<commit_before>// This object will contain registration prices for 2015 PYM
// The hierarchy for prices is as follows
//  age group -> registration type -> accommodations -> days attending
prices = {
    /*
    * Adult prices
    */
    'adult': {
        'commuter': 50, // daily commuter fee
        'daily': {
            'private': 100, // daily private lodgings
            'semiPrivate': 75, // daily semi-private lodgings
            'dorm': 50, // daily dorm lodgings
            'camping': 25 // daily camping
        },
        'weekly': {
            'private': 500, // weekly private lodgings
            'semiPrivate': 400, // weekly semi-private
            'dorm': 300, // weekly dorm
            'camping': 200, // weekly camping
            'yaf': 200, // weekly yaf
            'jym': 200 // weekly jym
        }
    },
     /*
    * Young adult prices
    */
    'youngAdult': {
        'commuter': 50,
        'daily': {
            'private': 200,
            'semiPrivate': 150,
            'dorm': 100,
            'camping': 50
        },
        'weekly': {
            'private': 500,
            'semiPrivate': 400,
            'dorm': 300,
            'camping': 200,
            'yaf': 200,
            'jym': 200
        }
    },
    /*
    * Teen prices
    */
    'teen': {
        'commuter': 50,
        'daily': {
            'private': 200,
            'semiPrivate': 150,
            'dorm': 100,
            'camping': 50
        },
        'weekly': {
            'private': 500,
            'semiPrivate': 400,
            'dorm': 300,
            'camping': 200,
            'yaf': 200,
            'jym': 200
        }
    },
    /*
    * Youth prices
    */
    'youth': {
        'commuter': 50,
        'daily': {
            'private': 200,
            'semiPrivate': 150,
            'dorm': 100,
            'camping': 50,
            'jym': 50
        },
        'weekly': {
            'private': 500,
            'semiPrivate': 400,
            'dorm': 300,
            'camping': 200,
            'yaf': 200,
            'jym': 200
        }
    },
    /*
    * Child prices
    */
    'child': {
        'commuter': 50,
        'daily': {
            'private': 200,
            'semiPrivate': 150,
            'dorm': 100,
            'camping': 50
        },
        'weekly': {
            'private': 500,
            'semiPrivate': 400,
            'dorm': 300,
            'camping': 200
        }
    }
};

calculateRegistrationPrice = function () {
    // Calculate registration type based on Age, registration type, accommodations, and number of days

    // var total = 0;

    // if registration type is commuter
        // dayFee = prices[ageGroup][registrationType]
        // for each selected days
            // check to see if any day should be discounted
            // total += dayFee

    // if registration type is daily
        // dayFee = prices[ageGroup][registrationType][accommodations]
        // for each selected days
            // if day should be discounted
                //total += day * discount (e.g. 0.5)
            // else
                // total += day

    // if registration type is weekly
    // total = prices[ageGroup][registrationType][accommodations]

    //temporary test
    total = 200;
    return total;
};
<commit_msg>Function documentation; try catch<commit_after>// This object will contain registration prices for 2015 PYM
// The hierarchy for prices is as follows
//  age group -> registration type -> accommodations -> days attending
prices = {
    /*
    * Adult prices
    */
    'adult': {
        'commuter': 50, // daily commuter fee
        'daily': {
            'private': 100, // daily private lodgings
            'semiPrivate': 75, // daily semi-private lodgings
            'dorm': 50, // daily dorm lodgings
            'camping': 25 // daily camping
        },
        'weekly': {
            'private': 500, // weekly private lodgings
            'semiPrivate': 400, // weekly semi-private
            'dorm': 300, // weekly dorm
            'camping': 200, // weekly camping
            'yaf': 200, // weekly yaf
            'jym': 200 // weekly jym
        }
    },
     /*
    * Young adult prices
    */
    'youngAdult': {
        'commuter': 50,
        'daily': {
            'private': 200,
            'semiPrivate': 150,
            'dorm': 100,
            'camping': 50
        },
        'weekly': {
            'private': 500,
            'semiPrivate': 400,
            'dorm': 300,
            'camping': 200,
            'yaf': 200,
            'jym': 200
        }
    },
    /*
    * Teen prices
    */
    'teen': {
        'commuter': 50,
        'daily': {
            'private': 200,
            'semiPrivate': 150,
            'dorm': 100,
            'camping': 50
        },
        'weekly': {
            'private': 500,
            'semiPrivate': 400,
            'dorm': 300,
            'camping': 200,
            'yaf': 200,
            'jym': 200
        }
    },
    /*
    * Youth prices
    */
    'youth': {
        'commuter': 50,
        'daily': {
            'private': 200,
            'semiPrivate': 150,
            'dorm': 100,
            'camping': 50,
            'jym': 50
        },
        'weekly': {
            'private': 500,
            'semiPrivate': 400,
            'dorm': 300,
            'camping': 200,
            'yaf': 200,
            'jym': 200
        }
    },
    /*
    * Child prices
    */
    'child': {
        'commuter': 50,
        'daily': {
            'private': 200,
            'semiPrivate': 150,
            'dorm': 100,
            'camping': 50
        },
        'weekly': {
            'private': 500,
            'semiPrivate': 400,
            'dorm': 300,
            'camping': 200
        }
    }
};

calculateRegistrationPrice = function (ageGroup, registrationType, accommodations, days) {
    /*
    * Calculate registration type based on
    *    Age,
    *    registration type,
    *    accommodations, and
    *    number of days
    */

    var total = 0;

    // Convert the input from reactive variables if needed
    try{
        ageGroup = ageGroup.get();
        registrationType = registrationType.get();
        accommodations = accommodations.get();
    } catch (e) {
        console.log(e);
    }

     // Testing variable input
    console.log("Age group input: " + ageGroup);
    console.log("Registration type input: " + registrationType);
    console.log("Accommodations input: " + accommodations);
    //console.log("Days input: " + days);

    // if registration type is commuter
        // dayFee = prices[ageGroup][registrationType]
        // for each selected days
            // check to see if any day should be discounted
            // total += dayFee

    // if registration type is daily
        // dayFee = prices[ageGroup][registrationType][accommodations]
        // for each selected days
            // if day should be discounted
                //total += day * discount (e.g. 0.5)
            // else
                // total += day

    // if registration type is weekly
    // total = prices[ageGroup][registrationType][accommodations]

    //temporary test
    total = 200;
    return total;
};
<|endoftext|>


