<commit_before>var JSIQ = function(){

    this.from = function(list){
        return new JSIQ.Query(list);
    }

    var OrderEnum = function(value){
        this.value = value;
    }

    this.Order = {
        "ascending" : new OrderEnum("ascending"),
        "descending" : new OrderEnum("descending"),
        "equals" : function(o1, o2) {
                       return o1.value === o2.value;
                   }
    }

    this.Query = function(list){
        if(typeof(list) !== typeof([])) throw "Not array";

        var result = list;

        this.all = function(){
            return result;
        }

        this.where = function(predicate){
            if(typeof(predicate) !== typeof(Function)) return null;
            if(Array.prototype.filter !== undefined){
                result = result.filter(predicate);
                return this;
            }
            var tempResult = [];
            for(var index in result){
                var item = result[index];
                if(predicate(item))
                    tempResult.push(item);
            }
            result = tempResult;

            return this;
        }

        this.select = function(selector){
            if(typeof(selector) !== typeof(Function)) return null;
            var tempResult = [];
            for(var index in result){
                tempResult.push(selector(result[index]));
            }
            result = tempResult;
            return this;
        }

        var defaultComparer = function(e1, e2){
            return e1 - e2;
        }

        this.orderBy = function(keySelector, order, comparer){
            if(typeof(keySelector) !== typeof(Function)) return null;

            if(order === undefined)
                order = JSIQ.Order.ascending;
            if(!order instanceof OrderEnum) return null;

            if(comparer === undefined)
                comparer = defaultComparer;
            if(typeof(comparer) !== typeof(Function)) return null;

            var index;
            var tempOrder = [];
            for(index in result)
                tempOrder.push({"element":keySelector(result[index]),"index":index});
            tempOrder = tempOrder.sort(function(e1, e2){
                if(JSIQ.Order.equals(order, JSIQ.Order.ascending))
                    return comparer(e1.element, e2.element);
                if(JSIQ.Order.equals(order, JSIQ.Order.descending))
                    return -comparer(e1.element, e2.element);
            });
            var tempResult = [];
            for(index in tempOrder)
                tempResult.push(result[tempOrder[index].index]);
            result = tempResult;
            return this;
        }
    }

    this.query = function(query){

    }

};
JSIQ = new JSIQ();
<commit_msg>changed the way to create single instance<commit_after>(function(){

    this.jsiq = {};

    var root = this.jsiq;

    root.from = function(list){
        return new Query(list);
    }

    var Order = function(value){
        this.value = value;
    }

    root.ascending = new Order("ascending");
    root.descending = new Order("descending");

    var Query = function(list){
        if(typeof(list) !== typeof([])) throw "Not array";

        var result = list;

        this.all = function(){
            return result;
        }

        this.where = function(predicate){
            if(typeof(predicate) !== typeof(Function)) return null;
            if(Array.prototype.filter !== undefined){
                result = result.filter(predicate);
                return this;
            }
            var tempResult = [];
            for(var index in result){
                var item = result[index];
                if(predicate(item))
                    tempResult.push(item);
            }
            result = tempResult;

            return this;
        }

        this.select = function(selector){
            if(typeof(selector) !== typeof(Function)) return null;
            var tempResult = [];
            for(var index in result){
                tempResult.push(selector(result[index]));
            }
            result = tempResult;
            return this;
        }

        var defaultComparer = function(e1, e2){
            return e1 - e2;
        }

        this.orderBy = function(keySelector, order, comparer){
            if(typeof(keySelector) !== typeof(Function)) return null;

            if(order === undefined)
                order = root.ascending;
            if(!order instanceof Order) return null;

            if(comparer === undefined)
                comparer = defaultComparer;
            if(typeof(comparer) !== typeof(Function)) return null;

            var index;
            var tempOrder = [];
            for(index in result)
                tempOrder.push({"element":keySelector(result[index]),"index":index});
            tempOrder = tempOrder.sort(function(e1, e2){
                if(order.value === root.ascending.value)
                    return comparer(e1.element, e2.element);
                if(order.value, root.descending.value)
                    return -comparer(e1.element, e2.element);
            });
            var tempResult = [];
            for(index in tempOrder)
                tempResult.push(result[tempOrder[index].index]);
            result = tempResult;
            return this;
        }
    }

    jsiq.query = function(query){

    }

}).call(this);
<|endoftext|>


<commit_before>'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.InstallationsRouter = undefined;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };

var _ClassesRouter2 = require('./ClassesRouter');

var _ClassesRouter3 = _interopRequireDefault(_ClassesRouter2);

var _PromiseRouter = require('../PromiseRouter');

var _PromiseRouter2 = _interopRequireDefault(_PromiseRouter);

var _rest = require('../rest');

var _rest2 = _interopRequireDefault(_rest);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } // InstallationsRouter.js

var InstallationsRouter = exports.InstallationsRouter = function (_ClassesRouter) {
  _inherits(InstallationsRouter, _ClassesRouter);

  function InstallationsRouter() {
    _classCallCheck(this, InstallationsRouter);

    return _possibleConstructorReturn(this, Object.getPrototypeOf(InstallationsRouter).apply(this, arguments));
  }

  _createClass(InstallationsRouter, [{
    key: 'handleFind',
    value: function handleFind(req) {
      var options = {};
      if (req.body.skip) {
        options.skip = Number(req.body.skip);
      }
      if (req.body.limit) {
        options.limit = Number(req.body.limit);
      }
      if (req.body.order) {
        options.order = String(req.body.order);
      }
      if (req.body.count) {
        options.count = true;
      }
      if (req.body.include) {
        options.include = String(req.body.include);
      }

      return _rest2.default.find(req.config, req.auth, '_Installation', req.body.where, options).then(function (response) {
        return { response: response };
      });
    }
  }, {
    key: 'handleGet',
    value: function handleGet(req) {
      req.params.className = '_Installation';
      return _get(Object.getPrototypeOf(InstallationsRouter.prototype), 'handleGet', this).call(this, req);
    }
  }, {
    key: 'handleCreate',
    value: function handleCreate(req) {
      req.params.className = '_Installation';
      return _get(Object.getPrototypeOf(InstallationsRouter.prototype), 'handleCreate', this).call(this, req);
    }
  }, {
    key: 'handleUpdate',
    value: function handleUpdate(req) {
      req.params.className = '_Installation';
      return _get(Object.getPrototypeOf(InstallationsRouter.prototype), 'handleUpdate', this).call(this, req);
    }
  }, {
    key: 'handleDelete',
    value: function handleDelete(req) {
      req.params.className = '_Installation';
      return _get(Object.getPrototypeOf(InstallationsRouter.prototype), 'handleDelete', this).call(this, req);
    }
  }, {
    key: 'mountRoutes',
    value: function mountRoutes() {
      var _this2 = this;

      this.route('GET', '/installations', function (req) {
        return _this2.handleFind(req);
      });
      this.route('GET', '/installations/:objectId', function (req) {
        return _this2.handleGet(req);
      });
      this.route('POST', '/installations', function (req) {
        return _this2.handleCreate(req);
      });
      this.route('PUT', '/installations/:objectId', function (req) {
        return _this2.handleUpdate(req);
      });
      this.route('DELETE', '/installations/:objectId', function (req) {
        return _this2.handleDelete(req);
      });
    }
  }]);

  return InstallationsRouter;
}(_ClassesRouter3.default);

exports.default = InstallationsRouter;<commit_msg>debug installations query<commit_after>'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.InstallationsRouter = undefined;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };

var _ClassesRouter2 = require('./ClassesRouter');

var _ClassesRouter3 = _interopRequireDefault(_ClassesRouter2);

var _PromiseRouter = require('../PromiseRouter');

var _PromiseRouter2 = _interopRequireDefault(_PromiseRouter);

var _rest = require('../rest');

var _rest2 = _interopRequireDefault(_rest);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } // InstallationsRouter.js

var InstallationsRouter = exports.InstallationsRouter = function (_ClassesRouter) {
  _inherits(InstallationsRouter, _ClassesRouter);

  function InstallationsRouter() {
    _classCallCheck(this, InstallationsRouter);

    return _possibleConstructorReturn(this, Object.getPrototypeOf(InstallationsRouter).apply(this, arguments));
  }

  _createClass(InstallationsRouter, [{
    key: 'handleFind',
    value: function handleFind(req) {
      var options = {};
      if (req.body.skip) {
        options.skip = Number(req.body.skip);
      }
      if (req.body.limit) {
        options.limit = Number(req.body.limit);
      }
      if (req.body.order) {
        options.order = String(req.body.order);
      }
      if (req.body.count) {
        options.count = true;
      }
      if (req.body.include) {
        options.include = String(req.body.include);
      }

      console.log('AP >> InstallationsRouter >> Req Body >> ' + req.body.where);

      return _rest2.default.find(req.config, req.auth, '_Installation', req.body.where, options).then(function (response) {
        return { response: response };
      });
    }
  }, {
    key: 'handleGet',
    value: function handleGet(req) {
      req.params.className = '_Installation';
      return _get(Object.getPrototypeOf(InstallationsRouter.prototype), 'handleGet', this).call(this, req);
    }
  }, {
    key: 'handleCreate',
    value: function handleCreate(req) {
      req.params.className = '_Installation';
      return _get(Object.getPrototypeOf(InstallationsRouter.prototype), 'handleCreate', this).call(this, req);
    }
  }, {
    key: 'handleUpdate',
    value: function handleUpdate(req) {
      req.params.className = '_Installation';
      return _get(Object.getPrototypeOf(InstallationsRouter.prototype), 'handleUpdate', this).call(this, req);
    }
  }, {
    key: 'handleDelete',
    value: function handleDelete(req) {
      req.params.className = '_Installation';
      return _get(Object.getPrototypeOf(InstallationsRouter.prototype), 'handleDelete', this).call(this, req);
    }
  }, {
    key: 'mountRoutes',
    value: function mountRoutes() {
      var _this2 = this;

      this.route('GET', '/installations', function (req) {
        return _this2.handleFind(req);
      });
      this.route('GET', '/installations/:objectId', function (req) {
        return _this2.handleGet(req);
      });
      this.route('POST', '/installations', function (req) {
        return _this2.handleCreate(req);
      });
      this.route('PUT', '/installations/:objectId', function (req) {
        return _this2.handleUpdate(req);
      });
      this.route('DELETE', '/installations/:objectId', function (req) {
        return _this2.handleDelete(req);
      });
    }
  }]);

  return InstallationsRouter;
}(_ClassesRouter3.default);

