<commit_before>// Karma configuration
// Generated on Tue Feb 02 2015 14:46:14 GMT+0000 (GMT Standard Time)

module.exports = function(config) {
  config.set({
    basePath: '',
    frameworks: ['jasmine'],
    files: [
      'example_tests/**/*.spec.js'
    ],
    exclude: [
    ],
    reporters: ['nicer'],
    niceReporter : {
      successMsg: 'yay',
      failureMsg: 'nay',
    },
    proxies : {
    },
    port: 9876,
    colors: true,
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_ERROR,
    autoWatch: false,
    browsers: ['PhantomJS'],
    singleRun: true,
    concurrency: Infinity
  });
};
<commit_msg>Added options to karma.conf.js<commit_after>// Karma configuration
// Generated on Tue Feb 02 2015 14:46:14 GMT+0000 (GMT Standard Time)

module.exports = function(config) {
  config.set({
    basePath: '',
    frameworks: ['jasmine'],
    files: [
      'example_tests/**/*.spec.js'
    ],
    exclude: [
    ],
    reporters: ['nicer'],
    /*
    nicerReporter settings (optional) here showing the default colors.
    Uses chalk (https://github.com/chalk/chalk)
    available colors: black  red  green  yellow  blue  magenta  cyan  white  gray
    */
    nicerReporter : {
      defaulColor: 'cyan',
      successColor: 'green',
      failColor: 'red',
      skipColor: 'yellow',
      errorLogColor: 'white'
    },
    proxies : {
    },
    port: 9876,
    colors: true,
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_ERROR,
    autoWatch: false,
    browsers: ['PhantomJS'],
    singleRun: true,
    concurrency: Infinity
  });
};
<|endoftext|>


<commit_before>/* jshint node: true */

module.exports = function(environment) {
  var ENV = {
    modulePrefix: 'flowerpot',
    environment: environment,
    contentSecurityPolicy: { 'connect-src': "'self' https://auth.firebase.com wss://*.firebaseio.com" },
    firebase: {
      apiKey: process.env.FIREBASE_API_KEY,
      authDomain:  process.env.FIREBASE_APP_NAME + ".firebaseapp.com",
      databaseURL: "https://" + process.env.FIREBASE_APP_NAME + ".firebaseio.com",
      storageBucket:  process.env.FIREBASE_APP_NAME + ".appspot.com",
    },
    torii: {
      sessionServiceName: 'session'
    },
    baseURL: '/',
    locationType: 'auto',
    EmberENV: {
      FEATURES: {
        // Here you can enable experimental features on an ember canary build
        // e.g. 'with-controller': true
      }
    },

    APP: {},

    featureFlags: {
      'show-index': true,
      'use-firebase': false,
      // Here you can pass flags/options to your application instance
      // when it is created
    }
  };

  if (environment === 'development') {
    // ENV.APP.LOG_RESOLVER = true;
    // ENV.APP.LOG_ACTIVE_GENERATION = true;
    // ENV.APP.LOG_TRANSITIONS = true;
    // ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
    // ENV.APP.LOG_VIEW_LOOKUPS = true;
  }

  if (environment === 'test') {
    // Testem prefers this...
    ENV.baseURL = '/';
    ENV.locationType = 'none';

    // keep test console output quieter
    ENV.APP.LOG_ACTIVE_GENERATION = false;
    ENV.APP.LOG_VIEW_LOOKUPS = false;

    ENV.APP.rootElement = '#ember-testing';
    ENV.featureFlags['show-index'] = false;
    ENV.featureFlags['use-firebase'] = false;
  }

  if (environment === 'production') {
    ENV.featureFlags['show-index'] = true;
    ENV.featureFlags['use-firebase'] = true;
  }

  return ENV;
};
<commit_msg>only set up firebase if the feature flag is enabled<commit_after>/* jshint node: true */

module.exports = function(environment) {
  var ENV = {
    modulePrefix: 'flowerpot',
    environment: environment,
    contentSecurityPolicy: { 'connect-src': "'self' https://auth.firebase.com wss://*.firebaseio.com" },
    torii: {
      sessionServiceName: 'session'
    },
    baseURL: '/',
    locationType: 'auto',
    EmberENV: {
      FEATURES: {
        // Here you can enable experimental features on an ember canary build
        // e.g. 'with-controller': true
      }
    },

    APP: {},

    featureFlags: {
      'show-index': true,
      'use-firebase': false,
      // Here you can pass flags/options to your application instance
      // when it is created
    }
  };

  if (environment === 'development') {
    // ENV.APP.LOG_RESOLVER = true;
    // ENV.APP.LOG_ACTIVE_GENERATION = true;
    // ENV.APP.LOG_TRANSITIONS = true;
    // ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
    // ENV.APP.LOG_VIEW_LOOKUPS = true;
  }

  if (environment === 'test') {
    // Testem prefers this...
    ENV.baseURL = '/';
    ENV.locationType = 'none';

    // keep test console output quieter
    ENV.APP.LOG_ACTIVE_GENERATION = false;
    ENV.APP.LOG_VIEW_LOOKUPS = false;

    ENV.APP.rootElement = '#ember-testing';
    ENV.featureFlags['show-index'] = false;
    ENV.featureFlags['use-firebase'] = false;
  }

  if (environment === 'production') {
    ENV.featureFlags['show-index'] = true;
    ENV.featureFlags['use-firebase'] = true;
  }

  if (ENV.featureFlags['use-firebase']) {
    ENV.firebase = {
      apiKey: process.env.FIREBASE_API_KEY,
      authDomain:  process.env.FIREBASE_APP_NAME + ".firebaseapp.com",
      databaseURL: "https://" + process.env.FIREBASE_APP_NAME + ".firebaseio.com",
      storageBucket:  process.env.FIREBASE_APP_NAME + ".appspot.com",
    };
  }

  return ENV;
};
<|endoftext|>


