<commit_before>/**
 * Created by KlimMalgin on 21.10.2014.
 */
'use strict';

var assert = require("assert");
require("./Morphine");

describe('Public API tests', function () {
    //var PublicApi = MorphineShareApi.CommonPrototypeMixin;

    describe('Morphine constructor', function () {

        it('Create from object', function () {
            var source = {
                myObject: {
                    start: {
                        value: 'start object value'
                    },
                    end: {
                        value: 'end object value'
                    }
                },
                myArray: [
                    {
                        index: 0,
                        value: 96
                    },
                    {
                        index: 1,
                        value: 'text value'
                    }
                ]
            };
            var morph = new Morphine(source);
            assert.equal(morph.has('myObject.start.value'), true, 'Объект содержит структуру "myObject.start.value"');
            assert.equal(morph.get('myObject.start.value'), 'start object value', 'Структура "myObject.start.value" соответствует ожидаемому значению');

            assert.equal(morph.has('myObject.end.value'), true, 'Объект содержит структуру "myObject.end.value"');
            assert.equal(morph.get('myObject.end.value'), 'end object value', 'Структура "myObject.end.value" соответствует ожидаемому значению');

            assert.equal(morph.has('myArray.0.index'), true, 'Объект содержит структуру "myArray.0.index"');
            assert.equal(morph.get('myArray.0.index'), 0, 'Структура "myArray.0.index" соответствует ожидаемому значению');

            assert.equal(morph.has('myArray.0.value'), true, 'Объект содержит структуру "myArray.0.value"');
            assert.equal(morph.get('myArray.0.value'), 96, 'Структура "myArray.0.value" соответствует ожидаемому значению');

            assert.equal(morph.has('myArray.1.index'), true, 'Объект содержит структуру "myArray.1.index"');
            assert.equal(morph.get('myArray.1.index'), 1, 'Структура "myArray.1.index" соответствует ожидаемому значению');

            assert.equal(morph.has('myArray.1.value'), true, 'Объект содержит структуру "myArray.1.value"');
            assert.equal(morph.has('myArray.1.value'), 'text value', 'Структура "myArray.1.value" соответствует ожидаемому значению');

            assert.deepEqual(morph.plain(), source, 'Структура созданного Morphine-объекта соответствует исходной');

        });

        it('Create from path', function () {
            var morph = new Morphine('root.level1.level2.$.value.innerValue', 44);

            assert.equal(morph.has('root.level1.level2.0.value.innerValue'), true, 'Объект содержит структуру "root.level1.level2.0.value.innerValue"');
            assert.equal(morph.get('root.level1.level2.0.value.innerValue'), 44, 'Структура "root.level1.level2.0.value.innerValue" соответствует ожидаемому значению');
        });

    });

    it('isObject', function () {
        var morph = new Morphine();
        assert.equal(morph.isObject(), true, 'Вновь созданая Morphine-сущность является объектом.');
        assert.notEqual(morph.isArray(), true, 'Вновь созданая Morphine-сущность не является массивом.');
    });

    it('isArray', function () {
        var morph = new Morphine('root.$');
        assert.equal(morph.get('root').isArray(), true, 'Вложенный в корень элемент "root" является массивом.');
        assert.notEqual(morph.get('root').isObject(), true, 'Вложенный в корень элемент "root" не является объектом.');
    });

    it('isNull', function () {
        var morph = new Morphine('root', null);
        assert.equal(morph.isNull('root'), true, 'Элемент "root" равен null.');
    });

    it('isUndefined', function () {
        var morph = new Morphine('root', undefined);
        assert.equal(morph.has('root'), true, 'Элемент "root" присутствует в созданном объекте.');
        assert.equal(morph.isUndefined('root'), true, 'Элемент "root" равен undefined.');
    });

    it('isEmpty', function () {
        var morph = new Morphine();
        assert.equal(morph.isEmpty(), true, 'Вновь созданный Morphine-объект является пустым.');
        morph.set('my.path', 'some value');
        assert.notEqual(morph.isEmpty(), true, 'Вновь созданный Morphine-объект не является пустым.');
    });

    it('has', function () {
        var morph = new Morphine('root.level1.level2.$.val', 'some value');
        assert.equal(morph.has('root'), true, 'Объект содержит "root" на текущем уровне.');

        var inner = morph.get('root.level1');
        assert.equal(inner.has('level2'), true, 'Объект содержит "level2" на текущем уровне.');
        assert.notEqual(inner.has('level3'), true, 'Объект не содержит "level3" на текущем уровне.');
        // ===
        assert.equal(morph.has('root.level1.level2'), true, 'Объект содержит вложенную структуру вида "root.level1.level2".');
    });

    /**
     * Выполнит merge src c текущим объектом
     * @param {Any Object} src
     */
    //merge
    /**
     * Установит свойство по указанному path
     * @param {String} path Путь по которому нужно установить значение
     * @param {*} value значение для установки в объекте
     * @return {Morphine} Текущий экземпляр объекта
     */
    //set
    /**
     * Вернет значение по указанному path
     * @param {String} path путь по которому нужно получить значение
     * @return {*} Значение расположенное по заданному пути
     */
    //get
    /**
     * Сконфигурирует текущий экземпляр объекта
     * @param {Object} options объект опций для конфигурирования текущего экземпляра Morphine
     * @return {Morphine} Текущий экземпляр объекта
     */
    //config
    /**
     * Сериализация Morphine-объекта в строку
     * return {String} Строковое представление текущего экземпляра объекта
     */
    //stringify
    /**
     * Преобразование Morphine-объекта в plain-объект
     */
    //plain
    /**
     * Преобразует текущий экземпляр объекта в массив path-элементов
     */
    //toPaths
    /**
     * Удалит вложенный объект или значение по указанному path
     */
    //remove
    /**
     * Очистит текущий экземпляр объекта
     */
    //clear
    /**
     * Преобразует текущий экземпляр объекта в объект описаный
     * переданным массивом path-элементов
     */
    //buildFromPaths

});
<commit_msg>Исправил тест на проверку значения<commit_after>/**
 * Created by KlimMalgin on 21.10.2014.
 */
'use strict';

var assert = require("assert");
require("./Morphine");

describe('Public API tests', function () {
    //var PublicApi = MorphineShareApi.CommonPrototypeMixin;

    describe('Morphine constructor', function () {

        it('Create from object', function () {
            var source = {
                myObject: {
                    start: {
                        value: 'start object value'
                    },
                    end: {
                        value: 'end object value'
                    }
                },
                myArray: [
                    {
                        index: 0,
                        value: 96
                    },
                    {
                        index: 1,
                        value: 'text value'
                    }
                ]
            };
            var morph = new Morphine(source);
            assert.equal(morph.has('myObject.start.value'), true, 'Объект содержит структуру "myObject.start.value"');
            assert.equal(morph.get('myObject.start.value'), 'start object value', 'Структура "myObject.start.value" соответствует ожидаемому значению');

            assert.equal(morph.has('myObject.end.value'), true, 'Объект содержит структуру "myObject.end.value"');
            assert.equal(morph.get('myObject.end.value'), 'end object value', 'Структура "myObject.end.value" соответствует ожидаемому значению');

            assert.equal(morph.has('myArray.0.index'), true, 'Объект содержит структуру "myArray.0.index"');
            assert.equal(morph.get('myArray.0.index'), 0, 'Структура "myArray.0.index" соответствует ожидаемому значению');

            assert.equal(morph.has('myArray.0.value'), true, 'Объект содержит структуру "myArray.0.value"');
            assert.equal(morph.get('myArray.0.value'), 96, 'Структура "myArray.0.value" соответствует ожидаемому значению');

            assert.equal(morph.has('myArray.1.index'), true, 'Объект содержит структуру "myArray.1.index"');
            assert.equal(morph.get('myArray.1.index'), 1, 'Структура "myArray.1.index" соответствует ожидаемому значению');

            assert.equal(morph.has('myArray.1.value'), true, 'Объект содержит структуру "myArray.1.value"');
            assert.equal(morph.get('myArray.1.value'), 'text value', 'Структура "myArray.1.value" соответствует ожидаемому значению');

            assert.deepEqual(morph.plain(), source, 'Структура созданного Morphine-объекта соответствует исходной');

        });

        it('Create from path', function () {
            var morph = new Morphine('root.level1.level2.$.value.innerValue', 44);

            assert.equal(morph.has('root.level1.level2.0.value.innerValue'), true, 'Объект содержит структуру "root.level1.level2.0.value.innerValue"');
            assert.equal(morph.get('root.level1.level2.0.value.innerValue'), 44, 'Структура "root.level1.level2.0.value.innerValue" соответствует ожидаемому значению');
        });

    });

    it('isObject', function () {
        var morph = new Morphine();
        assert.equal(morph.isObject(), true, 'Вновь созданая Morphine-сущность является объектом.');
        assert.notEqual(morph.isArray(), true, 'Вновь созданая Morphine-сущность не является массивом.');
    });

    it('isArray', function () {
        var morph = new Morphine('root.$');
        assert.equal(morph.get('root').isArray(), true, 'Вложенный в корень элемент "root" является массивом.');
        assert.notEqual(morph.get('root').isObject(), true, 'Вложенный в корень элемент "root" не является объектом.');
    });

    it('isNull', function () {
        var morph = new Morphine('root', null);
        assert.equal(morph.isNull('root'), true, 'Элемент "root" равен null.');
    });

    it('isUndefined', function () {
        var morph = new Morphine('root', undefined);
        assert.equal(morph.has('root'), true, 'Элемент "root" присутствует в созданном объекте.');
        assert.equal(morph.isUndefined('root'), true, 'Элемент "root" равен undefined.');
    });

    it('isEmpty', function () {
        var morph = new Morphine();
        assert.equal(morph.isEmpty(), true, 'Вновь созданный Morphine-объект является пустым.');
        morph.set('my.path', 'some value');
        assert.notEqual(morph.isEmpty(), true, 'Вновь созданный Morphine-объект не является пустым.');
    });

    it('has', function () {
        var morph = new Morphine('root.level1.level2.$.val', 'some value');
        assert.equal(morph.has('root'), true, 'Объект содержит "root" на текущем уровне.');

        var inner = morph.get('root.level1');
        assert.equal(inner.has('level2'), true, 'Объект содержит "level2" на текущем уровне.');
        assert.notEqual(inner.has('level3'), true, 'Объект не содержит "level3" на текущем уровне.');
        // ===
        assert.equal(morph.has('root.level1.level2'), true, 'Объект содержит вложенную структуру вида "root.level1.level2".');
    });

    /**
     * Выполнит merge src c текущим объектом
     * @param {Any Object} src
     */
    //merge
    /**
     * Установит свойство по указанному path
     * @param {String} path Путь по которому нужно установить значение
     * @param {*} value значение для установки в объекте
     * @return {Morphine} Текущий экземпляр объекта
     */
    //set
    /**
     * Вернет значение по указанному path
     * @param {String} path путь по которому нужно получить значение
     * @return {*} Значение расположенное по заданному пути
     */
    //get
    /**
     * Сконфигурирует текущий экземпляр объекта
     * @param {Object} options объект опций для конфигурирования текущего экземпляра Morphine
     * @return {Morphine} Текущий экземпляр объекта
     */
    //config
    /**
     * Сериализация Morphine-объекта в строку
     * return {String} Строковое представление текущего экземпляра объекта
     */
    //stringify
    /**
     * Преобразование Morphine-объекта в plain-объект
     */
    //plain
    /**
     * Преобразует текущий экземпляр объекта в массив path-элементов
     */
    //toPaths
    /**
     * Удалит вложенный объект или значение по указанному path
     */
    //remove
    /**
     * Очистит текущий экземпляр объекта
     */
    //clear
    /**
     * Преобразует текущий экземпляр объекта в объект описаный
     * переданным массивом path-элементов
     */
    //buildFromPaths

});
<|endoftext|>