exports.default = InstallationsRouter;<|endoftext|>


<commit_before>var CoreView = require('backbone/core-view');
var _ = require('underscore');
var CarouselFormView = require('../../../components/carousel-form-view');
var CarouselCollection = require('../../../components/custom-carousel/custom-carousel-collection');
var WidgetFormFactory = require('./widgets-form-factory');
var WidgetsFormFieldsView = require('./widgets-form-fields-view');
var checkAndBuildOpts = require('../../../helpers/required-opts');
var loadingTemplate = require('../../layers/panel-loading-template.tpl');

var TIME_SERIES_VALUE = 'time-series';
var REQUIRED_OPTS = [
  'userActions',
  'widgetDefinitionModel',
  'modals',
  'querySchemaModel',
  'configModel',
  'userModel'
];

module.exports = CoreView.extend({

  initialize: function (opts) {
    checkAndBuildOpts(opts, REQUIRED_OPTS, this);
    this._initBinds();

    if (this._querySchemaModel.shouldFetch()) {
      this._querySchemaModel.fetch();
    }
  },

  render: function () {
    this.clearSubViews();
    this.$el.empty();

    if (!this._querySchemaModel.isFetched()) {
      this.$el.html(loadingTemplate());
    } else {
      this._renderCarousel();
      this._renderForm();
    }

    return this;
  },

  _initBinds: function () {
    this.listenTo(this._widgetDefinitionModel, 'change:type', this._renderFormAndValidate);
    this.listenTo(this._querySchemaModel, 'change:status', this.render);
  },

  _renderCarousel: function () {
    var containsTimeSeries = _.any(this._widgetDefinitionModel.collection.models, function (model) {
      return model.get('type') === TIME_SERIES_VALUE;
    });
    var filteredDataTypes = _.filter(WidgetFormFactory.getDataTypes(this._querySchemaModel), function (type) {
      // Do not allow to change the widget to TimeSeries if there is already a TimeSeries widget
      return (!containsTimeSeries ||
              type.value !== TIME_SERIES_VALUE ||
              this._widgetDefinitionModel.get('type') === TIME_SERIES_VALUE);
    }, this);
    var carouselCollection = new CarouselCollection(
      _.map(filteredDataTypes, function (type) {
        return {
          selected: this._widgetDefinitionModel.get('type') === type.value,
          val: type.value,
          label: type.label,
          template: function () {
            return (type.iconTemplate && type.iconTemplate({ makeItBig: true })) || type.value;
          }
        };
      }, this)
    );

    carouselCollection.bind('change:selected', function (mdl) {
      if (mdl.get('selected')) {
        this._widgetDefinitionModel.changeType(mdl.getValue());
      }
    }, this);

    var view = new CarouselFormView({
      collection: carouselCollection,
      template: require('./widgets-form-types.tpl')
    });
    this.addView(view);
    this.$el.append(view.render().el);
  },

  _renderFormAndValidate: function () {
    this._renderForm();

    if (this._formView.validateForm() === null) {
      this._userActions.saveWidget(this._widgetDefinitionModel);
    }
  },

  _renderForm: function () {
    if (this._formView) {
      this.removeView(this._formView);
      this._formView.clean();
    }
    this._formView = new WidgetsFormFieldsView({
      userActions: this._userActions,
      widgetDefinitionModel: this._widgetDefinitionModel,
      querySchemaModel: this._querySchemaModel,
      modals: this._modals,
      userModel: this._userModel,
      configModel: this._configModel
    });
    this.addView(this._formView);
    this.$el.append(this._formView.render().el);
  }
});
<commit_msg>Fix tests<commit_after>var CoreView = require('backbone/core-view');
var _ = require('underscore');
var CarouselFormView = require('../../../components/carousel-form-view');
var CarouselCollection = require('../../../components/custom-carousel/custom-carousel-collection');
var WidgetFormFactory = require('./widgets-form-factory');
var WidgetsFormFieldsView = require('./widgets-form-fields-view');
var checkAndBuildOpts = require('../../../helpers/required-opts');
var loadingTemplate = require('../../layers/panel-loading-template.tpl');

var TIME_SERIES_TYPE = 'time-series';
var REQUIRED_OPTS = [
  'userActions',
  'widgetDefinitionModel',
  'modals',
  'querySchemaModel',
  'configModel',
  'userModel'
];

module.exports = CoreView.extend({

  initialize: function (opts) {
    checkAndBuildOpts(opts, REQUIRED_OPTS, this);
    this._initBinds();

    if (this._querySchemaModel.shouldFetch()) {
      this._querySchemaModel.fetch();
    }
  },

  render: function () {
    this.clearSubViews();
    this.$el.empty();

    if (!this._querySchemaModel.isFetched()) {
      this.$el.html(loadingTemplate());
    } else {
      this._renderCarousel();
      this._renderForm();
    }

    return this;
  },

  _initBinds: function () {
    this.listenTo(this._widgetDefinitionModel, 'change:type', this._renderFormAndValidate);
    this.listenTo(this._querySchemaModel, 'change:status', this.render);
  },

  _renderCarousel: function () {
    var containsTimeSeries = false;
    var modelCollection = this._widgetDefinitionModel.collection;
    if (modelCollection && modelCollection.models) {
      containsTimeSeries = _.any(modelCollection.models, function (model) {
        return model.get('type') === TIME_SERIES_TYPE;
      });
    }
    var filteredDataTypes = _.filter(WidgetFormFactory.getDataTypes(this._querySchemaModel), function (type) {
      // Do not allow to change the widget to time-series if there is already a time-series widget
      return (!containsTimeSeries ||
              type.value !== TIME_SERIES_TYPE ||
              this._widgetDefinitionModel.get('type') === TIME_SERIES_TYPE);
    }, this);
    var carouselCollection = new CarouselCollection(
      _.map(filteredDataTypes, function (type) {
        return {
          selected: this._widgetDefinitionModel.get('type') === type.value,
          val: type.value,
          label: type.label,
          template: function () {
            return (type.iconTemplate && type.iconTemplate({ makeItBig: true })) || type.value;
          }
        };
      }, this)
    );

    carouselCollection.bind('change:selected', function (mdl) {
      if (mdl.get('selected')) {
        this._widgetDefinitionModel.changeType(mdl.getValue());
      }
    }, this);

    var view = new CarouselFormView({
      collection: carouselCollection,
      template: require('./widgets-form-types.tpl')
    });
    this.addView(view);
    this.$el.append(view.render().el);
  },

  _renderFormAndValidate: function () {
    this._renderForm();

    if (this._formView.validateForm() === null) {
      this._userActions.saveWidget(this._widgetDefinitionModel);
    }
  },

  _renderForm: function () {
    if (this._formView) {
      this.removeView(this._formView);
      this._formView.clean();
    }
    this._formView = new WidgetsFormFieldsView({
      userActions: this._userActions,
      widgetDefinitionModel: this._widgetDefinitionModel,
      querySchemaModel: this._querySchemaModel,
      modals: this._modals,
      userModel: this._userModel,
      configModel: this._configModel
    });
    this.addView(this._formView);
    this.$el.append(this._formView.render().el);
  }
});
<|endoftext|>


<commit_before>var _ = require('underscore');
var SimpleStyleDefaults = require('./simple-style-defaults');
var rampList = require('cartocolor');

module.exports = _.defaults({

  generateAttributes: function (geometryType) {
    return _.extend(
      this._getFillAttrs(geometryType),
      this._getAnimatedAttrs()
    );
  },

  _getFillAttrs: function (geometryType) {
    var attrs = {
      fill: {
        'size': {
          fixed: 45
        },
        'color': {
          attribute: 'points_agg',
          range: rampList.ag_Sunset[7].reverse(),
          // ['#00F', '#0FF', '#90EE90', '#FF0', '#FFA500', '#F00'],
          bins: 6
        }
      }
    };

    return attrs;
  },

  _getAnimatedAttrs: function (geometryType) {
    return {
      animated: {
        attribute: 'cartodb_id',
        overlap: false,
        duration: 30,
        steps: 1,
        trails: 0,
        resolution: 4
      }
    };
  }

}, SimpleStyleDefaults);
<commit_msg>Don't reverse heatmap fill ramp + reset aggregation values<commit_after>var _ = require('underscore');
var SimpleStyleDefaults = require('./simple-style-defaults');
var rampList = require('cartocolor');

module.exports = _.defaults({

  generateAttributes: function (geometryType) {
    return _.extend(
      this._getFillAttrs(geometryType),
      this._getAggrAttrs(),
      this._getAnimatedAttrs(),
      this._getLabelsAttrs()
    );
  },

  _getFillAttrs: function (geometryType) {
    var attrs = {
      fill: {
        'size': {
          fixed: 45
        },
        'color': {
          attribute: 'cartodb_id',
          range: rampList.ag_Sunset[7],
          bins: 6
        }
      }
    };

    return attrs;
  },

  _getAggrAttrs: function () {
    return {
      aggregation: {}
    };
  },

  _getAnimatedAttrs: function (geometryType) {
    return {
      animated: {
        attribute: 'cartodb_id',
        overlap: false,
        duration: 30,
        steps: 1,
        trails: 0,
        resolution: 4
      }
    };
  },

  _getLabelsAttrs: function () {
    return {
      labels: {}
    };
  }

}, SimpleStyleDefaults);
<|endoftext|>


<commit_before>var $dateQuery = $('#dateQuery'),
	$holder = $('#days'),
	$prev = $('#prev'),
	$next = $('#next'),
	$pickerList = $('.picker-list'),
	$ctitle = $('#calendar-title'),
	$cyear = $('#calendar-year'),
	$customQueryBtn = $('#customQueryBtn');

var LIMITNUM = 5; //限制选择最多个数

var monthName = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'];

var _d = new Date(),
	_year = _d.getFullYear(),
	_month = _d.getMonth() + 1,
	_day = _d.getDate();

var dayStart = function(year, month) { //获取某一个月的第一天是星期几
	var tempDate = new Date(year, month, 1);
	return tempDate.getDay();
};

var getMonthDays = function(year, month) { //获取一个月有多少天
	var hashDate = new Date();
	hashDate.setFullYear(year, month, 0);
	return hashDate.getDate();
};

