<commit_before>/**
* User stats embeded in the dashboard
*
* It shows the tables and the space used in the user account
* You must set the username, the user id and the tables model,
* if not, it won't work.
*
* Usage example:
*
*  var userStats = new cdb.admin.dashboard.UserStats({
*    el: $('div.subheader'),
*    model: this.user**
*  })
*
*  **  It needs a user model to work properly.
*
*/

cdb.admin.dashboard.UserStats = cdb.core.View.extend({

  defaults: {
    loaded: false
  },

  events: {
    'click section.warning a.close':  '_disableWarning'
  },

  initialize: function() {

    if (!this.options.user_stats) this.options.user_stats = "";

    this.template = cdb.templates.getTemplate('dashboard/views/user_stats');

    this._setupLocalStorage();
    this._setupBindings();
    this._checkUpgradedUser();
  },

  _setupLocalStorage: function() {

    // Control messages with LocalStorage
    // - Limit message ->       'limit'       -> Expire with the session

    // Recently upgraded message is under control thanks to a central request
    // - Upgraded message ->    'upgraded'    -> It doesn't expire, comes from server

    // Init localStorage
    var key = this.options.localStorageKey || 'cartodb_user';

    this.limitStorage     = new cdb.admin.localStorage(key + "_limit");
    this.migratedStorage  = new cdb.admin.localStorage(key + "_migrated");

  },

  _setupBindings: function() {

    var self = this;

    this.options.tables.bind("add remove reset",    this._refresh, this);
    this.model.bind('change:table_count',           this._refresh, this);

    this.model.bind("change:table_quota_status",    this._onTablesQuotaStatusChange, this);
    this.model.bind("change:byte_quota_status",     this._onSpaceQuotaStatusChange, this);
    this.model.bind("change:mapviews_quota_status", this._onMapViewsQuotaStatusChange, this);

    this.model.bind("change:limits_tables_exceeded",       this._refresh, this);
    this.model.bind("change:limits_space_exceeded",       this._refresh, this);
    this.model.bind("change:limits_mapviews_exceeded",       this._refresh, this);

  },

  _refresh: function() {
    this._calculateQuotas();
    this._updateGraphs();
    this._toggleWarnings();
  },

  _onTablesQuotaStatusChange: function(m) {
    var status = m.get("table_quota_status");

    if (status == "boom" || status == "danger")
      this.model.set("limits_tables_exceeded", "tables");
    else
      this.model.set("limits_tables_exceeded", null);
  },

  _onSpaceQuotaStatusChange: function(m) {
    var status = m.get("byte_quota_status");

    if (status == "boom" || status == "danger")
      this.model.set("limits_space_exceeded", "space");
    else
      this.model.set("limits_space_exceeded", null);
  },

  _onMapViewsQuotaStatusChange: function(m) {
    var status = m.get("mapviews_quota_status");

    if (status == "boom" || status == "danger")
      this.model.set("limits_mapviews_exceeded", "mapviews");
    else
      this.model.set("limits_mapviews_exceeded", null);
  },

  render: function() {

    this.$el.html(this.template(_.extend(this.model.toJSON(), this.options)));

    this._calculateQuotas();

    this._toggleUserStats();
    this._toggleDedicatedSupport();

    if (this.model.get("table_quota") === null ) {
      this.$('.progress').addClass('unlimited')
    }

    // Rendering for the first time?
    if (!this.options.loaded) {
      this.options.loaded = !this.options.loaded;
    }

    this._updateGraphs();
    this._toggleWarnings();

    return this;
  },

  _toggleUserStats: function() {
    (this.model.get("table_count") > 0) ? this._activate() : this._deactivate();
  },

  _toggleDedicatedSupport: function() {
    this.model.get("dedicated_support") ? this._showDedicatedSupport() : this._hideDedicatedSupport();
  },

  /**
  *  Manage how and when we should show any warning message
  */
  _toggleWarnings: function() {

    if (config && config.custom_com_hosted) return;

    if (this.recently_upgraded) {
      this._showWarning('upgraded');
      return;
    }

    if (!this.migratedStorage.get('migrated') && !this.model.get("migrated") ) {
      this._showWarning('migrated');
      return;
    }

    if (!this.limitStorage.get('limit') && this.model.get("limits_tables_exceeded")) {
      this._showWarning('limit');
      return;
    }

    this._hideWarning();

  },

  /**
  *  Check if the user has recently upgraded his account
  */
  _checkUpgradedUser: function() {
    // After know if the user has recently upgraded his account,
    // then render the stats
    if (config && !config.custom_com_hosted && config.account_host) {

      var self = this;

      $.ajax({
        url: '//' + config.account_host + '/account/' + this.model.get('username') + '/recently_upgraded',
        timeout: 5000,
        dataType: 'jsonp',
        success: function(r) {
          self.recently_upgraded = r.recently_upgraded;
          self._toggleWarnings();
        },
        error: function(e) {
          self._toggleWarnings();
        }
      });
    }

  },

  /*
  * Calculate user quotas status
  */
  _calculateQuotas: function() {

    this.model.set("table_quota_status",    this._calculateTableQuota());
    this.model.set("byte_quota_status",     this._calculateSpaceQuota());
    this.model.set("mapviews_quota_status", this._calculateMapViewsQuota());

  },

  _calculateTableQuota: function() {

    var quota = this.model.get("table_quota");
    var count = this.model.get("table_count");

    if (quota == null || quota == 0) return "green";

    var p = (count / quota * 100);

    if (p < 80) return "";
    if (p < 90) return "danger";

    return "boom";

  },

  _calculateSpaceQuota: function() {

    var quota           = this.model.get("byte_quota");
    var remaining_quota = this.model.get("remaining_byte_quota");

    if (quota == null || quota == 0) return "green";

    var p = ((quota - remaining_quota) / quota) * 100;

    if (p < 80) return "";
    if (p < 90) return "danger";

    return "boom";

  },

  _calculateMapViewsQuota: function() {

    var quota = this.model.get("api_calls_quota");

    if (quota == null || quota == 0) return "green";

    var sum = this._calcTotalMapViews();
    var p   = this._calcMapViewsPercentage(sum);

    if (p < 80) return "";
    if (p < 90) return "danger";

    return "boom";

  },

  _updateGraphs: function() {
    this._updateTableGraph();
    this._updateSpaceGraph();
    this._updateMapViewsGraph();
  },

  _updateTableGraph: function() {

    var quota  = this.model.get("table_quota");
    var count  = this.model.get("table_count");
    var status = this.model.get("table_quota_status");

    var p = 100, limit = "∞";

    if (quota != null && quota > 0) {
      p = (count / quota) * 100;
      limit = quota;
    }

    var text  = "" + count + " of " + limit + " tables created";
    var $el   = this.$el.find("section.stats .tables");

    this._updateGraph($el, p, text, status);

  },

  _updateSpaceGraph: function() {

    var quota           = this.model.get("byte_quota");
    var remaining_quota = this.model.get("remaining_byte_quota");
    var status          = this.model.get("byte_quota_status");

    var $el    = this.$el.find("section.stats .size");

    var space_stats = {};

    if (quota == null || quota == 0) {
      space_stats.total = "∞";
    } else {
      space_stats = this._bytesToSize(quota, (quota - remaining_quota));
    }

    var width = 100;
    var text = "You have " + space_stats.total + " space";

    if (quota != null && quota > 0) {
      width = (( space_stats.used / space_stats.total) * 100);
      text = "" + space_stats.used + " of " + space_stats.total + " used " + space_stats.size;
    }

    this._updateGraph($el, width, text, status);

  },

  _updateMapViewsGraph: function() {

    var status = this.model.get("mapviews_quota_status");

    var $el = this.$el.find("section.stats .mapviews");

    var sum   = this._calcTotalMapViews();
    var width = this._calcMapViewsPercentage(sum);

    var text = '' + this._formatNumber(sum) + ' map views in the last 30 days';

    this._updateGraph($el, width, text, status);

  },

  _updateGraph: function($el, percentage, message, status) {

    $el.find("p").html(message);

    $el.find("div.progress span")
    .removeAttr("class").addClass(status)
    .animate({
      width: percentage + "%"
    }, 500);

  },

  _calcTotalMapViews: function() {
    return _.reduce(this.model.get("api_calls"), function(memo, num){ return memo + num; }, 0);
  },

  _calcMapViewsPercentage: function(map_views) {
    return (map_views / this.model.get("api_calls_quota")) * 100;
  },

  /*
  * Disabled the warning upgrade flash
  */
  _disableWarning: function(ev) {
    ev.preventDefault();

    if (this.recently_upgraded) {

      this.recently_upgraded = false;

    } else if (!this.limitStorage.get('limit') && this.warning_type == "limit") {

      this.limitStorage.set({ "limit": true });
      this.warning_type = null;

    } else if (!this.migratedStorage.get('migrated') && this.warning_type == "migrated") {

      this.migratedStorage.set({ "migrated": true });
      this.warning_type = null;

    }

    this._hideWarning();
  },

  /*
  * Show the warning upgrade flash
  */
  _showWarning: function(type) {

    this.warning_type = type;

    this.$el.find("section.warning")
    .removeClass("upgraded migrated limit")
    .addClass("visible " + type);
  },

  /*
  * Hide the warning upgrade flash
  */
  _hideWarning: function() {
    this.$el.find("section.warning").removeClass("visible");
  },

  /*
  * Show dedicated support
  */
  _showDedicatedSupport: function() {
    this.$el.closest("body").find("article.support").show();
  },

  /*
  * Hide dedicated support
  */
  _hideDedicatedSupport: function() {
    this.$el.closest("body").find("article.support").hide();
  },

  /*
  * Activate the table stats
  */
  _activate: function() {
    this.$el.addClass("active");
  },

  /*
  * Deactivate the table stats
  */
  _deactivate: function() {
    this.$el.removeClass("active");
  },

  /*
  * Convert bytes to any size
  */
  _bytesToSize: function(total_bytes, used_bytes) {
    var sizes = ['bytes', 'kilobytes', 'megabytes', 'gigabytes', 'terabytes'];
    if (total_bytes == 0) return 'n/a';
    var i = parseInt(Math.floor(Math.log(total_bytes) / Math.log(1024)));

    return { total: (total_bytes / Math.pow(1024, i)).toFixed(1), used: (used_bytes / Math.pow(1024, i)).toFixed(1), size: sizes[i] };
  },

  _formatNumber: function(str) {

    var amount = new String(str);
    amount = amount.split("").reverse();

    var output = "";

    for ( var i = 0; i <= amount.length-1; i++ ){

      output = amount[i] + output;
      if ((i+1) % 3 == 0 && (amount.length-1) !== i) output = ',' + output;

    }

    return output;
  }

});
<commit_msg>Fixes stats rendering<commit_after>/**
* User stats embeded in the dashboard
*
* It shows the tables and the space used in the user account
* You must set the username, the user id and the tables model,
* if not, it won't work.
*
* Usage example:
*
*  var userStats = new cdb.admin.dashboard.UserStats({
*    el: $('div.subheader'),
*    model: this.user**
*  })
*
*  **  It needs a user model to work properly.
*
*/