<commit_before>var TapeStateMachine = require('./tapeStateMachine');
var util = require('util');
var utils = require('../../src/utils');

var RedirMatcher = module.exports = function (tape) {
    TapeStateMachine.call(this, tape);
    tape.setMark();
    this.state = st.START;

    this.on(st.START, /\s/, function () {
        tape.setMark();
    });
    this.on(st.START, /\d/, function () {
        this.state = st.NUMBER;
    });
    this.on(st.START, '>', function () {
        this.state = st.GT;
    });
    this.on(st.START, '<', function () {
        this.state = st.LT;
    });

    var first;
    this.on(st.NUMBER, /\d/, function () {
    });
    this.on(st.NUMBER, '>', function () {
        first = this.tape.getMarked();
        first = first.substring(0, first.length - 1);
        this.state = st.GT;
    });
    this.on(st.NUMBER, '<', function () {
        first = this.tape.getMarked();
        first = first.substring(0, first.length - 1);
        this.state = st.LT;
    });
    this.on(st.NUMBER, this.ANY, function () {
        this.notRedir();
    });

    this.on(st.GT, '>', function () {

    });

};

util.inherits(RedirMatcher, TapeStateMachine);

var st = RedirMatcher.prototype.states = utils.createEnum('START', 'NUMBER', 'GT', 'LT');

var t = RedirMatcher.prototype.tokens = utils.createEnum('NOTREDIR', 'GT', 'GTGT', 'GTAMP', 'LT', 'LTGT', 'LTAMP');

var run_ = TapeStateMachine.prototype.run;

RedirMatcher.prototype.run = function () {
    this.stack = [];
    run_.call(this);
    return this.token;
};
RedirMatcher.prototype.notRedir = function () {
    this.token = {type: t.NOTREDIR, text: this.tape.getMarked()};
    this.stop();
};
<commit_msg>Tryout -- Redirection matcher<commit_after>var TapeStateMachine = require('./tapeStateMachine');
var util = require('util');
var utils = require('../../src/utils');

var RedirMatcher = module.exports = function (tape) {
    TapeStateMachine.call(this, tape);
    tape.setMark();
    this.state = st.START;

    this.on(st.START, /\s/, function () {
        tape.setMark();
    });
    this.on(st.START, /\d/, function () {
        this.state = st.NUMBER;
    });
    this.on(st.START, '>', function () {
        this.state = st.GT;
    });
    this.on(st.START, '<', function () {
        this.state = st.LT;
    });
    this.on(st.START, this.ANY, function () {
        this.notRedir();
    });

    var number;
    this.on(st.NUMBER, /\d/, function () {
    });
    this.on(st.NUMBER, '>', function () {
        number = this.tape.getMarked();
        number = number.substring(0, number.length - 1);
        this.state = st.GT;
    });
    this.on(st.NUMBER, '<', function () {
        number = this.tape.getMarked();
        number = number.substring(0, number.length - 1);
        this.state = st.LT;
    });
    this.on(st.NUMBER, this.ANY, function () {
        this.notRedir();
    });

    this.on(st.GT, this.ANY, function (ch) {
        var type;
        if (ch === '>') {
            type = t.GTGT;
        } else if (ch === '&') {
            type = t.GTAMP;
        } else {
            type = t.GT;
            if (ch !== this.EOF) {
                this.tape.prev();
            }
        }
        this.token = {
            type: t.type,
            text: this.tape.getMarked()
        };
        if (!utils.isUndefined(number)) {
            this.token.number = number;
        }
        this.stop();
    });

    this.on(st.LT, this.ANY, function (ch) {
        var type;
        if (ch === '>') {
            type = t.LTGT;
        } else if (ch === '&') {
            type = t.LTAMP;
        } else {
            type = t.LT;
            if (ch !== this.EOF) {
                this.tape.prev();
            }
        }
        this.token = {
            type: t.type,
            text: this.tape.getMarked()
        };
        if (!utils.isUndefined(number)) {
            this.token.number = number;
        }
        this.stop();
    });

};

util.inherits(RedirMatcher, TapeStateMachine);

var st = RedirMatcher.prototype.states = utils.createEnum('START', 'NUMBER', 'GT', 'LT');

var t = RedirMatcher.prototype.tokens = utils.createEnum('NOTREDIR', 'GT', 'GTGT', 'GTAMP', 'LT', 'LTGT', 'LTAMP');

var run_ = TapeStateMachine.prototype.run;

RedirMatcher.prototype.run = function () {
    this.stack = [];
    run_.call(this);
    return this.token;
};
RedirMatcher.prototype.notRedir = function () {
    this.token = {type: t.NOTREDIR, text: this.tape.getMarked()};
    this.stop();
};
<|endoftext|>


<commit_before>/**
 *
 */
Ext.namespace('Gemma');