var getDayInfo = function(infoYear, infoMonth, infoDay) { //转换当天的信息,如:2016年12月30号转换为20161230
	infoMonth = infoMonth[1] ? infoMonth : '0' + infoMonth;
	infoDay = infoDay[1] ? infoDay : '0' + infoDay;
	return infoYear + infoMonth + infoDay;
};

var refreshDate = function() { //生成当前月份显示
	var str = '',
		totalDays = getMonthDays(_year, _month), //获取该月天数
		firstaDay = dayStart(_year, _month - 1);
	for(var i = 1; i < firstaDay; i++) {
		str += '

'; //为起始日期之前的日期创建空白节点
	};
	for(var i = 1; i <= totalDays; i++) {
		str += '
' + i + '
'
	};
	$holder.html(str);
	$ctitle.html(monthName[_month - 1]);
	$cyear.html(_year);
};
refreshDate();

$prev.on('click', function() {
	_month--;
	if(_month < 1) {
		_year--;
		_month = 12;
	}
	refreshDate();
});

$next.on('click', function() {
	_month++;
	if(_month > 12) {
		_year++;
		_month = 1;
	}
	refreshDate();
});

$pickerList.on('click', 'li', function() {
	var activeLen = $(this).parent().find('.active').length;
	if($(this).hasClass('active')) {
		$(this).removeClass('active');
	} else {
		if(activeLen < LIMITNUM) {
			$(this).addClass('active');
		}
	}
});

$customQueryBtn.on('click', function() { //点击确认后,将所选的日期信息放到隐藏域中提交到后台
	var daysQueryStr = '', //将所选的日期以逗号隔开拼成字符串传给后台
		infoYear = parseInt($cyear.html()).toString(),
		infoMonth = parseInt($ctitle.html()).toString(),
		checkedDays = $pickerList.find('.active');
    if(checkedDays.length == 0){
    	alert('请先选择要查询的日期')
    }else{
	    checkedDays.each(function(i, e) {
			var infoDay = $(e).attr('data-day');
			daysQueryStr += getDayInfo(infoYear, infoMonth, infoDay)+','; //将所选的日期拼成字符串以逗号隔开传给后台
		});
	    $dateQuery.val(daysQueryStr);
	    $('#customQueryForm').submit();
    }
});<commit_msg>update<commit_after>var $dateQuery = $('#dateQuery'),
	$holder = $('#days'),
	$prev = $('#prev'),
	$next = $('#next'),
	$pickerList = $('.picker-list'),
	$ctitle = $('#calendar-title'),
	$cyear = $('#calendar-year'),
	$customQueryBtn = $('#customQueryBtn');

var LIMITNUM = 5; //限制选择最多个数

var monthName = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'];

var _d = new Date(),
	_year = _d.getFullYear(),
	_month = _d.getMonth() + 1,
	_day = _d.getDate();

var dayStart = function(year, month) { //获取某一个月的第一天是星期几,0的话表示是星期日
	var tempDate = new Date(year, month, 1);
	return tempDate.getDay();
};

var getMonthDays = function(year, month) { //获取一个月有多少天
	var hashDate = new Date();
	hashDate.setFullYear(year, month, 0);
	return hashDate.getDate();
};

var getDayInfo = function(infoYear, infoMonth, infoDay) { //转换当天的信息,如:2016年12月30号转换为20161230
	infoMonth = infoMonth[1] ? infoMonth : '0' + infoMonth;
	infoDay = infoDay[1] ? infoDay : '0' + infoDay;
	return infoYear + infoMonth + infoDay;
};

var refreshDate = function() { //生成当前月份显示
	var str = '',
		totalDays = getMonthDays(_year, _month), //获取该月天数
		firstaDay = dayStart(_year, _month - 1);
	firstaDay = firstaDay == 0?7:firstaDay;
	for(var i = 1; i < firstaDay; i++) {
		str += '

'; //为起始日期之前的日期创建空白节点
	};
	for(var i = 1; i <= totalDays; i++) {
		str += '
' + i + '
'
	};
	$holder.html(str);
	$ctitle.html(monthName[_month - 1]);
	$cyear.html(_year);
};
refreshDate();

$prev.on('click', function() {
	_month--;
	if(_month < 1) {
		_year--;
		_month = 12;
	}
	refreshDate();
});

$next.on('click', function() {
	_month++;
	if(_month > 12) {
		_year++;
		_month = 1;
	}
	refreshDate();
});

$pickerList.on('click', 'li', function() {
	var activeLen = $(this).parent().find('.active').length;
	if($(this).hasClass('active')) {
		$(this).removeClass('active');
	} else {
		if(activeLen < LIMITNUM) {
			$(this).addClass('active');
		}
	}
});

$customQueryBtn.on('click', function() { //点击确认后,将所选的日期信息放到隐藏域中提交到后台
	var daysQueryStr = '', //将所选的日期以逗号隔开拼成字符串传给后台
		infoYear = parseInt($cyear.html()).toString(),
		infoMonth = parseInt($ctitle.html()).toString(),
		checkedDays = $pickerList.find('.active');
	if(checkedDays.length == 0) {
		alert('请先选择要查询的日期')
	} else {
		checkedDays.each(function(i, e) {
			var infoDay = $(e).attr('data-day');
			daysQueryStr += getDayInfo(infoYear, infoMonth, infoDay) + ','; //将所选的日期拼成字符串以逗号隔开传给后台
		});
		$dateQuery.val(daysQueryStr);
		$('#customQueryForm').submit();
	}
});<|endoftext|>


<commit_before>/* global app:true */

(function() {
  'use strict';

  app = app || {};

  app.Project = Backbone.Model.extend({
    idAttribute: '_id',
    defaults: {
      _id: undefined,
      name: '',
      slogan: '',
      company: '',
      companySlogan: '',
      copyrightYear: '',
    },
    url: function() {
      return '/admin/accounts/'+ (this.isNew() ? '' : this.id +'/');
    }
  });

  app.Record = Backbone.Model.extend({
    idAttribute: '_id',
    defaults: {
      _id: undefined,
      'name.full': '',
      company: '',
      phone: '',
      zip: '',
      status: {
        id: undefined,
        name: '',
        userCreated: {}
      },
      userCreated: {}
    },
    url: function() {
      return '/admin/accounts/'+ (this.isNew() ? '' : this.id +'/');
    }
  });

  app.RecordCollection = Backbone.Collection.extend({
    model: app.Record,
    url: '/admin/accounts/',
    parse: function(results) {
      app.pagingView.model.set({
        pages: results.pages,
        items: results.items
      });
      app.filterView.model.set(results.filters);
      return results.data;
    }
  });

  app.Filter = Backbone.Model.extend({
    defaults: {
      search: '',
      status: '',
      sort: '',
      limit: ''
    }
  });

  app.Paging = Backbone.Model.extend({
    defaults: {
      pages: {},
      items: {}
    }
  });

  app.PublicMenuView = Backbone.View.extend({
    el: '#public-menu',
    events: {
      'click #home': 'processHome',
      'click #about': 'processAbout',
      'click #contact': 'processContact',
      'click #signup': 'processSignup',
      'click #login': 'processLogin'
    },
    processAbout: function(e){
      e.preventDefault();
      console.log('view: #about clicked');
      //Backbone.history.navigate('about', {trigger: true});
      app.router.navigate('#about', {trigger: true});
    }
  });

  app.HeaderView = Backbone.View.extend({
    el: '#header',
    //template: _.template( $('#tmpl-header').html() ),
    events: {
      'submit form': 'preventSubmit',
      'keypress input[type="text"]': 'addNewOnEnter',
      'click .btn-add': 'addNew'
    },
    initialize: function() {
      this.model = new app.Record();
      this.listenTo(this.model, 'change', this.render);
      this.render();
    },
    render: function() {
      this.$el.html(this.template( this.model.attributes ));
    },
    preventSubmit: function(event) {
      event.preventDefault();
    },
    addNewOnEnter: function(event) {
      if (event.keyCode !== 13) { return; }
      event.preventDefault();
      this.addNew();
    },
    addNew: function() {
      if (this.$el.find('[name="name"]').val() === '') {
        alert('Please enter a name.');
      }
      else {
        this.model.save({
          'name.full': this.$el.find('[name="name"]').val()
        },{
          success: function(model, response) {
            if (response.success) {
              model.id = response.record._id;
              location.href = model.url();
            }
            else {
              alert(response.errors.join('\n'));
            }
          }
        });
      }
    }
  });

  app.ResultsView = Backbone.View.extend({
    el: '#results-table',
    //template: _.template( $('#tmpl-results-table').html() ),
    initialize: function() {
      this.collection = new app.RecordCollection( app.mainView.results.data );
      this.listenTo(this.collection, 'reset', this.render);
      this.render();
    },
    render: function() {
      this.$el.html( this.template() );

      var frag = document.createDocumentFragment();
      this.collection.each(function(record) {
        var view = new app.ResultsRowView({ model: record });
        frag.appendChild(view.render().el);
      }, this);
      $('#results-rows').append(frag);

      if (this.collection.length === 0) {
        $('#results-rows').append( $('#tmpl-results-empty-row').html() );
      }
    }
  });

  app.ResultsRowView = Backbone.View.extend({
    tagName: 'tr',
    //template: _.template( $('#tmpl-results-row').html() ),
    events: {
      'click .btn-details': 'viewDetails'
    },
    viewDetails: function() {
      location.href = this.model.url();
    },
    render: function() {
      this.$el.html(this.template( this.model.attributes ));
      this.$el.find('.timeago').each(function(index, indexValue) {
        if (indexValue.innerText) {
          var myMoment = moment(indexValue.innerText);
          indexValue.innerText = myMoment.from();
          if (indexValue.getAttribute('data-age')) {
            indexValue.innerText = indexValue.innerText.replace('ago', 'old');
          }
        }
      });
      return this;
    }
  });

  app.FilterView = Backbone.View.extend({
    el: '#filters',
    //template: _.template( $('#tmpl-filters').html() ),
    events: {
      'submit form': 'preventSubmit',
      'keypress input[type="text"]': 'filterOnEnter',
      'change select': 'filter'
    },
    initialize: function() {
      this.model = new app.Filter( app.mainView.results.filters );
      this.listenTo(this.model, 'change', this.render);
      this.render();
    },
    render: function() {
      this.$el.html(this.template( this.model.attributes ));

      for (var key in this.model.attributes) {
        if (this.model.attributes.hasOwnProperty(key)) {
          this.$el.find('[name="'+ key +'"]').val(this.model.attributes[key]);
        }
      }
    },
    preventSubmit: function(event) {
      event.preventDefault();
    },
    filterOnEnter: function(event) {
      if (event.keyCode !== 13) { return; }
      this.filter();
    },
    filter: function() {
      var query = $('#filters form').serialize();
      Backbone.history.navigate('q/'+ query, { trigger: true });
    }
  });

  app.PagingView = Backbone.View.extend({
    el: '#results-paging',
    //template: _.template( $('#tmpl-results-paging').html() ),
    events: {
      'click .btn-page': 'goToPage'
    },
    initialize: function() {
      this.model = new app.Paging({ pages: app.mainView.results.pages, items: app.mainView.results.items });
      this.listenTo(this.model, 'change', this.render);
      this.render();
    },
    render: function() {
      if (this.model.get('pages').total > 1) {
        this.$el.html(this.template( this.model.attributes ));

        if (!this.model.get('pages').hasPrev) {
          this.$el.find('.btn-prev').attr('disabled', 'disabled');
        }

        if (!this.model.get('pages').hasNext) {
          this.$el.find('.btn-next').attr('disabled', 'disabled');
        }
      }
      else {
        this.$el.empty();
      }
    },
    goToPage: function(event) {
      var query = $('#filters form').serialize() +'&page='+ $(event.target).data('page');
      Backbone.history.navigate('q/'+ query, { trigger: true });
      $('body').scrollTop(0);
    }
  });

  app.MainView = Backbone.View.extend({
    //el: 'body',
    el: '.page .container',
    initialize: function() {
      app.mainView = this;
      //this.results = JSON.parse( unescape($('#data-results').html()) );

      app.publicMenuView = new app.PublicMenuView();
      //app.headerView = new app.HeaderView();
      //app.resultsView = new app.ResultsView();
      //app.filterView = new app.FilterView();
      //app.pagingView = new app.PagingView();
    }
  });

  app.Router = Backbone.Router.extend({
    routes: {
      '': 'default',
      'q/:params': 'query',
      '#about': 'about',
      '#contact': 'contact',
      '#signup': 'signup',
      '#login': 'login'
    },
    initialize: function() {
      app.mainView = new app.MainView();
    },
    default: function() {
      if (!app.firstLoad) {
        app.resultsView.collection.fetch({ reset: true });
      }

      app.firstLoad = false;
    },
    query: function(params) {
      app.resultsView.collection.fetch({ data: params, reset: true });
      app.firstLoad = false;
    },
    about: function() {
      console.log('router: about');
    },
    contact: function() {
      console.log('router: contact');
    },
    signup: function() {
      console.log('router: signup');
    },
    login: function() {
      console.log('router: login');
    }
  });

  $(document).ready(function() {
    console.log('app loading...');
    app.firstLoad = true;
    app.router = new app.Router();
    Backbone.history.start();
    console.log('app loaded!');
  });
}());
<commit_msg>testing routing<commit_after>/* global app:true */