<commit_before>(function () {
  'use strict';

  angular.module('permission')
    .provider('Permission', function () {
      var permissionStore = {};
      var self = this;

      /**
       * Allows to define permission on application configuration
       * @deprecated
       *
       * @param permission {String} Name of defined permission
       * @param validationFunction {Function} Function used to validate if permission is valid
       */
      this.defineRole = function (permission, validationFunction) {
        console.warn('Function "defineRole" will be deprecated. Use "definePermission" instead');
        self.definePermission(permission, validationFunction);
        return this;
      };

      /**
       * Allows to define permission on application configuration
       *
       * @param permission {String} Name of defined permission
       * @param validationFunction {Function} Function used to validate if permission is valid
       */
      this.definePermission = function (permission, validationFunction) {
        validatePermission(permission, validationFunction);
        permissionStore[permission] = validationFunction;
        return this;
      };

      /**
       * Allows to define set of permissions with shared validation function on application configuration
       *
       * @param permissions {Array} Set of permission names
       * @param validationFunction {Function} Function used to validate if permission is valid
       */
      this.defineManyPermissions = function (permissions, validationFunction) {
        if (!angular.isArray(permissions)) {
          throw new TypeError('Parameter "permissions" name must be Array');
        }

        angular.forEach(permissions, function (permissionName) {
          self.definePermission(permissionName, validationFunction);
        });

        return this;
      };

      /**
       * Checks if provided permission has accepted parameter types
       * @private
       *
       * @param permission {String} Name of defined permission
       * @param validationFunction {Function} Function used to validate if permission is valid
       */
      function validatePermission(permission, validationFunction) {
        if (!angular.isString(permission)) {
          throw new TypeError('Parameter "permission" name must be String');
        }
        if (!angular.isFunction(validationFunction)) {
          throw new TypeError('Parameter "validationFunction" must be Function');
        }
      }

      /**
       * Checks if provided permission map has accepted parameter types
       * @private
       *
       * @param permissionMap {Object}
       */
      function validatePermissionMap(permissionMap) {
        if (!angular.isObject(permissionMap)) {
          throw new TypeError('Parameter "permissionMap" has to be Object');
        }

        if (angular.isUndefined(permissionMap.only) && angular.isUndefined(permissionMap.except)) {
          throw new ReferenceError('Either "only" or "except" keys must me defined');
        }

        if (!(angular.isArray(permissionMap.only) || angular.isArray(permissionMap.except))) {
          throw new TypeError('Parameter "permissionMap" properties must be Array');
        }
      }

      this.$get = ['$q', function ($q) {

        /**
         * Converts a value into a promise, if the value is truthy it resolves it, otherwise it rejects it
         * @private
         *
         * @param func {Function} Function to be wrapped into promise
         * @return {Promise} $q.promise object
         */
        function wrapInPromise(func) {
          var dfd = $q.defer();

          if (func) {
            dfd.resolve();
          } else {
            dfd.reject();
          }

          return dfd.promise;
        }

        /**
         * Performs iteration over list of defined permissions looking for matching roles
         * @private
         *
         * @param permissions {Array} Set of permission names
         * @param toParams {Object} UI-Router params object
         * @returns {promise} $q.promise object
         */
        function findMatchingRole(permissions, toParams) {
          var deferred = $q.defer();
          var currentPermission = permissions.shift();

          if (angular.isDefined(currentPermission) && angular.isFunction(permissionStore[currentPermission])) {
            var validationResult = permissionStore[currentPermission].call(self, toParams, currentPermission);

            if (!angular.isFunction(validationResult.then)) {
              validationResult = wrapInPromise(validationResult);
            }

            $q.when(validationResult)
              .then(function () {
                deferred.resolve();
              })
              .catch(function () {
                findMatchingRole(permissions, toParams)
                  .then(function () {
                    deferred.resolve();
                  })
                  .catch(function () {
                    deferred.reject();
                  });
              });
          } else {
            // If no roles left to validate reject promise
            deferred.reject();
          }

          return deferred.promise;
        }

        /**
         * Resolves promise if search permission is found
         * @private
         *
         * @param permissions {Array} Set of permission names
         * @param toParams {Object} UI-Router params object
         * @returns {promise} $q.promise object
         */
        function resolveIfMatch(permissions, toParams) {
          var deferred = $q.defer();

          findMatchingRole(permissions, toParams)
            .then(function () {
              deferred.resolve();
            })
            .catch(function () {
              deferred.reject();
            });

          return deferred.promise;
        }

        /**
         * Resolves promise if search permission is missing
         * @private
         *
         * @param permissions {Array} Set of permission names
         * @param toParams {Object} UI-Router params object
         * @returns {promise} $q.promise object
         */
        function rejectIfMatch(permissions, toParams) {
          var deferred = $q.defer();

          findMatchingRole(permissions, toParams)
            .then(function () {
              deferred.reject();
            })
            .catch(function () {
              deferred.resolve();
            });

          return deferred.promise;
        }

        var Permission = {
          /**
           * Allows to define permission in runtime
           * @deprecated
           *
           * @param permission {String} Name of defined permission
           * @param validationFunction {Function} Function used to validate if permission is valid
           */
          defineRole: function (permission, validationFunction) {
            console.warn('Function "defineRole" will be deprecated. Use "definePermission" instead');
            self.definePermission(permission, validationFunction);
            return Permission;
          },

          /**
           * Allows to define permission in runtime
           *
           * @param permission {String} Name of defined permission
           * @param validationFunction {Function} Function used to validate if permission is valid
           */
          definePermission: function (permission, validationFunction) {
            self.definePermission(permission, validationFunction);
            return Permission;
          },

          /**
           * Allows to define set of permissions with shared validation function in runtime
           * @deprecated
           *
           * @param permissions {Array} Set of permission names
           * @param validationFunction {Function} Function used to validate if permission is valid
           */
          defineManyRoles: function (permissions, validationFunction) {
            console.warn('Function "defineManyRoles" will be deprecated. Use "defineManyPermissions" instead');
            self.defineManyPermissions(permissions, validationFunction);
            return Permission;
          },

          /**
           * Allows to define set of permissions with shared validation function in runtime
           *
           * @param permissions {Array} Set of permission names
           * @param validationFunction {Function} Function used to validate if permission is valid
           */
          defineManyPermissions: function (permissions, validationFunction) {
            self.defineManyPermissions(permissions, validationFunction);
            return Permission;
          },

          /**
           * Deletes permission
           *
           * @param permission {String} Name of defined permission
           */
          removePermission: function (permission) {
            delete permissionStore[permission];
          },

          /**
           * Deletes set of permissions
           *
           * @param permissions {Array} Set of permission names
           */
          removeManyPermissions: function (permissions) {
            angular.forEach(permissions, function (permission) {
              delete permissionStore[permission];
            });
          },

          /**
           * Checks if permission exists
           *
           * @param permission {String} Name of defined permission
           * @returns {Boolean}
           */
          hasPermission: function (permission) {
            return angular.isDefined(permissionStore[permission]);
          },

          /**
           * Returns all permissions
           *
           * @returns {Object} Permissions collection
           */
          getPermissions: function () {
            return permissionStore;
          },

          /**
           * Removes all permissions
           */
          clearPermissions: function () {
            permissionStore = [];
          },

          /**
           * Checks if provided permissions are acceptable
           *
           * @param permissionsMap {Object} Map of "only" or "except" permission names
           * @param toParams {Object} UI-Router params object
           * @returns {promise} $q.promise object
           */
          authorize: function (permissionsMap, toParams) {
            var result;

            validatePermissionMap(permissionsMap);

            if (angular.isDefined(permissionsMap.only)) {
              result = resolveIfMatch(angular.copy(permissionsMap.only), toParams);
            } else {
              result = rejectIfMatch(angular.copy(permissionsMap.except), toParams);
            }

            return result;
          }
        };

        return Permission;
      }];
    });
})();<commit_msg>chore: smallfix<commit_after>(function () {
  'use strict';

  angular.module('permission')
    .provider('Permission', function () {
      var permissionStore = {};
      var self = this;

      /**
       * Allows to define permission on application configuration
       * @deprecated
       *
       * @param permission {String} Name of defined permission
       * @param validationFunction {Function} Function used to validate if permission is valid
       */
      this.defineRole = function (permission, validationFunction) {
        console.warn('Function "defineRole" will be deprecated. Use "definePermission" instead');
        self.definePermission(permission, validationFunction);
        return this;
      };

      /**
       * Allows to define permission on application configuration
       *
       * @param permission {String} Name of defined permission
       * @param validationFunction {Function} Function used to validate if permission is valid
       */
      this.definePermission = function (permission, validationFunction) {
        validatePermission(permission, validationFunction);
        permissionStore[permission] = validationFunction;
        return this;
      };

      /**
       * Allows to define set of permissions with shared validation function on application configuration
       *
       * @param permissions {Array} Set of permission names
       * @param validationFunction {Function} Function used to validate if permission is valid
       */
      this.defineManyPermissions = function (permissions, validationFunction) {
        if (!angular.isArray(permissions)) {
          throw new TypeError('Parameter "permissions" name must be Array');
        }

        angular.forEach(permissions, function (permissionName) {
          self.definePermission(permissionName, validationFunction);
        });

        return this;
      };

      /**
       * Checks if provided permission has accepted parameter types
       * @private
       *
       * @param permission {String} Name of defined permission
       * @param validationFunction {Function} Function used to validate if permission is valid
       */
      function validatePermission(permission, validationFunction) {
        if (!angular.isString(permission)) {
          throw new TypeError('Parameter "permission" name must be String');
        }
        if (!angular.isFunction(validationFunction)) {
          throw new TypeError('Parameter "validationFunction" must be Function');
        }
      }

      /**
       * Checks if provided permission map has accepted parameter types
       * @private
       *
       * @param permissionMap {Object}
       */
      function validatePermissionMap(permissionMap) {
        if (!angular.isObject(permissionMap)) {
          throw new TypeError('Parameter "permissionMap" has to be Object');
        }

        if (angular.isUndefined(permissionMap.only) && angular.isUndefined(permissionMap.except)) {
          throw new ReferenceError('Either "only" or "except" keys must me defined');
        }

        if (!(angular.isArray(permissionMap.only) || angular.isArray(permissionMap.except))) {
          throw new TypeError('Parameter "permissionMap" properties must be Array');
        }
      }

      this.$get = ['$q', function ($q) {

        /**
         * Converts a value into a promise, if the value is truthy it resolves it, otherwise it rejects it
         * @private
         *
         * @param func {Function} Function to be wrapped into promise
         * @return {promise} $q.promise object
         */
        function wrapInPromise(func) {
          var dfd = $q.defer();

          if (func) {
            dfd.resolve();
          } else {
            dfd.reject();
          }

          return dfd.promise;
        }

        /**
         * Performs iteration over list of defined permissions looking for matching roles
         * @private
         *
         * @param permissions {Array} Set of permission names
         * @param toParams {Object} UI-Router params object
         * @returns {promise} $q.promise object
         */
        function findMatchingRole(permissions, toParams) {
          var deferred = $q.defer();
          var currentPermission = permissions.shift();

          if (angular.isDefined(currentPermission) && angular.isFunction(permissionStore[currentPermission])) {
            var validationResult = permissionStore[currentPermission].call(self, toParams, currentPermission);

            if (!angular.isFunction(validationResult.then)) {
              validationResult = wrapInPromise(validationResult);
            }

            $q.when(validationResult)
              .then(function () {
                deferred.resolve();
              })
              .catch(function () {
                findMatchingRole(permissions, toParams)
                  .then(function () {
                    deferred.resolve();
                  })
                  .catch(function () {
                    deferred.reject();
                  });
              });
          } else {
            // If no roles left to validate reject promise
            deferred.reject();
          }

          return deferred.promise;
        }

        /**
         * Resolves promise if search permission is found
         * @private
         *
         * @param permissions {Array} Set of permission names
         * @param toParams {Object} UI-Router params object
         * @returns {promise} $q.promise object
         */
        function resolveIfMatch(permissions, toParams) {
          var deferred = $q.defer();

          findMatchingRole(permissions, toParams)
            .then(function () {
              deferred.resolve();
            })
            .catch(function () {
              deferred.reject();
            });

          return deferred.promise;
        }

        /**
         * Resolves promise if search permission is missing
         * @private
         *
         * @param permissions {Array} Set of permission names
         * @param toParams {Object} UI-Router params object
         * @returns {promise} $q.promise object
         */
        function rejectIfMatch(permissions, toParams) {
          var deferred = $q.defer();

          findMatchingRole(permissions, toParams)
            .then(function () {
              deferred.reject();
            })
            .catch(function () {
              deferred.resolve();
            });

          return deferred.promise;
        }

        var Permission = {
          /**
           * Allows to define permission in runtime
           * @deprecated
           *
           * @param permission {String} Name of defined permission
           * @param validationFunction {Function} Function used to validate if permission is valid
           */
          defineRole: function (permission, validationFunction) {
            console.warn('Function "defineRole" will be deprecated. Use "definePermission" instead');
            self.definePermission(permission, validationFunction);
            return Permission;
          },

          /**
           * Allows to define permission in runtime
           *
           * @param permission {String} Name of defined permission
           * @param validationFunction {Function} Function used to validate if permission is valid
           */
          definePermission: function (permission, validationFunction) {
            self.definePermission(permission, validationFunction);
            return Permission;
          },

          /**
           * Allows to define set of permissions with shared validation function in runtime
           * @deprecated
           *
           * @param permissions {Array} Set of permission names
           * @param validationFunction {Function} Function used to validate if permission is valid
           */
          defineManyRoles: function (permissions, validationFunction) {
            console.warn('Function "defineManyRoles" will be deprecated. Use "defineManyPermissions" instead');
            self.defineManyPermissions(permissions, validationFunction);
            return Permission;
          },

          /**
           * Allows to define set of permissions with shared validation function in runtime
           *
           * @param permissions {Array} Set of permission names
           * @param validationFunction {Function} Function used to validate if permission is valid
           */
          defineManyPermissions: function (permissions, validationFunction) {
            self.defineManyPermissions(permissions, validationFunction);
            return Permission;
          },

          /**
           * Deletes permission
           *
           * @param permission {String} Name of defined permission
           */
          removePermission: function (permission) {
            delete permissionStore[permission];
          },

          /**
           * Deletes set of permissions
           *
           * @param permissions {Array} Set of permission names
           */
          removeManyPermissions: function (permissions) {
            angular.forEach(permissions, function (permission) {
              delete permissionStore[permission];
            });
          },

          /**
           * Checks if permission exists
           *
           * @param permission {String} Name of defined permission
           * @returns {Boolean}
           */
          hasPermission: function (permission) {
            return angular.isDefined(permissionStore[permission]);
          },

          /**
           * Returns all permissions
           *
           * @returns {Object} Permissions collection
           */
          getPermissions: function () {
            return permissionStore;
          },

          /**
           * Removes all permissions
           */
          clearPermissions: function () {
            permissionStore = [];
          },

          /**
           * Checks if provided permissions are acceptable
           *
           * @param permissionsMap {Object} Map of "only" or "except" permission names
           * @param toParams {Object} UI-Router params object
           * @returns {promise} $q.promise object
           */
          authorize: function (permissionsMap, toParams) {
            var result;

            validatePermissionMap(permissionsMap);

            if (angular.isDefined(permissionsMap.only)) {
              result = resolveIfMatch(angular.copy(permissionsMap.only), toParams);
            } else {
              result = rejectIfMatch(angular.copy(permissionsMap.except), toParams);
            }

            return result;
          }
        };

        return Permission;
      }];
    });
})();<|endoftext|>