Gemma.GeoBrowseGrid = Ext
		.extend(
				Gemma.GemmaGridPanel,
				{
					collapsible : false,
					loadMask : true,
					defaults : {
						autoScroll : true
					},

					height : 500,
					width : 1300,
					autoScroll : true,
					loadMask : true,

					autoExpandColumn : 'description',

					record : Ext.data.Record.create([ {
						name : "usable",
						type : "boolean"
					}, {
						name : "geoAccession"
					}, {
						name : "numSamples",
						type : "int"
					}, {
						name : 'title'
					}, {
						name : 'correspondingExperiments'
					}, {
						name : "releaseDate",
						type : "date"
					}, {
						name : "organisms"
					}, {
						name : "inGemma",
						type : "boolean"
					}, {
						name : "usable",
						type : "boolean"
					}, {
						name : "previousClicks",
						type : "int"
					} ]),

					proceed : function(s) {
						// new start
						this.start = Number(s) > 0 ? this.start + Number(s)
								: (this.start + this.count);
						console.log("skip=" + Number(s) + " start="
								+ this.start);

						this.store.load({
							params : [ this.start, this.count ]
						});

					},

					/**
					 * S is the skip.
					 *
					 * @param s
					 */
					back : function(s) {

						// new start. Either go to the skip, or go back one
						// 'page', make sure greater than zero.
						this.start = Math.max(0, Number(s) > 0 ? this.start
								- Number(s) : this.start - this.count);
						console.log("skip=" + Number(s) + " start="
								+ this.start);

						this.store.load({
							params : [ this.start, this.count ]
						});

					},

					// initial starting point
					start : 0,

					// page size
					count : 20,

					initComponent : function() {

						Ext
								.apply(
										this,
										{
											store : new Ext.data.Store(
													{
														proxy : new Ext.data.DWRProxy(
																{
																	apiActionToHandlerMap : {
																		read : {
																			dwrFunction : GeoRecordBrowserController.browse
																		}
																	},
																	getDwrArgsFunction : function(
																			request,
																			recordDataArray) {
																		return [
																				this.start,
																				this.count ];
																	}
																}),
														reader : new Ext.data.ListRangeReader(
																{
																	id : "id"
																}, this.record)
													})
										});

						Ext
								.apply(
										this,
										{
											columns : [
													{
														header : "Accession",
														dataIndex : "geoAccession",
														scope : this,
														renderer : this.geoAccessionRenderer
													},
													{
														header : "Title",
														dataIndex : "title",
														renderer : this.titleRenderer,
														width : 500
													},
													{
														header : "Release date",
														dataIndex : "releaseDate",
														renderer : new Ext.util.Format.dateRenderer(
																"M d, Y"),
														width : 76
													},
													{
														header : "numSamples",
														dataIndex : "numSamples",
														sortable : true,
														width : 40
													},
													{
														header : "In Gemma?",
														dataIndex : "inGemma",
														renderer : this.inGemmaRenderer,
														width : 40
													},
													{
														header : "taxa",
														dataIndex : "organisms",
														scope : this,
														renderer : this.taxonRenderer
													},
													{
														header : "Usable?",
														dataIndex : "usable",
														scope : this,
														width : 30,
														renderer : this.usableRenderer
													},
													{
														header : "Examined",
														dataIndex : "previousClicks",
														scope : this,
														width : 30,
														renderer : this.clicksRenderer
													} ]
										});

						Gemma.GeoBrowseGrid.superclass.initComponent.call(this);

						this.getStore().on(
								"load",
								function(store, records, options) {

									// there must be a better way of doing this.
									Ext.DomHelper.overwrite(Ext
											.getDom('numRecords'),
											""
													+ records.length
													+ "");

								}, this);

						this.getSelectionModel().on('rowselect',
								this.showDetails, this, {
									buffer : 100
								// keep from firing too many times at once
								});

						this.getStore().load({
							params : [ this.start, this.count ]
						});

					},

					/**
					 * Show some dots.
					 */
					clicksRenderer : function(value, metadata, record, row,
							col, ds) {
						var m = record.get('previousClicks');
						var result = "";
						for ( var i = 0; i < Math.min(m, 5); i++) {
							result = result + "•";
						}
						return result;
					},

					geoAccessionRenderer : function(value, metadata, record,
							row, col, ds) {
						return ""
								+ record.get('geoAccession') + "";
					},

					titleRenderer : function(value, metadata, record, row, col,
							ds) {
						return record.get('title');
					},

					inGemmaRenderer : function(value, metadata, record, row,
							col, ds) {

						if (record.get('correspondingExperiments').length == 0) {
							return "<input type=\"button\" value=\"Load\" "
									+ "\" onClick=\"load('"
									+ record.get('geoAccession') + "')\" >";
						}

						var r = "";
						for ( var i = 0; i < record
								.get('correspondingExperiments').length; i++) {
							var ee = record.get('correspondingExperiments')[i];
							r = r
									+ ""
									+ record.get('geoAccession') + "";

						}
						return r;

					},

					taxonRenderer : function(value, metadata, record, row, col,
							ds) {
						var r = "";
						for ( var i = 0; i < record.get('organisms').length; i++) {
							var ee = record.get('organisms')[i];
							r = r + " " + ee;

						}
						return r;
					},

					usableRenderer : function(value, metadata, record, row,
							col, ds) {
						if (record.get('correspondingExperiments').length > 0) {
							return "";
						}
						if (record.get('usable')) {
							return "";
						} else {
							return "";
						}
					},

					showDetails : function(model, rowindex, record) {
						var callParams = [];
						callParams.push(record.get('geoAccession'));

						var delegate = handleSuccess.createDelegate(this, [],
								true);
						var errorHandler = handleFailure.createDelegate(this,
								[], true);

						callParams.push({
							callback : delegate,
							errorHandler : errorHandler
						});

						GeoRecordBrowserController.getDetails.apply(this,
								callParams);
						Ext.DomHelper.overwrite("messages", {
							tag : 'img',
							src : '/Gemma/images/default/tree/loading.gif'
						});
						Ext.DomHelper.append("messages", {
							tag : 'span',
							html : " Please wait..."
						});

					}

				});

function handleSuccess(data) {
	Ext.DomHelper.overwrite("messages", {
		tag : 'div',
		html : data
	});
}

function handleUsabilitySuccess(data, accession) {

	if (data) {
		Ext.DomHelper.overwrite(accession + "-rating", {
			tag : 'img',
			src : '/Gemma/images/icons/thumbsup.png'
		});
	} else {
		Ext.DomHelper.overwrite(accession + "-rating", {
			tag : 'img',
			src : '/Gemma/images/icons/thumbsdown-red.png'
		});
	}

}

function handleFailure(data, e) {
	Ext.DomHelper.overwrite("taskId", "");
	Ext.DomHelper.overwrite("messages", {
		tag : 'img',
		src : '/Gemma/images/icons/warning.png'
	});
	Ext.DomHelper.append("messages", {
		tag : 'span',
		html : " There was an error: " + data
	});
}

function toggleUsability(accession) {
	var callParams = [];
	callParams.push(accession);

	var delegate = handleUsabilitySuccess.createDelegate(this, [ accession ],
			true);
	var errorHandler = handleFailure.createDelegate(this, [], true);

	callParams.push({
		callback : delegate,
		errorHandler : errorHandler
	});

	GeoRecordBrowserController.toggleUsability.apply(this, callParams);
	Ext.DomHelper.overwrite(accession + "-rating", {
		tag : 'img',
		src : '/Gemma/images/default/tree/loading.gif'
	});
}

function handleLoadSuccess(taskId) {
	try {
		Ext.DomHelper.overwrite("messages", "");

		var p = new Gemma.ProgressWindow({
			taskId : taskId,
			errorHandler : handleFailure,
			callback : function() {
				document.location.reload(true);
				Ext.DomHelper.overwrite("messages", "Successfully loaded");
			}
		});

		p.show('upload-button');

	} catch (e) {
		handleFailure(data, e);
		return;
	}

}

function load(accession) {

	var suppressMatching = "false";
	var loadPlatformOnly = "false";
	var arrayExpress = "false";
	var arrayDesign = "";

	var callParams = [];

	var commandObj = {
		accession : accession,
		suppressMatching : suppressMatching,
		loadPlatformOnly : loadPlatformOnly,
		arrayExpress : arrayExpress,
		arrayDesignName : arrayDesign
	};

	callParams.push(commandObj);

	var delegate = handleLoadSuccess.createDelegate(this, [], true);
	var errorHandler = handleFailure.createDelegate(this, [], true);

	callParams.push({
		callback : delegate,
		errorHandler : errorHandler
	});

	// this should return quickly, with the task id.
	Ext.DomHelper.overwrite("messages", {
		tag : 'img',
		src : '/Gemma/images/default/tree/loading.gif'
	});
	Ext.DomHelper.append("messages", " Submitting job...");
	ExpressionExperimentLoadController.load.apply(this, callParams);

}
<commit_msg>remove logging<commit_after>/**
 *
 */
Ext.namespace('Gemma');