(function() {
  'use strict';

  app = app || {};

  app.Project = Backbone.Model.extend({
    idAttribute: '_id',
    defaults: {
      _id: undefined,
      name: '',
      slogan: '',
      company: '',
      companySlogan: '',
      copyrightYear: '',
    },
    url: function() {
      return '/admin/accounts/'+ (this.isNew() ? '' : this.id +'/');
    }
  });

  app.Record = Backbone.Model.extend({
    idAttribute: '_id',
    defaults: {
      _id: undefined,
      'name.full': '',
      company: '',
      phone: '',
      zip: '',
      status: {
        id: undefined,
        name: '',
        userCreated: {}
      },
      userCreated: {}
    },
    url: function() {
      return '/admin/accounts/'+ (this.isNew() ? '' : this.id +'/');
    }
  });

  app.RecordCollection = Backbone.Collection.extend({
    model: app.Record,
    url: '/admin/accounts/',
    parse: function(results) {
      app.pagingView.model.set({
        pages: results.pages,
        items: results.items
      });
      app.filterView.model.set(results.filters);
      return results.data;
    }
  });

  app.Filter = Backbone.Model.extend({
    defaults: {
      search: '',
      status: '',
      sort: '',
      limit: ''
    }
  });

  app.Paging = Backbone.Model.extend({
    defaults: {
      pages: {},
      items: {}
    }
  });

  app.PublicMenuView = Backbone.View.extend({
    el: '#public-menu',
    events: {
      'click #home': 'processHome',
      'click #about': 'processAbout',
      'click #contact': 'processContact',
      'click #signup': 'processSignup',
      'click #login': 'processLogin'
    },
    processHome: function(e){
      e.preventDefault();
      console.log('view: #home clicked');
      Backbone.history.navigate('#home', {trigger: true});
    },
    processAbout: function(e){
      e.preventDefault();
      console.log('view: #about clicked');
      Backbone.history.navigate('#about', {trigger: true});
    },
    processContact: function(e){
      e.preventDefault();
      console.log('view: #contact clicked');
      Backbone.history.navigate('#contact', {trigger: true});
    },
    processSignup: function(e){
      e.preventDefault();
      console.log('view: #signup clicked');
      Backbone.history.navigate('#signup', {trigger: true});
    },
    processLogin: function(e){
      e.preventDefault();
      console.log('view: #login clicked');
      Backbone.history.navigate('#login', {trigger: true});
    },
  });

  app.HeaderView = Backbone.View.extend({
    el: '#header',
    //template: _.template( $('#tmpl-header').html() ),
    events: {
      'submit form': 'preventSubmit',
      'keypress input[type="text"]': 'addNewOnEnter',
      'click .btn-add': 'addNew'
    },
    initialize: function() {
      this.model = new app.Record();
      this.listenTo(this.model, 'change', this.render);
      this.render();
    },
    render: function() {
      this.$el.html(this.template( this.model.attributes ));
    },
    preventSubmit: function(event) {
      event.preventDefault();
    },
    addNewOnEnter: function(event) {
      if (event.keyCode !== 13) { return; }
      event.preventDefault();
      this.addNew();
    },
    addNew: function() {
      if (this.$el.find('[name="name"]').val() === '') {
        alert('Please enter a name.');
      }
      else {
        this.model.save({
          'name.full': this.$el.find('[name="name"]').val()
        },{
          success: function(model, response) {
            if (response.success) {
              model.id = response.record._id;
              location.href = model.url();
            }
            else {
              alert(response.errors.join('\n'));
            }
          }
        });
      }
    }
  });

  app.ResultsView = Backbone.View.extend({
    el: '#results-table',
    //template: _.template( $('#tmpl-results-table').html() ),
    initialize: function() {
      this.collection = new app.RecordCollection( app.mainView.results.data );
      this.listenTo(this.collection, 'reset', this.render);
      this.render();
    },
    render: function() {
      this.$el.html( this.template() );

      var frag = document.createDocumentFragment();
      this.collection.each(function(record) {
        var view = new app.ResultsRowView({ model: record });
        frag.appendChild(view.render().el);
      }, this);
      $('#results-rows').append(frag);

      if (this.collection.length === 0) {
        $('#results-rows').append( $('#tmpl-results-empty-row').html() );
      }
    }
  });

  app.ResultsRowView = Backbone.View.extend({
    tagName: 'tr',
    //template: _.template( $('#tmpl-results-row').html() ),
    events: {
      'click .btn-details': 'viewDetails'
    },
    viewDetails: function() {
      location.href = this.model.url();
    },
    render: function() {
      this.$el.html(this.template( this.model.attributes ));
      this.$el.find('.timeago').each(function(index, indexValue) {
        if (indexValue.innerText) {
          var myMoment = moment(indexValue.innerText);
          indexValue.innerText = myMoment.from();
          if (indexValue.getAttribute('data-age')) {
            indexValue.innerText = indexValue.innerText.replace('ago', 'old');
          }
        }
      });
      return this;
    }
  });

  app.FilterView = Backbone.View.extend({
    el: '#filters',
    //template: _.template( $('#tmpl-filters').html() ),
    events: {
      'submit form': 'preventSubmit',
      'keypress input[type="text"]': 'filterOnEnter',
      'change select': 'filter'
    },
    initialize: function() {
      this.model = new app.Filter( app.mainView.results.filters );
      this.listenTo(this.model, 'change', this.render);
      this.render();
    },
    render: function() {
      this.$el.html(this.template( this.model.attributes ));

      for (var key in this.model.attributes) {
        if (this.model.attributes.hasOwnProperty(key)) {
          this.$el.find('[name="'+ key +'"]').val(this.model.attributes[key]);
        }
      }
    },
    preventSubmit: function(event) {
      event.preventDefault();
    },
    filterOnEnter: function(event) {
      if (event.keyCode !== 13) { return; }
      this.filter();
    },
    filter: function() {
      var query = $('#filters form').serialize();
      Backbone.history.navigate('q/'+ query, { trigger: true });
    }
  });

  app.PagingView = Backbone.View.extend({
    el: '#results-paging',
    //template: _.template( $('#tmpl-results-paging').html() ),
    events: {
      'click .btn-page': 'goToPage'
    },
    initialize: function() {
      this.model = new app.Paging({ pages: app.mainView.results.pages, items: app.mainView.results.items });
      this.listenTo(this.model, 'change', this.render);
      this.render();
    },
    render: function() {
      if (this.model.get('pages').total > 1) {
        this.$el.html(this.template( this.model.attributes ));

        if (!this.model.get('pages').hasPrev) {
          this.$el.find('.btn-prev').attr('disabled', 'disabled');
        }

        if (!this.model.get('pages').hasNext) {
          this.$el.find('.btn-next').attr('disabled', 'disabled');
        }
      }
      else {
        this.$el.empty();
      }
    },
    goToPage: function(event) {
      var query = $('#filters form').serialize() +'&page='+ $(event.target).data('page');
      Backbone.history.navigate('q/'+ query, { trigger: true });
      $('body').scrollTop(0);
    }
  });

  app.MainView = Backbone.View.extend({
    //el: 'body',
    el: '.page .container',
    initialize: function() {
      app.mainView = this;
      //this.results = JSON.parse( unescape($('#data-results').html()) );

      app.publicMenuView = new app.PublicMenuView();
      //app.headerView = new app.HeaderView();
      //app.resultsView = new app.ResultsView();
      //app.filterView = new app.FilterView();
      //app.pagingView = new app.PagingView();
    }
  });

  app.Router = Backbone.Router.extend({
    routes: {
      '': 'default',
      'q/:params': 'query',
      '#home': 'home',
      '#about': 'about',
      '#contact': 'contact',
      '#signup': 'signup',
      '#login': 'login'
    },
    initialize: function() {
      app.mainView = new app.MainView();
    },
    default: function() {
      if (!app.firstLoad) {
        app.resultsView.collection.fetch({ reset: true });
      }

      app.firstLoad = false;
    },
    query: function(params) {
      app.resultsView.collection.fetch({ data: params, reset: true });
      app.firstLoad = false;
    },
    home: function() {
      console.log('router: home');
    },
    about: function() {
      console.log('router: about');
    },
    contact: function() {
      console.log('router: contact');
    },
    signup: function() {
      console.log('router: signup');
    },
    login: function() {
      console.log('router: login');
    }
  });

  $(document).ready(function() {
    console.log('app loading...');
    app.firstLoad = true;
    app.router = new app.Router();
    Backbone.history.start();
    console.log('app loaded!');
  });
}());
<|endoftext|>