cdb.admin.dashboard.UserStats = cdb.core.View.extend({

  defaults: {
    loaded: false
  },

  events: {
    'click section.warning a.close':  '_disableWarning'
  },

  initialize: function() {

    if (!this.options.user_stats) this.options.user_stats = "";

    this.template = cdb.templates.getTemplate('dashboard/views/user_stats');

    this._setupLocalStorage();
    this._setupBindings();
    this._checkUpgradedUser();
  },

  _setupLocalStorage: function() {

    // Control messages with LocalStorage
    // - Limit message ->       'limit'       -> Expire with the session

    // Recently upgraded message is under control thanks to a central request
    // - Upgraded message ->    'upgraded'    -> It doesn't expire, comes from server

    // Init localStorage
    var key = this.options.localStorageKey || 'cartodb_user';

    this.limitStorage     = new cdb.admin.localStorage(key + "_limit");
    this.migratedStorage  = new cdb.admin.localStorage(key + "_migrated");

  },

  _setupBindings: function() {

    var self = this;

    this.options.tables.bind("add remove reset",       this._refresh, this);
    this.model.bind('change:table_count',              this._refresh, this);

    this.model.bind("change:table_quota_status",       this._onTablesQuotaStatusChange, this);
    this.model.bind("change:byte_quota_status",        this._onSpaceQuotaStatusChange, this);
    this.model.bind("change:mapviews_quota_status",    this._onMapViewsQuotaStatusChange, this);

    this.model.bind("change:limits_tables_exceeded",   this._refresh, this);
    this.model.bind("change:limits_space_exceeded",    this._refresh, this);
    this.model.bind("change:limits_mapviews_exceeded", this._refresh, this);

  },

  _refresh: function() {
    this._calculateQuotas();
    this._updateGraphs();
    this._toggleWarnings();
  },

  _onTablesQuotaStatusChange: function(m) {
    var status = m.get("table_quota_status");

    if (status == "boom" || status == "danger")
      this.model.set("limits_tables_exceeded", "tables");
    else
      this.model.set("limits_tables_exceeded", null);
  },

  _onSpaceQuotaStatusChange: function(m) {
    var status = m.get("byte_quota_status");

    if (status == "boom" || status == "danger")
      this.model.set("limits_space_exceeded", "space");
    else
      this.model.set("limits_space_exceeded", null);
  },

  _onMapViewsQuotaStatusChange: function(m) {
    var status = m.get("mapviews_quota_status");

    if (status == "boom" || status == "danger")
      this.model.set("limits_mapviews_exceeded", "mapviews");
    else
      this.model.set("limits_mapviews_exceeded", null);
  },

  render: function() {

    this.$el.html(this.template(_.extend(this.model.toJSON(), this.options)));

    this._calculateQuotas();

    this._toggleUserStats();
    this._toggleDedicatedSupport();

    if (this.model.get("table_quota") === null ) {
      this.$('.progress').addClass('unlimited')
    }

    // Rendering for the first time?
    if (!this.options.loaded) {
      this.options.loaded = !this.options.loaded;
    }

    this._updateGraphs();
    this._toggleWarnings();

    return this;
  },

  _toggleUserStats: function() {
    (this.model.get("table_count") > 0) ? this._activate() : this._deactivate();
  },

  _toggleDedicatedSupport: function() {
    this.model.get("dedicated_support") ? this._showDedicatedSupport() : this._hideDedicatedSupport();
  },

  /**
  *  Manage how and when we should show any warning message
  */
  _toggleWarnings: function() {

    if (config && config.custom_com_hosted) return;

    if (this.recently_upgraded) {
      this._showWarning('upgraded');
      return;
    }

    if (!this.migratedStorage.get('migrated') && !this.model.get("migrated") ) {
      this._showWarning('migrated');
      return;
    }

    if (!this.limitStorage.get('limit') && this.model.get("limits_tables_exceeded")) {
      this._showWarning('limit');
      return;
    }

    this._hideWarning();

  },

  /**
  *  Check if the user has recently upgraded his account
  */
  _checkUpgradedUser: function() {
    // After know if the user has recently upgraded his account,
    // then render the stats
    if (config && !config.custom_com_hosted && config.account_host) {

      var self = this;

      $.ajax({
        url: '//' + config.account_host + '/account/' + this.model.get('username') + '/recently_upgraded',
        timeout: 5000,
        dataType: 'jsonp',
        success: function(r) {
          self.recently_upgraded = r.recently_upgraded;
          self._toggleWarnings();
        },
        error: function(e) {
          self._toggleWarnings();
        }
      });
    }

  },

  /*
  * Calculate user quotas status
  */
  _calculateQuotas: function() {

    this.model.set("table_quota_status",    this._calculateTableQuota());
    this.model.set("byte_quota_status",     this._calculateSpaceQuota());
    this.model.set("mapviews_quota_status", this._calculateMapViewsQuota());

  },

  _calculateTableQuota: function() {

    var quota = this.model.get("table_quota");
    var count = this.model.get("table_count");

    if (quota == null || quota == 0) return "green";

    var p = (count / quota * 100);

    if (p < 80) return "";
    if (p < 90) return "danger";

    return "boom";

  },

  _calculateSpaceQuota: function() {

    var quota           = this.model.get("byte_quota");
    var remaining_quota = this.model.get("remaining_byte_quota");

    if (quota == null || quota == 0) return "green";

    var p = ((quota - remaining_quota) / quota) * 100;

    if (p < 80) return "";
    if (p < 90) return "danger";

    return "boom";

  },

  _calculateMapViewsQuota: function() {

    var quota = this.model.get("api_calls_quota");

    if (quota == null || quota == 0) return "green";

    var sum = this._calcTotalMapViews();
    var p   = this._calcMapViewsPercentage(sum);

    if (p < 80) return "";
    if (p < 90) return "danger";

    return "boom";

  },

  _updateGraphs: function() {
    this._updateTableGraph();
    this._updateSpaceGraph();
    this._updateMapViewsGraph();
  },

  _updateTableGraph: function() {

    var quota  = this.model.get("table_quota");
    var count  = this.model.get("table_count");
    var status = this.model.get("table_quota_status");

    var p = 100, limit = "∞";

    if (quota != null && quota > 0) {
      p = (count / quota) * 100;
      limit = quota;
    }

    var text  = "" + count + " of " + limit + " tables created";
    var $el   = this.$el.find("section.stats .tables");

    this._updateGraph($el, p, text, status);

  },

  _updateSpaceGraph: function() {

    var quota           = this.model.get("byte_quota");
    var remaining_quota = this.model.get("remaining_byte_quota");
    var status          = this.model.get("byte_quota_status");

    var $el    = this.$el.find("section.stats .size");

    var space_stats = {};

    if (quota == null || quota == 0) {
      space_stats.total = "∞";
    } else {
      space_stats = this._bytesToSize(quota, (quota - remaining_quota));
    }

    var width = 100;
    var text = "You have " + space_stats.total + " space";

    if (quota != null && quota > 0) {
      width = (( space_stats.used / space_stats.total) * 100);
      text = "" + space_stats.used + " of " + space_stats.total + " used " + space_stats.size;
    }

    this._updateGraph($el, width, text, status);

  },

  _updateMapViewsGraph: function() {

    var status = this.model.get("mapviews_quota_status");

    var $el = this.$el.find("section.stats .mapviews");

    var sum   = this._calcTotalMapViews();
    var width = this._calcMapViewsPercentage(sum);

    var text = '' + this._formatNumber(sum) + ' map views in the last 30 days';

    this._updateGraph($el, width, text, status);

  },

  _updateGraph: function($el, percentage, message, status) {

    $el.find("p").html(message);

    $el.find(".progress span")
    .removeAttr("class").addClass(status)
    .animate({
      width: percentage + "%"
    }, 500);

  },

  _calcTotalMapViews: function() {
    return _.reduce(this.model.get("api_calls"), function(memo, num){ return memo + num; }, 0);
  },

  _calcMapViewsPercentage: function(map_views) {
    return (map_views / this.model.get("api_calls_quota")) * 100;
  },

  /*
  * Disabled the warning upgrade flash
  */
  _disableWarning: function(ev) {
    ev.preventDefault();

    if (this.recently_upgraded) {

      this.recently_upgraded = false;

    } else if (!this.limitStorage.get('limit') && this.warning_type == "limit") {

      this.limitStorage.set({ "limit": true });
      this.warning_type = null;

    } else if (!this.migratedStorage.get('migrated') && this.warning_type == "migrated") {

      this.migratedStorage.set({ "migrated": true });
      this.warning_type = null;

    }

    this._hideWarning();
  },

  /*
  * Show the warning upgrade flash
  */
  _showWarning: function(type) {

    this.warning_type = type;

    this.$el.find("section.warning")
    .removeClass("upgraded migrated limit")
    .addClass("visible " + type);
  },

  /*
  * Hide the warning upgrade flash
  */
  _hideWarning: function() {
    this.$el.find("section.warning").removeClass("visible");
  },

  /*
  * Show dedicated support
  */
  _showDedicatedSupport: function() {
    this.$el.closest("body").find("article.support").show();
  },

  /*
  * Hide dedicated support
  */
  _hideDedicatedSupport: function() {
    this.$el.closest("body").find("article.support").hide();
  },

  /*
  * Activate the table stats
  */
  _activate: function() {
    this.$el.addClass("active");
  },

  /*
  * Deactivate the table stats
  */
  _deactivate: function() {
    this.$el.removeClass("active");
  },

  /*
  * Convert bytes to any size
  */
  _bytesToSize: function(total_bytes, used_bytes) {
    var sizes = ['bytes', 'kilobytes', 'megabytes', 'gigabytes', 'terabytes'];
    if (total_bytes == 0) return 'n/a';
    var i = parseInt(Math.floor(Math.log(total_bytes) / Math.log(1024)));

    return { total: (total_bytes / Math.pow(1024, i)).toFixed(1), used: (used_bytes / Math.pow(1024, i)).toFixed(1), size: sizes[i] };
  },

  _formatNumber: function(str) {

    var amount = new String(str);
    amount = amount.split("").reverse();

    var output = "";

    for ( var i = 0; i <= amount.length-1; i++ ){

      output = amount[i] + output;
      if ((i+1) % 3 == 0 && (amount.length-1) !== i) output = ',' + output;

    }

    return output;
  }

});
<|endoftext|>


<commit_before>// Copyright (c) 2012 HIRAKI Satoru, https://github.com/Layzie
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(function(window, undefined) {
  'use strict';

  var _selectStorage = function _selectStorage(flag) {
    var storage;

    if (typeof flag !== 'boolean' && flag !== undefined) {
      throw new Error('2nd argument should be boolean');
    } else {
      if (flag === true || flag === undefined) {
        storage = localStorage;
      } else {
        storage = sessionStorage;
      }
    }

    return storage;
  };

  if (typeof window.RS === 'undefined') {
    window.RS = {};
  }

  window.RS = {
    put: function put(obj, flag) {
      var storage = _selectStorage(flag);

      if (typeof obj === 'object') {
        if (obj instanceof Array) {
          throw new Error('1st argument should be object');
        }
        for (var i in obj) {
          if (obj.hasOwnProperty(i)) {
            storage.setItem(i, JSON.stringify(obj[i]));
          }
        }
      } else {
        throw new Error('1st argument should be object');
      }
    },
    get: function get(key, flag) {
      var storage = _selectStorage(flag),
          selectKey = storage.getItem(key);

      if (typeof key === 'string') {
        if (selectKey) {
          return JSON.parse(selectKey);
        } else {
          console.log('This key is not in storage');
        }
      } else {
        throw new Error('1st argument should be string');
      }
    },
    remove: function remove(key, flag) {
      var storage = _selectStorage(flag);

      storage.removeItem(key);
    },
    clear: function clear(flag) {
      var storage = _selectStorage(flag);

      storage.clear();
    },
    is: function(key, flag) {
      var storage = _selectStorage(flag),
          selectKey = storage.getItem(key);

      if (typeof key === 'string') {
        if (selectKey) {
          return true;
        } else {
          return false;
        }
      } else {
        throw new Error('1st argument should be strings');
      }
    }
  };
})(this);

