<commit_before>'use strict';

angular.module('mgcrea.ngStrap.modal', ['mgcrea.ngStrap.core', 'mgcrea.ngStrap.helpers.dimensions'])

  .provider('$modal', function () {

    var defaults = this.defaults = {
      animation: 'am-fade',
      backdropAnimation: 'am-fade',
      customClass: '',
      prefixClass: 'modal',
      prefixEvent: 'modal',
      placement: 'top',
      templateUrl: 'modal/modal.tpl.html',
      template: '',
      contentTemplate: false,
      container: false,
      element: null,
      backdrop: true,
      keyboard: true,
      html: false,
      show: true,
      size: null
    };

    this.$get = function ($window, $rootScope, $bsCompiler, $animate, $timeout, $sce, dimensions) {

      var forEach = angular.forEach;
      var requestAnimationFrame = $window.requestAnimationFrame || $window.setTimeout;
      var bodyElement = angular.element($window.document.body);

      var backdropCount = 0;
      var dialogBaseZindex = 1050;
      var backdropBaseZindex = 1040;

      var validSizes = {
        lg: 'modal-lg',
        sm: 'modal-sm'
      };

      function ModalFactory(config) {

        var $modal = {};

        // Common vars
        var options = $modal.$options = angular.extend({}, defaults, config);
        var promise = $modal.$promise = $bsCompiler.compile(options);
        var scope = $modal.$scope = options.scope && options.scope.$new() || $rootScope.$new();

        if (!options.element && !options.container) {
          options.container = 'body';
        }

        // Store $id to identify the triggering element in events
        // give priority to options.id, otherwise, try to use
        // element id if defined
        $modal.$id = options.id || options.element && options.element.attr('id') || '';

        // Support scope as string options
        forEach(['title', 'content'], function (key) {
          if (options[key]) scope[key] = $sce.trustAsHtml(options[key]);
        });

        // Provide scope helpers
        scope.$hide = function () {
          scope.$$postDigest(function () {
            $modal.hide();
          });
        };
        scope.$show = function () {
          scope.$$postDigest(function () {
            $modal.show();
          });
        };
        scope.$toggle = function () {
          scope.$$postDigest(function () {
            $modal.toggle();
          });
        };
        // Publish isShown as a protected var on scope
        $modal.$isShown = scope.$isShown = false;

        // Fetch, compile then initialize modal
        var compileData;
        var modalElement;
        var modalScope;
        var backdropElement = angular.element('
');
        backdropElement.css({position: 'fixed', top: '0px', left: '0px', bottom: '0px', right: '0px'});
        promise.then(function (data) {
          compileData = data;
          $modal.init();
        });

        $modal.init = function () {

          // Options: show
          if (options.show) {
            scope.$$postDigest(function () {
              $modal.show();
            });
          }

        };

        $modal.destroy = function () {

          // Remove element
          destroyModalElement();

          // remove backdrop element
          if (backdropElement) {
            backdropElement.remove();
            backdropElement = null;
          }

          // Destroy scope
          scope.$destroy();
        };

        $modal.show = function () {
          if ($modal.$isShown) return;

          var parent;
          var after;
          if (angular.isElement(options.container)) {
            parent = options.container;
            after = options.container[0].lastChild ? angular.element(options.container[0].lastChild) : null;
          } else {
            if (options.container) {
              parent = findElement(options.container);
              after = parent[0] && parent[0].lastChild ? angular.element(parent[0].lastChild) : null;
            } else {
              parent = null;
              after = options.element;
            }
          }

          // destroy any existing modal elements
          if (modalElement) destroyModalElement();

          // create a new scope, so we can destroy it and all child scopes
          // when destroying the modal element
          modalScope = $modal.$scope.$new();
          // Fetch a cloned element linked from template (noop callback is required)
          modalElement = $modal.$element = compileData.link(modalScope, function (clonedElement, scope) {});

          if (options.backdrop) {
            // set z-index
            modalElement.css({'z-index': dialogBaseZindex + (backdropCount * 20)});
            backdropElement.css({'z-index': backdropBaseZindex + (backdropCount * 20)});

            // increment number of backdrops
            backdropCount++;
          }

          if (scope.$emit(options.prefixEvent + '.show.before', $modal).defaultPrevented) {
            return;
          }

          // Set the initial positioning.
          modalElement.css({display: 'block'}).addClass(options.placement);

          // Options: customClass
          if (options.customClass) {
            modalElement.addClass(options.customClass);
          }

          // Options: size
          if(options.size && validSizes[options.size]) {
            angular.element(findElement('.modal-dialog', modalElement[0])).addClass(validSizes[options.size]);
          }

          // Options: animation
          if (options.animation) {
            if (options.backdrop) {
              backdropElement.addClass(options.backdropAnimation);
            }
            modalElement.addClass(options.animation);
          }

          if (options.backdrop) {
            $animate.enter(backdropElement, bodyElement, null);
          }

          // Support v1.2+ $animate
          // https://github.com/angular/angular.js/issues/11713
          if (angular.version.minor <= 2) {
            $animate.enter(modalElement, parent, after, enterAnimateCallback);
          } else {
            $animate.enter(modalElement, parent, after).then(enterAnimateCallback);
          }

          $modal.$isShown = scope.$isShown = true;
          safeDigest(scope);
          // Focus once the enter-animation has started
          // Weird PhantomJS bug hack
          var el = modalElement[0];
          requestAnimationFrame(function () {
            el.focus();
          });

          bodyElement.addClass(options.prefixClass + '-open');
          if (options.animation) {
            bodyElement.addClass(options.prefixClass + '-with-' + options.animation);
          }

          // Bind events
          bindBackdropEvents();
          bindKeyboardEvents();
        };

        function enterAnimateCallback() {
          scope.$emit(options.prefixEvent + '.show', $modal);
        }

        $modal.hide = function () {
          if (!$modal.$isShown) return;

          if (options.backdrop) {
            // decrement number of modals
            backdropCount--;
          }

          if (scope.$emit(options.prefixEvent + '.hide.before', $modal).defaultPrevented) {
            return;
          }

          // Support v1.2+ $animate
          // https://github.com/angular/angular.js/issues/11713
          if (angular.version.minor <= 2) {
            $animate.leave(modalElement, leaveAnimateCallback);
          } else {
            $animate.leave(modalElement).then(leaveAnimateCallback);
          }

          if (options.backdrop) {
            $animate.leave(backdropElement);
          }
          $modal.$isShown = scope.$isShown = false;
          safeDigest(scope);

          // Unbind events
          unbindBackdropEvents();
          unbindKeyboardEvents();
        };

        function leaveAnimateCallback() {
          scope.$emit(options.prefixEvent + '.hide', $modal);
          bodyElement.removeClass(options.prefixClass + '-open');
          if (options.animation) {
            bodyElement.removeClass(options.prefixClass + '-with-' + options.animation);
          }
        }

        $modal.toggle = function () {
          if ($modal.$isShown) {
            $modal.hide();
          } else {
            $modal.show();
          }
        };

        $modal.focus = function () {
          modalElement[0].focus();
        };

        // Protected methods

        $modal.$onKeyUp = function (evt) {

          if (evt.which === 27 && $modal.$isShown) {
            $modal.hide();
            evt.stopPropagation();
          }

        };

        function bindBackdropEvents() {
          if (options.backdrop) {
            modalElement.on('click', hideOnBackdropClick);
            backdropElement.on('click', hideOnBackdropClick);
            backdropElement.on('wheel', preventEventDefault);
          }
        }

        function unbindBackdropEvents() {
          if (options.backdrop) {
            modalElement.off('click', hideOnBackdropClick);
            backdropElement.off('click', hideOnBackdropClick);
            backdropElement.off('wheel', preventEventDefault);
          }
        }

        function bindKeyboardEvents() {
          if (options.keyboard) {
            modalElement.on('keyup', $modal.$onKeyUp);
          }
        }

        function unbindKeyboardEvents() {
          if (options.keyboard) {
            modalElement.off('keyup', $modal.$onKeyUp);
          }
        }

        // Private helpers

        function hideOnBackdropClick(evt) {
          if (evt.target !== evt.currentTarget) return;
          if (options.backdrop === 'static') {
            $modal.focus();
          } else {
            $modal.hide();
          }
        }

        function preventEventDefault(evt) {
          evt.preventDefault();
        }

        function destroyModalElement() {
          if ($modal.$isShown && modalElement !== null) {
            // un-bind events
            unbindBackdropEvents();
            unbindKeyboardEvents();
          }

          if (modalScope) {
            modalScope.$destroy();
            modalScope = null;
          }

          if (modalElement) {
            modalElement.remove();
            modalElement = $modal.$element = null;
          }
        }

        return $modal;

      }

      // Helper functions

      function safeDigest(scope) {
        /* eslint-disable no-unused-expressions */
        scope.$$phase || (scope.$root && scope.$root.$$phase) || scope.$digest();
        /* eslint-enable no-unused-expressions */
      }

      function findElement(query, element) {
        return angular.element((element || document).querySelectorAll(query));
      }

      return ModalFactory;

    };

  })

  .directive('bsModal', function ($window, $sce, $modal) {

    return {
      restrict: 'EAC',
      scope: true,
      link: function postLink(scope, element, attr, transclusion) {

        // Directive options
        var options = {scope: scope, element: element, show: false};
        angular.forEach(['template', 'templateUrl', 'controller', 'controllerAs', 'contentTemplate', 'placement', 'backdrop', 'keyboard', 'html', 'container', 'animation', 'backdropAnimation', 'id', 'prefixEvent', 'prefixClass', 'customClass', 'modalClass', 'size'], function (key) {
          if (angular.isDefined(attr[key])) options[key] = attr[key];
        });

        // Options: alias modalClass to customClass
        if (options.modalClass) {
          options.customClass = options.modalClass;
        }

        // use string regex match boolean attr falsy values, leave truthy values be
        var falseValueRegExp = /^(false|0|)$/i;
        angular.forEach(['backdrop', 'keyboard', 'html', 'container'], function (key) {
          if (angular.isDefined(attr[key]) && falseValueRegExp.test(attr[key])) options[key] = false;
        });

        // Support scope as data-attrs
        angular.forEach(['title', 'content'], function (key) {
          if (attr[key]) {
            attr.$observe(key, function (newValue, oldValue) {
              scope[key] = $sce.trustAsHtml(newValue);
            });
          }
        });

        // Support scope as an object
        if (attr.bsModal) {
          scope.$watch(attr.bsModal, function (newValue, oldValue) {
            if (angular.isObject(newValue)) {
              angular.extend(scope, newValue);
            } else {
              scope.content = newValue;
            }
          }, true);
        }

        // Initialize modal
        var modal = $modal(options);

        // Trigger
        element.on(attr.trigger || 'click', modal.toggle);

        // Garbage collection
        scope.$on('$destroy', function () {
          if (modal) modal.destroy();
          options = null;
          modal = null;
        });

      }
    };

  });
<commit_msg>feat(modal): support modal size option<commit_after>'use strict';

angular.module('mgcrea.ngStrap.modal', ['mgcrea.ngStrap.core', 'mgcrea.ngStrap.helpers.dimensions'])

  .provider('$modal', function () {

    var defaults = this.defaults = {
      animation: 'am-fade',
      backdropAnimation: 'am-fade',
      customClass: '',
      prefixClass: 'modal',
      prefixEvent: 'modal',
      placement: 'top',
      templateUrl: 'modal/modal.tpl.html',
      template: '',
      contentTemplate: false,
      container: false,
      element: null,
      backdrop: true,
      keyboard: true,
      html: false,
      show: true,
      size: null
    };

    this.$get = function ($window, $rootScope, $bsCompiler, $animate, $timeout, $sce, dimensions) {

      var forEach = angular.forEach;
      var requestAnimationFrame = $window.requestAnimationFrame || $window.setTimeout;
      var bodyElement = angular.element($window.document.body);

      var backdropCount = 0;
      var dialogBaseZindex = 1050;
      var backdropBaseZindex = 1040;

      var validSizes = {
        lg: 'modal-lg',
        sm: 'modal-sm'
      };

      function ModalFactory(config) {

        var $modal = {};

        // Common vars
        var options = $modal.$options = angular.extend({}, defaults, config);
        var promise = $modal.$promise = $bsCompiler.compile(options);
        var scope = $modal.$scope = options.scope && options.scope.$new() || $rootScope.$new();

        if (!options.element && !options.container) {
          options.container = 'body';
        }

        // Store $id to identify the triggering element in events
        // give priority to options.id, otherwise, try to use
        // element id if defined
        $modal.$id = options.id || options.element && options.element.attr('id') || '';

        // Support scope as string options
        forEach(['title', 'content'], function (key) {
          if (options[key]) scope[key] = $sce.trustAsHtml(options[key]);
        });

        // Provide scope helpers
        scope.$hide = function () {
          scope.$$postDigest(function () {
            $modal.hide();
          });
        };
        scope.$show = function () {
          scope.$$postDigest(function () {
            $modal.show();
          });
        };
        scope.$toggle = function () {
          scope.$$postDigest(function () {
            $modal.toggle();
          });
        };
        // Publish isShown as a protected var on scope
        $modal.$isShown = scope.$isShown = false;

        // Fetch, compile then initialize modal
        var compileData;
        var modalElement;
        var modalScope;
        var backdropElement = angular.element('
');
        backdropElement.css({position: 'fixed', top: '0px', left: '0px', bottom: '0px', right: '0px'});
        promise.then(function (data) {
          compileData = data;
          $modal.init();
        });

        $modal.init = function () {

          // Options: show
          if (options.show) {
            scope.$$postDigest(function () {
              $modal.show();
            });
          }

        };

        $modal.destroy = function () {

          // Remove element
          destroyModalElement();

          // remove backdrop element
          if (backdropElement) {
            backdropElement.remove();
            backdropElement = null;
          }

          // Destroy scope
          scope.$destroy();
        };

        $modal.show = function () {
          if ($modal.$isShown) return;

          var parent;
          var after;
          if (angular.isElement(options.container)) {
            parent = options.container;
            after = options.container[0].lastChild ? angular.element(options.container[0].lastChild) : null;
          } else {
            if (options.container) {
              parent = findElement(options.container);
              after = parent[0] && parent[0].lastChild ? angular.element(parent[0].lastChild) : null;
            } else {
              parent = null;
              after = options.element;
            }
          }

          // destroy any existing modal elements
          if (modalElement) destroyModalElement();

          // create a new scope, so we can destroy it and all child scopes
          // when destroying the modal element
          modalScope = $modal.$scope.$new();
          // Fetch a cloned element linked from template (noop callback is required)
          modalElement = $modal.$element = compileData.link(modalScope, function (clonedElement, scope) {});

          if (options.backdrop) {
            // set z-index
            modalElement.css({'z-index': dialogBaseZindex + (backdropCount * 20)});
            backdropElement.css({'z-index': backdropBaseZindex + (backdropCount * 20)});

            // increment number of backdrops
            backdropCount++;
          }

          if (scope.$emit(options.prefixEvent + '.show.before', $modal).defaultPrevented) {
            return;
          }

          // Set the initial positioning.
          modalElement.css({display: 'block'}).addClass(options.placement);

          // Options: customClass
          if (options.customClass) {
            modalElement.addClass(options.customClass);
          }

          // Options: size
          if (options.size && validSizes[options.size]) {
            angular.element(findElement('.modal-dialog', modalElement[0])).addClass(validSizes[options.size]);
          }

          // Options: animation
          if (options.animation) {
            if (options.backdrop) {
              backdropElement.addClass(options.backdropAnimation);
            }
            modalElement.addClass(options.animation);
          }

          if (options.backdrop) {
            $animate.enter(backdropElement, bodyElement, null);
          }

          // Support v1.2+ $animate
          // https://github.com/angular/angular.js/issues/11713
          if (angular.version.minor <= 2) {
            $animate.enter(modalElement, parent, after, enterAnimateCallback);
          } else {
            $animate.enter(modalElement, parent, after).then(enterAnimateCallback);
          }

          $modal.$isShown = scope.$isShown = true;
          safeDigest(scope);
          // Focus once the enter-animation has started
          // Weird PhantomJS bug hack
          var el = modalElement[0];
          requestAnimationFrame(function () {
            el.focus();
          });

          bodyElement.addClass(options.prefixClass + '-open');
          if (options.animation) {
            bodyElement.addClass(options.prefixClass + '-with-' + options.animation);
          }

          // Bind events
          bindBackdropEvents();
          bindKeyboardEvents();
        };

        function enterAnimateCallback() {
          scope.$emit(options.prefixEvent + '.show', $modal);
        }

        $modal.hide = function () {
          if (!$modal.$isShown) return;

          if (options.backdrop) {
            // decrement number of modals
            backdropCount--;
          }

          if (scope.$emit(options.prefixEvent + '.hide.before', $modal).defaultPrevented) {
            return;
          }

          // Support v1.2+ $animate
          // https://github.com/angular/angular.js/issues/11713
          if (angular.version.minor <= 2) {
            $animate.leave(modalElement, leaveAnimateCallback);
          } else {
            $animate.leave(modalElement).then(leaveAnimateCallback);
          }

          if (options.backdrop) {
            $animate.leave(backdropElement);
          }
          $modal.$isShown = scope.$isShown = false;
          safeDigest(scope);

          // Unbind events
          unbindBackdropEvents();
          unbindKeyboardEvents();
        };

        function leaveAnimateCallback() {
          scope.$emit(options.prefixEvent + '.hide', $modal);
          bodyElement.removeClass(options.prefixClass + '-open');
          if (options.animation) {
            bodyElement.removeClass(options.prefixClass + '-with-' + options.animation);
          }
        }

        $modal.toggle = function () {
          if ($modal.$isShown) {
            $modal.hide();
          } else {
            $modal.show();
          }
        };

        $modal.focus = function () {
          modalElement[0].focus();
        };

        // Protected methods

        $modal.$onKeyUp = function (evt) {

          if (evt.which === 27 && $modal.$isShown) {
            $modal.hide();
            evt.stopPropagation();
          }

        };

        function bindBackdropEvents() {
          if (options.backdrop) {
            modalElement.on('click', hideOnBackdropClick);
            backdropElement.on('click', hideOnBackdropClick);
            backdropElement.on('wheel', preventEventDefault);
          }
        }

        function unbindBackdropEvents() {
          if (options.backdrop) {
            modalElement.off('click', hideOnBackdropClick);
            backdropElement.off('click', hideOnBackdropClick);
            backdropElement.off('wheel', preventEventDefault);
          }
        }

        function bindKeyboardEvents() {
          if (options.keyboard) {
            modalElement.on('keyup', $modal.$onKeyUp);
          }
        }

        function unbindKeyboardEvents() {
          if (options.keyboard) {
            modalElement.off('keyup', $modal.$onKeyUp);
          }
        }

        // Private helpers

        function hideOnBackdropClick(evt) {
          if (evt.target !== evt.currentTarget) return;
          if (options.backdrop === 'static') {
            $modal.focus();
          } else {
            $modal.hide();
          }
        }

        function preventEventDefault(evt) {
          evt.preventDefault();
        }

        function destroyModalElement() {
          if ($modal.$isShown && modalElement !== null) {
            // un-bind events
            unbindBackdropEvents();
            unbindKeyboardEvents();
          }

          if (modalScope) {
            modalScope.$destroy();
            modalScope = null;
          }

          if (modalElement) {
            modalElement.remove();
            modalElement = $modal.$element = null;
          }
        }

        return $modal;

      }

      // Helper functions

      function safeDigest(scope) {
        /* eslint-disable no-unused-expressions */
        scope.$$phase || (scope.$root && scope.$root.$$phase) || scope.$digest();
        /* eslint-enable no-unused-expressions */
      }

      function findElement(query, element) {
        return angular.element((element || document).querySelectorAll(query));
      }

      return ModalFactory;

    };

  })

  .directive('bsModal', function ($window, $sce, $modal) {

    return {
      restrict: 'EAC',
      scope: true,
      link: function postLink(scope, element, attr, transclusion) {

        // Directive options
        var options = {scope: scope, element: element, show: false};
        angular.forEach(['template', 'templateUrl', 'controller', 'controllerAs', 'contentTemplate', 'placement', 'backdrop', 'keyboard', 'html', 'container', 'animation', 'backdropAnimation', 'id', 'prefixEvent', 'prefixClass', 'customClass', 'modalClass', 'size'], function (key) {
          if (angular.isDefined(attr[key])) options[key] = attr[key];
        });

        // Options: alias modalClass to customClass
        if (options.modalClass) {
          options.customClass = options.modalClass;
        }

        // use string regex match boolean attr falsy values, leave truthy values be
        var falseValueRegExp = /^(false|0|)$/i;
        angular.forEach(['backdrop', 'keyboard', 'html', 'container'], function (key) {
          if (angular.isDefined(attr[key]) && falseValueRegExp.test(attr[key])) options[key] = false;
        });

        // Support scope as data-attrs
        angular.forEach(['title', 'content'], function (key) {
          if (attr[key]) {
            attr.$observe(key, function (newValue, oldValue) {
              scope[key] = $sce.trustAsHtml(newValue);
            });
          }
        });

        // Support scope as an object
        if (attr.bsModal) {
          scope.$watch(attr.bsModal, function (newValue, oldValue) {
            if (angular.isObject(newValue)) {
              angular.extend(scope, newValue);
            } else {
              scope.content = newValue;
            }
          }, true);
        }

        // Initialize modal
        var modal = $modal(options);

        // Trigger
        element.on(attr.trigger || 'click', modal.toggle);

        // Garbage collection
        scope.$on('$destroy', function () {
          if (modal) modal.destroy();
          options = null;
          modal = null;
        });

      }
    };

  });
<|endoftext|>


<commit_before>'use strict';

import mongoose from 'mongoose';

module.exports = function (done) {
    var Schema = mongoose.Schema,
        ObjectId = Schema.ObjectId;

    var BlogPost = new Schema({
        name: {type: String, unique: true},
        password: {type:String},
        nickname: {type: String}
    });

    $.mongodb.model('User', User);
    $.model.User = $.mongodb.model('User');

    done();
}<commit_msg>添加了user model<commit_after>'use strict';

import mongoose from 'mongoose';

module.exports = function (done) {
    var Schema = mongoose.Schema,
        ObjectId = Schema.ObjectId;

    const User = new Schema({
        name: {type: String, unique: true},
        email: {type: String, unique: true},
        password: {type: String},
        nickname: {type: String},
        about: {type: String}
    })

    $.mongodb.model('User', User);
    $.model.User = $.mongodb.model('User');

    done();
}<|endoftext|>


<commit_before>
var level = require('level')
var sublevel = require('level-sublevel/bytewise')
var opts = require('./defaults')
var SSB = require('./')

module.exports = function (path, opts, keys) {
  opts = opts || require('./defaults')
  return SSB(
    sublevel(level(path, {
      valueEncoding: opts.codec
    })), opts, keys)
}
<commit_msg>hard wire codec<commit_after>
var level = require('level')
var sublevel = require('level-sublevel/bytewise')
var opts = require('./defaults')
var SSB = require('./')

module.exports = function (path, opts, keys) {
  opts = opts || require('./defaults')
  return SSB(
    sublevel(level(path, {
      valueEncoding: require('./codec')
    })), opts, keys)
}
<|endoftext|>


<commit_before>var Model = require('../models/model'),
  config = require('../../config');

// Constructor
function Bill(){
  this.query = {
    apikey: config.apiKey
  };
  this.endpoint = '/bills';
  this.url = config.urls.congress;
}

Bill.prototype = new Model();

Bill.prototype.findById = function(query, callback) {
  this.url += query.id;
  this.find(query, callback);
};

Bill.prototype.findByChamber = function(query, callback){

  if (query.chamber === 'senate') {
      query['history.senate_passage_result__exists'] = true;
  } else {
      query['history.house_passage_result__exists'] = true;
  }
  this.find( query, callback );
};

Bill.prototype.formatResponse = function(body) {
  var responseData = {};
  responseData = JSON.parse( body ).results;

  responseData = responseData.filter(function(item) {
    // `undefined != null` coerces undefined to null
    return item.bill_id != null;
  });

  return {bills: responseData};
};

module.exports = Bill;
<commit_msg>Conver bill model to ES6 class.<commit_after>'use strict';

var Model = require('../models/model'),
  config = require('../../config');

class Bill extends Model {
    constructor() {
        this.query = {
          apikey: config.apiKey
        };
        this.endpoint = '/bills';
        this.url = config.urls.congress;
    }

    findById (query, callback) {
      this.url += query.id;
      this.find(query, callback);
    }

    findByChamber(query, callback) {

      if (query.chamber === 'senate') {
          query['history.senate_passage_result__exists'] = true;
      } else {
          query['history.house_passage_result__exists'] = true;
      }
      this.find( query, callback );
    }

    formatResponse(body) {
      var responseData = {};
      responseData = JSON.parse( body ).results;

      responseData = responseData.filter(function(item) {
        // `undefined != null` coerces undefined to null
        return item.bill_id != null;
      });

      return {bills: responseData};
    }

}

module.exports = Bill;
<|endoftext|>


<commit_before>var scaliendb =
{
	controller: "",
	developer: false,
	onResponse: this.showResult,
	onDisconnect: this.showError,
	timeout: 60 * 1000,

    //========================================================================
	//
	// ScalienDB Client interface
	//
	//========================================================================

	getQuorumState: function(configState, quorumID)
	{
		var quorum = locateQuorum(configState, quorumID);
		if (quorum["hasPrimary"] == "true")
		{
			if (quorum["inactiveNodes"].length == 0)
				state = "healthy";
			else
				state = "unhealthy";
		}
		else
			state = "critical";

		return state;
	},

	getQuorumInfo: function(configState, nodeID, quorumID)
	{
		var shardServer = scaliendb.getShardServer(configState, nodeID);
		for (var i in shardServer["quorumInfos"])
		{
			var quorumInfo = shardServer["quorumInfos"][i];
			if (quorumInfo["quorumID"] == quorumID)
				return quorumInfo;
		}
		return null;
	},

	getTableState: function(configState, tableID)
	{
		var state = "healthy";
		var table = scaliendb.getTable(configState, tableID);
		for (var i in table["shards"])
		{
			var shardID = table["shards"][i];
			var shard = locateShard(configState, shardID);
			var quorumState = scaliendb.getQuorumState(configState, shard["quorumID"]);
			if (state == "critical")
				continue;
			if (state == "unhealthy" && quorumState == "critical")
				state = quorumState;
			if (state == "healthy" && quorumState != "healthy")
				state = quorumState;
		}
		return state;
	},

	getClusterState: function(configState)
	{
		var state = "healthy";
		for (var i in configState["quorums"])
		{
			var quorum = configState["quorums"][i];
			var quorumState = scaliendb.getQuorumState(configState, quorum["quorumID"]);
			if (state == "critical")
				continue;
			if (state == "unhealthy" && quorumState == "critical")
				state = quorumState;
			if (state == "healthy" && quorumState != "healthy")
				state = quorumState;
		}
		return state;
	},

	findMaster: function(onFindMaster)
	{
		this.json.rpc(scaliendb.controller, onFindMaster, scaliendb.onDisconnect, "getMasterHttp");
	},

	getConfigState: function(onConfigState)
	{
		this.json.rpc(scaliendb.controller, onConfigState, scaliendb.onDisconnect, "getConfigState");
	},

	pollConfigState: function(onConfigState, paxosID)
	{
		var params = {};
		params["paxosID"] = paxosID;
		params["changeTimeout"] = scaliendb.timeout;
		this.json.rpc(scaliendb.controller, onConfigState, scaliendb.onDisconnect, "pollConfigState", params);
	},

	getTable: function(configState, tableID)
	{
		for (var i in configState["tables"])
		{
			var table = configState["tables"][i];
			if (table["tableID"] == tableID)
				return table;
		}

		return null;
	},

	getController: function(configState, nodeID)
	{
		for (var i in configState["controllers"])
		{
			var controller = configState["controllers"][i];
			if (controller["nodeID"] == nodeID)
				return controller;
		}

		return null;
	},

	getShardServer: function(configState, nodeID)
	{
		for (var i in configState["shardServers"])
		{
			var shardServer = configState["shardServers"][i];
			if (shardServer["nodeID"] == nodeID)
				return shardServer;
		}

		return null;
	},

	unregisterShardServer: function(nodeID)
	{
		var params = {};
		params["nodeID"] = nodeID;
		this.rpc("unregisterShardserver", params);
	},

	createQuorum: function(name, nodes)
	{
		var params = {};
		params["name"] = name;
		params["nodes"] = nodes;
		this.rpc("createQuorum", params);
	},

	renameQuorum: function(quorumID, name)
	{
		var params = {};
		params["quorumID"] = quorumID;
		params["name"] = name;
		this.rpc("renameQuorum", params);
	},

	deleteQuorum: function(quorumID)
	{
		var params = {};
		params["quorumID"] = quorumID;
		this.rpc("deleteQuorum", params);
	},

	addNode: function(quorumID, nodeID)
	{
		var params = {};
		params["quorumID"] = quorumID;
		params["nodeID"] = nodeID;
		this.rpc("addShardserverToQuorum", params);
	},

	removeNode: function(quorumID, nodeID)
	{
		var params = {};
		params["quorumID"] = quorumID;
		params["nodeID"] = nodeID;
		this.rpc("removeShardserverFromQuorum", params);
	},

	activateNode: function(quorumID, nodeID)
	{
		var params = {};
		params["quorumID"] = quorumID;
		params["nodeID"] = nodeID;
		this.rpc("activateShardserver", params);
	},

	createDatabase: function(name)
	{
		var params = {};
		params["name"] = name;
		this.rpc("createDatabase", params);
	},

	deleteDatabase: function(name)
	{
		var params = {};
		params["name"] = name;
		this.rpc("deleteDatabase", params);
	},

	renameDatabase: function(databaseID, name)
	{
		var params = {};
		params["databaseID"] = databaseID;
		params["name"] = name;
		this.rpc("renameDatabase", params);
	},

	deleteDatabase: function(databaseID)
	{
		var params = {};
		params["databaseID"] = databaseID;
		this.rpc("deleteDatabase", params);
	},

	createTable: function(databaseID, quorumID, name)
	{
		var params = {};
		params["databaseID"] = databaseID;
		params["quorumID"] = quorumID;
		params["name"] = name;
		this.rpc("createTable", params);
	},

	renameTable: function(tableID, name)
	{
		var params = {};
		params["tableID"] = tableID;
		params["name"] = name;
		this.rpc("renameTable", params);
	},

	deleteTable: function(tableID)
	{
		var params = {};
		params["tableID"] = tableID;
		this.rpc("deleteTable", params);
	},

	truncateTable: function(tableID)
	{
		var params = {};
		params["tableID"] = tableID;
		this.rpc("truncateTable", params);
	},

	freezeTable: function(tableID)
	{
		var params = {};
		params["tableID"] = tableID;
		this.rpc("freezeTable", params);
	},

	unfreezeTable: function(tableID)
	{
		var params = {};
		params["tableID"] = tableID;
		this.rpc("unfreezeTable", params);
	},

	splitShard: function(shardID, key)
	{
		var params = {};
		params["shardID"] = shardID;
		params["key"] = key;
		this.rpc("splitShard", params);
	},

	migrateShard: function(shardID, quorumID)
	{
		var params = {};
		params["shardID"] = shardID;
		params["quorumID"] = quorumID;
		this.rpc("migrateShard", params);
	},

	showResult: function(data)
	{
		//alert(data["response"]);
	},

	showError: function()
	{
		alert("connection lost");
	},

	rpc: function(name, params)
	{
		this.json.rpc(scaliendb.controller, scaliendb.onResponse, scaliendb.onDisconnect, name, params);
	},

	disconnect: function()
	{
		this.json.abort();
	},

    //========================================================================
	//
	// JSON utilities
	//
	//========================================================================
	json:
	{
		counter : 0,
		active : 0,
		func: {},
		debug: true,
		pollRequest: null,

		getJSONP: function(url, userfunc, errorfunc, showload)
		{
			var id = this.counter++;

			url += "&callback=scaliendb.json.func[" + id + "]";
			var scriptTag = document.createElement("script");
			scriptTag.setAttribute("id", "json" + id);
			scriptTag.setAttribute("type", "text/javascript");
			scriptTag.setAttribute("src", url);
			document.getElementsByTagName("head")[0].appendChild(scriptTag);
			if (showload)
				this.active++;
			scaliendb.util.trace("[" + this.active + "] calling " + url);

			this.func[id] = function(data)
			{
				if (data == undefined)
				{
					if (this.debug)
						alert("json.func[" + id + "]: empty callback");
					scaliendb.util.trace("json.func[" + id + "]: empty callback");
					errorfunc();
					return;
				}

				if (data.hasOwnProperty("error"))
				{
					if (this.debug)
						alert("json.func[" + id + "]: " + data.error);
					scaliendb.util.trace("json.func" + id + ": " + data.error);

					if (data.hasOwnProperty("type") && data.type == "session")
					{
						scaliendb.util.logout();
						return;
					}
				}

				scaliendb.util.trace("[" + this.active + "] json callback " + id);
				userfunc(data);
				if (showload)
					this.active--;
				scaliendb.util.trace("[" + this.active + "] json callback " + id + " after userfunc");
				scaliendb.util.removeElement("json" + id);
				this.func = scaliendb.util.removeKey(this.func, "func" + id);
			}
		},

		getXHR: function(url, userfunc, errorfunc, showload)
		{
			var xhr = new XMLHttpRequest();
			var decode = this.decode;

			xhr.open("GET", url + "&origin=*", true);

			var requestTimer = setTimeout(function() {
				xhr.abort();
				errorfunc();
			}, 2 * scaliendb.timeout);

			var onreadystatechange = function()
			{
				if (xhr.readyState != 4)
					return;

				clearTimeout(requestTimer);

				if (xhr.status != 200)
				{
					// pollRequest == null indicates that the request is aborted
					if (scaliendb.json.pollRequest !== null)
						errorfunc();
					scaliendb.json.pollRequest = null;
					return;
				}
				scaliendb.json.pollRequest = null;
				userfunc(decode(xhr.responseText));
			}

			xhr.onreadystatechange = onreadystatechange;
			this.pollRequest = xhr;
			xhr.send();
		},

		rpc: function(baseUrl, userfunc, errorfunc, cmd, params)
		{
			var url = baseUrl + cmd + "?mimetype=text/javascript";
			for (var name in params)
			{
				url += "&" + name + "=";
				param = params[name];
				if (typeof(param) != "undefined")
				{
					if (typeof(param) == "object" || typeof(param) == "array")
						var arg = this.encode(param);
					else
						var arg = param;
					var value = encodeURIComponent(arg);
				}
				else
					var value = "";
				url += value;
			}
			// TODO: detecting browser functionality
			// this.getJSONP(url, userfunc, errorfunc, true);
			this.abort();
			this.getXHR(url, userfunc, errorfunc, true);
		},

		abort: function()
		{
			if (this.pollRequest != null)
			{
				var request = this.pollRequest;
				// this indicates that the request is aborted
				this.pollRequest = null;
				request.abort();
			}
		},

		encode: function(jsobj)
		{
			// if (typeof(jsobj) == "undefined")
			//  	return "";

			return JSON.stringify(jsobj);
		},

		decode: function(jsontext)
		{
			return JSON.parse(jsontext);
		}
	},

    //========================================================================
	//
	// Other utility functions
	//
	//========================================================================
	util:
	{
	 	elem: function(id)
		{
			return document.getElementById(id);
		},

		keys: function(arr)
		{
			var r = new Array();
			for (var key in arr)
				r.push(key);
			return r;
		},

	   removeKey: function(arr, key)
		{
			var n = new Array();
			for (var i in arr)
				if (i != key)
					n.push(arr[i]);
			return n;
		},

		removeElement: function(id)
		{
			e = this.elem(id);
			e.parentNode.removeChild(e);
		},

		padString: function(str, width, pad)
		{
			str = "" + str;
			while (str.length < width)
				str = pad + str;

			return str;
		},

		escapeQuotes: function(str)
		{
			str = str.replace(/'/g, "\\x27");
			str = str.replace(/\"/g, "\\x22");
			return str;
		},

		trace: function(msg)
		{
		},

		startsWith: function(str, s)
		{
			return (str.indexOf(s) == 0)
		},

		endsWith: function(str, s)
		{
			return (str.indexOf(s) == (str.length - s.length));
		},

		removeSpaces: function(str)
		{
			return str.replace(/ /g,'')
		},

		clear: function(node)
		{
			while (node.childNodes.length > 0)
			{
			    node.removeChild(node.firstChild);
			}
		},

		defstr: function(val, defval)
		{
			if (typeof val == 'undefined')
			{
				if (typeof defval == 'undefined')
					return "";
				return "" + defval;
			}
			return "" + val;
		},

		numDigits: function(num)
		{
			return ("" + num).length;
		},

		humanBytes: function(size)
		{
			var units = "kMGTPEZY";
			var n = size;
			var m = size;
			var u = 0;

			if (typeof size == 'undefined')
				return "0";

			while (this.numDigits(n) > 3)
			{
				m = Math.round(n / 100.0) / 10.0;
				n = Math.round(n / 1000.0);
				u++;
			}

			var dim = (u == 0 ? "" : units[u - 1]);
			return "" + m + dim;
		},

		pluralize: function(count, noun)
		{
			// add exceptions here
			if (count <= 1)
				return noun;
			else
				return noun + "s";
		},

		cardinality: function(count, noun)
		{
			return count + " " + scaliendb.util.pluralize(count, noun);
		}
	}
}

<commit_msg>Fixed Javascript error handling on JSON decoding.<commit_after>var scaliendb =
{
	controller: "",
	developer: false,
	onResponse: this.showResult,
	onDisconnect: this.showError,
	timeout: 60 * 1000,

    //========================================================================
	//
	// ScalienDB Client interface
	//
	//========================================================================

	getQuorumState: function(configState, quorumID)
	{
		var quorum = locateQuorum(configState, quorumID);
		if (quorum["hasPrimary"] == "true")
		{
			if (quorum["inactiveNodes"].length == 0)
				state = "healthy";
			else
				state = "unhealthy";
		}
		else
			state = "critical";

		return state;
	},

	getQuorumInfo: function(configState, nodeID, quorumID)
	{
		var shardServer = scaliendb.getShardServer(configState, nodeID);
		for (var i in shardServer["quorumInfos"])
		{
			var quorumInfo = shardServer["quorumInfos"][i];
			if (quorumInfo["quorumID"] == quorumID)
				return quorumInfo;
		}
		return null;
	},

	getTableState: function(configState, tableID)
	{
		var state = "healthy";
		var table = scaliendb.getTable(configState, tableID);
		for (var i in table["shards"])
		{
			var shardID = table["shards"][i];
			var shard = locateShard(configState, shardID);
			var quorumState = scaliendb.getQuorumState(configState, shard["quorumID"]);
			if (state == "critical")
				continue;
			if (state == "unhealthy" && quorumState == "critical")
				state = quorumState;
			if (state == "healthy" && quorumState != "healthy")
				state = quorumState;
		}
		return state;
	},

	getClusterState: function(configState)
	{
		var state = "healthy";
		for (var i in configState["quorums"])
		{
			var quorum = configState["quorums"][i];
			var quorumState = scaliendb.getQuorumState(configState, quorum["quorumID"]);
			if (state == "critical")
				continue;
			if (state == "unhealthy" && quorumState == "critical")
				state = quorumState;
			if (state == "healthy" && quorumState != "healthy")
				state = quorumState;
		}
		return state;
	},

	findMaster: function(onFindMaster)
	{
		this.json.rpc(scaliendb.controller, onFindMaster, scaliendb.onDisconnect, "getMasterHttp");
	},

	getConfigState: function(onConfigState)
	{
		this.json.rpc(scaliendb.controller, onConfigState, scaliendb.onDisconnect, "getConfigState");
	},

	pollConfigState: function(onConfigState, paxosID)
	{
		var params = {};
		params["paxosID"] = paxosID;
		params["changeTimeout"] = scaliendb.timeout;
		this.json.rpc(scaliendb.controller, onConfigState, scaliendb.onDisconnect, "pollConfigState", params);
	},

	getTable: function(configState, tableID)
	{
		for (var i in configState["tables"])
		{
			var table = configState["tables"][i];
			if (table["tableID"] == tableID)
				return table;
		}

		return null;
	},

	getController: function(configState, nodeID)
	{
		for (var i in configState["controllers"])
		{
			var controller = configState["controllers"][i];
			if (controller["nodeID"] == nodeID)
				return controller;
		}

		return null;
	},

	getShardServer: function(configState, nodeID)
	{
		for (var i in configState["shardServers"])
		{
			var shardServer = configState["shardServers"][i];
			if (shardServer["nodeID"] == nodeID)
				return shardServer;
		}

		return null;
	},

	unregisterShardServer: function(nodeID)
	{
		var params = {};
		params["nodeID"] = nodeID;
		this.rpc("unregisterShardserver", params);
	},

	createQuorum: function(name, nodes)
	{
		var params = {};
		params["name"] = name;
		params["nodes"] = nodes;
		this.rpc("createQuorum", params);
	},

	renameQuorum: function(quorumID, name)
	{
		var params = {};
		params["quorumID"] = quorumID;
		params["name"] = name;
		this.rpc("renameQuorum", params);
	},

	deleteQuorum: function(quorumID)
	{
		var params = {};
		params["quorumID"] = quorumID;
		this.rpc("deleteQuorum", params);
	},

	addNode: function(quorumID, nodeID)
	{
		var params = {};
		params["quorumID"] = quorumID;
		params["nodeID"] = nodeID;
		this.rpc("addShardserverToQuorum", params);
	},

	removeNode: function(quorumID, nodeID)
	{
		var params = {};
		params["quorumID"] = quorumID;
		params["nodeID"] = nodeID;
		this.rpc("removeShardserverFromQuorum", params);
	},

	activateNode: function(quorumID, nodeID)
	{
		var params = {};
		params["quorumID"] = quorumID;
		params["nodeID"] = nodeID;
		this.rpc("activateShardserver", params);
	},

	createDatabase: function(name)
	{
		var params = {};
		params["name"] = name;
		this.rpc("createDatabase", params);
	},

	deleteDatabase: function(name)
	{
		var params = {};
		params["name"] = name;
		this.rpc("deleteDatabase", params);
	},

	renameDatabase: function(databaseID, name)
	{
		var params = {};
		params["databaseID"] = databaseID;
		params["name"] = name;
		this.rpc("renameDatabase", params);
	},

	deleteDatabase: function(databaseID)
	{
		var params = {};
		params["databaseID"] = databaseID;
		this.rpc("deleteDatabase", params);
	},

	createTable: function(databaseID, quorumID, name)
	{
		var params = {};
		params["databaseID"] = databaseID;
		params["quorumID"] = quorumID;
		params["name"] = name;
		this.rpc("createTable", params);
	},

	renameTable: function(tableID, name)
	{
		var params = {};
		params["tableID"] = tableID;
		params["name"] = name;
		this.rpc("renameTable", params);
	},

	deleteTable: function(tableID)
	{
		var params = {};
		params["tableID"] = tableID;
		this.rpc("deleteTable", params);
	},

	truncateTable: function(tableID)
	{
		var params = {};
		params["tableID"] = tableID;
		this.rpc("truncateTable", params);
	},

	freezeTable: function(tableID)
	{
		var params = {};
		params["tableID"] = tableID;
		this.rpc("freezeTable", params);
	},

	unfreezeTable: function(tableID)
	{
		var params = {};
		params["tableID"] = tableID;
		this.rpc("unfreezeTable", params);
	},

	splitShard: function(shardID, key)
	{
		var params = {};
		params["shardID"] = shardID;
		params["key"] = key;
		this.rpc("splitShard", params);
	},

	migrateShard: function(shardID, quorumID)
	{
		var params = {};
		params["shardID"] = shardID;
		params["quorumID"] = quorumID;
		this.rpc("migrateShard", params);
	},

	showResult: function(data)
	{
		//alert(data["response"]);
	},

	showError: function()
	{
		alert("connection lost");
	},

	rpc: function(name, params)
	{
		this.json.rpc(scaliendb.controller, scaliendb.onResponse, scaliendb.onDisconnect, name, params);
	},

	disconnect: function()
	{
		this.json.abort();
	},

    //========================================================================
	//
	// JSON utilities
	//
	//========================================================================
	json:
	{
		counter : 0,
		active : 0,
		func: {},
		debug: true,
		pollRequest: null,

		getJSONP: function(url, userfunc, errorfunc, showload)
		{
			var id = this.counter++;

			url += "&callback=scaliendb.json.func[" + id + "]";
			var scriptTag = document.createElement("script");
			scriptTag.setAttribute("id", "json" + id);
			scriptTag.setAttribute("type", "text/javascript");
			scriptTag.setAttribute("src", url);
			document.getElementsByTagName("head")[0].appendChild(scriptTag);
			if (showload)
				this.active++;
			scaliendb.util.trace("[" + this.active + "] calling " + url);

			this.func[id] = function(data)
			{
				if (data == undefined)
				{
					if (this.debug)
						alert("json.func[" + id + "]: empty callback");
					scaliendb.util.trace("json.func[" + id + "]: empty callback");
					errorfunc();
					return;
				}

				if (data.hasOwnProperty("error"))
				{
					if (this.debug)
						alert("json.func[" + id + "]: " + data.error);
					scaliendb.util.trace("json.func" + id + ": " + data.error);

					if (data.hasOwnProperty("type") && data.type == "session")
					{
						scaliendb.util.logout();
						return;
					}
				}

				scaliendb.util.trace("[" + this.active + "] json callback " + id);
				userfunc(data);
				if (showload)
					this.active--;
				scaliendb.util.trace("[" + this.active + "] json callback " + id + " after userfunc");
				scaliendb.util.removeElement("json" + id);
				this.func = scaliendb.util.removeKey(this.func, "func" + id);
			}
		},

		getXHR: function(url, userfunc, errorfunc, showload)
		{
			var xhr = new XMLHttpRequest();
			var decode = this.decode;

			xhr.open("GET", url + "&origin=*", true);

			var requestTimer = setTimeout(function() {
				xhr.abort();
				errorfunc();
			}, 2 * scaliendb.timeout);

			var onreadystatechange = function()
			{
				if (xhr.readyState != 4)
					return;

				clearTimeout(requestTimer);

				if (xhr.status != 200)
				{
					// pollRequest == null indicates that the request is aborted
					if (scaliendb.json.pollRequest !== null)
						errorfunc();
					scaliendb.json.pollRequest = null;
					return;
				}
				scaliendb.json.pollRequest = null;
				userfunc(decode(xhr.responseText));
			}

			xhr.onreadystatechange = onreadystatechange;
			this.pollRequest = xhr;
			xhr.send();
		},

		rpc: function(baseUrl, userfunc, errorfunc, cmd, params)
		{
			var url = baseUrl + cmd + "?mimetype=text/javascript";
			for (var name in params)
			{
				url += "&" + name + "=";
				param = params[name];
				if (typeof(param) != "undefined")
				{
					if (typeof(param) == "object" || typeof(param) == "array")
						var arg = this.encode(param);
					else
						var arg = param;
					var value = encodeURIComponent(arg);
				}
				else
					var value = "";
				url += value;
			}
			// TODO: detecting browser functionality
			// this.getJSONP(url, userfunc, errorfunc, true);
			this.abort();
			this.getXHR(url, userfunc, errorfunc, true);
		},

		abort: function()
		{
			if (this.pollRequest != null)
			{
				var request = this.pollRequest;
				// this indicates that the request is aborted
				this.pollRequest = null;
				request.abort();
			}
		},

		encode: function(jsobj)
		{
			// if (typeof(jsobj) == "undefined")
			//  	return "";

			return JSON.stringify(jsobj);
		},

		decode: function(jsontext)
		{
			try {
				return JSON.parse(jsontext);
			} catch (e) {
				return null;
			}
		}
	},

    //========================================================================
	//
	// Other utility functions
	//
	//========================================================================
	util:
	{
	 	elem: function(id)
		{
			return document.getElementById(id);
		},

		keys: function(arr)
		{
			var r = new Array();
			for (var key in arr)
				r.push(key);
			return r;
		},

	   removeKey: function(arr, key)
		{
			var n = new Array();
			for (var i in arr)
				if (i != key)
					n.push(arr[i]);
			return n;
		},

		removeElement: function(id)
		{
			e = this.elem(id);
			e.parentNode.removeChild(e);
		},

		padString: function(str, width, pad)
		{
			str = "" + str;
			while (str.length < width)
				str = pad + str;

			return str;
		},

		escapeQuotes: function(str)
		{
			str = str.replace(/'/g, "\\x27");
			str = str.replace(/\"/g, "\\x22");
			return str;
		},

		trace: function(msg)
		{
		},

		startsWith: function(str, s)
		{
			return (str.indexOf(s) == 0)
		},

		endsWith: function(str, s)
		{
			return (str.indexOf(s) == (str.length - s.length));
		},

		removeSpaces: function(str)
		{
			return str.replace(/ /g,'')
		},

		clear: function(node)
		{
			while (node.childNodes.length > 0)
			{
			    node.removeChild(node.firstChild);
			}
		},

		defstr: function(val, defval)
		{
			if (typeof val == 'undefined')
			{
				if (typeof defval == 'undefined')
					return "";
				return "" + defval;
			}
			return "" + val;
		},

		numDigits: function(num)
		{
			return ("" + num).length;
		},

		humanBytes: function(size)
		{
			var units = "kMGTPEZY";
			var n = size;
			var m = size;
			var u = 0;

			if (typeof size == 'undefined')
				return "0";

			while (this.numDigits(n) > 3)
			{
				m = Math.round(n / 100.0) / 10.0;
				n = Math.round(n / 1000.0);
				u++;
			}

			var dim = (u == 0 ? "" : units[u - 1]);
			return "" + m + dim;
		},

		pluralize: function(count, noun)
		{
			// add exceptions here
			if (count <= 1)
				return noun;
			else
				return noun + "s";
		},

		cardinality: function(count, noun)
		{
			return count + " " + scaliendb.util.pluralize(count, noun);
		}
	}
}

<|endoftext|>


<commit_before>import Realm from 'realm';
import { createRecord } from '../utilities';

export class StocktakeBatch extends Realm.Object {
  get snapshotTotalQuantity() {
    return this.snapshotNumberOfPacks * this.packSize;
  }

  get countedTotalQuantity() {
    if (this.countedNumberOfPacks === null) return this.snapshotTotalQuantity;
    return this.countedNumberOfPacks * this.packSize;
  }

  /**
   * Stock on hand should never be negative. This can occur when stock has been issued
   * in a customer invoice for this batch before the parent stocktake was finalised.
   * If the difference applied to the |stockOnHand| for this batch would result in a
   * negative, return true.
   *
   * @return {boolean} True if |stockOnHand + stocktakebatch.difference| is negative.
   */
  get isReducedBelowMinimum() {
    const stockOnHand = this.itemBatch.totalQuantity;
    return stockOnHand + this.difference < 0;
  }

  /**
   * Returns true if the |snapshotTotalQuantity| does not match the |totalQuantity| of the
   * |itemBatch| this |stocktakeBatch| is associated with. Will occur if inventory has changed
   * since this |stocktakeBatch| was created. If the net change on this batch is 0, then return
   * false.
   *
   * @return {boolean} True if |snapshotTotalQuantity !== this.itemBatch.totalQuantity|
   */
  get isSnapshotOutdated() {
    return this.snapshotTotalQuantity !== this.itemBatch.totalQuantity;
  }

  get hasBeenCounted() {
    return this.countedNumberOfPacks !== null;
  }

  get itemId() {
    if (!this.itemBatch) return '';
    return this.itemBatch.item ? this.itemBatch.item.id : '';
  }

  get itemBatchId() {
    return this.itemBatch ? this.itemBatch.id : '';
  }

  get difference() {
    return this.countedTotalQuantity - this.snapshotTotalQuantity;
  }

  set countedTotalQuantity(quantity) {
    // Handle packsize of 0.
    this.countedNumberOfPacks = this.packSize ? quantity / this.packSize : 0;
  }

  /**
   * Finalising stocktake batch will adjust inventory appropriately and will add a
   * new transaction batch in reducing or increasing transaction for this stocktake.
   *
   * @param  {Realm}  database  App database.
   */
  finalise(database) {
    // Update the item batch details.
    this.itemBatch.batch = this.batch;
    this.itemBatch.expiryDate = this.expiryDate;

    // Make inventory adjustments if there is a difference to apply.
    if (this.difference !== 0) {
      const isAddition = this.countedTotalQuantity > this.snapshotTotalQuantity;
      const inventoryAdjustment = isAddition
        ? this.stocktake.getAdditions(database)
        : this.stocktake.getReductions(database);

      // Create transaction item and transaction batch to store inventory adjustments in this
      // stocktake.
      const transactionItem = createRecord(
        database,
        'TransactionItem',
        inventoryAdjustment,
        this.itemBatch.item
      );
      const transactionBatch = createRecord(
        database,
        'TransactionBatch',
        transactionItem,
        this.itemBatch
      );

      // Apply difference from stocktake to actual stock on hand levels. Whether stock is increased
      // or decreased is determined by the transaction, so we need to use the absolute value of
      // difference (i.e. always treat as positive).
      const snapshotDifference = Math.abs(this.difference);
      transactionBatch.setTotalQuantity(database, snapshotDifference);
      database.save('TransactionBatch', transactionBatch);
    }
    database.save('ItemBatch', this.itemBatch);
  }

  toString() {
    return `Stocktake batch representing ${this.itemBatch}`;
  }

  destructor(database) {
    // Delete item batch that was created as a result of creating this stocktake batch.
    if (this.snapshotNumberOfPacks === 0 && this.itemBatch.numberOfPacks === 0) {
      database.delete('ItemBatch', this.itemBatch);
    }
  }
}

export default StocktakeBatch;

StocktakeBatch.schema = {
  name: 'StocktakeBatch',
  primaryKey: 'id',
  properties: {
    id: 'string',
    stocktake: 'Stocktake',
    itemBatch: 'ItemBatch',
    snapshotNumberOfPacks: 'double',
    packSize: 'double',
    expiryDate: { type: 'date', optional: true },
    batch: 'string',
    costPrice: 'double',
    sellPrice: 'double',
    countedNumberOfPacks: { type: 'double', optional: true },
    sortIndex: { type: 'int', optional: true },
  },
};
<commit_msg>Add update to Stock Take Batch schema<commit_after>import Realm from 'realm';
import { createRecord } from '../utilities';

export class StocktakeBatch extends Realm.Object {
  get snapshotTotalQuantity() {
    return this.snapshotNumberOfPacks * this.packSize;
  }

  get countedTotalQuantity() {
    if (this.countedNumberOfPacks === null) return this.snapshotTotalQuantity;
    return this.countedNumberOfPacks * this.packSize;
  }

  /**
   * Stock on hand should never be negative. This can occur when stock has been issued
   * in a customer invoice for this batch before the parent stocktake was finalised.
   * If the difference applied to the |stockOnHand| for this batch would result in a
   * negative, return true.
   *
   * @return {boolean} True if |stockOnHand + stocktakebatch.difference| is negative.
   */
  get isReducedBelowMinimum() {
    const stockOnHand = this.itemBatch.totalQuantity;
    return stockOnHand + this.difference < 0;
  }

  /**
   * Returns true if the |snapshotTotalQuantity| does not match the |totalQuantity| of the
   * |itemBatch| this |stocktakeBatch| is associated with. Will occur if inventory has changed
   * since this |stocktakeBatch| was created. If the net change on this batch is 0, then return
   * false.
   *
   * @return {boolean} True if |snapshotTotalQuantity !== this.itemBatch.totalQuantity|
   */
  get isSnapshotOutdated() {
    return this.snapshotTotalQuantity !== this.itemBatch.totalQuantity;
  }

  get hasBeenCounted() {
    return this.countedNumberOfPacks !== null;
  }

  get itemId() {
    if (!this.itemBatch) return '';
    return this.itemBatch.item ? this.itemBatch.item.id : '';
  }

  get itemBatchId() {
    return this.itemBatch ? this.itemBatch.id : '';
  }

  get difference() {
    return this.countedTotalQuantity - this.snapshotTotalQuantity;
  }

  set countedTotalQuantity(quantity) {
    // Handle packsize of 0.
    this.countedNumberOfPacks = this.packSize ? quantity / this.packSize : 0;
  }

  /**
   * Finalising stocktake batch will adjust inventory appropriately and will add a
   * new transaction batch in reducing or increasing transaction for this stocktake.
   *
   * @param  {Realm}  database  App database.
   */
  finalise(database) {
    // Update the item batch details.
    this.itemBatch.batch = this.batch;
    this.itemBatch.expiryDate = this.expiryDate;

    // Make inventory adjustments if there is a difference to apply.
    if (this.difference !== 0) {
      const isAddition = this.countedTotalQuantity > this.snapshotTotalQuantity;
      const inventoryAdjustment = isAddition
        ? this.stocktake.getAdditions(database)
        : this.stocktake.getReductions(database);

      // Create transaction item and transaction batch to store inventory adjustments in this
      // stocktake.
      const transactionItem = createRecord(
        database,
        'TransactionItem',
        inventoryAdjustment,
        this.itemBatch.item
      );
      const transactionBatch = createRecord(
        database,
        'TransactionBatch',
        transactionItem,
        this.itemBatch
      );

      // Apply difference from stocktake to actual stock on hand levels. Whether stock is increased
      // or decreased is determined by the transaction, so we need to use the absolute value of
      // difference (i.e. always treat as positive).
      const snapshotDifference = Math.abs(this.difference);
      transactionBatch.setTotalQuantity(database, snapshotDifference);
      database.save('TransactionBatch', transactionBatch);
    }
    database.save('ItemBatch', this.itemBatch);
  }

  toString() {
    return `Stocktake batch representing ${this.itemBatch}`;
  }

  destructor(database) {
    // Delete item batch that was created as a result of creating this stocktake batch.
    if (this.snapshotNumberOfPacks === 0 && this.itemBatch.numberOfPacks === 0) {
      database.delete('ItemBatch', this.itemBatch);
    }
  }
}

export default StocktakeBatch;

StocktakeBatch.schema = {
  name: 'StocktakeBatch',
  primaryKey: 'id',
  properties: {
    id: 'string',
    stocktake: 'Stocktake',
    itemBatch: 'ItemBatch',
    snapshotNumberOfPacks: 'double',
    packSize: 'double',
    expiryDate: { type: 'date', optional: true },
    batch: 'string',
    costPrice: 'double',
    sellPrice: 'double',
    countedNumberOfPacks: { type: 'double', optional: true },
    sortIndex: { type: 'int', optional: true },
    option: { type: 'Options', optional: true },
  },
};
<|endoftext|>


<commit_before>/* eslint-disable camelcase */
import { combineReducers } from 'redux'
import { createForms } from 'react-redux-form'
import appReducer from './appReducer'
import brief from './briefReducers'
import user from './memberInfoReducers'
import dashboard from './dashboardReducers'
import errorMessage from './errorMessage'
import form_options from './form_options'

export default combineReducers({
  app: appReducer,
  user,
  brief,
  dashboard,
  form_options,
  errorMessage,
  ...createForms({
    signupForm: {
      name: '',
      email_address: ''
    },
    createUserForm: {
      name: '',
      password: ''
    },
    briefResponseForm: {
      availability: '',
      respondToEmailAddress: ''
    },
    resetPasswordEmailForm: {
      email_address: ''
    },
    resetPasswordForm: {
      password: '',
      confirmPassword: ''
    },
    loginForm: {
      emailAddress: '',
      password: ''
    }
  })
})
<commit_msg>add dayRate back to init (#627)<commit_after>/* eslint-disable camelcase */
import { combineReducers } from 'redux'
import { createForms } from 'react-redux-form'
import appReducer from './appReducer'
import brief from './briefReducers'
import user from './memberInfoReducers'
import dashboard from './dashboardReducers'
import errorMessage from './errorMessage'
import form_options from './form_options'

export default combineReducers({
  app: appReducer,
  user,
  brief,
  dashboard,
  form_options,
  errorMessage,
  ...createForms({
    signupForm: {
      name: '',
      email_address: ''
    },
    createUserForm: {
      name: '',
      password: ''
    },
    briefResponseForm: {
      availability: '',
      dayRate: '',
      respondToEmailAddress: ''
    },
    resetPasswordEmailForm: {
      email_address: ''
    },
    resetPasswordForm: {
      password: '',
      confirmPassword: ''
    },
    loginForm: {
      emailAddress: '',
      password: ''
    }
  })
})
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2016
 *
 * This file is licensed under the Affero General Public License version 3
 * or later.
 *
 * See the COPYING-README file.
 *
 */

(function(OC, OCA) {

	/**
	 * @class OCA.Notes.NoteCollection
	 * @classdesc
	 *
	 * Collection of notes assigned to a file
	 *
	 */
	var NoteCollection = OC.Backbone.Collection.extend(
		/** @lends OCA.Notes.NoteCollection.prototype */ {

		sync: OC.Backbone.davSync,

		_baseUrl: OC.generateUrl('/apps/ownnotes/notes'),
		/**
		 * Object type
		 *
		 * @type string
		 */
		_objectType: 'files',

		/**
		 * Object id
		 *
		 * @type string
		 */
		_objectId: null,
		setObjectId: function(objectId) {
			this._objectId = objectId;
		},

		insert: function(data) {
			data.objectId = this._objectId;
			console.log(data);
			// var deferred = $.Deferred();
	  //       var self = this;
	  //       $.ajax({
	  //           url: this._baseUrl,
	  //           method: 'POST',
	  //           contentType: 'application/json',
	  //           data: JSON.stringify(data)
	  //       }).done(function (data) {
	  //           deferred.resolve();
	  //       }).fail(function () {
	  //           deferred.reject();
	  //       });

	  //       return deferred.promise();
		}
	});

	OCA.Notes.NoteCollection = NoteCollection;
})(OC, OCA);

<commit_msg>update ownnote tab view file 20th<commit_after>/*
 * Copyright (c) 2016
 *
 * This file is licensed under the Affero General Public License version 3
 * or later.
 *
 * See the COPYING-README file.
 *
 */

(function(OC, OCA) {

	/**
	 * @class OCA.Notes.NoteCollection
	 * @classdesc
	 *
	 * Collection of notes assigned to a file
	 *
	 */
	var NoteCollection = OC.Backbone.Collection.extend(
		/** @lends OCA.Notes.NoteCollection.prototype */ {

		sync: OC.Backbone.davSync,

		_baseUrl: OC.generateUrl('/apps/ownnotes/notes'),
		/**
		 * Object type
		 *
		 * @type string
		 */
		_objectType: 'files',

		/**
		 * Object id
		 *
		 * @type string
		 */
		_objectId: null,
		setObjectId: function(objectId) {
			this._objectId = objectId;
		},

		insert: function(data) {
			data.objectId = this._objectId;
			console.log(data);
			OC.Notification.showTemporary(data);
			// var deferred = $.Deferred();
	  //       var self = this;
	  //       $.ajax({
	  //           url: this._baseUrl,
	  //           method: 'POST',
	  //           contentType: 'application/json',
	  //           data: JSON.stringify(data)
	  //       }).done(function (data) {
	  //           deferred.resolve();
	  //       }).fail(function () {
	  //           deferred.reject();
	  //       });

	  //       return deferred.promise();
		}
	});

	OCA.Notes.NoteCollection = NoteCollection;
})(OC, OCA);

<|endoftext|>


<commit_before>define(
  'ephox.alloy.demo.FormDemo',

  [
    'ephox.alloy.api.Gui',
    'ephox.alloy.demo.HtmlDisplay',
    'ephox.highway.Merger',
    'ephox.sugar.api.Class',
    'ephox.sugar.api.Element',
    'ephox.sugar.api.Insert',
    'global!document'
  ],

  function (Gui, HtmlDisplay, Merger, Class, Element, Insert, document) {
    return function () {
      var gui = Gui.create();
      var body = Element.fromDom(document.body);
      Class.add(gui.element(), 'gui-root-demo-container');
      Insert.append(body, gui.element());

      var mungers = {
        'text-input': function (spec) {
          return Merger.deepMerge(spec, {
            dom: {
              tag: 'div'
            },
            components: [
              { uiType: 'placeholder', name: '<alloy.form.field-label>', owner: 'formlabel' },
              { uiType: 'placeholder', name: '<alloy.form.field-input>', owner: 'formlabel' }
            ]
          });
        },
        'radio-group': function (spec) {
          return Merger.deepMerge(spec, {
            dom: {
              tag: 'fieldset'
            },
            label: 'Radio',
            parts: {
              legend: { },
              fields: { }
            },
            components: [
              { uiType: 'placeholder', name: '<alloy.form.radio-fields>', owner: 'radio-group' },
              { uiType: 'placeholder', name: '<alloy.form.field-legend>', owner: 'radio-group' }
            ]
          });
        }
      };

      var form = HtmlDisplay.section(
        gui,
        'This form has many fields',
        {
          uiType: 'form',
          dom: {
            tag: 'div',
            classes: [ 'outside-form' ]
          },
          members: {
            ui: {
              munge: function (spec) {
                return mungers[spec.type](spec);
              }
            }
          },
          parts: {
            alpha: { type: 'text-input', label: 'Alpha' },
            beta: { type: 'text-input', label: 'Beta' },
            gamma: {
              type: 'radio-group',
              name: 'gamma',
              candidates: [
                { value: 'abra', text: 'Abra' },
                { value: 'cad', text: 'Cad' },
                { value: 'abra!', text: 'abra!' }
              ]
            }
          },

          components: [
            { uiType: 'placeholder', owner: 'form', name: '<alloy.field.alpha>' },
            { uiType: 'placeholder', owner: 'form', name: '<alloy.field.beta>' },
            { uiType: 'placeholder', owner: 'form', name: '<alloy.field.gamma>' },
          ],

          // uis: [
          //   { type: 'text-input', label: 'Alpha', name: 'alpha' },
          //   { type: 'text-input', label: 'Beta', inline: false, name: 'beta' },
            // {
            //   type: 'radio-group',
            //   name: 'gamma',
            //   candidates: [
            //     { value: 'abra', text: 'Abra' },
            //     { value: 'cad', text: 'Cad' },
            //     { value: 'abra!', text: 'abra!' }
            //   ]
            // },
            // {
            //   type: 'form-scaffold',
            //   dom: {
            //     tag: 'div',
            //     classes: [ 'scaffold' ]
            //   },
            //   parts: {
            //     field: {
            //       type: 'text-input',
            //       label: 'scaffold-a',
            //       name: 'scaffold-a'
            //     }
            //   },
            //   components: [
            //     { uiType: 'placeholder', name: '<alloy.form.element>', owner: 'form-scaffold' }
            //   ]
            // }
          // ],
          keying: {
            mode: 'cyclic'
          }
        }
      );

      form.apis().setValue({
        alpha: 'doggy',
        beta: 'bottle',
        gamma: 'cad'
      });
    };
  }
);<commit_msg>VAN-44-wheel-hackery: cleaner form syntax<commit_after>define(
  'ephox.alloy.demo.FormDemo',

  [
    'ephox.alloy.api.Gui',
    'ephox.alloy.demo.HtmlDisplay',
    'ephox.highway.Merger',
    'ephox.sugar.api.Class',
    'ephox.sugar.api.Element',
    'ephox.sugar.api.Insert',
    'global!document'
  ],

  function (Gui, HtmlDisplay, Merger, Class, Element, Insert, document) {
    return function () {
      var gui = Gui.create();
      var body = Element.fromDom(document.body);
      Class.add(gui.element(), 'gui-root-demo-container');
      Insert.append(body, gui.element());

      var mungers = {
        'text-input': function (spec) {
          return Merger.deepMerge(spec, {
            dom: {
              tag: 'div'
            },
            components: [
              { uiType: 'placeholder', name: '<alloy.form.field-label>', owner: 'formlabel' },
              { uiType: 'placeholder', name: '<alloy.form.field-input>', owner: 'formlabel' }
            ]
          });
        },
        'radio-group': function (spec) {
          return Merger.deepMerge(spec, {
            dom: {
              tag: 'fieldset'
            },
            label: 'Radio',
            parts: {
              legend: { },
              fields: { }
            },
            components: [
              { uiType: 'placeholder', name: '<alloy.form.radio-fields>', owner: 'radio-group' },
              { uiType: 'placeholder', name: '<alloy.form.field-legend>', owner: 'radio-group' }
            ]
          });
        }
      };

      var form = HtmlDisplay.section(
        gui,
        'This form has many fields',
        {
          uiType: 'form',
          dom: {
            tag: 'div',
            classes: [ 'outside-form' ]
          },
          members: {
            ui: {
              munge: function (spec) {
                return mungers[spec.type](spec);
              }
            }
          },
          parts: {
            alpha: { type: 'text-input', label: 'Alpha', inline: false },
            beta: { type: 'text-input', label: 'Beta' },
            gamma: {
              type: 'radio-group',
              name: 'gamma',
              candidates: [
                { value: 'abra', text: 'Abra' },
                { value: 'cad', text: 'Cad' },
                { value: 'abra!', text: 'abra!' }
              ]
            },
            delta: { type: 'text-input', label: 'Delta' },
            epsilon: { type: 'text-input', label: 'Epsilon' }
          },

          components: [
            { uiType: 'placeholder', owner: 'form', name: '<alloy.field.alpha>' },
            { uiType: 'placeholder', owner: 'form', name: '<alloy.field.beta>' },
            { uiType: 'placeholder', owner: 'form', name: '<alloy.field.gamma>' },
            {
              uiType: 'container',
              components: [
                { uiType: 'placeholder', owner: 'form', name: '<alloy.field.delta>' },
                { uiType: 'placeholder', owner: 'form', name: '<alloy.field.epsilon>' }
              ]
            }
          ],

          // uis: [
          //   { type: 'text-input', label: 'Alpha', name: 'alpha' },
          //   { type: 'text-input', label: 'Beta', inline: false, name: 'beta' },
            // {
            //   type: 'radio-group',
            //   name: 'gamma',
            //   candidates: [
            //     { value: 'abra', text: 'Abra' },
            //     { value: 'cad', text: 'Cad' },
            //     { value: 'abra!', text: 'abra!' }
            //   ]
            // },
            // {
            //   type: 'form-scaffold',
            //   dom: {
            //     tag: 'div',
            //     classes: [ 'scaffold' ]
            //   },
            //   parts: {
            //     field: {
            //       type: 'text-input',
            //       label: 'scaffold-a',
            //       name: 'scaffold-a'
            //     }
            //   },
            //   components: [
            //     { uiType: 'placeholder', name: '<alloy.form.element>', owner: 'form-scaffold' }
            //   ]
            // }
          // ],
          keying: {
            mode: 'cyclic'
          }
        }
      );

      form.apis().setValue({
        alpha: 'doggy',
        beta: 'bottle',
        gamma: 'cad'
      });
    };
  }
);<|endoftext|>


<commit_before>define(
  'ephox.darwin.demo.Logbook',

  [
    'ephox.peanut.Fun',
    'ephox.sugar.api.Css',
    'ephox.sugar.api.Element',
    'ephox.sugar.api.Insert',
    'global!Date'
  ],

  function (Fun, Css, Element, Insert, Date) {
    // This file was used for a previous demo.
    return function () {
      var logbook = Element.fromTag('div');
      Css.setAll(logbook, {
        width: '800px',
        float: 'right',
        height: '300px',
        overflow: 'scroll',
        border: '1px solid #333'
      });

      var updateLogbook = function (msg) {
        var pre = Element.fromHtml('<p>' + new Date().toString() + ': ' + msg + '</p>');
        Insert.prepend(logbook, pre);
      };

      return {
        element: Fun.constant(logbook)
      };
    };
  }
);<commit_msg>TBIO-2621: unused<commit_after><|endoftext|>


<commit_before>(function(global, _, Sizzle, smx){

const ComputedAttributes = {

    /**
     *  @method index
     *  position in parent children
     */

    test: function(){

      //this === node

    }

};

//extend SMXNode with computed attribute functions as getters
_.each(ComputedAttributes, function(fn,key){
  Object.defineProperty(smx.Node.prototype, key, { get: fn });
});

})(window, window._, window.Sizzle, window.smx);
<commit_msg>delete old unused file<commit_after><|endoftext|>


<commit_before>'use strict';

/**
 * @ngdoc object
 * @name ng.$document
 * @requires $window
 *
 * @description
 * A {@link angular.element jQuery or jqLite} wrapper for the browser's `window.document` element.
 */
function $DocumentProvider(){
  this.$get = ['$window', function(window){
    return jqLite(window.document);
  }];
}
<commit_msg>docs($document): moar better description<commit_after>'use strict';

/**
 * @ngdoc object
 * @name ng.$document
 * @requires $window
 *
 * @description
 * A {@link angular.element jQuery or jqLite} wrapper for the browser's `window.document` object.
 */
function $DocumentProvider(){
  this.$get = ['$window', function(window){
    return jqLite(window.document);
  }];
}
<|endoftext|>


<commit_before>#!/usr/bin/env node

const fs = require('fs');
const path = require('path');

//command line arguments
//first argument is the directory you want to
//turn into a soundfont.
const sfPath = process.argv[2];

//only these files will be parsed
var acceptExt = [
	".wav", ".ogg", ".mp3", ".aiff", ".aif"
];

var noteExp = /(?:\\-|\b)[a-g]#?[0-7]/ig;
var velExp = /(?:-vel)+[\d]/ig;

function getFileNamesInFolder(folderPath) {
	folderPath = path.resolve(folderPath); //make it absolute.

	if (fs.lstatSync(folderPath).isDirectory()) {
		var filenames = fs.readdirSync(folderPath);

		return filenames;
	} else {throw Error(`${folderPath} is not a directory!`);}
}

function setNote(noteLetter) {
	switch (noteLetter) {
		case "a": return "10";
		case "a#": return "11";
		case "b": return "12";
		case "c": return "01";
		case "c#": return "02";
		case "d": return "03";
		case "d#": return "04";
		case "e": return "05";
		case "f": return "06";
		case "f#": return "07";
		case "g": return "08";
		case "g#": return "09";
	}
}

function parseSFZ() {
	var sfz = "";
	var notes = [];

	//get conversion information
	for (var f in names) {
		var note = {
			letter : "n",
			octave : {},
			note : {},
			velocity : {},
			sample : {}
		};

		if (acceptExt.includes(path.extname(names[f]))) {
			notes.push(note); //push instance
			note.sample = names[f]; //store the filename

			var noteNames = names[f].toLowerCase().match(noteExp);
			var velNums = names[f].match(velExp);

			//console.log(velNums);

			if (noteNames.length > 1) {
				console.log("Check", names[f], "for instances resembling note names.");

				for (var i in noteNames) {
					console.log("Detected Sequence " + (parseInt(i) + 1) + " is " + noteNames[i]);
				} process.exit(1);
			} else {
				if (noteNames[0].length > 2) {
					note.letter = noteNames[0][0] + noteNames[0][1];
					note.octave = noteNames[0][2];
					note.note = setNote(noteNames[0][0] + noteNames[0][1]);
				} else {
					note.letter = noteNames[0][0];
					note.octave = noteNames[0][1];
					note.note = setNote(noteNames[0][0]);
				}
			}
		}
	}

	notes = notes.sort(function(a,b){
		if (a.octave == b.octave) {
			if (a.note == b.note) { return parseInt(a.velocity) - parseInt(b.velocity); } //by velocity
			else { return parseInt(a.note) - parseInt(b.note); } //by note
		} else { return parseInt(a.octave) - parseInt(b.octave); } //by octave
	});

	//console.log(notes);

	//build text file
	for (var i in notes) {
		var low = "";
		var high = "";

		sfz = sfz + "<region>\n";
		sfz = sfz + "sample=" + notes[i].sample + "\n";

		if (i == 0) {
			high = middleKey(notes[i], notes[parseInt(i) + 1], "up");
			sfz = sfz + "hikey=" + high + "\n";
		} else if (i == notes.length - 1) {
			low = middleKey(notes[i], notes[parseInt(i) - 1], "down");
			sfz = sfz + "lokey=" + low + "\n";
		} else {
			low = middleKey(notes[i], notes[parseInt(i) - 1], "down");
			high = middleKey(notes[i], notes[parseInt(i) + 1], "up");
			sfz = sfz + "lokey=" + low + "\n";
			sfz = sfz + "hikey=" + high + "\n";
		}

		sfz = sfz + "pitch_keycenter=" + notes[i].letter + notes[i].octave + "\n";
		sfz += "\n";
	}

	return sfz;
}

//find note between samples
function middleKey(self, friend, dir) {
	var newKey = "";
	var noteCount = [];

	var myNote = parseInt(self.note);
	var myOctave = parseInt(self.octave)
	var frNote = parseInt(friend.note);
	var frOctave = parseInt(friend.octave)

	var distance = distCount(myNote, frNote, myOctave, frOctave, dir);

	var distLow = Math.floor(distance/2);
	var distHigh = distance - distLow - 1;

	if (dir == "down") {noteCount = keyCount(myNote, distLow, myOctave, "down");}
	else {noteCount = keyCount(myNote, distHigh, myOctave, "up");}

	newKey = nameNote(self, friend, noteCount[0], noteCount[1]);

	return newKey;
}

//name note...obvs
function nameNote(me, them, num, oct) {
	var numString = ""

	switch (num) {
		case 1: numString = "c"; break;
		case 2: numString = "c#"; break;
		case 3: numString = "d"; break;
		case 4: numString = "d#"; break;
		case 5: numString = "e"; break;
		case 6: numString = "f"; break;
		case 7: numString = "f#"; break;
		case 8: numString = "g"; break;
		case 9: numString = "g#"; break;
		case 10: numString = "a"; break;
		case 11: numString = "a#"; break;
		case 12: numString = "b"; break;
	}

	if (numString == them.letter && oct == them.octave) {
		numString = me.letter + me.octave;
	} else {numString = numString + oct.toString();}

	return numString;
}

//find note
function keyCount(countFrom, countAmount, octave, dir) {
	var count = 0;
	var newOctave = octave;
	var newKey = countFrom;
	var both = [];

	while(count < countAmount) {
		if (dir == "up") {newKey++;}
		if (dir == "down") {newKey--;}

		if (newKey > 12) {newOctave++; newKey = 1;}
		if (newKey < 1) {newOctave--; newKey = 12;}
		count++;
	}

	both.push(newKey);
	both.push(newOctave);

	return both;
}

//find distance
function distCount(countFrom, countTo, sOct, fOct, dir) {
	var distance = 0;
	var count = countFrom;
	var nOct = sOct;

	while (count != countTo || nOct != fOct) {
		if (dir == "up") {
			distance++;
			count++;
		}

		if (dir == "down") {
			distance++;
			count--;
		}

		if (count > 12) {nOct++; count = 1;}
		if (count < 1) {nOct--; count = 12;}
	}

	return distance;
}

function writeFile(filePath, contents) {
	filePath = path.resolve(filePath);
	fs.writeFileSync(filePath, contents);
}

var names = getFileNamesInFolder(sfPath);
var folderName = path.basename(sfPath);

//write sfz to text file
writeFile(path.join(sfPath, folderName + ".sfz"), parseSFZ(names));<commit_msg>Added velocity support<commit_after>#!/usr/bin/env node

const fs = require('fs');
const path = require('path');

//command line arguments
//first argument is the directory you want to
//turn into a soundfont.
const sfPath = process.argv[2];

//only these files will be parsed
var acceptExt = [
	".wav", ".ogg", ".mp3", ".aiff", ".aif"
];

var noteExp = /(?:\\-|\b)[a-g]#?[0-7]/ig;
var velExp = /(vel[^-]+)[\d]/ig;

function getFileNamesInFolder(folderPath) {
	folderPath = path.resolve(folderPath); //make it absolute.

	if (fs.lstatSync(folderPath).isDirectory()) {
		var filenames = fs.readdirSync(folderPath);

		return filenames;
	} else {throw Error(`${folderPath} is not a directory!`);}
}

function setNote(noteLetter) {
	switch (noteLetter) {
		case "a": return "10";
		case "a#": return "11";
		case "b": return "12";
		case "c": return "01";
		case "c#": return "02";
		case "d": return "03";
		case "d#": return "04";
		case "e": return "05";
		case "f": return "06";
		case "f#": return "07";
		case "g": return "08";
		case "g#": return "09";
	}
}

function parseSFZ() {
	var sfz = "";
	var notes = [];
	var venabled = false;

	//get conversion information
	for (var f in names) {
		var note = {
			letter : "n",
			octave : {},
			note : {},
			velocity : null,
			sample : {}
		};

		if (acceptExt.includes(path.extname(names[f]))) {
			notes.push(note); //push instance
			note.sample = names[f]; //store the filename

			var noteNames = names[f].toLowerCase().match(noteExp);
			var velNums = names[f].match(velExp);

			if (velNums != null) { //store velocity
				note.velocity = velNums[0].replace(/\D/g,''); //isolate the velocity integers
				venabled = true;
			} else if (venabled) {
				console.log("Check", names[f], "for missing velocity markings.");
				process.exit(1);
			}

			if (noteNames == null) { //debug if dashes aren't used properly
				console.log("Check", names[f], "for improper formatting.");
				process.exit(1);
			} else {
				if (noteNames.length > 1) { //too many instances resembling note names
					console.log("Check", names[f], "for instances resembling note names.");

					for (var i in noteNames) {
						console.log("Detected Sequence " + (parseInt(i) + 1) + " is " + noteNames[i]);
					} process.exit(1);
				} else { //store note name
					if (noteNames[0].length > 2) {
						note.letter = noteNames[0][0] + noteNames[0][1];
						note.octave = noteNames[0][2];
						note.note = setNote(noteNames[0][0] + noteNames[0][1]);
					} else {
						note.letter = noteNames[0][0];
						note.octave = noteNames[0][1];
						note.note = setNote(noteNames[0][0]);
					}
				}
			}
		}
	}

	notes = notes.sort(function(a,b) {
		if (a.octave == b.octave) {
			if (a.note == b.note) { return parseInt(a.velocity) - parseInt(b.velocity); } //by velocity
			else { return parseInt(a.note) - parseInt(b.note); } //by note
		} else { return parseInt(a.octave) - parseInt(b.octave); } //by octave
	});

	//console.log(notes);

	//build text file
	for (var i in notes) {
		var down = null;
		var up = null;
		var low = "";
		var high = "";
		var vel = "";

		sfz = sfz + "<region>\n";
		sfz = sfz + "sample=" + notes[i].sample + "\n";

		down = findNextNote(notes[i], notes, "down");
		up = findNextNote(notes[i], notes, "up");

		if (down != null) {low = middleKey( notes[i], down, "down"); }
		if (up != null) {high = middleKey( notes[i], up, "up"); }
		if (low != "") {sfz = sfz + "lokey=" + low + "\n";}
		if (high != "") {sfz = sfz + "hikey=" + high + "\n";}

		if (notes[i].velocity != null) {
			if (i > 0) {
				if (notes[i-1].letter == notes[i].letter && notes[i-1].octave == notes[i].octave) {
					vel = setVelocity(notes[i-1].velocity, "high");
					sfz = sfz + "lovel=" + vel + "\n";
				}
			}

			sfz = sfz + "hivel=" + notes[i].velocity + "\n";
		}

		/*
		if (i == 0) { //first in the array
			//high = middleKey(notes[i], notes[parseInt(i) + 1], "up");
			next = findNextNote(notes[i], notes, "up");
			high = middleKey(notes[i], next, "up");
			sfz = sfz + "hikey=" + high + "\n";

			console.log(next);

			if (notes[i].velocity != null) {
				sfz = sfz + "hivel=" + notes[i].velocity + "\n";
			} else {console.log("this is it");}
		} else if (i == notes.length - 1) { //last in the array
			//low = middleKey(notes[i], notes[parseInt(i) - 1], "down");
			next = findNextNote(notes[i], notes, "down");
			low = middleKey(notes[i], next, "down");
			sfz = sfz + "lokey=" + low + "\n";

			//low velocity
			if (notes[i].velocity != null) { //if velocity was specified at all in filename
				if (notes[i-1].letter == notes[i].letter && notes[i-1].octave == notes[i].octave) {
					vel = setVelocity(notes[i-1].velocity, "high");
					sfz = sfz + "lovel=" + vel + "\n";
				} sfz = sfz + "hivel=" + notes[i].velocity + "\n"; //high velocity
			}
		} else { //middle of the array
			next = findNextNote(notes[i], notes, "down");
			low = middleKey(notes[i], next, "down");
			//low = middleKey(notes[i], notes[parseInt(i) - 1], "down");
			next = findNextNote(notes[i], notes, "up");
			//high = middleKey(notes[i], notes[parseInt(i) + 1], "up");
			high = middleKey(notes[i], next, "up");
			sfz = sfz + "lokey=" + low + "\n";
			sfz = sfz + "hikey=" + high + "\n";

			if (notes[i].velocity != null) {
				if (notes[i-1].letter == notes[i].letter && notes[i-1].octave == notes[i].octave) {
					vel = setVelocity(notes[i-1].velocity, "high");
					sfz = sfz + "lovel=" + vel + "\n";
				} sfz = sfz + "hivel=" + notes[i].velocity + "\n";
			}
		}
		*/
		sfz = sfz + "pitch_keycenter=" + notes[i].letter + notes[i].octave + "\n";
		sfz += "\n";
	}

	return sfz;
}

function setVelocity(vel) {
	vel = parseInt(vel);
	vel = vel + 1;
	return vel.toString();
}

function findNextNote(self, friends, dir) {
	var okay = false;

	if (dir == "up") {
		for (var f = 0; f < friends.length; f++) {
			if (okay) {
				if (self.letter != friends[f].letter) {return friends[f];}
				else if (self.octave != friends[f].octave) {return friends[f];}
			} else if (friends[f] == self) {okay = true;}
		}
	} else {
		for (var g = friends.length - 1; g > -1; g--) {
			if (okay) {
				if (self.letter != friends[g].letter) {return friends[g];}
				else if (self.octave != friends[g].octave) {return friends[g];}
			} else if (friends[g] == self) {okay = true;}
		}
	}
}

//find note between samples
function middleKey(self, friend, dir) {
	var newKey = "";
	var noteCount = [];

	var myNote = parseInt(self.note);
	var myOctave = parseInt(self.octave)
	var frNote = parseInt(friend.note);
	var frOctave = parseInt(friend.octave)

	var distance = distCount(myNote, frNote, myOctave, frOctave, dir);

	var distLow = Math.floor(distance/2);
	var distHigh = distance - distLow - 1;

	if (dir == "down") {noteCount = keyCount(myNote, distLow, myOctave, "down");}
	else {noteCount = keyCount(myNote, distHigh, myOctave, "up");}

	newKey = nameNote(self, friend, noteCount[0], noteCount[1]);

	return newKey;
}

//name note...obvs
function nameNote(me, them, num, oct) {
	var numString = ""

	switch (num) {
		case 1: numString = "c"; break;
		case 2: numString = "c#"; break;
		case 3: numString = "d"; break;
		case 4: numString = "d#"; break;
		case 5: numString = "e"; break;
		case 6: numString = "f"; break;
		case 7: numString = "f#"; break;
		case 8: numString = "g"; break;
		case 9: numString = "g#"; break;
		case 10: numString = "a"; break;
		case 11: numString = "a#"; break;
		case 12: numString = "b"; break;
	}

	if (numString == them.letter && oct == them.octave) {
		numString = me.letter + me.octave;
	} else {numString = numString + oct.toString();}

	return numString;
}

//find note
function keyCount(countFrom, countAmount, octave, dir) {
	var count = 0;
	var newOctave = octave;
	var newKey = countFrom;
	var both = [];

	while(count < countAmount) {
		if (dir == "up") {newKey++;}
		if (dir == "down") {newKey--;}

		if (newKey > 12) {newOctave++; newKey = 1;}
		if (newKey < 1) {newOctave--; newKey = 12;}
		count++;
	}

	both.push(newKey);
	both.push(newOctave);

	return both;
}

//find distance
function distCount(countFrom, countTo, sOct, fOct, dir) {
	var distance = 0;
	var count = countFrom;
	var nOct = sOct;

	while (count != countTo || nOct != fOct) {
		if (dir == "up") {
			distance++;
			count++;
		}

		if (dir == "down") {
			distance++;
			count--;
		}

		if (count > 12) {nOct++; count = 1;}
		if (count < 1) {nOct--; count = 12;}
	}

	return distance;
}

function writeFile(filePath, contents) {
	filePath = path.resolve(filePath);
	fs.writeFileSync(filePath, contents);
}

var names = getFileNamesInFolder(sfPath);
var folderName = path.basename(sfPath);

//write sfz to text file
writeFile(path.join(sfPath, folderName + ".sfz"), parseSFZ(names));<|endoftext|>


<commit_before>#!/usr/bin/env node

/*
 * A command line script to produce mocked data output for the
 * CrowdCompass CSV input interfaces.
 *
 * Usage: gsvGen [#]
*/

var fake = require('faker');
var fs = require('fs');

var URL = function() { return("http://www." + fake.internet.domainName() + "/" + fake.lorem.words(1)); };
var Company = function() { return(fake.company.bsAdjective() + " " + fake.company.bsNoun())};
var Job = function() { return(fake.company.catchPhraseAdjective() + " " + fake.company.catchPhraseNoun() + " Specialist") };

var locales = ['de', 'de_AT','de_CH','en','en_AU','en_BORK','en_CA','en_GB','en_IND',
  'en_US','en_au_ocker','es','fa','fr','it','ja','ko','nb_NO','nep','nl','pl','pt_BR',
  'ru','sk','sv','vi','zh_CN'];

if (!process.argv[2]) {
  console.log("Usage: csvGen #");
} else {
  input = +process.argv[2];
  console.log("Unique ID, First Name, Last Name, Email, Registration Code, Show on Attendee List, Company Name, Job Title, Brief Bio, Work Phone, Mobile Phone, Other Phone, Other Phone Type, Address, Address 2, City, State, Zipcode, Country, Website, Website 2, Linkedin URL, Twitter URL, Facebook URL, Group List (comma-separated)");
  for (var i=0; i < input; i++) {
      for (i=0; i < locales.length; i++) {
        fake.locale = locales[i];
        var stream = fs.createWriteStream(locales[i] + "_import.csv");
        stream.once('open', function(fd) {
          stream.write("A-" + (i+1) + ", " + fake.name.firstName() + ", " + fake.name.lastName()
               + ", " + fake.internet.email() + ", " + ", " + "FALSE, " + Company()
               + ", " + Job() + ", " + ", " + fake.phone.phoneNumber() + ", " + ", "
               + ", " + ", " + fake.address.streetAddress() + ", " + ", " + fake.address.city()
               + ", " + fake.address.state() + ", " + fake.address.zipCode()
               + ", " + fake.address.country() + ", " + URL() + ", " + URL()
               + ", " + ", " + ", " + ", ");
          stream.end();
      }
   }
}

/*

var stream = fs.createWriteStream("my_file.txt");
stream.once('open', function(fd) {
  stream.write("My first row\n");
  stream.write("My second row\n");
  stream.end();
});

console.log("File output as my_file.txt");

*/
<commit_msg>new and improved csvGen. looping record export into a file works. Now need to flesh out what it exports again<commit_after>#!/usr/bin/env node

var fake = require('faker');
var fs = require('fs');
//var localeKey = ["en_US", "en_AU", "en_UK"];
var localeKey = "en_US";  // lets just go with English for now and make it functional

if (!process.argv[2] || isNaN(+process.argv[2])) {
  console.log("Usage: csvGen #");
} else { // only write a file if the user indicates how many records
  userInput = +process.argv[2];
  var stream = fs.createWriteStream("en_US.csv");
  stream.once('open', function(fd) {
    stream.write("Record, First Name, Last Name, Email \n");
    for (i=0; i<userInput; i++) {
      stream.write(fake.name.firstName() + ", " + fake.name.lastName() + ", " + fake.internet.email() + "\n");
    }
    stream.end();
    console.log(localeKey + ".csv created");
  });
}
<|endoftext|>