<commit_before>import {resolve} from "bluebird";

import * as config from "./services/config";
import log from "./services/logger";
import * as mongodb from "./services/mongodb";

export function findSiteBySensorId (sensorId) {
    return resolve(sensorId)
        .then(sensorId => mongodb.findOne({
            url: config.MONGODB_URL,
            collectionName: config.SITES,
            query: {
                sensorIds: {
                    $in: [sensorId]
                }
            }
        }));
}

function getSensor (measurements) {
    return {
        measurements: measurements.reduce((acc, measurement) => ({
            ...acc,
            [measurement.type]: measurement.value
        }), {}),
        lastUpdated: new Date().toISOString()
    };
}
export function updateReadingsRealTimeAggregate (site, element) {
    if (!site) {
        log.info("Site not found");
        return null;
    }
    log.info({site}, "Found site");
    const params = {
        url: config.MONGODB_URL,
        collectionName: config.READINGS_REAL_TIME_AGGREGATES,
        query: {
            _id: site._id,
            siteId: site._id
        },
        modifier: {
            $set: {
                [`sensors.${element.sensorId}`]: getSensor(element.measurements)
                // TODO update virtual sensors
            }
        }
    };
    log.info({params}, "Upserting");
    return mongodb.upsert(params);
}
<commit_msg>Fixed site-retrieving query<commit_after>import {resolve} from "bluebird";

import * as config from "./services/config";
import log from "./services/logger";
import * as mongodb from "./services/mongodb";

export function findSiteBySensorId (sensorId) {
    return resolve(sensorId)
        .then(sensorId => mongodb.findOne({
            url: config.MONGODB_URL,
            collectionName: config.SITES,
            query: {
                sensorsIds: {
                    $in: [sensorId]
                }
            }
        }));
}

function getSensor (measurements) {
    return {
        measurements: measurements.reduce((acc, measurement) => ({
            ...acc,
            [measurement.type]: measurement.value
        }), {}),
        lastUpdated: new Date().toISOString()
    };
}
export function updateReadingsRealTimeAggregate (site, element) {
    if (!site) {
        log.info("Site not found");
        return null;
    }
    log.info({site}, "Found site");
    const params = {
        url: config.MONGODB_URL,
        collectionName: config.READINGS_REAL_TIME_AGGREGATES,
        query: {
            _id: site._id,
            siteId: site._id
        },
        modifier: {
            $set: {
                [`sensors.${element.sensorId}`]: getSensor(element.measurements)
                // TODO update virtual sensors
            }
        }
    };
    log.info({params}, "Upserting");
    return mongodb.upsert(params);
}
<|endoftext|>


<commit_before>/* ------------------
 * java.lang.Object
 * ------------------ */

(function ($env) {
  function ObjectClass() {
  }
  ObjectClass.prototype.constructor = ObjectClass;

  ObjectClass.prototype["<init>():java.lang.Object"] = function() {
    return this;
  }

  ObjectClass.prototype["getClass():java.lang.Class"] = function() {
    return this.$classData.class;
  }

  ObjectClass.prototype["hashCode():scala.Int"] = function() {
    // TODO
    return 42;
  }

  ObjectClass.prototype["equals(java.lang.Object):scala.Boolean"] = function(rhs) {
    return this === rhs;
  }

  ObjectClass.prototype["clone():java.lang.Object"] = function() {
    if ($env.isInstance(this, "java.lang.Cloneable")) {
      throw new this.classes["scala.NotImplementedError"].type()[
        "<init>():scala.NotImplementedError"]();
    } else {
      throw new this.classes["java.lang.CloneNotSupportedException"].type()[
        "<init>():java.lang.CloneNotSupportedException"]();
    }
  }

  ObjectClass.prototype["toString():java.lang.String"] = function() {
    // getClass().getName() + "@" + Integer.toHexString(hashCode())
    var className = this["getClass():java.lang.Class"]()["getName():java.lang.String"]();
    var hashCode = this["hashCode():scala.Int"]();
    return className + '@' + hashCode.toString(16);
  }

  // Bridge for toString()
  ObjectClass.prototype.toString = function() {
    return this["toString():java.lang.String"]();
  }

  ObjectClass.prototype["notify():scala.Unit"] = function() {}
  ObjectClass.prototype["notifyAll():scala.Unit"] = function() {}
  ObjectClass.prototype["wait(scala.Long):scala.Unit"] = function() {}
  ObjectClass.prototype["wait(scala.Long,scala.Int):scala.Unit"] = function() {}
  ObjectClass.prototype["wait():scala.Unit"] = function() {}

  ObjectClass.prototype["finalize():scala.Unit"] = function() {}

  $env.createClass("java.lang.Object", ObjectClass, null, {
    "java.lang.Object": true
  });
})($ScalaJSEnvironment);
<commit_msg>Added JS bridges in java.lang.Object.<commit_after>/* ------------------
 * java.lang.Object
 * ------------------ */

(function ($env) {
  function ObjectClass() {
  }
  ObjectClass.prototype.constructor = ObjectClass;

  ObjectClass.prototype["<init>():java.lang.Object"] = function() {
    return this;
  }

  ObjectClass.prototype["getClass():java.lang.Class"] = function() {
    return this.$classData.class;
  }

  // Bridge for getClass()
  ObjectClass.prototype.getClass = function() {
    return this["getClass():java.lang.Class"]();
  }

  ObjectClass.prototype["hashCode():scala.Int"] = function() {
    // TODO
    return 42;
  }

  // Bridge for hashCode()
  ObjectClass.prototype.hashCode = function() {
    return this["hashCode():scala.Int"]();
  }

  ObjectClass.prototype["equals(java.lang.Object):scala.Boolean"] = function(rhs) {
    return this === rhs;
  }

  // Bridge for equals(Object)
  ObjectClass.prototype.equals = function(that) {
    return this["equals(java.lang.Object):scala.Boolean"](that);
  }

  ObjectClass.prototype["clone():java.lang.Object"] = function() {
    if ($env.isInstance(this, "java.lang.Cloneable")) {
      throw new this.classes["scala.NotImplementedError"].type()[
        "<init>():scala.NotImplementedError"]();
    } else {
      throw new this.classes["java.lang.CloneNotSupportedException"].type()[
        "<init>():java.lang.CloneNotSupportedException"]();
    }
  }

  // Bridge for clone()
  ObjectClass.prototype.clone = function() {
    return this["clone():java.lang.Object"]();
  }

  ObjectClass.prototype["toString():java.lang.String"] = function() {
    // getClass().getName() + "@" + Integer.toHexString(hashCode())
    var className = this["getClass():java.lang.Class"]()["getName():java.lang.String"]();
    var hashCode = this["hashCode():scala.Int"]();
    return className + '@' + hashCode.toString(16);
  }

  // Bridge for toString()
  ObjectClass.prototype.toString = function() {
    return this["toString():java.lang.String"]();
  }

  ObjectClass.prototype["notify():scala.Unit"] = function() {}
  ObjectClass.prototype["notifyAll():scala.Unit"] = function() {}
  ObjectClass.prototype["wait(scala.Long):scala.Unit"] = function() {}
  ObjectClass.prototype["wait(scala.Long,scala.Int):scala.Unit"] = function() {}
  ObjectClass.prototype["wait():scala.Unit"] = function() {}

  ObjectClass.prototype["finalize():scala.Unit"] = function() {}

  $env.createClass("java.lang.Object", ObjectClass, null, {
    "java.lang.Object": true
  });
})($ScalaJSEnvironment);
<|endoftext|>


<commit_before>var fs = require( 'fs' ),
    knox = require( 'knox' ),
    Path = require( 'path' );

// Make sure the dir exists, and its parent. Create if not.
function ensurePathExistsSync( path ) {
  var parent = Path.dirname( path );

  // Build paths above too, if not present. Check for relative or absolute paths
  if ( parent !== "." && parent !== "/" ) {
    ensurePathExistsSync( parent );
  }

  if ( !fs.existsSync( path ) ) {
    fs.mkdirSync( path );
  }
}

var BaseFileStore = {

  // By default, we use no prefix/suffix unless user-supplied.
  namePrefix: '',
  nameSuffix: '',

  // If we have a root directory, we need to work with the FS
  get requiresFileSystem() {
    return !!this.root;
  },

  // Expand a name to include the namePrefix
  expand: function( name ) {
    // Make sure name is a string, since non-strings are ignored by join
    name = name + '';
    return Path.join( this.namePrefix, name ) + this.nameSuffix;
  }
};

/**
 * LocalFileStore - stores data in local file system using root dir
 */
function LocalFileStore( options ) {
  // A root path for all filenames
  if( !options.root ) {
    throw 'LocalFileStore Error: expected root';
  }
  this.root = options.root;

  // An optional prefix for all filenames.  Will be joined with /
  // For example: filename=foo namePrefix=v becomes v/foo
  if( options.namePrefix ) {
    this.namePrefix = options.namePrefix;
  }
  ensurePathExistsSync( Path.join( this.root, this.namePrefix ) );

  // An optional suffix for all filenames.  Will be joined directly
  // For example: filename=foo nameSuffix=.html becomes foo.html
  if( options.nameSuffix ) {
    this.nameSuffix = options.nameSuffix;
  }

  // If embedHostname isn't appropriate, a hostname can be provided to override it.
  this.hostname = options.hostname;
}