<commit_msg>add return statment<commit_after>// Copyright (c) 2012 HIRAKI Satoru, https://github.com/Layzie
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(function(window, undefined) {
  'use strict';

  var _selectStorage = function _selectStorage(flag) {
    var storage;

    if (typeof flag !== 'boolean' && flag !== undefined) {
      throw new Error('2nd argument should be boolean');
    } else {
      if (flag === true || flag === undefined) {
        storage = localStorage;
      } else {
        storage = sessionStorage;
      }
    }

    return storage;
  };

  if (typeof window.RS === 'undefined') {
    window.RS = {};
  }

  window.RS = {
    put: function put(obj, flag) {
      var storage = _selectStorage(flag);

      if (typeof obj === 'object') {
        if (obj instanceof Array) {
          throw new Error('1st argument should be object');
        }
        for (var i in obj) {
          if (obj.hasOwnProperty(i)) {
            storage.setItem(i, JSON.stringify(obj[i]));
          }
        }
      } else {
        throw new Error('1st argument should be object');
      }
    },
    get: function get(key, flag) {
      var storage = _selectStorage(flag),
          selectKey = storage.getItem(key);

      if (typeof key === 'string') {
        if (selectKey) {
          return JSON.parse(selectKey);
        } else {
          return console.log('This key is not in storage');
        }
      } else {
        throw new Error('1st argument should be string');
      }
    },
    remove: function remove(key, flag) {
      var storage = _selectStorage(flag);

      storage.removeItem(key);
    },
    clear: function clear(flag) {
      var storage = _selectStorage(flag);

      storage.clear();
    },
    is: function(key, flag) {
      var storage = _selectStorage(flag),
          selectKey = storage.getItem(key);

      if (typeof key === 'string') {
        if (selectKey) {
          return true;
        } else {
          return false;
        }
      } else {
        throw new Error('1st argument should be strings');
      }
    }
  };
})(this);

<|endoftext|>


<commit_before>/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/

'use strict';

// MODULES //

var tape = require( 'tape' );
var isUint32Array = require( '@stdlib/assert/is-uint32array' );
var beta = require( './../lib' );

// TESTS //

tape( 'main export is a function', function test( t ) {
	t.ok( true, __filename );
	t.equal( typeof beta, 'function', 'main export is a function' );
	t.end();
});

tape( 'attached to the main export is a method to generate pseudorandom number generators', function test( t ) {
	t.equal( typeof beta.factory, 'function', 'has `factory` method' );
	t.end();
});

tape( 'attached to the main export is the generator name', function test( t ) {
	t.equal( beta.NAME, 'beta', 'has `NAME` property' );
	t.end();
});

tape( 'attached to the main export is the underlying PRNG', function test( t ) {
	t.equal( typeof beta.PRNG, 'function', 'has `PRNG` property' );
	t.end();
});

tape( 'attached to the main export is the generator seed', function test( t ) {
	t.equal( isUint32Array( beta.seed ), true, 'has `seed` property' );
	t.end();
});

tape( 'attached to the main export is the generator state', function test( t ) {
	t.equal( isUint32Array( beta.state ), true, 'has `state` property' );
	t.end();
});

tape( 'attached to the main export is the generator state length', function test( t ) {
	t.equal( typeof beta.stateLength, 'number', 'has `stateLength` property' );
	t.end();
});

tape( 'attached to the main export is the generator state size', function test( t ) {
	t.equal( typeof beta.byteLength, 'number', 'has `byteLength` property' );
	t.end();
});

tape( 'the function returns pseudorandom numbers', function test( t ) {
	var r;
	var i;
	for ( i = 0; i < 1e2; i++ ) {
		r = beta( 2.0, 1.0 );
		t.strictEqual( typeof r, 'number', 'returns a number' );
		t.strictEqual( r >= 0.0, true, 'returns a nonnegative number' );
	}
	t.end();
});

tape( 'the function supports setting the generator state (alpha = beta > 1.5)', function test( t ) {
	var state;
	var arr;
	var i;

	// Move to a future state...
	for ( i = 0; i < 100; i++ ) {
		beta( 2.0, 2.0 );
	}
	// Capture the current state:
	state = beta.state;

	// Move to a future state...
	arr = [];
	for ( i = 0; i < 100; i++ ) {
		arr.push( beta( 2.0, 2.0 ) );
	}
	// Set the state:
	beta.state = state;

	// Replay previously generated values...
	for ( i = 0; i < 100; i++ ) {
		t.equal( beta( 2.0, 2.0 ), arr[ i ], 'returns expected value. i: '+i+'.' );
	}
	t.end();
});

tape( 'the function supports setting the generator state (alpha != beta > 1.0)', function test( t ) {
	var state;
	var arr;
	var i;

	// Move to a future state...
	for ( i = 0; i < 100; i++ ) {
		beta( 2.0, 5.0 );
	}
	// Capture the current state:
	state = beta.state;

	// Move to a future state...
	arr = [];
	for ( i = 0; i < 100; i++ ) {
		arr.push( beta( 2.0, 5.0 ) );
	}
	// Set the state:
	beta.state = state;

	// Replay previously generated values...
	for ( i = 0; i < 100; i++ ) {
		t.equal( beta( 2.0, 5.0 ), arr[ i ], 'returns expected value. i: '+i+'.' );
	}
	t.end();
});

tape( 'the function supports setting the generator state (alpha,beta <= 1.0)', function test( t ) {
	var state;
	var arr;
	var i;

	// Move to a future state...
	for ( i = 0; i < 100; i++ ) {
		beta( 0.5, 1.0 );
	}
	// Capture the current state:
	state = beta.state;

	// Move to a future state...
	arr = [];
	for ( i = 0; i < 100; i++ ) {
		arr.push( beta( 0.5, 1.0 ) );
	}
	// Set the state:
	beta.state = state;

	// Replay previously generated values...
	for ( i = 0; i < 100; i++ ) {
		t.equal( beta( 0.5, 1.0 ), arr[ i ], 'returns expected value. i: '+i+'.' );
	}
	t.end();
});
<commit_msg>Update tests<commit_after>/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/

'use strict';

// MODULES //

var tape = require( 'tape' );
var isUint32Array = require( '@stdlib/assert/is-uint32array' );
var beta = require( './../lib' );

// TESTS //

tape( 'main export is a function', function test( t ) {
	t.ok( true, __filename );
	t.equal( typeof beta, 'function', 'main export is a function' );
	t.end();
});

tape( 'attached to the main export is a method to generate pseudorandom number generators', function test( t ) {
	t.equal( typeof beta.factory, 'function', 'has method' );
	t.end();
});

tape( 'attached to the main export is the generator name', function test( t ) {
	t.equal( beta.NAME, 'beta', 'has property' );
	t.end();
});

tape( 'attached to the main export is the underlying PRNG', function test( t ) {
	t.equal( typeof beta.PRNG, 'function', 'has property' );
	t.end();
});

tape( 'attached to the main export is the generator seed', function test( t ) {
	t.equal( isUint32Array( beta.seed ), true, 'has property' );
	t.end();
});

tape( 'attached to the main export is the generator seed length', function test( t ) {
	t.equal( typeof beta.seedLength, 'number', 'has property' );
	t.end();
});

tape( 'attached to the main export is the generator state', function test( t ) {
	t.equal( isUint32Array( beta.state ), true, 'has property' );
	t.end();
});

tape( 'attached to the main export is the generator state length', function test( t ) {
	t.equal( typeof beta.stateLength, 'number', 'has property' );
	t.end();
});

tape( 'attached to the main export is the generator state size', function test( t ) {
	t.equal( typeof beta.byteLength, 'number', 'has property' );
	t.end();
});

tape( 'the function returns pseudorandom numbers', function test( t ) {
	var r;
	var i;
	for ( i = 0; i < 1e2; i++ ) {
		r = beta( 2.0, 1.0 );
		t.strictEqual( typeof r, 'number', 'returns a number' );
		t.strictEqual( r >= 0.0, true, 'returns a nonnegative number' );
	}
	t.end();
});

tape( 'the function supports setting the generator state (alpha = beta > 1.5)', function test( t ) {
	var state;
	var arr;
	var i;

	// Move to a future state...
	for ( i = 0; i < 100; i++ ) {
		beta( 2.0, 2.0 );
	}
	// Capture the current state:
	state = beta.state;

	// Move to a future state...
	arr = [];
	for ( i = 0; i < 100; i++ ) {
		arr.push( beta( 2.0, 2.0 ) );
	}
	// Set the state:
	beta.state = state;

	// Replay previously generated values...
	for ( i = 0; i < 100; i++ ) {
		t.equal( beta( 2.0, 2.0 ), arr[ i ], 'returns expected value. i: '+i+'.' );
	}
	t.end();
});

tape( 'the function supports setting the generator state (alpha != beta > 1.0)', function test( t ) {
	var state;
	var arr;
	var i;

	// Move to a future state...
	for ( i = 0; i < 100; i++ ) {
		beta( 2.0, 5.0 );
	}
	// Capture the current state:
	state = beta.state;

	// Move to a future state...
	arr = [];
	for ( i = 0; i < 100; i++ ) {
		arr.push( beta( 2.0, 5.0 ) );
	}
	// Set the state:
	beta.state = state;

	// Replay previously generated values...
	for ( i = 0; i < 100; i++ ) {
		t.equal( beta( 2.0, 5.0 ), arr[ i ], 'returns expected value. i: '+i+'.' );
	}
	t.end();
});

tape( 'the function supports setting the generator state (alpha,beta <= 1.0)', function test( t ) {
	var state;
	var arr;
	var i;

	// Move to a future state...
	for ( i = 0; i < 100; i++ ) {
		beta( 0.5, 1.0 );
	}
	// Capture the current state:
	state = beta.state;

	// Move to a future state...
	arr = [];
	for ( i = 0; i < 100; i++ ) {
		arr.push( beta( 0.5, 1.0 ) );
	}
	// Set the state:
	beta.state = state;

	// Replay previously generated values...
	for ( i = 0; i < 100; i++ ) {
		t.equal( beta( 0.5, 1.0 ), arr[ i ], 'returns expected value. i: '+i+'.' );
	}
	t.end();
});
<|endoftext|>


<commit_before>// 78: Promise - API overview
// To do: make all tests pass, leave the assert lines unchanged!
// Follow the hints of the failure messages!

describe('`Promise` API overview', function() {
  it('`new Promise()` requires a function as param', () => {
    //// const param = null;
    const param = () => {};
    assert.doesNotThrow(() => { new Promise(param); });
  });
  describe('resolving a promise', () => {
    // reminder: the test passes when a fulfilled promise is returned
    it('via constructor parameter `new Promise((resolve) => { resolve(); })`', () => {
      //// const param = () => { resolve(); };
      const param = (resolve) => { resolve(); };
      return new Promise(param);
    });
    it('using `Promise.resolve()`', () => {
      //// return Promise.reject('all fine');
      return Promise.resolve('all fine');
    });
  });
  describe('a rejected promise', () => {
    it('using the constructor parameter', (done) => {
      //// const promise = new Promise((reject) => { reject(); });
      const promise = new Promise((_, reject) => { reject(); });
      promise
        .then(() => done(new Error('The promise is expected to be rejected.')))
        .catch(() => done());
    });
    it('via `Promise.reject()`', (done) => {
      //// const promise = Promise.resolve();
      const promise = Promise.reject();
      promise
        .then(() => done(new Error('The promise is expected to be rejected.')))
        .catch(() => done());
    });
  });
  const resolvingPromise = Promise.resolve();
  const rejectingPromise = Promise.reject();
  describe('`Promise.all()`', () => {
    it('`Promise.all([p1, p2])` resolves when all promises resolve', () =>
      //// Promise.all([resolvingPromise, rejectingPromise, resolvingPromise])
      Promise.all([resolvingPromise, resolvingPromise])
    );
    it('`Promise.all([p1, p2])` rejects when a promise is rejected', (done) => {
      //// Promise.all([resolvingPromise])
      Promise.all([resolvingPromise, rejectingPromise ])
        .then(() => done(new Error('The promise is expected to be rejected.')))
        .catch(() => done())
    });
  });
  describe('`Promise.race()`', () => {
    it('`Promise.race([p1, p2])` resolves when one of the promises resolves', () =>
      //// Promise.race([rejectingPromise])
      Promise.race([resolvingPromise, rejectingPromise])
    );
    it('`Promise.race([p1, p2])` rejects when one of the promises rejects', (done) => {
      //// Promise.race([resolvingPromise])
      Promise.race([rejectingPromise, resolvingPromise])
        .then(() => done(new Error('The promise is expected to be rejected.')))
        .catch(() => done())
    });
    it('`Promise.race([p1, p2])` order matters (and timing)', () =>
      //// Promise.race([rejectingPromise, resolvingPromise])
      Promise.race([resolvingPromise, rejectingPromise])
    );
  });
});
<commit_msg>Fix the names, since the assignment makes the promises resolved/rejected.<commit_after>// 78: Promise - API overview
// To do: make all tests pass, leave the assert lines unchanged!
// Follow the hints of the failure messages!

