<commit_before>/////////////////////////////////////////////////////////////////////////////////
//                                                                             //
//-----------------------------------------------------------------------------//
//                          ANGULAR DATALIST DIRECTIVE                         //
//-----------------------------------------------------------------------------//
//                                                                             //
/////////////////////////////////////////////////////////////////////////////////

/**------------------------------------------------------------------------------
 * @name ngDatalist
 * @author Przemysław Hardyn
 * @description Simple datalist directive.
 * @license MIT Licence <http://creativecommons.org/licenses/MIT/>
 ------------------------------------------------------------------------------*/

angular.module('ng-datalist', [])
  .directive('ngDatalist', ['$timeout', '$window', '$rootScope', ngDatalist]);

function ngDatalist ($timeout, $window, $rootScope) {
  return {
    restrict: 'E',
    replace: true,
    require: 'ngModel',
    scope: {
      items: '<?',         /** @type {Array}   */
      fetchItems: '&?',         /** @type {function}   */
      ngModel: '=',            /** @type {string}  */
      fieldRequired: '=?req',   /** @type {boolean} */
      styling: '=styling',      /** @type {boolean} */
      placeholder: '@?placeholder',      /** @type {string} */
      inputClass: '@?inputClass',         /** @type {string} */
      ngDisabled: '=?',            /** @type {string}  */
      width: '=?',
      containerWidth: '=?',
      minWidth: '=?',
      func: '=?',
    },
    link: function (scope, elem, attrs, ctrl) {
      // --------------------------------------------------------- //
      //                      SCOPE & VARIABLES                    //
      // --------------------------------------------------------- //
      // Functions binded to the template:
      scope.selectItem = selectItem;
      scope.showList = showList;
      scope.hideList = hideList;
      scope.highlightItem = highlightItem;
      scope.clearHighlightedItem = clearHighlightedItem;
      scope.keydown = keydown;
      scope.change = change;
      if (scope.placeholder) {
        elem.find('input').attr('placeholder', scope.placeholder);
      }
      scope.$on('openNewList', function(event) {
        hideList(event);
      });
      elem.find('input').on('input propertychange', function() {
        scope.ngModel = this.value;
        ctrl.$setViewValue(scope.ngModel);
        scope.inputItem = this.value;
        scope.$evalAsync();
      });
      if (!Array.isArray(scope.items)) {
        scope.items = [];
      }
      if (scope.func) {
        // call showList from external javascript
        scope.func.showList = showList;
      }

      // Expose dependencies in the directive:
      var domReady = $timeout;

      // Set field to not required if attribute set to false
      // or not provided.
      if (scope.fieldRequired !== true) {
        scope.fieldRequired = false;
      }

      // Basic color config:
      var borderColor = '#DDDDDD';
      var highlightColor = '#DDDDDD';

      // --------------------------------------------------------- //
      //                           STYLES                          //
      // --------------------------------------------------------- //
      // Use default styles only if custom not set:
      if (scope.styling !== false) {
        // Container element styles:
        scope.containerStyle = {
          'display': 'inline-block',
          'position': 'relative',
          'box-sizing': 'border-box',
          'height': '32px'
        };

        // Input element styles:
        scope.inputStyle = {
          'box-sizing': 'border-box',
          'height': '32px',
          'padding': '5px',
          'margin': '0px'
        };
        if (scope.containerWidth) {
          if (typeof scope.containerWidth === 'string' && scope.containerWidth.indexOf('%') !== -1) {
            scope.containerStyle.width = scope.containerWidth;
          } else {
            scope.containerStyle.width = (+scope.containerWidth || 0) + 'px';
          }
        }
        if (scope.width) {
          if (typeof scope.width === 'string' && scope.width.indexOf('%') !== -1) {
            scope.inputStyle.width = scope.width;
          } else {
            scope.inputStyle.width = (+scope.width || 0) + 'px';
          }
        }
        if (scope.minWidth) {
          if (typeof scope.minWidth === 'string' && scope.minWidth.indexOf('%') !== -1) {
            scope.inputStyle['min-width'] = scope.minWidth;
          } else {
            scope.inputStyle['min-width'] = (+scope.minWidth || 0) + 'px';
          }
        }

        // List element styles:
        scope.ulStyle = {
          'list-style-type': 'none',
          'padding': '0',
          'margin': '0',
          'display': 'none',
          'position': 'absolute',
          'top': '32px',
          'background-color': '#FFFFFF',
          'overflow-y': 'auto',
          'border-left': '1px solid '+borderColor,
          'border-bottom': '1px solid '+borderColor,
          'border-right': '1px solid '+borderColor,
          'z-index': 10
        };

        // List items styles:
        scope.liStyle = {
          'display': 'block',
          'padding': '5px',
          'cursor': 'pointer',
          'box-sizing': 'border-box'
        }
      }

      // --------------------------------------------------------- //
      //                          FUNCTIONS                        //
      // --------------------------------------------------------- //
      /**
       * @function selectItem
       * @description Copy data from selected list item to the model.
       * @param {Object} event Click event used to prevent bubbling.
       * @param {string} item  Text to be copied to the model.
       */
      function selectItem (event, index) {
        event.stopPropagation();
        scope.ngModel = elem.find('li').eq(index).text();
        ctrl.$setViewValue(scope.ngModel);
        elem.find('ul').css('display', 'none');
        elem.find('input').triggerHandler('focus');
      }

      /**
       * @function showList
       * @description Show ul DOM element containing the list.
       * @param {Object} event Click event used to prevent bubbling.
       */
      var cursor = null;
      function showList (event) {
        if (event) {
          event.stopPropagation();
        }
        $rootScope.$broadcast('openNewList');

        if (scope.fetchItems) {
          scope.fetchItems({items: scope.items});
        }
        var inputElem = elem[0].firstChild;
        var maxHeight = $window.innerHeight - inputElem.getBoundingClientRect().top - 40;
        var ul = elem.find('ul');
        ul.css('max-height',  maxHeight + 'px')
        .css('display', 'block');
        scope.liStyle.width = inputElem.clientWidth + 'px';
        scope.inputItem = '';
        cursor = null;
      }

      /**
       * @function hideList
       * @description Hide ul DOM element containing the list.
       * @param {Object} event Click event used to prevent bubbling.
       */
      function hideList (event) {
        if (event.stopPropagation) {
          event.stopPropagation();
        }
        elem.find('ul').css('display', 'none');
      }

      /**
       * @function highlightItem
       * @description Highlight hovered list item.
       * @param {Object} event Mouseover event used to prevent bubbling.
       * @param {Number} index Used to locate current list item in the DOM tree.
       */
      function highlightItem (event, index) {
        event.stopPropagation();
        var li = elem.find('li');
        if (index < 0 || index >= li.length) {
          return;
        }
        li.css({
          'background-color': 'transparent'
        });
        li.eq(index).css({
          'background-color': borderColor
        });
        cursor = index;
      }

      /**
       * @function clearHighlightedItem
       * @description Remove item highlight on mouseleave.
       * @param {Object} event Mouseleave event used to prevent bubbling.
       */
      function clearHighlightedItem (event, index) {
        event.stopPropagation();
        var li = elem.find('li');
        if (index < 0 || index >= li.length) {
          return;
        }
        li.eq(index).css({
          'background-color': 'transparent'
        });
      }
      function keydown(event) {
        if (13 === event.keyCode) {
          //enter
          if (null !== cursor) {
            selectItem(event, cursor);
          }
        }else if (40 === event.keyCode) {
          //down
          if (null !== cursor) {
            highlightItem(event, cursor + 1);
          }else {
            highlightItem(event, 0);
          }
        }else if (38 === event.keyCode) {
          //up
          if (null !== cursor) {
            highlightItem(event, cursor - 1);
          }
        }else if (37 === event.keyCode || 39 === event.keyCode || 8 === event.keyCode) {
          // left, right, backspace
          clearHighlightedItem(event, cursor);
          showList(event);
        }else if (9 === event.keyCode) {
          // tab
          hideList(event);
        }
      }

      function change() {
        // ng-change発生時はoninputイベントが発生しないため、oninputと同じ処理
        ctrl.$setViewValue(scope.ngModel);
        scope.inputItem = scope.ngModel;
      }

      // https://github.com/jquery/jquery/blob/2d4f53416e5f74fa98e0c1d66b6f3c285a12f0ce/external/sizzle/dist/sizzle.js#L850
      function jq_contains(a, b) {
        if (a.contains) {
            var adown = a.nodeType === 9 ? a.documentElement : a,
                bup = b && b.parentNode;
            return a === bup || !!( bup && bup.nodeType === 1 && (
                adown.contains ?
                    adown.contains( bup ) :
                    a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16
            ));
        }else {
            if ( b ) {
                while ( (b = b.parentNode) ) {
                    if ( b === a ) {
                        return true;
                    }
                }
            }
            return false;
        }
      }

      function hideListImpl(event) {
        var contains = jq_contains(elem, event.target);
        if (!contains) {
          scope.hideList(event);
        }
      }

      // --------------------------------------------------------- //
      //                           EVENTS                          //
      // --------------------------------------------------------- //
      // Bind click event to the document to hide list:
      domReady(function () {
        // ng-datalistが複数あると複数個登録されることに注意
        document.addEventListener('click', hideListImpl);
      })

      // Remove document click event on destroy:
      elem.on('$destroy', function () {
        document.removeEventListener('click', hideListImpl);
      });
    },
    template:
    '
'+
      '<input type="text" '+
             'class="ng-datalist-input {{inputClass}}" '+
             'ng-required="fieldRequired" '+
             'ng-model="ngModel" '+
             'ng-click="showList($event)" '+
             'ng-style="inputStyle" '+
             'ng-change="change($event)" '+
             'ng-keydown="keydown($event)" '+
             'ng-disabled="ngDisabled">'+
      '
'+
        '
{{ item }}
'+
      '
'+
    '
'
  }
}
<commit_msg>on-blur属性でng-blurのタイミングで処理を可能に<commit_after>/////////////////////////////////////////////////////////////////////////////////
//                                                                             //
//-----------------------------------------------------------------------------//
//                          ANGULAR DATALIST DIRECTIVE                         //
//-----------------------------------------------------------------------------//
//                                                                             //
/////////////////////////////////////////////////////////////////////////////////

/**------------------------------------------------------------------------------
 * @name ngDatalist
 * @author Przemysław Hardyn
 * @description Simple datalist directive.
 * @license MIT Licence <http://creativecommons.org/licenses/MIT/>
 ------------------------------------------------------------------------------*/

angular.module('ng-datalist', [])
  .directive('ngDatalist', ['$timeout', '$window', '$rootScope', ngDatalist]);