Gemma.GeoBrowseGrid = Ext
		.extend(
				Gemma.GemmaGridPanel,
				{
					collapsible : false,
					loadMask : true,
					defaults : {
						autoScroll : true
					},

					height : 500,
					width : 1300,
					autoScroll : true,
					loadMask : true,

					autoExpandColumn : 'description',

					record : Ext.data.Record.create([ {
						name : "usable",
						type : "boolean"
					}, {
						name : "geoAccession"
					}, {
						name : "numSamples",
						type : "int"
					}, {
						name : 'title'
					}, {
						name : 'correspondingExperiments'
					}, {
						name : "releaseDate",
						type : "date"
					}, {
						name : "organisms"
					}, {
						name : "inGemma",
						type : "boolean"
					}, {
						name : "usable",
						type : "boolean"
					}, {
						name : "previousClicks",
						type : "int"
					} ]),

					proceed : function(s) {
						// new start
						this.start = Number(s) > 0 ? this.start + Number(s)
								: (this.start + this.count);

						this.store.load({
							params : [ this.start, this.count ]
						});

					},

					/**
					 * S is the skip.
					 *
					 * @param s
					 */
					back : function(s) {

						// new start. Either go to the skip, or go back one
						// 'page', make sure greater than zero.
						this.start = Math.max(0, Number(s) > 0 ? this.start
								- Number(s) : this.start - this.count);

						this.store.load({
							params : [ this.start, this.count ]
						});

					},

					// initial starting point
					start : 0,

					// page size
					count : 20,

					initComponent : function() {

						Ext
								.apply(
										this,
										{
											store : new Ext.data.Store(
													{
														proxy : new Ext.data.DWRProxy(
																{
																	apiActionToHandlerMap : {
																		read : {
																			dwrFunction : GeoRecordBrowserController.browse
																		}
																	},
																	getDwrArgsFunction : function(
																			request,
																			recordDataArray) {
																		return [
																				this.start,
																				this.count ];
																	}
																}),
														reader : new Ext.data.ListRangeReader(
																{
																	id : "id"
																}, this.record)
													})
										});

						Ext
								.apply(
										this,
										{
											columns : [
													{
														header : "Accession",
														dataIndex : "geoAccession",
														scope : this,
														renderer : this.geoAccessionRenderer
													},
													{
														header : "Title",
														dataIndex : "title",
														renderer : this.titleRenderer,
														width : 500
													},
													{
														header : "Release date",
														dataIndex : "releaseDate",
														renderer : new Ext.util.Format.dateRenderer(
																"M d, Y"),
														width : 76
													},
													{
														header : "numSamples",
														dataIndex : "numSamples",
														sortable : true,
														width : 40
													},
													{
														header : "In Gemma?",
														dataIndex : "inGemma",
														renderer : this.inGemmaRenderer,
														width : 40
													},
													{
														header : "taxa",
														dataIndex : "organisms",
														scope : this,
														renderer : this.taxonRenderer
													},
													{
														header : "Usable?",
														dataIndex : "usable",
														scope : this,
														width : 30,
														renderer : this.usableRenderer
													},
													{
														header : "Examined",
														dataIndex : "previousClicks",
														scope : this,
														width : 30,
														renderer : this.clicksRenderer
													} ]
										});

						Gemma.GeoBrowseGrid.superclass.initComponent.call(this);

						this.getStore().on(
								"load",
								function(store, records, options) {

									// there must be a better way of doing this.
									Ext.DomHelper.overwrite(Ext
											.getDom('numRecords'),
											""
													+ records.length
													+ "");

								}, this);

						this.getSelectionModel().on('rowselect',
								this.showDetails, this, {
									buffer : 100
								// keep from firing too many times at once
								});

						this.getStore().load({
							params : [ this.start, this.count ]
						});

					},

					/**
					 * Show some dots.
					 */
					clicksRenderer : function(value, metadata, record, row,
							col, ds) {
						var m = record.get('previousClicks');
						var result = "";
						for ( var i = 0; i < Math.min(m, 5); i++) {
							result = result + "•";
						}
						return result;
					},

					geoAccessionRenderer : function(value, metadata, record,
							row, col, ds) {
						return ""
								+ record.get('geoAccession') + "";
					},

					titleRenderer : function(value, metadata, record, row, col,
							ds) {
						return record.get('title');
					},

					inGemmaRenderer : function(value, metadata, record, row,
							col, ds) {

						if (record.get('correspondingExperiments').length == 0) {
							return "<input type=\"button\" value=\"Load\" "
									+ "\" onClick=\"load('"
									+ record.get('geoAccession') + "')\" >";
						}

						var r = "";
						for ( var i = 0; i < record
								.get('correspondingExperiments').length; i++) {
							var ee = record.get('correspondingExperiments')[i];
							r = r
									+ ""
									+ record.get('geoAccession') + "";

						}
						return r;

					},

					taxonRenderer : function(value, metadata, record, row, col,
							ds) {
						var r = "";
						for ( var i = 0; i < record.get('organisms').length; i++) {
							var ee = record.get('organisms')[i];
							r = r + " " + ee;

						}
						return r;
					},

					usableRenderer : function(value, metadata, record, row,
							col, ds) {
						if (record.get('correspondingExperiments').length > 0) {
							return "";
						}
						if (record.get('usable')) {
							return "";
						} else {
							return "";
						}
					},

					showDetails : function(model, rowindex, record) {
						var callParams = [];
						callParams.push(record.get('geoAccession'));

						var delegate = handleSuccess.createDelegate(this, [],
								true);
						var errorHandler = handleFailure.createDelegate(this,
								[], true);

						callParams.push({
							callback : delegate,
							errorHandler : errorHandler
						});

						GeoRecordBrowserController.getDetails.apply(this,
								callParams);
						Ext.DomHelper.overwrite("messages", {
							tag : 'img',
							src : '/Gemma/images/default/tree/loading.gif'
						});
						Ext.DomHelper.append("messages", {
							tag : 'span',
							html : " Please wait..."
						});

					}

				});

function handleSuccess(data) {
	Ext.DomHelper.overwrite("messages", {
		tag : 'div',
		html : data
	});
}

function handleUsabilitySuccess(data, accession) {

	if (data) {
		Ext.DomHelper.overwrite(accession + "-rating", {
			tag : 'img',
			src : '/Gemma/images/icons/thumbsup.png'
		});
	} else {
		Ext.DomHelper.overwrite(accession + "-rating", {
			tag : 'img',
			src : '/Gemma/images/icons/thumbsdown-red.png'
		});
	}

}

function handleFailure(data, e) {
	Ext.DomHelper.overwrite("taskId", "");
	Ext.DomHelper.overwrite("messages", {
		tag : 'img',
		src : '/Gemma/images/icons/warning.png'
	});
	Ext.DomHelper.append("messages", {
		tag : 'span',
		html : " There was an error: " + data
	});
}

function toggleUsability(accession) {
	var callParams = [];
	callParams.push(accession);

	var delegate = handleUsabilitySuccess.createDelegate(this, [ accession ],
			true);
	var errorHandler = handleFailure.createDelegate(this, [], true);

	callParams.push({
		callback : delegate,
		errorHandler : errorHandler
	});

	GeoRecordBrowserController.toggleUsability.apply(this, callParams);
	Ext.DomHelper.overwrite(accession + "-rating", {
		tag : 'img',
		src : '/Gemma/images/default/tree/loading.gif'
	});
}

function handleLoadSuccess(taskId) {
	try {
		Ext.DomHelper.overwrite("messages", "");

		var p = new Gemma.ProgressWindow({
			taskId : taskId,
			errorHandler : handleFailure,
			callback : function() {
				document.location.reload(true);
				Ext.DomHelper.overwrite("messages", "Successfully loaded");
			}
		});

		p.show('upload-button');

	} catch (e) {
		handleFailure(data, e);
		return;
	}

}

function load(accession) {

	var suppressMatching = "false";
	var loadPlatformOnly = "false";
	var arrayExpress = "false";
	var arrayDesign = "";

	var callParams = [];

	var commandObj = {
		accession : accession,
		suppressMatching : suppressMatching,
		loadPlatformOnly : loadPlatformOnly,
		arrayExpress : arrayExpress,
		arrayDesignName : arrayDesign
	};

	callParams.push(commandObj);

	var delegate = handleLoadSuccess.createDelegate(this, [], true);
	var errorHandler = handleFailure.createDelegate(this, [], true);

	callParams.push({
		callback : delegate,
		errorHandler : errorHandler
	});

	// this should return quickly, with the task id.
	Ext.DomHelper.overwrite("messages", {
		tag : 'img',
		src : '/Gemma/images/default/tree/loading.gif'
	});
	Ext.DomHelper.append("messages", " Submitting job...");
	ExpressionExperimentLoadController.load.apply(this, callParams);

}
<|endoftext|>


<commit_before>L.FieldStore.TopologyStore = L.FieldStore.extend({

    lock: function () {
        this._locked = true;
    },

    unlock: function () {
        this._locked = false;
    },

    save: function (layer) {
        if (this._locked)
            return;
        L.FieldStore.prototype.save.call(this, layer);
    },

    _deserialize: function (value) {
        if (value === undefined || value === '')
            return null;
        if (typeof value == 'string')
            return JSON.parse(value);
        return value;
    },

    _serialize: function (layer) {
        var serialized;
        if (layer instanceof L.Marker) {
            var p = layer.getLatLng();
            serialized = {lat: p.lat, lng: p.lng};
            // In case the marker is snapped, serialize this information.
            if (layer.snap) {
                serialized['snap'] = layer.snap.properties.pk;
            }
        }
        else {
            serialized = layer;  // Returned by TopologyHelper
        }
        return JSON.stringify(serialized);
    }
});