describe('`Promise` API overview', function() {
  it('`new Promise()` requires a function as param', () => {
    //// const param = null;
    const param = () => {};
    assert.doesNotThrow(() => { new Promise(param); });
  });
  describe('resolving a promise', () => {
    // reminder: the test passes when a fulfilled promise is returned
    it('via constructor parameter `new Promise((resolve) => { resolve(); })`', () => {
      //// const param = () => { resolve(); };
      const param = (resolve) => { resolve(); };
      return new Promise(param);
    });
    it('using `Promise.resolve()`', () => {
      //// return Promise.reject('all fine');
      return Promise.resolve('all fine');
    });
  });
  describe('a rejected promise', () => {
    it('using the constructor parameter', (done) => {
      //// const promise = new Promise((reject) => { reject(); });
      const promise = new Promise((_, reject) => { reject(); });
      promise
        .then(() => done(new Error('The promise is expected to be rejected.')))
        .catch(() => done());
    });
    it('via `Promise.reject()`', (done) => {
      //// const promise = Promise.resolve();
      const promise = Promise.reject();
      promise
        .then(() => done(new Error('The promise is expected to be rejected.')))
        .catch(() => done());
    });
  });
  const resolvedPromise = Promise.resolve();
  const rejectedPromise = Promise.reject();
  describe('`Promise.all()`', () => {
    it('`Promise.all([p1, p2])` resolves when all promises resolve', () =>
      //// Promise.all([resolvedPromise, rejectedPromise, resolvedPromise])
      Promise.all([resolvedPromise, resolvedPromise])
    );
    it('`Promise.all([p1, p2])` rejects when a promise is rejected', (done) => {
      //// Promise.all([resolvedPromise])
      Promise.all([resolvedPromise, rejectedPromise ])
        .then(() => done(new Error('The promise is expected to be rejected.')))
        .catch(() => done())
    });
  });
  describe('`Promise.race()`', () => {
    it('`Promise.race([p1, p2])` resolves when one of the promises resolves', () =>
      //// Promise.race([rejectedPromise])
      Promise.race([resolvedPromise, rejectedPromise])
    );
    it('`Promise.race([p1, p2])` rejects when one of the promises rejects', (done) => {
      //// Promise.race([resolvedPromise])
      Promise.race([rejectedPromise, resolvedPromise])
        .then(() => done(new Error('The promise is expected to be rejected.')))
        .catch(() => done())
    });
    it('`Promise.race([p1, p2])` order matters (and timing)', () =>
      //// Promise.race([rejectedPromise, resolvedPromise])
      Promise.race([resolvedPromise, rejectedPromise])
    );
  });
});
<|endoftext|>


<commit_before>// 'use strict';

var schedule = require('node-schedule');
var slack = require('./slack.js');

module.exports = scheduler;

function scheduler() {
  var hrr11 = slack.students.getChannelGroupOrDMByName('hrr11');
  var hrr12 = slack.students.getChannelGroupOrDMByName('hrr12');
  var hrr13 = slack.students.getChannelGroupOrDMByName('hrr13');
  var general = slack.students.getChannelGroupOrDMByName('general');
  var test = slack.students.getChannelGroupOrDMByName('codydaig');

  // var daily9am = new schedule.RecurrenceRule();
  // daily9am.dayOfWeek = [new Schedule.Range(1,6)];
  // daily9am.hour = 12;
  // daily9am.minute = 30;

  // var obj = {
  //   when: daily9am,
  //   who: [test],
  //   message: 'Testing of the 9am Logic'
  // };

  //var date = new Date(2016, 01, 11, 11, 00, 0);
  // var date2 = new Date(2016, 01, 11, 11, 55, 0);

  // var j = schedule.scheduleJob(date, function(){
  //   var msg = '<!channel> ';
  //   hrr11.send(msg);
  //   hrr12.send(msg);
  //   hrr13.send(msg);
  // }.bind(this));

  // var k = schedule.scheduleJob(obj.when, function(){
  //   var msg = 'Good Morning!!!';
  //   test.send(obj.message);
  //   // hrr11.send(obj.message);
  //   // hrr12.send(obj.message);
  //   // hrr13.send(obj.message);
  // }.bind(this));
}
<commit_msg>debugging<commit_after>// 'use strict';

var schedule = require('node-schedule');
var slack = require('./slack.js');

module.exports = scheduler;

function scheduler() {
  var hrr11 = slack.students.getChannelGroupOrDMByName('hrr11');
  var hrr12 = slack.students.getChannelGroupOrDMByName('hrr12');
  var hrr13 = slack.students.getChannelGroupOrDMByName('hrr13');
  var general = slack.students.getChannelGroupOrDMByName('general');
  var test = slack.students.getChannelGroupOrDMByName('codydaig');

  var daily9am = new schedule.RecurrenceRule();
  daily9am.dayOfWeek = [1,2,3,4,5,6];
  daily9am.hour = 12;
  daily9am.minute = 30;

  // var obj = {
  //   when: daily9am,
  //   who: [test],
  //   message: 'Testing of the 9am Logic'
  // };

  //var date = new Date(2016, 01, 11, 11, 00, 0);
  // var date2 = new Date(2016, 01, 11, 11, 55, 0);

  // var j = schedule.scheduleJob(date, function(){
  //   var msg = '<!channel> ';
  //   hrr11.send(msg);
  //   hrr12.send(msg);
  //   hrr13.send(msg);
  // }.bind(this));

  // var k = schedule.scheduleJob(obj.when, function(){
  //   var msg = 'Good Morning!!!';
  //   test.send(obj.message);
  //   // hrr11.send(obj.message);
  //   // hrr12.send(obj.message);
  //   // hrr13.send(obj.message);
  // }.bind(this));
}
<|endoftext|>


<commit_before>var Utils        = require("./utils")
  , ModelFactory = require("./model-factory")
  , DataTypes    = require('./data-types')
  , ModelManager = require("./model-manager")

module.exports = (function() {
  var Sequelize = function(database, username, password, options) {
    options = options || {}

    Utils._.reject(options, function(_, key) {
      return ["host", "port", "disableTableNameModification"].indexOf(key) > -1
    })

    this.options = options
    this.options.connector = this.options.connector || 'mysql'
    this.config = {
      database: database,
      username: username,
      password: (( (["", null, false].indexOf(password) > -1) || (typeof password == 'undefined')) ? null : password),
      host    : options.host || 'localhost',
      port    : options.port || 3306
    }

    var ConnectorManager = require("./connectors/" + this.options.connector + "/connector-manager")

    this.modelManager = new ModelManager(this)
    this.connectorManager = new ConnectorManager(this, this.config)
  }

  Sequelize.Utils = Utils
  Sequelize.Utils._.map(DataTypes, function(sql, accessor) { Sequelize[accessor] = sql})

  Sequelize.prototype.define = function(modelName, attributes, options) {
    options = options || {}

    if(this.options.define)
      options = Sequelize.Utils.merge(options, this.options.define)

    var model = this.modelManager.addModel(new ModelFactory(modelName, attributes, options))

    return model
  }

  Sequelize.prototype.import = function(path) {
    var defineCall = require(path)
    return defineCall(this, DataTypes)
  }

  Sequelize.prototype.query = function(sql, callee, options) {
    options = options || {}

    if(this.options.query)
      options = Sequelize.Utils.merge(options, this.options.query)

    options.logging = this.options.hasOwnProperty('logging') ? this.options.logging : true

    return this.connectorManager.query(sql, callee, options)
  }

  Sequelize.prototype.sync = function(options) {
    options = options || {}

    if(this.options.sync)
      options = Sequelize.Utils.merge(options, this.options.sync)

    var self = this
    var eventEmitter = new Utils.CustomEventEmitter(function() {
      var chainer = new Utils.QueryChainer

      self.modelManager.models.forEach(function(model) { chainer.add(model.sync(options)) })

      chainer
        .run()
        .on('success', function() { eventEmitter.emit('success', null) })
        .on('failure', function(err) { eventEmitter.emit('failure', err) })
    })
    return eventEmitter.run()
  }

  Sequelize.prototype.drop = function() {
    var self = this

    return new Utils.CustomEventEmitter(function(emitter) {
      var chainer = new Utils.QueryChainer

      self.modelManager.models.forEach(function(model) { chainer.add(model.drop()) })

      chainer
        .run()
        .on('success', function() { emitter.emit('success', null) })
        .on('failure', function(err) { emitter.emit('failure', err) })
    }).run()
  }

  return Sequelize
})()
<commit_msg>better option usage<commit_after>var Utils        = require("./utils")
  , ModelFactory = require("./model-factory")
  , DataTypes    = require('./data-types')
  , ModelManager = require("./model-manager")

module.exports = (function() {
  var Sequelize = function(database, username, password, options) {
    this.options = Utils._.extend({
      connector: 'mysql',
      host: 'localhost',
      port: 3306,
    }, options || {})

    this.config = {
      database: database,
      username: username,
      password: (( (["", null, false].indexOf(password) > -1) || (typeof password == 'undefined')) ? null : password),
      host    : this.options.host,
      port    : this.options.port
    }

    var ConnectorManager = require("./connectors/" + this.options.connector + "/connector-manager")

    this.modelManager = new ModelManager(this)
    this.connectorManager = new ConnectorManager(this, this.config)
  }

  Sequelize.Utils = Utils
  Sequelize.Utils._.map(DataTypes, function(sql, accessor) { Sequelize[accessor] = sql})

  Sequelize.prototype.define = function(modelName, attributes, options) {
    options = options || {}

    if(this.options.define)
      options = Sequelize.Utils.merge(options, this.options.define)

    var model = this.modelManager.addModel(new ModelFactory(modelName, attributes, options))

    return model
  }

  Sequelize.prototype.import = function(path) {
    var defineCall = require(path)
    return defineCall(this, DataTypes)
  }

  Sequelize.prototype.query = function(sql, callee, options) {
    options = options || {}

    if(this.options.query)
      options = Sequelize.Utils.merge(options, this.options.query)

    options.logging = this.options.hasOwnProperty('logging') ? this.options.logging : true

    return this.connectorManager.query(sql, callee, options)
  }

  Sequelize.prototype.sync = function(options) {
    options = options || {}

    if(this.options.sync)
      options = Sequelize.Utils.merge(options, this.options.sync)

    var self = this
    var eventEmitter = new Utils.CustomEventEmitter(function() {
      var chainer = new Utils.QueryChainer

      self.modelManager.models.forEach(function(model) { chainer.add(model.sync(options)) })

      chainer
        .run()
        .on('success', function() { eventEmitter.emit('success', null) })
        .on('failure', function(err) { eventEmitter.emit('failure', err) })
    })
    return eventEmitter.run()
  }

  Sequelize.prototype.drop = function() {
    var self = this

    return new Utils.CustomEventEmitter(function(emitter) {
      var chainer = new Utils.QueryChainer

      self.modelManager.models.forEach(function(model) { chainer.add(model.drop()) })

      chainer
        .run()
        .on('success', function() { emitter.emit('success', null) })
        .on('failure', function(err) { emitter.emit('failure', err) })
    }).run()
  }

  return Sequelize
})()
<|endoftext|>


<commit_before>'use babel';

import { CompositeDisposable, Disposable, Point, Range } from 'atom';