LocalFileStore.prototype = Object.create( BaseFileStore );

LocalFileStore.prototype.write = function( path, data, callback ) {
  path = Path.join( this.root, this.expand( path ) );
  ensurePathExistsSync( Path.dirname( path ) );

  fs.writeFile( path, data, function( err ) {
    if (err) {
      callback( err );
    } else {
      callback();
    }
  });
};

LocalFileStore.prototype.remove = function( path, callback ) {
  callback = callback || function(){};
  path = Path.join( this.root, this.expand( path ) );
  fs.unlink( path, callback );
};

/**
 * S3FileStore - store data using Amazon S3
 */
function S3FileStore( options ) {
  // Amazon S3 credentials for accessing a bucket
  this.client = knox.createClient({
    key: options.key,
    secret: options.secret,
    bucket: options.bucket
  });

  // An optional prefix for all keys.  Will be joined with /
  // For example: key=foo namePrefix=v becomes v/foo
  if( options.namePrefix ) {
    this.namePrefix = options.namePrefix;
  }

  // An optional suffix for all filenames.  Will be joined directly
  // For example: filename=foo nameSuffix=.html becomes foo.html
  if( options.nameSuffix ) {
    this.nameSuffix = options.nameSuffix;
  }

  // An optional mime type for the files to be written.  Defaults to
  // text/plain if none given.
  this.contentType = options.contentType || 'text/plain';

  // If embedHostname isn't appropriate, a hostname can be provided to override it.
  this.hostname = options.hostname;

  // Append any additional headers to send with a write request
  if ( options.headers ) {
    this.headers = options.headers;
  }
}

S3FileStore.prototype = Object.create( BaseFileStore );

S3FileStore.prototype.write = function( key, data, callback ) {
  var headers = {
    'x-amz-acl': 'public-read',
    'Content-Length': data.length,
    'Content-Type': this.contentType
  };

  Object.keys( this.headers ).forEach(function( key ) {
    headers[ key ] = this.headers[ key ];
  });

  this.client.put( this.expand( key ), headers )
  .on( 'response', function( res ) {
    if( res.statusCode === 200 ) {
      callback();
    } else {
      callback( res.statusCode );
    }
  })
  .end( data );
};

S3FileStore.prototype.remove = function( key, callback ) {
  callback = callback || function(){};
  this.client.del( this.expand( key ) )
  .on( 'response', function( res ) {
    if( res.statusCode === 200 ) {
      callback();
    } else {
      callback( res.statusCode );
    }
  })
  .end();
};

var FileStores = {
  'S3': S3FileStore,
  'LOCAL': LocalFileStore
};

module.exports = {
  // Pass a type (one of 'local' or 's3') to build a FileStore object.
  create: function( type, options ) {
    options = options || {};

    var Constructor = FileStores[ type.toUpperCase() ];
    if( !Constructor ) {
      throw 'Unknown FileStore type: ' + type;
    }

    return new Constructor( options );
  }
};
<commit_msg>No Bug - Add default object for S3 headers<commit_after>var fs = require( 'fs' ),
    knox = require( 'knox' ),
    Path = require( 'path' );

// Make sure the dir exists, and its parent. Create if not.
function ensurePathExistsSync( path ) {
  var parent = Path.dirname( path );

  // Build paths above too, if not present. Check for relative or absolute paths
  if ( parent !== "." && parent !== "/" ) {
    ensurePathExistsSync( parent );
  }

  if ( !fs.existsSync( path ) ) {
    fs.mkdirSync( path );
  }
}

var BaseFileStore = {

  // By default, we use no prefix/suffix unless user-supplied.
  namePrefix: '',
  nameSuffix: '',

  // If we have a root directory, we need to work with the FS
  get requiresFileSystem() {
    return !!this.root;
  },

  // Expand a name to include the namePrefix
  expand: function( name ) {
    // Make sure name is a string, since non-strings are ignored by join
    name = name + '';
    return Path.join( this.namePrefix, name ) + this.nameSuffix;
  }
};

/**
 * LocalFileStore - stores data in local file system using root dir
 */
function LocalFileStore( options ) {
  // A root path for all filenames
  if( !options.root ) {
    throw 'LocalFileStore Error: expected root';
  }
  this.root = options.root;

  // An optional prefix for all filenames.  Will be joined with /
  // For example: filename=foo namePrefix=v becomes v/foo
  if( options.namePrefix ) {
    this.namePrefix = options.namePrefix;
  }
  ensurePathExistsSync( Path.join( this.root, this.namePrefix ) );

  // An optional suffix for all filenames.  Will be joined directly
  // For example: filename=foo nameSuffix=.html becomes foo.html
  if( options.nameSuffix ) {
    this.nameSuffix = options.nameSuffix;
  }

  // If embedHostname isn't appropriate, a hostname can be provided to override it.
  this.hostname = options.hostname;
}

LocalFileStore.prototype = Object.create( BaseFileStore );

LocalFileStore.prototype.write = function( path, data, callback ) {
  path = Path.join( this.root, this.expand( path ) );
  ensurePathExistsSync( Path.dirname( path ) );

  fs.writeFile( path, data, function( err ) {
    if (err) {
      callback( err );
    } else {
      callback();
    }
  });
};

LocalFileStore.prototype.remove = function( path, callback ) {
  callback = callback || function(){};
  path = Path.join( this.root, this.expand( path ) );
  fs.unlink( path, callback );
};

/**
 * S3FileStore - store data using Amazon S3
 */
function S3FileStore( options ) {
  // Amazon S3 credentials for accessing a bucket
  this.client = knox.createClient({
    key: options.key,
    secret: options.secret,
    bucket: options.bucket
  });

  // An optional prefix for all keys.  Will be joined with /
  // For example: key=foo namePrefix=v becomes v/foo
  if( options.namePrefix ) {
    this.namePrefix = options.namePrefix;
  }

  // An optional suffix for all filenames.  Will be joined directly
  // For example: filename=foo nameSuffix=.html becomes foo.html
  if( options.nameSuffix ) {
    this.nameSuffix = options.nameSuffix;
  }

  // An optional mime type for the files to be written.  Defaults to
  // text/plain if none given.
  this.contentType = options.contentType || 'text/plain';

  // If embedHostname isn't appropriate, a hostname can be provided to override it.
  this.hostname = options.hostname;

  // Append any additional headers to send with a write request
  this.headers = {};
  if ( options.headers ) {
    this.headers = options.headers;
  }
}

S3FileStore.prototype = Object.create( BaseFileStore );

S3FileStore.prototype.write = function( key, data, callback ) {
  var headers = {
    'x-amz-acl': 'public-read',
    'Content-Length': data.length,
    'Content-Type': this.contentType
  };

  Object.keys( this.headers ).forEach(function( key ) {
    headers[ key ] = this.headers[ key ];
  });

  this.client.put( this.expand( key ), headers )
  .on( 'response', function( res ) {
    if( res.statusCode === 200 ) {
      callback();
    } else {
      callback( res.statusCode );
    }
  })
  .end( data );
};

S3FileStore.prototype.remove = function( key, callback ) {
  callback = callback || function(){};
  this.client.del( this.expand( key ) )
  .on( 'response', function( res ) {
    if( res.statusCode === 200 ) {
      callback();
    } else {
      callback( res.statusCode );
    }
  })
  .end();
};

var FileStores = {
  'S3': S3FileStore,
  'LOCAL': LocalFileStore
};

module.exports = {
  // Pass a type (one of 'local' or 's3') to build a FileStore object.
  create: function( type, options ) {
    options = options || {};

    var Constructor = FileStores[ type.toUpperCase() ];
    if( !Constructor ) {
      throw 'Unknown FileStore type: ' + type;
    }

    return new Constructor( options );
  }
};
<|endoftext|>


<commit_before>var listFiles = require('./list')
var tail = require('keep-reading')
var split = require('line-stream')
var nameLog = require('./namelog')
var path = require('path')
var through2 = require('through2')
var parseSeq = nameLog.parseSeq
var bw = require('bytewise')

module.exports = function (opts) {
  opts = opts || {}

  var dir = opts.dir
  var suffix = opts.suffix || '.log'
  var position = parseSeq(opts.start || false)

  if (!opts.dir) throw new Error('dir required')

  // add sequence id.
  var out = through2.obj(function (chunk, enc, cb) {
    chunk.seq = position.file+'-'+bw.encode(chunk.start + chunk.length)
    cb(false, chunk)
  })

  var stream

  listFiles(dir, suffix, function (err, l) {
    if (err) return out.emit('error', err)
    out.list = l
    setup()
  })

  function setup () {
    var pos = validateSequence(out.list, position, suffix)

    // wait for any log files to appear
    if (!pos) {
      return setTimeout(function () {
        setup()
      }, 1000)
    }

    position = pos

    stream = streamFile(out, pos.path, pos.offset)
    stream.pipe(out, {end: false})
    handleStream(stream)
  }

  var ended = false
  function handleStream (stream) {
    if (ended) return stream.end()

    stream.on('waiting', function onWait (duration) {
      if (stream.listing) return

      if (duration <= 500) {
        // if the current list already has a next item use it
        if(haveMore()) checkList()
        // this causes a delay polling the directory for new log files.
        return
      }

      stream.listing = true
      listFiles(dir, suffix, function (e, l) {
        if (e) return out.emit('error', e)
        out.list = l

        checkList()

        stream.listing = false
      })

      function checkList(){
        // check to see if we should move to the next file.
        var current = out.list.order.indexOf(position.path)

        if (current < out.list.order.length - 1) {
          var next = out.list.order[current + 1]
          position = {offset: 0, path: next, file: path.basename(next, suffix)}
          stream.removeListener('waiting', onWait)
          stream.end()

          return setup()
        }
      }

      function haveMore(){
        return out.list.order.indexOf(position.path) < out.list.order.length-1
      }
    })

    stream.on('error', function (err) {
      ended = true
      out.emit('error', err)
    })
  }

  out.on('end', function () {
    ended = true
  })

  return out
}

module.exports.validateSequence = validateSequence