<commit_before>/*
* Application list is the entry point for the application management.
*/
define(function (require) {
  'use strict';

  var states = require('states');
  var modules = require('modules');
  var angular = require('angular');
  var alienUtils = require('scripts/utils/alien_utils');
  var _ = require('lodash');

  require('scripts/layout/resource_layout');

  require('scripts/_ref/applications/controllers/applications_detail_users');
  require('scripts/_ref/applications/controllers/applications_detail_versions');
  require('scripts/_ref/applications/controllers/applications_detail_environments');

  require('scripts/_ref/applications/controllers/applications_detail_environment');
  require('scripts/_ref/applications/controllers/applications_detail_version');

  require('scripts/_ref/applications/services/application_environments_manager_factory');

  require('scripts/applications/services/application_services');
  require('scripts/applications/services/application_version_services');

  require('scripts/_ref/common/directives/tags');
  require('scripts/_ref/common/filters/highlight');
  require('scripts/_ref/common/directives/breadcrumbs');
  require('scripts/_ref/common/services/breadcrumbs_service');

  require('scripts/common/services/user_context_services');
  require('scripts/meta-props/directives/meta_props_display');

  states.state('applications.detail', {
    url: '/detail/:id',
    templateUrl: 'views/_ref/applications/applications_detail.html',
    controller: 'ApplicationDetailCtrl',
    resolve: {
      application: ['applicationServices', '$stateParams',
        function(applicationServices, $stateParams) {
          return _.catch(function() {
            return applicationServices.get({
              applicationId: $stateParams.id
            }).$promise;
          });
        }
      ],
      applicationEnvironmentsManager: ['application', 'applicationEnvironmentsManagerFactory',
        function(applicationResponse, applicationEnvironmentsManagerFactory) {
          return _.catch(function() {
            return applicationEnvironmentsManagerFactory(applicationResponse.data);
          });
        }
      ],
      archiveVersions: ['$http', 'application', 'applicationVersionServices',
        function($http, application, applicationVersionServices) {
          return _.catch(function() {
            var searchAppVersionRequestObject = {
              'from': 0,
              'size': 400
            };
            return applicationVersionServices.searchVersion({
              delegateId: application.data.id
            }, angular.toJson(searchAppVersionRequestObject)).$promise.then(function(result) {
              return result.data;
            });
          });
        }
      ]
    },
    params: {
      // optional id of the environment to automatically select when triggering this state
      openOnEnvironment: null
    }
  });

  modules.get('a4c-applications').controller('ApplicationDetailCtrl',['$scope','application', 'breadcrumbsService','$state',
    function($scope, application, breadcrumbsService, $state) {
      breadcrumbsService.putConfig({
        state : 'applications.detail',
        text: function(){
          return application.data.name;
        },
        onClick: function(){
          $state.go('applications.detail', { id: application.data.id });
        }
      });
  }]);

  states.state('applications.detail.info', {
    url: '/infos',
    templateUrl: 'views/_ref/applications/applications_detail_info.html',
    controller: 'ApplicationInfoCtrl'
  });
  states.forward('applications.detail', 'applications.detail.info');

  modules.get('a4c-applications').controller('ApplicationInfoCtrl',
    ['$controller', '$scope', '$state', '$translate', 'toaster', 'Upload', 'menu', 'resourceLayoutService', 'authService', 'applicationServices', 'application', 'applicationEnvironmentsManager', 'archiveVersions',
    function ($controller, $scope, $state, $translate, toaster, $upload, menu, resourceLayoutService, authService, applicationServices, applicationResponse, applicationEnvironmentsManager, versionsResponse) {
      $scope.application = applicationResponse.data;

      $scope.versions = versionsResponse.data;

      if(!$scope.application.tags) {
        $scope.application.tags = {};
      }
      $scope.environments = applicationEnvironmentsManager.environments;
      $scope.statusCss = alienUtils.getStatusIconCss;

      // Add the resource layout controller to the scope (mixin)
      $controller('ResourceLayoutCtrl', {$scope: $scope, menu: menu, resourceLayoutService: resourceLayoutService, resource: $scope.application});

      // Application rights
      $scope.isManager = authService.hasResourceRole($scope.application, 'APPLICATION_MANAGER');

      $scope.$on('$destroy', function() {
        // We must stop all event registrations
        applicationEnvironmentsManager.stopEvents();
      });

      $scope.onEnvironment = function (environmentId) {
        $state.go('applications.detail.environment', {
          environmentId: environmentId
        });
      };

      $scope.onVersion = function (versionId) {
        $state.go('applications.detail.version', {
          versionId: versionId
        });
      };

      $scope.removeApplication = function(applicationId) {
        applicationServices.remove({
          applicationId: applicationId
        }, function(response) {
          if (!response.error && response.data === true) {
            $state.go('applications.list');
          } else {
            // toaster message
            toaster.pop('error', $translate.instant('APPLICATIONS.ERRORS.DELETE_TITLE'), $translate.instant('APPLICATIONS.ERRORS.DELETING_FAILED'), 4000, 'trustedHtml', null);
          }
        });
      };

      $scope.updateApplication = function(fieldName, fieldValue) {
        var applicationUpdateRequest = {};
        if(_.undefined(fieldValue)) {
          fieldValue = '';
        }
        applicationUpdateRequest[fieldName] = fieldValue;
        return applicationServices.update({
          applicationId: $scope.application.id
        }, angular.toJson(applicationUpdateRequest), undefined).$promise.then(
          function() { // Success
            // reload the current application info page after update
            $state.go($state.current, {}, {reload: true});
          },
          function(errorResponse) { // Error
            return $translate.instant('ERRORS.' + errorResponse.data.error.code);
          }
        );
      };

      // Image upload
      $scope.doUpload = function(file) {
        $upload.upload({
          url: 'rest/latest/applications/' + $scope.application.id + '/image',
          file: file
        }).success(function(result) {
          $scope.application.imageId = result.data;
        });
      };
      $scope.onImageSelected = function($files) {
        var file = $files[0];
        $scope.doUpload(file);
      };
    }
  ]);
});
<commit_msg>Work in progress on variant version to prepare for sorting.<commit_after>/*
* Application list is the entry point for the application management.
*/
define(function (require) {
  'use strict';

  var states = require('states');
  var modules = require('modules');
  var angular = require('angular');
  var alienUtils = require('scripts/utils/alien_utils');
  var _ = require('lodash');

  require('scripts/layout/resource_layout');

  require('scripts/_ref/applications/controllers/applications_detail_users');
  require('scripts/_ref/applications/controllers/applications_detail_versions');
  require('scripts/_ref/applications/controllers/applications_detail_environments');

  require('scripts/_ref/applications/controllers/applications_detail_environment');
  require('scripts/_ref/applications/controllers/applications_detail_version');

  require('scripts/_ref/applications/services/application_environments_manager_factory');

  require('scripts/applications/services/application_services');
  require('scripts/applications/services/application_version_services');

  require('scripts/_ref/common/directives/tags');
  require('scripts/_ref/common/filters/highlight');
  require('scripts/_ref/common/directives/breadcrumbs');
  require('scripts/_ref/common/services/breadcrumbs_service');

  require('scripts/common/services/user_context_services');
  require('scripts/meta-props/directives/meta_props_display');

  states.state('applications.detail', {
    url: '/detail/:id',
    templateUrl: 'views/_ref/applications/applications_detail.html',
    controller: 'ApplicationDetailCtrl',
    resolve: {
      application: ['applicationServices', '$stateParams',
        function(applicationServices, $stateParams) {
          return _.catch(function() {
            return applicationServices.get({
              applicationId: $stateParams.id
            }).$promise;
          });
        }
      ],
      applicationEnvironmentsManager: ['application', 'applicationEnvironmentsManagerFactory',
        function(applicationResponse, applicationEnvironmentsManagerFactory) {
          return _.catch(function() {
            return applicationEnvironmentsManagerFactory(applicationResponse.data);
          });
        }
      ],
      archiveVersions: ['$http', 'application', 'applicationVersionServices',
        function($http, application, applicationVersionServices) {
          return _.catch(function() {
            var searchAppVersionRequestObject = {
              'from': 0,
              'size': 400
            };
            return applicationVersionServices.searchVersion({
              delegateId: application.data.id
            }, angular.toJson(searchAppVersionRequestObject)).$promise.then(function(result) {
              _.each(result.data.data, function(version) {
                _.each(version.topologyVersion, function(variant, variantKey) {
                  variant.version = variantKey;
                });
              });
              return result.data;
            });
          });
        }
      ]
    },
    params: {
      // optional id of the environment to automatically select when triggering this state
      openOnEnvironment: null
    }
  });

  modules.get('a4c-applications').controller('ApplicationDetailCtrl',['$scope','application', 'breadcrumbsService','$state',
    function($scope, application, breadcrumbsService, $state) {
      breadcrumbsService.putConfig({
        state : 'applications.detail',
        text: function(){
          return application.data.name;
        },
        onClick: function(){
          $state.go('applications.detail', { id: application.data.id });
        }
      });
  }]);

  states.state('applications.detail.info', {
    url: '/infos',
    templateUrl: 'views/_ref/applications/applications_detail_info.html',
    controller: 'ApplicationInfoCtrl'
  });
  states.forward('applications.detail', 'applications.detail.info');

  modules.get('a4c-applications').controller('ApplicationInfoCtrl',
    ['$controller', '$scope', '$state', '$translate', 'toaster', 'Upload', 'menu', 'resourceLayoutService', 'authService', 'applicationServices', 'application', 'applicationEnvironmentsManager', 'archiveVersions',
    function ($controller, $scope, $state, $translate, toaster, $upload, menu, resourceLayoutService, authService, applicationServices, applicationResponse, applicationEnvironmentsManager, versionsResponse) {
      $scope.application = applicationResponse.data;

      $scope.versions = versionsResponse.data;

      if(!$scope.application.tags) {
        $scope.application.tags = {};
      }
      $scope.environments = applicationEnvironmentsManager.environments;
      $scope.statusCss = alienUtils.getStatusIconCss;

      // Add the resource layout controller to the scope (mixin)
      $controller('ResourceLayoutCtrl', {$scope: $scope, menu: menu, resourceLayoutService: resourceLayoutService, resource: $scope.application});

      // Application rights
      $scope.isManager = authService.hasResourceRole($scope.application, 'APPLICATION_MANAGER');

      $scope.$on('$destroy', function() {
        // We must stop all event registrations
        applicationEnvironmentsManager.stopEvents();
      });

      $scope.onEnvironment = function (environmentId) {
        $state.go('applications.detail.environment', {
          environmentId: environmentId
        });
      };

      $scope.onVersion = function (versionId) {
        $state.go('applications.detail.version', {
          versionId: versionId
        });
      };

      $scope.removeApplication = function(applicationId) {
        applicationServices.remove({
          applicationId: applicationId
        }, function(response) {
          if (!response.error && response.data === true) {
            $state.go('applications.list');
          } else {
            // toaster message
            toaster.pop('error', $translate.instant('APPLICATIONS.ERRORS.DELETE_TITLE'), $translate.instant('APPLICATIONS.ERRORS.DELETING_FAILED'), 4000, 'trustedHtml', null);
          }
        });
      };

      $scope.updateApplication = function(fieldName, fieldValue) {
        var applicationUpdateRequest = {};
        if(_.undefined(fieldValue)) {
          fieldValue = '';
        }
        applicationUpdateRequest[fieldName] = fieldValue;
        return applicationServices.update({
          applicationId: $scope.application.id
        }, angular.toJson(applicationUpdateRequest), undefined).$promise.then(
          function() { // Success
            // reload the current application info page after update
            $state.go($state.current, {}, {reload: true});
          },
          function(errorResponse) { // Error
            return $translate.instant('ERRORS.' + errorResponse.data.error.code);
          }
        );
      };

      // Image upload
      $scope.doUpload = function(file) {
        $upload.upload({
          url: 'rest/latest/applications/' + $scope.application.id + '/image',
          file: file
        }).success(function(result) {
          $scope.application.imageId = result.data;
        });
      };
      $scope.onImageSelected = function($files) {
        var file = $files[0];
        $scope.doUpload(file);
      };
    }
  ]);
});
<|endoftext|>


<commit_before><commit_msg>plugins: jsAPI: nodeJsPlugin: read http server port from arguments<commit_after><|endoftext|>


<commit_before>var config = require('../config')
if(!config.tasks.js) return

var path            = require('path')
var pathToUrl       = require('./pathToUrl')
var webpack         = require('webpack')
var webpackManifest = require('./webpackManifest')

module.exports = function(env) {
  var jsSrc = path.resolve(config.root.src, config.tasks.js.src)
  var jsDest = path.resolve(config.root.dest, config.tasks.js.dest)
  var publicPath = pathToUrl(config.tasks.js.dest, '/')

  var extensions = config.tasks.js.extensions.map(function(extension) {
    return '.' + extension
  })

  var rev = config.tasks.production.rev && env === 'production'
  var filenamePattern = rev ? '[name]-[hash].js' : '[name].js'

  var webpackConfig = {
    context: jsSrc,
    plugins: [
      new webpack.ProvidePlugin({
        '$': 'jquery',
        'jQuery': 'jquery',
        'window.jquery': 'jquery'
      })
    ],

    resolve: {
      modules: [
        jsSrc,
        'node_modules',
        'modules'
      ],
      enforceExtension: false
    },

    module: {
      rules: [{
        test: /\.js$/,
        exclude: [/node_modules/],
        use: [{
          loader: 'babel-loader',
          options: { presets: ['es2015', 'stage-1'] }
        }],
      }]
    }
  }

  if(env === 'development') {
    webpackConfig.devtool = 'inline-source-map'

    // Create new entries object with webpack-hot-middleware added
    for (var key in config.tasks.js.entries) {
      var entry = config.tasks.js.entries[key]
      config.tasks.js.entries[key] = ['webpack-hot-middleware/client?&reload=true'].concat(entry)
    }

    webpackConfig.plugins.push(new webpack.HotModuleReplacementPlugin())
  }

  if(env !== 'test') {
    // Karma doesn't need entry points or output settings
    webpackConfig.entry = config.tasks.js.entries

    webpackConfig.output= {
      path: path.normalize(jsDest),
      filename: filenamePattern,
      publicPath: publicPath
    }

    if(config.tasks.js.extractSharedJs) {
      // Factor out common dependencies into a shared.js
      webpackConfig.plugins.push(
        new webpack.optimize.CommonsChunkPlugin({
          name: 'shared',
          filename: filenamePattern,
        })
      )
    }
  }

  if(env === 'production') {
    if(rev) {
      webpackConfig.plugins.push(new webpackManifest(publicPath, config.root.dest))
    }
    webpackConfig.plugins.push(
      new webpack.DefinePlugin({
        'process.env': {
          'NODE_ENV': JSON.stringify('production')
        }
      }),
      new webpack.optimize.UglifyJsPlugin(),
      new webpack.NoEmitOnErrorsPlugin()
    )
  }

  return webpackConfig
}
<commit_msg>Re-format BabelLoader config<commit_after>var config = require('../config')
if(!config.tasks.js) return

var path            = require('path')
var pathToUrl       = require('./pathToUrl')
var webpack         = require('webpack')
var webpackManifest = require('./webpackManifest')

