<commit_before>/*
 * CARIS oscar - Open Spatial Component ARchitecture
 *
 * Copyright 2014 CARIS <http://www.caris.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
oscar.Control.SimpleCatalogueSearch = oscar.BaseClass(oscar.Control.CatalogueSearchForm, {
    BANG : /!e/,
    form : null,
    basicSearch : true,
    handler : null,
    help : "help/simple-search-{0}.html",
    spatialSearch : null,
    initialize : function(options) {
        oscar.Control.CatalogueSearchForm.prototype.initialize.apply(this, arguments);
        this.spatialSearch = new oscar.Control.Box({
            allowPanning : false,
            keyMask : OpenLayers.Handler.MOD_CTRL
        });
        this.spatialSearch.events.on({
            "done" : this.buildSpatial,
            scope : this
        });

        this.events.on({
            "search" : this.preprocessQuery,
            scope : this
        });
    },
    helpLocation : function() {
        return oscar._getScriptLocation() + this.help;
    },
    preprocessQuery : function(query) {
        // check for advanced search flag.
        if (this.bangLookup(query) || query.trim().length === 0) {
            return;
        }

        // build the query filter string
        var queryArray = [];
        for (var i = 0; i < this.catalogueService.defaultSearchFields.length; i++) {
            var queryString = "";
            queryString += this.catalogueService.defaultSearchFields[i] + " LIKE ";
            queryString += "'" + query + "'";
            queryArray.push(queryString);
        }
        this.searchHandler.events.triggerEvent("displayfilter", queryArray.join(" OR "));
        this.performSearch(queryArray.join(" OR "));
    },
    bangLookup : function(query) {
        var hasMatch = function(text, pattern) {
            if (pattern instanceof RegExp) {
                return pattern.exec(text);
            } else {
                return pattern(text);
            }
        };
        var hasBang = false;
        while ((matches = hasMatch(query, this.BANG))) {
            if (!hasBang) {
                hasBang = true;
            }
            var match = matches[0];
            query = query.replace(match, "").trim();
        }
        if (hasBang) {
            this.searchHandler.events.triggerEvent("advancedSearch", query.trim());
            return true;
        }
        return false;
    },
    draw : function() {
        oscar.Control.CatalogueSearchForm.prototype.draw.apply(this, arguments);

        this.input = $$("<input type='search' id='q' name='q' size='50' value=''>");
        this.input.attr("placeholder", oscar.i18n("simple-search-placeholder"));
        this.input.addClass("ui-widget ui-corner-all");
        this.input.css({
            'text-align' : 'left',
            'outline' : 'none',
            'cursor' : 'text',
            'border' : '1px solid #2a3583',
            'line-height' : '1.9em',
        });
        if (this.defaultText) {
            this.input.val(this.defaultText);
        }
        this.map.addControl(this.spatialSearch);
        this.spatialSearch.activate();
        var inputContainer = $$("

");
        inputContainer.addClass("oscar-inline-container");
        inputContainer.append(this.input);

        this.form.append(inputContainer);
        this.button = $$("<button></button").html(oscar.i18n("Search"));

        var search_btn_container = $$("

");
        search_btn_container.addClass("oscar-inline-container");
        search_btn_container.append(this.button);
        this.form.append(search_btn_container);
        var help_container = $$("

");
        help_container.addClass("oscar-inline-container");

        this.addHelp("Help", help_container);
        this.form.append(help_container);

        var scope = this;
        this.button.button({
            icons : {
                primary : "ui-icon-oux-search"
            },
            text : true
        }).click($$.proxy(function() {
            this.events.triggerEvent("search", this.input.val());
        }, this));
        var args = OpenLayers.Util.getParameters();
        if (args.q) {
            this.input.val(args.q);
            setTimeout($$.proxy(function() {
                this.button.click();
            }, this), 500);
        }

        return this.div;
    },
    toggleFeatureSelection : function(forceDeactivate) {
        var selFeatures = this.map.getControlsByClass("OpenLayers.Control.SelectFeature");
        for (var i = 0; i < selFeatures.length; i++) {
            if (forceDeactivate) {
                selFeatures[i].deactivate();
            } else {
                selFeatures[i].activate();
            }
        }
    },
    buildSpatial : function(geom) {
        var query = {
            spatial : geom.getBounds(),
            projection : this.map.getProjection(),
            type : oscar.Handler.CSW.prototype.SPATIAL
        }
        var criteria = new oscar.QueryType(oscar.QueryType.prototype.SPATIAL, query);
        this.searchHandler.search(criteria);
    },
    CLASS_NAME : "oscar.Control.SimpleCatalogueSearch"
});<commit_msg>SFD-220<commit_after>/*
 * CARIS oscar - Open Spatial Component ARchitecture
 *
 * Copyright 2014 CARIS <http://www.caris.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
oscar.Control.SimpleCatalogueSearch = oscar.BaseClass(oscar.Control.CatalogueSearchForm, {
    BANG : /!e/,
    form : null,
    basicSearch : true,
    handler : null,
    help : "help/simple-search-{0}.html",
    spatialSearch : null,
    initialize : function(options) {
        oscar.Control.CatalogueSearchForm.prototype.initialize.apply(this, arguments);
        this.spatialSearch = new oscar.Control.Box({
            allowPanning : false,
            keyMask : OpenLayers.Handler.MOD_CTRL
        });
        this.spatialSearch.events.on({
            "done" : this.buildSpatial,
            scope : this
        });

        this.events.on({
            "search" : this.preprocessQuery,
            scope : this
        });
    },
    helpLocation : function() {
        return oscar._getScriptLocation() + this.help;
    },
    preprocessQuery : function(query) {
        // check for advanced search flag.
        if (this.bangLookup(query) || query.trim().length === 0) {
            return;
        }

        // build the query filter string
		//add wildcards to the start and end of the query
		if(!query.startsWith("*")) {
			query = "*"+query;
		}
		if(!query.endsWith("*")) {
			query+="*";
		}

        var queryArray = [];
        for (var i = 0; i < this.catalogueService.defaultSearchFields.length; i++) {
            var queryString = "";
            queryString += this.catalogueService.defaultSearchFields[i] + " LIKE ";
            queryString += "'" + query + "'";
            queryArray.push(queryString);
        }
        this.searchHandler.events.triggerEvent("displayfilter", queryArray.join(" OR "));
        this.performSearch(queryArray.join(" OR "));
    },
    bangLookup : function(query) {
        var hasMatch = function(text, pattern) {
            if (pattern instanceof RegExp) {
                return pattern.exec(text);
            } else {
                return pattern(text);
            }
        };
        var hasBang = false;
        while ((matches = hasMatch(query, this.BANG))) {
            if (!hasBang) {
                hasBang = true;
            }
            var match = matches[0];
            query = query.replace(match, "").trim();
        }
        if (hasBang) {
            this.searchHandler.events.triggerEvent("advancedSearch", query.trim());
            return true;
        }
        return false;
    },
    draw : function() {
        oscar.Control.CatalogueSearchForm.prototype.draw.apply(this, arguments);

        this.input = $$("<input type='search' id='q' name='q' size='50' value=''>");
        this.input.attr("placeholder", oscar.i18n("simple-search-placeholder"));
        this.input.addClass("ui-widget ui-corner-all");
        this.input.css({
            'text-align' : 'left',
            'outline' : 'none',
            'cursor' : 'text',
            'border' : '1px solid #2a3583',
            'line-height' : '1.9em',
        });
        if (this.defaultText) {
            this.input.val(this.defaultText);
        }
        this.map.addControl(this.spatialSearch);
        this.spatialSearch.activate();
        var inputContainer = $$("

");
        inputContainer.addClass("oscar-inline-container");
        inputContainer.append(this.input);

        this.form.append(inputContainer);
        this.button = $$("<button></button").html(oscar.i18n("Search"));

        var search_btn_container = $$("

");
        search_btn_container.addClass("oscar-inline-container");
        search_btn_container.append(this.button);
        this.form.append(search_btn_container);
        var help_container = $$("

");
        help_container.addClass("oscar-inline-container");

        this.addHelp("Help", help_container);
        this.form.append(help_container);

        var scope = this;
        this.button.button({
            icons : {
                primary : "ui-icon-oux-search"
            },
            text : true
        }).click($$.proxy(function() {
            this.events.triggerEvent("search", this.input.val());
        }, this));
        var args = OpenLayers.Util.getParameters();
        if (args.q) {
            this.input.val(args.q);
            setTimeout($$.proxy(function() {
                this.button.click();
            }, this), 500);
        }

        return this.div;
    },
    toggleFeatureSelection : function(forceDeactivate) {
        var selFeatures = this.map.getControlsByClass("OpenLayers.Control.SelectFeature");
        for (var i = 0; i < selFeatures.length; i++) {
            if (forceDeactivate) {
                selFeatures[i].deactivate();
            } else {
                selFeatures[i].activate();
            }
        }
    },
    buildSpatial : function(geom) {
        var query = {
            spatial : geom.getBounds(),
            projection : this.map.getProjection(),
            type : oscar.Handler.CSW.prototype.SPATIAL
        }
        var criteria = new oscar.QueryType(oscar.QueryType.prototype.SPATIAL, query);
        this.searchHandler.search(criteria);
    },
    CLASS_NAME : "oscar.Control.SimpleCatalogueSearch"
});<|endoftext|>


<commit_before>//
// Copyright 2010-2011 Three Crickets LLC.
//
// The contents of this file are subject to the terms of the Apache License
// version 2.0: http://www.opensource.org/licenses/apache2.0.php
//
// Alternatively, you can obtain a royalty free commercial license with less
// limitations, transferable or non-transferable, directly from Three Crickets
// at http://threecrickets.com/
//

//
// MongoVision Settings
//

document.execute('/defaults/application/settings/')
document.executeOnce('/mongo-db/')

applicationName = 'MongoVision'
applicationDescription = 'A MongoDB frontend'
applicationAuthor = 'Tal Liron'
applicationOwner = 'Three Crickets'
applicationHomeURL = 'http://threecrickets.com/'
applicationContactEmail = 'info@threecrickets.com'

showDebugOnError = true
//minimumTimeBetweenValidityChecks = 0

predefinedGlobals['mongovision.version'] = '1.0 R%REVISION%'
predefinedGlobals['mongovision.extJS.debug'] = false
predefinedGlobals['mongovision.locale'] = 'en'

try {
	if (null !== predefinedSharedGlobals['mongoDb.defaultConnection']) {
		var addresses = []
		for (var i = predefinedSharedGlobals['mongoDb.defaultConnection'].allAddress.iterator(); i.hasNext(); ) {
			addresses.push(String(i.next()))
		}
		predefinedGlobals['mongovision.connection'] = MongoDB.connect(addresses)
	}
	else if (predefinedSharedGlobals['mongoDb.defaultServers']) {
		predefinedGlobals['mongovision.connection'] = MongoDB.connect(predefinedSharedGlobals['mongoDb.defaultServers'])
	}
	else {
		predefinedGlobals['mongovision.connection'] = MongoDB.connect('127.0.0.1')
	}
}
catch (x) {
}
<commit_msg>Clone shared connection<commit_after>//
// Copyright 2010-2011 Three Crickets LLC.
//
// The contents of this file are subject to the terms of the Apache License
// version 2.0: http://www.opensource.org/licenses/apache2.0.php
//
// Alternatively, you can obtain a royalty free commercial license with less
// limitations, transferable or non-transferable, directly from Three Crickets
// at http://threecrickets.com/
//

//
// MongoVision Settings
//

document.execute('/defaults/application/settings/')
document.executeOnce('/applications/mongovision/libraries/mongo-db/')

applicationName = 'MongoVision'
applicationDescription = 'A MongoDB frontend'
applicationAuthor = 'Tal Liron'
applicationOwner = 'Three Crickets'
applicationHomeURL = 'http://threecrickets.com/'
applicationContactEmail = 'info@threecrickets.com'

showDebugOnError = true
//minimumTimeBetweenValidityChecks = 0

predefinedGlobals['mongovision.version'] = '1.0 R%REVISION%'
predefinedGlobals['mongovision.extJS.debug'] = false
predefinedGlobals['mongovision.locale'] = 'en'

try {
	if (null !== predefinedSharedGlobals['mongoDb.defaultConnection']) {
		var addresses = []
		for (var i = predefinedSharedGlobals['mongoDb.defaultConnection'].allAddress.iterator(); i.hasNext(); ) {
			addresses.push(String(i.next()))
		}
		predefinedGlobals['mongovision.connection'] = MongoDB.connect(addresses)
	}
	else if (predefinedSharedGlobals['mongoDb.defaultServers']) {
		predefinedGlobals['mongovision.connection'] = MongoDB.connect(predefinedSharedGlobals['mongoDb.defaultServers'])
	}
	else {
		predefinedGlobals['mongovision.connection'] = MongoDB.connect('127.0.0.1')
	}
}
catch (x) {
}
<|endoftext|>


<commit_before>import * as utils from 'base/utils';
import Model from 'base/model';

/*!
 * VIZABI Time Model
 */