function ngDatalist ($timeout, $window, $rootScope) {
  return {
    restrict: 'E',
    replace: true,
    require: 'ngModel',
    scope: {
      items: '<?',         /** @type {Array}   */
      fetchItems: '&?',         /** @type {function}   */
      ngModel: '=',            /** @type {string}  */
      fieldRequired: '=?req',   /** @type {boolean} */
      styling: '=styling',      /** @type {boolean} */
      placeholder: '@?placeholder',      /** @type {string} */
      inputClass: '@?inputClass',         /** @type {string} */
      ngDisabled: '=?',            /** @type {string}  */
      width: '=?',
      containerWidth: '=?',
      minWidth: '=?',
      onBlur: '&?',
      func: '=?',
    },
    link: function (scope, elem, attrs, ctrl) {
      // --------------------------------------------------------- //
      //                      SCOPE & VARIABLES                    //
      // --------------------------------------------------------- //
      // Functions binded to the template:
      scope.selectItem = selectItem;
      scope.showList = showList;
      scope.hideList = hideList;
      scope.highlightItem = highlightItem;
      scope.clearHighlightedItem = clearHighlightedItem;
      scope.keydown = keydown;
      scope.blur = blur;
      scope.change = change;
      if (scope.placeholder) {
        elem.find('input').attr('placeholder', scope.placeholder);
      }
      scope.$on('openNewList', function(event) {
        hideList(event);
      });
      elem.find('input').on('input propertychange', function() {
        scope.ngModel = this.value;
        ctrl.$setViewValue(scope.ngModel);
        scope.inputItem = this.value;
        scope.$evalAsync();
      });
      if (!Array.isArray(scope.items)) {
        scope.items = [];
      }
      if (scope.func) {
        // call showList from external javascript
        scope.func.showList = showList;
      }

      // Expose dependencies in the directive:
      var domReady = $timeout;

      // Set field to not required if attribute set to false
      // or not provided.
      if (scope.fieldRequired !== true) {
        scope.fieldRequired = false;
      }

      // Basic color config:
      var borderColor = '#DDDDDD';
      var highlightColor = '#DDDDDD';

      // --------------------------------------------------------- //
      //                           STYLES                          //
      // --------------------------------------------------------- //
      // Use default styles only if custom not set:
      if (scope.styling !== false) {
        // Container element styles:
        scope.containerStyle = {
          'display': 'inline-block',
          'position': 'relative',
          'box-sizing': 'border-box',
          'height': '32px'
        };

        // Input element styles:
        scope.inputStyle = {
          'box-sizing': 'border-box',
          'height': '32px',
          'padding': '5px',
          'margin': '0px'
        };
        if (scope.containerWidth) {
          if (typeof scope.containerWidth === 'string' && scope.containerWidth.indexOf('%') !== -1) {
            scope.containerStyle.width = scope.containerWidth;
          } else {
            scope.containerStyle.width = (+scope.containerWidth || 0) + 'px';
          }
        }
        if (scope.width) {
          if (typeof scope.width === 'string' && scope.width.indexOf('%') !== -1) {
            scope.inputStyle.width = scope.width;
          } else {
            scope.inputStyle.width = (+scope.width || 0) + 'px';
          }
        }
        if (scope.minWidth) {
          if (typeof scope.minWidth === 'string' && scope.minWidth.indexOf('%') !== -1) {
            scope.inputStyle['min-width'] = scope.minWidth;
          } else {
            scope.inputStyle['min-width'] = (+scope.minWidth || 0) + 'px';
          }
        }

        // List element styles:
        scope.ulStyle = {
          'list-style-type': 'none',
          'padding': '0',
          'margin': '0',
          'display': 'none',
          'position': 'absolute',
          'top': '32px',
          'background-color': '#FFFFFF',
          'overflow-y': 'auto',
          'border-left': '1px solid '+borderColor,
          'border-bottom': '1px solid '+borderColor,
          'border-right': '1px solid '+borderColor,
          'z-index': 10
        };

        // List items styles:
        scope.liStyle = {
          'display': 'block',
          'padding': '5px',
          'cursor': 'pointer',
          'box-sizing': 'border-box'
        }
      }

      // --------------------------------------------------------- //
      //                          FUNCTIONS                        //
      // --------------------------------------------------------- //
      /**
       * @function selectItem
       * @description Copy data from selected list item to the model.
       * @param {Object} event Click event used to prevent bubbling.
       * @param {string} item  Text to be copied to the model.
       */
      function selectItem (event, index) {
        event.stopPropagation();
        scope.ngModel = elem.find('li').eq(index).text();
        ctrl.$setViewValue(scope.ngModel);
        elem.find('ul').css('display', 'none');
        elem.find('input').triggerHandler('focus');
      }

      /**
       * @function showList
       * @description Show ul DOM element containing the list.
       * @param {Object} event Click event used to prevent bubbling.
       */
      var cursor = null;
      function showList (event) {
        if (event) {
          event.stopPropagation();
        }
        $rootScope.$broadcast('openNewList');

        if (scope.fetchItems) {
          scope.fetchItems({items: scope.items});
        }
        var inputElem = elem[0].firstChild;
        var maxHeight = $window.innerHeight - inputElem.getBoundingClientRect().top - 40;
        var ul = elem.find('ul');
        ul.css('max-height',  maxHeight + 'px')
        .css('display', 'block');
        scope.liStyle.width = inputElem.clientWidth + 'px';
        scope.inputItem = '';
        cursor = null;
      }

      /**
       * @function hideList
       * @description Hide ul DOM element containing the list.
       * @param {Object} event Click event used to prevent bubbling.
       */
      function hideList (event) {
        if (event.stopPropagation) {
          event.stopPropagation();
        }
        elem.find('ul').css('display', 'none');
      }

      /**
       * @function highlightItem
       * @description Highlight hovered list item.
       * @param {Object} event Mouseover event used to prevent bubbling.
       * @param {Number} index Used to locate current list item in the DOM tree.
       */
      function highlightItem (event, index) {
        event.stopPropagation();
        var li = elem.find('li');
        if (index < 0 || index >= li.length) {
          return;
        }
        li.css({
          'background-color': 'transparent'
        });
        li.eq(index).css({
          'background-color': borderColor
        });
        cursor = index;
      }

      /**
       * @function clearHighlightedItem
       * @description Remove item highlight on mouseleave.
       * @param {Object} event Mouseleave event used to prevent bubbling.
       */
      function clearHighlightedItem (event, index) {
        event.stopPropagation();
        var li = elem.find('li');
        if (index < 0 || index >= li.length) {
          return;
        }
        li.eq(index).css({
          'background-color': 'transparent'
        });
      }
      function keydown(event) {
        if (13 === event.keyCode) {
          //enter
          if (null !== cursor) {
            selectItem(event, cursor);
          }
        }else if (40 === event.keyCode) {
          //down
          if (null !== cursor) {
            highlightItem(event, cursor + 1);
          }else {
            highlightItem(event, 0);
          }
        }else if (38 === event.keyCode) {
          //up
          if (null !== cursor) {
            highlightItem(event, cursor - 1);
          }
        }else if (37 === event.keyCode || 39 === event.keyCode || 8 === event.keyCode) {
          // left, right, backspace
          clearHighlightedItem(event, cursor);
          showList(event);
        }else if (9 === event.keyCode) {
          // tab
          hideList(event);
        }
      }

      function blur(event) {
        if (scope.onBlur) {
          scope.onBlur(event);
        }
      }

      function change() {
        // ng-change発生時はoninputイベントが発生しないため、oninputと同じ処理
        ctrl.$setViewValue(scope.ngModel);
        scope.inputItem = scope.ngModel;
      }

      // https://github.com/jquery/jquery/blob/2d4f53416e5f74fa98e0c1d66b6f3c285a12f0ce/external/sizzle/dist/sizzle.js#L850
      function jq_contains(a, b) {
        if (a.contains) {
            var adown = a.nodeType === 9 ? a.documentElement : a,
                bup = b && b.parentNode;
            return a === bup || !!( bup && bup.nodeType === 1 && (
                adown.contains ?
                    adown.contains( bup ) :
                    a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16
            ));
        }else {
            if ( b ) {
                while ( (b = b.parentNode) ) {
                    if ( b === a ) {
                        return true;
                    }
                }
            }
            return false;
        }
      }

      function hideListImpl(event) {
        var contains = jq_contains(elem, event.target);
        if (!contains) {
          scope.hideList(event);
        }
      }

      // --------------------------------------------------------- //
      //                           EVENTS                          //
      // --------------------------------------------------------- //
      // Bind click event to the document to hide list:
      domReady(function () {
        // ng-datalistが複数あると複数個登録されることに注意
        document.addEventListener('click', hideListImpl);
      })

      // Remove document click event on destroy:
      elem.on('$destroy', function () {
        document.removeEventListener('click', hideListImpl);
      });
    },
    template:
    '
'+
      '<input type="text" '+
             'class="ng-datalist-input {{inputClass}}" '+
             'ng-required="fieldRequired" '+
             'ng-model="ngModel" '+
             'ng-click="showList($event)" '+
             'ng-style="inputStyle" '+
             'ng-change="change($event)" '+
             'ng-keydown="keydown($event)" '+
             'ng-blur="blur($event)" '+
             'ng-disabled="ngDisabled">'+
      '
'+
        '
{{ item }}
'+
      '
'+
    '
'
  }
}
<|endoftext|>


<commit_before>import {CabinModel, RoomModel, FloorAreaModel, FloorModel} from 'models/commonModels';
import $ from 'jquery';
import 'ms-signalr-client';

export class Dashboard {
    activate() {
        var connection = $.hubConnection('enttoi-api.azurewebsites.net');
        var hub = connection.createHubProxy('commonHub');
        var vm = this;

        hub.on('sensorStatePush', function(state) {

            if(!vm.lastState || vm.lastState < state.timestamp)
                vm.lastState = state.timestamp;

            console.log(JSON.stringify(state));
        });

        /*return*/ connection.start({ })
            .done(function(){
                console.log('Connected');
                hub.requestInitialState();
                vm.hubConnected = true;
            })
            .fail(function(){
                console.log('Could not connect');
                vm.hubConnected = false;
            });
    }
}
<commit_msg>Subscriptions start<commit_after>import {CabinModel, RoomModel, FloorAreaModel, FloorModel} from 'models/commonModels';
import {inject} from 'aurelia-framework';
import {HttpClient} from 'aurelia-fetch-client';
import $ from 'jquery';
import 'ms-signalr-client';

@inject(HttpClient)
export class Dashboard {

    constructor(http) {
        this.connection = $.hubConnection('//enttoi-api.azurewebsites.net/');
        this.hub = this.connection.createHubProxy('commonHub');

        http.configure(config => {
            config
              .useStandardConfiguration()
              .withBaseUrl('//enttoi-api.azurewebsites.net/');
        });

        this.http = http;
    }

    activate() {
        var vm = this;

        this.hub.on('sensorStatePush', function(state) {

            if(!vm.lastState || vm.lastState < state.timestamp)
                vm.lastState = state.timestamp;

            console.log(JSON.stringify(state));
        });

        this.connection.start({ })
            .done(function(){
                console.log('Connected to hub');
                vm.hub.invoke('requestInitialState');
            })
            .fail(function(){
                console.log('Failed to connect to hub');
            });
    }

    deactivate(){
        this.connection.stop();
    }
}
<|endoftext|>


<commit_before>var monk = require('monk');

import {sites} from './config.js';

let dbInfoMap = new Map();

let newDB = (site, temp) => {
  let db = monk(site.db + (temp? '-temp' : ''));
  let dbInfo = {
    db,
    questions: db.get('questions'),
    answers: db.get('answers'),
    users: db.get('users'),
    tags: db.get('tags'),
    stats: db.get('stats'),
  };

  dbInfo.questions.index('id',{ unique: true });
  dbInfo.questions.index('page');
  dbInfo.questions.index('ownerUserId');
  dbInfo.answers.index('id', { unique: true});
  dbInfo.answers.index('id parentId', { unique: true });
  dbInfo.answers.index('ownerUserId');
  dbInfo.users.index('id', { unique: true });
  dbInfo.users.index('page');
  dbInfo.tags.index({ 'tagName': 1 }, { unique: true });

  return dbInfo;
};

sites.forEach(site => {
    dbInfoMap.set(site.slug, newDB(site));
    dbInfoMap.set(`${site.slug}-temp`, newDB(site, true));
});

function set(collection, query, obj) {
  return new Promise((resolve, reject) => {
    let retries = 0;
    try {
      collection.findAndModify(query, obj, { timeout: false }, (err, data) => {
        if (err) {
          reject(err);
          return;
        }
        if (data) {
          resolve(data);
        } else {
          collection.insert(obj, { timeout: false }, (err2, data2) => {
            if (err2) {
              reject(err2);
              return;
            }
            resolve(data2);
          });
        }
      });
    } catch (e) {
      retries++;
      console.error('caught exception in set with', retries, ' retries. Exception:', e);
      if (e.stack) {
        console.error(e.stack);
      }
      if (retries > 5) {
        throw e;
      }
      return set(collection, query, obj);
    }
  });
}

/**
 * Obtains an object for the key, and deserializes it
 */
function get(collection, query, options) {
  return new Promise((resolve, reject) => {
    let retries = 0;
    try {
      options = options || {};
      options.timeout = false;
      collection.find(query, options, (err, data) => {
        if (err) {
          reject(err);
          return;
        }
        resolve(data);
      });
    } catch (e) {
      retries++;
      console.error('caught exception in get with', retries, ' retries. Exception:', e);
      if (e.stack) {
        console.error(e.stack);
      }
      if (retries > 5) {
        throw e;
      }
      return get(collection, query, options);
    }
  });
}