export default {
  subscriptions: null,

  config: {
    autoHardWrap: {
      type: 'boolean',
      default: true
    },
    columnGuide: {
      type: 'integer',
      default: 80
    }
  },

  // FIXME: May not work for Windows.
  newline: /\n/,

  activate(state) {
    // Events subscribed to in atom's system can be easily cleaned up with a CompositeDisposable
    this.subscriptions = new CompositeDisposable();

    // Register command that toggles this view
    this.subscriptions.add(atom.commands.add('atom-workspace', {
      'slickwrap:toggle': () => this.toggle()
    }));

    // Register keyboard event.
    var editor = atom.workspace.getActiveTextEditor();
    var editorView = atom.views.getView(editor);
    this.subscribeEvent(editorView, 'keyup', (event) => {
      // keycode: 32 -> space, 13 -> enter, 9 -> tab
      var code = event.keyCode;
      if (code == 32 || code == 13 || code == 9) {
        if (atom.config.get('slickwrap.autoHardWrap')) {
          this.adjust(code);
        }
      }
    });
  },

  subscribeEvent(observed, type, callback) {
    observed.addEventListener(type, callback);
    this.subscriptions.add(new Disposable(() => {
      observed.removeEventListener(type, callback)}));
  },

  deactivate() {
    this.subscriptions.dispose();
  },

  toggle() {
    this.adjust();
  },
    // var buffer = editor.getBuffer();
    // var cursorPosition = editor.getCursorBufferPosition();
    // var cursorIndex = buffer.characterIndexForPosition(cursorPosition);

  adjustRow(row) {
    var editor = atom.workspace.getActiveTextEditor();
    var buffer = editor.getBuffer();
    var maxLen = atom.config.get('slickwrap.columnGuide');

    // if the line that contains cursor is longer than our limitation,
    // wrap the line at the closest whitespace before the limitation column.
    var text = buffer.lineForRow(row);
    console.log(text);

    // console.log(text);

    // text is longer than our column guide
    // adjust the currentline by inserting newline character(s).
    if (text.length > maxLen) {
      // |i am a cake
      // |l         r
      var l = 0;
      var r = text.length - 1;

      // skip white spaces
      while (this.isWS(text[l]) && l < r) ++l;
      while (this.isWS(text[r]) && l < r) --r;

      // the actual text is not exceeding boundary so ignore
      if (r < maxLen || l >= r) return;

      // find left "gap", if we can find any, wrap.
      if (l < maxLen) {
        var li = maxLen;
        while (!this.isWS(text[li]) && li > l) --li;
        if (li == l) {
          var ri = maxLen;
          while (!this.isWS(text[ri]) && ri < r) ++ ri;
          if (ri == r) return;
          var rl = ri;
          while (this.isWS(text[rl])) --rl;
          var rr = ri;
          while (this.isWS(text[rr])) ++rr;
          this.setText(row, rl+1, rr);
        }
        var ll = li;
        while (this.isWS(text[ll])) --ll;
        var lr = li;
        while (this.isWS(text[lr])) ++lr;
        this.setText(row, ll+1, lr);
      //   var left = new Point(cursor.row, wrap);
      //   var right = new Point(cursor.row, r + 1);
      //   buffer.setTextInRange(new Range(left, right), '\n');

      }

      // find right "gap" if no left "gap", and wrap if we find any

      // var r = text.length - 1
      //
      // // find the most recent whitespace character (' ' or '\t')
      // // ignore the leading spaces
      // var l = 0;
      // while (this.isWhiteSpace(text[l]) && l < cursor.column) {
      //   l += 1;
      // }
      //
      // r = maxLen
      // var r = cursor.column - 2 > maxLen ? maxLen : cursor.column - 2;
      // while (!this.isWhiteSpace(text[r]) && r > l) {
      //   r -= 1;
      // }
      //
      // var wrap = r;
      // while (wrap > l && this.isWhiteSpace(text[wrap - 1])) {
      //   wrap -= 1;
      // }
      //
      // if (wrap > l && wrap <= r) {
      //   var left = new Point(cursor.row, wrap);
      //   var right = new Point(cursor.row, r + 1);
      //   buffer.setTextInRange(new Range(left, right), '\n');
      // }

      // we wrap right after the character before ws
    }

  },

  setText(row, left, right) {
    var editor = atom.workspace.getActiveTextEditor();
    var buffer = editor.getBuffer();
    var lbound = new Point(row, left);
    var rbound = new Point(row, right);
    buffer.setTextInRange(new Range(lbound, rbound), '\n');
  },

  // Adjust the current line and set cursor to the end.
  // mimicing the emacs behavior.
  adjust(code) {
    var editor = atom.workspace.getActiveTextEditor();
    var cursor = editor.getCursorBufferPosition();

    // if it's enter, we look at the previous row
    var row = (code == 13) ? cursor.row - 1 : cursor.row;

    this.adjustRow(row);

    // var editor = atom.workspace.getActiveTextEditor();
    // var endColumn = atom.config.get('slickwrap.columnGuide');
    // var cursorPos = editor.getCursorBufferPosition();
    // if (cursorPos.column <= endColumn) {
    //   return;
    // }
    //
    // var text = editor.getText();
    // var lines = text.split(/\r?\n/);
    // var resultLines = [];
    // var cursorPosition = editor.getCursorBufferPosition();
    // var i = 0;
    // while (i < lines.length) {
    //   resultLines.push.apply(resultLines, this.adjusted(lines[i], endColumn, pos, i));
    //   ++i;
    // }
    //
    // var len = resultLines.length;
    // if (len > 0) {
    //   // FIXME: This doesn't support windows.
    //   var newText = resultLines.join('\n');
    //   editor.setText(newText);
    //   var lastRow = len - 1;
    //   var lastCol = resultLines[len - 1].length - 1;
    //   editor.setCursorBufferPosition([lastRow, lastCol]);
    // }
  },

  isWS(ch) {
    return ch == ' ' || ch == '\t';
  },

  // adjusted(line, limit, cursorPosition, index) {
    // var resultLines = [];
    // if (line && line.length > limit) {
    //   var currentLength = 0;
    //   var currentLine = "";
    //   var lineRemaining = line;
    //   while (true) {
    //     var ws = lineRemaining.search(/\s/);
    //     if (ws < 0) {
    //       ws = lineRemaining.length - 1;
    //     }
    //     currentLength += (ws + 1);
    //     if (currentLength > limit) {
    //       break;
    //     }
    //     currentLine += lineRemaining.substring(0, ws + 1);
    //     lineRemaining = lineRemaining.substring(ws + 1);
    //   }
    //   resultLines.push(currentLine)
    //   resultLines.push.apply(resultLines, this.adjusted(lineRemaining, limit));
    // }
    // else {
    //   resultLines.push(line);
    // }
    // return resultLines;
  // },

};
<commit_msg>Cleaning up and fixed a bug that wraps a long line.<commit_after>'use babel';

import { CompositeDisposable, Disposable, Point, Range } from 'atom';

export default {
  subscriptions: null,

  config: {
    autoHardWrap: {
      type: 'boolean',
      default: true
    },
    columnGuide: {
      type: 'integer',
      default: 80
    }
  },

  // FIXME: May not work for Windows.
  newline: /\n/,

  activate(state) {
    // Events subscribed to in atom's system can be
    // easily cleaned up with a CompositeDisposable
    this.subscriptions = new CompositeDisposable();

    // Register command that toggles this view
    this.subscriptions.add(atom.commands.add('atom-workspace', {
      'slickwrap:toggle': () => this.toggle()
    }));

    // Register keyboard event.
    var editor = atom.workspace.getActiveTextEditor();
    var editorView = atom.views.getView(editor);
    this.subscribeEvent(editorView, 'keyup', (event) => {
      // keycode: 32 -> space, 13 -> enter, 9 -> tab
      var code = event.keyCode;
      if (code == 32 || code == 13 || code == 9) {
        if (atom.config.get('slickwrap.autoHardWrap')) {
          this.adjust(code);
        }
      }
    });
  },

  subscribeEvent(observed, type, callback) {
    observed.addEventListener(type, callback);
    this.subscriptions.add(new Disposable(() => {
      observed.removeEventListener(type, callback)}));
  },

  deactivate() {
    this.subscriptions.dispose();
  },

  toggle() {
    this.adjust();
  },
    // var buffer = editor.getBuffer();
    // var cursorPosition = editor.getCursorBufferPosition();
    // var cursorIndex = buffer.characterIndexForPosition(cursorPosition);

  adjustRow(row) {
    var editor = atom.workspace.getActiveTextEditor();
    var buffer = editor.getBuffer();
    var maxLen = atom.config.get('slickwrap.columnGuide');

    // if the line that contains cursor is longer than our limitation,
    // wrap the line at the closest whitespace before the limitation column.
    var text = buffer.lineForRow(row);
    console.log(text);

    // text is longer than our column guide
    // adjust the currentline by inserting newline character(s).
    if (text.length > maxLen) {
      // |i am a cake
      // |l         r
      var l = 0;
      var r = text.length - 1;

      // skip white spaces
      while (this.isWS(text[l]) && l < r) ++l;
      while (this.isWS(text[r]) && l < r) --r;

      // the actual text is not exceeding boundary so ignore
      if (r < maxLen || l >= r) return;

      // find left "gap", if we can find any, wrap.
      if (l < maxLen) {
        var li = maxLen;
        while (!this.isWS(text[li]) && li > l) --li;
        if (li == l) {
          var ri = maxLen;
          while (!this.isWS(text[ri]) && ri < r) ++ ri;
          if (ri == r) return;
          var rl = ri;
          while (this.isWS(text[rl])) --rl;
          var rr = ri;
          while (this.isWS(text[rr])) ++rr;
          this.setText(row, rl+1, rr);
          return;
        }
        var ll = li;
        while (this.isWS(text[ll])) --ll;
        var lr = li;
        while (this.isWS(text[lr])) ++lr;
        this.setText(row, ll+1, lr);
      }
    }

  },

  setText(row, left, right) {
    var editor = atom.workspace.getActiveTextEditor();
    var buffer = editor.getBuffer();
    var lbound = new Point(row, left);
    var rbound = new Point(row, right);
    buffer.setTextInRange(new Range(lbound, rbound), '\n');
  },

  // Adjust the current line and set cursor to the end.
  // mimicing the emacs behavior.
  adjust(code) {
    var editor = atom.workspace.getActiveTextEditor();
    var cursor = editor.getCursorBufferPosition();

    // if it's enter, we look at the previous row
    var row = (code == 13) ? cursor.row - 1 : cursor.row;

    this.adjustRow(row);
  },

  isWS(ch) {
    return ch == ' ' || ch == '\t';
  },

};
<|endoftext|>


<commit_before>var tls = require('tls');
var fs = require('fs');
var net = require('net');

var options = null;

exports.createClient = function (options, callback) {
  options.client = true;
  createComponent(options, callback);
};

exports.createServer = function (options, callback) {
  options.server = true;
  createComponent(options, callback);
};

var Log = {"error":0, "warning":1, "info":2, "verbose":3};
exports.Log = Log;