var time_units = Object.keys(utils.timeFormats);

var TimeModel = Model.extend({

  /**
   * Default values for this model
   */
  _defaults: {
    dim: "time",
    value: "2015",
    start: "1800",
    end: "2015",
    playable: true,
    playing: false,
    loop: false,
    round: 'round',
    delay: 300,
    delayAnimations: 300,
    delayStart: 1200,
    delayEnd: 75,
    delayThresholdX2: 300,
    delayThresholdX4: 150,
    delaySet: false,
    unit: "year",
    step: 1, //step must be integer
    adaptMinMaxZoom: false, //TODO: remove from here. only for bubble chart
    xLogStops: [], //TODO: remove from here. only for mountain chart
    yMaxMethod: "latest", //TODO: remove from here. only for mountain chart
    record: false,
    probeX: 0, //TODO: remove from here. only for mountain chart
    tailFatX: 1, //TODO: remove from here. only for mountain chart
    tailCutX: 0, //TODO: remove from here. only for mountain chart
    tailFade: 1, //TODO: remove from here. only for mountain chart
    xScaleFactor: 1, //TODO: remove from here. only for mountain chart
    xScaleShift: 0, //TODO: remove from here. only for mountain chart
    xPoints: 50 //TODO: remove from here. only for mountain chart
  },

  /**
   * Initializes the language model.
   * @param {Object} values The initial values of this model
   * @param parent A reference to the parent model
   * @param {Object} bind Initial events to bind
   */
  init: function(name, values, parent, bind) {

    this._type = "time";
    //default values for time model
    var defaults = utils.deepClone(this._defaults);
    values = utils.extend(defaults, values);

    //same constructor
    this._super(name, values, parent, bind);

    var _this = this;
    this.dragging = false;
    this.postponePause = false;
    this.allSteps = {};

    //bing play method to model change
    this.on({

      "change:playing": function() {
        if(_this.playing === true) {
          _this._startPlaying();
        } else {
          _this._stopPlaying();
        }
      },

    });
  },

  /**
   * Formats value, start and end dates to actual Date objects
   */
  _formatToDates: function() {

    var date_attr = ["value", "start", "end"];
    for(var i = 0; i < date_attr.length; i++) {
      var attr = date_attr[i];
      if(!utils.isDate(this[attr])) {
        var date = utils.parseTime(this[attr].toString(), this.unit);
        this.set(attr, date);
      }
    }
  },

  /**
   * Validates the model
   */
  validate: function() {

    //unit has to be one of the available_time_units
    if(time_units.indexOf(this.unit) === -1) {
      utils.warn(this.unit + ' is not a valid time unit, using "year" instead.');
      this.unit = "year";
    }

    if(this.step < 1) {
      this.step = "year";
    }

    //make sure dates are transformed into dates at all times
    if(!utils.isDate(this.start) || !utils.isDate(this.end) || !utils.isDate(this.value)) {
      this._formatToDates();
    }

    //end has to be >= than start
    if(this.end < this.start) {
      this.end = this.start;
    }
    //value has to be between start and end
    if(this.value < this.start) {
      this.value = this.start;
    } else if(this.value > this.end) {
      this.value = this.end;
    }

    if(this.playable === false && this.playing === true) {
      this.playing = false;
    }
  },

  /**
   * Plays time
   */
  play: function() {
    this._startPlaying();
  },

  /**
   * Pauses time
   */
  pause: function(soft) {
    if(soft) {
      this.postponePause = true;
    } else {
      this.playing = false;
    }
  },

  /**
   * Indicates dragging of time
   */
  dragStart: function() {
    this.dragging = true;
  },
  dragStop: function() {
    this.dragging = false;
  },

  /**
   * gets time range
   * @returns range between start and end
   */
  getRange: function() {
    return d3.time[this.unit].utc.range(this.start, this.end, this.step);
  },

  /**
   * Gets filter for time
   * @param {Boolean} firstScreen get filter for current year only
   * @returns {Object} time filter
   */
  getFilter: function(firstScreen) {
    var start = utils.formatTime(this.start, this.unit);
    var end = utils.formatTime(this.end, this.unit);
    var value = utils.formatTime(this.value, this.unit);
    var dim = this.getDimension();
    var filter = {};

    filter[dim] = (firstScreen) ? [
      [value]
    ] : [
      [start, end]
    ];
    return filter;
  },

  /**
   * Gets formatter for this model
   * @returns {Function} formatter function
   */
  getParser: function() {
    var timeFormat = utils.getTimeFormat(this.unit);
    return function(d) {
      return timeFormat.parse(d);
    }
  },

  /**
   * Gets an array with all time steps for this model
   * @returns {Array} time array
   */
  getAllSteps: function() {
    var hash = "" + this.start + this.end + this.step;

    //return if cached
    if(this.allSteps[hash]) return this.allSteps[hash];

    this.allSteps[hash] = [];
    var curr = this.start;
    while(curr <= this.end) {
      this.allSteps[hash].push(curr);
      curr = d3.time[this.unit].utc.offset(curr, this.step);
    }
    return this.allSteps[hash];
  },

  /**
   * Snaps the time to integer
   * possible inputs are "start", "end", "value". "value" is default
   */
  snap: function(what) {
    if(!this.round) return;
    if(what == null) what = "value";
    var op = 'round';
    if(this.round === 'ceil') op = 'ceil';
    if(this.round === 'floor') op = 'floor';
    var time = d3.time[this.unit].utc[op](this[what]);
    this.set(what, time, true); //3rd argumennt forces update
  },

  /**
   * Starts playing the time, initializing the interval
   */
  _startPlaying: function() {
    //don't play if it's not playable
    if(!this.playable) return;

    var _this = this;
    var time = this.value;

    //go to start if we start from end point
    if(_this.end - time <= 0) {
      time = this.start;
      _this.value = time;
    } else {
      this.snap();
    }
    this.playing = true;
    this.playInterval();

    this.trigger("play");
  },

  playInterval: function(){
    if(!this.playing) return;
    var _this = this;
    var time = this.value;
    this.delayAnimations = this.delay;
    if(this.delay < this.delayThresholdX2) this.delayAnimations*=2;
    if(this.delay < this.delayThresholdX4) this.delayAnimations*=2;

    this._intervals.setInterval('playInterval_' + this._id, function() {
      if(time >= _this.end) {
        if(_this.loop) {
          time = _this.start;
          _this.value = time
        } else {
          _this.playing = false;
        }
        return;
      } else {

        _this._intervals.clearInterval('playInterval_' + _this._id);

        if(_this.postponePause || !_this.playing) {
          _this.playing = false;
          _this.postponePause = false;
          _this.getModelObject('value').set(_this.value, true, true /*force the change and make it persistent for URL and history*/);
        } else {
          var step = _this.step;
          if(_this.delay < _this.delayThresholdX2) step*=2;
          if(_this.delay < _this.delayThresholdX4) step*=2;
          time = d3.time[_this.unit].utc.offset(time, step);
          _this.getModelObject('value').set(time, null, false /*make change non-persistent for URL and history*/);
          _this.playInterval();
        }
      }
    }, this.delayAnimations);

  },

  /**
   * Stops playing the time, clearing the interval
   */
  _stopPlaying: function() {
    this._intervals.clearInterval('playInterval_' + this._id);
    //this.snap();
    this.trigger("pause");
  }

});