/**
 * Obtains an object for the key, and deserializes it
 */
function getOne(collection, query, options) {
  return new Promise((resolve, reject) => {
    get(collection, query, options).then((data) => {
      resolve(data[0]);
    }).catch(reject);
  });
}

/**
 * Calls a callback for each item in a query resultset
 */
function getStream(collection, filter, eachCB) {
  return new Promise((resolve, reject) => {
    collection.find(filter, { stream: true, timeout: false })
      .each(eachCB)
      .error(reject)
      .success(resolve);
  });
}

/**
 * Adds the specified question to the DB
 * Note that there is only 1 entry total, not 1 per language.
 */
export function setStats(siteSlug, stats) {
  return set(dbInfoMap.get(siteSlug).stats, {}, stats);
}

/**
 * Adds the specified question to the DB
 * Note that there is only 1 entry total, not 1 per language.
 */
export function addQuestion(siteSlug, question) {
  return set(dbInfoMap.get(siteSlug).questions, { id: question.id }, question);
}

/**
 * Adds the specified answer to the DB
 * Note that there is only 1 entry total, not 1 per language.
 */
export function addAnswer(siteSlug, answer) {
  return set(dbInfoMap.get(siteSlug).answers, { id: answer.id, parentId: answer.parentId }, answer);
}

/**
 * Adds the specified user to the DB
 * Note that there is only 1 entry total, not 1 per language.
 */
export function addUser(siteSlug, user) {
  return set(dbInfoMap.get(siteSlug).users, { id: user.id}, user);
}

/**
 * Adds the specified tag to the DB to the tag list
 * Note that there is only 1 entry total, not 1 per language.
 */
export function addTag(siteSlug, tag) {
  return set(dbInfoMap.get(siteSlug).tags, { tagName: tag.tagName}, tag);
}

/**
 * Obtains all questions from the DB calling eachCB for each, and resolves once done
 * Results will be localized in the specified language.
 */
export function getQuestionsStream(siteSlug, lang, filter, eachCB) {
  return getStream(dbInfoMap.get(siteSlug).questions, filter, (question) => {
    // TODO: Normalize question to specified format
    eachCB(question);
  });
}

/**
 * Obtains all answers from the DB calling eachCB for each, and resolves once done
 * Results will be localized in the specified language.
 */
export function getAnswersStream(siteSlug, lang, filter, eachCB) {
  return getStream(dbInfoMap.get(siteSlug).answers, filter, (question) => {
    // TODO: Normalize question to specified format
    eachCB(question);
  });
}

/**
 * Obtains all users from the DB calling eachCB for each, and resolves once done
 * Results will be localized in the specified language.
 */
export function getUsersStream(siteSlug, lang, eachCB) {
  return getStream(dbInfoMap.get(siteSlug).users, {}, (user) => {
    // TODO: Normalize user to specified format
    eachCB(user);
  });
}

/**
 * Obtains all tags from the DB calling eachCB for each, and resolves once done
 * Results will be localized in the specified language.
 */
export function getTagsStream(siteSlug, lang, eachCB) {
  return getStream(dbInfoMap.get(siteSlug).tags, {}, (tag) => {
    // TODO: Normalize tag to specified format
    eachCB(tag);
  });
}

/**
 * Obtains the specified question from the DB.
 * Results will be localized in the specified language.
 */
export function getStats(siteSlug) {
  return getOne(dbInfoMap.get(siteSlug).stats, {});
}

/**
 * Obtains the specified question from the DB.
 * Results will be localized in the specified language.
 */
export function getQuestion(siteSlug, lang, questionId) {
  return new Promise((resolve, reject) => {
    getOne(dbInfoMap.get(siteSlug).questions, { id: questionId }).then(question => {
      // TODO: normalize question to localized format
      resolve(question);
    }).catch(reject);
  });
}

/**
 * Obtains all questions from the DB.
 * Results will be localized in the specified language.
 */
export function getQuestions(siteSlug, lang, page) {
  return new Promise((resolve, reject) => {
    get(dbInfoMap.get(siteSlug).questions, { page: Number(page) }).then(questions => {
      // TODO: normalize question to localized format
      resolve(questions);
    }).catch(reject);
  });
}

/**
 * Obtains all users from the DB.
 * Results will be localized in the specified language.
 */
export function getUsers(siteSlug, lang, page) {
  return new Promise((resolve, reject) => {
    get(dbInfoMap.get(siteSlug).users, { page: Number(page) }).then(users => {
      // TODO: normalize question to localized format
      resolve(users);
    }).catch(reject);
  });
}

/**
 * Obtains a single answer by the answerId.
 * Results will be localized in the specified language.
 */
export function getAnswer(siteSlug, lang, answerId) {
  return new Promise((resolve, reject) => {
    getOne(dbInfoMap.get(siteSlug).answers, { id: answerId }).then(answer => {
      // TODO: normalize answers to localized format
      resolve(answer);
    }).catch(reject);
  });
}

/**
 * Obtains a list of answers for the specified questionId.
 * Results will be localized in the specified language.
 */
export function getAnswers(siteSlug, lang, questionId) {
  return new Promise((resolve, reject) => {
    get(dbInfoMap.get(siteSlug).answers, { parentId: questionId }, { sort: { score: -1 }} ).then(answers => {
      // TODO: normalize answers to localized format
      resolve(answers);
    }).catch(reject);
  });
}

/**
 * Obtains the specified user from the DB
 * Results will be localized in the specified language.
 */
export function getUser(siteSlug, lang, userId) {
  return new Promise((resolve, reject) => {
    getOne(dbInfoMap.get(siteSlug).users, { id: userId }).then(user => {
      // TODO: normalize user to localized format
      resolve(user);
    }).catch(reject);
  });
}

export function getTags(siteSlug, lang) {
  return new Promise((resolve, reject) => {
    get(dbInfoMap.get(siteSlug).tags, {} ,{sort: { tagName: 1 }}).then(tags => {
      // TODO: normalize tags to localized format
      resolve(tags);
    }).catch(reject);
  });
}

export function getTag(siteSlug, lang, tagName) {
  return new Promise((resolve, reject) => {
    getOne(dbInfoMap.get(siteSlug).tags, { tagName }).then(tag => {
      // TODO: normalize tags to localized format
      resolve(tag);
    }).catch(reject);
  });
}

/**
 * Uninitialize the DB connection
 */
export function uninitDB() {
  dbInfoMap.forEach(dbInfo => dbInfo.db.close());
}
<commit_msg>Add functions to get count<commit_after>var monk = require('monk');

import {sites} from './config.js';

let dbInfoMap = new Map();

let newDB = (site, temp) => {
  let db = monk(site.db + (temp? '-temp' : ''));
  let dbInfo = {
    db,
    questions: db.get('questions'),
    answers: db.get('answers'),
    users: db.get('users'),
    tags: db.get('tags'),
    stats: db.get('stats'),
  };

  dbInfo.questions.index('id',{ unique: true });
  dbInfo.questions.index('page');
  dbInfo.questions.index('ownerUserId');
  dbInfo.answers.index('id', { unique: true});
  dbInfo.answers.index('id parentId', { unique: true });
  dbInfo.answers.index('ownerUserId');
  dbInfo.users.index('id', { unique: true });
  dbInfo.users.index('page');
  dbInfo.tags.index({ 'tagName': 1 }, { unique: true });

  return dbInfo;
};

sites.forEach(site => {
    dbInfoMap.set(site.slug, newDB(site));
    dbInfoMap.set(`${site.slug}-temp`, newDB(site, true));
});

function set(collection, query, obj) {
  return new Promise((resolve, reject) => {
    let retries = 0;
    try {
      collection.findAndModify(query, obj, { timeout: false }, (err, data) => {
        if (err) {
          reject(err);
          return;
        }
        if (data) {
          resolve(data);
        } else {
          collection.insert(obj, { timeout: false }, (err2, data2) => {
            if (err2) {
              reject(err2);
              return;
            }
            resolve(data2);
          });
        }
      });
    } catch (e) {
      retries++;
      console.error('caught exception in set with', retries, ' retries. Exception:', e);
      if (e.stack) {
        console.error(e.stack);
      }
      if (retries > 5) {
        throw e;
      }
      return set(collection, query, obj);
    }
  });
}

/**
 * Obtains an object for the key, and deserializes it
 */
function get(collection, query, options) {
  return new Promise((resolve, reject) => {
    let retries = 0;
    try {
      options = options || {};
      options.timeout = false;
      collection.find(query, options, (err, data) => {
        if (err) {
          reject(err);
          return;
        }
        resolve(data);
      });
    } catch (e) {
      retries++;
      console.error('caught exception in get with', retries, ' retries. Exception:', e);
      if (e.stack) {
        console.error(e.stack);
      }
      if (retries > 5) {
        throw e;
      }
      return get(collection, query, options);
    }
  });
}

/**
 * Obtains an object for the key, and deserializes it
 */
function count(collection, query) {
  return new Promise((resolve, reject) => {
    collection.count(query, (err, result) => {
      if (err) {
        reject(err);
        return;
      }
      resolve(result);
    });
  });
}

/**
 * Obtains an object for the key, and deserializes it
 */
function getOne(collection, query, options) {
  return new Promise((resolve, reject) => {
    get(collection, query, options).then((data) => {
      resolve(data[0]);
    }).catch(reject);
  });
}

/**
 * Calls a callback for each item in a query resultset
 */
function getStream(collection, filter, eachCB) {
  return new Promise((resolve, reject) => {
    collection.find(filter, { stream: true, timeout: false })
      .each(eachCB)
      .error(reject)
      .success(resolve);
  });
}

/**
 * Adds the specified question to the DB
 * Note that there is only 1 entry total, not 1 per language.
 */
export function setStats(siteSlug, stats) {
  return set(dbInfoMap.get(siteSlug).stats, {}, stats);
}

/**
 * Adds the specified question to the DB
 * Note that there is only 1 entry total, not 1 per language.
 */
export function addQuestion(siteSlug, question) {
  return set(dbInfoMap.get(siteSlug).questions, { id: question.id }, question);
}

/**
 * Adds the specified answer to the DB
 * Note that there is only 1 entry total, not 1 per language.
 */
export function addAnswer(siteSlug, answer) {
  return set(dbInfoMap.get(siteSlug).answers, { id: answer.id, parentId: answer.parentId }, answer);
}

/**
 * Adds the specified user to the DB
 * Note that there is only 1 entry total, not 1 per language.
 */
export function addUser(siteSlug, user) {
  return set(dbInfoMap.get(siteSlug).users, { id: user.id}, user);
}

/**
 * Adds the specified tag to the DB to the tag list
 * Note that there is only 1 entry total, not 1 per language.
 */
export function addTag(siteSlug, tag) {
  return set(dbInfoMap.get(siteSlug).tags, { tagName: tag.tagName}, tag);
}

/**
 * Obtains all questions from the DB calling eachCB for each, and resolves once done
 * Results will be localized in the specified language.
 */
export function getQuestionsStream(siteSlug, lang, filter, eachCB) {
  return getStream(dbInfoMap.get(siteSlug).questions, filter, (question) => {
    // TODO: Normalize question to specified format
    eachCB(question);
  });
}

/**
 * Obtains all answers from the DB calling eachCB for each, and resolves once done
 * Results will be localized in the specified language.
 */
export function getAnswersStream(siteSlug, lang, filter, eachCB) {
  return getStream(dbInfoMap.get(siteSlug).answers, filter, (question) => {
    // TODO: Normalize question to specified format
    eachCB(question);
  });
}

/**
 * Obtains all users from the DB calling eachCB for each, and resolves once done
 * Results will be localized in the specified language.
 */
export function getUsersStream(siteSlug, lang, eachCB) {
  return getStream(dbInfoMap.get(siteSlug).users, {}, (user) => {
    // TODO: Normalize user to specified format
    eachCB(user);
  });
}