function createComponent(options, callback) {

  function log(level, message) {
		if (level <= options.loglevel) {
      switch(level)
      {
      case 0:
        console.error(message);
        break;
      case 1:
        console.warn(message);
        break;
      case 2:
      case 3:
        console.log(message);
        break;
      default:
        console.log(message);
      }
    }
	}

  callback = callback || function () { };

  if (options.client && options.server || !options.client && !options.server) {
    log(Log.error,'got invalid options');
    throw new Error('invalid ssl tunnel instantiation - should be server or client');
  }

  var isClient = options.client;

  var clientPort = options.client_port;
  var serverPort = options.server_port;

  var clientHost = options.client_host;

  var clientPackage = isClient ? tls : net;
  var serverPackage = isClient ? net : tls;

  // options for the listener
  var serverOptions = {};
  if (!isClient) {
    serverOptions = {

      // read the server certificate
      key: fs.readFileSync(options.server_private_cert),
      cert: fs.readFileSync(options.server_public_cert),

      // request client certificate
      requestCert: true,

      // reject unauthorized requests
      rejectUnauthorized: true,

      // validate the CA of the client certificate
      ca: [fs.readFileSync(options.client_public_cert)]
    };
  }

  // options for the client socket
  var clientOptions = {};
  if (isClient) {
    clientOptions = {

      // read the client certificate
      key: fs.readFileSync(options.client_private_cert),
      cert: fs.readFileSync(options.client_public_cert),

      // get public server certificate and mark it as approved
      ca: [fs.readFileSync(options.server_public_cert)]
    };
  }

  var server = serverPackage.createServer(serverOptions, function (proxySocket) {

    // the socket to the service (either ssltunnel server or real backend server)
    var serviceSocket = null;

    // pause the input stream until the connection is established
    proxySocket.pause();

    // connect to the server
    if (isClient) {
      clientOptions.socket = new net.Socket();
      clientOptions.socket.on('connect', function () {
        clientOptions.socket.setKeepAlive(true, 30000);
      });
      clientOptions.socket.connect(clientPort, clientHost);
      serviceSocket = clientPackage.connect(clientPort, clientHost, clientOptions);
    }
    else {
      serviceSocket = clientPackage.connect(clientPort, clientHost);
    }

    // on secureConnect (for ssltunnel client)
    serviceSocket.on("secureConnect", function () {

      log(Log.info,'Connected to the ssltunnel server');

      // pipe service stream to client stream
      // piple client stream to service stream
      // resume the client stream
      serviceSocket.pipe(proxySocket);
      proxySocket.pipe(serviceSocket);
      proxySocket.resume();
    });

    // on connect (for ssltunnel server)
    serviceSocket.on("connect", function () {

      log(Log.info,'Connected to the real BE server');
      serviceSocket.setKeepAlive(true, 30000);

      // pipe service stream to client stream
      // piple client stream to service stream
      // resume the client stream
      serviceSocket.pipe(proxySocket);
      proxySocket.pipe(serviceSocket);
      proxySocket.resume();
    });

    // check that we got no errors when talking to the server
    serviceSocket.on("error", function (exception) {

      log(Log.info,'Error communicating with the server. Error: ' + JSON.stringify(exception));
      proxySocket.end();

    });

    // check that we got no errors when talking to the client
    proxySocket.on("error", function (exception) {

      log(Log.info,'Error communicating with the client. Error: ' + JSON.stringify(exception));
      serviceSocket.end();

    });

    // print diagnostics when connection to server ends
    serviceSocket.on("end", function () {
      log(Log.verbose,'connection to server was closed');
    });

    // print diagnostics when connection to client ends
    proxySocket.on("end", function () {
      log(Log.verbose,'connection to client was closed');
    });
  });

  server.listen(serverPort);

  // calls the callback when the server is in listening state with the actual port
  server.on("listening", function () {
    if (isClient) {
      log(Log.info,'Running \'client\' role. Listening on ' + server.address().port +
            ', encrypting and forwarding to ssltunnel\'s server on ' + options.client_host + ':' + options.client_port);
    } else {
      log(Log.info,'Running \'server\' role. Listening on ' + server.address().port +
            ', decrypting and forwarding to real server machine on ' + options.client_host + ':' + options.client_port);
    }
    callback(null, server.address().port);
  });
}

<commit_msg>fix keep-alive<commit_after>var tls = require('tls');
var fs = require('fs');
var net = require('net');

var options = null;

exports.createClient = function (options, callback) {
  options.client = true;
  createComponent(options, callback);
};

exports.createServer = function (options, callback) {
  options.server = true;
  createComponent(options, callback);
};

var Log = {"error":0, "warning":1, "info":2, "verbose":3};
exports.Log = Log;

function createComponent(options, callback) {

  function log(level, message) {
		if (level <= options.loglevel) {
      switch(level)
      {
      case 0:
        console.error(message);
        break;
      case 1:
        console.warn(message);
        break;
      case 2:
      case 3:
        console.log(message);
        break;
      default:
        console.log(message);
      }
    }
	}

  callback = callback || function () { };

  if (options.client && options.server || !options.client && !options.server) {
    log(Log.error,'got invalid options');
    throw new Error('invalid ssl tunnel instantiation - should be server or client');
  }

  var isClient = options.client;

  var clientPort = options.client_port;
  var serverPort = options.server_port;

  var clientHost = options.client_host;

  var clientPackage = isClient ? tls : net;
  var serverPackage = isClient ? net : tls;

  // options for the listener
  var serverOptions = {};
  if (!isClient) {
    serverOptions = {

      // read the server certificate
      key: fs.readFileSync(options.server_private_cert),
      cert: fs.readFileSync(options.server_public_cert),

      // request client certificate
      requestCert: true,

      // reject unauthorized requests
      rejectUnauthorized: true,

      // validate the CA of the client certificate
      ca: [fs.readFileSync(options.client_public_cert)]
    };
  }

  // options for the client socket
  var clientOptions = {};
  if (isClient) {
    clientOptions = {

      // read the client certificate
      key: fs.readFileSync(options.client_private_cert),
      cert: fs.readFileSync(options.client_public_cert),

      // get public server certificate and mark it as approved
      ca: [fs.readFileSync(options.server_public_cert)]
    };
  }

  var server = serverPackage.createServer(serverOptions, function (proxySocket) {

    // the socket to the service (either ssltunnel server or real backend server)
    var serviceSocket = null;

    // pause the input stream until the connection is established
    proxySocket.pause();

    // connect to the server
    if (isClient) {
      serviceSocket = clientPackage.connect(clientPort, clientHost, clientOptions);
    }
    else {
      serviceSocket = clientPackage.connect(clientPort, clientHost);
    }

    // on secureConnect (for ssltunnel client)
    serviceSocket.on("secureConnect", function () {

      log(Log.info,'Connected to the ssltunnel server');

      // set keep alive for every 30 sec to fight Azure's balancer
      // connection closing (after 1 min of inactivity)
      serviceSocket.socket.setKeepAlive(true, 30000);

      // pipe service stream to client stream
      // piple client stream to service stream
      // resume the client stream
      serviceSocket.pipe(proxySocket);
      proxySocket.pipe(serviceSocket);
      proxySocket.resume();
    });

    // on connect (for ssltunnel server)
    serviceSocket.on("connect", function () {

      log(Log.info,'Connected to the real BE server');
      serviceSocket.setKeepAlive(true, 30000);

      // pipe service stream to client stream
      // piple client stream to service stream
      // resume the client stream
      serviceSocket.pipe(proxySocket);
      proxySocket.pipe(serviceSocket);
      proxySocket.resume();
    });

    // check that we got no errors when talking to the server
    serviceSocket.on("error", function (exception) {

      log(Log.info,'Error communicating with the server. Error: ' + JSON.stringify(exception));
      proxySocket.end();

    });

    // check that we got no errors when talking to the client
    proxySocket.on("error", function (exception) {

      log(Log.info,'Error communicating with the client. Error: ' + JSON.stringify(exception));
      serviceSocket.end();

    });

    // print diagnostics when connection to server ends
    serviceSocket.on("end", function () {
      log(Log.verbose,'connection to server was closed');
    });

    // print diagnostics when connection to client ends
    proxySocket.on("end", function () {
      log(Log.verbose,'connection to client was closed');
    });
  });

  server.listen(serverPort);

  // calls the callback when the server is in listening state with the actual port
  server.on("listening", function () {
    if (isClient) {
      log(Log.info,'Running \'client\' role. Listening on ' + server.address().port +
            ', encrypting and forwarding to ssltunnel\'s server on ' + options.client_host + ':' + options.client_port);
    } else {
      log(Log.info,'Running \'server\' role. Listening on ' + server.address().port +
            ', decrypting and forwarding to real server machine on ' + options.client_host + ':' + options.client_port);
    }
    callback(null, server.address().port);
  });
}

<|endoftext|>


<commit_before>/*
 * Copyright (c) Jeevanandam M. (jeeva@myjeeva.com)
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at
 * https://github.com/jeevatkm/ReplyWithHeaderMozilla/blob/master/LICENSE
 */

'use strict';

/* globals ReplyWithHeader */

ChromeUtils.import('resource://gre/modules/XPCOMUtils.jsm');
ChromeUtils.import('resource://replywithheader/host.jsm');