<commit_before>// ==UserScript==
// @name         Results replacement
// @namespace    https://enopoletus.github.io
// @version      0.31
// @description  Replaces link to framed version with no-frame version of page on uselectionatlas.org
// @author       E. Harding
// @include      *
// @updateURL    https://enopoletus.github.io/atlasnoframes.user.js
// @grant        none
// @run-at document-start
// ==/UserScript==

window.addEventListener("load", function overwrites(){
const x = document.getElementsByTagName("a");
for (let i of x) {
  const iref=i.getAttribute("href");
  if (iref == "RESULTS/") {
  i.setAttribute("href", "https://uselectionatlas.org/RESULTS/national.php?year=2016&f=0&off=0&elect=0");
  };
  if (iref == "https://uselectionatlas.org/RESULTS/") {
  i.setAttribute("href", "https://uselectionatlas.org/RESULTS/national.php?year=2016&f=0&off=0&elect=0");
  };
  if (iref == "http://uselectionatlas.org/RESULTS/") {
  i.setAttribute("href", "https://uselectionatlas.org/RESULTS/national.php?year=2016&f=0&off=0&elect=0");
  };
  if (/uselectionatlas/.test(iref) == true){
     i.setAttribute("href", iref.replace(/&f=1/g,"&f=0"));
     }
  if (/&f=1/.test(iref) == true && /uselectionatlas/.test(location.href) == true){
     i.setAttribute("href", iref.replace(/&f=1/g,"&f=0"));
     }
  if (/uselectionatlas/.test(location.href) == true && /&f=1/g.test(location.href) == true){
     window.location=location.href.replace(/&f=1/g,"&f=0");
     }
  };
 });
<commit_msg>changed version of atlasnoframes<commit_after>// ==UserScript==
// @name         Results replacement
// @namespace    https://enopoletus.github.io
// @version      0.36
// @description  Replaces link to framed version with no-frame version of page on uselectionatlas.org
// @author       E. Harding
// @include      *
// @updateURL    https://enopoletus.github.io/atlasnoframes.user.js
// @grant        none
// @run-at document-start
// ==/UserScript==

window.addEventListener("load", function overwrites(){
const x = document.getElementsByTagName("a");
for (let i of x) {
  const iref=i.getAttribute("href");
  if (iref == "RESULTS/") {
  i.setAttribute("href", "https://uselectionatlas.org/RESULTS/national.php?year=2016&f=0&off=0&elect=0");
  };
  if (iref == "https://uselectionatlas.org/RESULTS/") {
  i.setAttribute("href", "https://uselectionatlas.org/RESULTS/national.php?year=2016&f=0&off=0&elect=0");
  };
  if (iref == "http://uselectionatlas.org/RESULTS/") {
  i.setAttribute("href", "https://uselectionatlas.org/RESULTS/national.php?year=2016&f=0&off=0&elect=0");
  };
  if (/uselectionatlas/.test(iref) == true){
     i.setAttribute("href", iref.replace(/&f=1/g,"&f=0"));
     }
  if (/&f=1/.test(iref) == true && /uselectionatlas/.test(location.href) == true){
     i.setAttribute("href", iref.replace(/&f=1/g,"&f=0"));
     }
  if (/uselectionatlas/.test(location.href) == true && /&f=1/g.test(location.href) == true){
     window.location=location.href.replace(/&f=1/g,"&f=0");
     }
  };
 });
<|endoftext|>


<commit_before>
function tentarLogin(){
    try{
        $.post("/login", $("#login-form").serialize(),
               function(data, status){
                    var auths = Object.keys(data)
                    if(auths.length == 1){
                        var resultadoObj = data;
                        if(resultadoObj.tabela == "aluno"){
                            URL = "aluno-principal.html";
                        }else if(resultadoObj.tabela == "professor"){
                            URL = "professor-principal.html";
                        }else if(resultadoObj.tabela == "coordenador"){
                            URL = "coordenador-principal.html";
                        }else if(resultadoObj.tabela == "membro-dacc"){
                            URL = "membro-dacc-principal.html";
                        }
                    }else{
                        var authjson = encodeURIComponent(
                                       $.base64.encode(
                                       JSON.stringify(auths)));
                        URL = "desambiguacao.html?auths=" + authjson;
                    }
                    window.location.href = URL;
               }).fail(function(jqobj, status, error){
                    if(jqobj.status == 400){
                        $("#erro-senha").slideDown(250);
                        setTimeout(function () {
                            $("#erro-senha").slideUp(500);
                        }, 5000);
                    }
                },
               "json");
        return false;
    }catch(err){
        console.log(err);
        return false;
    }
}

function enviarCadastro(){
    try{
        $.put("/cadastro",
              $("#cadastro-form").serialize(),
              function(){
                    window.location.href = "login.html";
              })
    }catch(err){
        console.log(err);
        return false;
    }
}

function getParameterByName(name, url) {
    if (!url) url = window.location.href;
    name = name.replace(/[\[\]]/g, "\\$&");
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, " "));
}

function desambigua(tipo){
    var auths = JSON.parse(
                $.base64.decode(
                getParameterByName("auths")));
    var auth_selecionado = auths[tipo];
    var URL;
    document.cookie = "auth=" + auth_selecionado;
    if(tipo == "aluno"){
        URL = "aluno-principal.html";
    }else if(tipo == "professor"){
        URL = "professor-principal.html";
    }else if(tipo == "coordenador"){
        URL = "coordenador-principal.html";
    }else if(tipo == "membro-dacc"){
        URL = "membro-dacc-principal.html";
    }
    window.location.href = URL;
}

function mostrarBotoes(){
    var mapeamento = {"aluno":"aluno", "dacc":"membro-dacc", "coordenacao":"coordenador", "professor":"professor"};
    var auths = JSON.parse(
                $.base64.decode(
                getParameterByName("auths")));
    auths.forEach(
        function(auth){
            console.log(mapeamento.auth);
            $("#" + mapeamento.auth).show(200);
        }
    );
}
<commit_msg>debug orientado a printf<commit_after>
function tentarLogin(){
    try{
        $.post("/login", $("#login-form").serialize(),
               function(data, status){
                    var auths = Object.keys(data)
                    if(auths.length == 1){
                        var resultadoObj = data;
                        if(resultadoObj.tabela == "aluno"){
                            URL = "aluno-principal.html";
                        }else if(resultadoObj.tabela == "professor"){
                            URL = "professor-principal.html";
                        }else if(resultadoObj.tabela == "coordenador"){
                            URL = "coordenador-principal.html";
                        }else if(resultadoObj.tabela == "membro-dacc"){
                            URL = "membro-dacc-principal.html";
                        }
                    }else{
                        var authjson = encodeURIComponent(
                                       $.base64.encode(
                                       JSON.stringify(auths)));
                        URL = "desambiguacao.html?auths=" + authjson;
                    }
                    window.location.href = URL;
               }).fail(function(jqobj, status, error){
                    if(jqobj.status == 400){
                        $("#erro-senha").slideDown(250);
                        setTimeout(function () {
                            $("#erro-senha").slideUp(500);
                        }, 5000);
                    }
                },
               "json");
        return false;
    }catch(err){
        console.log(err);
        return false;
    }
}

function enviarCadastro(){
    try{
        $.put("/cadastro",
              $("#cadastro-form").serialize(),
              function(){
                    window.location.href = "login.html";
              })
    }catch(err){
        console.log(err);
        return false;
    }
}

function getParameterByName(name, url) {
    if (!url) url = window.location.href;
    name = name.replace(/[\[\]]/g, "\\$&");
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, " "));
}

function desambigua(tipo){
    var auths = JSON.parse(
                $.base64.decode(
                getParameterByName("auths")));
    var auth_selecionado = auths[tipo];
    var URL;
    document.cookie = "auth=" + auth_selecionado;
    if(tipo == "aluno"){
        URL = "aluno-principal.html";
    }else if(tipo == "professor"){
        URL = "professor-principal.html";
    }else if(tipo == "coordenador"){
        URL = "coordenador-principal.html";
    }else if(tipo == "membro-dacc"){
        URL = "membro-dacc-principal.html";
    }
    window.location.href = URL;
}

function mostrarBotoes(){
    var mapeamento = {"aluno":"aluno", "dacc":"membro-dacc", "coordenacao":"coordenador", "professor":"professor"};
    var auths = JSON.parse(
                $.base64.decode(
                getParameterByName("auths")));
    auths.forEach(
        function(auth){
            console.log(auth, mapeamento.auth);
            $("#" + mapeamento.auth).show(200);
        }
    );
}
<|endoftext|>


<commit_before>/**
 * Copyright JS Foundation and other contributors, http://js.foundation
 *
 * 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.
 **/

var clone = require("clone");
var log = require("../../log");
var memory = require("./memory");

var settings;

// A map of scope id to context instance
var contexts = {};

// A map of store name to instance
var stores = {};
var storeList = [];
var defaultStore;

// Whether there context storage has been configured or left as default
var hasConfiguredStore = false;

// Unknown Stores
var unknownStores = {};

function logUnknownStore(name) {
    if (name) {
        var count = unknownStores[name] || 0;
        if (count == 0) {
            log.warn(log._("context.unknown-store", {name: name}));
            count++;
            unknownStores[name] = count;
        }
    }
}