export default TimeModel;
<commit_msg>Removed time snapping on start playing. The assumption is that the time is already snapped when we start playing because only dragging the timeslider can un-snap the time, and it snaps on drag.end. Nothing else can do it. So we don't need this line. let's see if we survive without. As a consequence, the first time update in playing sequence will have this.playing flag up, so the bubble chart will zoom in smoothly. Closes #1213<commit_after>import * as utils from 'base/utils';
import Model from 'base/model';

/*!
 * VIZABI Time Model
 */

var time_units = Object.keys(utils.timeFormats);

var TimeModel = Model.extend({

  /**
   * Default values for this model
   */
  _defaults: {
    dim: "time",
    value: "2015",
    start: "1800",
    end: "2015",
    playable: true,
    playing: false,
    loop: false,
    round: 'round',
    delay: 300,
    delayAnimations: 300,
    delayStart: 1200,
    delayEnd: 75,
    delayThresholdX2: 300,
    delayThresholdX4: 150,
    delaySet: false,
    unit: "year",
    step: 1, //step must be integer
    adaptMinMaxZoom: false, //TODO: remove from here. only for bubble chart
    xLogStops: [], //TODO: remove from here. only for mountain chart
    yMaxMethod: "latest", //TODO: remove from here. only for mountain chart
    record: false,
    probeX: 0, //TODO: remove from here. only for mountain chart
    tailFatX: 1, //TODO: remove from here. only for mountain chart
    tailCutX: 0, //TODO: remove from here. only for mountain chart
    tailFade: 1, //TODO: remove from here. only for mountain chart
    xScaleFactor: 1, //TODO: remove from here. only for mountain chart
    xScaleShift: 0, //TODO: remove from here. only for mountain chart
    xPoints: 50 //TODO: remove from here. only for mountain chart
  },

  /**
   * Initializes the language model.
   * @param {Object} values The initial values of this model
   * @param parent A reference to the parent model
   * @param {Object} bind Initial events to bind
   */
  init: function(name, values, parent, bind) {

    this._type = "time";
    //default values for time model
    var defaults = utils.deepClone(this._defaults);
    values = utils.extend(defaults, values);

    //same constructor
    this._super(name, values, parent, bind);

    var _this = this;
    this.dragging = false;
    this.postponePause = false;
    this.allSteps = {};

    //bing play method to model change
    this.on({

      "change:playing": function() {
        if(_this.playing === true) {
          _this._startPlaying();
        } else {
          _this._stopPlaying();
        }
      },

    });
  },

  /**
   * Formats value, start and end dates to actual Date objects
   */
  _formatToDates: function() {

    var date_attr = ["value", "start", "end"];
    for(var i = 0; i < date_attr.length; i++) {
      var attr = date_attr[i];
      if(!utils.isDate(this[attr])) {
        var date = utils.parseTime(this[attr].toString(), this.unit);
        this.set(attr, date);
      }
    }
  },

  /**
   * Validates the model
   */
  validate: function() {

    //unit has to be one of the available_time_units
    if(time_units.indexOf(this.unit) === -1) {
      utils.warn(this.unit + ' is not a valid time unit, using "year" instead.');
      this.unit = "year";
    }

    if(this.step < 1) {
      this.step = "year";
    }

    //make sure dates are transformed into dates at all times
    if(!utils.isDate(this.start) || !utils.isDate(this.end) || !utils.isDate(this.value)) {
      this._formatToDates();
    }

    //end has to be >= than start
    if(this.end < this.start) {
      this.end = this.start;
    }
    //value has to be between start and end
    if(this.value < this.start) {
      this.value = this.start;
    } else if(this.value > this.end) {
      this.value = this.end;
    }

    if(this.playable === false && this.playing === true) {
      this.playing = false;
    }
  },

  /**
   * Plays time
   */
  play: function() {
    this._startPlaying();
  },

  /**
   * Pauses time
   */
  pause: function(soft) {
    if(soft) {
      this.postponePause = true;
    } else {
      this.playing = false;
    }
  },

  /**
   * Indicates dragging of time
   */
  dragStart: function() {
    this.dragging = true;
  },
  dragStop: function() {
    this.dragging = false;
  },

  /**
   * gets time range
   * @returns range between start and end
   */
  getRange: function() {
    return d3.time[this.unit].utc.range(this.start, this.end, this.step);
  },

  /**
   * Gets filter for time
   * @param {Boolean} firstScreen get filter for current year only
   * @returns {Object} time filter
   */
  getFilter: function(firstScreen) {
    var start = utils.formatTime(this.start, this.unit);
    var end = utils.formatTime(this.end, this.unit);
    var value = utils.formatTime(this.value, this.unit);
    var dim = this.getDimension();
    var filter = {};

    filter[dim] = (firstScreen) ? [
      [value]
    ] : [
      [start, end]
    ];
    return filter;
  },

  /**
   * Gets formatter for this model
   * @returns {Function} formatter function
   */
  getParser: function() {
    var timeFormat = utils.getTimeFormat(this.unit);
    return function(d) {
      return timeFormat.parse(d);
    }
  },

  /**
   * Gets an array with all time steps for this model
   * @returns {Array} time array
   */
  getAllSteps: function() {
    var hash = "" + this.start + this.end + this.step;

    //return if cached
    if(this.allSteps[hash]) return this.allSteps[hash];

    this.allSteps[hash] = [];
    var curr = this.start;
    while(curr <= this.end) {
      this.allSteps[hash].push(curr);
      curr = d3.time[this.unit].utc.offset(curr, this.step);
    }
    return this.allSteps[hash];
  },

  /**
   * Snaps the time to integer
   * possible inputs are "start", "end", "value". "value" is default
   */
  snap: function(what) {
    if(!this.round) return;
    if(what == null) what = "value";
    var op = 'round';
    if(this.round === 'ceil') op = 'ceil';
    if(this.round === 'floor') op = 'floor';
    var time = d3.time[this.unit].utc[op](this[what]);
    this.set(what, time, true); //3rd argumennt forces update
  },

  /**
   * Starts playing the time, initializing the interval
   */
  _startPlaying: function() {
    //don't play if it's not playable
    if(!this.playable) return;

    var _this = this;
    var time = this.value;

    //go to start if we start from end point
    if(_this.end - time <= 0) {
      time = this.start;
      _this.value = time;
    } else {
      //the assumption is that the time is already snapped when we start playing
      //because only dragging the timeslider can un-snap the time, and it snaps on drag.end
      //so we don't need this line. let's see if we survive without.
      //as a consequence, the first time update in playing sequence will have this.playing flag up
      //so the bubble chart will zoom in smoothly. Closes #1213
      //this.snap();
    }
    this.playing = true;
    this.playInterval();

    this.trigger("play");
  },

  playInterval: function(){
    if(!this.playing) return;
    var _this = this;
    var time = this.value;
    this.delayAnimations = this.delay;
    if(this.delay < this.delayThresholdX2) this.delayAnimations*=2;
    if(this.delay < this.delayThresholdX4) this.delayAnimations*=2;

    this._intervals.setInterval('playInterval_' + this._id, function() {
      if(time >= _this.end) {
        if(_this.loop) {
          time = _this.start;
          _this.value = time
        } else {
          _this.playing = false;
        }
        return;
      } else {

        _this._intervals.clearInterval('playInterval_' + _this._id);

        if(_this.postponePause || !_this.playing) {
          _this.playing = false;
          _this.postponePause = false;
          _this.getModelObject('value').set(_this.value, true, true /*force the change and make it persistent for URL and history*/);
        } else {
          var step = _this.step;
          if(_this.delay < _this.delayThresholdX2) step*=2;
          if(_this.delay < _this.delayThresholdX4) step*=2;
          time = d3.time[_this.unit].utc.offset(time, step);
          _this.getModelObject('value').set(time, null, false /*make change non-persistent for URL and history*/);
          _this.playInterval();
        }
      }
    }, this.delayAnimations);

  },

  /**
   * Stops playing the time, clearing the interval
   */
  _stopPlaying: function() {
    this._intervals.clearInterval('playInterval_' + this._id);
    //this.snap();
    this.trigger("pause");
  }

});

export default TimeModel;
<|endoftext|>


<commit_before>import * as t from "babel-types";

var awaitVisitor = {
  Function() {
    this.skip();
  },

  AwaitExpression(node) {
    node.type = "YieldExpression";

    if (node.all) {
      // await* foo; -> yield Promise.all(foo);
      node.all = false;
      node.argument = t.callExpression(t.memberExpression(t.identifier("Promise"), t.identifier("all")), [node.argument]);
    }
  }
};

var referenceVisitor = {
  ReferencedIdentifier(node, parent, scope, state) {
    var name = state.id.name;
    if (node.name === name && scope.bindingIdentifierEquals(name, state.id)) {
      return state.ref = state.ref || scope.generateUidIdentifier(name);
    }
  }
};