MapEntity.GeometryField.TopologyField = MapEntity.GeometryField.extend({
    options: {
        field_store_class: L.FieldStore.TopologyStore,
    },

    includes: MapEntity.GeometryField.GeometryFieldPathMixin,

    initialize: function () {
        MapEntity.GeometryField.prototype.initialize.apply(this, arguments);
        this.options.all_modifiable = this.options.modifiable;
        this.options.modifiable = false; // Will disable leaflet.draw in leaflet.forms.js
        this._objectsLayer = null;
        this._pathsLayer = null;
        this._pointControl = null;
        this._lineControl = null;
    },

    addTo: function (map) {
        MapEntity.GeometryField.prototype.addTo.call(this, map);
        if (this.options.all_modifiable) {
            this._initTopologyControl(map);
        };
    },

    _initTopologyControl: function (map) {
        // This will make sure that we can't activate a control, while the
        // other is being used.
        var exclusive = new L.Control.ExclusiveActivation();

        if (this.options.is_point_topology) {
            addTopologyControl.call(this, '_pointControl', L.Control.PointTopology);
        }
        if (this.options.is_line_topology) {
            addTopologyControl.call(this, '_lineControl', L.Control.LineTopology);
        }

        function addTopologyControl(name, controlClass) {
            var control = this[name] = new controlClass(map, this._pathsLayer, this);
            map.addControl(control);
            exclusive.add(control);
            control.activable(false);
            control.handler.on('computed_topology', function (e) {
                this.store.save(e.topology);
            }, this);
            // Make sure, we clean-up geometries when user changes from point to line
            control.handler.on('enabled', resetTopologies, this);
        }

        function resetTopologies() {
            if (this._pointControl) this._pointControl.handler.reset();
            if (this._lineControl) this._lineControl.handler.reset();
        }
    },

    buildObjectsLayer: function () {
        this._objectsLayer = MapEntity.GeometryField.prototype.buildObjectsLayer.call(this);
        this._pathsLayer = this.buildPathsLayer(this._objectsLayer);
        this._pathsLayer.on('loaded', this._loadTopologyGraph, this);
        return this._objectsLayer;
    },

    _loadTopologyGraph: function () {
        // Make sure paths stay above other layers
        this._pathsLayer.bringToFront();

        // We now have the path, we can find out the topology bounds.
        var topo = this.store.load();
        if (topo)
            this._map.fitBounds(this._topologyBounds(topo));

        if (this._pointControl)
            this._pointControl.activable(true);
        if (this._lineControl)
            this._lineControl.activable(true);

        if (this._lineControl === null) {
            // No need to load graph for point topologies
            this.load();
            return;
        }

        // Path layer is ready, load graph !
        this._pathsLayer.fire('data:loading');
        var url = window.SETTINGS.urls.path_graph + '?_u=' + (new Date().getTime());
        $.getJSON(url, this._onGraphLoaded.bind(this))
         .error(graphError.bind(this));

        function graphError(jqXHR, textStatus, errorThrown) {
            this._pathsLayer.fire('data:loaded');
            $(this._map._container).addClass('map-error');
            console.error("Could not load url '" + window.SETTINGS.urls.path_graph + "': " + textStatus);
            console.error(errorThrown);
        }
    },

    _onGraphLoaded: function (graph) {
        // Load graph
        this._lineControl.setGraph(graph);
        this.load();
        // Stop spinning !
        this._pathsLayer.fire('data:loaded');
    },

    load: function () {
        if (this._pathsLayer === null) {
            // Use basic behaviour from MapEntityField until
            this._setView();
            return;
        }

        var topo = this.store.load();
        if (topo) {
            // Lock modification of initial value during load
            this.store.lock();
            console.debug("Deserialize topology: " + JSON.stringify(topo));
            if (this._lineControl && !topo.lat && !topo.lng) {
                this._lineControl.handler.restoreTopology(topo);
            }
            if (this._pointControl && topo.lat && topo.lng) {
                this._pointControl.handler.restoreTopology(topo);
            }
            // Unlock now, user can edit
            this.store.unlock();
        }
    },

    _topologyBounds: function (topo) {
        var bounds = L.latLngBounds([]);
        if (topo.lat && topo.lng) {
            bounds.extend(L.latLng([topo.lat - 0.005, topo.lng - 0.005]));
            bounds.extend(L.latLng([topo.lat + 0.005, topo.lng + 0.005]));
        }
        else {
            var paths =  [];
            for (var i=0; i<topo.length; i++) {
                var subtopology = topo[i];
                for (var j=0; j<subtopology.paths.length; j++) {
                    var pathPk = subtopology.paths[j];
                    var pathLayer = this._pathsLayer.getLayer(pathPk);
                    bounds.extend(pathLayer.getBounds());
                }
            }
        }
        return bounds;
    }
});
<commit_msg>Destroy map when the user has no permission to change geom<commit_after>L.FieldStore.TopologyStore = L.FieldStore.extend({

    lock: function () {
        this._locked = true;
    },

    unlock: function () {
        this._locked = false;
    },

    save: function (layer) {
        if (this._locked)
            return;
        L.FieldStore.prototype.save.call(this, layer);
    },

    _deserialize: function (value) {
        if (value === undefined || value === '')
            return null;
        if (typeof value == 'string')
            return JSON.parse(value);
        return value;
    },

    _serialize: function (layer) {
        var serialized;
        if (layer instanceof L.Marker) {
            var p = layer.getLatLng();
            serialized = {lat: p.lat, lng: p.lng};
            // In case the marker is snapped, serialize this information.
            if (layer.snap) {
                serialized['snap'] = layer.snap.properties.pk;
            }
        }
        else {
            serialized = layer;  // Returned by TopologyHelper
        }
        return JSON.stringify(serialized);
    }
});

MapEntity.GeometryField.TopologyField = MapEntity.GeometryField.extend({
    options: {
        field_store_class: L.FieldStore.TopologyStore,
    },

    includes: MapEntity.GeometryField.GeometryFieldPathMixin,

    initialize: function () {
        MapEntity.GeometryField.prototype.initialize.apply(this, arguments);
        this.options.all_modifiable = this.options.modifiable;
        this.options.modifiable = false; // Will disable leaflet.draw in leaflet.forms.js
        this._objectsLayer = null;
        this._pathsLayer = null;
        this._pointControl = null;
        this._lineControl = null;
    },

    addTo: function (map) {
        MapEntity.GeometryField.prototype.addTo.call(this, map);
        this._initTopologyControl(map);
    },

    _initTopologyControl: function (map) {
        // This will make sure that we can't activate a control, while the
        // other is being used.
        var exclusive = new L.Control.ExclusiveActivation();

        if (this.options.is_point_topology) {
            addTopologyControl.call(this, '_pointControl', L.Control.PointTopology);
        }
        if (this.options.is_line_topology) {
            addTopologyControl.call(this, '_lineControl', L.Control.LineTopology);
        }

        function addTopologyControl(name, controlClass) {
            if (this.options.all_modifiable){
                var control = this[name] = new controlClass(map, this._pathsLayer, this);
                    map.addControl(control);
                    exclusive.add(control);
                    control.activable(false);
                control.handler.on('computed_topology', function (e) {
                    this.store.save(e.topology);
                }, this);
                // Make sure, we clean-up geometries when user changes from point to line
                control.handler.on('enabled', resetTopologies, this);
            }
            else {
                map.remove()
            };
        }

        function resetTopologies() {
            if (this._pointControl) this._pointControl.handler.reset();
            if (this._lineControl) this._lineControl.handler.reset();
        }
    },

    buildObjectsLayer: function () {
        this._objectsLayer = MapEntity.GeometryField.prototype.buildObjectsLayer.call(this);
        this._pathsLayer = this.buildPathsLayer(this._objectsLayer);
        this._pathsLayer.on('loaded', this._loadTopologyGraph, this);
        return this._objectsLayer;
    },

    _loadTopologyGraph: function () {
        // Make sure paths stay above other layers
        this._pathsLayer.bringToFront();

        // We now have the path, we can find out the topology bounds.
        var topo = this.store.load();
        if (topo)
            this._map.fitBounds(this._topologyBounds(topo));

        if (this._pointControl)
            this._pointControl.activable(true);
        if (this._lineControl)
            this._lineControl.activable(true);

        if (this._lineControl === null) {
            // No need to load graph for point topologies
            this.load();
            return;
        }

        // Path layer is ready, load graph !
        this._pathsLayer.fire('data:loading');
        var url = window.SETTINGS.urls.path_graph + '?_u=' + (new Date().getTime());
        $.getJSON(url, this._onGraphLoaded.bind(this))
         .error(graphError.bind(this));

        function graphError(jqXHR, textStatus, errorThrown) {
            this._pathsLayer.fire('data:loaded');
            $(this._map._container).addClass('map-error');
            console.error("Could not load url '" + window.SETTINGS.urls.path_graph + "': " + textStatus);
            console.error(errorThrown);
        }
    },

    _onGraphLoaded: function (graph) {
        // Load graph
        this._lineControl.setGraph(graph);
        this.load();
        // Stop spinning !
        this._pathsLayer.fire('data:loaded');
    },

    load: function () {
        if (this._pathsLayer === null) {
            // Use basic behaviour from MapEntityField until
            this._setView();
            return;
        }

        var topo = this.store.load();
        if (topo) {
            // Lock modification of initial value during load
            this.store.lock();
            console.debug("Deserialize topology: " + JSON.stringify(topo));
            if (this._lineControl && !topo.lat && !topo.lng) {
                this._lineControl.handler.restoreTopology(topo);
            }
            if (this._pointControl && topo.lat && topo.lng) {
                this._pointControl.handler.restoreTopology(topo);
            }
            // Unlock now, user can edit
            this.store.unlock();
        }
    },

    _topologyBounds: function (topo) {
        var bounds = L.latLngBounds([]);
        if (topo.lat && topo.lng) {
            bounds.extend(L.latLng([topo.lat - 0.005, topo.lng - 0.005]));
            bounds.extend(L.latLng([topo.lat + 0.005, topo.lng + 0.005]));
        }
        else {
            var paths =  [];
            for (var i=0; i<topo.length; i++) {
                var subtopology = topo[i];
                for (var j=0; j<subtopology.paths.length; j++) {
                    var pathPk = subtopology.paths[j];
                    var pathLayer = this._pathsLayer.getLayer(pathPk);
                    bounds.extend(pathLayer.getBounds());
                }
            }
        }
        return bounds;
    }
});
<|endoftext|>


<commit_before>'use strict'

/**
* --locale='zh-CN'
* --namespace='vux'
*/

var argv = require('yargs').argv
var namespace = argv.namespace || 'vux'

let config = require('./webpack.prod.conf.js')
config.vux.plugins.forEach(function(plugin) {
  if (plugin.name === 'i18n') {
    plugin.vuxStaticReplace = true
    plugin.vuxLocale = argv['locale'] || 'zh-CN'
  }
})
config.vux.options.env = 'production'

const webpack = require('webpack')
const mkdirp = require('mkdirp')
const fs = require('fs')
const touch = require('touch')
const path = require('path')

mkdirp.sync(path.resolve(__dirname, '../dist/plugins'))
mkdirp.sync(path.resolve(__dirname, '../dist/styles'))

const list = require(path.resolve(__dirname, '../src/datas/vux_component_list.json'))
const maps = require(path.resolve(__dirname, '../src/components/map.json'))
// 查找在maps里但不在list里的组件
let others = []
for(let i in maps) {
  let match = list.filter(function(one){
    return _camelCase(one.name) === i
  })
  if (match.length === 0 && !/Plugin|Data|Directive|Filter|Item|NOTICE|Demo|Dev/.test(i)) {
    others.push({
      name: toDash(i),
      importName: i,
      path: maps[i]
    })
  }
}