/**
 * Obtains all tags from the DB calling eachCB for each, and resolves once done
 * Results will be localized in the specified language.
 */
export function getTagsStream(siteSlug, lang, eachCB) {
  return getStream(dbInfoMap.get(siteSlug).tags, {}, (tag) => {
    // TODO: Normalize tag to specified format
    eachCB(tag);
  });
}

/**
 * Obtains the specified question from the DB.
 * Results will be localized in the specified language.
 */
export function getStats(siteSlug) {
  return getOne(dbInfoMap.get(siteSlug).stats, {});
}

/**
 * Obtains the specified question from the DB.
 * Results will be localized in the specified language.
 */
export function getQuestion(siteSlug, lang, questionId) {
  return new Promise((resolve, reject) => {
    getOne(dbInfoMap.get(siteSlug).questions, { id: questionId }).then(question => {
      // TODO: normalize question to localized format
      resolve(question);
    }).catch(reject);
  });
}

/**
 * Obtains all questions from the DB.
 * Results will be localized in the specified language.
 */
export function getQuestions(siteSlug, lang, page) {
  return new Promise((resolve, reject) => {
    get(dbInfoMap.get(siteSlug).questions, { page: Number(page) }).then(questions => {
      // TODO: normalize question to localized format
      resolve(questions);
    }).catch(reject);
  });
}

/**
 * Obtains all users from the DB.
 * Results will be localized in the specified language.
 */
export function getUsers(siteSlug, lang, page) {
  return new Promise((resolve, reject) => {
    get(dbInfoMap.get(siteSlug).users, { page: Number(page) }).then(users => {
      // TODO: normalize question to localized format
      resolve(users);
    }).catch(reject);
  });
}

/**
 * Obtains a single answer by the answerId.
 * Results will be localized in the specified language.
 */
export function getAnswer(siteSlug, lang, answerId) {
  return new Promise((resolve, reject) => {
    getOne(dbInfoMap.get(siteSlug).answers, { id: answerId }).then(answer => {
      // TODO: normalize answers to localized format
      resolve(answer);
    }).catch(reject);
  });
}

/**
 * Obtains a list of answers for the specified questionId.
 * Results will be localized in the specified language.
 */
export function getAnswers(siteSlug, lang, questionId) {
  return new Promise((resolve, reject) => {
    get(dbInfoMap.get(siteSlug).answers, { parentId: questionId }, { sort: { score: -1 }} ).then(answers => {
      // TODO: normalize answers to localized format
      resolve(answers);
    }).catch(reject);
  });
}

/**
 * Obtains the specified user from the DB
 * Results will be localized in the specified language.
 */
export function getUser(siteSlug, lang, userId) {
  return new Promise((resolve, reject) => {
    getOne(dbInfoMap.get(siteSlug).users, { id: userId }).then(user => {
      // TODO: normalize user to localized format
      resolve(user);
    }).catch(reject);
  });
}

export function getTags(siteSlug, lang) {
  return new Promise((resolve, reject) => {
    get(dbInfoMap.get(siteSlug).tags, {} ,{sort: { tagName: 1 }}).then(tags => {
      // TODO: normalize tags to localized format
      resolve(tags);
    }).catch(reject);
  });
}

export function getTag(siteSlug, lang, tagName) {
  return new Promise((resolve, reject) => {
    getOne(dbInfoMap.get(siteSlug).tags, { tagName }).then(tag => {
      // TODO: normalize tags to localized format
      resolve(tag);
    }).catch(reject);
  });
}

export function getQuestionsCount(siteSlug, query = {}) {
  return count(dbInfoMap.get(siteSlug).questions, query);
}

export function getAnswersCount(siteSlug, query = {}) {
  return count(dbInfoMap.get(siteSlug).answers, query);
}

export function getTagsCount(siteSlug, query = {}) {
  return count(dbInfoMap.get(siteSlug).tags, query);
}

export function getUsersCount(siteSlug, query = {}) {
  return count(dbInfoMap.get(siteSlug).users, query);
}

/**
 * Uninitialize the DB connection
 */
export function uninitDB() {
  dbInfoMap.forEach(dbInfo => dbInfo.db.close());
}
<|endoftext|>


<commit_before>var jogoModulo = angular.module('jogoModulo', [])

jogoModulo.directive('jogoform', function(){
    return{
        restrict: 'E',
        replace: true,
        templateUrl: '/static/jogos/novo.html',
        scope:{
            game: '=',
            games: "=",
            isEditing: "=?",
            editOrCreate: "=?",
            formOnOff: "&"
        },
        controller:function($scope, $http){
            $scope.salvando = false;
           var save_or_edit_url =  '/jogos/rest/new';
            $scope.salvar = function(){
                $scope.salvando = true;
              if ($scope.isEditing){
                save_or_edit_url = '/jogos/rest/edit';
                $scope.game.jogo_id = $scope.game.id;
              }
              else{
                save_or_edit_url = '/jogos/rest/new';
                  $scope.games.push($scope.game);
              }
              $http.post(save_or_edit_url, $scope.game).success(function(game){
                  console.log(game);
                  $scope.game.tit='';
                  $scope.game.map='';
                  $scope.game.qtd='';
                  $scope.game.tmp='';
                  $scope.game.grp='';
                  $scope.salvando = false
                  $scope.formOnOff();
              }).error(function(errors){
                  $scope.errors=errors;
                  console.log(errors);
                  $scope.salvando = false;
              });
          };
        }
    };
});
<commit_msg>:thunder:<commit_after>var jogoModulo = angular.module('jogoModulo', [])

jogoModulo.directive('jogoform', function(){
    return{
        restrict: 'E',
        replace: true,
        templateUrl: '/static/jogos/novo.html',
        scope:{
            game: '=',
            games: "=",
            isEditing: "=?",
            editOrCreate: "=?",
            formOnOff: "&"
        },
        controller:function($scope, $http){
            $scope.salvando = false;
           var save_or_edit_url =  '/jogos/rest/new';
            $scope.salvar = function(){
                $scope.salvando = true;
              if ($scope.isEditing){
                save_or_edit_url = '/jogos/rest/edit';
                $scope.game.jogo_id = $scope.game.id;
              }
              else{
                save_or_edit_url = '/jogos/rest/new';
              }
              $http.post(save_or_edit_url, $scope.game).success(function(game){
                  console.log(game);
                  $scope.game.tit='';
                  $scope.game.map='';
                  $scope.game.qtd='';
                  $scope.game.tmp='';
                  $scope.game.grp='';
                  $scope.salvando = false
                  $scope.formOnOff();
                  $scope.games.push($scope.game);
              }).error(function(errors){
                  $scope.errors=errors;
                  console.log(errors);
                  $scope.salvando = false;
              });
          };
        }
    };
});
<|endoftext|>


<commit_before>let redis = require('redis');

let redisClient;
export function init(port) {
  redisClient = redis.createClient(port);
  redisClient.on('error', function (err) {
    console.error('DB: Error ' + err);
  });
}

/**
 * Adds an object to a list
 */
function pushToList(key, obj) {
  return new Promise((resolve, reject) => {
    redisClient.rpush(key, JSON.stringify(obj), err => {
      if (err) {
        reject(err);
      } else {
        resolve();
      }
    });
  });
}

/**
 * Obtains all items in a list
 */
function getListElements(key) {
  return new Promise((resolve, reject) => {
    redisClient.lrange(key, 0, -1, (err, replies) => {
      if (err) {
        reject(err);
        return;
      }
      resolve(replies.map(result => JSON.parse(result.toString())));
    });
  });
}

/**
 * Adds the specified commment to the DB to the location comments:{blogPostId}
 *
 * Comments typically contain:
 *   - name
 *   - email
 *   - homepage
 *   - body
 *   - datePosted
 */
export function addComment(blogPostId, comment) {
  comment.datePosted = new Date().toISOString();
  return pushToList(`comments:${blogPostId}`, comment);
}

/**
 * Obtains a list of comments for the specified blogPostId
 * See addComment for the data stored for each comment.
 */
export function getComments(blogPostId) {
  return getListElements(`comments:${blogPostId}`);
}
<commit_msg>Add a uninitRedis function<commit_after>let redis = require('redis');

let redisClient;
export function initRedis(port = 10226) {
  redisClient = redis.createClient(port);
  redisClient.on('error', function (err) {
    console.error('DB: Error ' + err);
  });
}

export function uninitRedis() {
  redisClient.quit();
}

/**
 * Adds an object to a list
 */
function pushToList(key, obj) {
  return new Promise((resolve, reject) => {
    redisClient.rpush(key, JSON.stringify(obj), err => {
      if (err) {
        reject(err);
      } else {
        resolve();
      }
    });
  });
}

/**
 * Obtains all items in a list
 */
function getListElements(key) {
  return new Promise((resolve, reject) => {
    redisClient.lrange(key, 0, -1, (err, replies) => {
      if (err) {
        reject(err);
        return;
      }
      resolve(replies.map(result => JSON.parse(result)));
    });
  });
}

/**
 * Adds the specified commment to the DB to the location comments:{blogPostId}
 *
 * Comments typically contain:
 *   - name
 *   - email
 *   - homepage
 *   - body
 *   - datePosted
 */
export function addComment(blogPostId, comment) {
  return pushToList(`comments:${blogPostId}`, comment);
}

/**
 * Obtains a list of comments for the specified blogPostId
 * See addComment for the data stored for each comment.
 */
export function getComments(blogPostId) {
  return getListElements(`comments:${blogPostId}`);
}
<|endoftext|>


<commit_before>/* istanbul ignore if */
if (typeof define !== "function") {
	var define = require("amdefine")(module);
}

define(function (require) {
	"use strict";

	var DateUtil,
		meta = require("../meta"),
		createClass = require("../class");

	DateUtil = createClass(
		meta({
			"name": "DateUtil",
			"type": "class",
			"description": "Singleton instance is exported and not class constructor",
			"properties": {
				"JANUARY": 0,
				"FEBRUARY": 1,
				"MARCH": 2,
				"APRIL": 3,
				"MAY": 4,
				"JUNE": 5,
				"JULY": 6,
				"AUGUST": 7,
				"SEPTEMBER": 8,
				"OCTOBER": 9,
				"NOVEMBER": 10,
				"DECEMBER": 11,

				"SUNDAY": 0,
				"MONDAY": 1,
				"TUESDAY": 2,
				"WEDNESDAY": 3,
				"THURSDAY": 4,
				"FRIDAY": 5,
				"SATURDAY": 6,

				"MILLISECONDS_IN_SECOND": 1000,
				"SECONDS_IN_MINUTE": 60,
				"MINUTES_IN_HOUR": 60,
				"HOURS_IN_DAY": 24,
				"DAYS_IN_WEEK": 7,
				"MONTHS_IN_QUARTER": 3,
				"MONTHS_IN_YEAR": 12,

				"NOON": 12,
				"MIDNIGHT": 12,

				"WEEKDAYS": ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
				"MONTHS": ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
			}
		})
	);

	DateUtil.method(
		meta({
			"name": "hoursFromStandard",
			"description": "Calculates the number of hours deviation from standard time. 0 if date is in standard time. A positive integer if in daylight savings time.",
			"arguments": [{
				"name": "date",
				"type": "date|string|number",
				"description": "A date object or a primitive value that represents a date that can be parsed."
			}],
			"returns": "number"
		}),
		hoursFromStandard
	);

	DateUtil.method(
		meta({
			"name": "isLeapYear",
			"description": "Tests if year is leap year",
			"arguments": [{
				"name": "year",
				"type": "number",
				"description": "A full year integer (ie... 1998)"
			}],
			"returns": "boolean"
		}),
		isLeapYear
	);

	DateUtil.method(
		meta({
			"name": "isDayLightSavings",
			"description": "Tests if date is within daylight savings time",
			"arguments": [{
				"name": "date",
				"type": "date|string|number",
				"description": "A date object or a primitive value that represents a date that can be parsed."
			}],
			"returns": "boolean"
		}),
		isDayLightSavings
	);

	DateUtil.method({
			name: "hoursFromStandard",
			signature: "!date"
		},
		function (dateLike) {
			return hoursFromStandard(new Date(dateLike));
		}
	);

	function hoursFromStandard (date) {
		var january = 0,
			july = 6,
			minutesInHour = 60,
			year = date.getFullYear(),
			offset = date.getTimezoneOffset(),
			januaryOffset = new Date(year, january, 1).getTimezoneOffset(),
			julyOffset = new Date(year, july, 1).getTimezoneOffset(),
			standardOffset = Math.max(januaryOffset, julyOffset);

		return (standardOffset - offset) / minutesInHour;
	}

	function isLeapYear (year) {
		var february = 1,
			leapDay = 29;

		return new Date(year, february, leapDay).getDate() === leapDay;
	}

	function isDayLightSavings (date) {
		return hoursFromStandard(date) > 0;
	}

	return DateUtil.singleton();
});<commit_msg>refactoring a bit and correcting isDayLightSavings to isDaylightSavings - lower l in light<commit_after>/* istanbul ignore if */
if (typeof define !== "function") {
	var define = require("amdefine")(module);
}