module.exports = function(env) {
  var jsSrc = path.resolve(config.root.src, config.tasks.js.src)
  var jsDest = path.resolve(config.root.dest, config.tasks.js.dest)
  var publicPath = pathToUrl(config.tasks.js.dest, '/')

  var extensions = config.tasks.js.extensions.map(function(extension) {
    return '.' + extension
  })

  var rev = config.tasks.production.rev && env === 'production'
  var filenamePattern = rev ? '[name]-[hash].js' : '[name].js'

  var webpackConfig = {
    context: jsSrc,
    plugins: [
      new webpack.ProvidePlugin({
        '$': 'jquery',
        'jQuery': 'jquery',
        'window.jquery': 'jquery'
      })
    ],

    resolve: {
      modules: [
        jsSrc,
        'node_modules',
        'modules'
      ],
      enforceExtension: false
    },

    module: {
      rules: [{
        test: /\.js$/,
        exclude: [/node_modules/],
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['es2015', 'stage-1']
          }
        },
      }]
    }
  }

  if(env === 'development') {
    webpackConfig.devtool = 'inline-source-map'

    // Create new entries object with webpack-hot-middleware added
    for (var key in config.tasks.js.entries) {
      var entry = config.tasks.js.entries[key]
      config.tasks.js.entries[key] = ['webpack-hot-middleware/client?&reload=true'].concat(entry)
    }

    webpackConfig.plugins.push(new webpack.HotModuleReplacementPlugin())
  }

  if(env !== 'test') {
    // Karma doesn't need entry points or output settings
    webpackConfig.entry = config.tasks.js.entries

    webpackConfig.output= {
      path: path.normalize(jsDest),
      filename: filenamePattern,
      publicPath: publicPath
    }

    if(config.tasks.js.extractSharedJs) {
      // Factor out common dependencies into a shared.js
      webpackConfig.plugins.push(
        new webpack.optimize.CommonsChunkPlugin({
          name: 'shared',
          filename: filenamePattern,
        })
      )
    }
  }

  if(env === 'production') {
    if(rev) {
      webpackConfig.plugins.push(new webpackManifest(publicPath, config.root.dest))
    }
    webpackConfig.plugins.push(
      new webpack.DefinePlugin({
        'process.env': {
          'NODE_ENV': JSON.stringify('production')
        }
      }),
      new webpack.optimize.UglifyJsPlugin(),
      new webpack.NoEmitOnErrorsPlugin()
    )
  }

  return webpackConfig
}
<|endoftext|>


<commit_before>'use strict'

export class Cursor {

  constructor () {
    this._size = 14
    this._timeout = 400
    this._initTransition = `all ${this._timeout}ms ease-in-out`
    this._position = {
      x: 0,
      y: 0
    }

    this._point = window.document.getElementById('mocha-extjs-testing-tool-pointer')

    if (!this._point) {
      this._point = document.createElement('div')

      this._point.id = 'mocha-extjs-testing-tool-pointer'
      this._point.style.top = `${this._position.y}px`
      this._point.style.left = `${this._position.x}px`
      this._point.style.width = `${this._size}px`
      this._point.style.zIndex = '90000'
      this._point.style.height = `${this._size}px`
      this._point.style.border = '2px solid #ffffff'
      this._point.style.opacity = '1'
      this._point.style.position = 'absolute'
      this._point.style.transition = this._initTransition
      this._point.style.borderRadius = `0 ${this._size / 2}px ${this._size / 2}px ${this._size / 2}px`
      this._point.style.backgroundColor = '#ee3300'

      window.document.body.appendChild(this._point)
    }
  }

  moveTo (x, y, callback) {
    const translate = `translate(${x}px, ${y}px)`

    this._point.style.transform = translate

    setTimeout(() => {
      this._point.style.transition = 'all 50ms ease-in-out'
      this._point.style.transform = `${translate} scale(0.5)`
      setTimeout(() => {
        this._point.style.transform = `${translate} scale(1)`
        setTimeout(() => {
          this._point.style.transition = this._initTransition
          return callback(null)
        }, 50)
      }, 50)
    }, this._timeout)
  }

  hide () {
    this._point.style.display = 'none'
  }

  show () {
    this._point.style.display = 'block'
  }

}
<commit_msg>Move cursove on phantomjs screenshots<commit_after>'use strict'

export class Cursor {

  constructor () {
    this._size = 14
    this._timeout = 400
    this._initTransition = `all ${this._timeout}ms ease-in-out`
    this._position = {
      x: 0,
      y: 0
    }

    this._point = window.document.getElementById('mocha-extjs-testing-tool-pointer')

    if (!this._point) {
      this._point = document.createElement('div')

      this._point.id = 'mocha-extjs-testing-tool-pointer'
      this._point.style.top = `${this._position.y}px`
      this._point.style.left = `${this._position.x}px`
      this._point.style.width = `${this._size}px`
      this._point.style.zIndex = '90000'
      this._point.style.height = `${this._size}px`
      this._point.style.border = '2px solid #ffffff'
      this._point.style.opacity = '1'
      this._point.style.position = 'absolute'
      this._point.style.transition = this._initTransition
      this._point.style.borderRadius = `0 ${this._size / 2}px ${this._size / 2}px ${this._size / 2}px`
      this._point.style.backgroundColor = '#ee3300'

      window.document.body.appendChild(this._point)
    }
  }

  moveTo (x, y, callback) {
    if (window.callPhantom) {
      this._point.style.left = `${x}px`
      this._point.style.top = `${y}px`
      return callback(null)
    } else {
      const translate = `translate(${x}px, ${y}px)`
      this._point.style.transform = translate
      setTimeout(() => {
        this._point.style.transition = 'all 50ms ease-in-out'
        this._point.style.transform = `${translate} scale(0.5)`
        setTimeout(() => {
          this._point.style.transform = `${translate} scale(1)`
          setTimeout(() => {
            this._point.style.transition = this._initTransition
            return callback(null)
          }, 50)
        }, 50)
      }, this._timeout)
    }
  }

  hide () {
    this._point.style.display = 'none'
  }

  show () {
    this._point.style.display = 'block'
  }

}
<|endoftext|>


<commit_before>// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

// add trim function to String class
String.prototype.trim = function() { return this.replace(/^\s*|\s*$/g,""); };

var SessionTimer = {
  start: function() {
    SessionTimer.interval_id = setTimeout(SessionTimer.check, 60000);
  },
  disable: function() {
    window.clearTimeout(SessionTimer.interval_id);
  },
  check: function() {
    jQuery.getScript('/session');
    SessionTimer.start();
  },
  reset: function() {
    jQuery.ajax({
      type: 'PUT',
      url: '/session',
      dataType: 'script'
    });
  }
};