export default function (path, callId) {
  var node = path.node;

  node.async = false;
  node.generator = true;

  path.traverse(awaitVisitor, state);

  var call = t.callExpression(callId, [node]);

  var id = node.id;
  node.id = null;

  if (t.isFunctionDeclaration(node)) {
    var declar = t.variableDeclaration("let", [
      t.variableDeclarator(id, call)
    ]);
    declar._blockHoist = true;
    return declar;
  } else {
    if (id) {
      var state = { id };
      path.traverse(referenceVisitor, state);

      if (state.ref) {
        path.scope.parent.push({ id: state.ref });
        return t.assignmentExpression("=", state.ref, call);
      }
    }

    return call;
  }
}
<commit_msg>add missing FunctionExpression conversion when wrapping a function expression in a call for async to generator helper - fixes #2325<commit_after>import * as t from "babel-types";

var awaitVisitor = {
  Function() {
    this.skip();
  },

  AwaitExpression(node) {
    node.type = "YieldExpression";

    if (node.all) {
      // await* foo; -> yield Promise.all(foo);
      node.all = false;
      node.argument = t.callExpression(t.memberExpression(t.identifier("Promise"), t.identifier("all")), [node.argument]);
    }
  }
};

var referenceVisitor = {
  ReferencedIdentifier(node, parent, scope, state) {
    var name = state.id.name;
    if (node.name === name && scope.bindingIdentifierEquals(name, state.id)) {
      return state.ref = state.ref || scope.generateUidIdentifier(name);
    }
  }
};

export default function (path, callId) {
  var node = path.node;

  node.async = false;
  node.generator = true;

  path.traverse(awaitVisitor, state);

  var call = t.callExpression(callId, [node]);

  var id = node.id;
  node.id = null;

  if (t.isFunctionDeclaration(node)) {
    var declar = t.variableDeclaration("let", [
      t.variableDeclarator(id, call)
    ]);
    declar._blockHoist = true;
    return declar;
  } else {
    node.type = "FunctionExpression";

    if (id) {
      var state = { id };
      path.traverse(referenceVisitor, state);

      if (state.ref) {
        path.scope.parent.push({ id: state.ref });
        return t.assignmentExpression("=", state.ref, call);
      }
    }

    return call;
  }
}
<|endoftext|>


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

var carbonModule = require("carbon");
var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"];
var userModule = require("/app/modules/business-controllers/user.js")["userModule"];

//noinspection JSUnresolvedFunction Server
var carbonServer = new carbonModule.server.Server({
    tenanted: true,
    url: devicemgtProps["httpsURL"] + "/admin"
});

application.put("carbonServer", carbonServer);

var permissions = {
    "/permission/admin/Login": ["ui.execute"]
};

var adminPermissions = {
    "/permission/admin": ["ui.execute"]
};

//On Startup, admin user will get both roles: devicemgt-admin and devicemgt-user
//Average user through sign-up will only receive the role: devicemgt-user.
//Admin can setup necessary permissions for the role: devicemgt-user
userModule.addRole("internal/devicemgt-user", ["admin"], permissions);
userModule.addRole("internal/devicemgt-admin", ["admin"], adminPermissions);
<commit_msg>API subscription permission added to [devicemgt-user] role<commit_after>/*
 * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 * WSO2 Inc. licenses this file to you under the Apache License,
 * Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

var carbonModule = require("carbon");
var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"];
var userModule = require("/app/modules/business-controllers/user.js")["userModule"];

//noinspection JSUnresolvedFunction Server
var carbonServer = new carbonModule.server.Server({
    tenanted: true,
    url: devicemgtProps["httpsURL"] + "/admin"
});

application.put("carbonServer", carbonServer);

var permissions = {
    "/permission/admin/Login": ["ui.execute"],
    "/permission/admin/manage/api/subscribe": ["ui.execute"]
};

var adminPermissions = {
    "/permission/admin": ["ui.execute"]
};

//On Startup, admin user will get both roles: devicemgt-admin and devicemgt-user
//Average user through sign-up will only receive the role: devicemgt-user.
//Admin can setup necessary permissions for the role: devicemgt-user
userModule.addRole("internal/devicemgt-user", ["admin"], permissions);
userModule.addRole("internal/devicemgt-admin", ["admin"], adminPermissions);
<|endoftext|>


<commit_before>(function(g, Module) {

var _guid = 0;

function Base() {
	this.guid = ++_guid;
	this.options = {};
};

Base.unregister = function unregister(module) {
	if (!Module.manager) {
		return;
	}

	Module.manager.unregister(module);
};

Base.prototype = {

	document: null,

	element: null,

	guid: null,

	window: null,

	constructor: Base,

	init: function init(elementOrId, options) {
		if (elementOrId) {
			this.setElement(elementOrId);
		}

		if (options) {
			this.setOptions(options);
		}

		return this;
	},

	destructor: function destructor(keepElement) {
		Base.unregister(this);

		if (!keepElement && this.element && this.element.parentNode) {
			this.element.parentNode.removeChild(this.element);
		}

		this.element = this.options = this.document = this.window = null;
	},

	focus: function focus(anything) {
		var element,
			typeRegex = /checkbox|radio|submit|button|image|reset/,
		    selector = [
		    	"textarea",
		    	"select",
		    	"input[type=text]",
		    	"input[type=password]",
		    	"input[type=checkbox]",
		    	"input[type=radio]",
		    	"input[type=email]",
		    	"input[type=number]",
		    	"input[type=search]",
		    	"input[type=url]"
		    ];

		if (anything) {
			selector.push(
				"a",
				"button",
				"input[type=submit]",
				"input[type=button]",
				"input[type=image]",
				"input[type=reset]"
			);
		}

		element = this.element.querySelector(selector.join(", "));

		if (element && element.focus) {
			element.focus();

			if (element.select && !typeRegex.test(element.type)) {
				element.select();
			}
		}

		element = null;
	},

	_loading: function _loading(element) {
		(element || this.element).classList.add("loading");
		element = null;
	},

	_loaded: function _loaded(element) {
		(element || this.element).classList.remove("loading");
		element = null;
	},

	setElement: function setElement(elementOrId) {
		this.element = typeof elementOrId === "string"
		             ? document.getElementById(elementOrId)
		             : elementOrId;

		if (!this.element) {
			throw new Error("Could not find element: " + elementOrId);
		}

		this.document = this.element.ownerDocument;
		this.window = this.document.defaultView || this.document.parentWindow;
	},

	setOptions: function setOptions(overrides) {
		for (var key in overrides) {
			if (overrides.hasOwnProperty(key)) {
				this.options[key] = overrides[key];
			}
		}

		overrides = null;
	}

};

Module.Base = Base;

/*
Module.Base = Object.extend({

	prototype: {

		init: function init(elementOrId, options) {
			if (elementOrId) {
				this.setElement(elementOrId);
			}

			if (!this.hasOwnProperty("options")) {
				this.options = new Hash();
			}

			this._initOptions(this.options);

			if (options) {
				this.options.merge(options);
			}

			if (!this.delegator) {
				this.delegator = new dom.events.Delegator();
			}

			this.delegator.delegate = this;
			this.delegator.node = this.element;

			if (this.options.actionPrefix) {
				this.delegator.setActionPrefix(this.options.actionPrefix);
			}

			this.delegator.init();

			this._initActions();
			this._initCallbacks();
			this._initNotifications();
			this.initElementStore(this.element);
			this.callbacks.execute("beforeReady");
			this._ready();
			this.callbacks.execute("afterReady");

			if (this.options.defaultModule) {
				this.constructor.getManager().setDefaultModule(this);
			}

			return this;
		},

		destructor: function destructor(keepElement) {
			this.callbacks.execute("beforeDestroy");

			this.constructor.unregister(this);
			this.destroyElementStore();
			this.destroyCallbacks();

			if (this.delegator) {
				this.delegator.destructor();
			}

			if (!keepElement && this.element) {
				this.element.parentNode.removeChild(this.element);
			}

			if (this.options) {
				this.options.destructor();
			}

			this.actions = this.element = this.delegator = this.options = this.document = this.window = null;
		},

		cancel: function cancel(event, element, params) {
			event.stop();
			this.destructor();
			event = element = params = null;
		},

		_ready: function _ready() {

		},

		_initActions: function _initActions() {
			// TODO: Actions appear to be merging incorrectly here and making delegator double up on events
			var actions = new Hash(), proto = this.__proto__;

			while (proto) {
				if (proto.hasOwnProperty("actions")) {
					actions.safeMerge(proto.actions);
				}

				proto = proto.__proto__;
			}

			this.delegator.setEventActionMapping(actions);
		},

		_initCallbacks: function _initCallbacks() {
			var types = new Hash(), proto = this.__proto__;

			while (proto) {
				if (proto.hasOwnProperty("callbacks")) {
					types.safeMerge(proto.callbacks);
				}

				proto = proto.__proto__;
			}

			this.initCallbacks(types);
		},

		_initOptions: function _initOptions() {
			var proto = this.__proto__;

			while (proto) {
				if (proto.hasOwnProperty("options")) {
					this.options.safeMerge(proto.options);
				}

				proto = proto.__proto__;
			}
		},

	}

});
*/