ReplyWithHeader.Prefs = {
  getIntPref: function(p) {
    return this.branch.getIntPref('extensions.replywithheader.' + p);
  },

  getBoolPref: function(p) {
    return this.branch.getBoolPref('extensions.replywithheader.' + p);
  },

  getStringPref: function(p) {
    return this.branch.getCharPref('extensions.replywithheader.' + p);
  },

  get isEnabled() {
    return this.getBoolPref('enable');
  },

  get isDebugEnabled() {
    return this.getBoolPref('debug');
  },

  get fromLabelStyle() {
    return this.getIntPref('header.from.style');
  },

  get toccLabelStyle() {
    return this.getIntPref('header.tocc.style');
  },

  get beforeSepSpaceCnt() {
    return this.getIntPref('header.separator.space.before');
  },

  get beforeHdrSpaceCnt() {
    return this.getIntPref('header.space.before');
  },

  get afterHdrSpaceCnt() {
    return this.getIntPref('header.space.after');
  },

  get headerSepLineSize() {
    return this.getIntPref('header.separator.line.size');
  },

  get headerSepLineColor() {
    return this.getStringPref('header.separator.line.color');
  },

  get headerDateFormat() {
    return this.getIntPref('header.date.format');
  },

  get headerTimeFormat() {
    return this.getIntPref('header.time.format');
  },

  get headerIncludeTimeZone() {
    return this.getBoolPref('header.date.timezone');
  },

  get headerFontFace() {
    return this.getStringPref('header.font.face');
  },

  get headerFontSize() {
    return this.getIntPref('header.font.size');
  },

  get headerFontSizeUnit() {
    return this.getStringPref('header.font.size.unit');
  },

  get headerFontColor() {
    return this.getStringPref('header.font.color');
  },

  get headerQuotLblSeq() {
    return this.getIntPref('header.lblseq.style');
  },

  get headerLocale() {
    return this.getStringPref('header.locale');
  },

  get isSubjectPrefixEnabled() {
    return this.getBoolPref('trans.subject.prefix');
  },

  get cleanBlockQuote() {
    return this.getBoolPref('clean.blockquote');
  },

  get cleanNewBlockQuote() {
    return this.getBoolPref('clean.new.blockquote');
  },

  get cleanGreaterThanChar() {
    return this.getBoolPref('clean.char.greaterthan');
  },

  get cleanOnlyNewQuoteChar() {
    return this.getBoolPref('clean.only.new.quote.char');
  },

  get excludePlainTxtHdrPrefix() {
    return this.getBoolPref('clean.pln.hdr.prefix');
  },

  openWebsite: function() {
    ReplyWithHeader.openUrl(ReplyWithHeader.homepageUrl);
  },

  openReviews: function() {
    ReplyWithHeader.openUrl(ReplyWithHeader.reviewsPageUrl);
  },

  reportIssues: function() {
    ReplyWithHeader.openUrl(ReplyWithHeader.issuesPageUrl);
  },

  openPaypal: function() {
    ReplyWithHeader.showAlert('Opening PayPal Service. Thanks for supporting ReplyWithHeader.');
    ReplyWithHeader.openUrl(ReplyWithHeader.paypalDonateUrl);
  },

  copyBtcAddress: function() {
    this.copyToClipboard(ReplyWithHeader.btcAddress);
    ReplyWithHeader.showAlert('BTC address is copied. Thanks for supporting ReplyWithHeader.');
  },

  copyToClipboard: function(str) {
    if (str) {
      this.clipboard.copyString(str);
    }
  },

  fixCursorBlink: function() {
    // Ref: Due this Bug 567240 - Cursor does not blink when replying
    // (https://bugzilla.mozilla.org/show_bug.cgi?id=567240)
    // RWH is setting this 'mail.compose.max_recycled_windows' value to 0
    if (this.branch.getPrefType('mail.compose.max_recycled_windows')) {
      let maxRecycledWindows = this.branch.getIntPref('mail.compose.max_recycled_windows');
      if (maxRecycledWindows == 1) {
        this.branch.setIntPref('mail.compose.max_recycled_windows', 0);
      }
    } else {
      this.branch.setIntPref('mail.compose.max_recycled_windows', 0);
    }
  },

  migrate: function() {
    // header locale value
    if (this.headerLocale == 0) {
      return this.branch.setStringPref('header.locale', 'en-US');
    }
  },

  createMenuItem: function(v, l) {
    var menuItem = document.createElement('menuitem');
    menuItem.setAttribute('value', v);
    menuItem.setAttribute('label', l);
    return menuItem;
  },

  loadFontFaces: function() {
    let allFonts = Components.classes['@mozilla.org/gfx/fontenumerator;1']
      .createInstance(Components.interfaces.nsIFontEnumerator).EnumerateAllFonts({});

    let hdrFontface = this.headerFontFace;
    let menuPopup = document.createElement('menupopup');
    let selectedIdx = 0;

    for (let fontCount = allFonts.length, i = 0; i < fontCount; i++) {
      if (allFonts[i] == hdrFontface) {
        selectedIdx = i;
      }
      menuPopup.appendChild(this.createMenuItem(allFonts[i], allFonts[i]));
    }

    let hdrFontfaceObj = ReplyWithHeader.byId('hdrFontface');
    hdrFontfaceObj.appendChild(menuPopup);
    hdrFontfaceObj.selectedIndex = selectedIdx;
  },

  loadFontSizes: function() {
    let menuPopup = document.createElement('menupopup');
    let selectedIdx = 0;

    for (let i = 7, j = 0; i < 35; i++, j++) {
      menuPopup.appendChild(this.createMenuItem(i, i));
    }

    let hdrFontsizeObj = ReplyWithHeader.byId('hdrFontsize');
    hdrFontsizeObj.appendChild(menuPopup);
    hdrFontsizeObj.selectedIndex = this.headerFontSize - 7;
  },

  populateLocale: function() {
    var menu = ReplyWithHeader.byId('hdrLocale').firstChild;

    for (var lang in i18n.lang) {
      menu.appendChild(this.createMenuItem(
        lang, i18n.lang[lang] + ' (' + lang + ')'
      ));
    }
    menu.parentNode.value = this.headerLocale;
  },

  init: function() {
    this.toggleRwh();

    // Assigning RWH name and version #
    ReplyWithHeader.byId('abtRwhCaption').value = ReplyWithHeader.addOnName + ' v' + ReplyWithHeader.addOnVersion;

    let d = new Date();
    ReplyWithHeader.byId('abtRwhCopyrights').value = 'Ⓒ ' + d.getFullYear() + ' Jeevanandam M.'

    this.loadFontFaces();

    this.loadFontSizes();

    this.populateLocale();

    this.toggleBlockQuote();

    this.toggleQuoteChar();

    this.forPostbox(true);

    // Apply platform style
    this.applyPlatformStyle();
  },

  toggleRwh: function() {
    let rwh = ReplyWithHeader.byId('enableRwh');
    var ids = ['lblFromAttribution', 'fromAttributionStyle', 'lblHeaderToCcAttrib', 'toccAttributionStyle',
      'lblHdrDate', 'quotDateAttributionStyle', 'lblTypography', 'lblFontface', 'hdrFontface', 'lblFontsize',
      'hdrFontsize', 'hdrFontsizeUnit', 'lblFontcolor', 'hdrFontColor', 'lblSpace', 'lblBeforeHeader', 'spaceBeforeHdr',
      'lblAfterHeader', 'spaceAfterHdr', 'lblBeforeSeparator', 'spaceBeforeSep', 'lblSepLineSize', 'lblSepLineColor',
      'hdrSepLineSize', 'hdrSepLineColor', 'lblHeaderQuotSeq', 'quotSeqAttributionStyle', 'quotTimeAttributionStyle',
      'lblHeaderCleanups', 'hdrLocale', 'transSubjectPrefix', 'lblNotAppBeforeSeparator', 'lblCntFormat',
      'cleanBlockQuote', 'cleanNewBlockQuote', 'cleanGreaterThanChar', 'lblHeaderFormat', 'excludePlainTextHdrPrefix',
      'cleanOnlyNewQuoteChar', 'enableRwhDebugMode', 'quotDateIncludeTimezone'
    ];

    for (let len = ids.length, i = 0; i < len; i++) {
      this.toggle(ids[i], !rwh.checked);
    }

    this.forPostbox(true);
  },

  toggle: function(id, v) {
    let obj = ReplyWithHeader.byId(id);
    if (obj) {
      obj.disabled = v;
    } else {
      ReplyWithHeader.Log.debug('func: toggle - Element not found ['+ id +']');
    }
  },

  forPostbox: function(v) {
    if (ReplyWithHeader.isPostbox) {
      this.toggle('lblBeforeSeparator', v);
      this.toggle('spaceBeforeSep', v);
      this.toggle('lblNotAppBeforeSeparator', v);
    } else {
      ReplyWithHeader.byId('lblNotAppBeforeSeparator').style.display = 'none';
    }
  },

  toggleBlockQuote: function() {
    let cbq = ReplyWithHeader.byId('cleanBlockQuote');
    this.toggle('cleanNewBlockQuote', !cbq.checked);
  },

  toggleQuoteChar: function() {
    let cqc = ReplyWithHeader.byId('cleanGreaterThanChar');
    this.toggle('cleanOnlyNewQuoteChar', !cqc.checked);
  },

  applyPlatformStyle: function() {
    if (rwhhost.isMacOSX) {
      ReplyWithHeader.byId('hboxFromAttribution').style.marginTop = '-10px';
      ReplyWithHeader.byId('hboxCntFormat').style.marginTop = '-10px';
    } else if (rwhhost.isWindows) {
      ReplyWithHeader.byId('hdrFontsize').style.marginLeft = '6px';
      ReplyWithHeader.byId('spaceBeforeSep').style.marginLeft = '.63em';
      ReplyWithHeader.byId('hdrSepLineSize').style.marginLeft = '4.15em';
      ReplyWithHeader.byId('abtRwhLogo').style.marginLeft = '132px';
      ReplyWithHeader.byId('abtRwhCopyrights').style.marginLeft = '-133px';
      ReplyWithHeader.byId('hboxRwhBtn').style.marginLeft = '95px';
      ReplyWithHeader.byId('hboxEnableRwhDebugMode').style.marginLeft = '170px';
      ReplyWithHeader.byId('hboxDonateBtn').style.marginLeft = '16px';
    } else if (rwhhost.isLinux) {
      ReplyWithHeader.byId('hdrFontsize').style.marginLeft = '7px';
      ReplyWithHeader.byId('spaceBeforeSep').style.marginLeft = '0px';
      ReplyWithHeader.byId('hdrSepLineSize').style.marginLeft = '4.05em';
      ReplyWithHeader.byId('abtRwhLogo').style.marginLeft = '110px';
      ReplyWithHeader.byId('abtRwhCopyrights').style.marginLeft = '-164px';
      ReplyWithHeader.byId('hboxRwhBtn').style.marginLeft = '65px';
      ReplyWithHeader.byId('hboxDonateBtn').style.marginLeft = '19px';
    }
  }
};

// Initializing Services
XPCOMUtils.defineLazyServiceGetter(ReplyWithHeader.Prefs, 'branch',
                                   '@mozilla.org/preferences-service;1',
                                   'nsIPrefBranch');

XPCOMUtils.defineLazyServiceGetter(ReplyWithHeader.Prefs, 'clipboard',
                                  '@mozilla.org/widget/clipboardhelper;1',
                                  'nsIClipboardHelper');
<commit_msg>corrected pref key name<commit_after>/*
 * Copyright (c) Jeevanandam M. (jeeva@myjeeva.com)
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at
 * https://github.com/jeevatkm/ReplyWithHeaderMozilla/blob/master/LICENSE
 */

'use strict';

/* globals ReplyWithHeader */

ChromeUtils.import('resource://gre/modules/XPCOMUtils.jsm');
ChromeUtils.import('resource://replywithheader/host.jsm');