function init(_settings) {
    settings = _settings;
    contexts = {};
    stores = {};
    storeList = [];
    hasConfiguredStore = false;
    var seed = settings.functionGlobalContext || {};
    contexts['global'] = createContext("global",seed);
    // create a default memory store - used by the unit tests that skip the full
    // `load()` initialisation sequence.
    // If the user has any stores configured, this will be disgarded
    stores["_"] = new memory();
    defaultStore = "memory";
}

function load() {
    return new Promise(function(resolve,reject) {
        // load & init plugins in settings.contextStorage
        var plugins = settings.contextStorage || {};
        var defaultIsAlias = false;
        var promises = [];
        if (plugins && Object.keys(plugins).length > 0) {
            var hasDefault = plugins.hasOwnProperty('default');
            var defaultName;
            for (var pluginName in plugins) {
                if (plugins.hasOwnProperty(pluginName)) {
                    // "_" is a reserved name - do not allow it to be overridden
                    if (pluginName === "_") {
                        continue;
                    }
                    if (!/^[a-zA-Z0-9_]+$/.test(pluginName)) {
                        return reject(new Error(log._("context.error-invalid-module-name", {name:pluginName})));
                    }

                    // Check if this is setting the 'default' context to be a named plugin
                    if (pluginName === "default" && typeof plugins[pluginName] === "string") {
                        // Check the 'default' alias exists before initialising anything
                        if (!plugins.hasOwnProperty(plugins[pluginName])) {
                            return reject(new Error(log._("context.error-invalid-default-module", {storage:plugins["default"]})));
                        }
                        defaultIsAlias = true;
                        continue;
                    }
                    if (!hasDefault && !defaultName) {
                        defaultName = pluginName;
                    }
                    var plugin;
                    if (plugins[pluginName].hasOwnProperty("module")) {
                        // Get the provided config and copy in the 'approved' top-level settings (eg userDir)
                        var config = plugins[pluginName].config || {};
                        copySettings(config, settings);

                        if (typeof plugins[pluginName].module === "string") {
                            // This config identifies the module by name - assume it is a built-in one
                            // TODO: check it exists locally, if not, try to require it as-is
                            try {
                                plugin = require("./"+plugins[pluginName].module);
                            } catch(err) {
                                return reject(new Error(log._("context.error-loading-module", {module:plugins[pluginName].module,message:err.toString()})));
                            }
                        } else {
                            // Assume `module` is an already-required module we can use
                            plugin = plugins[pluginName].module;
                        }
                        try {
                            // Create a new instance of the plugin by calling its module function
                            stores[pluginName] = plugin(config);
                            log.info(log._("context.log-store-init", {name:pluginName, info:"module="+plugins[pluginName].module}));
                        } catch(err) {
                            return reject(new Error(log._("context.error-loading-module",{module:pluginName,message:err.toString()})));
                        }
                    } else {
                        // Plugin does not specify a 'module'
                        return reject(new Error(log._("context.error-module-not-defined", {storage:pluginName})));
                    }
                }
            }

            // Open all of the configured contexts
            for (var plugin in stores) {
                if (stores.hasOwnProperty(plugin)) {
                    promises.push(stores[plugin].open());
                }
            }
            // There is a 'default' listed in the configuration
            if (hasDefault) {
                // If 'default' is an alias, point it at the right module - we have already
                // checked that it exists. If it isn't an alias, then it will
                // already be set to a configured store
                if (defaultIsAlias) {
                    stores["_"] =  stores[plugins["default"]];
                    defaultStore = plugins["default"];
                } else {
                    stores["_"] = stores["default"];
                    defaultStore = "default";
                }
            } else if (defaultName) {
                // No 'default' listed, so pick first in list as the default
                stores["_"] = stores[defaultName];
                defaultStore = defaultName;
                defaultIsAlias = true;
            } else {
                // else there were no stores list the config object - fall through
                // to below where we default to a memory store
                storeList = ["memory"];
                defaultStore = "memory";
            }
            hasConfiguredStore = true;
            storeList = Object.keys(stores).filter(n=>!(defaultIsAlias && n==="default") && n!== "_");
        } else {
            // No configured plugins
            log.info(log._("context.log-store-init", {name:"default", info:"module=memory"}));
            promises.push(stores["_"].open())
            storeList = ["memory"];
            defaultStore = "memory";
        }
        return resolve(Promise.all(promises));
    });
}

function copySettings(config, settings){
    var copy = ["userDir"]
    config.settings = {};
    copy.forEach(function(setting){
        config.settings[setting] = clone(settings[setting]);
    });
}

function getContextStorage(storage) {
    if (stores.hasOwnProperty(storage)) {
        // A known context
        return stores[storage];
    } else if (stores.hasOwnProperty("_")) {
        // Not known, but we have a default to fall back to
        if (storage !== defaultStore) {
            // It isn't the default store either, so log it
            logUnknownStore(storage);
        }
        return stores["_"];
    }
}

function createContext(id,seed) {
    // Seed is only set for global context - sourced from functionGlobalContext
    var scope = id;
    var obj = seed || {};
    var seedKeys;
    var insertSeedValues;
    if (seed) {
        seedKeys = Object.keys(seed);
        insertSeedValues = function(keys,values) {
            if (!Array.isArray(keys)) {
                if (values[0] === undefined) {
                    values[0] = seed[keys];
                }
            } else {
                for (var i=0;i<keys.length;i++) {
                    if (values[i] === undefined) {
                        values[i] = seed[keys[i]];
                    }
                }
            }
        }
    }

    obj.get = function(key, storage, callback) {
        var context;
        if (!storage && !callback) {
            context = stores["_"];
        } else {
            if (typeof storage === 'function') {
                callback = storage;
                storage = "_";
            }
            if (callback && typeof callback !== 'function'){
                throw new Error("Callback must be a function");
            }
            context = getContextStorage(storage);
        }
        if (callback) {
            if (!seed) {
                context.get(scope,key,callback);
            } else {
                context.get(scope,key,function() {
                    if (arguments[0]) {
                        callback(arguments[0]);
                        return;
                    }
                    var results = Array.prototype.slice.call(arguments,[1]);
                    insertSeedValues(key,results);
                    // Put the err arg back
                    results.unshift(undefined);
                    callback.apply(null,results);
                });
            }
        } else {
            // No callback, attempt to do this synchronously
            var results = context.get(scope,key);
            if (seed) {
                if (Array.isArray(key)) {
                    insertSeedValues(key,results);
                } else if (results === undefined){
                    results = seed[key];
                }
            }
            return results;
        }
    };
    obj.set = function(key, value, storage, callback) {
        var context;
        if (!storage && !callback) {
            context = stores["_"];
        } else {
            if (typeof storage === 'function') {
                callback = storage;
                storage = "_";
            }
            if (callback && typeof callback !== 'function') {
                throw new Error("Callback must be a function");
            }
            context = getContextStorage(storage);
        }
        context.set(scope, key, value, callback);
    };
    obj.keys = function(storage, callback) {
        var context;
        if (!storage && !callback) {
            context = stores["_"];
        } else {
            if (typeof storage === 'function') {
                callback = storage;
                storage = "_";
            }
            if (callback && typeof callback !== 'function') {
                throw new Error("Callback must be a function");
            }
            context = getContextStorage(storage);
        }
        if (seed) {
            if (callback) {
                context.keys(scope, function(err,keys) {
                    callback(err,Array.from(new Set(seedKeys.concat(keys)).keys()));
                });
            } else {
                var keys = context.keys(scope);
                return Array.from(new Set(seedKeys.concat(keys)).keys())
            }
        } else {
            return context.keys(scope, callback);
        }
    };
    return obj;
}

function getContext(localId,flowId) {
    var contextId = localId;
    if (flowId) {
        contextId = localId+":"+flowId;
    }
    if (contexts.hasOwnProperty(contextId)) {
        return contexts[contextId];
    }
    var newContext = createContext(contextId);
    if (flowId) {
        newContext.flow = getContext(flowId);
    }
    newContext.global = contexts['global'];
    contexts[contextId] = newContext;
    return newContext;
}

function deleteContext(id,flowId) {
    if(!hasConfiguredStore){
        // only delete context if there's no configured storage.
        var contextId = id;
        if (flowId) {
            contextId = id+":"+flowId;
        }
        delete contexts[contextId];
        return stores["_"].delete(contextId);
    }else{
        return Promise.resolve();
    }
}

function clean(flowConfig) {
    var promises = [];
    for(var plugin in stores){
        if(stores.hasOwnProperty(plugin)){
            promises.push(stores[plugin].clean(Object.keys(flowConfig.allNodes)));
        }
    }
    for (var id in contexts) {
        if (contexts.hasOwnProperty(id) && id !== "global") {
            var idParts = id.split(":");
            if (!flowConfig.allNodes.hasOwnProperty(idParts[0])) {
                delete contexts[id];
            }
        }
    }
    return Promise.all(promises);
}

function close() {
    var promises = [];
    for(var plugin in stores){
        if(stores.hasOwnProperty(plugin)){
            promises.push(stores[plugin].close());
        }
    }
    return Promise.all(promises);
}

function listStores() {
    return {default:defaultStore,stores:storeList};
}

module.exports = {
    init: init,
    load: load,
    listStores: listStores,
    get: getContext,
    delete: deleteContext,
    clean: clean,
    close: close
};
<commit_msg>Improve custom context store module logging<commit_after>/**
 * Copyright JS Foundation and other contributors, http://js.foundation
 *
 * 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.
 **/

var clone = require("clone");
var log = require("../../log");
var memory = require("./memory");

var settings;

// A map of scope id to context instance
var contexts = {};

// A map of store name to instance
var stores = {};
var storeList = [];
var defaultStore;

// Whether there context storage has been configured or left as default
var hasConfiguredStore = false;

// Unknown Stores
var unknownStores = {};

function logUnknownStore(name) {
    if (name) {
        var count = unknownStores[name] || 0;
        if (count == 0) {
            log.warn(log._("context.unknown-store", {name: name}));
            count++;
            unknownStores[name] = count;
        }
    }
}

function init(_settings) {
    settings = _settings;
    contexts = {};
    stores = {};
    storeList = [];
    hasConfiguredStore = false;
    var seed = settings.functionGlobalContext || {};
    contexts['global'] = createContext("global",seed);
    // create a default memory store - used by the unit tests that skip the full
    // `load()` initialisation sequence.
    // If the user has any stores configured, this will be disgarded
    stores["_"] = new memory();
    defaultStore = "memory";
}