// Make globally available
g.Module = Module;

})(this, this.Module || {});<commit_msg>Adding ability to set default module.<commit_after>(function(g, Module) {

var _guid = 0;

function Base() {
	this.guid = ++_guid;
	this.options = {};
};

Base.setDefaultModule = function setDefaultModule(module) {
	Module.manager.setDefaultModule(module);
};

Base.unregister = function unregister(module) {
	if (!Module.manager) {
		return;
	}

	Module.manager.unregister(module);
};

Base.prototype = {

	document: null,

	element: null,

	guid: null,

	window: null,

	constructor: Base,

	init: function init(elementOrId, options) {
		if (elementOrId) {
			this.setElement(elementOrId);
		}

		if (options) {
			this.setOptions(options);
		}

		if (this.options.defaultModule) {
			Base.setDefaultModule(this);
		}

		return this;
	},

	destructor: function destructor(keepElement) {
		Base.unregister(this);

		if (!keepElement && this.element && this.element.parentNode) {
			this.element.parentNode.removeChild(this.element);
		}

		this.element = this.options = this.document = this.window = null;
	},

	focus: function focus(anything) {
		var element,
			typeRegex = /checkbox|radio|submit|button|image|reset/,
		    selector = [
		    	"textarea",
		    	"select",
		    	"input[type=text]",
		    	"input[type=password]",
		    	"input[type=checkbox]",
		    	"input[type=radio]",
		    	"input[type=email]",
		    	"input[type=number]",
		    	"input[type=search]",
		    	"input[type=url]"
		    ];

		if (anything) {
			selector.push(
				"a",
				"button",
				"input[type=submit]",
				"input[type=button]",
				"input[type=image]",
				"input[type=reset]"
			);
		}

		element = this.element.querySelector(selector.join(", "));

		if (element && element.focus) {
			element.focus();

			if (element.select && !typeRegex.test(element.type)) {
				element.select();
			}
		}

		element = null;
	},

	_loading: function _loading(element) {
		(element || this.element).classList.add("loading");
		element = null;
	},

	_loaded: function _loaded(element) {
		(element || this.element).classList.remove("loading");
		element = null;
	},

	setElement: function setElement(elementOrId) {
		this.element = typeof elementOrId === "string"
		             ? document.getElementById(elementOrId)
		             : elementOrId;

		if (!this.element) {
			throw new Error("Could not find element: " + elementOrId);
		}

		this.document = this.element.ownerDocument;
		this.window = this.document.defaultView || this.document.parentWindow;
	},

	setOptions: function setOptions(overrides) {
		for (var key in overrides) {
			if (overrides.hasOwnProperty(key)) {
				this.options[key] = overrides[key];
			}
		}

		overrides = null;
	}

};

Module.Base = Base;

/*
Module.Base = Object.extend({

	prototype: {

		init: function init(elementOrId, options) {
			if (elementOrId) {
				this.setElement(elementOrId);
			}

			if (!this.hasOwnProperty("options")) {
				this.options = new Hash();
			}

			this._initOptions(this.options);

			if (options) {
				this.options.merge(options);
			}

			if (!this.delegator) {
				this.delegator = new dom.events.Delegator();
			}

			this.delegator.delegate = this;
			this.delegator.node = this.element;

			if (this.options.actionPrefix) {
				this.delegator.setActionPrefix(this.options.actionPrefix);
			}

			this.delegator.init();

			this._initActions();
			this._initCallbacks();
			this._initNotifications();
			this.initElementStore(this.element);
			this.callbacks.execute("beforeReady");
			this._ready();
			this.callbacks.execute("afterReady");

			if (this.options.defaultModule) {
				this.constructor.getManager().setDefaultModule(this);
			}

			return this;
		},

		destructor: function destructor(keepElement) {
			this.callbacks.execute("beforeDestroy");

			this.constructor.unregister(this);
			this.destroyElementStore();
			this.destroyCallbacks();

			if (this.delegator) {
				this.delegator.destructor();
			}

			if (!keepElement && this.element) {
				this.element.parentNode.removeChild(this.element);
			}

			if (this.options) {
				this.options.destructor();
			}

			this.actions = this.element = this.delegator = this.options = this.document = this.window = null;
		},

		cancel: function cancel(event, element, params) {
			event.stop();
			this.destructor();
			event = element = params = null;
		},

		_ready: function _ready() {

		},

		_initActions: function _initActions() {
			// TODO: Actions appear to be merging incorrectly here and making delegator double up on events
			var actions = new Hash(), proto = this.__proto__;

			while (proto) {
				if (proto.hasOwnProperty("actions")) {
					actions.safeMerge(proto.actions);
				}

				proto = proto.__proto__;
			}

			this.delegator.setEventActionMapping(actions);
		},

		_initCallbacks: function _initCallbacks() {
			var types = new Hash(), proto = this.__proto__;

			while (proto) {
				if (proto.hasOwnProperty("callbacks")) {
					types.safeMerge(proto.callbacks);
				}

				proto = proto.__proto__;
			}

			this.initCallbacks(types);
		},

		_initOptions: function _initOptions() {
			var proto = this.__proto__;

			while (proto) {
				if (proto.hasOwnProperty("options")) {
					this.options.safeMerge(proto.options);
				}

				proto = proto.__proto__;
			}
		},

	}

});
*/

// Make globally available
g.Module = Module;

})(this, this.Module || {});<|endoftext|>


<commit_before>require('dotenv').load()

var clone = require('clone');
var debug = require('debug')('pirate-talk:converse');
var merge = require('deepmerge');

module.exports = function (controller, middleware) {

  // Dialog history
  var dialogs = [];

  // Store the given feedback for the workspace
  function store_dialog(controller, feedback, workspace_id) {
    controller.storage.workspaces.get(workspace_id, function(err, workspace) {

      // Create a new one if none exists
      if (!workspace) {
        workspace = {
          id: workspace_id,
          feedbacks: []
        }
      }

      // Add the feedback to the workspace
      workspace.feedbacks.push(feedback);

      // Save the updated workspace
      console.log('Saving workspace: ' + workspace_id);
      controller.storage.workspaces.save(workspace, function(err, id) {
        if (err) {
          console.error('Error: could not workspace %s', id);
        }
      });
    });
  }

  // Main reply function, where all the logic to
  // interact with watson conversation is processed.
  function bot_reply(bot, msg) {
    console.log('Message: ' + JSON.stringify(msg));

    var has_attachments = false;
    if (msg.watsonData.output.action && msg.watsonData.output.action.attachments) {
      has_attachments = true;
      bot.reply(msg, {
        attachments: msg.watsonData.output.action.attachments
      });
    }

    // Contruct the replay message
    var reply = {
        text: msg.watsonData.output.text.join('\n'),
        attachments : []
    };

    // No feedback request if specifically removed
    var no_feedback_request = (msg.watsonData.output.action && msg.watsonData.output.action.no_feedback);

    // Request for a feedback, if this is not the first dialog round.
    if (!no_feedback_request) {

      // Reply with feedback request, that is, adding action buttons
      reply.attachments.push({
        unfurl_media: false,
        callback_id: msg.watsonData.context.conversation_id,
        mrkdwn_in: ['text'],
        text: '',
        actions: [{
          "name": "ok",
          "text": "Right :thumbsup:",
          "value": "good",
          "style": "primary",
          "type": "button"
        }, {
          "name": "soso",
          "text": "Improve :raised_hand:",
          "value": "maybe",
          "style": "default",
          "type": "button"
        }, {
          "name": "no",
          "text": "Wrong :thumbsdown:",
          "value": "bad",
          "style": "danger",
          "type": "button"
        }]
      });
    }

    // If we have attachments to process, wait
    // for 0.5 sec, before sending the next message.
    // Unfortunately, it doesn't seem there is a
    // more elegant way, in slack, to know whether
    // a message has been delivered and visible or not.
    // This is needed in order to avoid a message
    // to be received out of order, as it will happen
    // if some of the messages are heavir than others,
    // such as, when we have media files (images) attached.
    setTimeout(function() {
      console.log('Reply: ' + JSON.stringify(reply));
      bot.reply(msg, reply);

      // Add a dialog info to the list of dialogs. When the conversation restarts, the index
      // of dialog_turn_counter starts over again, hence, previous dialogs will be overwritten,
      //  and this will prevent the array to grow indefinitelly.
      dialogs.splice(msg.watsonData.context.system.dialog_turn_counter, 0, {
        user_input: msg.watsonData.input.text,
        bot_output: msg.watsonData.output.text,
        intents: msg.watsonData.intents,
        entities: msg.watsonData.entities,
        turn_id: msg.watsonData.context.system.dialog_turn_counter,
        conversation_id: msg.watsonData.context.conversation_id
      })

      //console.error('Dialogs: ' + JSON.stringify(dialogs))

    }, (has_attachments) ? 500 : 0 );
  }

  // Handle reset special case
  controller.hears(['reset'], ['direct_message', 'direct_mention', 'mention'], function (bot, message) {
    middleware.updateContext(message.user, {}, function (context) {
      const msg = clone(message);
      msg.text = 'reset';
      console.log('Context: ' + JSON.stringify(context));
      middleware.sendToWatson(bot, msg, function () {
        console.log('Reset: ' + JSON.stringify(msg));
        bot_reply(bot, msg);
      });
    });
  });

  // Handle common case through Watson conversation system
  controller.hears(['.*'], ['direct_message', 'direct_mention', 'mention'], function (bot, message) {
    middleware.interpret(bot, message, function () {
      if (message.watsonError) {
        console.error(message.watsonError);
        bot.reply(message, "I'm sorry, but for technical reasons I can't respond to your message");
      } else {
        console.log('Watson: ' + JSON.stringify(message.watsonData));
        bot_reply(bot, message);
      }
    });
  });

  // Receive an interactive message, and reply with a message that will replace the original
  controller.on('interactive_message_callback', function(bot, message) {
    console.log('Interactive: ' + JSON.stringify(message));

    // Since event handler aren't processed by middleware and have no watsonData attribute,
    // the context has to be extracted from the current user stored data.
    middleware.readContext(message.user, function(err, context) {
      if (!context) return;

      // check message.actions and message.callback_id to see what action to take...
      if (message && message.callback_id && message.callback_id == context.conversation_id) {

        // Get last stored dialog, if the dialog_turn and the conversation_id match,
        // then, add the feedback score to the object before we save it to storage.
        var current = dialogs.find(function(dialog, index){
          return (index == context.system.dialog_turn_counter)
            && (dialog.conversation_id == context.conversation_id);
        })

        // We also need the previous dialog, as we want to
        // extract what the bot has asked in the first place.
        // This is not a mandatory requirement though.
        var previous = dialogs.find(function(dialog, index){
          return (index == context.system.dialog_turn_counter - 1)
            && (dialog.conversation_id == context.conversation_id);
        })

        // Store given feedback for later revision
        if (current) {
          var feedback = merge(
            {
              action: message.text,
              bot_asked: (previous) ? previous.bot_output: ''
            },
            current
          );

          store_dialog(controller, feedback, process.env.WATSON_WORKSPACE_ID);
        }

        // Update the original message, that is,
        // the user will be notified its contribution
        // it has been taken into account.
        bot.replyInteractive(message, {
          text: message.original_message.text,
          attachments : [{
            fallback: '',
            footer: 'Thanks for the feedback :clap:',
            ts: message.action_ts
          }]
        });
      }
    });
  });

} <commit_msg>Some comment corrections<commit_after>require('dotenv').load()