function validateSequence (list, sequence, suffix) {
  if (!list.order.length) return false

  for (var i = 0; i < list.order.length; ++i) {
    if (list.order[i] === sequence.path) {
      // found matching sequence file.
      return sequence
    } else if (sequence.path < list.order[i]) {
      // missing sequence log file. lets start on the next log file
      return {offset: 0, file: path.basename(list.order[i], suffix), path: list.order[i]}
    }
  }
  // start from beginning
  var first = list.order[0]
  return {offset: 0, file: path.basename(first, suffix), path: first}
}

function streamFile (out, file, start) {
  var s = split({start: start,delimiter:"\n"})
  var data = tail(file, start)

  data.on('error', function (err) {
    s.emit('error', err)
  })

  data.on('waiting', function (duration) {
    s.emit('waiting', duration)
  })

  data.pipe(s)

  return s
}
<commit_msg>fixing since / start<commit_after>var listFiles = require('./list')
var tail = require('keep-reading')
var split = require('line-stream')
var nameLog = require('./namelog')
var path = require('path')
var through2 = require('through2')
var parseSeq = nameLog.parseSeq
var bw = require('bytewise')

module.exports = function (opts) {
  opts = opts || {}

  var dir = opts.dir
  var suffix = opts.suffix || '.log'
  var position = parseSeq(opts.start || opts.since || false, dir, suffix)

  if (!opts.dir) throw new Error('dir required')

  // add sequence id.
  var out = through2.obj(function (chunk, enc, cb) {
    chunk.seq = position.file+'-'+bw.encode(chunk.start + chunk.length)
    cb(false, chunk)
  })

  var stream

  listFiles(dir, suffix, function (err, l) {
    if (err) return out.emit('error', err)
    out.list = l
    setup()
  })

  function setup () {
    var pos = validateSequence(out.list, position, suffix)

    // wait for any log files to appear
    if (!pos) {
      return setTimeout(function () {
        setup()
      }, 1000)
    }

    position = pos

    stream = streamFile(out, pos.path, pos.offset)
    stream.pipe(out, {end: false})
    handleStream(stream)
  }

  var ended = false
  function handleStream (stream) {
    if (ended) return stream.end()

    stream.on('waiting', function onWait (duration) {
      if (stream.listing) return

      if (duration <= 500) {
        // if the current list already has a next item use it
        if(haveMore()) checkList()
        // this causes a delay polling the directory for new log files.
        return
      }

      stream.listing = true
      listFiles(dir, suffix, function (e, l) {
        if (e) return out.emit('error', e)
        out.list = l

        checkList()

        stream.listing = false
      })

      function checkList(){
        // check to see if we should move to the next file.
        var current = out.list.order.indexOf(position.path)

        if (current < out.list.order.length - 1) {
          var next = out.list.order[current + 1]
          position = {offset: 0, path: next, file: path.basename(next, suffix)}
          stream.removeListener('waiting', onWait)
          stream.end()

          return setup()
        }
      }

      function haveMore(){
        return out.list.order.indexOf(position.path) < out.list.order.length-1
      }
    })

    stream.on('error', function (err) {
      ended = true
      out.emit('error', err)
    })
  }

  out.on('end', function () {
    ended = true

    // should end keep-reading stream!
    stream.end()
  })

  return out
}

module.exports.validateSequence = validateSequence

function validateSequence (list, sequence, suffix) {
  if (!list.order.length) return false

  for (var i = 0; i < list.order.length; ++i) {
    if (list.order[i] === sequence.path) {
      // found matching sequence file.
      return sequence
    } else if (sequence.path < list.order[i]) {
      // missing sequence log file. lets start on the next log file
      return {offset: 0, file: path.basename(list.order[i], suffix), path: list.order[i]}
    }
  }
  // start from beginning
  var first = list.order[0]
  return {offset: 0, file: path.basename(first, suffix), path: first}
}

function streamFile (out, file, start) {
  var s = split({start: start,delimiter:"\n"})
  var data = tail(file, start)

  data.on('error', function (err) {
    s.emit('error', err)
  })

  data.on('waiting', function (duration) {
    s.emit('waiting', duration)
  })

  data.pipe(s)

  return s
}
<|endoftext|>


<commit_before>import R from 'ramda';
import React from 'react';

const NavLink = ({item, getTitle, setItem, count}) => (
  {getTitle(item)} {count ? <CountBadge count={count} /> : undefined}
);

const NavStages = ({stages, currentStage, getStageTitle, setStage}) => (

      Stage: {getStageTitle(currentStage)}

      { R.map(x => (

          <NavLink item={x.stageIndex} getTitle={getStageTitle} setItem={setStage} />

        ), stages)
      }

);

const NavTypes = ({types, focusSource, focusResult, currentType, getType, setType}) => {
  const getTypeTitle = x => getType(x).title;
  const getValueCount = x => getType(x).values.length;
  const LocalNavLink = ({index}) => (<NavLink item={index} getTitle={getTypeTitle} setItem={setType} count={getValueCount(index)} />);
  return (

        View: {getType(currentType).title}

        { R.flatten(
            [ !R.isNil(focusResult) ?
              ( [
Focus Result

                ,
<LocalNavLink index={focusResult} />

                ]
              ) :
              [],
            , !R.isNil(focusSource) && focusSource !== focusResult ?
              ( [
Focus Source

                ,
<LocalNavLink index={focusSource} />

                ]
              ) :
              [],
            , !R.isNil(maybe(focusResult, focusSource)) ?
              ( [

 ] ) :
              [],
            , R.map(x => (
<LocalNavLink index={x} />
), types)
            ]
          )
        }

  );
};

const NavGroups = ({groups, currentType, currentGroup, getGroupTitle, setGroup}) => (

      Group By: {getGroupTitle(currentGroup)}

      { R.map(x => (

          <NavLink item={x} getTitle={getGroupTitle} setItem={setGroup} />

        ), groups)
      }

);

const Nav = ({getType, getGroupTitle, stages, types, groups, currentStage, currentType, currentGroup, focusResult, focusSource, setStage, setType, setGroup}) => {
  const getTypeTitle = typeIndex => getType(typeIndex).title
  const getStageTitle = stageIndex => getTypeTitle(stages[stageIndex].topLevelType);
  return (

        <NavStages
          stages={stages}
          currentStage={currentStage}
          getStageTitle={getStageTitle}
          setStage={setStage} />

        <NavTypes
          types={types}
          currentType={currentType}
          focusResult={focusResult}
          focusSource={focusSource}
          getType={getType}
          setType={setType} />

        <NavGroups
          groups={groups}
          currentType={currentType}
          currentGroup={currentGroup}
          getGroupTitle={getGroupTitle}
          setGroup={setGroup} />

    );
};

const CountBadge = ({count}) => ({count});

const Content = ({values, currentGroupIndex, getValueTitle}) => {
  const elementId = 'accordion';
  return (

      { R.map(item =>
        {
          const itemIndex = item.index;
          const headingId = 'heading' + itemIndex;
          const collapseId = 'collapse' + itemIndex;
          const count = item.values.length;
          return (

                    {getValueTitle(itemIndex)} {count !== 1 ? <CountBadge count={count} /> : undefined}

                  { R.map(x =>
{x.title}
, item.values) }

);
        }, values)
      }

);
};

function doGroup(groupByFunc) {
  return R.compose(
    R.last,
    R.mapAccum((i, x) => [i + 1, { index: i, key: x.key, values: x.values } ], 0),
    xs => R.map(x => ({ key: x, values: xs[x] }), R.keys(xs)),
    R.groupBy(groupByFunc)
  );
}

function maybe(...args) {
  return R.compose(R.head, R.dropWhile(R.isNil))(args);
}

function maybeProp(prop, obj) {
  return R.isNil(obj) ? undefined : R.prop(prop, obj);
}

export class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      currentStage: props.stage,
      currentType: props.type,
      currentGroup: props.group
    };
  }
  setStage(stageIndex, event) {
    this.setState({
      currentStage: stageIndex
    });
  }
  setType(typeIndex, event) {
    this.setState({
      currentType: typeIndex
    });
  }
  setGroup(groupIndex, event) {
    this.setState({
      currentGroup: groupIndex
    });
  }
  render() {
    const noneTitle = 'None';

    const getType = x => this.props.data.types[x];
    const getGroupTitle = x => x === undefined ? noneTitle : getType(x).title;

    const currentStageIndex = maybe(this.state.currentStage, 0);
    const currentStage = this.props.data.stages[currentStageIndex];

    const focusResult = currentStage.focusResultType;
    const focusSource = currentStage.focusSourceType;
    const stageTypes = R.filter(x => x !== focusResult && x !== focusSource, currentStage.allTypes);
    const currentTypeIndex = this.state.currentType && R.contains(this.state.currentType, stageTypes) ?
      this.state.currentType :
      maybe(focusResult, focusSource, stageTypes[0]);
    const currentType = getType(currentTypeIndex);

    const typeGroups = R.concat([undefined], currentType.propertyTypes);
    const currentGroupIndex = this.state.currentGroup && R.contains(this.state.currentGroup, typeGroups) ? this.state.currentGroup : undefined;

    const groupByFunc = currentGroupIndex === undefined ? x => x.valueIndex : (x => maybe(x.propertyValues[currentGroupIndex], 'none'));
    const groupTypeIndex = maybe(currentGroupIndex, currentTypeIndex);
    const groupType = getType(groupTypeIndex);
    const getValueTitle = x => maybe(maybeProp('title', groupType.values[x]), noneTitle);
    const values = doGroup(groupByFunc)(currentType.values);

    return (

        <Nav
          getType={getType}
          getGroupTitle={getGroupTitle}

          stages={this.props.data.stages}
          types={stageTypes}
          groups={typeGroups}

          currentStage={currentStageIndex}
          currentType={currentTypeIndex}
          currentGroup={currentGroupIndex}

          focusSource={focusSource}
          focusResult={focusResult}

          setStage={this.setStage.bind(this)}
          setType={this.setType.bind(this)}
          setGroup={this.setGroup.bind(this)}
        />

        <Content
          values={values}
          getValueTitle={getValueTitle}
        />

);
  }
}
<commit_msg>Rename maybe to oneOf and remove use of group index.<commit_after>import R from 'ramda';
import React from 'react';

const NavLink = ({item, getTitle, setItem, count}) => (
  {getTitle(item)} {count ? <CountBadge count={count} /> : undefined}
);

const NavStages = ({stages, currentStage, getStageTitle, setStage}) => (

      Stage: {getStageTitle(currentStage)}

      { R.map(x => (

          <NavLink item={x.stageIndex} getTitle={getStageTitle} setItem={setStage} />

        ), stages)
      }

);