define(function (require) {
	"use strict";

	var DateUtil,
		meta = require("../meta"),
		createClass = require("../class");

	DateUtil = createClass(
		meta({
			"name": "DateUtil",
			"type": "class",
			"description": "Singleton instance is exported and not class constructor",
			"properties": {
				"JANUARY": 0,
				"FEBRUARY": 1,
				"MARCH": 2,
				"APRIL": 3,
				"MAY": 4,
				"JUNE": 5,
				"JULY": 6,
				"AUGUST": 7,
				"SEPTEMBER": 8,
				"OCTOBER": 9,
				"NOVEMBER": 10,
				"DECEMBER": 11,

				"SUNDAY": 0,
				"MONDAY": 1,
				"TUESDAY": 2,
				"WEDNESDAY": 3,
				"THURSDAY": 4,
				"FRIDAY": 5,
				"SATURDAY": 6,

				"MILLISECONDS_IN_SECOND": 1000,
				"SECONDS_IN_MINUTE": 60,
				"MINUTES_IN_HOUR": 60,
				"HOURS_IN_DAY": 24,
				"DAYS_IN_WEEK": 7,
				"MONTHS_IN_QUARTER": 3,
				"MONTHS_IN_YEAR": 12,

				"NOON": 12,
				"MIDNIGHT": 12,

				"WEEKDAYS": ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
				"MONTHS": ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
			}
		})
	);

	DateUtil.method(
		meta({
			"name": "hoursFromStandard",
			"description": "Calculates the number of hours deviation from standard time. 0 if date is in standard time. A positive integer if in daylight savings time.",
			"arguments": [{
				"name": "date",
				"type": "date|string|number",
				"description": "A date object or a primitive value that represents a date that can be parsed."
			}],
			"returns": "number"
		}),
		hoursFromStandard
	);

	// overload
	DateUtil.method({name:"hoursFromStandard", signature:"!date"}, hoursFromStandardDateLike);

	DateUtil.method(
		meta({
			"name": "isLeapYear",
			"description": "Tests if year is leap year",
			"arguments": [{
				"name": "year",
				"type": "number",
				"description": "A full year integer (ie... 1998)"
			}],
			"returns": "boolean"
		}),
		isLeapYear
	);

	DateUtil.method(
		meta({
			"name": "isDaylightSavings",
			"description": "Tests if date is within daylight savings time",
			"arguments": [{
				"name": "date",
				"type": "date|string|number",
				"description": "A date object or a primitive value that represents a date that can be parsed."
			}],
			"returns": "boolean"
		}),
		isDaylightSavings
	);

	function hoursFromStandard (date) {
		var january = 0,
			july = 6,
			minutesInHour = 60,
			year = date.getFullYear(),
			offset = date.getTimezoneOffset(),
			januaryOffset = new Date(year, january, 1).getTimezoneOffset(),
			julyOffset = new Date(year, july, 1).getTimezoneOffset(),
			standardOffset = Math.max(januaryOffset, julyOffset);

		return (standardOffset - offset) / minutesInHour;
	}

	function hoursFromStandardDateLike (dateLike) {
		return hoursFromStandard(new Date(dateLike));
	}

	function isLeapYear (year) {
		var february = 1,
			leapDay = 29;

		return new Date(year, february, leapDay).getDate() === leapDay;
	}

	function isDaylightSavings (date) {
		// could call this.hoursFromStandard but calling from prototype
		// makes isDaylightSavings safe to be removed from context
		return DateUtil.prototype.hoursFromStandard(date) > 0;
	}

	return DateUtil.singleton();
});<|endoftext|>


<commit_before>import * as util from './util';
import {makeReactor} from './reactors';
import * as types from './types';
import {derive as _derive} from './derivation.js';
import {unpack} from './unpack';
import {map, mMap, or, mOr, and, mAnd} from './combinators.js';

export var derivablePrototype = {
    /**
     * Creates a derived value whose state will always be f applied to this
     * value
     */
  derive: function (f, a, b, c, d) {
    var that = this;
    switch (arguments.length) {
    case 0:
      throw new Error('.derive takes at least one argument');
    case 1:
      if (typeof f === 'function') {
          return _derive(f, that);
      } else {
        if (f instanceof Array) {
          return f.map(function (x) {
            return that.derive(x);
          });
        } else if (types.isDerivable(f)) {
          return _derive(function () {
            var deriver = f.get();
            var thing = that.get();
            if (typeof deriver === 'function') {
              return deriver(thing);
            } else {
                throw Error('type error');
            }
          });
        } else {
          throw Error('type error');
        }
      }
    case 2:
      return _derive(f, that, a);
    case 3:
      return _derive(f, that, a, b);
    case 4:
      return _derive(f, that, a, b, c);
    case 5:
      return _derive(f, that, a, b, c, d);
    default:
      var args = ([f, that]).concat(util.slice(arguments, 1));
      return _derive.apply(null, args);
    }
  },

  map(f) {
    return map(f, this);
  },

  mMap(f) {
    return mMap(f, this);
  },

  react: function (f, opts) {
    makeReactor(this, f, opts);
  },

  mReact: function (f, opts) {
    var mWhen = _derive(() => Boolean(this.get()));
    if (opts && 'when' in opts && opts.when !== true) {
      var when = opts.when;
      if (typeof when === 'function' || when === false) {
        when = _derive(when);
      } else if (!types.isDerivable(when)) {
        throw new Error('when condition must be bool, function, or derivable');
      }
      mWhen = when.and(mWhen);
    }
    return this.react(f, util.assign({}, opts, {when: mWhen}));
  },

  is: function (other) {
    var x = this;
    return _derive(function () {
      return x.__equals(x.get(), unpack(other));
    });
  },

  or: function (other) {
    return or(this, other);
  },

  mOr: function (other) {
    return mOr(this, other);
  },

  and: function (other) {
    return and(this, other);
  },

  mAnd: function (other) {
    return mAnd(this, other);
  },

  mDerive: function (arg) {
    if (arguments.length === 1 && arg instanceof Array) {
      var that = this;
      return arg.map(function (a) { return that.mDerive(a); });
    } else {
      const thenClause = this.derive.apply(this, arguments);
      return this.derive(() => this.get() ? thenClause.get() : undefined);
    }
  },

  withEquality: function (equals) {
    if (equals) {
      if (typeof equals !== 'function') {
        throw new Error('equals must be function');
      }
    } else {
      equals = null;
    }

    return util.setEquals(this._clone(), equals);
  },

  __equals: function (a, b) {
    return (this._equals || util.equals)(a, b);
  },
};
<commit_msg>Remove derive and mDerive tuple support<commit_after>import * as util from './util';
import {makeReactor} from './reactors';
import * as types from './types';
import {derive as _derive} from './derivation.js';
import {unpack} from './unpack';
import {map, mMap, or, mOr, and, mAnd} from './combinators.js';

export var derivablePrototype = {
    /**
     * Creates a derived value whose state will always be f applied to this
     * value
     */
  derive: function (f, a, b, c, d) {
    var that = this;
    switch (arguments.length) {
    case 0:
      throw new Error('.derive takes at least one argument');
    case 1:
      if (typeof f === 'function') {
          return _derive(f, that);
      } else {
        if (types.isDerivable(f)) {
          return _derive(function () {
            var deriver = f.get();
            var thing = that.get();
            if (typeof deriver === 'function') {
              return deriver(thing);
            } else {
                throw Error('type error');
            }
          });
        } else {
          throw Error('type error');
        }
      }
    case 2:
      return _derive(f, that, a);
    case 3:
      return _derive(f, that, a, b);
    case 4:
      return _derive(f, that, a, b, c);
    case 5:
      return _derive(f, that, a, b, c, d);
    default:
      var args = ([f, that]).concat(util.slice(arguments, 1));
      return _derive.apply(null, args);
    }
  },

  map(f) {
    return map(f, this);
  },

  mMap(f) {
    return mMap(f, this);
  },

  react: function (f, opts) {
    makeReactor(this, f, opts);
  },

  mReact: function (f, opts) {
    var mWhen = _derive(() => Boolean(this.get()));
    if (opts && 'when' in opts && opts.when !== true) {
      var when = opts.when;
      if (typeof when === 'function' || when === false) {
        when = _derive(when);
      } else if (!types.isDerivable(when)) {
        throw new Error('when condition must be bool, function, or derivable');
      }
      mWhen = when.and(mWhen);
    }
    return this.react(f, util.assign({}, opts, {when: mWhen}));
  },

  is: function (other) {
    var x = this;
    return _derive(function () {
      return x.__equals(x.get(), unpack(other));
    });
  },

  or: function (other) {
    return or(this, other);
  },

  mOr: function (other) {
    return mOr(this, other);
  },

  and: function (other) {
    return and(this, other);
  },

  mAnd: function (other) {
    return mAnd(this, other);
  },

  mDerive: function (arg) {
    if (arguments.length === 1 && arg instanceof Array) {
      var that = this;
      return arg.map(function (a) { return that.mDerive(a); });
    } else {
      const thenClause = this.derive.apply(this, arguments);
      return this.derive(() => this.get() ? thenClause.get() : undefined);
    }
  },

  withEquality: function (equals) {
    if (equals) {
      if (typeof equals !== 'function') {
        throw new Error('equals must be function');
      }
    } else {
      equals = null;
    }

    return util.setEquals(this._clone(), equals);
  },

  __equals: function (a, b) {
    return (this._equals || util.equals)(a, b);
  },
};
<|endoftext|>