others.push({
  name: 'swiper-item',
  importName: 'SwiperItem',
  path: maps['SwiperItem']
})

var ExtractTextPlugin = require('extract-text-webpack-plugin')
var co = require('co')
var thunkify = require('thunkify')
var pkg = require(path.resolve(__dirname, '../package.json'))

var build = thunkify(function (config, name, cb) {
  let start = new Date().getTime()
  console.log(`start:${name}`)
  webpack(config, function (err, stats) {
    if (!config.entry.vux) {
      mkdirp.sync(path.resolve(config.output.path))
      touch.sync(path.resolve(config.output.path, './index.min.css'))
    }
    var jsonStats = stats.toJson()
    var assets = jsonStats.assets[0]
    var size = assets.size / 1024
    size = size.toFixed(2) + 'k'
    console.log('size', size)
    console.log('time', (new Date().getTime() - start) / 1000 + 's')
    console.log('----------------')
    cb && cb(err)
  })
})

var utils = require('./utils')
config.devtool = false
config.plugins = config.plugins.slice(0, -2)
config.plugins.forEach((one, index) => {
  if (one.constructor.name === 'HtmlWebpackPlugin') {
    config.plugins.splice(index, 1)
  }
  if (one.constructor.name === 'ExtractTextPlugin') {
    config.plugins.splice(index, 1)
  }
})

config.output.assetsPublicPath = '/'

let isBuilding = false

co(function*() {
  try {
    for (let n = 0; n < others.length; n++) {
      yield build(buildConfig(others[n]), others[n].name)
    }
  } catch (e) {}
})

co(function* () {
  try {
    yield build(buildMainConfig(), 'vux')
  } catch(e){
    console.log(e)
  }

  try {
    const pluginList = ['Confirm', 'Toast', 'Device', 'Alert', 'Loading']
    for (let j = 0; j < pluginList.length; j++) {
      yield build(buildPlugin(pluginList[j]), `Plugin ${pluginList[j]}`)
    }
  } catch (e) {
    console.log(e)
  }

  try {
    for (let i = 0; i < list.length; i++) {
      let one = list[i]
      if(one.items) {
        for(let j = 0; j < one.items.length; j++) {
          one.name = one.items[j]
          one.importName = _camelCase(one.items[j])
          one.path = maps[one.importName]
          yield build(buildConfig(one), one.items[j])
        }
      } else {
        yield build(buildConfig(one), one.name)
      }
    }
  } catch (e) {
    console.log(e)
  }
})

function camelCase(input) {
  let str = input.toLowerCase().replace(/-(.)/g, function (match, group1) {
    return group1.toUpperCase();
  })
  str = str.replace(/_(.)/g, function (match, group1) {
    return group1.toUpperCase()
  });
  return str
}

function _camelCase(input) {
  let str = camelCase(input)
  return str.slice(0, 1).toUpperCase() + str.slice(1)
}

function buildMainConfig() {

  // list all components
  const list = require('../src/components/map.json')
  let code = 'const vux = {}\n'
  code += `/* only for building vux.css */
import Style from '../styles/index.vue'\n`

  delete list['NOTICE']
  delete list['ChinaAddressV1Data']

  for (let i in list) {
      const name = `${namespace}${i}`
      code += `import ${name} from '${list[i]}'\n
vux['${name}'] = ${name}\n`
  }

  code += `
if (!!window) {
  for (let i in vux) {
    window[i] = vux[i]
  }
}\n`
  code += `module.exports = vux`

  fs.writeFileSync(path.resolve(__dirname, '../src/components/index.js'), code)

  delete config.entry

  config.plugins.forEach((one, index) => {
    if (one.constructor.name === 'ExtractTextPlugin') {
      config.plugins.splice(index, 1)
    }
  })

  config.plugins.push(new ExtractTextPlugin(`vux.min.css`))

  config.entry = config.entry || {}
  config.entry['vux'] = 'src/components/index.js'
  config.output = {}
  config.output.libraryTarget = 'umd'
  config.output.library = `vux`
  config.output.filename = `vux.min.js`
  config.output.path = path.resolve(__dirname, `../dist/`)
  return config
}

// build plugins
function buildPlugin (name) {
  delete config.entry

  config.plugins.forEach((one, index) => {
    if (one.constructor.name === 'ExtractTextPlugin') {
      config.plugins.splice(index, 1)
    }
  })

  config.plugins.push(new ExtractTextPlugin(`index.min.css`))
  config.entry = config.entry || {}
  config.entry['plugin'] = `src/plugins/${name.toLowerCase()}/index.js`
  config.output = {}
  config.output.libraryTarget = 'umd'
  config.output.library = `${namespace}${name}Plugin`
  config.output.filename = `index.min.js`
  config.output.path = path.resolve(__dirname, `../dist/plugins/${name.toLowerCase()}`)
  return config
}

function buildConfig(one) {
  one.importName = _camelCase(one.name)
  one.path = path.resolve(__dirname, '../' + maps[one.importName])

  delete config.entry

  config.plugins.forEach((one, index) => {
    if (one.constructor.name === 'ExtractTextPlugin') {
      config.plugins.splice(index, 1)
    }
  })

  config.plugins.push(new ExtractTextPlugin(`index.min.css`))

  config.entry = config.entry || {}
  config.entry[one.name] = one.path
  config.output = {}
  config.output.libraryTarget = 'umd'
  config.output.library = `${namespace}${one.importName}`
  config.output.filename = `index.min.js`
  config.output.path = path.resolve(__dirname, `../dist/components/${one.name}/`)
  return config
}

function toDash(str) {
  return str.replace(/([A-Z])/g, function (m, w) {
    return '-' + w.toLowerCase();
  }).replace('-', '')
}
<commit_msg>build: Exclude tools<commit_after>'use strict'

/**
* --locale='zh-CN'
* --namespace='vux'
*/

var argv = require('yargs').argv
var namespace = argv.namespace || 'vux'

let config = require('./webpack.prod.conf.js')
config.vux.plugins.forEach(function(plugin) {
  if (plugin.name === 'i18n') {
    plugin.vuxStaticReplace = true
    plugin.vuxLocale = argv['locale'] || 'zh-CN'
  }
})
config.vux.options.env = 'production'

const webpack = require('webpack')
const mkdirp = require('mkdirp')
const fs = require('fs')
const touch = require('touch')
const path = require('path')

mkdirp.sync(path.resolve(__dirname, '../dist/plugins'))
mkdirp.sync(path.resolve(__dirname, '../dist/styles'))

const list = require(path.resolve(__dirname, '../src/datas/vux_component_list.json'))
const maps = require(path.resolve(__dirname, '../src/components/map.json'))
// 查找在maps里但不在list里的组件
let others = []
for(let i in maps) {
  let match = list.filter(function(one){
    return _camelCase(one.name) === i
  })
  if (match.length === 0 && !/Plugin|Data|Directive|Filter|Item|NOTICE|Demo|Dev|Tool|md5|base64|cookie/.test(i)) {
    others.push({
      name: toDash(i),
      importName: i,
      path: maps[i]
    })
  }
}

others.push({
  name: 'swiper-item',
  importName: 'SwiperItem',
  path: maps['SwiperItem']
})

var ExtractTextPlugin = require('extract-text-webpack-plugin')
var co = require('co')
var thunkify = require('thunkify')
var pkg = require(path.resolve(__dirname, '../package.json'))

var build = thunkify(function (config, name, cb) {
  let start = new Date().getTime()
  console.log(`start:${name}`)
  webpack(config, function (err, stats) {
    if (!config.entry.vux) {
      mkdirp.sync(path.resolve(config.output.path))
      touch.sync(path.resolve(config.output.path, './index.min.css'))
    }
    var jsonStats = stats.toJson()
    var assets = jsonStats.assets[0]
    var size = assets.size / 1024
    size = size.toFixed(2) + 'k'
    console.log('size', size)
    console.log('time', (new Date().getTime() - start) / 1000 + 's')
    console.log('----------------')
    cb && cb(err)
  })
})

var utils = require('./utils')
config.devtool = false
config.plugins = config.plugins.slice(0, -2)
config.plugins.forEach((one, index) => {
  if (one.constructor.name === 'HtmlWebpackPlugin') {
    config.plugins.splice(index, 1)
  }
  if (one.constructor.name === 'ExtractTextPlugin') {
    config.plugins.splice(index, 1)
  }
})

config.output.assetsPublicPath = '/'

let isBuilding = false

co(function*() {
  try {
    for (let n = 0; n < others.length; n++) {
      yield build(buildConfig(others[n]), others[n].name)
    }
  } catch (e) {}
})

co(function* () {
  try {
    yield build(buildMainConfig(), 'vux')
  } catch(e){
    console.log(e)
  }

  try {
    const pluginList = ['Confirm', 'Toast', 'Device', 'Alert', 'Loading']
    for (let j = 0; j < pluginList.length; j++) {
      yield build(buildPlugin(pluginList[j]), `Plugin ${pluginList[j]}`)
    }
  } catch (e) {
    console.log(e)
  }

  try {
    for (let i = 0; i < list.length; i++) {
      let one = list[i]
      if(one.items) {
        for(let j = 0; j < one.items.length; j++) {
          one.name = one.items[j]
          one.importName = _camelCase(one.items[j])
          one.path = maps[one.importName]
          yield build(buildConfig(one), one.items[j])
        }
      } else {
        yield build(buildConfig(one), one.name)
      }
    }
  } catch (e) {
    console.log(e)
  }
})