var wesabe = {
  __name__: 'wesabe',

  expando: (function() {
    var element = $('

');
    for (var k in element)
      if (/^jQuery\d+$/.test(k))
        return k;
    // choose a semi-plausible fallback
    return 'appendTo';
  })(),

  isJQuery: function(object) {
    return !!(object && object[wesabe.expando]);
  },

  __idCounter__: 0,

  uniqueId: function() {
    return '__id'+(wesabe.__idCounter__++);
  },

  get: function(pkg, module, base, callback) {
    var name  = wesabe._fqn(pkg, module),
        parts = name.split('.');

    if (!base)
      base = window;

    if (base.__name__)
      parts.unshift(base.__name__);

    if (!callback)
      callback = function(o){ return o };

    if (typeof module == 'string')
      parts.push(module);

    for (var i = 0; i < parts.length; i++) {
      base = base[parts[i]] = callback(base[parts[i]], parts.slice(0, i+1).join('.'));
      if (!base) return null;
    }

    return base;
  },

  _fqn: function(pkg, module) {
    var result = pkg && pkg.__name__ || pkg;

    if (module)
      result += '.' + module;

    return result;
  },

  /**
   * Define a namespace under the toplevel 'wesabe' namespace.
   *
   * @param {!string} module A dot-separated namespace (e.g. lang.string).
   * @param {?*} value An optional value for the namespace (defaults to {}).
   * @return {*}
   */
  provide: function(module, value) {
    if (!/^wesabe\./.test(module))
      module = 'wesabe.' + module;

    return wesabe.get(module, null, null, function(part, name) {
      part = ((module == name) && value) || part || {};
      part.__name__ = name;
      return part;
    });
  },

  /**
   * Takes a callback to be run once the given module has been loaded.
   *
   *   wesabe.ready("$.historyInit", function() {
   *     wesabe.privacy.registerSanitizer(...);
   *   });
   *
   * @param {!string} name The dot-separated name of the module/class to watch for.
   * @param {!function(*)} callback A function to call when the module is ready.
   * @param {?number} ttl Number of times to check for the module (default: 100).
   */
  ready: function(name, callback, ttl) {
    ttl = ttl || 100;

    (function() {
      var obj = wesabe.get(name);

      if (obj) {
        // got it, fire the callback
        callback(obj);
      } else if (ttl--) {
        // not yet, try again in 50ms
        setTimeout(arguments.callee, 50);
      }
    })();
  },

  /* Dynamically load a javascript module.
   *
   * @param {!string|object} pkg The path to a javascript file or a JS package object.
   * @param {?string} module The name of the module to load within pkg, if given a JS object.
   * @param {?function(object)} callback A function to call after the module has been loaded.
   */
  load: function(pkg, module, callback) {
    var src;

    var obj = wesabe.get(pkg, module);
    if (obj) {
      callback(obj);
      return;
    }

    src = /\//.test(pkg) ? pkg
                         : wesabe._fqn(pkg, module).replace(/\./g, '/');

    if (!src.match(/\.js$/))
      src = src+'.js?'+(new Date().getTime());
    if (!src.match(/^(http(s)?:|\/javascripts\/)/))
      src = '/javascripts/' + src;

    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = src;
    document.getElementsByTagName('body')[0].appendChild(script);

    if (callback)
      wesabe.ready(wesabe._fqn(pkg, module), callback);
  },

  /**
   * Builds a class with +name+ with an optional superclass given by +$super+,
   * yielding the class, superclass, and package to +callback+.
   *
   * @param {!string} name The full name of the class "foo.Bar".
   * @param {?function()} $super Optional superclass, used as callback if no 3rd
   *                             argument is given, defaults to wesabe.lang.Subscribable.
   * @param {?function(function, function, object)} callback
   * @return {function()} The class that was built.
   */
  $class: function(name, $super, callback) {
    if (callback === undefined) {
      callback = $super;
      $super = undefined;
    }

    // make sure everything is Subscribable by default
    if ($super === undefined) $super = wesabe.lang.Subscribable;

    // use the prototype if they gave us a class
    if ($super && $super.prototype) $super = $super.prototype;

    // create the constructor and inject it into the tree
    var $class = wesabe.provide(name, function() {
      if (this.init)
        this.init.apply(this, arguments);
    });

    // build the class
    $class.prototype = $.extend($super ? $.extend({}, $super) : {}, {
      getClass: function(){ return $class },
      isInstanceOf: function(klass){ return klass === this.getClass() }
    });

    // get the package
    var $package = wesabe.get($class.__name__.replace(/\.[^\.]+$/, ''));

    if (callback)
      callback($class, $super, $package);

    return $class;
  }
};

var either = function() {
  for (var i = 0; i < arguments.length; i++)
    if (arguments[i]!==null && arguments[i]!==undefined)
      return arguments[i];
};

var hasValue = function(val) {
  return val !== undefined && val !== null
};

// from http://dominiek.com/108-ajax-snippet-blank-out-a-div-with-a-spinner
function spinDiv(div) {
  // see if the spinDiv exists already, and remove it to toggle off
  if (div.children(".spin_div").remove().length == 0) {
    var container = div[0]; // assumes jQuery element
    var positioning = 'top: '+container.offsetTop+'px; width: '+container.offsetWidth+'px; height: '+container.offsetHeight+'px; left: ' + container.offsetLeft + 'px;';
    div.append('

');
  }
}
<commit_msg>Fix that BaseWidget & descendants were sometimes considered jQuery objects.<commit_after>// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

// add trim function to String class
String.prototype.trim = function() { return this.replace(/^\s*|\s*$/g,""); };

var SessionTimer = {
  start: function() {
    SessionTimer.interval_id = setTimeout(SessionTimer.check, 60000);
  },
  disable: function() {
    window.clearTimeout(SessionTimer.interval_id);
  },
  check: function() {
    jQuery.getScript('/session');
    SessionTimer.start();
  },
  reset: function() {
    jQuery.ajax({
      type: 'PUT',
      url: '/session',
      dataType: 'script'
    });
  }
};

var wesabe = {
  __name__: 'wesabe',

  expando: (function() {
    var element = $('

');
    for (var k in element)
      if (/^jQuery\d+$/.test(k))
        return k;
    // choose a semi-plausible fallback
    return 'appendTo';
  })(),

  isJQuery: function(object) {
    return !!(object && object[wesabe.expando] && !object.getClass);
  },

  __idCounter__: 0,

  uniqueId: function() {
    return '__id'+(wesabe.__idCounter__++);
  },

  get: function(pkg, module, base, callback) {
    var name  = wesabe._fqn(pkg, module),
        parts = name.split('.');

    if (!base)
      base = window;

    if (base.__name__)
      parts.unshift(base.__name__);

    if (!callback)
      callback = function(o){ return o };

    if (typeof module == 'string')
      parts.push(module);

    for (var i = 0; i < parts.length; i++) {
      base = base[parts[i]] = callback(base[parts[i]], parts.slice(0, i+1).join('.'));
      if (!base) return null;
    }

    return base;
  },

  _fqn: function(pkg, module) {
    var result = pkg && pkg.__name__ || pkg;

    if (module)
      result += '.' + module;

    return result;
  },

  /**
   * Define a namespace under the toplevel 'wesabe' namespace.
   *
   * @param {!string} module A dot-separated namespace (e.g. lang.string).
   * @param {?*} value An optional value for the namespace (defaults to {}).
   * @return {*}
   */
  provide: function(module, value) {
    if (!/^wesabe\./.test(module))
      module = 'wesabe.' + module;

    return wesabe.get(module, null, null, function(part, name) {
      part = ((module == name) && value) || part || {};
      part.__name__ = name;
      return part;
    });
  },

  /**
   * Takes a callback to be run once the given module has been loaded.
   *
   *   wesabe.ready("$.historyInit", function() {
   *     wesabe.privacy.registerSanitizer(...);
   *   });
   *
   * @param {!string} name The dot-separated name of the module/class to watch for.
   * @param {!function(*)} callback A function to call when the module is ready.
   * @param {?number} ttl Number of times to check for the module (default: 100).
   */
  ready: function(name, callback, ttl) {
    ttl = ttl || 100;

    (function() {
      var obj = wesabe.get(name);

      if (obj) {
        // got it, fire the callback
        callback(obj);
      } else if (ttl--) {
        // not yet, try again in 50ms
        setTimeout(arguments.callee, 50);
      }
    })();
  },

  /* Dynamically load a javascript module.
   *
   * @param {!string|object} pkg The path to a javascript file or a JS package object.
   * @param {?string} module The name of the module to load within pkg, if given a JS object.
   * @param {?function(object)} callback A function to call after the module has been loaded.
   */
  load: function(pkg, module, callback) {
    var src;

    var obj = wesabe.get(pkg, module);
    if (obj) {
      callback(obj);
      return;
    }

    src = /\//.test(pkg) ? pkg
                         : wesabe._fqn(pkg, module).replace(/\./g, '/');

    if (!src.match(/\.js$/))
      src = src+'.js?'+(new Date().getTime());
    if (!src.match(/^(http(s)?:|\/javascripts\/)/))
      src = '/javascripts/' + src;

    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = src;
    document.getElementsByTagName('body')[0].appendChild(script);

    if (callback)
      wesabe.ready(wesabe._fqn(pkg, module), callback);
  },

  /**
   * Builds a class with +name+ with an optional superclass given by +$super+,
   * yielding the class, superclass, and package to +callback+.
   *
   * @param {!string} name The full name of the class "foo.Bar".
   * @param {?function()} $super Optional superclass, used as callback if no 3rd
   *                             argument is given, defaults to wesabe.lang.Subscribable.
   * @param {?function(function, function, object)} callback
   * @return {function()} The class that was built.
   */
  $class: function(name, $super, callback) {
    if (callback === undefined) {
      callback = $super;
      $super = undefined;
    }

    // make sure everything is Subscribable by default
    if ($super === undefined) $super = wesabe.lang.Subscribable;

    // use the prototype if they gave us a class
    if ($super && $super.prototype) $super = $super.prototype;

    // create the constructor and inject it into the tree
    var $class = wesabe.provide(name, function() {
      if (this.init)
        this.init.apply(this, arguments);
    });

    // build the class
    $class.prototype = $.extend($super ? $.extend({}, $super) : {}, {
      getClass: function(){ return $class },
      isInstanceOf: function(klass){ return klass === this.getClass() }
    });

    // get the package
    var $package = wesabe.get($class.__name__.replace(/\.[^\.]+$/, ''));

    if (callback)
      callback($class, $super, $package);

    return $class;
  }
};

var either = function() {
  for (var i = 0; i < arguments.length; i++)
    if (arguments[i]!==null && arguments[i]!==undefined)
      return arguments[i];
};

var hasValue = function(val) {
  return val !== undefined && val !== null
};

// from http://dominiek.com/108-ajax-snippet-blank-out-a-div-with-a-spinner
function spinDiv(div) {
  // see if the spinDiv exists already, and remove it to toggle off
  if (div.children(".spin_div").remove().length == 0) {
    var container = div[0]; // assumes jQuery element
    var positioning = 'top: '+container.offsetTop+'px; width: '+container.offsetWidth+'px; height: '+container.offsetHeight+'px; left: ' + container.offsetLeft + 'px;';
    div.append('

');
  }
}
<|endoftext|>


<commit_before>// Karma configuration
// Generated on Sat Apr 08 2017 23:03:49 GMT-0600 (MDT)

module.exports = function(config) {
  config.set({

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '',

    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['jasmine'],

    // list of files / patterns to load in the browser
    files: [
      'spec/**/*.ts'
    ],

    // list of files to exclude
    exclude: [
    ],

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
    },

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['progress'],

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: ['Chrome'],

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: false,

    // Concurrency level
    // how many browser should be started simultaneous
    concurrency: Infinity
  })
}
<commit_msg>fix(build): add in ts preprocessing<commit_after>// Karma configuration
// Generated on Sat Apr 08 2017 23:03:49 GMT-0600 (MDT)

module.exports = function(config) {
  config.set({

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '',

    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['jasmine', "karma-typescript"],

    // list of files / patterns to load in the browser
    files: [
      'spec/**/*.ts'
    ],

    // list of files to exclude
    exclude: [
    ],

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
      "spec/**/*.ts": ["karma-typescript"],
    },

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['progress', "karma-typescript"],
        karmaTypescriptConfig: {
            tsconfig: "./tsconfig.json"
        },

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: ['Chrome'],

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: false,

    // Concurrency level
    // how many browser should be started simultaneous
    concurrency: Infinity,
  })
}
<|endoftext|>


<commit_before>/* eslint key-spacing:0 */
export default (config) => ({
  compiler_fail_on_warning : false,
  compiler_hash_type       : 'chunkhash',
  compiler_source_maps     : false,
  compiler_stats           : {
    chunks : true,
    chunkModules : true,
    colors : true
  }
});
<commit_msg>Specify the publicPath to be the github pages URL for production deploys.<commit_after>/* eslint key-spacing:0 */
export default (config) => ({
  compiler_fail_on_warning : false,
  compiler_hash_type       : 'chunkhash',
  compiler_source_maps     : false,
  compiler_stats           : {
    chunks : true,
    chunkModules : true,
    colors : true
  },
  compiler_public_path     : 'https://fiviumaustralia.github.io/RNSH-Pilot/'
});
<|endoftext|>


<commit_before>/* jshint node: true */

module.exports = function(environment) {
    const authorizationType = 'cookie';

    const ENV = {
        modulePrefix: 'preprint-service',
        environment: environment,
        rootURL: '/',
        locationType: 'auto',
        authorizationType: authorizationType,
        sentryDSN: 'http://test@localhost/80' || process.env.SENTRY_DSN,
        'ember-simple-auth': {
            authorizer: `authorizer:osf-${authorizationType}`,
            authenticator: `authenticator:osf-${authorizationType}`
        },
        EmberENV: {
            FEATURES: {
                // Here you can enable experimental features on an ember canary build
                // e.g. 'with-controller': true
            }
        },
        APP: {
            // Here you can pass flags/options to your application instance
            // when it is created
        },
        SHARE: {
            baseUrl: process.env.SHARE_BASE_URL || 'https://staging-share.osf.io/',
            searchUrl: process.env.SHARE_SEARCH_URL || 'https://staging-share.osf.io/api/v2/search/creativeworks/_search'
        },
        moment: {
            outputFormat: 'YYYY-MM-DD hh:mm a'
        },
        PREPRINTS: {
            defaultProvider: 'osf',
            // Logos are needed for open graph sharing meta tags (Facebook, LinkedIn, etc) and must be at least 200x200
            providers: [
                // OSF must be the first provider
                {
                    id: 'osf',
                    domain: 'osf.io',
                    logoSharing: {
                        path: '/assets/img/provider_logos/osf-dark.png',
                        type: 'image/png',
                        width: 363,
                        height: 242
                    },
                    permissionLanguage: 'no_trademark'
                },
                {
                    id: 'engrxiv',
                    domain: 'engrxiv.org',
                    logoSharing: {
                        path: '/assets/img/provider_logos/engrxiv-sharing.png',
                        type: 'image/png',
                        width: 1200,
                        height: 488

                    },
                    permissionLanguage: 'arxiv_non_endorsement'
                },
                {
                    id: 'socarxiv',
                    domain: 'socarxiv.org',
                    logoSharing: {
                        path: '/assets/img/provider_logos/socarxiv-sharing.png',
                        type: 'image/png',
                        width: 1200,
                        height: 488
                    },
                    permissionLanguage: 'arxiv_trademark_license'
                },
                {
                    id: 'psyarxiv',
                    // domain: 'psyarxiv.org', // Temporarily disabling until ready
                    logoSharing: {
                        path: '/assets/img/provider_logos/psyarxiv-sharing.png',
                        type: 'image/png',
                        width: 1200,
                        height: 488
                    },
                    permissionLanguage: 'arxiv_trademark_license'
                },
                {
                    id: 'bitss',
                    // Does not use a provider domain
                    logoSharing: {
                        path: '/assets/img/provider_logos/bitss-small.png',
                        type: 'image/png',
                        width: 1500,
                        height: 1500
                    },
                    permissionLanguage: 'no_trademark'
                },
                {
                    id: 'scielo',
                    // domain: 'scielo.org', // Temporarily disabling until ready
                    logoSharing: {
                        path: '/assets/img/provider_logos/scielo-logo.png',
                        type: 'image/png',
                        width: 1200,
                        height: 488
                    },
                    permissionLanguage: 'no_trademark'
                },
                {
                    id: 'agrixiv',
                    domain: 'agrixiv.org',
                    logoSharing: {
                        path: 'assets/img/provider_logos/agrixiv-banner.svg',
                        type: 'image/png',
                        width: 1200,
                        height: 488
                    },
                    permissionLanguage: 'arxiv_non_endorsement'
                }
            ],
        },
        i18n: {
            defaultLocale: 'en'
        },
        metricsAdapters: [
            {
                name: 'GoogleAnalytics',
                environments: ['all'],
                config: {
                    id: process.env.GOOGLE_ANALYTICS_ID
                }
            }
        ],
        FB_APP_ID: process.env.FB_APP_ID,
    };

    if (environment === 'development') {
        // ENV.APP.LOG_RESOLVER = true;
        // ENV.APP.LOG_ACTIVE_GENERATION = true;
        // ENV.APP.LOG_TRANSITIONS = true;
        // ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
        // ENV.APP.LOG_VIEW_LOOKUPS = true;

        ENV.metricsAdapters[0].config.cookieDomain = 'none';
    }

    if (environment === 'test') {
        // Testem prefers this...
        ENV.baseURL = '/';
        ENV.locationType = 'none';

        // keep test console output quieter
        ENV.APP.LOG_ACTIVE_GENERATION = false;
        ENV.APP.LOG_VIEW_LOOKUPS = false;

        ENV.APP.rootElement = '#ember-testing';

        // Don't make external requests during unit test
        // TODO: Provide mocks for all components with manual AJAX calls in the future.
        ENV.SHARE.baseUrl = '/nowhere';
        ENV.SHARE.searchUrl = '/nowhere';

        ENV.metricsAdapters[0].config.cookieDomain = 'none'
    }

    if (environment === 'production') {
        ENV.sentryDSN = process.env.SENTRY_DSN || 'https://2f0a61d03b99480ea11e259edec18bd9@sentry.cos.io/45';
        ENV.ASSET_SUFFIX = process.env.GIT_COMMIT || 'git_commit_env_not_set';
    } else {
        // Fallback to throwaway defaults if the environment variables are not set
        ENV.metricsAdapters[0].config.id = ENV.metricsAdapters[0].config.id || 'UA-84580271-1';
        ENV.FB_APP_ID = ENV.FB_APP_ID || '1039002926217080';

        const {DOMAIN_PREFIX, PORT, OSF_URL} = process.env;

        for (const provider of ENV.PREPRINTS.providers) {
            if (!provider.domain)
                continue;

            if (provider.id === 'osf') {
                provider.domain = OSF_URL || 'localhost:5000';
                continue;
            }

            const suffix = DOMAIN_PREFIX ? '' : `:${PORT ? PORT : '4200'}`;
            provider.domain = `${DOMAIN_PREFIX || 'local'}.${provider.domain}${suffix}`;
        }
    }

    if (ENV.ASSET_SUFFIX) {
        ENV.PREPRINTS.providers = ENV.PREPRINTS.providers.map(provider => {
            provider.logoSharing.path = provider.logoSharing.path
                .replace(/\..*$/, match => `-${ENV.ASSET_SUFFIX}${match}`);

            return provider;
        });
    }

    return ENV;
};
<commit_msg>Use environment variable to enable provider domains<commit_after>/* jshint node: true */

module.exports = function(environment) {
    const authorizationType = 'cookie';

    const ENV = {
        modulePrefix: 'preprint-service',
        environment: environment,
        rootURL: '/',
        locationType: 'auto',
        authorizationType: authorizationType,
        sentryDSN: 'http://test@localhost/80' || process.env.SENTRY_DSN,
        'ember-simple-auth': {
            authorizer: `authorizer:osf-${authorizationType}`,
            authenticator: `authenticator:osf-${authorizationType}`
        },
        EmberENV: {
            FEATURES: {
                // Here you can enable experimental features on an ember canary build
                // e.g. 'with-controller': true
            }
        },
        APP: {
            // Here you can pass flags/options to your application instance
            // when it is created
        },
        SHARE: {
            baseUrl: process.env.SHARE_BASE_URL || 'https://staging-share.osf.io/',
            searchUrl: process.env.SHARE_SEARCH_URL || 'https://staging-share.osf.io/api/v2/search/creativeworks/_search'
        },
        moment: {
            outputFormat: 'YYYY-MM-DD hh:mm a'
        },
        PREPRINTS: {
            defaultProvider: 'osf',
            // Logos are needed for open graph sharing meta tags (Facebook, LinkedIn, etc) and must be at least 200x200
            providers: [
                // OSF must be the first provider
                {
                    id: 'osf',
                    domain: 'osf.io',
                    logoSharing: {
                        path: '/assets/img/provider_logos/osf-dark.png',
                        type: 'image/png',
                        width: 363,
                        height: 242
                    },
                    permissionLanguage: 'no_trademark'
                },
                {
                    id: 'engrxiv',
                    domain: 'engrxiv.org',
                    logoSharing: {
                        path: '/assets/img/provider_logos/engrxiv-sharing.png',
                        type: 'image/png',
                        width: 1200,
                        height: 488

                    },
                    permissionLanguage: 'arxiv_non_endorsement'
                },
                {
                    id: 'socarxiv',
                    domain: 'socarxiv.org',
                    logoSharing: {
                        path: '/assets/img/provider_logos/socarxiv-sharing.png',
                        type: 'image/png',
                        width: 1200,
                        height: 488
                    },
                    permissionLanguage: 'arxiv_trademark_license'
                },
                {
                    id: 'psyarxiv',
                    // domain: 'psyarxiv.org', // Temporarily disabling until ready
                    logoSharing: {
                        path: '/assets/img/provider_logos/psyarxiv-sharing.png',
                        type: 'image/png',
                        width: 1200,
                        height: 488
                    },
                    permissionLanguage: 'arxiv_trademark_license'
                },
                {
                    id: 'bitss',
                    // Does not use a provider domain
                    logoSharing: {
                        path: '/assets/img/provider_logos/bitss-small.png',
                        type: 'image/png',
                        width: 1500,
                        height: 1500
                    },
                    permissionLanguage: 'no_trademark'
                },
                {
                    id: 'scielo',
                    // domain: 'scielo.org', // Temporarily disabling until ready
                    logoSharing: {
                        path: '/assets/img/provider_logos/scielo-logo.png',
                        type: 'image/png',
                        width: 1200,
                        height: 488
                    },
                    permissionLanguage: 'no_trademark'
                },
                {
                    id: 'agrixiv',
                    domain: 'agrixiv.org',
                    logoSharing: {
                        path: 'assets/img/provider_logos/agrixiv-banner.svg',
                        type: 'image/png',
                        width: 1200,
                        height: 488
                    },
                    permissionLanguage: 'arxiv_non_endorsement'
                }
            ],
        },
        i18n: {
            defaultLocale: 'en'
        },
        metricsAdapters: [
            {
                name: 'GoogleAnalytics',
                environments: ['all'],
                config: {
                    id: process.env.GOOGLE_ANALYTICS_ID
                }
            }
        ],
        FB_APP_ID: process.env.FB_APP_ID,
    };

    if (process.env.ENABLE_PROVIDER_DOMAINS !== 'true') {
        for (const provider of ENV.PREPRINTS.providers) {
            delete provider.domain;
        }
    }

    if (environment === 'development') {
        // ENV.APP.LOG_RESOLVER = true;
        // ENV.APP.LOG_ACTIVE_GENERATION = true;
        // ENV.APP.LOG_TRANSITIONS = true;
        // ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
        // ENV.APP.LOG_VIEW_LOOKUPS = true;

        ENV.metricsAdapters[0].config.cookieDomain = 'none';
    }

    if (environment === 'test') {
        // Testem prefers this...
        ENV.baseURL = '/';
        ENV.locationType = 'none';

        // keep test console output quieter
        ENV.APP.LOG_ACTIVE_GENERATION = false;
        ENV.APP.LOG_VIEW_LOOKUPS = false;

        ENV.APP.rootElement = '#ember-testing';

        // Don't make external requests during unit test
        // TODO: Provide mocks for all components with manual AJAX calls in the future.
        ENV.SHARE.baseUrl = '/nowhere';
        ENV.SHARE.searchUrl = '/nowhere';

        ENV.metricsAdapters[0].config.cookieDomain = 'none'
    }

    if (environment === 'production') {
        ENV.sentryDSN = process.env.SENTRY_DSN || 'https://2f0a61d03b99480ea11e259edec18bd9@sentry.cos.io/45';
        ENV.ASSET_SUFFIX = process.env.GIT_COMMIT || 'git_commit_env_not_set';
    } else {
        // Fallback to throwaway defaults if the environment variables are not set
        ENV.metricsAdapters[0].config.id = ENV.metricsAdapters[0].config.id || 'UA-84580271-1';
        ENV.FB_APP_ID = ENV.FB_APP_ID || '1039002926217080';

        const {DOMAIN_PREFIX, PORT, OSF_URL} = process.env;

        for (const provider of ENV.PREPRINTS.providers) {
            if (!provider.domain)
                continue;

            if (provider.id === 'osf') {
                provider.domain = OSF_URL || 'localhost:5000';
                continue;
            }

            const suffix = DOMAIN_PREFIX ? '' : `:${PORT ? PORT : '4200'}`;
            provider.domain = `${DOMAIN_PREFIX || 'local'}.${provider.domain}${suffix}`;
        }
    }

    if (ENV.ASSET_SUFFIX) {
        ENV.PREPRINTS.providers = ENV.PREPRINTS.providers.map(provider => {
            provider.logoSharing.path = provider.logoSharing.path
                .replace(/\..*$/, match => `-${ENV.ASSET_SUFFIX}${match}`);

            return provider;
        });
    }

    return ENV;
};
<|endoftext|>


<commit_before>const mongoose = require('mongoose')
const dbSettings = require('../config.js').database
const articlesExpire = dbSettings.clean === true && (dbSettings.articlesExpire > 0 || dbSettings.articlesExpire === -1) ? dbSettings.articlesExpire : 14

function hash (str) {
  // https://stackoverflow.com/questions/6122571/simple-non-secure-hash-function-for-javascript
  let hash = 0
  if (str.length === 0) return hash
  for (var i = 0; i < str.length; i++) {
    const char = str.charCodeAt(i)
    hash = ((hash << 5) - hash) + char
    hash = hash & hash // Convert to 32bit integer
  }
  return hash
}

function getCollectionID (link, shardId, scheduleName = '') {
  if (!scheduleName || scheduleName === 'default') scheduleName = ''
  let res = (shardId != null ? `${shardId}_` : '') + scheduleName.slice(0, 10) + hash(link).toString() + (new URL(link)).hostname.replace(/\.|\$/g, '')
  const len = mongoose.connection.name ? (res.length + mongoose.connection.name.length + 1) : res.length + 1 // mongoose.connection.name is undefined if config.database.uri is a databaseless folder path
  if (len > 115) res = res.slice(0, 115)
  return res
}

function expireDate () {
  return () => {
    const date = new Date()
    date.setDate(date.getDate() + articlesExpire) // Add days
    return date
  }
}

const schema = mongoose.Schema({
  id: String,
  title: String,
  date: {
    type: Date,
    default: Date.now
  },
  customComparisons: Object,
  ...articlesExpire > 0 ? { expiresAt: {
    type: Date,
    default: expireDate(),
    index: { expires: 0 }
  } } : {}
})

exports.schema = schema
exports.model = (link, shardId, scheduleName) => mongoose.model(getCollectionID(link, shardId, scheduleName), schema, getCollectionID(link, shardId, scheduleName)) // Third parameter is not let mongoose auto-pluralize the collection name
exports.modelByID = collectionID => mongoose.model(collectionID, schema, collectionID) // Third parameter is not let mongoose auto-pluralize the collection name
exports.getCollectionID = getCollectionID
<commit_msg>Fix node v8 tests for missing URL require<commit_after>const URL = require('url').URL
const mongoose = require('mongoose')
const dbSettings = require('../config.js').database
const articlesExpire = dbSettings.clean === true && (dbSettings.articlesExpire > 0 || dbSettings.articlesExpire === -1) ? dbSettings.articlesExpire : 14

function hash (str) {
  // https://stackoverflow.com/questions/6122571/simple-non-secure-hash-function-for-javascript
  let hash = 0
  if (str.length === 0) return hash
  for (var i = 0; i < str.length; i++) {
    const char = str.charCodeAt(i)
    hash = ((hash << 5) - hash) + char
    hash = hash & hash // Convert to 32bit integer
  }
  return hash
}

function getCollectionID (link, shardId, scheduleName = '') {
  if (!scheduleName || scheduleName === 'default') scheduleName = ''
  let res = (shardId != null ? `${shardId}_` : '') + scheduleName.slice(0, 10) + hash(link).toString() + (new URL(link)).hostname.replace(/\.|\$/g, '')
  const len = mongoose.connection.name ? (res.length + mongoose.connection.name.length + 1) : res.length + 1 // mongoose.connection.name is undefined if config.database.uri is a databaseless folder path
  if (len > 115) res = res.slice(0, 115)
  return res
}

function expireDate () {
  return () => {
    const date = new Date()
    date.setDate(date.getDate() + articlesExpire) // Add days
    return date
  }
}

const schema = mongoose.Schema({
  id: String,
  title: String,
  date: {
    type: Date,
    default: Date.now
  },
  customComparisons: Object,
  ...articlesExpire > 0 ? { expiresAt: {
    type: Date,
    default: expireDate(),
    index: { expires: 0 }
  } } : {}
})

exports.schema = schema
exports.model = (link, shardId, scheduleName) => mongoose.model(getCollectionID(link, shardId, scheduleName), schema, getCollectionID(link, shardId, scheduleName)) // Third parameter is not let mongoose auto-pluralize the collection name
exports.modelByID = collectionID => mongoose.model(collectionID, schema, collectionID) // Third parameter is not let mongoose auto-pluralize the collection name
exports.getCollectionID = getCollectionID
<|endoftext|>


<commit_before>if(!TASK_CONFIG.javascripts) return

var path            = require('path')
var pathToUrl       = require('./pathToUrl')
var webpack         = require('webpack')
var webpackManifest = require('./webpackManifest')

module.exports = function(env) {
  var jsSrc = path.resolve(process.env.PWD, PATH_CONFIG.src, PATH_CONFIG.javascripts.src)
  var jsDest = path.resolve(process.env.PWD, PATH_CONFIG.dest, PATH_CONFIG.javascripts.dest)
  var publicPath = pathToUrl(TASK_CONFIG.javascripts.publicPath || PATH_CONFIG.javascripts.dest, '/')

  var extensions = TASK_CONFIG.javascripts.extensions.map(function(extension) {
    return '.' + extension
  })

  var rev = TASK_CONFIG.production.rev && env === 'production'
  var filenamePattern = rev ? '[name]-[hash].js' : '[name].js'

  // TODO: To work in < node 6, prepend process.env.PWD + node_modules/babel-preset- to each
  var defaultBabelConfig = {
    presets: ['es2015', 'stage-1']
  }

  var testPattern = new RegExp(`(\\${TASK_CONFIG.javascripts.extensions.join('$|\\.')}$)`)

  var webpackConfig = {
    context: jsSrc,
    output: {},
    plugins: [
      new webpack.optimize.OccurenceOrderPlugin()
    ],
    resolve: {
      root: jsSrc,
      extensions: [''].concat(extensions),
      alias: TASK_CONFIG.javascripts.alias,
      fallback: path.resolve(process.env.PWD, 'node_modules')
    }, // See https://github.com/facebook/react/issues/4566
    resolveLoader: {
      fallback: path.resolve(process.env.PWD, 'node_modules')
    },
    module: {
      loaders: [
        {
          test: testPattern,
          loader: 'babel-loader',
          exclude: /node_modules/,
          query: TASK_CONFIG.javascripts.babel || defaultBabelConfig
        }
      ]
    }
  }

  // Add additional loaders from config
  webpackConfig.module.loaders = webpackConfig.module.loaders.concat(TASK_CONFIG.javascripts.loaders || [])

  if(env === 'development') {
    webpackConfig.devtool = TASK_CONFIG.javascripts.devtool || 'eval-cheap-module-source-map'
    webpackConfig.output.pathinfo = true

    // Create new entries object with webpack-hot-middleware and react-hot-loader (if enabled)
    if(TASK_CONFIG.javascripts.hot.enabled !== false) {
      for (var key in TASK_CONFIG.javascripts.entries) {
        var entry = TASK_CONFIG.javascripts.entries[key]
        // TODO: To work in < node 6, prepend process.env.PWD + node_modules/
        const entries = []
        let middleware = 'webpack-hot-middleware/client?'

        if(TASK_CONFIG.javascripts.hot.reload !== false) {
          middleware+= '&reload=true'
        }

        if(TASK_CONFIG.javascripts.hot.noInfo) {
          middleware+= '&noInfo=true'
        }

        if(TASK_CONFIG.javascripts.hot.quiet) {
          middleware+= '&quiet=true'
        }

        if(TASK_CONFIG.javascripts.hot.react) {
          entries.push('react-hot-loader/patch')
        }

        TASK_CONFIG.javascripts.entries[key] = entries.concat(middleware).concat(entry)
      }

      webpackConfig.plugins.push(new webpack.HotModuleReplacementPlugin())
    }
    // Addtional loaders for dev
    webpackConfig.module.loaders = webpackConfig.module.loaders.concat(TASK_CONFIG.javascripts.developmentLoaders || [])
  }

  if(env !== 'test') {
    // Karma doesn't need entry points or output settings
    webpackConfig.entry = TASK_CONFIG.javascripts.entries

    webpackConfig.output.path = path.normalize(jsDest),
    webpackConfig.output.filename = filenamePattern,
    webpackConfig.output.publicPath = publicPath

    if(TASK_CONFIG.javascripts.extractSharedJs) {
      // Factor out common dependencies into a shared.js
      webpackConfig.plugins.push(
        new webpack.optimize.CommonsChunkPlugin({
          name: 'shared',
          filename: filenamePattern,
        })
      )
    }

    // Addtional loaders for tests
    webpackConfig.module.loaders = webpackConfig.module.loaders.concat(TASK_CONFIG.javascripts.testLoaders || [])
  }

  if(env === 'production') {
    if(rev) {
      webpackConfig.plugins.push(new webpackManifest(PATH_CONFIG.javascripts.dest, PATH_CONFIG.dest))
    }
    webpackConfig.plugins.push(
      new webpack.DefinePlugin({
        'process.env': {
          'NODE_ENV': JSON.stringify('production')
        }
      }),
      new webpack.optimize.DedupePlugin(),
      new webpack.optimize.UglifyJsPlugin(),
      new webpack.NoErrorsPlugin()
    )

    // Addtional loaders for production
    webpackConfig.module.loaders = webpackConfig.module.loaders.concat(TASK_CONFIG.javascripts.productionLoaders || [])
  }

  return webpackConfig
}
<commit_msg>fix: TypeError: Cannot read property 'enabled' of undefined (fixes #369)<commit_after>if(!TASK_CONFIG.javascripts) return

var path            = require('path')
var pathToUrl       = require('./pathToUrl')
var webpack         = require('webpack')
var webpackManifest = require('./webpackManifest')

module.exports = function(env) {
  var jsSrc = path.resolve(process.env.PWD, PATH_CONFIG.src, PATH_CONFIG.javascripts.src)
  var jsDest = path.resolve(process.env.PWD, PATH_CONFIG.dest, PATH_CONFIG.javascripts.dest)
  var publicPath = pathToUrl(TASK_CONFIG.javascripts.publicPath || PATH_CONFIG.javascripts.dest, '/')

  var extensions = TASK_CONFIG.javascripts.extensions.map(function(extension) {
    return '.' + extension
  })

  var rev = TASK_CONFIG.production.rev && env === 'production'
  var filenamePattern = rev ? '[name]-[hash].js' : '[name].js'

  // TODO: To work in < node 6, prepend process.env.PWD + node_modules/babel-preset- to each
  var defaultBabelConfig = {
    presets: ['es2015', 'stage-1']
  }

  var testPattern = new RegExp(`(\\${TASK_CONFIG.javascripts.extensions.join('$|\\.')}$)`)

  var webpackConfig = {
    context: jsSrc,
    output: {},
    plugins: [
      new webpack.optimize.OccurenceOrderPlugin()
    ],
    resolve: {
      root: jsSrc,
      extensions: [''].concat(extensions),
      alias: TASK_CONFIG.javascripts.alias,
      fallback: path.resolve(process.env.PWD, 'node_modules')
    }, // See https://github.com/facebook/react/issues/4566
    resolveLoader: {
      fallback: path.resolve(process.env.PWD, 'node_modules')
    },
    module: {
      loaders: [
        {
          test: testPattern,
          loader: 'babel-loader',
          exclude: /node_modules/,
          query: TASK_CONFIG.javascripts.babel || defaultBabelConfig
        }
      ]
    }
  }

  // Add additional loaders from config
  webpackConfig.module.loaders = webpackConfig.module.loaders.concat(TASK_CONFIG.javascripts.loaders || [])

  if(env === 'development') {
    webpackConfig.devtool = TASK_CONFIG.javascripts.devtool || 'eval-cheap-module-source-map'
    webpackConfig.output.pathinfo = true

    // Create new entries object with webpack-hot-middleware and react-hot-loader (if enabled)
    if(TASK_CONFIG.javascripts.hot && TASK_CONFIG.javascripts.hot.enabled !== false) {
      for (var key in TASK_CONFIG.javascripts.entries) {
        var entry = TASK_CONFIG.javascripts.entries[key]
        // TODO: To work in < node 6, prepend process.env.PWD + node_modules/
        const entries = []
        let middleware = 'webpack-hot-middleware/client?'

        if(TASK_CONFIG.javascripts.hot.reload !== false) {
          middleware+= '&reload=true'
        }

        if(TASK_CONFIG.javascripts.hot.noInfo) {
          middleware+= '&noInfo=true'
        }

        if(TASK_CONFIG.javascripts.hot.quiet) {
          middleware+= '&quiet=true'
        }

        if(TASK_CONFIG.javascripts.hot.react) {
          entries.push('react-hot-loader/patch')
        }

        TASK_CONFIG.javascripts.entries[key] = entries.concat(middleware).concat(entry)
      }

      webpackConfig.plugins.push(new webpack.HotModuleReplacementPlugin())
    }
    // Addtional loaders for dev
    webpackConfig.module.loaders = webpackConfig.module.loaders.concat(TASK_CONFIG.javascripts.developmentLoaders || [])
  }

  if(env !== 'test') {
    // Karma doesn't need entry points or output settings
    webpackConfig.entry = TASK_CONFIG.javascripts.entries

    webpackConfig.output.path = path.normalize(jsDest),
    webpackConfig.output.filename = filenamePattern,
    webpackConfig.output.publicPath = publicPath

    if(TASK_CONFIG.javascripts.extractSharedJs) {
      // Factor out common dependencies into a shared.js
      webpackConfig.plugins.push(
        new webpack.optimize.CommonsChunkPlugin({
          name: 'shared',
          filename: filenamePattern,
        })
      )
    }

    // Addtional loaders for tests
    webpackConfig.module.loaders = webpackConfig.module.loaders.concat(TASK_CONFIG.javascripts.testLoaders || [])
  }

  if(env === 'production') {
    if(rev) {
      webpackConfig.plugins.push(new webpackManifest(PATH_CONFIG.javascripts.dest, PATH_CONFIG.dest))
    }
    webpackConfig.plugins.push(
      new webpack.DefinePlugin({
        'process.env': {
          'NODE_ENV': JSON.stringify('production')
        }
      }),
      new webpack.optimize.DedupePlugin(),
      new webpack.optimize.UglifyJsPlugin(),
      new webpack.NoErrorsPlugin()
    )

    // Addtional loaders for production
    webpackConfig.module.loaders = webpackConfig.module.loaders.concat(TASK_CONFIG.javascripts.productionLoaders || [])
  }

  return webpackConfig
}
<|endoftext|>


<commit_before>Dash.namespace('Source.Graphite');

Dash.Source.Graphite = function(stat) {
  var stub = stat.source + "/render?target=" + encodeURI(stat.target);

  this.url = function(period) {          // how to get data
    return stub + "&from=" + period.from + "&format=json";
  };

  this.link = function(period) {         // link to the original data source
    return stub + "&from=" + period.from + "&height=600&width=800";
  };

  return this;
}

Dash.Source.Graphite.find = function(cfg, callback) {
  var source = cfg.source || "http://graphite",
      request = {
        url: source + '/metrics/find?format=completer&query=' + cfg.target,
        dataType: 'json'
      };

  return Dash.ajax(request)
    .done(function(data) {
      var metrics = data.metrics.filter(function(metric) {
        return metric.is_leaf == 1;
      }).map(function(metric) {
        return metric.path;
      });
      callback(metrics);
    });
};

Dash.Source.Graphite.prototype = {

  toSeries: function(data) {
    return data.map(function(metric) {
      return {
        name:  metric.target,
        data:  metric.datapoints.map(function(point) {
          return { x: point[1], y: point[0] };
        })
      }
    });
  },

  // return sparse series of epochs where x>0
  toEvents: function(data) {
    return data.map(function(metric) {
      return {
        target: metric.target,
        epochs: metric.datapoints.filter(function(point) {
          var x = point[0];
          return x > 0;
        }).map(function(point) {
          return point[1];
        })
      }
    });
  }
};
<commit_msg>graphite source now uses summarize to give sanity to long-period resolution<commit_after>Dash.namespace('Source.Graphite');

Dash.Source.Graphite = function(stat) {
  var stub = stat.source + "/render?target=";

  // choose a sane resolution by period length
  this.stepSize = function(length) {
    var step;
    if ( length <= 4*3600 ) {            // 4hour
      step = '10s';                      // likely default for graphite
    } else if ( length <= 12*3600 ) {    // 12hours
      step = '1min';
    } else if ( length <= 24*3600 ) {    // 1d
      step = '5min';
    } else if ( length <= 14*24*3600 ) { // 2weeks
      step = '1h';
    } else {
      step = '1d';
    }
    return step;
  };

  // return graphite function call to bucket data appropriately for period
  this.summarize = function(length) {
    var func = 'smartSummarize(' + stat.target + ',"' +
      this.stepSize(length)  + '","' + stat.display + '")';
    return encodeURI(func);
  };

  // how to get data
  this.url = function(period) {
    return stub + this.summarize(period.length) + "&from=" + period.from + "&format=json";
  };

  // link to the original data source
  var link = stub + encodeURI(stat.target) + "&height=600&width=800";
  this.link = function(period) {
    return link + "&from=" + period.from;
  };

  return this;
}

Dash.Source.Graphite.find = function(cfg, callback) {
  var source = cfg.source || "http://graphite",
      request = {
        url: source + '/metrics/find?format=completer&query=' + cfg.target,
        dataType: 'json'
      };

  return Dash.ajax(request)
    .done(function(data) {
      var metrics = data.metrics.filter(function(metric) {
        return metric.is_leaf == 1;
      }).map(function(metric) {
        return metric.path;
      });
      callback(metrics);
    });
};

Dash.Source.Graphite.prototype = {

  toSeries: function(data) {
    return data.map(function(metric) {
      return {
        name:  metric.target,
        data:  metric.datapoints.map(function(point) {
          return { x: point[1], y: point[0] };
        })
      }
    });
  },

  // return sparse series of epochs where x>0
  toEvents: function(data) {
    return data.map(function(metric) {
      return {
        target: metric.target,
        epochs: metric.datapoints.filter(function(point) {
          var x = point[0];
          return x > 0;
        }).map(function(point) {
          return point[1];
        })
      }
    });
  }
};
<|endoftext|>


<commit_before>function Range(first, last, step) {
    var sequence = [];

    this.forEach = function (callback) {
        sequence.forEach(callback);
        return this;
    };

    this.over = function (array) {
        sequence = array;
        return this;
    };

    if (first === undefined) {
        first = 0;
    }
    if (last === undefined) {
        // to make Range(10) produce [0, 1, 2, ..., 8, 9]
        last = first;
        first = 0;
    }
    if (!step) {
        // prevent 0-step ranges as they would create infinite loops
        // since the whole range sequence is created during range object construction
        step = 1;
    }

    for (var i = first; ((first < last) ? (i < last) : (i > last)); i += step) {
        sequence.push(i);
    }

    return this;
}

function range(first, last, step) {
    /** Simple range function.
     *
     *  Documentation by examples:
     *
     *      range(4)        -> [0, 1, 2, 3]
     *      range(1, 5)     -> [1, 2, 3, 4]
     *      range(0, 8, 2)  -> [0, 2, 4, 6]
     *
     *  The function does not return an array as such, but an object it returns may
     *  be used as one if the only thing needed is the .forEach() function.
     *
     */
    return (new Range(first, last, step));
}

/*
console.log('Range() demonstration code');

console.log('range(4).forEach(...): simple range');
range(4).forEach(function (item) { console.log(item); });

console.log();
console.log('range(4, 8).forEach(...): range with specified outer bounds');
range(4, 8).forEach(function (item) { console.log(item); });

console.log();
console.log('range(8, 16, 2).forEach(...): range with step');
range(8, 16, 2).forEach(function (item) { console.log(item); });

console.log();
console.log('range(22, 14, -2).forEach(...): range with negative step');
range(22, 14, -2).forEach(function (item) { console.log(item); });

console.log();
console.log('range(23, 27, 0).forEach(...): range with step evaluating to zero (0, false, null, undefined) is not legal, step is silently set to 1');
range(23, 27, 0).forEach(function (item) { console.log(item); });
*/
<commit_msg>Range.range(first, last, step) method<commit_after>function Range(first, last, step) {
    var sequence = [];

    this.forEach = function (callback) {
        sequence.forEach(callback);
        return this;
    };

    this.range = function (first, last, step) {
        if (first === undefined) {
            first = 0;
        }
        if (last === undefined) {
            // to make Range(10) produce [0, 1, 2, ..., 8, 9]
            last = first;
            first = 0;
        }
        if (!step) {
            // prevent 0-step ranges as they would create infinite loops
            // since the whole range sequence is created during range object construction
            step = 1;
        }

        sequence = [];
        for (var i = first; ((first < last) ? (i < last) : (i > last)); i += step) {
            sequence.push(i);
        }

        return this;
    };
    this.over = function (array) {
        sequence = array;
        return this;
    };

    if (first === undefined) {
        first = 0;
    }
    if (last === undefined) {
        // to make Range(10) produce [0, 1, 2, ..., 8, 9]
        last = first;
        first = 0;
    }
    if (!step) {
        // prevent 0-step ranges as they would create infinite loops
        // since the whole range sequence is created during range object construction
        step = 1;
    }

    for (var i = first; ((first < last) ? (i < last) : (i > last)); i += step) {
        sequence.push(i);
    }

    return this;
}

function range(first, last, step) {
    /** Simple range function.
     *
     *  Documentation by examples:
     *
     *      range(4)        -> [0, 1, 2, 3]
     *      range(1, 5)     -> [1, 2, 3, 4]
     *      range(0, 8, 2)  -> [0, 2, 4, 6]
     *
     *  The function does not return an array as such, but an object it returns may
     *  be used as one if the only thing needed is the .forEach() function.
     *
     */
    return (new Range(first, last, step));
}

/*
console.log('Range() demonstration code');

console.log('range(4).forEach(...): simple range');
range(4).forEach(function (item) { console.log(item); });

console.log();
console.log('range(4, 8).forEach(...): range with specified outer bounds');
range(4, 8).forEach(function (item) { console.log(item); });

console.log();
console.log('range(8, 16, 2).forEach(...): range with step');
range(8, 16, 2).forEach(function (item) { console.log(item); });

console.log();
console.log('range(22, 14, -2).forEach(...): range with negative step');
range(22, 14, -2).forEach(function (item) { console.log(item); });

console.log();
console.log('range(23, 27, 0).forEach(...): range with step evaluating to zero (0, false, null, undefined) is not legal, step is silently set to 1');
range(23, 27, 0).forEach(function (item) { console.log(item); });
*/
<|endoftext|>


<commit_before>
this.init = function(index, gameServer) {
  this.gameServer = gameServer;
this.index = index;
}

this.beforespawn = function (player) {
if (!player.auth) {
  player.frozen = true;
  if (!player.astage) player.astage = 0;
  if (player.astage == 0) {
    player.aname = player.name;
  var name = 'w = login';
  if (this.index.config.allowregister == 1) {
    name = name + ', Space = register';
  }
  if (this.index.config.requirelogin != 1) {
    name = name + ', q = playasguest';
  }
  player.name = name;
  } else if (player.astage == 1) {
    player.name = 'Username: (press w)';

  } else if (player.astage == 2) {
    player.un = player.name;
    player.name = 'pass: (press w)';

  } else if (player.astage == 3) {
    player.pa = player.name;
    player.name = 'Press w to confirm';
  } else if (player.astage == 5) {
    player.name = 'Username (press w)';

  } else if (player.astage == 6) {
    var ok = true;
    for (var i in this.gameServer.account) {
      if (this.gameServer.account[i].username == player.name) {
        ok = false
        break;
      }

    }
    if (ok) {
    player.pa = player.name;
    player.name = 'Pass: (pres w)';
    player.astage = 7;
    } else {
      player.name = 'Username taken (press w)';
      player.astage = 50;
    }

  } else if (player.astage == 8) {
    player.pass = player.name;
    player.astage = 9;
    var ac = {
      username: player.un,
      pass: player.pass,

    };
    this.gameServer.account.push(ac);

    player.name = 'Success!, Press w to login'
    player.astage = 50;
  }

  return true;
}
return true;

};
this.beforeeject = function(player) {
if (player.astage > -1 && player.astage < 3) {
  player.cells.forEach((cell)=>this.removeNode(cell));
  player.astage ++;
  return false;
} else if (player.astage == 3) {
  var ok = false;
  for (var i in this.gameServer.account) {
    var account = this.gameServer.account[i];
   if (account && account.pass == player.pa && account.un == account.username) {
     ok = true;
     player.accountid = i;
     break;
   }
  }
  if (!ok) {
    player.name = 'Wrong pass or username , press w';
    player.astage = 50;
  } else {
    player.name = 'Success, press w'
    player.astage = 4;
  }
  return false
} else if (player.astage == 4) {
  player.frozen = false;
  player.name = player.aname;
  player.astage = 100;
  return false
} else if (player.astage == 5) {
player.cells.forEach((cell)=>this.gameServer.removeNode(cell));
player.astage = 6;
} else if (player.astage == 50) {
  player.cells.forEach((cell)=>this.gameServer.removeNode(cell));
  player.astage = 0;
} else if (player.astage == 7) {
  player.cells.forEach((cell)=>this.gameServer.removeNode(cell));
  player.astage = 8;
  } else {
  return true;
}
return false;
};
this.beforesplit = function(player) {
if (player.astage == 0 && this.index.config.allowregister == 1) {
  player.cells.forEach((cell)=>this.gameServer.removeNode(cell));
  player.astage = 5;
} else {
  return true;
}
return false;
};
this.beforeq = function(player) {
  if (player.astage == 0 && this.index.config.requirelogin != 1) {
    player.frozen = false;
    player.name = player.aname;
    player.astage = 50
  } else if (player.astage > 0 && player.astage < 100) {
    player.cells.forEach((cell)=>this.gameServer.removeNode(cell));
  player.astage = 0;

  }

}
module.exports = this;

<commit_msg>Update auth.js<commit_after>
this.init = function(index, gameServer) {
  this.gameServer = gameServer;
this.index = index;
}

this.beforespawn = function (player,gameServer) {
if (!player.auth) {
  player.frozen = true;
  if (!player.astage) player.astage = 0;
  if (player.astage == 0) {
    player.aname = player.name;
  var name = 'w = login';
  if (this.index.config.allowregister == 1) {
    name = name + ', Space = register';
  }
  if (this.index.config.requirelogin != 1) {
    name = name + ', q = playasguest';
  }
  player.name = name;
  } else if (player.astage == 1) {
    player.name = 'Username: (press w)';

  } else if (player.astage == 2) {
    player.un = player.name;
    player.name = 'pass: (press w)';

  } else if (player.astage == 3) {
    player.pa = player.name;
    player.name = 'Press w to confirm';
  } else if (player.astage == 5) {
    player.name = 'Username (press w)';

  } else if (player.astage == 6) {
    var ok = true;
    for (var i in gameServer.account) {
      if (gameServer.account[i].username == player.name) {
        ok = false
        break;
      }

    }
    if (ok) {
    player.pa = player.name;
    player.name = 'Pass: (pres w)';
    player.astage = 7;
    } else {
      player.name = 'Username taken (press w)';
      player.astage = 50;
    }

  } else if (player.astage == 8) {
    player.pass = player.name;
    player.astage = 9;
    var ac = {
      username: player.un,
      pass: player.pass,

    };
    gameServer.account.push(ac);

    player.name = 'Success!, Press w to login'
    player.astage = 50;
  }

  return true;
}
return true;

};
this.beforeeject = function(player, gameServer) {
if (player.astage > -1 && player.astage < 3) {
  player.cells.forEach((cell)=>this.removeNode(cell));
  player.astage ++;
  return false;
} else if (player.astage == 3) {
  var ok = false;
  for (var i in gameServer.account) {
    var account = gameServer.account[i];
   if (account && account.pass == player.pa && account.un == account.username) {
     ok = true;
     player.accountid = i;
     break;
   }
  }
  if (!ok) {
    player.name = 'Wrong pass or username , press w';
    player.astage = 50;
  } else {
    player.name = 'Success, press w'
    player.astage = 4;
  }
  return false
} else if (player.astage == 4) {
  player.frozen = false;
  player.name = player.aname;
  player.astage = 100;
  return false
} else if (player.astage == 5) {
player.cells.forEach((cell)=>gameServer.removeNode(cell));
player.astage = 6;
} else if (player.astage == 50) {
  player.cells.forEach((cell)=>gameServer.removeNode(cell));
  player.astage = 0;
} else if (player.astage == 7) {
  player.cells.forEach((cell)=>gameServer.removeNode(cell));
  player.astage = 8;
  } else {
  return true;
}
return false;
};
this.beforesplit = function(player,gameServer) {
if (player.astage == 0 && this.index.config.allowregister == 1) {
  player.cells.forEach((cell)=>gameServer.removeNode(cell));
  player.astage = 5;
} else {
  return true;
}
return false;
};
this.beforeq = function(player, gameServer) {
  if (player.astage == 0 && this.index.config.requirelogin != 1) {
    player.frozen = false;
    player.name = player.aname;
    player.astage = 50
  } else if (player.astage > 0 && player.astage < 100) {
    player.cells.forEach((cell)=>gameServer.removeNode(cell));
  player.astage = 0;

  }

}
module.exports = this;

<|endoftext|>


<commit_before>/* jshint node: true */
require('dotenv').config({silent: false});

module.exports = function(environment) {
  var ENV = {
    modulePrefix: 'isp',
    environment: environment,
    rootURL: '/',
    locationType: 'auto',
    i18n: {
      defaultLocale: 'en'
    },
    EmberENV: {
      FEATURES: {
        // Here you can enable experimental features on an ember canary build
        // e.g. 'with-controller': true
      }
    },
    sentry: {
      dsn: process.env.SENTRY_DSN || '',
      cdn: 'https://cdn.ravenjs.com/3.5.1/ember/raven.min.js'
    },
    APP: {
      // Here you can pass flags/options to your application instance
      // when it is created
    }
  };

  ENV['ember-simple-auth'] = {
    authenticationRoute: 'participate.login',
    routeIfAlreadyAuthenticated: 'participate.survey'
  };

  if (environment === 'development') {
    // ENV.APP.LOG_RESOLVER = true;
    // ENV.APP.LOG_ACTIVE_GENERATION = true;
    // ENV.APP.LOG_TRANSITIONS = true;
    // ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
    // ENV.APP.LOG_VIEW_LOOKUPS = true;
  }
  ENV.JAMDB = {};

  if (environment === 'development') {
    ENV.JAMDB = {
      authorizer: 'jam-jwt',
      collection:'accounts',
      namespace: 'isp',
      url: 'http://localhost:1212'
    };
  }

  if (environment === 'staging' || environment === 'production') {
    ENV.JAMDB = {
      authorizer: 'jam-jwt',
      collection:'accounts',
      url: process.env.JAM_URL || 'https://staging-metadata.osf.io',
      namespace: 'isp'
    };
  }

  if (environment === 'test') {
    // Testem prefers this...
    ENV.locationType = 'none';

    // keep test console output quieter
    ENV.APP.LOG_ACTIVE_GENERATION = false;
    ENV.APP.LOG_VIEW_LOOKUPS = false;

    ENV.APP.rootElement = '#ember-testing';
  }

  if (environment === 'production') {

  }

  ENV.studyId = process.env.STUDY_ID;

  ENV.featureFlags = {
    // Whether to load existing expData into the exp-frames
    loadData: false,

    // Whether to validate survey forms
    validate: false,

    // Whether to redirect users who have already taken the study to an error page
    // Set to false to test study multiple times with the same account
    showStudyCompletedPage: false,

    // Whether to take the participant to the last page they were on
    // when they exited the study. If false, start from the beginning.
    continueSession: false
  };

  return ENV;
};
<commit_msg>Turn feature flags on<commit_after>/* jshint node: true */
require('dotenv').config({silent: false});

module.exports = function(environment) {
  var ENV = {
    modulePrefix: 'isp',
    environment: environment,
    rootURL: '/',
    locationType: 'auto',
    i18n: {
      defaultLocale: 'en'
    },
    EmberENV: {
      FEATURES: {
        // Here you can enable experimental features on an ember canary build
        // e.g. 'with-controller': true
      }
    },
    sentry: {
      dsn: process.env.SENTRY_DSN || '',
      cdn: 'https://cdn.ravenjs.com/3.5.1/ember/raven.min.js'
    },
    APP: {
      // Here you can pass flags/options to your application instance
      // when it is created
    }
  };

  ENV['ember-simple-auth'] = {
    authenticationRoute: 'participate.login',
    routeIfAlreadyAuthenticated: 'participate.survey'
  };

  if (environment === 'development') {
    // ENV.APP.LOG_RESOLVER = true;
    // ENV.APP.LOG_ACTIVE_GENERATION = true;
    // ENV.APP.LOG_TRANSITIONS = true;
    // ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
    // ENV.APP.LOG_VIEW_LOOKUPS = true;
  }
  ENV.JAMDB = {};

  if (environment === 'development') {
    ENV.JAMDB = {
      authorizer: 'jam-jwt',
      collection:'accounts',
      namespace: 'isp',
      url: 'http://localhost:1212'
    };
  }

  if (environment === 'staging' || environment === 'production') {
    ENV.JAMDB = {
      authorizer: 'jam-jwt',
      collection:'accounts',
      url: process.env.JAM_URL || 'https://staging-metadata.osf.io',
      namespace: 'isp'
    };
  }

  if (environment === 'test') {
    // Testem prefers this...
    ENV.locationType = 'none';

    // keep test console output quieter
    ENV.APP.LOG_ACTIVE_GENERATION = false;
    ENV.APP.LOG_VIEW_LOOKUPS = false;

    ENV.APP.rootElement = '#ember-testing';
  }

  if (environment === 'production') {

  }

  ENV.studyId = process.env.STUDY_ID;

  ENV.featureFlags = {
    // Whether to load existing expData into the exp-frames
    loadData: true,

    // Whether to validate survey forms
    validate: true,

    // Whether to redirect users who have already taken the study to an error page
    // Set to false to test study multiple times with the same account
    showStudyCompletedPage: true,

    // Whether to take the participant to the last page they were on
    // when they exited the study. If false, start from the beginning.
    continueSession: true
  };

  return ENV;
};
<|endoftext|>