var clone = require('clone');
var debug = require('debug')('pirate-talk:converse');
var merge = require('deepmerge');

module.exports = function (controller, middleware) {

  // Dialog history
  var dialogs = [];

  // Store the given feedback for the workspace
  function store_dialog(controller, feedback, workspace_id) {
    controller.storage.workspaces.get(workspace_id, function(err, workspace) {

      // Create a new one if none exists
      if (!workspace) {
        workspace = {
          id: workspace_id,
          feedbacks: []
        }
      }

      // Add the feedback to the workspace
      workspace.feedbacks.push(feedback);

      // Save the updated workspace
      console.log('Saving workspace: ' + workspace_id);
      controller.storage.workspaces.save(workspace, function(err, id) {
        if (err) {
          console.error('Error: could not workspace %s', id);
        }
      });
    });
  }

  // Main reply function, where all the logic to
  // interact with watson conversation is processed.
  function bot_reply(bot, msg) {
    console.log('Message: ' + JSON.stringify(msg));

    var has_attachments = false;
    if (msg.watsonData.output.action && msg.watsonData.output.action.attachments) {
      has_attachments = true;
      bot.reply(msg, {
        attachments: msg.watsonData.output.action.attachments
      });
    }

    // Construct the replay message
    var reply = {
        text: msg.watsonData.output.text.join('\n'),
        attachments : []
    };

    // No feedback request if specifically removed
    var no_feedback_request = (msg.watsonData.output.action && msg.watsonData.output.action.no_feedback);

    // Request for a feedback, if this is not the first dialog round.
    if (!no_feedback_request) {

      // Reply with feedback request, that is, adding action buttons
      reply.attachments.push({
        unfurl_media: false,
        callback_id: msg.watsonData.context.conversation_id,
        mrkdwn_in: ['text'],
        text: '',
        actions: [{
          "name": "ok",
          "text": "Right :thumbsup:",
          "value": "good",
          "style": "primary",
          "type": "button"
        }, {
          "name": "soso",
          "text": "Improve :raised_hand:",
          "value": "maybe",
          "style": "default",
          "type": "button"
        }, {
          "name": "no",
          "text": "Wrong :thumbsdown:",
          "value": "bad",
          "style": "danger",
          "type": "button"
        }]
      });
    }

    // If we have attachments to process, wait
    // for 0.5 sec, before sending the next message.
    // Unfortunately, it doesn't seem there is a
    // more elegant way, in slack, to know whether
    // a message has been delivered and visible or not.
    // This is needed in order to avoid a message
    // to be received out of order, as it will happen
    // if some of the messages are heavier than others,
    // such as, when we have media files (images) attached.
    setTimeout(function() {
      console.log('Reply: ' + JSON.stringify(reply));
      bot.reply(msg, reply);

      // Add a dialog info to the list of dialogs. When the conversation restarts, the index
      // of dialog_turn_counter starts over again, hence, previous dialogs will be overwritten,
      //  and this will prevent the array to grow indefinitely.
      dialogs.splice(msg.watsonData.context.system.dialog_turn_counter, 0, {
        user_input: msg.watsonData.input.text,
        bot_output: msg.watsonData.output.text,
        intents: msg.watsonData.intents,
        entities: msg.watsonData.entities,
        turn_id: msg.watsonData.context.system.dialog_turn_counter,
        conversation_id: msg.watsonData.context.conversation_id
      })

      //console.error('Dialogs: ' + JSON.stringify(dialogs))

    }, (has_attachments) ? 500 : 0 );
  }

  // Handle reset special case
  controller.hears(['reset'], ['direct_message', 'direct_mention', 'mention'], function (bot, message) {
    middleware.updateContext(message.user, {}, function (context) {
      const msg = clone(message);
      msg.text = 'reset';
      console.log('Context: ' + JSON.stringify(context));
      middleware.sendToWatson(bot, msg, function () {
        console.log('Reset: ' + JSON.stringify(msg));
        bot_reply(bot, msg);
      });
    });
  });

  // Handle common case through Watson conversation system
  controller.hears(['.*'], ['direct_message', 'direct_mention', 'mention'], function (bot, message) {
    middleware.interpret(bot, message, function () {
      if (message.watsonError) {
        console.error(message.watsonError);
        bot.reply(message, "I'm sorry, but for technical reasons I can't respond to your message");
      } else {
        console.log('Watson: ' + JSON.stringify(message.watsonData));
        bot_reply(bot, message);
      }
    });
  });

  // Receive an interactive message, and reply with a message that will replace the original
  controller.on('interactive_message_callback', function(bot, message) {
    console.log('Interactive: ' + JSON.stringify(message));

    // Since event handler aren't processed by middleware and have no watsonData attribute,
    // the context has to be extracted from the current user stored data.
    middleware.readContext(message.user, function(err, context) {
      if (!context) return;

      // check message.actions and message.callback_id to see what action to take...
      if (message && message.callback_id && message.callback_id == context.conversation_id) {

        // Get last stored dialog, if the dialog_turn and the conversation_id match,
        // then, add the feedback score to the object before we save it to storage.
        var current = dialogs.find(function(dialog, index){
          return (index == context.system.dialog_turn_counter)
            && (dialog.conversation_id == context.conversation_id);
        })

        // We also need the previous dialog, as we want to
        // extract what the bot has asked in the first place.
        // This is not a mandatory requirement though.
        var previous = dialogs.find(function(dialog, index){
          return (index == context.system.dialog_turn_counter - 1)
            && (dialog.conversation_id == context.conversation_id);
        })

        // Store given feedback for later revision
        if (current) {
          var feedback = merge(
            {
              action: message.text,
              bot_asked: (previous) ? previous.bot_output: ''
            },
            current
          );

          store_dialog(controller, feedback, process.env.WATSON_WORKSPACE_ID);
        }

        // Update the original message, that is,
        // the user will be notified its contribution
        // it has been taken into account.
        bot.replyInteractive(message, {
          text: message.original_message.text,
          attachments : [{
            fallback: '',
            footer: 'Thanks for the feedback :clap:',
            ts: message.action_ts
          }]
        });
      }
    });
  });

} <|endoftext|>


<commit_before>/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @flow
 * @providesModule getIdentifierForSelection
 * @format
 */

'use strict';

const invariant = require('invariant');
const stableJSONStringify = require('../util/stableJSONStringifyOSS');

import type {Selection} from './GraphQLIR';

/**
 * Generates an identifier that is unique to a given selection: the alias for
 * fields, the type for inline fragments, and a summary of the condition
 * variable and passing value for conditions.
 */
function getIdentifierForSelection(node: Selection): string {
  let obj;
  switch (node.kind) {
    case 'LinkedField':
    case 'ScalarField':
      obj = {
        directives: node.directives,
        field: node.alias || node.name,
      };
      break;
    case 'InlineFragment':
      obj = {
        inlineFragment: node.typeCondition.toString(),
      };
      break;
    case 'Condition':
      obj = {
        condition: node.condition,
        passingValue: node.passingValue,
      };
      break;
    case 'FragmentSpread':
      obj = {
        fragmentSpread: node.name,
        args: node.args,
      };
      break;
    default:
      invariant(
        false,
        'RelayFlattenTransform: Unexpected kind `%s`.',
        node.kind,
      );
  }
  return stableJSONStringify(obj);
}

module.exports = getIdentifierForSelection;
<commit_msg>Fix a misleading string in an invariant message<commit_after>/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @flow
 * @providesModule getIdentifierForSelection
 * @format
 */

'use strict';

const invariant = require('invariant');
const stableJSONStringify = require('../util/stableJSONStringifyOSS');

import type {Selection} from './GraphQLIR';

/**
 * Generates an identifier that is unique to a given selection: the alias for
 * fields, the type for inline fragments, and a summary of the condition
 * variable and passing value for conditions.
 */
function getIdentifierForSelection(node: Selection): string {
  let obj;
  switch (node.kind) {
    case 'LinkedField':
    case 'ScalarField':
      obj = {
        directives: node.directives,
        field: node.alias || node.name,
      };
      break;
    case 'InlineFragment':
      obj = {
        inlineFragment: node.typeCondition.toString(),
      };
      break;
    case 'Condition':
      obj = {
        condition: node.condition,
        passingValue: node.passingValue,
      };
      break;
    case 'FragmentSpread':
      obj = {
        fragmentSpread: node.name,
        args: node.args,
      };
      break;
    default:
      invariant(
        false,
        'getIdentifierForSelection: Unexpected kind `%s`.',
        node.kind,
      );
  }
  return stableJSONStringify(obj);
}

module.exports = getIdentifierForSelection;
<|endoftext|>


<commit_before>"use strict";
var platform_browser_dynamic_1 = require('@angular/platform-browser-dynamic');
var app_component_1 = require('./components/app.component');
platform_browser_dynamic_1.bootstrap(app_component_1.AppComponent);
//# sourceMappingURL=main.js.map<commit_msg>Cleaning up the tsc generated js files.<commit_after><|endoftext|>


<commit_before>var _          = require('_'),
    overload   = require('overload'),
    O          = overload.O,

    _SUPPORTS  = require('../supports'),
    _NODE_TYPE = require('../nodeType'),

    _utils     = require('../utils'),
    _div       = require('../div');

var _outerHtml = function() {
    return this.length ? this[0].outerHTML : null;
};