ReplyWithHeader.Prefs = {
  getIntPref: function(p) {
    return this.branch.getIntPref('extensions.replywithheader.' + p);
  },

  getBoolPref: function(p) {
    return this.branch.getBoolPref('extensions.replywithheader.' + p);
  },

  getStringPref: function(p) {
    return this.branch.getCharPref('extensions.replywithheader.' + p);
  },

  get isEnabled() {
    return this.getBoolPref('enable');
  },

  get isDebugEnabled() {
    return this.getBoolPref('debug');
  },

  get fromLabelStyle() {
    return this.getIntPref('header.from.style');
  },

  get toccLabelStyle() {
    return this.getIntPref('header.tocc.style');
  },

  get beforeSepSpaceCnt() {
    return this.getIntPref('header.separator.space.before');
  },

  get beforeHdrSpaceCnt() {
    return this.getIntPref('header.space.before');
  },

  get afterHdrSpaceCnt() {
    return this.getIntPref('header.space.after');
  },

  get headerSepLineSize() {
    return this.getIntPref('header.separator.line.size');
  },

  get headerSepLineColor() {
    return this.getStringPref('header.separator.line.color');
  },

  get headerDateFormat() {
    return this.getIntPref('header.date.format');
  },

  get headerTimeFormat() {
    return this.getIntPref('header.time.format');
  },

  get headerIncludeTimeZone() {
    return this.getBoolPref('header.date.timezone');
  },

  get headerFontFace() {
    return this.getStringPref('header.font.face');
  },

  get headerFontSize() {
    return this.getIntPref('header.font.size');
  },

  get headerFontSizeUnit() {
    return this.getStringPref('header.font.size.unit');
  },

  get headerFontColor() {
    return this.getStringPref('header.font.color');
  },

  get headerQuotLblSeq() {
    return this.getIntPref('header.lblseq.style');
  },

  get headerLocale() {
    return this.getStringPref('header.locale');
  },

  get isSubjectPrefixEnabled() {
    return this.getBoolPref('trans.subject.prefix');
  },

  get cleanBlockQuote() {
    return this.getBoolPref('clean.blockquote');
  },

  get cleanNewBlockQuote() {
    return this.getBoolPref('clean.new.blockquote');
  },

  get cleanGreaterThanChar() {
    return this.getBoolPref('clean.char.greaterthan');
  },

  get cleanOnlyNewQuoteChar() {
    return this.getBoolPref('clean.only.new.quote.char');
  },

  get excludePlainTxtHdrPrefix() {
    return this.getBoolPref('clean.pln.hdr.prefix');
  },

  openWebsite: function() {
    ReplyWithHeader.openUrl(ReplyWithHeader.homepageUrl);
  },

  openReviews: function() {
    ReplyWithHeader.openUrl(ReplyWithHeader.reviewsPageUrl);
  },

  reportIssues: function() {
    ReplyWithHeader.openUrl(ReplyWithHeader.issuesPageUrl);
  },

  openPaypal: function() {
    ReplyWithHeader.showAlert('Opening PayPal Service. Thanks for supporting ReplyWithHeader.');
    ReplyWithHeader.openUrl(ReplyWithHeader.paypalDonateUrl);
  },

  copyBtcAddress: function() {
    this.copyToClipboard(ReplyWithHeader.btcAddress);
    ReplyWithHeader.showAlert('BTC address is copied. Thanks for supporting ReplyWithHeader.');
  },

  copyToClipboard: function(str) {
    if (str) {
      this.clipboard.copyString(str);
    }
  },

  fixCursorBlink: function() {
    // Ref: Due this Bug 567240 - Cursor does not blink when replying
    // (https://bugzilla.mozilla.org/show_bug.cgi?id=567240)
    // RWH is setting this 'mail.compose.max_recycled_windows' value to 0
    if (this.branch.getPrefType('mail.compose.max_recycled_windows')) {
      let maxRecycledWindows = this.branch.getIntPref('mail.compose.max_recycled_windows');
      if (maxRecycledWindows == 1) {
        this.branch.setIntPref('mail.compose.max_recycled_windows', 0);
      }
    } else {
      this.branch.setIntPref('mail.compose.max_recycled_windows', 0);
    }
  },

  migrate: function() {
    // header locale value
    if (this.headerLocale == 0) {
      return this.branch.setStringPref('extensions.replywithheader.header.locale', 'en-US');
    }
  },

  createMenuItem: function(v, l) {
    var menuItem = document.createElement('menuitem');
    menuItem.setAttribute('value', v);
    menuItem.setAttribute('label', l);
    return menuItem;
  },

  loadFontFaces: function() {
    let allFonts = Components.classes['@mozilla.org/gfx/fontenumerator;1']
      .createInstance(Components.interfaces.nsIFontEnumerator).EnumerateAllFonts({});

    let hdrFontface = this.headerFontFace;
    let menuPopup = document.createElement('menupopup');
    let selectedIdx = 0;

    for (let fontCount = allFonts.length, i = 0; i < fontCount; i++) {
      if (allFonts[i] == hdrFontface) {
        selectedIdx = i;
      }
      menuPopup.appendChild(this.createMenuItem(allFonts[i], allFonts[i]));
    }

    let hdrFontfaceObj = ReplyWithHeader.byId('hdrFontface');
    hdrFontfaceObj.appendChild(menuPopup);
    hdrFontfaceObj.selectedIndex = selectedIdx;
  },

  loadFontSizes: function() {
    let menuPopup = document.createElement('menupopup');
    let selectedIdx = 0;

    for (let i = 7, j = 0; i < 35; i++, j++) {
      menuPopup.appendChild(this.createMenuItem(i, i));
    }

    let hdrFontsizeObj = ReplyWithHeader.byId('hdrFontsize');
    hdrFontsizeObj.appendChild(menuPopup);
    hdrFontsizeObj.selectedIndex = this.headerFontSize - 7;
  },

  populateLocale: function() {
    var menu = ReplyWithHeader.byId('hdrLocale').firstChild;

    for (var lang in i18n.lang) {
      menu.appendChild(this.createMenuItem(
        lang, i18n.lang[lang] + ' (' + lang + ')'
      ));
    }
    menu.parentNode.value = this.headerLocale;
  },

  init: function() {
    this.toggleRwh();

    // Assigning RWH name and version #
    ReplyWithHeader.byId('abtRwhCaption').value = ReplyWithHeader.addOnName + ' v' + ReplyWithHeader.addOnVersion;

    let d = new Date();
    ReplyWithHeader.byId('abtRwhCopyrights').value = 'Ⓒ ' + d.getFullYear() + ' Jeevanandam M.'

    this.loadFontFaces();

    this.loadFontSizes();

    this.populateLocale();

    this.toggleBlockQuote();

    this.toggleQuoteChar();

    this.forPostbox(true);

    // Apply platform style
    this.applyPlatformStyle();
  },

  toggleRwh: function() {
    let rwh = ReplyWithHeader.byId('enableRwh');
    var ids = ['lblFromAttribution', 'fromAttributionStyle', 'lblHeaderToCcAttrib', 'toccAttributionStyle',
      'lblHdrDate', 'quotDateAttributionStyle', 'lblTypography', 'lblFontface', 'hdrFontface', 'lblFontsize',
      'hdrFontsize', 'hdrFontsizeUnit', 'lblFontcolor', 'hdrFontColor', 'lblSpace', 'lblBeforeHeader', 'spaceBeforeHdr',
      'lblAfterHeader', 'spaceAfterHdr', 'lblBeforeSeparator', 'spaceBeforeSep', 'lblSepLineSize', 'lblSepLineColor',
      'hdrSepLineSize', 'hdrSepLineColor', 'lblHeaderQuotSeq', 'quotSeqAttributionStyle', 'quotTimeAttributionStyle',
      'lblHeaderCleanups', 'hdrLocale', 'transSubjectPrefix', 'lblNotAppBeforeSeparator', 'lblCntFormat',
      'cleanBlockQuote', 'cleanNewBlockQuote', 'cleanGreaterThanChar', 'lblHeaderFormat', 'excludePlainTextHdrPrefix',
      'cleanOnlyNewQuoteChar', 'enableRwhDebugMode', 'quotDateIncludeTimezone'
    ];

    for (let len = ids.length, i = 0; i < len; i++) {
      this.toggle(ids[i], !rwh.checked);
    }

    this.forPostbox(true);
  },

  toggle: function(id, v) {
    let obj = ReplyWithHeader.byId(id);
    if (obj) {
      obj.disabled = v;
    } else {
      ReplyWithHeader.Log.debug('func: toggle - Element not found ['+ id +']');
    }
  },

  forPostbox: function(v) {
    if (ReplyWithHeader.isPostbox) {
      this.toggle('lblBeforeSeparator', v);
      this.toggle('spaceBeforeSep', v);
      this.toggle('lblNotAppBeforeSeparator', v);
    } else {
      ReplyWithHeader.byId('lblNotAppBeforeSeparator').style.display = 'none';
    }
  },

  toggleBlockQuote: function() {
    let cbq = ReplyWithHeader.byId('cleanBlockQuote');
    this.toggle('cleanNewBlockQuote', !cbq.checked);
  },

  toggleQuoteChar: function() {
    let cqc = ReplyWithHeader.byId('cleanGreaterThanChar');
    this.toggle('cleanOnlyNewQuoteChar', !cqc.checked);
  },

  applyPlatformStyle: function() {
    if (rwhhost.isMacOSX) {
      ReplyWithHeader.byId('hboxFromAttribution').style.marginTop = '-10px';
      ReplyWithHeader.byId('hboxCntFormat').style.marginTop = '-10px';
    } else if (rwhhost.isWindows) {
      ReplyWithHeader.byId('hdrFontsize').style.marginLeft = '6px';
      ReplyWithHeader.byId('spaceBeforeSep').style.marginLeft = '.63em';
      ReplyWithHeader.byId('hdrSepLineSize').style.marginLeft = '4.15em';
      ReplyWithHeader.byId('abtRwhLogo').style.marginLeft = '132px';
      ReplyWithHeader.byId('abtRwhCopyrights').style.marginLeft = '-133px';
      ReplyWithHeader.byId('hboxRwhBtn').style.marginLeft = '95px';
      ReplyWithHeader.byId('hboxEnableRwhDebugMode').style.marginLeft = '170px';
      ReplyWithHeader.byId('hboxDonateBtn').style.marginLeft = '16px';
    } else if (rwhhost.isLinux) {
      ReplyWithHeader.byId('hdrFontsize').style.marginLeft = '7px';
      ReplyWithHeader.byId('spaceBeforeSep').style.marginLeft = '0px';
      ReplyWithHeader.byId('hdrSepLineSize').style.marginLeft = '4.05em';
      ReplyWithHeader.byId('abtRwhLogo').style.marginLeft = '110px';
      ReplyWithHeader.byId('abtRwhCopyrights').style.marginLeft = '-164px';
      ReplyWithHeader.byId('hboxRwhBtn').style.marginLeft = '65px';
      ReplyWithHeader.byId('hboxDonateBtn').style.marginLeft = '19px';
    }
  }
};

// Initializing Services
XPCOMUtils.defineLazyServiceGetter(ReplyWithHeader.Prefs, 'branch',
                                   '@mozilla.org/preferences-service;1',
                                   'nsIPrefBranch');

XPCOMUtils.defineLazyServiceGetter(ReplyWithHeader.Prefs, 'clipboard',
                                  '@mozilla.org/widget/clipboardhelper;1',
                                  'nsIClipboardHelper');
<|endoftext|>


<commit_before>var cwd = process.cwd();

var cons = require('consolidate'),
    swig = require('swig');

var debug = conf.get('env') != 'production';

exports.THEMES_ROOT = path.join(cwd, 'themes');
exports.THEME_ROOT = path.join(exports.THEMES_ROOT, exports.THEME);
exports.TEMPLATE_DIR = path.join(exports.THEME_ROOT, 'templates');
exports.STATIC_ROOT = path.join(exports.THEME_ROOT, 'public');

// Templates
swig.init({
  root: templateDir,
  allowErrors: debug,
  cache: !debug,
  tzOffset: util.tzToMinutes(conf.get('TIME_ZONE')),
  filters: filters
});
app.set('views', templateDir);
app.set('view engine', 'html');
app.set('view options', { layout: false });
app.engine('.html', cons.swig);<commit_msg>Moved template handling outside of index.js<commit_after>var cons = require('consolidate'),
    swig = require('swig'),
    conf = require('./conf.js'),
    filters = require('./filters.js'),
    debug = conf.get('env') != 'production',
    cwd = process.cwd();

// Templates
swig.init({
  root: conf.template_dir,
  allowErrors: debug,
  cache: !debug,
  tzOffset: util.tzToMinutes(conf.time_zone),
  filters: filters
});

exports.setup = function setup(app) {
  app.set('views', conf.template_dir);
  app.set('view engine', 'html');
  app.set('view options', { layout: false });
  app.engine('.html', cons.swig);
};

exports.swig = swig;<|endoftext|>


<commit_before>/*global require: false, exports: false */
/*jslint indent: 2 */

/* jshint strict: true, esnext: true, newcap: false,
   globalstrict: true, node: true */

"use strict";

const tabs = require("sdk/tabs");
const { data } = require("sdk/self");
const database = require('./service/database');
const { match } = require('./service/match');

const Point = require('./service/point');

const { log } = require('./utils/log');
const { TEXT } = require('./ratings');

// TOS-checker panel
const panel = require("sdk/panel").Panel({
  width: 560,
  height: 475,
  name : "TOS-Panel",
  contentURL: data.url("popup.html"),
  contentScriptFile: [data.url("libs/jquery-1.11.0.min.js"),
            data.url("popup.js")],
  contentScriptWhen: 'ready',
  onShow: function(){
    let service = match(tabs.activeTab.url);
    if (service) {
      Point.get(service.id).then(function ({ pointsData }) {
        service.pointsData = pointsData;
        panel.port.emit("service", service);
      });
    }
  },
  onMessage: function(message){
    //hide the panel if recieved close message
    if(message == "close") {
      panel.hide();
    }
  }
});

// panel.port.on('get-rating-text', function(rating) {
//   panel.port.emit('set-rating-text', TEXT[rating]);
// });

// Hide panel when new tab opened
// https://addons.mozilla.org/en-US/firefox/addon/terms-of-service-didnt-read/reviews/498180/
tabs.on('open', function() {
  panel.hide();
});

exports.panel = panel;
<commit_msg>Show "not rated" panel<commit_after>/*global require: false, exports: false */
/*jslint indent: 2 */

/* jshint strict: true, esnext: true, newcap: false,
   globalstrict: true, node: true */

"use strict";

const tabs = require("sdk/tabs");
const { data } = require("sdk/self");
const database = require('./service/database');
const { match } = require('./service/match');

const Point = require('./service/point');

const { log } = require('./utils/log');
const { TEXT } = require('./ratings');

// TOS-checker panel
const panel = require("sdk/panel").Panel({
  width: 560,
  height: 475,
  name : "TOS-Panel",
  contentURL: data.url("popup.html"),
  contentScriptFile: [data.url("libs/jquery-1.11.0.min.js"),
            data.url("popup.js")],
  contentScriptWhen: 'ready',
  onShow: function(){
    let service = match(tabs.activeTab.url);
    if (service) {
      Point.get(service.id).then(function ({ pointsData }) {
        service.pointsData = pointsData;
        panel.port.emit("service", service);
      });
    }else{
		// Show Not rated panel
    	panel.port.emit("service", null);
    }
  },
  onMessage: function(message){
    //hide the panel if recieved close message
    if(message == "close") {
      panel.hide();
    }
  }
});

// panel.port.on('get-rating-text', function(rating) {
//   panel.port.emit('set-rating-text', TEXT[rating]);
// });

// Hide panel when new tab opened
// https://addons.mozilla.org/en-US/firefox/addon/terms-of-service-didnt-read/reviews/498180/
tabs.on('open', function() {
  panel.hide();
});

exports.panel = panel;
<|endoftext|>