const NavTypes = ({types, focusSource, focusResult, currentType, getType, setType}) => {
  const getTypeTitle = x => getType(x).title;
  const getValueCount = x => getType(x).values.length;
  const LocalNavLink = ({index}) => (<NavLink item={index} getTitle={getTypeTitle} setItem={setType} count={getValueCount(index)} />);
  return (

        View: {getType(currentType).title}

        { R.flatten(
            [ !R.isNil(focusResult) ?
              ( [
Focus Result

                ,
<LocalNavLink index={focusResult} />

                ]
              ) :
              [],
            , !R.isNil(focusSource) && focusSource !== focusResult ?
              ( [
Focus Source

                ,
<LocalNavLink index={focusSource} />

                ]
              ) :
              [],
            , !R.isNil(oneOf(focusResult, focusSource)) ?
              ( [

 ] ) :
              [],
            , R.map(x => (
<LocalNavLink index={x} />
), types)
            ]
          )
        }

  );
};

const NavGroups = ({groups, currentType, currentGroup, getGroupTitle, setGroup}) => (

      Group By: {getGroupTitle(currentGroup)}

      { R.map(x => (

          <NavLink item={x} getTitle={getGroupTitle} setItem={setGroup} />

        ), groups)
      }

);

const Nav = ({getType, getGroupTitle, stages, types, groups, currentStage, currentType, currentGroup, focusResult, focusSource, setStage, setType, setGroup}) => {
  const getTypeTitle = typeIndex => getType(typeIndex).title
  const getStageTitle = stageIndex => getTypeTitle(stages[stageIndex].topLevelType);
  return (

        <NavStages
          stages={stages}
          currentStage={currentStage}
          getStageTitle={getStageTitle}
          setStage={setStage} />

        <NavTypes
          types={types}
          currentType={currentType}
          focusResult={focusResult}
          focusSource={focusSource}
          getType={getType}
          setType={setType} />

        <NavGroups
          groups={groups}
          currentType={currentType}
          currentGroup={currentGroup}
          getGroupTitle={getGroupTitle}
          setGroup={setGroup} />

    );
};

const CountBadge = ({count}) => ({count});

const Content = ({values, currentGroupIndex, getValueTitle}) => {
  const elementId = 'accordion';
  return (

      { R.map(item =>
        {
          const itemKey = item.key;
          const headingId = 'heading' + itemKey;
          const collapseId = 'collapse' + itemKey;
          const count = item.values.length;
          return (

                    {getValueTitle(itemKey)} {count !== 1 ? <CountBadge count={count} /> : undefined}

                  { R.map(x =>
{x.title}
, item.values) }

);
        }, values)
      }

);
};

function doGroup(groupByFunc) {
  return R.compose(
    xs => R.map(x => ({ key: x, values: xs[x] }), R.keys(xs)),
    R.groupBy(groupByFunc)
  );
}

function oneOf(...args) {
  return R.compose(R.head, R.dropWhile(R.isNil))(args);
}

function maybeProp(prop, obj) {
  return R.isNil(obj) ? undefined : R.prop(prop, obj);
}

export class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      currentStage: props.stage,
      currentType: props.type,
      currentGroup: props.group
    };
  }
  setStage(stageIndex, event) {
    this.setState({
      currentStage: stageIndex
    });
  }
  setType(typeIndex, event) {
    this.setState({
      currentType: typeIndex
    });
  }
  setGroup(groupIndex, event) {
    this.setState({
      currentGroup: groupIndex
    });
  }
  render() {
    const noneTitle = 'None';

    const getType = x => this.props.data.types[x];
    const getGroupTitle = x => x === undefined ? noneTitle : getType(x).title;

    const currentStageIndex = oneOf(this.state.currentStage, 0);
    const currentStage = this.props.data.stages[currentStageIndex];

    const focusResult = currentStage.focusResultType;
    const focusSource = currentStage.focusSourceType;
    const stageTypes = R.filter(x => x !== focusResult && x !== focusSource, currentStage.allTypes);
    const currentTypeIndex = this.state.currentType && R.contains(this.state.currentType, stageTypes) ?
      this.state.currentType :
      oneOf(focusResult, focusSource, stageTypes[0]);
    const currentType = getType(currentTypeIndex);

    const typeGroups = R.concat([undefined], currentType.propertyTypes);
    const currentGroupIndex = this.state.currentGroup && R.contains(this.state.currentGroup, typeGroups) ? this.state.currentGroup : undefined;

    const groupByFunc = currentGroupIndex === undefined ? x => x.valueIndex : (x => oneOf(x.propertyValues[currentGroupIndex], 'none'));
    const groupTypeIndex = oneOf(currentGroupIndex, currentTypeIndex);
    const groupType = getType(groupTypeIndex);
    const getValueTitle = x => oneOf(maybeProp('title', groupType.values[x]), noneTitle);
    const values = doGroup(groupByFunc)(currentType.values);

    return (

        <Nav
          getType={getType}
          getGroupTitle={getGroupTitle}

          stages={this.props.data.stages}
          types={stageTypes}
          groups={typeGroups}

          currentStage={currentStageIndex}
          currentType={currentTypeIndex}
          currentGroup={currentGroupIndex}

          focusSource={focusSource}
          focusResult={focusResult}

          setStage={this.setStage.bind(this)}
          setType={this.setType.bind(this)}
          setGroup={this.setGroup.bind(this)}
        />

        <Content
          values={values}
          getValueTitle={getValueTitle}
        />

);
  }
}
<|endoftext|>


<commit_before>Reports = new Mongo.Collection('reports');

numReports = function(line, dir, category) {
  var query = {
    line: line,
    expired: false
  };

  if (dir) {
    query.dir = dir;
  }

  if (category) {
    var names = allReportTypes.filter(function(report) {
      return report.category === category;
    }).map(function(report) {
      return report.name;
    });
    query.name = {$in: names};
  }

  return Reports.find(query).count();
};

Meteor.methods({
  saveReport: function (name, location, line, dir) {

    if (Meteor.isServer) {
      var rushHours = [7, 8, 16, 17];
      var currentUTCHour = (new Date()).getUTCHours();
      var query = {
        '_id': { $ne: this.userId },
        'profile.push-new-enabled': true
      };

      // if it's not rush hour, push to users how didn't select rush-hours-only
      if (rushHours.indexOf(currentUTCHour + 2) == -1) {
        query['profile.push-new-rushhours'] = { $ne: true };
      }

      var userIds = Meteor.users.find(
        query, { fields: { _id: 1 } }).map(
          function(user) { return user._id; });

      Push.send({
        from: 'push',
        title: line + ' ' + location,
        text: name,
        // send to all users for now
        query: {
          userId: {
            $in: userIds
          }
        }
      });
    }

    return Reports.insert({
      name: name,
      location: location,
      line: line,
      dir: dir,
      thanks: [],
      confirms: [],
      clears: [],
      createdAt: new Date(),
      createdBy: this.userId,
      expired: false,
      removed: false,
      weight: initialWeight
    });
  },
  thankReport: function(docId) {
    Reports.update(docId, {$addToSet: {thanks: this.userId}});
  },
  upvoteReport: function(docId) {
    // Cap weight to maxWeight
    var doc = Reports.findOne({_id: docId});
    Reports.update(docId, {
      $addToSet: {confirms: this.userId},
      $set: {weight: Math.min(doc.weight + upvoteWeight, maxWeight)}
    });
  },
  downvoteReport: function(docId) {
    Reports.update(docId, {
      $addToSet: {clears: this.userId},
      $inc: {weight: downvoteWeight}
    });
  },
  removeReport: function(docId) {
    Reports.update(docId, {
      $set: {
        expired: true,
        removed: true
      }
    });
  }
});
<commit_msg>weekends are not rush hours<commit_after>Reports = new Mongo.Collection('reports');

numReports = function(line, dir, category) {
  var query = {
    line: line,
    expired: false
  };

  if (dir) {
    query.dir = dir;
  }

  if (category) {
    var names = allReportTypes.filter(function(report) {
      return report.category === category;
    }).map(function(report) {
      return report.name;
    });
    query.name = {$in: names};
  }

  return Reports.find(query).count();
};

function isRushHour(date) {
  var rushDays = [1, 2, 3, 4, 5];
  var rushHours = [7, 8, 16, 17];

  if (rushDays.indexOf(date.getUTCDay()) === -1) {
    return false;
  }

  return rushHours.indexOf(date.getUTCHours + 2) > -1;
}

Meteor.methods({
  saveReport: function (name, location, line, dir) {

    if (Meteor.isServer) {
      var query = {
        '_id': { $ne: this.userId },
        'profile.push-new-enabled': true
      };

      // if it's not rush hour, exclude users who selected rush-hours-only
      if (!isRushHour(new Date())) {
        query['profile.push-new-rushhours'] = { $ne: true };
      }

      var userIds = Meteor.users.find(
        query, { fields: { _id: 1 } }).map(
          function(user) { return user._id; });

      Push.send({
        from: 'push',
        title: line + ' ' + location,
        text: name,
        // send to all users for now
        query: {
          userId: {
            $in: userIds
          }
        }
      });
    }

    return Reports.insert({
      name: name,
      location: location,
      line: line,
      dir: dir,
      thanks: [],
      confirms: [],
      clears: [],
      createdAt: new Date(),
      createdBy: this.userId,
      expired: false,
      removed: false,
      weight: initialWeight
    });
  },
  thankReport: function(docId) {
    Reports.update(docId, {$addToSet: {thanks: this.userId}});
  },
  upvoteReport: function(docId) {
    // Cap weight to maxWeight
    var doc = Reports.findOne({_id: docId});
    Reports.update(docId, {
      $addToSet: {confirms: this.userId},
      $set: {weight: Math.min(doc.weight + upvoteWeight, maxWeight)}
    });
  },
  downvoteReport: function(docId) {
    Reports.update(docId, {
      $addToSet: {clears: this.userId},
      $inc: {weight: downvoteWeight}
    });
  },
  removeReport: function(docId) {
    Reports.update(docId, {
      $set: {
        expired: true,
        removed: true
      }
    });
  }
});
<|endoftext|>


<commit_before><commit_msg>reveal.js update<commit_after><|endoftext|>


<commit_before>var config = require('./config'),
  passport = require('passport'),
  page = require('./database').load_model('page');