function camelCase(input) {
  let str = input.toLowerCase().replace(/-(.)/g, function (match, group1) {
    return group1.toUpperCase();
  })
  str = str.replace(/_(.)/g, function (match, group1) {
    return group1.toUpperCase()
  });
  return str
}

function _camelCase(input) {
  let str = camelCase(input)
  return str.slice(0, 1).toUpperCase() + str.slice(1)
}

function buildMainConfig() {

  // list all components
  const list = require('../src/components/map.json')
  let code = 'const vux = {}\n'
  code += `/* only for building vux.css */
import Style from '../styles/index.vue'\n`

  delete list['NOTICE']
  delete list['ChinaAddressV1Data']

  for (let i in list) {
      const name = `${namespace}${i}`
      code += `import ${name} from '${list[i]}'\n
vux['${name}'] = ${name}\n`
  }

  code += `
if (!!window) {
  for (let i in vux) {
    window[i] = vux[i]
  }
}\n`
  code += `module.exports = vux`

  fs.writeFileSync(path.resolve(__dirname, '../src/components/index.js'), code)

  delete config.entry

  config.plugins.forEach((one, index) => {
    if (one.constructor.name === 'ExtractTextPlugin') {
      config.plugins.splice(index, 1)
    }
  })

  config.plugins.push(new ExtractTextPlugin(`vux.min.css`))

  config.entry = config.entry || {}
  config.entry['vux'] = 'src/components/index.js'
  config.output = {}
  config.output.libraryTarget = 'umd'
  config.output.library = `vux`
  config.output.filename = `vux.min.js`
  config.output.path = path.resolve(__dirname, `../dist/`)
  return config
}

// build plugins
function buildPlugin (name) {
  delete config.entry

  config.plugins.forEach((one, index) => {
    if (one.constructor.name === 'ExtractTextPlugin') {
      config.plugins.splice(index, 1)
    }
  })

  config.plugins.push(new ExtractTextPlugin(`index.min.css`))
  config.entry = config.entry || {}
  config.entry['plugin'] = `src/plugins/${name.toLowerCase()}/index.js`
  config.output = {}
  config.output.libraryTarget = 'umd'
  config.output.library = `${namespace}${name}Plugin`
  config.output.filename = `index.min.js`
  config.output.path = path.resolve(__dirname, `../dist/plugins/${name.toLowerCase()}`)
  return config
}

function buildConfig(one) {
  one.importName = _camelCase(one.name)
  one.path = path.resolve(__dirname, '../' + maps[one.importName])

  delete config.entry

  config.plugins.forEach((one, index) => {
    if (one.constructor.name === 'ExtractTextPlugin') {
      config.plugins.splice(index, 1)
    }
  })

  config.plugins.push(new ExtractTextPlugin(`index.min.css`))

  config.entry = config.entry || {}
  config.entry[one.name] = one.path
  config.output = {}
  config.output.libraryTarget = 'umd'
  config.output.library = `${namespace}${one.importName}`
  config.output.filename = `index.min.js`
  config.output.path = path.resolve(__dirname, `../dist/components/${one.name}/`)
  return config
}

function toDash(str) {
  return str.replace(/([A-Z])/g, function (m, w) {
    return '-' + w.toLowerCase();
  }).replace('-', '')
}
<|endoftext|>


<commit_before>Package.describe({
  name: 'iron-dynamic-template',
  summary: 'Dynamic templates and data contexts.',
  version: "0.1.0",
  githubUrl: "https://github.com/eventedmind/iron-dynamic-template"
});

Package.on_use(function (api) {
  api.use('ui');
  api.use('spacebars');
  api.use('jquery')
  api.use('deps');
  api.use('templating');

  api.use('iron-core');

  api.add_files('dynamic_template.js', 'client');
});

Package.on_test(function (api) {
  api.use('iron-dynamic-template');
  api.use('templating');
  api.use('tinytest');
  api.use('test-helpers');
  api.use('ui');

  api.add_files('dynamic_template_test.html', 'client');
  api.add_files('dynamic_template_test.js', 'client');
});
<commit_msg>imply iron-core<commit_after>Package.describe({
  name: 'iron-dynamic-template',
  summary: 'Dynamic templates and data contexts.',
  version: "0.1.0",
  githubUrl: "https://github.com/eventedmind/iron-dynamic-template"
});

Package.on_use(function (api) {
  api.use('ui');
  api.use('spacebars');
  api.use('jquery')
  api.use('deps');
  api.use('templating');

  api.use('iron-core');
  api.imply('iron-core');

  api.add_files('dynamic_template.js', 'client');
});

Package.on_test(function (api) {
  api.use('iron-dynamic-template');
  api.use('templating');
  api.use('tinytest');
  api.use('test-helpers');
  api.use('ui');

  api.add_files('dynamic_template_test.html', 'client');
  api.add_files('dynamic_template_test.js', 'client');
});
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2012, Martin Borho.
 * Licensed under the Affero General Public License version 3 or later.
 * See LICENSE for details.
 */
var FeedMe = require('feedme'),
    parser = new FeedMe(),
    request = require('request'),
    md5 = require('blueimp-md5').md5;

var Feed = function(url, data, conditionals) {
    this.valid = false;
    this.conditionals = conditionals;
    this.skey = md5(url);
    this.url   = url;
    this.title = '';
    this.subtitle = '';
    this.link  = '';
    this.pubSubHub = false;
    this.entries = [];
    this.setData(data);
}

Feed.prototype.setData =function(data) {
    this.setTitle(data);
    this.setSubTitle(data);
    this.setLinks(data);
    this.setEntries(data);
    this.valid = true;
}

Feed.prototype.setTitle = function(data) {
    var title = '#';
    if(data.title !== undefined && data.title.text !== undefined) {
        title = data.title.text;
    } else if(typeof(data.title) === "string") {
        title = data.title;
    }
    this.title = this.trim(title);
}

Feed.prototype.setSubTitle = function(data) {
    var subtitle = '';
    if(data.subtitle !== undefined) {
        if(data.subtitle instanceof Object && data.subtitle.text !== undefined) {
            subtitle = data.subtitle.text;
        } else if(typeof(data.subtitle) === "string") {
            subtitle = data.subtitle;
        }
    } else if(data.description !== undefined) {
        if(data.description instanceof Object === true) {
//             console.log(data)
        } else if(typeof(data.description) === "string") {
            subtitle = data.description;
        }
    }
    this.subtitle = this.trim(subtitle);
}

Feed.prototype.setLinks = function(data) {
    var link = '',
        pubsub = false,
        links = [];

    if(typeof(data.link) === "string") {
        link = data.link;
    } else {
        // fill links arr for further checks
        links =  (!(data.link instanceof Array)) ? [data.link] : data.link;
    }

    if(data['atom10:link'] !== undefined) {
        // add to links arr for further checks
        links = links.concat(data['atom10:link']);
    }

    if(data['atom:link'] !== undefined) {
        // add to links arr for further checks
        links = links.concat(data['atom:link']);
    }

    links.forEach(function(rel) {
        if(rel !== undefined && rel.rel !== undefined) {
            if(rel.rel === 'hub') {
                pubsub = rel.href;
            } else if(rel.rel === 'alternate' && (rel.type == undefined || rel.type == 'text/html')) {
                link = rel.href;
            }
        }
    });

    this.link = this.trim(link);
    if(pubsub) this.pubSubHub = this.trim(pubsub);
}

Feed.prototype.setEntries = function(data) {
    var max = data.items.length,
        entries = [];
    for(var x=0; max > x;x++) {
        var entry = {};
        entry.title = this.getItemTitle(data.items[x]);
        entry.summary = this.getItemSummary(data.items[x]);
        entry.link = this.getItemLink(data.items[x]);
        entry.published = this.getItemPublished(data.items[x]);
        entries.push(entry);
    }
    this.entries = entries;
}

Feed.prototype.getItemTitle = function(item) {
    var result = '';
    if(typeof(item.title) == 'string') {
        result = item.title;
    } else if(typeof(item.title.text) == 'string') {
        result = item.title.text;
    }
    return result;
}

Feed.prototype.getItemLink = function(item) {
    var result = '',
        links = [];
    if(typeof(item.link) == 'string') {
        result = item.link;
    } else if(typeof(item.link) == 'object') {
        var links =  (!(item.link instanceof Array)) ? [item.link] : item.link;
        for(var y=0; links.length > y;y++) {
            if(links[y].rel == "alternate") {
                result = links[y].href;
                break;
            }
        }
    }
    return result;
}

Feed.prototype.getItemSummary = function(item) {
    var result = '';
    if(typeof(item['content:encoded']) == 'string') {
        result = item['content:encoded'];
    } else if(typeof(item.description) == 'string') {
        result = item.description;
    } else if(item.content !== undefined) {
        if(typeof(item.content) == 'object' && item.content.text !== undefined) {
            result = item.content.text;
        } else if(typeof(item.content) == 'string') {
            result = item.content;
        }
    } else if(item.summary !== undefined) {
        if(typeof(item.summary) == 'string') {
            result = item.summary;
        } else {
            var summaries = (!(item.summary instanceof Array)) ? [item.summary] : item.summary;
            for(var j=0; summaries.length > j;j++) {
                if(summaries[j].type == "html") {
                    result = summaries[j].text;
                    break;
                }
            }
        }
    }
    return result;
}