function load() {
    return new Promise(function(resolve,reject) {
        // load & init plugins in settings.contextStorage
        var plugins = settings.contextStorage || {};
        var defaultIsAlias = false;
        var promises = [];
        if (plugins && Object.keys(plugins).length > 0) {
            var hasDefault = plugins.hasOwnProperty('default');
            var defaultName;
            for (var pluginName in plugins) {
                if (plugins.hasOwnProperty(pluginName)) {
                    // "_" is a reserved name - do not allow it to be overridden
                    if (pluginName === "_") {
                        continue;
                    }
                    if (!/^[a-zA-Z0-9_]+$/.test(pluginName)) {
                        return reject(new Error(log._("context.error-invalid-module-name", {name:pluginName})));
                    }

                    // Check if this is setting the 'default' context to be a named plugin
                    if (pluginName === "default" && typeof plugins[pluginName] === "string") {
                        // Check the 'default' alias exists before initialising anything
                        if (!plugins.hasOwnProperty(plugins[pluginName])) {
                            return reject(new Error(log._("context.error-invalid-default-module", {storage:plugins["default"]})));
                        }
                        defaultIsAlias = true;
                        continue;
                    }
                    if (!hasDefault && !defaultName) {
                        defaultName = pluginName;
                    }
                    var plugin;
                    if (plugins[pluginName].hasOwnProperty("module")) {
                        // Get the provided config and copy in the 'approved' top-level settings (eg userDir)
                        var config = plugins[pluginName].config || {};
                        copySettings(config, settings);

                        if (typeof plugins[pluginName].module === "string") {
                            // This config identifies the module by name - assume it is a built-in one
                            // TODO: check it exists locally, if not, try to require it as-is
                            try {
                                plugin = require("./"+plugins[pluginName].module);
                            } catch(err) {
                                return reject(new Error(log._("context.error-loading-module", {module:plugins[pluginName].module,message:err.toString()})));
                            }
                        } else {
                            // Assume `module` is an already-required module we can use
                            plugin = plugins[pluginName].module;
                        }
                        try {
                            // Create a new instance of the plugin by calling its module function
                            stores[pluginName] = plugin(config);
                            var moduleInfo = plugins[pluginName].module;
                            if (typeof moduleInfo !== 'string') {
                                if (moduleInfo.hasOwnProperty("toString")) {
                                    moduleInfo = moduleInfo.toString();
                                } else {
                                    moduleInfo = "custom";
                                }
                            }
                            log.info(log._("context.log-store-init", {name:pluginName, info:"module="+moduleInfo}));
                        } catch(err) {
                            return reject(new Error(log._("context.error-loading-module",{module:pluginName,message:err.toString()})));
                        }
                    } else {
                        // Plugin does not specify a 'module'
                        return reject(new Error(log._("context.error-module-not-defined", {storage:pluginName})));
                    }
                }
            }

            // Open all of the configured contexts
            for (var plugin in stores) {
                if (stores.hasOwnProperty(plugin)) {
                    promises.push(stores[plugin].open());
                }
            }
            // There is a 'default' listed in the configuration
            if (hasDefault) {
                // If 'default' is an alias, point it at the right module - we have already
                // checked that it exists. If it isn't an alias, then it will
                // already be set to a configured store
                if (defaultIsAlias) {
                    stores["_"] =  stores[plugins["default"]];
                    defaultStore = plugins["default"];
                } else {
                    stores["_"] = stores["default"];
                    defaultStore = "default";
                }
            } else if (defaultName) {
                // No 'default' listed, so pick first in list as the default
                stores["_"] = stores[defaultName];
                defaultStore = defaultName;
                defaultIsAlias = true;
            } else {
                // else there were no stores list the config object - fall through
                // to below where we default to a memory store
                storeList = ["memory"];
                defaultStore = "memory";
            }
            hasConfiguredStore = true;
            storeList = Object.keys(stores).filter(n=>!(defaultIsAlias && n==="default") && n!== "_");
        } else {
            // No configured plugins
            log.info(log._("context.log-store-init", {name:"default", info:"module=memory"}));
            promises.push(stores["_"].open())
            storeList = ["memory"];
            defaultStore = "memory";
        }
        return resolve(Promise.all(promises));
    });
}

function copySettings(config, settings){
    var copy = ["userDir"]
    config.settings = {};
    copy.forEach(function(setting){
        config.settings[setting] = clone(settings[setting]);
    });
}

function getContextStorage(storage) {
    if (stores.hasOwnProperty(storage)) {
        // A known context
        return stores[storage];
    } else if (stores.hasOwnProperty("_")) {
        // Not known, but we have a default to fall back to
        if (storage !== defaultStore) {
            // It isn't the default store either, so log it
            logUnknownStore(storage);
        }
        return stores["_"];
    }
}

function createContext(id,seed) {
    // Seed is only set for global context - sourced from functionGlobalContext
    var scope = id;
    var obj = seed || {};
    var seedKeys;
    var insertSeedValues;
    if (seed) {
        seedKeys = Object.keys(seed);
        insertSeedValues = function(keys,values) {
            if (!Array.isArray(keys)) {
                if (values[0] === undefined) {
                    values[0] = seed[keys];
                }
            } else {
                for (var i=0;i<keys.length;i++) {
                    if (values[i] === undefined) {
                        values[i] = seed[keys[i]];
                    }
                }
            }
        }
    }

    obj.get = function(key, storage, callback) {
        var context;
        if (!storage && !callback) {
            context = stores["_"];
        } else {
            if (typeof storage === 'function') {
                callback = storage;
                storage = "_";
            }
            if (callback && typeof callback !== 'function'){
                throw new Error("Callback must be a function");
            }
            context = getContextStorage(storage);
        }
        if (callback) {
            if (!seed) {
                context.get(scope,key,callback);
            } else {
                context.get(scope,key,function() {
                    if (arguments[0]) {
                        callback(arguments[0]);
                        return;
                    }
                    var results = Array.prototype.slice.call(arguments,[1]);
                    insertSeedValues(key,results);
                    // Put the err arg back
                    results.unshift(undefined);
                    callback.apply(null,results);
                });
            }
        } else {
            // No callback, attempt to do this synchronously
            var results = context.get(scope,key);
            if (seed) {
                if (Array.isArray(key)) {
                    insertSeedValues(key,results);
                } else if (results === undefined){
                    results = seed[key];
                }
            }
            return results;
        }
    };
    obj.set = function(key, value, storage, callback) {
        var context;
        if (!storage && !callback) {
            context = stores["_"];
        } else {
            if (typeof storage === 'function') {
                callback = storage;
                storage = "_";
            }
            if (callback && typeof callback !== 'function') {
                throw new Error("Callback must be a function");
            }
            context = getContextStorage(storage);
        }
        context.set(scope, key, value, callback);
    };
    obj.keys = function(storage, callback) {
        var context;
        if (!storage && !callback) {
            context = stores["_"];
        } else {
            if (typeof storage === 'function') {
                callback = storage;
                storage = "_";
            }
            if (callback && typeof callback !== 'function') {
                throw new Error("Callback must be a function");
            }
            context = getContextStorage(storage);
        }
        if (seed) {
            if (callback) {
                context.keys(scope, function(err,keys) {
                    callback(err,Array.from(new Set(seedKeys.concat(keys)).keys()));
                });
            } else {
                var keys = context.keys(scope);
                return Array.from(new Set(seedKeys.concat(keys)).keys())
            }
        } else {
            return context.keys(scope, callback);
        }
    };
    return obj;
}

function getContext(localId,flowId) {
    var contextId = localId;
    if (flowId) {
        contextId = localId+":"+flowId;
    }
    if (contexts.hasOwnProperty(contextId)) {
        return contexts[contextId];
    }
    var newContext = createContext(contextId);
    if (flowId) {
        newContext.flow = getContext(flowId);
    }
    newContext.global = contexts['global'];
    contexts[contextId] = newContext;
    return newContext;
}

function deleteContext(id,flowId) {
    if(!hasConfiguredStore){
        // only delete context if there's no configured storage.
        var contextId = id;
        if (flowId) {
            contextId = id+":"+flowId;
        }
        delete contexts[contextId];
        return stores["_"].delete(contextId);
    }else{
        return Promise.resolve();
    }
}

function clean(flowConfig) {
    var promises = [];
    for(var plugin in stores){
        if(stores.hasOwnProperty(plugin)){
            promises.push(stores[plugin].clean(Object.keys(flowConfig.allNodes)));
        }
    }
    for (var id in contexts) {
        if (contexts.hasOwnProperty(id) && id !== "global") {
            var idParts = id.split(":");
            if (!flowConfig.allNodes.hasOwnProperty(idParts[0])) {
                delete contexts[id];
            }
        }
    }
    return Promise.all(promises);
}

function close() {
    var promises = [];
    for(var plugin in stores){
        if(stores.hasOwnProperty(plugin)){
            promises.push(stores[plugin].close());
        }
    }
    return Promise.all(promises);
}

function listStores() {
    return {default:defaultStore,stores:storeList};
}

module.exports = {
    init: init,
    load: load,
    listStores: listStores,
    get: getContext,
    delete: deleteContext,
    clean: clean,
    close: close
};
<|endoftext|>


<commit_before>import '../css/project.css'
import $ from 'jquery';

$(document).ready(function () {

    var tabs = $('#content-project .tab-pane');
    var lis = $('#nav-project li');

    $('#nav-project a').click(function (e) {
        e.preventDefault();
        tabs.removeClass('active');
        lis.removeClass('active');
        $(this).parent().addClass('active');
        $($(this).attr('href')).addClass('active');
    });

    if ($('ul#proj-filters').length > 0) {
        var projects = $('a.project');
        $('ul#proj-filters li').click(function (e) {
            if ($(this).hasClass('active')) {
                projects.addClass('hide');
                var search = $(this).attr('data-group');
                projects.each(function () {
                    var data = $(this).attr('data-groups');
                    if (data.indexOf(search + ',') > -1 || data.indexOf(search + ']') > -1 ) {
                        $(this).removeClass('hide')
                    }
                })
            } else {
                projects.removeClass('hide');
            }
        });
    }

});<commit_msg>Add tab anchor on project page<commit_after>import '../css/project.css'
import $ from 'jquery';