var defaultRoute = function(req, res){

  var styles = ['/media/bootstrap/css/bootstrap.min.css'];

  page.findPage(req.url, function (found_page) {
    if (found_page) {
      res.render('layout.hbs', {title: page.title, content: page.body, user: req.user, styles: styles});
    } else {
      res.status(404).render('layout.hbs', {title: 'ERROR', body: 'Not Found', styles: styles});
    }
  });

};

var adminRoute = function  (req, res) {
  var scripts = [
    '/media/js/jquery-1.7.2.min.js',
    '/media/bootstrap/js/bootstrap.min.js',
    '/media/bootstrap/js/bootstrap-dropdown.js'
    ];
  var styles = ['/media/bootstrap/css/bootstrap.min.css'];

  res.render('admin.hbs', {title: 'Admin', scripts: scripts, styles: styles, user: req.user});
};

var createPageRoute = function (req, res) {

};

var addRoutes = function(server) {

  server.post(config.get('login_route'), passport.authenticate('local', {
    successRedirect: "/",
    failureRedirect: "/",
    falshFailure: true
  }));

  server.get(config.get('logout_route'), function  (req, res) {
    req.logOut();
    res.redirect('/');
  });

  server.get(config.get('admin_route'), adminRoute);

  server.get('/*', defaultRoute);

  server.post('/*', createPageRoute);
};

module.exports.addRoutes = addRoutes;
module.exports.defaultRoute = defaultRoute;
module.exports.adminRoute = adminRoute;<commit_msg>Fixed page rendering<commit_after>var config = require('./config'),
  passport = require('passport'),
  page = require('./database').load_model('page');

var defaultRoute = function(req, res){

  var styles = ['/media/bootstrap/css/bootstrap.min.css'];

  page.findPage(req.url, function (found_page) {
    if (found_page) {
      res.render('layout.hbs', {title: found_page.title, content: found_page.body, user: req.user, styles: styles});
    } else {
      res.status(404).render('layout.hbs', {title: 'ERROR', body: 'Not Found', styles: styles});
    }
  });

};

var adminRoute = function  (req, res) {
  var scripts = [
    '/media/js/jquery-1.7.2.min.js',
    '/media/bootstrap/js/bootstrap.min.js',
    '/media/bootstrap/js/bootstrap-dropdown.js'
    ];
  var styles = ['/media/bootstrap/css/bootstrap.min.css'];

  res.render('admin.hbs', {title: 'Admin', scripts: scripts, styles: styles, user: req.user});
};

var createPageRoute = function (req, res) {

};

var addRoutes = function(server) {

  server.post(config.get('login_route'), passport.authenticate('local', {
    successRedirect: "/",
    failureRedirect: "/",
    falshFailure: true
  }));

  server.get(config.get('logout_route'), function  (req, res) {
    req.logOut();
    res.redirect('/');
  });

  server.get(config.get('admin_route'), adminRoute);

  server.get('/*', defaultRoute);

  server.post('/*', createPageRoute);
};

module.exports.addRoutes = addRoutes;
module.exports.defaultRoute = defaultRoute;
module.exports.adminRoute = adminRoute;<|endoftext|>


<commit_before>/*jslint continue: true, nomen: true, plusplus: true, regexp: true, vars: true, white: true, passfail: false, indent: 2 */
(function(jQuery, window, document) {
  var _rollbarParams = {
    "notifier.plugins.jquery.version": '0.0.1'
  };
  window._rollbar.push({_rollbarParams: _rollbarParams});

  // Report any ajax errors to Rollbar
  jQuery(document).ajaxError(function(event, jqXHR, ajaxSettings, thrownError) {
    var status = jqXHR.status;
    var url = ajaxSettings.url;

    window._rollbar.push({
      level: 'warning',
      msg: 'jQuery ajax error for url ' + url,
      jquery_status: status,
      jquery_url: url,
      jquery_thrown_error: thrownError,
      jquery_ajax_error: true
    });
  });

  // Wraps functions passed into jQuery's ready() with try/catch to
  // report errors to Rollbar
  var origReady = jQuery.fn.ready;
  jQuery.fn.ready = function(fn) {
    return origReady.call(this, function() {
      try {
        fn();
      } catch (e) {
        window._rollbar.push(e);
      }
    });
  };

  // Keeps track of a mapping of original function to wrapped function
  // when used with jQuery's on() and off() event handling
  var onFuncs = {};

  // Wraps functions (if any) passed into jQuery's on() with try/catch
  // to report errors to Rollbar
  var origOn = jQuery.fn.on;
  jQuery.fn.on = function(events, selector, data, fn) {
    var wrap = function(fn) {
      var newFunc = function() {
        try {
          return fn.apply(this, arguments);
        } catch (e) {
          window._rollbar.push(e);
          return null;
        }
      }

      onFuncs[fn] = newFunc;
      return newFunc;
    }

    if (selector && typeof selector === 'function') {
      selector = wrap(selector);
    } else if (data && typeof data === 'function') {
      data = wrap(data);
    } else if (fn && typeof fn === 'function') {
      fn = wrap(fn);
    }

    return origOn.call(this, events, selector, data, fn);
  };

  // Replaces any passed in functions with the Rollbar-wrapped version
  // created above in on(), deletes the mapping, and passes the resulting
  // function into jQuery's off() to remove the event handling
  var origOff = jQuery.fn.off;
  jQuery.fn.off = function(events, selector, fn) {
    if (selector && typeof selector === 'function') {
      selector = onFuncs[selector];
      delete onFuncs[selector];
    } else {
      fn = onFuncs[fn];
      delete onFuncs[fn];
    }

    return origOff.call(this, events, selector, fn);
  };
})(jQuery, window, document);
<commit_msg>Only load the jQuery plugin if `_rollbar` is available<commit_after>/*jslint continue: true, nomen: true, plusplus: true, regexp: true, vars: true, white: true, passfail: false, indent: 2 */
(function(jQuery, window, document) {

  if (!window._rolllbar) {
    return;
  }

  var _rollbarParams = {
    "notifier.plugins.jquery.version": '0.0.1'
  };
  window._rollbar.push({_rollbarParams: _rollbarParams});

  // Report any ajax errors to Rollbar
  jQuery(document).ajaxError(function(event, jqXHR, ajaxSettings, thrownError) {
    var status = jqXHR.status;
    var url = ajaxSettings.url;

    window._rollbar.push({
      level: 'warning',
      msg: 'jQuery ajax error for url ' + url,
      jquery_status: status,
      jquery_url: url,
      jquery_thrown_error: thrownError,
      jquery_ajax_error: true
    });
  });

  // Wraps functions passed into jQuery's ready() with try/catch to
  // report errors to Rollbar
  var origReady = jQuery.fn.ready;
  jQuery.fn.ready = function(fn) {
    return origReady.call(this, function() {
      try {
        fn();
      } catch (e) {
        window._rollbar.push(e);
      }
    });
  };

  // Keeps track of a mapping of original function to wrapped function
  // when used with jQuery's on() and off() event handling
  var onFuncs = {};

  // Wraps functions (if any) passed into jQuery's on() with try/catch
  // to report errors to Rollbar
  var origOn = jQuery.fn.on;
  jQuery.fn.on = function(events, selector, data, fn) {
    var wrap = function(fn) {
      var newFunc = function() {
        try {
          return fn.apply(this, arguments);
        } catch (e) {
          window._rollbar.push(e);
          return null;
        }
      }

      onFuncs[fn] = newFunc;
      return newFunc;
    }

    if (selector && typeof selector === 'function') {
      selector = wrap(selector);
    } else if (data && typeof data === 'function') {
      data = wrap(data);
    } else if (fn && typeof fn === 'function') {
      fn = wrap(fn);
    }

    return origOn.call(this, events, selector, data, fn);
  };

  // Replaces any passed in functions with the Rollbar-wrapped version
  // created above in on(), deletes the mapping, and passes the resulting
  // function into jQuery's off() to remove the event handling
  var origOff = jQuery.fn.off;
  jQuery.fn.off = function(events, selector, fn) {
    if (selector && typeof selector === 'function') {
      selector = onFuncs[selector];
      delete onFuncs[selector];
    } else {
      fn = onFuncs[fn];
      delete onFuncs[fn];
    }

    return origOff.call(this, events, selector, fn);
  };
})(jQuery, window, document);
<|endoftext|>


<commit_before>const ripple    = require('ripple-lib');
const express   = require('express');
const api       = require('./../api');
const remote    = require('./remote.js');
const serverLib = require('./server-lib.js');
const respond   = require('./response-handler.js');
const errors    = require('./errors.js');
const utils     = require('./utils.js');

var router = new express.Router();
router.remote = remote;

/* validate the correctness of ripple address params */
router.param('account', function(req, res, next, address) {
  if (ripple.UInt160.is_valid(address)) {
    next();
  } else {
    next(new errors.InvalidRequestError('Parameter is not a valid Ripple address: account'));
  }
});

router.param('destination_account', function(req, res, next, address) {
  if (ripple.UInt160.is_valid(address)) {
    next();
  } else {
    next(new errors.InvalidRequestError('Parameter is not a valid Ripple address: destination_account'));
  }
});

router.generateIndexPage = function(req, res) {
  var url_base = '/v' + utils.getApiVersion();

  res.json({
    success: true,
    name: 'ripple-rest',
    package_version: utils.getPackageVersion(),
    version: utils.getApiVersion(),
    documentation: 'https://github.com/ripple/ripple-rest',
    endpoints: {
      wallet_new: url_base + '/wallet/new',
      payment_paths: url_base + '/accounts/{address}/payments/paths/{destination_account}/{destination_amount as value+currency or value+currency+issuer}',
      payment_submit: url_base + '/accounts/{address}/payments',
      account_payments: url_base + '/accounts/{address}/payments/{hash,client_resource_id}{?direction,exclude_failed}',
      account_notifications: url_base + '/accounts/{address}/notifications/{hash,client_resource_id}',
      account_balances: url_base + '/accounts/{address}/balances',
      account_settings: url_base + '/accounts/{address}/settings',
      account_trustlines: url_base + '/accounts/{address}/trustlines',
      ripple_transactions: url_base + '/transactions/{hash}',
      server_status: url_base + '/server',
      server_connected: url_base + '/server/connected',
      transaction_fee: url_base + '/transaction-fee',
      uuid_generator: url_base + '/uuid'
    }
  });
};