<commit_before>(function() {
  'use strict';
  angular
    .module('google.autocomplete', [])
    .config(Config)
    .directive('gmapAutocomplete', gmapAutocomplete);

  Config.$inject = ['uiGmapGoogleMapApiProvider'];

  function Config(uiGmapGoogleMapApiProvider) {
    uiGmapGoogleMapApiProvider.configure({
      key: '<your google maps api key goes here>',
      libraries: 'geometry,places'
    });
  };

  gmapAutocomplete.$inject = ['$q', 'uiGmapGoogleMapApi'];
  /* @ngInject */
  function gmapAutocomplete($q, uiGmapGoogleMapApi) {
    // Usage:
    //  You'll want three attributes on your input element:
    //  gmap-autocomplete: initializes the directive
    //  gmap-autocomplete-callback: takes a function from parent scope, called
    //                              when user selects an address from the dropdown
    //  gmap-autocomplete-model: takes a variable from parent scope, attaches
    //                           the google map API's Autocomplete object
    var directive = {
      link: link,
      scope: {
        gmapAutocompleteCallback: '&',
        gmapAutocompleteModel: '='
      }
    };
    return directive;
    function link(scope, element, attrs) {
      if (element[0].nodeName === 'INPUT') {
        // we don't want input's autocomplete to mess with our dropdown
        attrs.autocomplete = "off";

        generateAutocomplete(element[0], scope.gmapAutocompleteCallback)
        .then(function(autocomplete) {
          scope.gmapAutocompleteModel = autocomplete;
        });
      }
    }

    // Attach the google maps Autocomplete search box to an element,
    // bind a given callback to dropdown selection,
    // return the Autocomplete object
    function generateAutocomplete(element, changeCallback) {
      // make google.maps object available
      return uiGmapGoogleMapApi
      .then(function(maps) {
        console.log(maps);
        // promise-ify the navigator.geolocation request
        return $q(function(resolve, reject) {
          var autocomplete = new maps.places.Autocomplete(element, {types: ['geocode']});
          autocomplete.addListener('place_changed', changeCallback);

          // ask for user's position so we can bias gmap autocomplete
          // TODO: check for existence of window.navigator? old browsers exist...
          navigator.geolocation.getCurrentPosition(function(position) {
            var bounds = new maps.Circle({
              lat: position.coords.latitude,
              lng: position.coords.longitude
            });
            autocomplete.setBounds(bounds.getBounds());

            resolve(autocomplete);
          }, function() {
            // couldn't get position so we'll create an autocomplete without the bias
            resolve(autocomplete);
          });
        });
      });
    }
  }
})();<commit_msg>help directive resolve scope bindings<commit_after>(function() {
  'use strict';
  angular
    .module('google.autocomplete', [])
    .config(Config)
    .directive('gmapAutocomplete', gmapAutocomplete);

  Config.$inject = ['uiGmapGoogleMapApiProvider'];

  function Config(uiGmapGoogleMapApiProvider) {
    uiGmapGoogleMapApiProvider.configure({
      key: '<your google maps api key goes here>',
      libraries: 'geometry,places'
    });
  };

  gmapAutocomplete.$inject = ['$q', 'uiGmapGoogleMapApi'];
  /* @ngInject */
  function gmapAutocomplete($q, uiGmapGoogleMapApi) {
    // Usage:
    //  You'll want three attributes on your input element:
    //  gmap-autocomplete: initializes the directive
    //  gmap-autocomplete-callback: takes a function from parent scope, called
    //                              when user selects an address from the dropdown
    //  gmap-autocomplete-model: takes a variable from parent scope, attaches
    //                           the google map API's Autocomplete object
    var directive = {
      link: link,
      scope: {
        gmapAutocompleteCallback: '&?',
        gmapAutocompleteModel: '=?'
      }
    };
    return directive;
    function link(scope, element, attrs) {
      if (element[0].nodeName === 'INPUT') {
        // we don't want input's autocomplete to mess with our dropdown
        attrs.autocomplete = "off";

        generateAutocomplete(element[0], scope.gmapAutocompleteCallback)
        .then(function(autocomplete) {
          scope.gmapAutocompleteModel = autocomplete;
        });
      }
    }

    // Attach the google maps Autocomplete search box to an element,
    // bind a given callback to dropdown selection,
    // return the Autocomplete object
    function generateAutocomplete(element, changeCallback) {
      // make google.maps object available
      return uiGmapGoogleMapApi
      .then(function(maps) {
        console.log(maps);
        // promise-ify the navigator.geolocation request
        return $q(function(resolve, reject) {
          var autocomplete = new maps.places.Autocomplete(element, {types: ['geocode']});
          autocomplete.addListener('place_changed', changeCallback);

          // ask for user's position so we can bias gmap autocomplete
          // TODO: check for existence of window.navigator? old browsers exist...
          navigator.geolocation.getCurrentPosition(function(position) {
            var bounds = new maps.Circle({
              lat: position.coords.latitude,
              lng: position.coords.longitude
            });
            autocomplete.setBounds(bounds.getBounds());

            resolve(autocomplete);
          }, function() {
            // couldn't get position so we'll create an autocomplete without the bias
            resolve(autocomplete);
          });
        });
      });
    }
  }
})();<|endoftext|>


<commit_before>var Log = require('./log.js')

var fs = require('fs')

function Directory () {
  this.config = require('./config.json')
  this.path = this.config.directory.path
}

Directory.prototype.list = function (dir) {
  var files = fs.readdirSync(this.path + dir)
  var list = {}
  var totalSize = 0
  if (files.length > 0) {
    files.forEach(function (file) {
      var stats = fs.statSync(instDirectory.path + dir + file)
      if (stats.isFile()) {
        list[file] = stats
      } else {
        stats.size = sizeRecursif(instDirectory.path + dir + file)
        list[file] = stats
      }
      list[file].isfile = stats.isFile()
      list[file].isdir = stats.isDirectory()

      totalSize += stats.size

    })
    return {
      'totalSize': totalSize,
      'files': list
    }
  } else {
    return {}
  }
}

Directory.prototype.remove = function (file) {
  Log.print('Remove file: ' + file)
  fs.stat(this.path + file, function(err, stats){
    if(err) Log.print(err)
    if (stats.isDirectory()) {
      removeRecursif(instDirectory.path + file)
    } else {
      fs.unlink(instDirectory.path + file, function(err){
        if(err) Log.print(err)
      })
    }
  })

}

Directory.prototype.rename = function (path, oldname, newname) {
  Log.print('Rename: ' + oldname + ' In: ' + newname)
  fs.rename(this.path + path + '/' + oldname, this.path + path + '/' + newname, function(err){
    if(err) Log.print(err)
  })
}

Directory.prototype.mkdir = function (path, name) {
  Log.print('Mkdir: ' + path + '/' + name)
  fs.mkdir(this.path + path + '/' + name, function(err){
    if(err) Log.print(err)
  })
}

Directory.prototype.mv = function (path, file, folder) {
  Log.print('Move: ' + file + ' into ' + path + folder)
  fs.rename(this.path + path + file, this.path + path + folder + '/' + file, function(err){
    if(err) Log.print(err)
  })
}

function removeRecursif (path) {
  if (fs.existsSync(path)) {
    fs.readdirSync(path).forEach(function (file, index) {
      var curPath = path + '/' + file
      if (fs.lstatSync(curPath).isDirectory()) { // recurse
        removeRecursif(curPath)
      } else { // delete file
        fs.unlinkSync(curPath)
      }
    })
    fs.rmdirSync(path)
  }
}

function sizeRecursif (path) {
  var size = 0
  if (fs.existsSync(path)) {
    fs.readdirSync(path).forEach(function (file, index) {
      var curPath = path + '/' + file
      if (fs.lstatSync(curPath).isDirectory()) { // recurse
        size += sizeRecursif(curPath)
      } else { // read size
        size += fs.statSync(curPath).size
      }
    })
    return size
  }
}

var instDirectory = new Directory()
module.exports = instDirectory
<commit_msg>add cache on listing directory<commit_after>var Log = require('./log.js')

var fs = require('fs')

function Directory() {
  this.config = require('./config.json')
  this.path = this.config.directory.path

  this.dir = {}
}

Directory.prototype.list = function(dir) {

  if (this.dir[dir] == null) {
    this.dir[dir] = this.getDir(dir)
  } else  {
    if (this.dir[dir].ctime < fs.statSync(instDirectory.path + dir).ctime) {
      this.dir[dir] = this.getDir(dir)
    }
  }

  return {
    'totalSize': this.dir[dir].totalSize,
    'files': this.dir[dir].files
  }
}

Directory.prototype.getDir = function(dir) {
  var list = {}
  var totalSize = 0
  var files = fs.readdirSync(this.path + dir)

  if (files.length > 0) {
    files.forEach(function(file) {
      var stats = fs.statSync(instDirectory.path + dir + file)
      if (stats.isFile()) {
        list[file] = stats
      } else {
        stats.size = sizeRecursif(instDirectory.path + dir + file)
        list[file] = stats
      }
      list[file].isfile = stats.isFile()
      list[file].isdir = stats.isDirectory()

      totalSize += stats.size
    })
  }

  return {
    'ctime': fs.statSync(instDirectory.path + dir).ctime,
    'totalSize': totalSize,
    'files': list
  }
}

Directory.prototype.remove = function(file) {
  Log.print('Remove file: ' + file)
  fs.stat(this.path + file, function(err, stats) {
    if (err) Log.print(err)
    if (stats.isDirectory()) {
      removeRecursif(instDirectory.path + file)
    } else {
      fs.unlink(instDirectory.path + file, function(err) {
        if (err) Log.print(err)
      })
    }
  })

}

Directory.prototype.rename = function(path, oldname, newname) {
  Log.print('Rename: ' + oldname + ' In: ' + newname)
  fs.rename(this.path + path + '/' + oldname, this.path + path + '/' + newname, function(err) {
    if (err) Log.print(err)
  })
}

Directory.prototype.mkdir = function(path, name) {
  Log.print('Mkdir: ' + path + '/' + name)
  fs.mkdir(this.path + path + '/' + name, function(err) {
    if (err) Log.print(err)
  })
}

Directory.prototype.mv = function(path, file, folder) {
  Log.print('Move: ' + file + ' into ' + path + folder)
  fs.rename(this.path + path + file, this.path + path + folder + '/' + file, function(err) {
    if (err) Log.print(err)
  })
}

function removeRecursif(path) {
  if (fs.existsSync(path)) {
    fs.readdirSync(path).forEach(function(file, index) {
      var curPath = path + '/' + file
      if (fs.lstatSync(curPath).isDirectory()) { // recurse
        removeRecursif(curPath)
      } else { // delete file
        fs.unlinkSync(curPath)
      }
    })
    fs.rmdirSync(path)
  }
}

function sizeRecursif(path) {
  var size = 0
  if (fs.existsSync(path)) {
    fs.readdirSync(path).forEach(function(file, index) {
      var curPath = path + '/' + file
      if (fs.lstatSync(curPath).isDirectory()) { // recurse
        size += sizeRecursif(curPath)
      } else { // read size
        size += fs.statSync(curPath).size
      }
    })
    return size
  }
}

var instDirectory = new Directory()
module.exports = instDirectory
<|endoftext|>


<commit_before>describe('Favorites module', function() {
  'use strict';
  var locatorMap;
  beforeEach(function() {
    module('geolocator', 'partials', function($provide) {
      $provide.provider('locatorMap', {
        $get: function() {
          return {};
        }
      });
    });
    inject(function(_locatorMap_){
      locatorMap = _locatorMap_;
    });
  });

  describe('geolocator directive', function() {
    var element, $scope, $parentScope;

    beforeEach(function() {
      var compiled = utils.compile('<geolocator on-location-selected="locationSelected($lat, $lng)" key="a-key" ng-show="ngShowBinding"></geolocator>');
      element = compiled.element;
      $scope = compiled.scope;
      $parentScope = compiled.parentScope;
      $parentScope.ngShowBinding = false;
    });

    it('should load map from service when made visible', function() {
      locatorMap.loadMapScript = jasmine.createSpy('loadMapScript');
      expect(locatorMap.loadMapScript).not.toHaveBeenCalled();

      $scope.$apply(function() {
        $parentScope.ngShowBinding = true;
      });

      expect(locatorMap.loadMapScript).toHaveBeenCalledWith('geolocator-canvas', 'a-key');
    });

    it('should load map from service only the first time', function() {
      locatorMap.loadMapScript = jasmine.createSpy('loadMapScript');

      $scope.$apply(function() {
        $parentScope.ngShowBinding = true;
      });
      $scope.$apply(function() {
        $parentScope.ngShowBinding = false;
      });
      $scope.$apply(function() {
        $parentScope.ngShowBinding = true;
      });

      expect(locatorMap.loadMapScript.calls.count()).toBe(1);
    });

    it('should call parent\'s location selected method with location from service when location selected', function() {
      $parentScope.locationSelected = jasmine.createSpy('locationSelected');
      locatorMap.getLocation = jasmine.createSpy('getLocation').and.returnValue({
        lat: 'lat',
        lng: 'lng',
      });

      $scope.locationSelected();

      expect($parentScope.locationSelected).toHaveBeenCalledWith('lat', 'lng');
    });
  });
});
<commit_msg>fix invalid test name<commit_after>describe('geolocator module', function() {
  'use strict';
  var locatorMap;
  beforeEach(function() {
    module('geolocator', 'partials', function($provide) {
      $provide.provider('locatorMap', {
        $get: function() {
          return {};
        }
      });
    });
    inject(function(_locatorMap_){
      locatorMap = _locatorMap_;
    });
  });

  describe('geolocator directive', function() {
    var element, $scope, $parentScope;

    beforeEach(function() {
      var compiled = utils.compile('<geolocator on-location-selected="locationSelected($lat, $lng)" key="a-key" ng-show="ngShowBinding"></geolocator>');
      element = compiled.element;
      $scope = compiled.scope;
      $parentScope = compiled.parentScope;
      $parentScope.ngShowBinding = false;
    });

    it('should load map from service when made visible', function() {
      locatorMap.loadMapScript = jasmine.createSpy('loadMapScript');
      expect(locatorMap.loadMapScript).not.toHaveBeenCalled();

      $scope.$apply(function() {
        $parentScope.ngShowBinding = true;
      });

      expect(locatorMap.loadMapScript).toHaveBeenCalledWith('geolocator-canvas', 'a-key');
    });

    it('should load map from service only the first time', function() {
      locatorMap.loadMapScript = jasmine.createSpy('loadMapScript');

      $scope.$apply(function() {
        $parentScope.ngShowBinding = true;
      });
      $scope.$apply(function() {
        $parentScope.ngShowBinding = false;
      });
      $scope.$apply(function() {
        $parentScope.ngShowBinding = true;
      });

      expect(locatorMap.loadMapScript.calls.count()).toBe(1);
    });

    it('should call parent\'s location selected method with location from service when location selected', function() {
      $parentScope.locationSelected = jasmine.createSpy('locationSelected');
      locatorMap.getLocation = jasmine.createSpy('getLocation').and.returnValue({
        lat: 'lat',
        lng: 'lng',
      });

      $scope.locationSelected();

      expect($parentScope.locationSelected).toHaveBeenCalledWith('lat', 'lng');
    });
  });
});
<|endoftext|>