var _text = {
    get: (_div.textContent !== undefined) ?
        function(elem) { return elem.textContent; } :
            function(elem) { return elem.innerText; } ,
    set: (_div.textContent !== undefined) ?
        function(elem, str) { elem.textContent = str; } :
            function(elem, str) { elem.innerText = str; }
};

var _valHooks = {
    option: {
        get: function(elem) {
            var val = elem.getAttribute('value');
            return _.exists(val) ? val : _text.get(elem);
        }
    },

    select: {
        get: function(elem) {
            var value, option,
                options = elem.options,
                index   = elem.selectedIndex,
                one     = elem.type === 'select-one' || index < 0,
                values  = one ? null : [],
                max     = one ? index + 1 : options.length,
                idx     = index < 0 ? max : (one ? index : 0);

            // Loop through all the selected options
            for (; idx < max; idx++) {
                option = options[idx];

                // oldIE doesn't update selected after form reset (#2551)
                if ((option.selected || idx === index) &&
                        // Don't return options that are disabled or in a disabled optgroup
                        (_SUPPORTS.optDisabled ? !option.disabled : option.getAttribute('disabled') === null) &&
                        (!option.parentNode.disabled || !_utils.isNodeName(option.parentNode, 'optgroup'))) {

                    // Get the specific value for the option
                    value = _valHooks.option.get(option);

                    // We don't need an array for one selects
                    if (one) {
                        return value;
                    }

                    // Multi-Selects return an array
                    values.push(value);
                }
            }

            return values;
        },

        set: function(elem, value) {
            var optionSet, option,
                options = elem.options,
                values  = jQuery.makeArray(value),
                idx     = options.length;

            while (idx--) {
                option = options[idx];

                if (jQuery.inArray(jQuery.valHooks.option.get(option), values) >= 0) {
                    option.selected = optionSet = true;
                } else {
                    option.selected = false;
                }
            }

            // Force browsers to behave consistently when non-matching value is set
            if (!optionSet) {
                elem.selectedIndex = -1;
            }
        }
    }

};

// Radios and checkboxes getter/setter
_.each(['radio', 'checkbox'], function(type) {
    _valHooks[type] = {
        set: function(elem, value) {
            if (_.isArray(value)) {
                return (elem.checked = jQuery.inArray(jQuery(elem).val(), value) >= 0);
            }
        }
    };

    if (!_SUPPORTS.checkOn) {
        _valHooks[type].get = function(elem) {
            // Support: Webkit - '' is returned instead of 'on' if a value isn't specified
            return elem.getAttribute('value') === null ? 'on' : elem.value;
        };
    }
});

var _getVal = function(elem) {
    if (!elem || (elem.nodeType !== _NODE_TYPE.ELEMENT)) { return; }

    var hook = _valHooks[elem.type] || _valHooks[_utils.normalNodeName(elem)];
    if (hook && hook.get) {
        return hook.get(elem);
    }

    var val = elem.value;
    if (val === undefined) {
        val = elem.getAttribute('value');
    }

    return _.isString(val) ? _utils.normalizeNewlines(val) : val;
};

var _setVal = function(elem, value) {
    if (elem.nodeType !== _NODE_TYPE.ELEMENT) { return; }

    var hook = _valHooks[elem.type] || _valHooks[_utils.normalNodeName(elem)];
    if (hook && hook.set) {
        hook.set(elem, value);
    } else {
        elem.setAttribute('value', value);
    }
};

module.exports = {
    fn: {
        // TODO: Overload and determine api
        // TODO: unit tests
        outerHtml: _outerHtml,
        outerHTML: _outerHtml,

        html: overload()
            .args(String)
            .use(function(html) {
                return _.each(this, function(elem) {
                    elem.innerHTML = html;
                });
            })

            .args(Function)
            .use(function(iterator) {
                return _.each(this, function(elem, idx) {
                    elem.innerHTML = iterator.call(elem, idx, elem.innerHTML);
                });
            })

            .fallback(function() {
                var first = this[0];
                return (!first) ? undefined : first.innerHTML;
            })
            .expose(),

        // TODO: Add handling of (and unit tests for) \r\n in IE
        val: overload()
            // Getter
            .args()
            .use(function() {
                // TODO: Select first element node instead of index 0?
                return _getVal(this[0]);
            })

            // Setters
            .args(O.any(String, Number))
            .use(function(value) {
                value = '' + value;
                return _.each(this, function(elem) {
                    _setVal(elem, value);
                });
            })

            .args(O.any(null, undefined))
            .use(function() {
                return _.each(this, function(elem) {
                    _setVal(elem, '');
                });
            })

            .args(Function)
            .use(function(iterator) {
                return _.each(this, function(elem, idx) {
                    if (elem.nodeType !== _NODE_TYPE.ELEMENT) { return; }

                    var value = iterator.call(elem, idx, _getVal(elem));
                    var hook = _valHooks[elem.type] || _valHooks[_utils.normalNodeName(elem)];

                    if (hook && hook.set) {
                        hook.set(elem, value);
                    } else {
                        elem.setAttribute('value', value);
                    }
                });
            })

            .args(Array)
            .use(function(arr) {
                var d = this,
                    len = this.length;
                _.each(arr, function(val, idx) {
                    if (idx >= len) { return false; }
                    _setVal(d[idx], '' + val);
                });
                return this;
            })

            .fallback(function(value) {
                value = '' + value;
                return _.each(this, function(elem) {
                    _setVal(elem, value);
                });
            })

            .expose(),

        text: overload()
            .args(String)
            .use(function(str) {
                return _.each(this, function(elem) {
                    _text.set(elem, str);
                });
            })

            .args(Function)
            .use(function(iterator) {
                return _.each(this, function(elem, idx) {
                    _text.set(elem, iterator.call(elem, idx, _text.get(elem)));
                });
            })

            .fallback(function() {
                var str = '';
                _.each(this, function(elem) {
                    str += _text.get(elem);
                });

                return str;
            })
            .expose()
    }
};
<commit_msg>Use underscore methods instead of jQuery helpers<commit_after>var _          = require('_'),
    overload   = require('overload'),
    O          = overload.O,

    _SUPPORTS  = require('../supports'),
    _NODE_TYPE = require('../nodeType'),

    _utils     = require('../utils'),
    _div       = require('../div');

var _outerHtml = function() {
    return this.length ? this[0].outerHTML : null;
};

var _text = {
    get: (_div.textContent !== undefined) ?
        function(elem) { return elem.textContent; } :
            function(elem) { return elem.innerText; } ,
    set: (_div.textContent !== undefined) ?
        function(elem, str) { elem.textContent = str; } :
            function(elem, str) { elem.innerText = str; }
};

var _valHooks = {
    option: {
        get: function(elem) {
            var val = elem.getAttribute('value');
            return _.exists(val) ? val : _text.get(elem);
        }
    },

    select: {
        get: function(elem) {
            var value, option,
                options = elem.options,
                index   = elem.selectedIndex,
                one     = elem.type === 'select-one' || index < 0,
                values  = one ? null : [],
                max     = one ? index + 1 : options.length,
                idx     = index < 0 ? max : (one ? index : 0);

            // Loop through all the selected options
            for (; idx < max; idx++) {
                option = options[idx];

                // oldIE doesn't update selected after form reset (#2551)
                if ((option.selected || idx === index) &&
                        // Don't return options that are disabled or in a disabled optgroup
                        (_SUPPORTS.optDisabled ? !option.disabled : option.getAttribute('disabled') === null) &&
                        (!option.parentNode.disabled || !_utils.isNodeName(option.parentNode, 'optgroup'))) {

                    // Get the specific value for the option
                    value = _valHooks.option.get(option);

                    // We don't need an array for one selects
                    if (one) {
                        return value;
                    }

                    // Multi-Selects return an array
                    values.push(value);
                }
            }

            return values;
        },

        set: function(elem, value) {
            var optionSet, option,
                options = elem.options,
                values  = _.makeArray(value),
                idx     = options.length;

            while (idx--) {
                option = options[idx];

                if (_.indexOf(values, _valHooks.option.get(option)) >= 0) {
                    option.selected = optionSet = true;
                } else {
                    option.selected = false;
                }
            }

            // Force browsers to behave consistently when non-matching value is set
            if (!optionSet) {
                elem.selectedIndex = -1;
            }
        }
    }

};

// Radios and checkboxes getter/setter
_.each(['radio', 'checkbox'], function(type) {
    _valHooks[type] = {
        set: function(elem, value) {
            if (_.isArray(value)) {
                return (elem.checked = _.indexOf(value, _getVal(elem)) >= 0);
            }
        }
    };

    if (!_SUPPORTS.checkOn) {
        _valHooks[type].get = function(elem) {
            // Support: Webkit - '' is returned instead of 'on' if a value isn't specified
            return elem.getAttribute('value') === null ? 'on' : elem.value;
        };
    }
});

var _getVal = function(elem) {
    if (!elem || (elem.nodeType !== _NODE_TYPE.ELEMENT)) { return; }

    var hook = _valHooks[elem.type] || _valHooks[_utils.normalNodeName(elem)];
    if (hook && hook.get) {
        return hook.get(elem);
    }

    var val = elem.value;
    if (val === undefined) {
        val = elem.getAttribute('value');
    }

    return _.isString(val) ? _utils.normalizeNewlines(val) : val;
};

var _setVal = function(elem, value) {
    if (elem.nodeType !== _NODE_TYPE.ELEMENT) { return; }

    var hook = _valHooks[elem.type] || _valHooks[_utils.normalNodeName(elem)];
    if (hook && hook.set) {
        hook.set(elem, value);
    } else {
        elem.setAttribute('value', value);
    }
};