router.get('/', router.generateIndexPage);

/* uuid util */
router.get('/uuid', api.info.uuid);

/**
 * For all the routes below, we need a connected rippled
 * insert the validateRemoteConnected middleware here
 */

/* make sure the remote is connected to a rippled */
router.all('*', function(req, res, next) {
  serverLib.ensureConnected(remote, function(error, connected) {
    if (connected) {
      next();
    } else {
      next(new errors.RippledNetworkError(error ? error.message : void(0)));
    }
  });
});

/* Connected - if we hit this route, it means the server is connected */
router.get('/server/connected', api.info.isConnected);

/* Transaction fee */
router.get('/transaction-fee', api.info.fee);

/* Server */
router.get('/server', api.info.serverStatus);

/* Wallet */
router.get('/wallet/new', api.wallet.generate);

/* Payments */
router.post('/accounts/:account/payments', api.payments.submit);
router.get('/accounts/:account/payments', api.payments.getAccountPayments);
router.get('/accounts/:account/payments/:identifier', api.payments.get);
router.get('/accounts/:account/payments/paths/:destination_account/:destination_amount_string', api.payments.getPathFind);

/* Orders */
router.post('/accounts/:account/orders', api.orders.placeOrder);
router.delete('/accounts/:account/orders/:sequence', api.orders.cancelOrder);

/* Notifications */
router.get('/accounts/:account/notifications', api.notifications.getNotification);
router.get('/accounts/:account/notifications/:identifier', api.notifications.getNotification);

/* Balances */
router.get('/accounts/:account/balances', api.balances.get);

/* Settings */
router.get('/accounts/:account/settings', api.settings.get);
router.post('/accounts/:account/settings', api.settings.change);

/* Standard Ripple Transactions */
router.get('/transactions/:identifier', api.transactions.get);

/* Trustlines */
router.get('/accounts/:account/trustlines', api.trustlines.get);
router.post('/accounts/:account/trustlines', api.trustlines.add);

module.exports = router;
<commit_msg>[Task] Orders: Add paths to index page<commit_after>const ripple    = require('ripple-lib');
const express   = require('express');
const api       = require('./../api');
const remote    = require('./remote.js');
const serverLib = require('./server-lib.js');
const respond   = require('./response-handler.js');
const errors    = require('./errors.js');
const utils     = require('./utils.js');

var router = new express.Router();
router.remote = remote;

/* validate the correctness of ripple address params */
router.param('account', function(req, res, next, address) {
  if (ripple.UInt160.is_valid(address)) {
    next();
  } else {
    next(new errors.InvalidRequestError('Parameter is not a valid Ripple address: account'));
  }
});

router.param('destination_account', function(req, res, next, address) {
  if (ripple.UInt160.is_valid(address)) {
    next();
  } else {
    next(new errors.InvalidRequestError('Parameter is not a valid Ripple address: destination_account'));
  }
});

router.generateIndexPage = function(req, res) {
  var url_base = '/v' + utils.getApiVersion();

  res.json({
    success: true,
    name: 'ripple-rest',
    package_version: utils.getPackageVersion(),
    version: utils.getApiVersion(),
    documentation: 'https://github.com/ripple/ripple-rest',
    endpoints: {
      wallet_new: url_base + '/wallet/new',
      payment_paths: url_base + '/accounts/{address}/payments/paths/{destination_account}/{destination_amount as value+currency or value+currency+issuer}',
      payment_submit: url_base + '/accounts/{address}/payments',
      account_payments: url_base + '/accounts/{address}/payments/{hash,client_resource_id}{?direction,exclude_failed}',
      account_notifications: url_base + '/accounts/{address}/notifications/{hash,client_resource_id}',
      account_balances: url_base + '/accounts/{address}/balances',
      account_settings: url_base + '/accounts/{address}/settings',
      account_trustlines: url_base + '/accounts/{address}/trustlines',
      account_orders_place: url_base + '/accounts/{address}/orders',
      account_orders_cancel: url_base + '/accounts/{address}/orders/{sequence}',
      ripple_transactions: url_base + '/transactions/{hash}',
      server_status: url_base + '/server',
      server_connected: url_base + '/server/connected',
      transaction_fee: url_base + '/transaction-fee',
      uuid_generator: url_base + '/uuid'
    }
  });
};

router.get('/', router.generateIndexPage);

/* uuid util */
router.get('/uuid', api.info.uuid);

/**
 * For all the routes below, we need a connected rippled
 * insert the validateRemoteConnected middleware here
 */

/* make sure the remote is connected to a rippled */
router.all('*', function(req, res, next) {
  serverLib.ensureConnected(remote, function(error, connected) {
    if (connected) {
      next();
    } else {
      next(new errors.RippledNetworkError(error ? error.message : void(0)));
    }
  });
});

/* Connected - if we hit this route, it means the server is connected */
router.get('/server/connected', api.info.isConnected);

/* Transaction fee */
router.get('/transaction-fee', api.info.fee);

/* Server */
router.get('/server', api.info.serverStatus);

/* Wallet */
router.get('/wallet/new', api.wallet.generate);

/* Payments */
router.post('/accounts/:account/payments', api.payments.submit);
router.get('/accounts/:account/payments', api.payments.getAccountPayments);
router.get('/accounts/:account/payments/:identifier', api.payments.get);
router.get('/accounts/:account/payments/paths/:destination_account/:destination_amount_string', api.payments.getPathFind);

/* Orders */
router.post('/accounts/:account/orders', api.orders.placeOrder);
router.delete('/accounts/:account/orders/:sequence', api.orders.cancelOrder);

/* Notifications */
router.get('/accounts/:account/notifications', api.notifications.getNotification);
router.get('/accounts/:account/notifications/:identifier', api.notifications.getNotification);

/* Balances */
router.get('/accounts/:account/balances', api.balances.get);

/* Settings */
router.get('/accounts/:account/settings', api.settings.get);
router.post('/accounts/:account/settings', api.settings.change);

/* Standard Ripple Transactions */
router.get('/transactions/:identifier', api.transactions.get);

/* Trustlines */
router.get('/accounts/:account/trustlines', api.trustlines.get);
router.post('/accounts/:account/trustlines', api.trustlines.add);

module.exports = router;
<|endoftext|>


<commit_before>import {
  YAHOO_SEARCH_EXISTING_USERS,
  YAHOO_SEARCH_NEW_USERS,
} from './experimentConstants'

const features = {
  'money-raised-exclamation-point': {
    defaultValue: false,
    rules: [
      /* Begin internal overrides */
      {
        condition: {
          v4BetaEnabled: true,
          'internalExperimentOverrides.money-raised-exclamation-point': true,
        },
        // Using variations instead of "force" also ensures other experiment
        // logic, such as logging the experiment assignment, is working
        // correctly.
        variations: [true, false],
        weights: [1.0, 0.0],
      },
      {
        condition: {
          v4BetaEnabled: true,
          'internalExperimentOverrides.money-raised-exclamation-point': false,
        },
        variations: [true, false],
        weights: [0.0, 1.0],
      },
      /* End internal overrides */
      {
        variations: [false, true],
        coverage: 0.4,
        condition: {
          v4BetaEnabled: true,
        },
      },
    ],
  },
}

features[YAHOO_SEARCH_EXISTING_USERS] = {
  defaultValue: false,
  // Enable when SFAC search engine is enabled.
  // rules: [
  //   {
  //     condition: {
  //       isTabTeamMember: true,
  //       env: 'local',
  //     },
  //     force: true,
  //   },
  // ],
}

features[YAHOO_SEARCH_NEW_USERS] = {
  defaultValue: 'Google',
  // Enable when SFAC search engine is enabled.
  // rules: [
  //   {
  //     condition: {
  //       isTabTeamMember: true,
  //       env: 'local',
  //     },
  //     force: 'SearchForACause',
  //   },
  // ],
}

export default features
<commit_msg>Launch a new test experiment<commit_after>import {
  YAHOO_SEARCH_EXISTING_USERS,
  YAHOO_SEARCH_NEW_USERS,
} from './experimentConstants'

const features = {
  'money-raised-exclamation-point-v2': {
    defaultValue: false,
    rules: [
      /* Begin internal overrides */
      {
        condition: {
          v4BetaEnabled: true,
          'internalExperimentOverrides.money-raised-exclamation-point-v2': true,
        },
        force: true,
      },
      {
        condition: {
          v4BetaEnabled: true,
          'internalExperimentOverrides.money-raised-exclamation-point-v2': false,
        },
        force: false,
      },
      /* End internal overrides */
      {
        variations: [false, true],
        weights: [0.5, 0.5],
        coverage: 0.4,
        condition: {
          v4BetaEnabled: true,
        },
      },
    ],
  },
}

features[YAHOO_SEARCH_EXISTING_USERS] = {
  defaultValue: false,
  // Enable when SFAC search engine is enabled.
  // rules: [
  //   {
  //     condition: {
  //       isTabTeamMember: true,
  //       env: 'local',
  //     },
  //     force: true,
  //   },
  // ],
}

features[YAHOO_SEARCH_NEW_USERS] = {
  defaultValue: 'Google',
  // Enable when SFAC search engine is enabled.
  // rules: [
  //   {
  //     condition: {
  //       isTabTeamMember: true,
  //       env: 'local',
  //     },
  //     force: 'SearchForACause',
  //   },
  // ],
}

export default features
<|endoftext|>


<commit_before><commit_msg>add basic router<commit_after>var Router = module.exports = exports = function() {
  this.routes = {
    'GET': {},
    'POST': {},
    'PUT': {},
    'PATCH': {},
    'DELETE': {}
  };
}

Router.prototype.get = function(route, callback) {
  this.routes['GET'][route] = callback;
};

Router.prototype.post = function(route, callback) {
  this.routes['POST'][route] = callback;
};

Router.prototype.put = function(route, callback) {
  this.routes['PUT'][route] = callback;
};

Router.prototype.patch = function(route, callback) {
  this.routes['PATCH'][route] = callback;
};

Router.prototype.delete = function(route, callback) {
  this.routes['DELETE'][route] = callback;
};

Router.prototype.fourOhFour = function(req, res) {
  res.writeHead(404, {
    'Content-Type': 'text/plain'
  });
  res.write('not found');
  res.end();
};

Router.prototype.route = function(req, res) {
  (this.routes[req.method][req.url] || this.fourOhFour)(req, res);
  res.end();
}
<|endoftext|>