<commit_before>const shadowsocks_presets = [
  // [stream ciphers]
  [
    {"name": "ss-base"},
    {"name": "ss-stream-cipher", "params": {"method": "aes-256-ctr"}}
  ],
  [
    {"name": "ss-base"},
    {"name": "ss-stream-cipher", "params": {"method": "aes-256-cfb"}}
  ],
  [
    {"name": "ss-base"},
    {"name": "ss-stream-cipher", "params": {"method": "camellia-256-cfb"}}
  ],
  // [aead ciphers]
  [
    {"name": "ss-base"},
    {"name": "ss-aead-cipher", "params": {"method": "aes-256-gcm"}}
  ],
  [
    {"name": "ss-base"},
    {"name": "ss-aead-cipher", "params": {"method": "chacha20-poly1305"}}
  ],
  [
    {"name": "ss-base"},
    {"name": "ss-aead-cipher", "params": {"method": "chacha20-ietf-poly1305"}}
  ],
  [
    {"name": "ss-base"},
    {"name": "ss-aead-cipher", "params": {"method": "xchacha20-ietf-poly1305"}}
  ]
];
const shadowsocks_obfs_presets = [
  [
    {"name": "ss-base"},
    {"name": "ss-stream-cipher", "params": {"method": "aes-256-ctr"}},
    {"name": "obfs-tls1.2-ticket", "params": {"sni": ["test.com"]}}
  ],
  [
    {"name": "ss-base"},
    {"name": "obfs-random-padding"},
    {"name": "ss-stream-cipher", "params": {"method": "aes-256-ctr"}}
  ],
  [
    {"name": "ss-base"},
    {"name": "ss-aead-cipher", "params": {"method": "aes-256-gcm"}},
    {"name": "obfs-tls1.2-ticket", "params": {"sni": ["test.com"]}}
  ],
  [
    {"name": "ss-base"},
    {"name": "obfs-random-padding"},
    {"name": "ss-aead-cipher", "params": {"method": "aes-256-gcm"}}
  ]
];

const v2ray_presets = [
  [{"name": "v2ray-vmess", "params": {"id": "a3482e88-686a-4a58-8126-99c9df64b7bf", "security": "none"}}],
  [{"name": "v2ray-vmess", "params": {"id": "a3482e88-686a-4a58-8126-99c9df64b7bf", "security": "aes-128-gcm"}}],
  [{"name": "v2ray-vmess", "params": {"id": "a3482e88-686a-4a58-8126-99c9df64b7bf", "security": "chacha20-poly1305"}}]
];
const v2ray_obfs_presets = [
  [
    {"name": "v2ray-vmess", "params": {"id": "a3482e88-686a-4a58-8126-99c9df64b7bf", "security": "aes-128-gcm"}},
    {"name": "obfs-tls1.2-ticket", "params": {"sni": ["test.com"]}}
  ]
];

const blinksocks_presets = [
  [
    {"name": "base-auth-stream", "params": {"method": "aes-256-ctr"}}
  ],
  [
    {"name": "base-with-padding", "params": {"salt": "any string"}},
    {"name": "ss-stream-cipher", "params": {"method": "aes-256-ctr"}}
  ],
  [
    {"name": "base-with-padding", "params": {"salt": "any string"}},
    {"name": "ss-aead-cipher", "params": {"method": "aes-256-gcm"}}
  ],
  [
    {"name": "base-with-padding", "params": {"salt": "any string"}},
    {"name": "aead-random-cipher", "params": {"method": "aes-256-gcm"}}
  ],
  [
    {"name": "ss-base"},
    {"name": "aead-random-cipher", "params": {"method": "aes-256-gcm"}}
  ],

];
const blinksocks_obfs_presets = [
  [
    {"name": "base-auth-stream", "params": {"method": "aes-256-ctr"}},
    {"name": "obfs-tls1.2-ticket", "params": {"sni": ["test.com"]}}
  ],
  [
    {"name": "base-with-padding", "params": {"salt": "any string"}},
    {"name": "ss-stream-cipher", "params": {"method": "aes-256-ctr"}},
    {"name": "obfs-tls1.2-ticket", "params": {"sni": ["test.com"]}}
  ],
  [
    {"name": "base-with-padding", "params": {"salt": "any string"}},
    {"name": "obfs-random-padding"},
    {"name": "ss-stream-cipher", "params": {"method": "aes-256-ctr"}}
  ],
  [
    {"name": "base-with-padding", "params": {"salt": "any string"}},
    {"name": "ss-aead-cipher", "params": {"method": "aes-256-gcm"}},
    {"name": "obfs-tls1.2-ticket", "params": {"sni": ["test.com"]}}
  ],
  [
    {"name": "base-with-padding", "params": {"salt": "any string"}},
    {"name": "obfs-random-padding"},
    {"name": "ss-aead-cipher", "params": {"method": "aes-256-gcm"}}
  ],
  [
    {"name": "base-with-padding", "params": {"salt": "any string"}},
    {"name": "aead-random-cipher", "params": {"method": "aes-256-gcm"}},
    {"name": "obfs-tls1.2-ticket", "params": {"sni": ["test.com"]}}
  ],
  [
    {"name": "ss-base"},
    {"name": "aead-random-cipher", "params": {"method": "aes-256-gcm"}},
    {"name": "obfs-tls1.2-ticket", "params": {"sni": ["test.com"]}}
  ]
];

module.exports = [
  ...shadowsocks_presets,
  ...shadowsocks_obfs_presets,
  ...v2ray_presets,
  ...v2ray_obfs_presets,
  ...blinksocks_presets,
  ...blinksocks_obfs_presets
];
<commit_msg>benchmark: update test cases<commit_after>const shadowsocks_presets = [
  // [stream ciphers]
  [
    {"name": "ss-base"},
    {"name": "ss-stream-cipher", "params": {"method": "aes-256-ctr"}}
  ],
  [
    {"name": "ss-base"},
    {"name": "ss-stream-cipher", "params": {"method": "aes-256-cfb"}}
  ],
  [
    {"name": "ss-base"},
    {"name": "ss-stream-cipher", "params": {"method": "camellia-256-cfb"}}
  ],
  // [aead ciphers]
  [
    {"name": "ss-base"},
    {"name": "ss-aead-cipher", "params": {"method": "aes-256-gcm"}}
  ],
  [
    {"name": "ss-base"},
    {"name": "ss-aead-cipher", "params": {"method": "chacha20-poly1305"}}
  ],
  [
    {"name": "ss-base"},
    {"name": "ss-aead-cipher", "params": {"method": "chacha20-ietf-poly1305"}}
  ],
  [
    {"name": "ss-base"},
    {"name": "ss-aead-cipher", "params": {"method": "xchacha20-ietf-poly1305"}}
  ]
];
const shadowsocks_obfs_presets = [
  [
    {"name": "ss-base"},
    {"name": "ss-stream-cipher", "params": {"method": "aes-256-ctr"}},
    {"name": "obfs-tls1.2-ticket", "params": {"sni": ["test.com"]}}
  ],
  [
    {"name": "ss-base"},
    {"name": "obfs-random-padding"},
    {"name": "ss-stream-cipher", "params": {"method": "aes-256-ctr"}}
  ],
  [
    {"name": "ss-base"},
    {"name": "ss-aead-cipher", "params": {"method": "aes-256-gcm"}},
    {"name": "obfs-tls1.2-ticket", "params": {"sni": ["test.com"]}}
  ],
  [
    {"name": "ss-base"},
    {"name": "obfs-random-padding"},
    {"name": "ss-aead-cipher", "params": {"method": "aes-256-gcm"}}
  ]
];

const v2ray_presets = [
  [{"name": "v2ray-vmess", "params": {"id": "a3482e88-686a-4a58-8126-99c9df64b7bf", "security": "none"}}],
  [{"name": "v2ray-vmess", "params": {"id": "a3482e88-686a-4a58-8126-99c9df64b7bf", "security": "aes-128-gcm"}}],
  [{"name": "v2ray-vmess", "params": {"id": "a3482e88-686a-4a58-8126-99c9df64b7bf", "security": "chacha20-poly1305"}}]
];
const v2ray_obfs_presets = [
  [
    {"name": "v2ray-vmess", "params": {"id": "a3482e88-686a-4a58-8126-99c9df64b7bf", "security": "aes-128-gcm"}},
    {"name": "obfs-tls1.2-ticket", "params": {"sni": ["test.com"]}}
  ]
];

const blinksocks_presets = [
  [
    {"name": "base-auth"},
    {"name": "ss-stream-cipher", "params": {"method": "aes-256-ctr"}}
  ],
  [
    {"name": "base-auth"},
    {"name": "ss-aead-cipher", "params": {"method": "aes-256-gcm"}}
  ],
  [
    {"name": "base-auth"},
    {"name": "aead-random-cipher", "params": {"method": "aes-256-gcm"}}
  ],
  [
    {"name": "ss-base"},
    {"name": "aead-random-cipher", "params": {"method": "aes-256-gcm"}}
  ]
];
const blinksocks_obfs_presets = [
  [
    {"name": "base-auth"},
    {"name": "ss-stream-cipher", "params": {"method": "aes-256-ctr"}},
    {"name": "obfs-tls1.2-ticket", "params": {"sni": ["test.com"]}}
  ],
  [
    {"name": "base-auth"},
    {"name": "obfs-random-padding"},
    {"name": "ss-stream-cipher", "params": {"method": "aes-256-ctr"}}
  ],
  [
    {"name": "base-auth"},
    {"name": "ss-aead-cipher", "params": {"method": "aes-256-gcm"}},
    {"name": "obfs-tls1.2-ticket", "params": {"sni": ["test.com"]}}
  ],
  [
    {"name": "base-auth"},
    {"name": "obfs-random-padding"},
    {"name": "ss-aead-cipher", "params": {"method": "aes-256-gcm"}}
  ],
  [
    {"name": "base-auth"},
    {"name": "aead-random-cipher", "params": {"method": "aes-256-gcm"}},
    {"name": "obfs-tls1.2-ticket", "params": {"sni": ["test.com"]}}
  ],
  [
    {"name": "ss-base"},
    {"name": "aead-random-cipher", "params": {"method": "aes-256-gcm"}},
    {"name": "obfs-tls1.2-ticket", "params": {"sni": ["test.com"]}}
  ]
];