$(document).ready(function () {

    var tabs = $('#content-project .tab-pane');
    var lis = $('#nav-project li');

    $('#nav-project a').click(function (e) {
        e.preventDefault();
        tabs.removeClass('active');
        lis.removeClass('active');
        $(this).parent().addClass('active');
        $($(this).attr('href')).addClass('active');
        try {
            if (history) {
                history.pushState(null, null, $(this).attr('href'));
            }
        } catch (e) {
        }
    });

    try {
        if (window && window.location && window.location.hash) {
            var f = null;
            lis.each(function () {
                if ($(this).find('a').attr('href') === window.location.hash) {
                    f = $(this);
                }
            });
            if (f) {
                lis.removeClass('active');
                tabs.removeClass('active');
                f.addClass('active');
                $(f.find('a').attr('href')).addClass('active');
            }
        }
    } catch (e) {
    }

    if ($('ul#proj-filters').length > 0) {
        var projects = $('a.project');
        $('ul#proj-filters li').click(function (e) {
            if ($(this).hasClass('active')) {
                projects.addClass('hide');
                var search = $(this).attr('data-group');
                projects.each(function () {
                    var data = $(this).attr('data-groups');
                    if (data.indexOf(search + ',') > -1 || data.indexOf(search + ']') > -1) {
                        $(this).removeClass('hide')
                    }
                })
            } else {
                projects.removeClass('hide');
            }
        });
    }

});<|endoftext|>


<commit_before>import React, {useState} from 'react';
import {Platform} from 'react-native';
import {StateNavigator} from 'navigation';
import {NavigationHandler} from 'navigation-react';
import {NavigationStack, TabBar, TabBarItem} from 'navigation-react-native';
import Home from './Home';
import Notifications from './Notifications';
import Tabs from './Tabs';
import Tweet from './Tweet';
import Timeline from './Timeline';
import {getHome, getFollows, getTweet, getTimeline} from './data';

const stateNavigator = new StateNavigator([
  {key: 'home'},
  {key: 'notifications'},
  {key: 'tweet', trackCrumbTrail: true},
  {key: 'timeline', trackCrumbTrail: true}
]);
const {home, notifications, tweet, timeline} = stateNavigator.states;
const HomeLayout = Platform.OS === 'ios' ? Home : Tabs;
home.renderScene = () => <HomeLayout tweets={getHome()} follows={getFollows()} />;
notifications.renderScene = () => <Notifications follows={getFollows()} />;
tweet.renderScene = ({id}) => <Tweet tweet={getTweet(id)}  />;
timeline.renderScene = ({id}) => <Timeline timeline={getTimeline(id)}  />;

const notificationsNavigator = new StateNavigator(stateNavigator);
stateNavigator.navigate('home');
notificationsNavigator.navigate('notifications');

const Stack = ({navigator}) => (
  <NavigationHandler stateNavigator={navigator}>
    <NavigationStack
      crumbStyle={from => from ? 'scale_in' : 'scale_out'}
      unmountStyle={from => from ? 'slide_in' : 'slide_out'} />
  </NavigationHandler>
);

const App = () => {
  const [notified, setNotified] = useState(false);
  return Platform.OS === 'ios' ? (
    <TabBar>
      <TabBarItem title="Home" image={require('./home.png')}>
        <Stack navigator={stateNavigator} />
      </TabBarItem>
      <TabBarItem
        title="Notifications"
        image={require('./notifications.png')}
        badge={!notified ? getFollows().length : null}
        onPress={() => {setNotified(true)}}>
        <Stack navigator={notificationsNavigator} />
      </TabBarItem>
    </TabBar>
  ) : (
    <Stack navigator={stateNavigator} />
  );
};

export default App;
<commit_msg>Tweaked format<commit_after>import React, {useState} from 'react';
import {Platform} from 'react-native';
import {StateNavigator} from 'navigation';
import {NavigationHandler} from 'navigation-react';
import {NavigationStack, TabBar, TabBarItem} from 'navigation-react-native';
import Home from './Home';
import Notifications from './Notifications';
import Tabs from './Tabs';
import Tweet from './Tweet';
import Timeline from './Timeline';
import {getHome, getFollows, getTweet, getTimeline} from './data';

const stateNavigator = new StateNavigator([
  {key: 'home'},
  {key: 'notifications'},
  {key: 'tweet', trackCrumbTrail: true},
  {key: 'timeline', trackCrumbTrail: true}
]);
const {home, notifications, tweet, timeline} = stateNavigator.states;
const HomeLayout = Platform.OS === 'ios' ? Home : Tabs;
home.renderScene = () => <HomeLayout tweets={getHome()} follows={getFollows()} />;
notifications.renderScene = () => <Notifications follows={getFollows()} />;
tweet.renderScene = ({id}) => <Tweet tweet={getTweet(id)}  />;
timeline.renderScene = ({id}) => <Timeline timeline={getTimeline(id)}  />;

const notificationsNavigator = new StateNavigator(stateNavigator);
stateNavigator.navigate('home');
notificationsNavigator.navigate('notifications');

const Stack = ({navigator}) => (
  <NavigationHandler stateNavigator={navigator}>
    <NavigationStack
      crumbStyle={from => from ? 'scale_in' : 'scale_out'}
      unmountStyle={from => from ? 'slide_in' : 'slide_out'} />
  </NavigationHandler>
);

const App = () => {
  const [notified, setNotified] = useState(false);
  return Platform.OS === 'ios' ? (
    <TabBar>
      <TabBarItem title="Home" image={require('./home.png')}>
        <Stack navigator={stateNavigator} />
      </TabBarItem>
      <TabBarItem
        title="Notifications"
        image={require('./notifications.png')}
        badge={!notified ? getFollows().length : null}
        onPress={() => {setNotified(true)}}>
        <Stack navigator={notificationsNavigator} />
      </TabBarItem>
    </TabBar>
  ) : (
    <Stack navigator={stateNavigator} />
  );
};

export default App;
<|endoftext|>


<commit_before>import React from 'react';
import {Platform} from 'react-native';
import {StateNavigator} from 'navigation';
import {NavigationHandler} from 'navigation-react';
import {NavigationStack, TabBarIOS, TabBarItemIOS} from 'navigation-react-native';
import Home from './Home';
import Notifications from './Notifications';
import Tweet from './Tweet';
import Timeline from './Timeline';
import {getHome, getFollows, getTweet, getTimeline} from './data';

var stateNavigator = new StateNavigator([
  {key: 'home'},
  {key: 'notifications'},
  {key: 'tweet', trackCrumbTrail: true},
  {key: 'timeline', trackCrumbTrail: true}
]);
const {home, notifications, tweet, timeline} = stateNavigator.states;
home.renderScene = () => <Home tweets={getHome()} follows={getFollows()} />;
notifications.renderScene = () => <Notifications follows={getFollows()} />;
tweet.renderScene = ({id}) => <Tweet tweet={getTweet(id)}  />;
timeline.renderScene = ({id}) => <Timeline timeline={getTimeline(id)}  />;

var notificationsNavigator = new StateNavigator(stateNavigator);
stateNavigator.navigate('home');

export default () => (
  Platform.OS === 'ios' ? (
    <TabBarIOS>
      <TabBarItemIOS title="Home">
        <NavigationHandler stateNavigator={stateNavigator}>
          <NavigationStack />
        </NavigationHandler>
      </TabBarItemIOS>
      <TabBarItemIOS title="Notifications" onPress={() => {
        if (!notificationsNavigator.stateContext.state)
          notificationsNavigator.navigate('notifications');
      }}>
        <NavigationHandler stateNavigator={notificationsNavigator}>
          <NavigationStack />
        </NavigationHandler>
      </TabBarItemIOS>
    </TabBarIOS>
  ) : (
    <NavigationHandler stateNavigator={stateNavigator}>
      <NavigationStack
        crumbStyle={from => from ? 'scale_in' : 'scale_out'}
        unmountStyle={from => from ? 'slide_in' : 'slide_out'}>
      </NavigationStack>
    </NavigationHandler>
  )
);
<commit_msg>Update to the Twitter example to reflect the new badge related props that has been introduced. Using the 'setState' hook since it is simpler and the existing content is already exported as a functional component.<commit_after>import React, {useState} from 'react';
import {Platform} from 'react-native';
import {StateNavigator} from 'navigation';
import {NavigationHandler} from 'navigation-react';
import {NavigationStack, TabBarIOS, TabBarItemIOS} from 'navigation-react-native';
import Home from './Home';
import Notifications from './Notifications';
import Tweet from './Tweet';
import Timeline from './Timeline';
import {getHome, getFollows, getTweet, getTimeline} from './data';

var stateNavigator = new StateNavigator([
  {key: 'home'},
  {key: 'notifications'},
  {key: 'tweet', trackCrumbTrail: true},
  {key: 'timeline', trackCrumbTrail: true}
]);
const {home, notifications, tweet, timeline} = stateNavigator.states;
home.renderScene = () => <Home tweets={getHome()} follows={getFollows()} />;
notifications.renderScene = () => <Notifications follows={getFollows()} />;
tweet.renderScene = ({id}) => <Tweet tweet={getTweet(id)}  />;
timeline.renderScene = ({id}) => <Timeline timeline={getTimeline(id)}  />;

var notificationsNavigator = new StateNavigator(stateNavigator);
stateNavigator.navigate('home');

export default() => {
  const [isNotified,
    setIsNotified] = useState(false);
  return (Platform.OS === 'ios'
    ? (<TabBarIOS>
        <TabBarItemIOS title="Home">
          <NavigationHandler stateNavigator={stateNavigator}>
            <NavigationStack/>
          </NavigationHandler>
        </TabBarItemIOS>
        <TabBarItemIOS
          title="Notifications"
          badge={!isNotified?getFollows().length:null}
          /* badgeColor="red" */
          onPress={() => {
            setIsNotified(!isNotified?!isNotified:isNotified);
            if (!notificationsNavigator.stateContext.state)
              notificationsNavigator.navigate('notifications');
            }}>
          <NavigationHandler stateNavigator={notificationsNavigator}>
            <NavigationStack/>
          </NavigationHandler>
        </TabBarItemIOS>
      </TabBarIOS>
    )
    : (<NavigationHandler stateNavigator={stateNavigator}>
        <NavigationStack
          crumbStyle={from => from
          ? 'scale_in'
          : 'scale_out'}
          unmountStyle={from => from
          ? 'slide_in'
          : 'slide_out'}></NavigationStack>
      </NavigationHandler>
    )
  );
}
<|endoftext|>