module.exports = {
    fn: {
        // TODO: Overload and determine api
        // TODO: unit tests
        outerHtml: _outerHtml,
        outerHTML: _outerHtml,

        html: overload()
            .args(String)
            .use(function(html) {
                return _.each(this, function(elem) {
                    elem.innerHTML = html;
                });
            })

            .args(Function)
            .use(function(iterator) {
                return _.each(this, function(elem, idx) {
                    elem.innerHTML = iterator.call(elem, idx, elem.innerHTML);
                });
            })

            .fallback(function() {
                var first = this[0];
                return (!first) ? undefined : first.innerHTML;
            })
            .expose(),

        // TODO: Add handling of (and unit tests for) \r\n in IE
        val: overload()
            // Getter
            .args()
            .use(function() {
                // TODO: Select first element node instead of index 0?
                return _getVal(this[0]);
            })

            // Setters
            .args(O.any(String, Number))
            .use(function(value) {
                value = '' + value;
                return _.each(this, function(elem) {
                    _setVal(elem, value);
                });
            })

            .args(O.any(null, undefined))
            .use(function() {
                return _.each(this, function(elem) {
                    _setVal(elem, '');
                });
            })

            .args(Function)
            .use(function(iterator) {
                return _.each(this, function(elem, idx) {
                    if (elem.nodeType !== _NODE_TYPE.ELEMENT) { return; }

                    var value = iterator.call(elem, idx, _getVal(elem));
                    var hook = _valHooks[elem.type] || _valHooks[_utils.normalNodeName(elem)];

                    if (hook && hook.set) {
                        hook.set(elem, value);
                    } else {
                        elem.setAttribute('value', value);
                    }
                });
            })

            .args(Array)
            .use(function(arr) {
                var d = this,
                    len = this.length;
                _.each(arr, function(val, idx) {
                    if (idx >= len) { return false; }
                    _setVal(d[idx], '' + val);
                });
                return this;
            })

            .fallback(function(value) {
                value = '' + value;
                return _.each(this, function(elem) {
                    _setVal(elem, value);
                });
            })

            .expose(),

        text: overload()
            .args(String)
            .use(function(str) {
                return _.each(this, function(elem) {
                    _text.set(elem, str);
                });
            })

            .args(Function)
            .use(function(iterator) {
                return _.each(this, function(elem, idx) {
                    _text.set(elem, iterator.call(elem, idx, _text.get(elem)));
                });
            })

            .fallback(function() {
                var str = '';
                _.each(this, function(elem) {
                    str += _text.get(elem);
                });

                return str;
            })
            .expose()
    }
};
<|endoftext|>


<commit_before>var path = require('path');
var fs = require('fs');
var nodeExternals = require('webpack-node-externals');
var Components = require('../components.json');
var saladConfig = require('../packages/theme-default/salad.config.json');

var utilsList = fs.readdirSync(path.resolve(__dirname, '../src/utils'));
var mixinsList = fs.readdirSync(path.resolve(__dirname, '../src/mixins'));
var transitionList = fs.readdirSync(path.resolve(__dirname, '../src/transitions'));
var externals = {};

Object.keys(Components).forEach(function(key) {
  externals[`element-ui/packages/${key}`] = `element-ui/lib/${key}`;
});

externals['element-ui/src/locale'] = 'element-ui/lib/locale';
utilsList.forEach(function(file) {
  file = path.basename(file, '.js');
  externals[`element-ui/src/utils/${file}`] = `element-ui/lib/utils/${file}`;
});
mixinsList.forEach(function(file) {
  file = path.basename(file, '.js');
  externals[`element-ui/src/mixins/${file}`] = `element-ui/lib/mixins/${file}`;
});
transitionList.forEach(function(file) {
  file = path.basename(file, '.js');
  externals[`element-ui/src/transitions/${file}`] = `element-ui/lib/transitions/${file}`;
});

externals = [Object.assign({
  vue: 'vue'
}, externals), nodeExternals()];

exports.externals = externals;

exports.alias = {
  main: path.resolve(__dirname, '../src'),
  packages: path.resolve(__dirname, '../packages'),
  examples: path.resolve(__dirname, '../examples'),
  'element-ui': path.resolve(__dirname, '../')
};

exports.vue = {
  root: 'Vue',
  commonjs: 'vue',
  commonjs2: 'vue',
  amd: 'vue'
};

exports.jsexclude = /node_modules|utils\/popper\.js|utils\/date.\js/;

exports.postcss = function(webapck) {
  saladConfig.features.partialImport = {
    addDependencyTo: webapck
  };
  return [
    require('postcss-salad')(saladConfig)
  ];
};
<commit_msg>fix build<commit_after>var path = require('path');
var fs = require('fs');
var nodeExternals = require('webpack-node-externals');
var Components = require('../components.json');
var saladConfig = require('../packages/theme-default/salad.config.json');

var utilsList = fs.readdirSync(path.resolve(__dirname, '../src/utils'));
var mixinsList = fs.readdirSync(path.resolve(__dirname, '../src/mixins'));
var transitionList = fs.readdirSync(path.resolve(__dirname, '../src/transitions'));
var externals = {};

Object.keys(Components).forEach(function(key) {
  console.log(1111111, key)
  externals[`nb-element/packages/${key}`] = `element-ui/lib/${key}`;
});

externals['nb-element/src/locale'] = 'element-ui/lib/locale';
utilsList.forEach(function(file) {
  file = path.basename(file, '.js');
  externals[`nb-element/src/utils/${file}`] = `element-ui/lib/utils/${file}`;
});
mixinsList.forEach(function(file) {
  file = path.basename(file, '.js');
  externals[`nb-element/src/mixins/${file}`] = `element-ui/lib/mixins/${file}`;
});
transitionList.forEach(function(file) {
  file = path.basename(file, '.js');
  externals[`nb-element/src/transitions/${file}`] = `element-ui/lib/transitions/${file}`;
});

externals = [Object.assign({
  vue: 'vue'
}, externals), nodeExternals()];

exports.externals = externals;

exports.alias = {
  main: path.resolve(__dirname, '../src'),
  packages: path.resolve(__dirname, '../packages'),
  examples: path.resolve(__dirname, '../examples'),
  'element-ui': path.resolve(__dirname, '../')
};

exports.vue = {
  root: 'Vue',
  commonjs: 'vue',
  commonjs2: 'vue',
  amd: 'vue'
};

exports.jsexclude = /node_modules|utils\/popper\.js|utils\/date.\js/;

exports.postcss = function(webapck) {
  saladConfig.features.partialImport = {
    addDependencyTo: webapck
  };
  return [
    require('postcss-salad')(saladConfig)
  ];
};
<|endoftext|>


<commit_before>var path = require('path')
var packageConf = require('../package.json')

module.exports = {
  build: {
    env: {
      NODE_ENV: '"production"'
    },
    index: path.resolve(__dirname, '../dist/index.html'),
    assetsRoot: path.resolve(__dirname, '../dist'),
    assetsSubDirectory: 'static',
    assetsPublicPath: '/' + packageConf.name + '/',
    productionSourceMap: true,
    // Gzip off by default as many popular static hosts such as
    // Surge or Netlify already gzip all static assets for you.
    // Before setting to `true`, make sure to:
    // npm install --save-dev compression-webpack-plugin
    productionGzip: false,
    productionGzipExtensions: ['js', 'css'],
    // multi pages
    basePath: '/vue-destop/views',
    targetRoot: path.resolve(__dirname, '../../test/webapp'),
    autoDeploy: false,
    pagesDir: 'views',
    pagesSubDir: '',
    pageExt: 'html'
  },
  dev: {
    env: {
      NODE_ENV: '"development"'
    },
    port: 8888,
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    proxyTable: {
      // proxy all requests starting with /api to rap
      '/api': {
        target: 'http://172.16.1.63:8018/mockjsdata/12',
        changeOrigin: true,
        pathRewrite: {
          '^/api': ''
        }
      }
    },
    // CSS Sourcemaps off by default because relative paths are "buggy"
    // with this option, according to the CSS-Loader README
    // (https://github.com/webpack/css-loader#sourcemaps)
    // In our experience, they generally work as expected,
    // just be aware of this issue when enabling this option.
    cssSourceMap: false,
    // multi pages
    // basePath: '/\<%=basePath %\>',
    basePath: '',
    pagesDir: '',
    pageExt: 'html'

  }
}
<commit_msg>Revert "update basepath"<commit_after>var path = require('path')
var packageConf = require('../package.json')

module.exports = {
  build: {
    env: {
      NODE_ENV: '"production"'
    },
    index: path.resolve(__dirname, '../dist/index.html'),
    assetsRoot: path.resolve(__dirname, '../dist'),
    assetsSubDirectory: 'static',
    assetsPublicPath: '/' + packageConf.name + '/',
    productionSourceMap: true,
    // Gzip off by default as many popular static hosts such as
    // Surge or Netlify already gzip all static assets for you.
    // Before setting to `true`, make sure to:
    // npm install --save-dev compression-webpack-plugin
    productionGzip: false,
    productionGzipExtensions: ['js', 'css'],
    // multi pages
    basePath: '/vue-destop',
    targetRoot: path.resolve(__dirname, '../../test/webapp'),
    autoDeploy: false,
    pagesDir: 'views',
    pagesSubDir: '',
    pageExt: 'html'
  },
  dev: {
    env: {
      NODE_ENV: '"development"'
    },
    port: 8888,
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    proxyTable: {
      // proxy all requests starting with /api to rap
      '/api': {
        target: 'http://172.16.1.63:8018/mockjsdata/12',
        changeOrigin: true,
        pathRewrite: {
          '^/api': ''
        }
      }
    },
    // CSS Sourcemaps off by default because relative paths are "buggy"
    // with this option, according to the CSS-Loader README
    // (https://github.com/webpack/css-loader#sourcemaps)
    // In our experience, they generally work as expected,
    // just be aware of this issue when enabling this option.
    cssSourceMap: false,
    // multi pages
    // basePath: '/\<%=basePath %\>',
    basePath: '',
    pagesDir: '',
    pageExt: 'html'

  }
}
<|endoftext|>