module.exports = [
  ...shadowsocks_presets,
  ...shadowsocks_obfs_presets,
  ...v2ray_presets,
  ...v2ray_obfs_presets,
  ...blinksocks_presets,
  ...blinksocks_obfs_presets
];
<|endoftext|>


<commit_before>//
// Reload the app if server detects local change
//
(function() {
    var url = document.location.protocol + '//' + document.location.host + '/__api__/autoreload';

    function postStatus() {
        var xhr = new XMLHttpRequest();
        xhr.open('post', url, true);
        xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
        xhr.onreadystatechange = function() {
            if (this.readyState === 4 && /^[2]/.test(this.status)) {
            }
        };
        xhr.send();
    }

    function checkForReload() {
        var xhr = new XMLHttpRequest();
        xhr.open('get', url, true);
        xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
        xhr.onreadystatechange = function() {
            if (this.readyState === 4 && /^[2]/.test(this.status)) {
                var response = JSON.parse(this.responseText);
                if (response.content.outdated) {
                    postStatus();
                    window.location.reload();
                }
            }
        };
        xhr.send();
    }

    setInterval(checkForReload, 1000 * 3);
})(window);
<commit_msg>fix autoreload callback loop<commit_after>//
// Reload the app if server detects local change
//
(function() {
    var url = document.location.protocol + '//' + document.location.host + '/__api__/autoreload';

    function postStatus() {
        var xhr = new XMLHttpRequest();
        xhr.open('post', url, true);
        xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
        xhr.onreadystatechange = function() {
            if (this.readyState === 4 && /^[2]/.test(this.status)) {
                window.location.reload();
            }
        };
        xhr.send();
    }

    function checkForReload() {
        var xhr = new XMLHttpRequest();
        xhr.open('get', url, true);
        xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
        xhr.onreadystatechange = function() {
            if (this.readyState === 4 && /^[2]/.test(this.status)) {
                var response = JSON.parse(this.responseText);
                if (response.content.outdated) {
                    postStatus();
                }
            }
        };
        xhr.send();
    }

    setInterval(checkForReload, 1000 * 3);
})(window);
<|endoftext|>


<commit_before>var FB = (function(){
  var self = { };

  self.init = function(options) {
    FBStub.appId(options.appId);
  };

  self.login = function(callback) {
    if (!FBStub.initialized()) return;
    FBStub.loginCallback = callback;
  };

  self.getLoginStatus = function(callback) {
    if (!FBStub.initialized()) return;
    var status;
    var authResponse = null;

    if (FBStub.isLoggedIn()) {
      if (FBStub.isConnected()) {
        status = "connected";
        authResponse = {
          accessToken: "",
          expiresIn: 4095,
          signedRequest: "",
          userID: FBStub.userID()
        };
      }
      else {
        status = "not_authorized";
      }
    }
    else {
      status = "unknown";
    }

    callback({
      status: status,
      authResponse: authResponse
    });
  };

  return self;
}( ));

var FBStub = (function() {
  var self = { };

  var state;

  var initialize = function() {
    state = {
      'loggedIn': false,
      'connected': false,
      'appId': null,
      'user': {}
    };
  };

  initialize();

  self.loggedIn = function(user) {
    state.loggedIn = true;
    state.user = user || {};
  };

  self.notLoggedIn = function() {
    state.loggedIn = false;
    state.user = {};
  };

  self.connected = function() {
    state.connected = true;
  };

  self.notConnected = function() {
    state.connected = false;
  };

  self.isLoggedIn = function() {
    return state.loggedIn;
  };

  self.isConnected = function() {
    return state.connected;
  };

  self.userID = function() {
    return state.user.userID;
  };

  self.appId = function(id) {
    if (id) {
      state.appId = id;
    }
    return state.appId;
  };

  self.reset = function() {
    initialize();
  };

  self.logInAndAuthorize = function() {
    if (!self.initialized()) return;
    self.loginCallback({
      status: "connected",
      authResponse: {
        accessToken: "",
        userID: "",
        expiresIn: 4374,
        signedRequest: ""
      }
    });
  };

  self.logInAndDeny = function() {
    if (!self.initialized()) return;
    self.loginCallback({
      status: "not_authorized",
      authResponse: null
    });
  };

  self.abortLogIn = function() {
    if (!self.initialized()) return;
    self.loginCallback({
      status: "unknown",
      authResponse: null
    });
  };

  self.initialized = function() {
    var appId = state.appId;
    return (typeof(appId) == 'number' || typeof(appId) == "string");
  };

  return self;
}( ));
<commit_msg>Updated compiled JavaScript library<commit_after>var FB = (function(){
  var self = { };

  self.init = function(options) {
    FBStub.appId(options.appId);
  };

  self.login = function(callback) {
    if (!FBStub.initialized()) return;
    FBStub.loginCallback = callback;
  };

  self.getLoginStatus = function(callback) {
    if (!FBStub.initialized()) return;
    var status;
    var authResponse = null;

    if (FBStub.isLoggedIn()) {
      if (FBStub.isConnected()) {
        status = "connected";
        authResponse = {
          accessToken: "",
          expiresIn: 4095,
          signedRequest: "",
          userID: FBStub.userID()
        };
      }
      else {
        status = "not_authorized";
      }
    }
    else {
      status = "unknown";
    }

    callback({
      status: status,
      authResponse: authResponse
    });
  };

  self.api = function(path, callback) {
    FBStub.addApiRequest(path, callback);
  };

  return self;
}( ));

var FBStub = (function() {
  var self = { };

  var state;

  var initialize = function() {
    state = {
      'loggedIn': false,
      'connected': false,
      'appId': null,
      'user': {}
    };
  };

  initialize();

  var apiRequests = { };

  self.addApiRequest = function(path, callback) {
    apiRequests[path] = callback;
  };

  self.loggedIn = function(user) {
    state.loggedIn = true;
    state.user = user || {};
  };

  self.notLoggedIn = function() {
    state.loggedIn = false;
    state.user = {};
  };

  self.connected = function() {
    state.connected = true;
  };

  self.notConnected = function() {
    state.connected = false;
  };

  self.isLoggedIn = function() {
    return state.loggedIn;
  };

  self.isConnected = function() {
    return state.connected;
  };

  self.userID = function() {
    return state.user.userID;
  };

  self.appId = function(id) {
    if (id) {
      state.appId = id;
    }
    return state.appId;
  };

  self.reset = function() {
    initialize();
  };

  self.logInAndAuthorize = function() {
    if (!self.initialized()) return;
    self.loginCallback({
      status: "connected",
      authResponse: {
        accessToken: "",
        userID: "",
        expiresIn: 4374,
        signedRequest: ""
      }
    });
  };

  self.logInAndDeny = function() {
    if (!self.initialized()) return;
    self.loginCallback({
      status: "not_authorized",
      authResponse: null
    });
  };

  self.abortLogIn = function() {
    if (!self.initialized()) return;
    self.loginCallback({
      status: "unknown",
      authResponse: null
    });
  };

  self.respondToApiRequest = function(path, response) {
    if (typeof(apiRequests[path]) === 'undefined') return;
    apiRequests[path](response);
  };

  self.initialized = function() {
    var appId = state.appId;
    return (typeof(appId) == 'number' || typeof(appId) == "string");
  };

  return self;
}( ));
<|endoftext|>


<commit_before>var request = require('request');
var async = require('async');

var table_port = process.env['TEABAG_TABLE_PORT'];
var store_port = process.env['TEABAG_STORE_PORT']

var table_url = process.env['TEABAG_STORE_URL'];
var store_url = process.env['TEABAG_STORE_URL'];

var table_key = process.env['TEABAG_TABLE_KEY'];
var store_key = process.env['TEABAG_STORE_KEY'];

var user_id = parseInt(process.argv[2], 10);
var master = process.argv[3];
var channel = process.argv[4];

if(!user_id || !master || channel) {
    console.log('Usage: node add_user.js {user_id} {master} {channel}');
      process.exit(1);
}

var store_code = '';

async.series([
  function(cb_) {
    var t_url = table_url + 'admin/user/' + user_id + '/master/' + master;
    console.log('>>>> PUT ' + t_url);
    request.put(t_url, {
      auth: {
        user: 'admin',
        pass: table_key
      }
    }, cb_);
  },
  function(cb_) {
    var s_url = store_url + 'admin/user/' + user_id;
    console.log('>>>> PUT ' + s_url);
    request.put(s_url, {
      auth: {
        user: 'admin',
        pass: store_key
      }
    }, cb_);
  },
  function(cb_) {
    var s_url = store_url + 'admin/user/' + user_id + '/code'
    console.log('>>>> GET ' + s_url);
    request.get('http://localhost:' + store.port + '/admin/user/' + my.user.id + '/code', {
      auth: {
        user: 'admin',
        pass: store_key,
      },
      json: true
    }, function(err, res, body) {
      if(err) {
        return cb_(err);
      }
      store_code = body.code;
      return cb_();
    });
  },
  function(cb_) {
    /*
    var t_url = table_url + 'table/' + my.user.channel + '/store?master=' + my.user.master;
    //console.log('>>>> ' + t_url);
    request.post(t_url, {
      json: {
        store_url: store.url,
        code: store.code
      }
    }, cb_);
    */
  }
<commit_msg>Adduser Script<commit_after>var request = require('request');
var async = require('async');

var table_port = process.env['TEABAG_TABLE_PORT'];
var store_port = process.env['TEABAG_STORE_PORT']

var table_url = process.env['TEABAG_TABLE_URL'];
var store_url = process.env['TEABAG_STORE_URL'];

var table_key = process.env['TEABAG_TABLE_KEY'];
var store_key = process.env['TEABAG_STORE_KEY'];

var user_id = parseInt(process.argv[2], 10);
var master = process.argv[3];
var channel = process.argv[4];

if(!user_id || !master || !channel) {
    console.log('Usage: node add_user.js {user_id} {master} {channel}');
      process.exit(1);
}

var store_code = '';

async.series([
  function(cb_) {
    var t_url = table_url + 'admin/user/' + user_id + '/master/' + master;
    console.log('>>>> PUT ' + t_url);
    console.log(table_key);
    request.put(t_url, {
      auth: {
        user: 'admin',
        pass: table_key
      },
      json: true
    }, function(err, res, json) {
      if(err) {
        return cb_(err);
      }
      if(!json || !json.ok) {
        return cb_(new Error(t_url));
      }
      return cb_();
    });
  },
  function(cb_) {
    var s_url = store_url + 'admin/user/' + user_id;
    console.log('>>>> PUT ' + s_url);
    request.put(s_url, {
      auth: {
        user: 'admin',
        pass: store_key
      },
      json: true
    }, function(err, res, json) {
      if(err) {
        return cb_(err);
      }
      if(!json || !json.ok) {
        return cb_(new Error(s_url));
      }
      return cb_();
    });
  },
  function(cb_) {
    var s_url = store_url + 'admin/user/' + user_id + '/code'
    console.log('>>>> GET ' + s_url);
    request.get(s_url, {
      auth: {
        user: 'admin',
        pass: store_key,
      },
      json: true
    }, function(err, res, body) {
      if(err) {
        return cb_(err);
      }
      store_code = body.code;
      return cb_();
    });
  },
  function(cb_) {
    var t_url = table_url + 'user/' + user_id + '/table/' + channel + '/store?master=' + master;
    console.log('>>>> POST ' + t_url);
    console.log(store_url + 'user/' + user_id + '/');
    console.log(store_code);
    request.post(t_url, {
      json: {
        store_url: store_url + 'user/' + user_id + '/',
        code: store_code
      }
    }, function(err, res, json) {
      if(err) {
        return cb_(err);
      }
      if(!json || !json.store_id) {
        console.log(json);
        return cb_(new Error(t_url));
      }
      return cb_();
    });
  }
], function(err) {
  if(err) {
    console.log(err);
    process.exit(1);
  }
  console.log('TABLE_URL: ' + table_url + 'user/' + user_id);
  console.log('MASTER: ' + master);
  console.log('CHANNEL: ' + channel);
  process.exit(0);
});
<|endoftext|>