Feed.prototype.getItemPublished = function(item) {
    var result = '';
    if(typeof(item.published) == 'string') {
        result = new Date(item.published).getTime()
    } else if(typeof(item.pubdate) == 'string') {
        result = new Date(item.pubdate).getTime()
    } else {
        result = new Date().getTime()
    }
    return result;
}

Feed.prototype.trim = function(str) {
    try {
        return str.replace(/^(\s*)((\S+\s*?)*)(\s*)$/,"$2")
    } catch(e) {
        console.log(e);
        console.log(str);
    }
    return '';
}

var FeedLoader = function(options, cb ) {

    this.conditionals = {};
    this.cb = cb;

    if(typeof(options) == "string") {
        this.url = options;
    } else if(typeof(options) == "object") {
        this.url = options.url;
        if (options.conditionals !== undefined)
            this.conditionals = options.conditionals;
    }

}

FeedLoader.prototype.load = function() {

    var cb = this.cb;
    request({uri:this.url, encoding:'binary', headers: this.conditionals}, function (error, response, body) {
        try {
            var res =  false,
                headers = {
                    "If-None-Match": (response.headers["etag"] !== undefined) ? response.headers["etag"] : false,
                    "If-Modified-Since": (response.headers["last-modified"] !== undefined)
                                        ? response.headers["last-modified"] : false,
                },
                parser = new FeedMe();
            if (!error){
                if(response.statusCode == 200) {
                    body = body.replace(/(\r\n|\n|\r)/gm,"");
                    if(body.search(/encoding=['"]utf-8['"]/i) > -1) {
                        var buffer = new Buffer(body, 'binary');
                        body = buffer.toString()
                    }
                    parser.write(body);
                    res = new Feed(response.request.uri.href, parser.done(), headers);
                    return cb(null, res);
                } else if(response.statusCode ==304){
                    console.log('304  not modified');
                    return cb(null, null);
                }
            } else {
                return cb(error);
            }
        } catch(e) {
            return cb(e);
        }
    });
}

exports.FeedLoader = FeedLoader
<commit_msg>fixed feedparser to work with feedme 0.2.2<commit_after>/**
 * Copyright (c) 2012, Martin Borho.
 * Licensed under the Affero General Public License version 3 or later.
 * See LICENSE for details.
 */
var FeedMe = require('feedme'),
    parser = new FeedMe(),
    request = require('request'),
    md5 = require('blueimp-md5').md5;

var Feed = function(url, data, conditionals) {
    this.valid = false;
    this.conditionals = conditionals;
    this.skey = md5(url);
    this.url   = url;
    this.title = '';
    this.subtitle = '';
    this.link  = '';
    this.pubSubHub = false;
    this.entries = [];
    this.setData(data);
}

Feed.prototype.setData =function(data) {
    this.setTitle(data);
    this.setSubTitle(data);
    this.setLinks(data);
    this.setEntries(data);
    this.valid = true;
}

Feed.prototype.setTitle = function(data) {
    var title = '#';
    if(data.title !== undefined && data.title.text !== undefined) {
        title = data.title.text;
    } else if(typeof(data.title) === "string") {
        title = data.title;
    }
    this.title = this.trim(title);
}

Feed.prototype.setSubTitle = function(data) {
    var subtitle = '';
    if(data.subtitle !== undefined) {
        if(data.subtitle instanceof Object && data.subtitle.text !== undefined) {
            subtitle = data.subtitle.text;
        } else if(typeof(data.subtitle) === "string") {
            subtitle = data.subtitle;
        }
    } else if(data.description !== undefined) {
        if(data.description instanceof Object === true) {
//             console.log(data)
        } else if(typeof(data.description) === "string") {
            subtitle = data.description;
        }
    }
    this.subtitle = this.trim(subtitle);
}

Feed.prototype.setLinks = function(data) {
    var link = '',
        pubsub = false,
        links = [];

    if(typeof(data.link) === "string") {
        link = data.link;
    } else {
        // fill links arr for further checks
        links =  (!(data.link instanceof Array)) ? [data.link] : data.link;
    }

    if(data['atom10:link'] !== undefined) {
        // add to links arr for further checks
        links = links.concat(data['atom10:link']);
    }

    if(data['atom:link'] !== undefined) {
        // add to links arr for further checks
        links = links.concat(data['atom:link']);
    }

    links.forEach(function(rel) {
        if(rel !== undefined && rel.rel !== undefined) {
            if(rel.rel === 'hub') {
                pubsub = rel.href;
            } else if(rel.rel === 'alternate' && (rel.type == undefined || rel.type == 'text/html')) {
                link = rel.href;
            }
        }
    });

    this.link = this.trim(link);
    if(pubsub) this.pubSubHub = this.trim(pubsub);
}

Feed.prototype.setEntries = function(data) {
    var max = data.items.length,
        entries = [];
    for(var x=0; max > x;x++) {
        var entry = {};
        entry.title = this.getItemTitle(data.items[x]);
        entry.summary = this.getItemSummary(data.items[x]);
        entry.link = this.getItemLink(data.items[x]);
        entry.published = this.getItemPublished(data.items[x]);
        entries.push(entry);
    }
    this.entries = entries;
}

Feed.prototype.getItemTitle = function(item) {
    var result = '';
    if(typeof(item.title) == 'string') {
        result = item.title;
    } else if(typeof(item.title.text) == 'string') {
        result = item.title.text;
    }
    return result;
}

Feed.prototype.getItemLink = function(item) {
    var result = '',
        links = [];
    if(typeof(item.link) == 'string') {
        result = item.link;
    } else if(typeof(item.link) == 'object') {
        var links =  (!(item.link instanceof Array)) ? [item.link] : item.link;
        for(var y=0; links.length > y;y++) {
            if(links[y].rel == "alternate") {
                result = links[y].href;
                break;
            }
        }
    }
    return result;
}

Feed.prototype.getItemSummary = function(item) {
    var result = '';
    if(typeof(item['content:encoded']) == 'string') {
        result = item['content:encoded'];
    } else if(typeof(item.description) == 'string') {
        result = item.description;
    } else if(item.content !== undefined) {
        if(typeof(item.content) == 'object' && item.content.text !== undefined) {
            result = item.content.text;
        } else if(typeof(item.content) == 'string') {
            result = item.content;
        }
    } else if(item.summary !== undefined) {
        if(typeof(item.summary) == 'string') {
            result = item.summary;
        } else {
            var summaries = (!(item.summary instanceof Array)) ? [item.summary] : item.summary;
            for(var j=0; summaries.length > j;j++) {
                if(summaries[j].type == "html") {
                    result = summaries[j].text;
                    break;
                }
            }
        }
    }
    return result;
}

Feed.prototype.getItemPublished = function(item) {
    var result = '';
    if(typeof(item.published) == 'string') {
        result = new Date(item.published).getTime()
    } else if(typeof(item.pubdate) == 'string') {
        result = new Date(item.pubdate).getTime()
    } else {
        result = new Date().getTime()
    }
    return result;
}

Feed.prototype.trim = function(str) {
    try {
        return str.replace(/^(\s*)((\S+\s*?)*)(\s*)$/,"$2")
    } catch(e) {
        console.log(e);
        console.log(str);
    }
    return '';
}

var FeedLoader = function(options, cb ) {

    this.conditionals = {};
    this.cb = cb;

    if(typeof(options) == "string") {
        this.url = options;
    } else if(typeof(options) == "object") {
        this.url = options.url;
        if (options.conditionals !== undefined)
            this.conditionals = options.conditionals;
    }

}

FeedLoader.prototype.load = function() {

    var cb = this.cb;
    request({uri:this.url, encoding:'binary', headers: this.conditionals}, function (error, response, body) {
        try {
            var res =  false,
                headers = {
                    "If-None-Match": (response.headers["etag"] !== undefined) ? response.headers["etag"] : false,
                    "If-Modified-Since": (response.headers["last-modified"] !== undefined)
                                        ? response.headers["last-modified"] : false,
                },
                parser = new FeedMe(true);
            if (!error){
                if(response.statusCode == 200) {
                    body = body.replace(/(\r\n|\n|\r)/gm,"");
                    if(body.search(/encoding=['"]utf-8['"]/i) > -1) {
                        var buffer = new Buffer(body, 'binary');
                        body = buffer.toString()
                    }
                    parser.write(body);
                    res = new Feed(response.request.uri.href, parser.done(), headers);
                    return cb(null, res);
                } else if(response.statusCode ==304){
                    console.log('304  not modified');
                    return cb(null, null);
                }
            } else {
                return cb(error);
            }
        } catch(e) {
            return cb(e);
        }
    });
}

exports.FeedLoader = FeedLoader
<|endoftext|>


<commit_before>Package.describe({
  summary: "meteor sql bindings for server-side calls"
});

Npm.depends({ "newrelic": "1.0.1" });

Package.on_use(function(api) {
  if (api.export) api.export('newrelic', 'server');
  api.add_files('newrelic_npm.js', 'server');
});

<commit_msg>Enable latest version of newrelic agent<commit_after>Package.describe({
  summary: "meteor sql bindings for server-side calls"
});

Npm.depends({ "newrelic": "1.x.x" });

Package.on_use(function(api) {
  if (api.export) api.export('newrelic', 'server');
  api.add_files('newrelic_npm.js', 'server');
});

<|endoftext|>