<commit_before>'use strict';

/**
 * RequestHandler
 */

var request      = require('request'),
    log          = require('./log'),
    merge        = require('lodash.merge'),
    errorCodes   = require('./errorCodes'),
    EventHandler = require('./EventHandler');

module.exports = RequestHandler;

function RequestHandler(options) {
    options = options || {};

    this.sessionID      = null;
    this.startPath      = '/wd/hub';

    // Wdjs calls RequestHandler with `host` badly set
    // A host is an hostname+port
    if (options.host !== undefined) {
        options.hostname = options.host;
        delete options.host;
    }

    // default request options
    this.defaultOptions = {
        hostname: '127.0.0.1',
        port: 4444,
        protocol: 'http'
    };

    // add user specific attributes
    this.defaultOptions = merge(this.defaultOptions, options);

    // set auth from user and password configs
    if(this.defaultOptions.user && this.defaultOptions.key) {
        this.auth = {
            user: this.defaultOptions.user,
            pass: this.defaultOptions.key
        };

        delete this.defaultOptions.user;
        delete this.defaultOptions.key;
    }
};

/**
 * set session ID for the next request
 *
 * @param {Object} response  response data with header information
 */
RequestHandler.prototype.setSessionID = function(data,response) {
    this.sessionID = data.sessionId;

    // check if we got a session id
    if(!this.sessionID) {
        EventHandler.emit('error', {
            err: {
                code: 'NOSESSIONID',
                message: data.message
            },
            requestData: data,
            requestOptions: this.fullRequestOptions,
            response: response
        });
        return;
    }

    log('SET SESSION ID ' + this.sessionID);
};

    /**
     * merges default options with request options
     *
     * @param  {Object} requestOptions  request options
     */
RequestHandler.prototype.createOptions = function(requestOptions, data) {
    var url = require('url');
    var newOptions = {};

    newOptions.uri =
        this.defaultOptions.protocol + '://' +
        this.defaultOptions.hostname + ':' + this.defaultOptions.port +
        this.startPath +
        requestOptions.path.replace(':sessionId', this.sessionID || '')

    // send authentication credentials only when creating new session
    if (requestOptions.path === '/session' && this.auth !== undefined) {
        newOptions.auth = this.auth;
    }

    if (requestOptions.method) {
        newOptions.method = requestOptions.method;
    }

    newOptions.json = true;
    newOptions.followAllRedirects = true;

    // needed by any JAVA server dealing with json
    // thus selenium server. We should not have
    // to set charset on a json request
    newOptions.headers = {
        'content-type': 'application/json; charset=UTF-8'
    }

    if (Object.keys(data).length > 0) {
        // what we should be doing
        // newOptions.body = data
        // but wait for https://github.com/mikeal/request/issues/784
        // to be merged
        newOptions.body = JSON.stringify(data);
        newOptions.method = 'POST';
    }

    return newOptions;
};

/**
 * creates a http request with its given options and send the protocol
 * command to the webdriver server
 *
 * @param  {Object}   requestOptions  defines url, method and other request options
 * @param  {Object}   data            contains request data
 * @param  {Function} callback        gets fired if server got a response
 */
RequestHandler.prototype.create = function(requestOptions, data, callback) {
    if (typeof requestOptions === 'string') {
        requestOptions = {
            path: requestOptions
        }
    }

    if (typeof data === 'function') {
        callback = data;
        data = {};
    }

    this.fullRequestOptions = this.createOptions(requestOptions, data);

    EventHandler.emit('command', {
        method: this.fullRequestOptions.method || 'GET',
        uri: this.fullRequestOptions.uri,
        data: data
    });

    request(this.fullRequestOptions, function(err, response, body) {
        var error = null;

        if(err || (body && body.status !== 0)) {
            EventHandler.emit('error', {
                err: err,
                requestData: data,
                requestOptions: this.fullRequestOptions,
                response: response,
                body: body
            });

            error = {
                status: body.status,
                type: errorCodes[body.status] ? errorCodes[body.status].id : 'unknown',
                message: errorCodes[body.status] ? errorCodes[body.status].message : 'unknown',
                orgStatusMessage: body.value.message
            };
        }

        // if we dont have a session id we set it here, unless we
        // call commands that dont require session ids, for
        // example /sessions. The call to /sessions is not
        // connected to a session itself and it therefore doesnt
        // require it
        if(this.sessionID === null && this.fullRequestOptions.requiresSession !== false) {
            this.setSessionID(body,response);
        }

        if(body === undefined) {
            body = {
                status: 0,
                orgStatusMessage: errorCodes[0].message
            };
        }

        EventHandler.emit('result', {
            requestData: data,
            requestOptions: this.fullRequestOptions,
            response: response,
            body: body,
        });

        if (callback) {
            callback(error, error ? null : body);
        }

    }.bind(this));
};<commit_msg>emit event on session initialization - refs #137<commit_after>'use strict';

/**
 * RequestHandler
 */

var request      = require('request'),
    log          = require('./log'),
    merge        = require('lodash.merge'),
    errorCodes   = require('./errorCodes'),
    EventHandler = require('./EventHandler');

module.exports = RequestHandler;

function RequestHandler(options) {
    options = options || {};

    this.sessionID      = null;
    this.startPath      = '/wd/hub';

    // Wdjs calls RequestHandler with `host` badly set
    // A host is an hostname+port
    if (options.host !== undefined) {
        options.hostname = options.host;
        delete options.host;
    }

    // default request options
    this.defaultOptions = {
        hostname: '127.0.0.1',
        port: 4444,
        protocol: 'http'
    };

    // add user specific attributes
    this.defaultOptions = merge(this.defaultOptions, options);

    // set auth from user and password configs
    if(this.defaultOptions.user && this.defaultOptions.key) {
        this.auth = {
            user: this.defaultOptions.user,
            pass: this.defaultOptions.key
        };

        delete this.defaultOptions.user;
        delete this.defaultOptions.key;
    }
};

/**
 * set session ID for the next request
 *
 * @param {Object} response  response data with header information
 */
RequestHandler.prototype.setSessionID = function(body,response,data) {
    this.sessionID = body.sessionId;

    // check if we got a session id
    if(!this.sessionID) {
        EventHandler.emit('error', {
            err: {
                code: 'NOSESSIONID',
                message: body.message
            },
            requestData: body,
            requestOptions: this.fullRequestOptions,
            response: response
        });
        return;
    }

    EventHandler.emit('init', {
        sessionID: this.sessionID,
        options: body.value,
        desiredCapabilities: data.desiredCapabilities
    });

    log('SET SESSION ID ' + this.sessionID);
};

    /**
     * merges default options with request options
     *
     * @param  {Object} requestOptions  request options
     */
RequestHandler.prototype.createOptions = function(requestOptions, data) {
    var url = require('url');
    var newOptions = {};

    newOptions.uri =
        this.defaultOptions.protocol + '://' +
        this.defaultOptions.hostname + ':' + this.defaultOptions.port +
        this.startPath +
        requestOptions.path.replace(':sessionId', this.sessionID || '')

    // send authentication credentials only when creating new session
    if (requestOptions.path === '/session' && this.auth !== undefined) {
        newOptions.auth = this.auth;
    }

    if (requestOptions.method) {
        newOptions.method = requestOptions.method;
    }

    newOptions.json = true;
    newOptions.followAllRedirects = true;

    // needed by any JAVA server dealing with json
    // thus selenium server. We should not have
    // to set charset on a json request
    newOptions.headers = {
        'content-type': 'application/json; charset=UTF-8'
    }

    if (Object.keys(data).length > 0) {
        // what we should be doing
        // newOptions.body = data
        // but wait for https://github.com/mikeal/request/issues/784
        // to be merged
        newOptions.body = JSON.stringify(data);
        newOptions.method = 'POST';
    }

    return newOptions;
};

/**
 * creates a http request with its given options and send the protocol
 * command to the webdriver server
 *
 * @param  {Object}   requestOptions  defines url, method and other request options
 * @param  {Object}   data            contains request data
 * @param  {Function} callback        gets fired if server got a response
 */
RequestHandler.prototype.create = function(requestOptions, data, callback) {
    if (typeof requestOptions === 'string') {
        requestOptions = {
            path: requestOptions
        }
    }

    if (typeof data === 'function') {
        callback = data;
        data = {};
    }

    this.fullRequestOptions = this.createOptions(requestOptions, data);

    EventHandler.emit('command', {
        method: this.fullRequestOptions.method || 'GET',
        uri: this.fullRequestOptions.uri,
        data: data
    });

    request(this.fullRequestOptions, function(err, response, body) {
        var error = null;

        if(err || (body && body.status !== 0)) {
            EventHandler.emit('error', {
                err: err,
                requestData: data,
                requestOptions: this.fullRequestOptions,
                response: response,
                body: body
            });

            error = {
                status: body.status,
                type: errorCodes[body.status] ? errorCodes[body.status].id : 'unknown',
                message: errorCodes[body.status] ? errorCodes[body.status].message : 'unknown',
                orgStatusMessage: body.value.message
            };
        }

        // if we dont have a session id we set it here, unless we
        // call commands that dont require session ids, for
        // example /sessions. The call to /sessions is not
        // connected to a session itself and it therefore doesnt
        // require it
        if(this.sessionID === null && this.fullRequestOptions.requiresSession !== false) {
            this.setSessionID(body,response,data);
        }

        if(body === undefined) {
            body = {
                status: 0,
                orgStatusMessage: errorCodes[0].message
            };
        }

        EventHandler.emit('result', {
            requestData: data,
            requestOptions: this.fullRequestOptions,
            response: response,
            body: body,
        });

        if (callback) {
            callback(error, error ? null : body);
        }

    }.bind(this));
};<|endoftext|>


<commit_before>/* eslint-env mocha */
'use strict';

var expect = require('expect.js');

var nj = require('../../src');

describe('convolve', function () {
  it('should work on vectors', function () {
    var x = nj.float32([0, 0, 1, 2, 1, 0, 0]);
    var filter = [-1, 0, 1];
    var conv = nj.convolve(x, filter);
    expect(conv.round().tolist())
      .to.eql([-1, -2, 0, 2, 1]);
    expect(conv.dtype).to.equal('float32');
  });

  it('should work with 3x3 filter', function () {
    var x = nj.arange(5 * 5).reshape(5, 5);
    var filter = nj.arange(9).reshape(3, 3);
    expect(x.convolve(filter).round().tolist())
      .to.eql([
      [120, 156, 192],
      [300, 336, 372],
      [480, 516, 552]]);
  });

  it('should work with 2x3 filter', function () {
    var x = nj.arange(5 * 5).reshape(5, 5);
    var filter = nj.arange(6).reshape(2, 3);
    expect(x.convolve(filter).round().tolist())
      .to.eql([
      [26, 41, 56],
      [101, 116, 131],
      [176, 191, 206],
      [251, 266, 281]]);
  });

  it('should work with 3x2 filter', function () {
    var x = nj.arange(5 * 5).reshape(5, 5);
    var filter = nj.arange(6).reshape(3, 2);
    expect(x.convolve(filter).round().tolist())
      .to.eql([
      [41, 56, 71, 86],
      [116, 131, 146, 161],
      [191, 206, 221, 236]]);
  });

  it('should work with 3x3x1 filter', function () {
    var x = nj.arange(5 * 5).reshape(5, 5, 1);
    var filter = nj.arange(9).reshape(3, 3, 1);
    var c = x.convolve(filter);
    expect(c.shape).to.eql([5 - 3 + 1, 5 - 3 + 1, 1]);
    expect(c.tolist())
      .to.eql(nj.array([
      [120, 156, 192],
      [300, 336, 372],
      [480, 516, 552]]).reshape(3, 3, 1).tolist());
  });

  it('should work with 5x5 filter', function () {
    var x = nj.arange(25).reshape(5, 5);
    var filter = nj.arange(25).reshape(5, 5);
    expect(x.convolve(filter).tolist())
      .to.eql([[2300]]);
  });

  it('should work with 5x5x1 filter', function () {
    var x = nj.arange(25).reshape(5, 5, 1);
    var filter = nj.arange(25).reshape(5, 5, 1);
    var c = x.convolve(filter);
    expect(c.shape).to.eql([1, 1, 1]);
    expect(c.tolist())
      .to.eql([[[2300]]]);
  });

  it('should be fast with 3x3 filter even if X is large', function () {
    this.timeout(500);
    var N = 1000;
    var x = nj.arange(N * N).reshape(N, N);
    var filter = nj.arange(9).reshape(3, 3);
    x.convolve(filter);
  });

  it('should be fast with 3x3x1 filter even if X is large', function () {
    this.timeout(500);
    var N = 1000;
    var x = nj.arange(N * N).reshape(N, N, 1);
    var filter = nj.arange(9).reshape(3, 3, 1);
    x.convolve(filter);
  });

  it('should be fast with 5x5 filter even if X is large', function () {
    this.timeout(500);
    var N = 1000;
    var x = nj.arange(N * N).reshape(N, N);
    var filter = nj.arange(25).reshape(5, 5);
    x.convolve(filter);
  });

  it('should be fast with 5x5x1 filter even if X is large', function () {
    this.timeout(500);
    var N = 1000;
    var x = nj.arange(N * N).reshape(N, N, 1);
    var filter = nj.arange(25).reshape(5, 5, 1);
    x.convolve(filter);
  });
});

describe('fftconvolve', function () {
  it('should work on vectors', function () {
    var x = nj.float32([0, 0, 1, 2, 1, 0, 0]);
    var filter = [-1, 0, 1];
    var conv = nj.fftconvolve(x, filter);
    expect(conv.round().tolist())
      .to.eql([-1, -2, 0, 2, 1]);
    expect(conv.dtype).to.equal('float32');
  });

  it('should work with 3x3 filter', function () {
    var x = nj.arange(5 * 5).reshape(5, 5);
    var filter = nj.arange(9).reshape(3, 3);
    expect(x.fftconvolve(filter).round().tolist())
      .to.eql([
      [120, 156, 192],
      [300, 336, 372],
      [480, 516, 552]]);
  });
});
<commit_msg>increase timeout<commit_after>/* eslint-env mocha */
'use strict';

var expect = require('expect.js');

var nj = require('../../src');

describe('convolve', function () {
  it('should work on vectors', function () {
    var x = nj.float32([0, 0, 1, 2, 1, 0, 0]);
    var filter = [-1, 0, 1];
    var conv = nj.convolve(x, filter);
    expect(conv.round().tolist())
      .to.eql([-1, -2, 0, 2, 1]);
    expect(conv.dtype).to.equal('float32');
  });

  it('should work with 3x3 filter', function () {
    var x = nj.arange(5 * 5).reshape(5, 5);
    var filter = nj.arange(9).reshape(3, 3);
    expect(x.convolve(filter).round().tolist())
      .to.eql([
      [120, 156, 192],
      [300, 336, 372],
      [480, 516, 552]]);
  });

  it('should work with 2x3 filter', function () {
    var x = nj.arange(5 * 5).reshape(5, 5);
    var filter = nj.arange(6).reshape(2, 3);
    expect(x.convolve(filter).round().tolist())
      .to.eql([
      [26, 41, 56],
      [101, 116, 131],
      [176, 191, 206],
      [251, 266, 281]]);
  });

  it('should work with 3x2 filter', function () {
    var x = nj.arange(5 * 5).reshape(5, 5);
    var filter = nj.arange(6).reshape(3, 2);
    expect(x.convolve(filter).round().tolist())
      .to.eql([
      [41, 56, 71, 86],
      [116, 131, 146, 161],
      [191, 206, 221, 236]]);
  });

  it('should work with 3x3x1 filter', function () {
    var x = nj.arange(5 * 5).reshape(5, 5, 1);
    var filter = nj.arange(9).reshape(3, 3, 1);
    var c = x.convolve(filter);
    expect(c.shape).to.eql([5 - 3 + 1, 5 - 3 + 1, 1]);
    expect(c.tolist())
      .to.eql(nj.array([
      [120, 156, 192],
      [300, 336, 372],
      [480, 516, 552]]).reshape(3, 3, 1).tolist());
  });

  it('should work with 5x5 filter', function () {
    var x = nj.arange(25).reshape(5, 5);
    var filter = nj.arange(25).reshape(5, 5);
    expect(x.convolve(filter).tolist())
      .to.eql([[2300]]);
  });

  it('should work with 5x5x1 filter', function () {
    var x = nj.arange(25).reshape(5, 5, 1);
    var filter = nj.arange(25).reshape(5, 5, 1);
    var c = x.convolve(filter);
    expect(c.shape).to.eql([1, 1, 1]);
    expect(c.tolist())
      .to.eql([[[2300]]]);
  });

  it('should be fast with 3x3 filter even if X is large', function () {
    this.timeout(1000);
    var N = 1000;
    var x = nj.arange(N * N).reshape(N, N);
    var filter = nj.arange(9).reshape(3, 3);
    x.convolve(filter);
  });

  it('should be fast with 3x3x1 filter even if X is large', function () {
    this.timeout(1000);
    var N = 1000;
    var x = nj.arange(N * N).reshape(N, N, 1);
    var filter = nj.arange(9).reshape(3, 3, 1);
    x.convolve(filter);
  });

  it('should be fast with 5x5 filter even if X is large', function () {
    this.timeout(1000);
    var N = 1000;
    var x = nj.arange(N * N).reshape(N, N);
    var filter = nj.arange(25).reshape(5, 5);
    x.convolve(filter);
  });

  it('should be fast with 5x5x1 filter even if X is large', function () {
    this.timeout(1000);
    var N = 1000;
    var x = nj.arange(N * N).reshape(N, N, 1);
    var filter = nj.arange(25).reshape(5, 5, 1);
    x.convolve(filter);
  });
});

describe('fftconvolve', function () {
  it('should work on vectors', function () {
    var x = nj.float32([0, 0, 1, 2, 1, 0, 0]);
    var filter = [-1, 0, 1];
    var conv = nj.fftconvolve(x, filter);
    expect(conv.round().tolist())
      .to.eql([-1, -2, 0, 2, 1]);
    expect(conv.dtype).to.equal('float32');
  });

  it('should work with 3x3 filter', function () {
    var x = nj.arange(5 * 5).reshape(5, 5);
    var filter = nj.arange(9).reshape(3, 3);
    expect(x.fftconvolve(filter).round().tolist())
      .to.eql([
      [120, 156, 192],
      [300, 336, 372],
      [480, 516, 552]]);
  });
});
<|endoftext|>


<commit_before>const
  _URL__GRUNT_CONFIG_FILE = './config/grunt.json',
  _URL__NPM_MANIFEST_FILE = './package.json';

var
  _gruntRegisterTasks = require('grunt-register-tasks'),
  _loadGruntTasks = require('load-grunt-tasks'),
  _timeGrunt = require('time-grunt');

module.exports = function ( $grunt ) {

    var

      _$grunt__file = $grunt.file,
      _$grunt__file__readJSON = _$grunt__file.readJSON,

      _plugins = [
          'grunt-contrib-*',
          'grunt-easy-nodefy',
          'grunt-jsonlint'
        ],

      _config = {
          'cfg': _$grunt__file__readJSON( _URL__GRUNT_CONFIG_FILE ),
          'clean': {
              'dist': '<%= cfg.PATH__DIST %>'
            },
          'copy': {
              'src': {
                  'cwd': '<%= cfg.PATH__SRC %>',
                  'dest': '<%= cfg.PATH__DIST__AMD %>',
                  'expand': true,
                  'src': '<%= cfg.GLOB__JS__RECURSIVE %>'
                }
            },
          'jsonlint': {
              'config': '<%= cfg.PATH__CONFIG %>/<%= cfg.GLOB__JSON__RECURSIVE %>',
              'manifests': '<%= cfg.PATH__ROOT %>/<%= cfg.GLOB__MANIFESTS %>'
            },
          'nodefy': {
              'src': {
                  'cwd': '<%= cfg.PATH__SRC %>',
                  'dest': '<%= cfg.PATH__DIST__CJS %>',
                  'expand': true,
                  'src': '<%= cfg.GLOB__JS__RECURSIVE %>'
                }
            },
          'pkg': _$grunt__file__readJSON( _URL__NPM_MANIFEST_FILE )
        },

      _tasks = {
          'build': [
              'default',
              'clean',
              'copy',
              'nodefy'
            ],
          'default': [
              'jsonlint'
            ],
        };

    _timeGrunt( $grunt ),

    $grunt.initConfig( _config ),

    _loadGruntTasks(
      $grunt,
      {
        pattern: _plugins,
        scope: 'devDependencies'
      }
    ),

    _gruntRegisterTasks(
      $grunt,
      _tasks
    );

  };<commit_msg>chore(grunt): add string-replace task<commit_after>const
  _URL__GRUNT_CONFIG_FILE = './config/grunt.json',
  _URL__NPM_MANIFEST_FILE = './package.json';

var
  _gruntRegisterTasks = require('grunt-register-tasks'),
  _loadGruntTasks = require('load-grunt-tasks'),
  _timeGrunt = require('time-grunt');

module.exports = function ( $grunt ) {

    var

      _$grunt__file = $grunt.file,
      _$grunt__file__readJSON = _$grunt__file.readJSON,

      _plugins = [
          'grunt-contrib-*',
          'grunt-easy-nodefy',
          'grunt-jsonlint',
          'grunt-string-replace'
        ],

      _config = {
          'cfg': _$grunt__file__readJSON( _URL__GRUNT_CONFIG_FILE ),
          'clean': {
              'dist': '<%= cfg.PATH__DIST %>'
            },
          'copy': {
              'src': {
                  'cwd': '<%= cfg.PATH__SRC %>',
                  'dest': '<%= cfg.PATH__DIST__AMD %>',
                  'expand': true,
                  'src': '<%= cfg.GLOB__JS__RECURSIVE %>'
                }
            },
          'jsonlint': {
              'config': '<%= cfg.PATH__CONFIG %>/<%= cfg.GLOB__JSON__RECURSIVE %>',
              'manifests': '<%= cfg.PATH__ROOT %>/<%= cfg.GLOB__MANIFESTS %>'
            },
          'nodefy': {
              'src': {
                  'cwd': '<%= cfg.PATH__SRC %>',
                  'dest': '<%= cfg.PATH__DIST__CJS %>',
                  'expand': true,
                  'src': '<%= cfg.GLOB__JS__RECURSIVE %>'
                }
            },
          'string-replace': {
              'src': {
                  'files': [
                      {
                        'cwd': '<%= cfg.PATH__DIST %>',
                        'dest': '<%= cfg.PATH__DIST %>',
                        'expand': true,
                        'src': '<%= cfg.GLOB__INDEX_JS__RECURSIVE %>'
                      }
                    ],
                  'options': {
                      'replacements': [
                          {
                            'pattern': /<%= pkg\.version %>/g,
                            'replacement': '<%= pkg.version %>'
                          }
                        ]
                    }
                }
            },
          'pkg': _$grunt__file__readJSON( _URL__NPM_MANIFEST_FILE )
        },

      _tasks = {
          'build': [
              'default',
              'clean',
              'copy',
              'nodefy',
              'string-replace'
            ],
          'default': [
              'jsonlint'
            ],
        };

    _timeGrunt( $grunt ),

    $grunt.initConfig( _config ),

    _loadGruntTasks(
      $grunt,
      {
        pattern: _plugins,
        scope: 'devDependencies'
      }
    ),

    _gruntRegisterTasks(
      $grunt,
      _tasks
    );

  };<|endoftext|>


<commit_before>/* global describe, it, before, after */
'use strict';

const path = require('path');
const lint = require('mocha-eslint');
const should = require('should');
const session = require('express-session');
const FirebaseStore = require(path.normalize(`${__dirname}/../lib/connect-session-firebase.js`))(session);

require('dotenv').config({ silent: true });

const store = new FirebaseStore({
  database: {
    serviceAccount: process.env.FIREBASE_SERVICE_ACCOUNT,
    databaseURL: process.env.FIREBASE_DATABASE_URL
  }
});

describe('FirebaseStore', function () {
  this.timeout(10000);

  after(() => {
    store.clear();
  });

  lint(['**/*.js', '!node_modules/**']);

  describe('Instantiation', () => {
    it('should be able to be created', () => {
      store.should.be.an.instanceOf(FirebaseStore);
    });
  });

  describe('Setting', () => {
    it('should set data correctly', done => {
      store.set('1234_#$[]', {
        name: 'tj',
        cookie: {
          maxAge: 2000
        }
      }, (err, res) => {
        if (err) throw err;

        done();
      });
    });
  });

  describe('Getting', () => {
    before(() => {
      store.set('1234', {
        name: 'tj',
        cookie: {
          maxAge: 2000
        }
      }, () => {});
    });

    it('should get data correctly', done => {
      store.get('1234', (err, res) => {
        if (err) throw err;

        res.name.should.eql('tj');
        res.cookie.should.eql({
          maxAge: 2000
        });

        done();
      });
    });
  });

  describe('Destroying', () => {
    before(() => {
      store.set('12345', {
        name: 'tj',
        cookie: {
          maxAge: 2000
        }
      }, () => {});
    });

    it('should destroy data correctly', done => {
      store.destroy('12345', (err, res) => {
        if (err) throw err;

        store.get('12345', (err, res) => {
          if (err) throw err;

          should.not.exist(res);

          done();
        });
      });
    });
  });

  describe('Clearing', () => {
    before(() => {
      store.set('abcd', {
        name: 'tj',
        cookie: {
          maxAge: 2000
        }
      }, () => {});

      store.set('abcdef', {
        name: 'tj',
        cookie: {
          maxAge: 2000
        }
      }, () => {});
    });

    it('should clear sessions correctly', done => {
      store.clear((err, res) => {
        if (err) throw err;

        store.get('abcd', (err, res) => {
          if (err) throw err;

          should.not.exist(res);

          store.get('abcdef', (err, res) => {
            if (err) throw err;

            should.not.exist(res);

            done();
          });
        });
      });
    });
  });

  describe('Reaping', () => {
    before(done => {
      store.set('abcd', {
        name: 'tj',
        cookie: {
          maxAge: -2000
        }
      }, done);
    });

    it('should reap data correctly', done => {
      store.reap((err, res) => {
        if (err) throw err;

        store.get('abcd', (err, res) => {
          if (err) throw err;

          should.not.exist(res);

          done();
        });
      });
    });
  });

  describe('Touching', () => {
    before(done => {
      store.set('abcd', {
        name: 'tj',
        cookie: {
          maxAge: 2000
        }
      }, done);
    });

    it('should touch data correctly', done => {
      store.touch('abcd', {
        name: 'bn',
        cookie: {
          maxAge: 3000
        }
      }, function (err) {
        if (err) throw err;

        store.get('abcd', (err, res) => {
          if (err) throw err;

          res.name.should.eql('tj');
          res.cookie.should.eql({
            maxAge: 3000
          });

          done();
        });
      });
    });
  });
});
<commit_msg>Move eslint to Code Standards test<commit_after>/* global describe, it, before, after */
'use strict';

const path = require('path');
const lint = require('mocha-eslint');
const should = require('should');
const session = require('express-session');
const FirebaseStore = require(path.normalize(`${__dirname}/../lib/connect-session-firebase.js`))(session);

require('dotenv').config({ silent: true });

const store = new FirebaseStore({
  database: {
    serviceAccount: process.env.FIREBASE_SERVICE_ACCOUNT,
    databaseURL: process.env.FIREBASE_DATABASE_URL
  }
});

describe('Code Standards', function () {
  lint(['**/*.js', '!node_modules/**']);
});

describe('FirebaseStore', function () {
  this.timeout(10000);

  after(() => {
    store.clear();
  });

  describe('Instantiation', () => {
    it('should be able to be created', () => {
      store.should.be.an.instanceOf(FirebaseStore);
    });
  });

  describe('Setting', () => {
    it('should set data correctly', done => {
      store.set('1234_#$[]', {
        name: 'tj',
        cookie: {
          maxAge: 2000
        }
      }, (err, res) => {
        if (err) throw err;

        done();
      });
    });
  });

  describe('Getting', () => {
    before(() => {
      store.set('1234', {
        name: 'tj',
        cookie: {
          maxAge: 2000
        }
      }, () => {});
    });

    it('should get data correctly', done => {
      store.get('1234', (err, res) => {
        if (err) throw err;

        res.name.should.eql('tj');
        res.cookie.should.eql({
          maxAge: 2000
        });

        done();
      });
    });
  });

  describe('Destroying', () => {
    before(() => {
      store.set('12345', {
        name: 'tj',
        cookie: {
          maxAge: 2000
        }
      }, () => {});
    });

    it('should destroy data correctly', done => {
      store.destroy('12345', (err, res) => {
        if (err) throw err;

        store.get('12345', (err, res) => {
          if (err) throw err;

          should.not.exist(res);

          done();
        });
      });
    });
  });

  describe('Clearing', () => {
    before(() => {
      store.set('abcd', {
        name: 'tj',
        cookie: {
          maxAge: 2000
        }
      }, () => {});

      store.set('abcdef', {
        name: 'tj',
        cookie: {
          maxAge: 2000
        }
      }, () => {});
    });

    it('should clear sessions correctly', done => {
      store.clear((err, res) => {
        if (err) throw err;

        store.get('abcd', (err, res) => {
          if (err) throw err;

          should.not.exist(res);

          store.get('abcdef', (err, res) => {
            if (err) throw err;

            should.not.exist(res);

            done();
          });
        });
      });
    });
  });

  describe('Reaping', () => {
    before(done => {
      store.set('abcd', {
        name: 'tj',
        cookie: {
          maxAge: -2000
        }
      }, done);
    });

    it('should reap data correctly', done => {
      store.reap((err, res) => {
        if (err) throw err;

        store.get('abcd', (err, res) => {
          if (err) throw err;

          should.not.exist(res);

          done();
        });
      });
    });
  });

  describe('Touching', () => {
    before(done => {
      store.set('abcd', {
        name: 'tj',
        cookie: {
          maxAge: 2000
        }
      }, done);
    });

    it('should touch data correctly', done => {
      store.touch('abcd', {
        name: 'bn',
        cookie: {
          maxAge: 3000
        }
      }, function (err) {
        if (err) throw err;

        store.get('abcd', (err, res) => {
          if (err) throw err;

          res.name.should.eql('tj');
          res.cookie.should.eql({
            maxAge: 3000
          });

          done();
        });
      });
    });
  });
});
<|endoftext|>


<commit_before>/*jshint -W030, -W020 */

DEBUG = !!process.env.VELOCITY_DEBUG;

(function () {

  'use strict';

  var path = Npm.require('path');

  var FRAMEWORK_NAME  = 'cucumber',
      FRAMEWORK_REGEX = '^tests/' + FRAMEWORK_NAME + '/((?!node_modules/).)+\\.(feature|js|coffee|litcoffee|coffee\\.md)$',
      SAMPLE_TESTS    = [{
        contents: Assets.getText(path.join('src', 'sample-tests', 'feature.feature')),
        path: path.join(FRAMEWORK_NAME, 'features', 'sample.feature')
      }, {
        contents: Assets.getText(path.join('src', 'sample-tests', 'steps.js')),
        path: path.join(FRAMEWORK_NAME, 'features', 'step_definitions', 'sample_steps.js')
      }, {
        contents: Assets.getText(path.join('src', 'sample-tests', 'fixture.js')),
        path: path.join(FRAMEWORK_NAME, 'fixtures', 'my_fixture.js')
      }, {
        contents: Assets.getText(path.join('src', 'sample-tests', 'package.json')),
        path: path.join(FRAMEWORK_NAME, 'package.json')
      }];

  if (!!process.env.INSTALL_DEPENDENCIES) {
    _installDependencies();
  }

  if (process.env.NODE_ENV !== 'development' || process.env.IS_MIRROR ||
    process.env[FRAMEWORK_NAME.toUpperCase()] === '0' || process.env.VELOCITY === '0') {
    return;
  }

  DEBUG && console.log('[xolvio:cucumber] Cucumber hub is loading');

  if (Velocity && Velocity.registerTestingFramework) {
    Velocity.registerTestingFramework(FRAMEWORK_NAME, {
      regex: FRAMEWORK_REGEX,
      sampleTestGenerator: function () { return SAMPLE_TESTS; }
    });
  }

  Meteor.methods({
    'cucumber/run': function () {
      this.unblock();
      var mirror = DDP.connect(VelocityMirrors.findOne({framework: 'cucumber'}).host);
      mirror.call('runAll', function () {
        mirror.disconnect();
      });
    }
  });

  Velocity.startup(function () {
    Meteor.call('velocity/mirrors/request', {
      framework: FRAMEWORK_NAME,
      args: ['--raw-logs'],
      testsPath: path.join(FRAMEWORK_NAME, 'fixtures'),
      nodes: process.env.CUCUMBER_NODES ? parseInt(process.env.CUCUMBER_NODES) : 1
    });

    if (process.env.CUCUMBER_TAIL) {
      _tailCucumberLogs();
    }

    var initOnce = _.once(Meteor.bindEnvironment(_init));
    VelocityMirrors.find({framework: FRAMEWORK_NAME, state: 'ready'}).observe({
      added: initOnce,
      changed: initOnce
    });
  });

  function _init () {

    if (!!process.env.CUCUMBER_NODES) {

      var debouncedRun = _.debounce(Meteor.bindEnvironment(_run), 600);
      VelocityTestFiles.find({targetFramework: FRAMEWORK_NAME}).observeChanges({
        added: debouncedRun,
        removed: debouncedRun,
        changed: debouncedRun
      });
      process.on('SIGUSR2', Meteor.bindEnvironment(debouncedRun));
      process.on('message', Meteor.bindEnvironment(function (message) {
        if (message.refresh && message.refresh === 'client') {
          debouncedRun();
        }
      }));

    }
  }

  function _tailCucumberLogs () {

    var cucumberLogFilePath = path.join(process.env.PWD, '.meteor', 'local', 'log', 'cucumber.log')
    var Tail = Npm.require('tail-forever');
    var tail = new Tail(cucumberLogFilePath, {});

    tail.on('line', function (data) {
      console.log('[cucumber.log]', data);
      if (data.indexOf('Exiting cucumber') !== -1) {
        tail.unwatch();
      }
    });

    tail.on('error', function (error) {
      console.error('[cucumber.log]', error);
    });

  }

  function _run (id, changes) {

    if (changes && changes.status) {
      // one of the files has changed status. good time to check if all files are done
      if (VelocityTestFiles.find({targetFramework: FRAMEWORK_NAME, status: 'DONE'}).count ===
        VelocityTestFiles.find({targetFramework: FRAMEWORK_NAME}).count) {
        Meteor.call('velocity/reports/completed', {framework: FRAMEWORK_NAME});
      }
      return;
    }

    Meteor.call('velocity/reports/reset', {framework: FRAMEWORK_NAME});

    // set all file statuses so mirrors can start working on files
    VelocityTestFiles.update(
      {targetFramework: FRAMEWORK_NAME, relativePath: /\.feature$/},
      {$set: {status: 'TODO'}},
      {multi: true}
    );

  }

  function _installDependencies () {
    DEBUG && console.log('[xolvio:cucumber] Attempting to install chimp dependencies');
    if (DEBUG) {
      process.env['chimp.debug'] = true;
    }
    Meteor.wrapAsync(Npm.require('chimp').install)();
  }

})();
<commit_msg>Fixes asset paths<commit_after>/*jshint -W030, -W020 */

DEBUG = !!process.env.VELOCITY_DEBUG;

(function () {

  'use strict';

  var path = Npm.require('path');

  var FRAMEWORK_NAME  = 'cucumber',
      FRAMEWORK_REGEX = '^tests/' + FRAMEWORK_NAME + '/((?!node_modules/).)+\\.(feature|js|coffee|litcoffee|coffee\\.md)$',
      SAMPLE_TESTS    = [{
        contents: Assets.getText(path.join('meteor', 'src', 'sample-tests', 'feature.feature')),
        path: path.join(FRAMEWORK_NAME, 'features', 'sample.feature')
      }, {
        contents: Assets.getText(path.join('meteor', 'src', 'sample-tests', 'steps.js')),
        path: path.join(FRAMEWORK_NAME, 'features', 'step_definitions', 'sample_steps.js')
      }, {
        contents: Assets.getText(path.join('meteor', 'src', 'sample-tests', 'fixture.js')),
        path: path.join(FRAMEWORK_NAME, 'fixtures', 'my_fixture.js')
      }, {
        contents: Assets.getText(path.join('meteor', 'src', 'sample-tests', 'package.json')),
        path: path.join(FRAMEWORK_NAME, 'package.json')
      }];

  if (!!process.env.INSTALL_DEPENDENCIES) {
    _installDependencies();
  }

  if (process.env.NODE_ENV !== 'development' || process.env.IS_MIRROR ||
    process.env[FRAMEWORK_NAME.toUpperCase()] === '0' || process.env.VELOCITY === '0') {
    return;
  }

  DEBUG && console.log('[xolvio:cucumber] Cucumber hub is loading');

  if (Velocity && Velocity.registerTestingFramework) {
    Velocity.registerTestingFramework(FRAMEWORK_NAME, {
      regex: FRAMEWORK_REGEX,
      sampleTestGenerator: function () { return SAMPLE_TESTS; }
    });
  }

  Meteor.methods({
    'cucumber/run': function () {
      this.unblock();
      var mirror = DDP.connect(VelocityMirrors.findOne({framework: 'cucumber'}).host);
      mirror.call('runAll', function () {
        mirror.disconnect();
      });
    }
  });

  Velocity.startup(function () {
    Meteor.call('velocity/mirrors/request', {
      framework: FRAMEWORK_NAME,
      args: ['--raw-logs'],
      testsPath: path.join(FRAMEWORK_NAME, 'fixtures'),
      nodes: process.env.CUCUMBER_NODES ? parseInt(process.env.CUCUMBER_NODES) : 1
    });

    if (process.env.CUCUMBER_TAIL) {
      _tailCucumberLogs();
    }

    var initOnce = _.once(Meteor.bindEnvironment(_init));
    VelocityMirrors.find({framework: FRAMEWORK_NAME, state: 'ready'}).observe({
      added: initOnce,
      changed: initOnce
    });
  });

  function _init () {

    if (!!process.env.CUCUMBER_NODES) {

      var debouncedRun = _.debounce(Meteor.bindEnvironment(_run), 600);
      VelocityTestFiles.find({targetFramework: FRAMEWORK_NAME}).observeChanges({
        added: debouncedRun,
        removed: debouncedRun,
        changed: debouncedRun
      });
      process.on('SIGUSR2', Meteor.bindEnvironment(debouncedRun));
      process.on('message', Meteor.bindEnvironment(function (message) {
        if (message.refresh && message.refresh === 'client') {
          debouncedRun();
        }
      }));

    }
  }

  function _tailCucumberLogs () {

    var cucumberLogFilePath = path.join(process.env.PWD, '.meteor', 'local', 'log', 'cucumber.log')
    var Tail = Npm.require('tail-forever');
    var tail = new Tail(cucumberLogFilePath, {});

    tail.on('line', function (data) {
      console.log('[cucumber.log]', data);
      if (data.indexOf('Exiting cucumber') !== -1) {
        tail.unwatch();
      }
    });

    tail.on('error', function (error) {
      console.error('[cucumber.log]', error);
    });

  }

  function _run (id, changes) {

    if (changes && changes.status) {
      // one of the files has changed status. good time to check if all files are done
      if (VelocityTestFiles.find({targetFramework: FRAMEWORK_NAME, status: 'DONE'}).count ===
        VelocityTestFiles.find({targetFramework: FRAMEWORK_NAME}).count) {
        Meteor.call('velocity/reports/completed', {framework: FRAMEWORK_NAME});
      }
      return;
    }

    Meteor.call('velocity/reports/reset', {framework: FRAMEWORK_NAME});

    // set all file statuses so mirrors can start working on files
    VelocityTestFiles.update(
      {targetFramework: FRAMEWORK_NAME, relativePath: /\.feature$/},
      {$set: {status: 'TODO'}},
      {multi: true}
    );

  }

  function _installDependencies () {
    DEBUG && console.log('[xolvio:cucumber] Attempting to install chimp dependencies');
    if (DEBUG) {
      process.env['chimp.debug'] = true;
    }
    Meteor.wrapAsync(Npm.require('chimp').install)();
  }

})();
<|endoftext|>


<commit_before>import React from 'react';
import ReactDOM from 'react-dom';
import './bootstrap.css';
import './index.css';

import PropTypes from "prop-types";
import ReactAudioPlayer from 'react-audio-player';
import axios from "axios";

class AvailableDatalist extends React.Component {
  render() {
    console.log("props during render songs")
    console.log(this.props)
    var ret = []
    if(this.props.song_set[0] !== 0){
      ret = this.props.song_set.map(c =>

          {c.songName[0]}
          {c.album}
          {c.author}
          {c.date}

      )
    }else{
      ret[0] =
loading...

    }

    console.log("ret nach bearbeitung")
    console.log(ret)

    return(

            Songname
            Album
            Author
            Date

          {ret}

    )
  }
}

AvailableDatalist.propTypes = {
  song_set: PropTypes.array.isRequired
};

class SongBoard extends React.Component {
	state = {
	  song_set: [0:{name:"none", album:"none", author:"none"}]
	};

	renderSongs(){
		console.log("button was clicked")
	}

	componentDidMount() {
		console.log("current location")
		console.log(window.location.hostname)
	  axios
	  .get("http://" + window.location.hostname + ":8000/album/")
	  .then(response => {
	    const song_set = response.data.map(c => {

	      return{
	        songName: c.song_set.map(d => {return(d.name)}),
	        album: c.name,
	        author: c.author,
	        date: c.release_date
	      };
	    });

	    const newState = Object.assign({}, this.state, {
	          song_set: song_set
	    });
	    this.setState(newState);
	    console.log("state after api request")
	    console.log(this.state)

	  })
	  .catch(error => console.log(error));

	}

  render() {

    return(

							    <input type="radio" name="options" id="option1" autoComplete="off" defaultChecked={true} />
										Songs

							    <input type="radio" name="options" id="option2" autoComplete="off" />
										Album

	          <AvailableDatalist song_set={this.state.song_set}/> {/*songs={this.state.contacts}*/}

						playlist

    )
  }
}

class Player extends React.Component {
  render() {
    return(
      <ReactAudioPlayer
        src="my_audio_file.ogg"
        autoPlay
        controls
      />
    )
  }
}

class Site extends React.Component {
  render() {
    return (

          <Player />

          <SongBoard />

    )
  }
}

ReactDOM.render(
  <Site />,
  document.getElementById('root')
);
<commit_msg>button click test<commit_after>import React from 'react';
import ReactDOM from 'react-dom';
import './bootstrap.css';
import './index.css';

import PropTypes from "prop-types";
import ReactAudioPlayer from 'react-audio-player';
import axios from "axios";

class AvailableDatalist extends React.Component {
  render() {
    console.log("props during render songs")
    console.log(this.props)
    var ret = []
    if(this.props.song_set[0] !== 0){
      ret = this.props.song_set.map(c =>

          {c.songName[0]}
          {c.album}
          {c.author}
          {c.date}

      )
    }else{
      ret[0] =
loading...

    }

    console.log("ret nach bearbeitung")
    console.log(ret)

    return(

            Songname
            Album
            Author
            Date

          {ret}

    )
  }
}

AvailableDatalist.propTypes = {
  song_set: PropTypes.array.isRequired
};

class SongBoard extends React.Component {
	state = {
	  song_set: [0:{name:"none", album:"none", author:"none"}]
	};

	renderSongs(){
		console.log("button was clicked")
	}

	componentDidMount() {
		console.log("current location")
		console.log(window.location.hostname)
	  axios
	  .get("http://" + window.location.hostname + ":8000/album/")
	  .then(response => {
	    const song_set = response.data.map(c => {

	      return{
	        songName: c.song_set.map(d => {return(d.name)}),
	        album: c.name,
	        author: c.author,
	        date: c.release_date
	      };
	    });

	    const newState = Object.assign({}, this.state, {
	          song_set: song_set
	    });
	    this.setState(newState);
	    console.log("state after api request")
	    console.log(this.state)

	  })
	  .catch(error => console.log(error));

	}

  render() {

    return(

							    <input type="radio" name="options" id="option1" autoComplete="off" defaultChecked={true} />
										Songs

							    <input type="radio" name="options" id="option2" autoComplete="off" />
										Album

	          <AvailableDatalist song_set={this.state.song_set}/> {/*songs={this.state.contacts}*/}

						playlist

    )
  }
}

class Player extends React.Component {
  render() {
    return(
      <ReactAudioPlayer
        src="my_audio_file.ogg"
        autoPlay
        controls
      />
    )
  }
}

class Site extends React.Component {
  render() {
    return (

          <Player />

          <SongBoard />

    )
  }
}

ReactDOM.render(
  <Site />,
  document.getElementById('root')
);
<|endoftext|>


<commit_before>var Component = require('yacomponent'),
	inheritClass = require('inherit-class'),
	Item = Collection.Item = require('./Item'),
	handlebars = require('handlebars-adapter');

function Collection() {
	this.items = [];

	this.template = null;

	this.fakeItem = undefined;
}

Collection.defaults = {
	dName: 'list',
	parent: null,
	Item: Item
};

inheritClass(Collection, Component, 'component');

Collection.prototype = $.extend({}, Collection.prototype, {
	init: function() {
		this.items = [];
		this.defineParentName();
		Component.prototype.init.call(this);
		this.makeFakeItem();
		this.defineItems();
		this.defineEvents();
	},

	makeFakeItem: function() {
		this.fakeItem = this.initItem({$el: $([]), fake: true});
	},

	defineTemplate: function() {
		this.template = handlebars.compile(this.options.parent.makeName(this.getItemDName()));
	},

	defineParentName: function() {
		if (this.options.parent) return;
		this.options.parent = this;
	},

	defineEvents: function() {
		var self = this;
		this.$el.on('click', this.elDel('makeSelector', 'remove'), function(e) {
			e.preventDefault();
			self.onRemove(e);
		});
		$('.' + this.options.dName + 'Add').on('click', function(e) {
			e.preventDefault();
			self.clickAdd();
		});
	},

	elDel: function(method, arg) {
		var args = [this.getItemDName()];
		args.push(arg);
		return this.options.parent[method].call(this.options.parent, args);
	},

	onRemove: function(event) {
		var item = this.getByEl(event.currentTarget);
		this.remove(item);
	},

	getByEl: function(el) {
		return this.items.filter(function(item) {
			return item.$el[0] === el || item.$el.find(el).length;
		})[0];
	},

	getItemDName: function() {
		return this.options.Item.defaults.dName;
	},

	defineItems: function() {
		var self = this;
		this.options.parent.find(this.getItemDName()).each(function() {
			var $el = $(this);
			var data = $el.data(self.options.parent.dName + '-' + self.options.Item.defaults.dName);
			var item = self.initItem({$el: $el, data: data});
			self.add(item);
		});
	},

	add: function(item, insert) {
		insert = typeof insert == 'undefined' ? false : insert;
		this.items.push(item);
		if (insert) this.$el.append(item.$el);
	},

	addByData: function(data) {
		var html = this.fakeItem.template(data);
		var item = this.initItem({$el: $(html), data: data});
		this.add(item, true);
	},

	clickAdd: function() {
		var data = this.getClickAddData();
		this.addByData(data);
	},

	getClickAddData: function() {
		return {};
	},

	remove: function(item) {
		var index = this.items.indexOf(item);
		item.$el.remove();
		this.items.splice(index, 1);
	},

	initItem: function(options) {
		options = $.extend({dName: this.options.parent.makeName(this.getItemDName())}, options, this.getItemOptions());
		return this.options.Item.init(options);
	},

	getItemOptions: function() {
		return {};
	},
});
Collection.prototype.constructor = Collection;

module.exports = Collection;<commit_msg>fix pass item template option to item options<commit_after>var Component = require('yacomponent'),
	inheritClass = require('inherit-class'),
	Item = Collection.Item = require('./Item'),
	handlebars = require('handlebars-adapter');

function Collection() {
	this.items = [];

	this.template = null;

	this.fakeItem = undefined;
}

Collection.defaults = {
	dName: 'list',
	parent: null,
	Item: Item
};

inheritClass(Collection, Component, 'component');

Collection.prototype = $.extend({}, Collection.prototype, {
	init: function() {
		this.items = [];
		this.defineParentName();
		Component.prototype.init.call(this);
		this.makeFakeItem();
		this.defineItems();
		this.defineEvents();
	},

	makeFakeItem: function() {
		this.fakeItem = this.initItem({$el: $([]), fake: true});
	},

	defineTemplate: function() {
		this.template = handlebars.compile(this.options.parent.makeName(this.getItemDName()));
	},

	defineParentName: function() {
		if (this.options.parent) return;
		this.options.parent = this;
	},

	defineEvents: function() {
		var self = this;
		this.$el.on('click', this.elDel('makeSelector', 'remove'), function(e) {
			e.preventDefault();
			self.onRemove(e);
		});
		$('.' + this.options.dName + 'Add').on('click', function(e) {
			e.preventDefault();
			self.clickAdd();
		});
	},

	elDel: function(method, arg) {
		var args = [this.getItemDName()];
		args.push(arg);
		return this.options.parent[method].call(this.options.parent, args);
	},

	onRemove: function(event) {
		var item = this.getByEl(event.currentTarget);
		this.remove(item);
	},

	getByEl: function(el) {
		return this.items.filter(function(item) {
			return item.$el[0] === el || item.$el.find(el).length;
		})[0];
	},

	getItemDName: function() {
		return this.options.Item.defaults.dName;
	},

	defineItems: function() {
		var self = this;
		this.options.parent.find(this.getItemDName()).each(function() {
			var $el = $(this);
			var data = $el.data(self.options.parent.dName + '-' + self.options.Item.defaults.dName);
			var item = self.initItem({$el: $el, data: data});
			self.add(item);
		});
	},

	add: function(item, insert) {
		insert = typeof insert == 'undefined' ? false : insert;
		this.items.push(item);
		if (insert) this.$el.append(item.$el);
	},

	addByData: function(data) {
		var html = this.fakeItem.template(data);
		var item = this.initItem({$el: $(html), data: data});
		this.add(item, true);
	},

	clickAdd: function() {
		var data = this.getClickAddData();
		this.addByData(data);
	},

	getClickAddData: function() {
		return {};
	},

	remove: function(item) {
		var index = this.items.indexOf(item);
		item.$el.remove();
		this.items.splice(index, 1);
	},

	initItem: function(options) {
		options = $.extend({
			dName: this.options.parent.makeName(this.getItemDName()),
			template: this.options.itemTemplate
		}, options, this.getItemOptions());
		return this.options.Item.init(options);
	},

	getItemOptions: function() {
		return {};
	},
});
Collection.prototype.constructor = Collection;

module.exports = Collection;<|endoftext|>


<commit_before>import RBush from 'rbush';

import { dispatch as d3_dispatch } from 'd3-dispatch';
import { json as d3_json } from 'd3-fetch';

import { t } from '../util/locale';
import { geoExtent, geoVecAdd } from '../geo';
import { qaError } from '../osm';
import { utilRebind, utilTiler, utilQsString } from '../util';
import { services } from '../../data/qa_errors.json';

const tiler = utilTiler();
const dispatch = d3_dispatch('loaded');
const _osmoseUrlRoot = 'https://osmose.openstreetmap.fr/';
const _erZoom = 14;

// This gets reassigned if reset
let _erCache;

function abortRequest(controller) {
  if (controller) {
    controller.abort();
  }
}

function abortUnwantedRequests(cache, tiles) {
  Object.keys(cache.inflightTile).forEach(k => {
    let wanted = tiles.find(tile => k === tile.id);
    if (!wanted) {
      abortRequest(cache.inflightTile[k]);
      delete cache.inflightTile[k];
    }
  });
}

function encodeErrorRtree(d) {
  return { minX: d.loc[0], minY: d.loc[1], maxX: d.loc[0], maxY: d.loc[1], data: d };
}

// replace or remove error from rtree
function updateRtree(item, replace) {
  _erCache.rtree.remove(item, (a, b) => a.data.id === b.data.id);

  if (replace) {
    _erCache.rtree.insert(item);
  }
}

function linkEntity(d) {
  return `<a class="error_entity_link">${d}</a>`;
}

// Errors shouldn't obscure eachother
function preventCoincident(loc) {
  let coincident = false;
  do {
    // first time, move marker up. after that, move marker right.
    let delta = coincident ? [0.00001, 0] : [0, 0.00001];
    loc = geoVecAdd(loc, delta);
    let bbox = geoExtent(loc).bbox();
    coincident = _erCache.rtree.search(bbox).length;
  } while (coincident);

  return loc;
}

export default {
  init() {
    if (!_erCache) {
      this.reset();
    }

    this.event = utilRebind(this, dispatch, 'on');
  },

  reset() {
    if (_erCache) {
      Object.values(_erCache.inflightTile).forEach(abortRequest);
    }
    _erCache = {
      data: {},
      loadedTile: {},
      inflightTile: {},
      inflightPost: {},
      closed: {},
      rtree: new RBush()
    };
  },

  loadErrors(projection) {
    let params = {
      // Tiles return a maximum # of errors
      // So we want to filter our request for only types iD supports
      item: services.osmose.items.join()
    };

    // determine the needed tiles to cover the view
    let tiles = tiler
      .zoomExtent([_erZoom, _erZoom])
      .getTiles(projection);

    // abort inflight requests that are no longer needed
    abortUnwantedRequests(_erCache, tiles);

    // issue new requests..
    tiles.forEach(tile => {
      if (_erCache.loadedTile[tile.id] || _erCache.inflightTile[tile.id]) return;

      let lang = 'en'; // todo: may want to use provided translations
      let [ x, y, z ] = tile.xyz;
      let url = _osmoseUrlRoot + `${lang}/map/issues/${z}/${x}/${y}.json?` + utilQsString(params);

      let controller = new AbortController();
      _erCache.inflightTile[tile.id] = controller;

      d3_json(url, { signal: controller.signal })
        .then(data => {
          delete _erCache.inflightTile[tile.id];
          _erCache.loadedTile[tile.id] = true;

          if (data.features) {
            data.features.forEach(issue => {
              const { item, class: error_class, issue_id: identifier } = issue.properties;
              // Item is the type of error, w/ class tells us the sub-type
              const error_type = [item, error_class].join('-');

              // Filter out unsupported error types (some are too specific or advanced)
              if (error_type in services.osmose.errorIcons) {
                let loc = issue.geometry.coordinates; // lon, lat
                loc = preventCoincident(loc);

                let d = new qaError({
                  // Info required for every error
                  loc,
                  service: 'osmose',
                  error_type,
                  // Extra details needed for this service
                  identifier, // needed to query and update the error
                  item // category of the issue for styling
                });

                // Special handling for some error types
                switch (d.item) {
                  case 8300:
                  case 8360: {
                    let k = error_class;

                    // First 17 classes are all speed limits
                    if (item === 8300 && error_class <= 17) {
                      k = 1;
                    }

                    // Setting elems here prevents UI error detail requests
                    d.replacements = [t(`QA.osmose.error_types.${d.item}.parts.${k}`)];
                    d.elems = [];
                    break;
                  }
                }

                _erCache.data[d.id] = d;
                _erCache.rtree.insert(encodeErrorRtree(d));
              }
            });
          }

          dispatch.call('loaded');
        })
        .catch(() => {
          delete _erCache.inflightTile[tile.id];
          _erCache.loadedTile[tile.id] = true;
        });
    });
  },

  loadErrorDetail(d, callback) {
    // Error details only need to be fetched once
    if (d.elems !== undefined) {
      if (callback) callback(null, d);
      return;
    }

    let url = _osmoseUrlRoot + `en/api/0.3beta/issue/${d.identifier}`;

    d3_json(url)
      .then(data => {
        // Associated elements used for highlighting
        // Assign directly for immediate use in the callback
        d.elems = data.elems.map(e => e.type.substring(0,1) + e.id);

        // Element links used in the error description
        d.replacements = d.elems.map(linkEntity);

        // Some error types have details in their subtitle
        const special = {
          '3040-3040': /Bad value for (.+)/i,
          '3090-3090': /Incorrect date "(.+)"/i,
          '4010-4010': /Tag (.+) is deprecated: (.+)/i,
          '4010-40102': /Tag (.+) is deprecated: (.+)/i,
          '4030-900': /Conflict between tags: (.+), (.+)/i,
          '5070-50703': /"(.+)"=".+" unexpected symbol char \(.+, (.+)\)/i,
          '5070-50704': /Umbalanced (.+)/i,
          '5070-50705': /Unexpected char (.+)/i,
          '9010-9010003': /(.+)/
        };
        if (d.error_type in special) {
          let [, ...details] = special[d.error_type].exec(data.subtitle);
          d.replacements.push(...details);

          if (d.error_type === '5070-50703') {
            d.replacements[2] = String.fromCharCode(details[1]);
          }
        } else if (d.error_type === '9010-9010001') {
          // This error has a rare subtitle variant
          let details = /(.+) is unnecessary/i.exec(data.subtitle);
          if (details == null) {
            details = /\. Remove (.+)/i.exec(data.subtitle);
          }
          d.replacements.push(details[1]);
        }

        this.replaceError(d);
        if (callback) callback(null, d);
      })
      .catch(err => {
        if (callback) callback(err.message);
      });
  },

  postUpdate(d, callback) {
    if (_erCache.inflightPost[d.id]) {
      return callback({ message: 'Error update already inflight', status: -2 }, d);
    }

    // UI sets the status to either 'done' or 'false'
    let url = _osmoseUrlRoot + `en/api/0.3beta/issue/${d.identifier}/${d.newStatus}`;

    let controller = new AbortController();
    _erCache.inflightPost[d.id] = controller;

    fetch(url, { signal: controller.signal })
      .then(() => {
        delete _erCache.inflightPost[d.id];

        this.removeError(d);
        if (d.newStatus === 'done') {
          // No error identifier, so we give a count of each category
          if (!(d.item in _erCache.closed)) {
            _erCache.closed[d.item] = 0;
          }
          _erCache.closed[d.item] += 1;
        }
        if (callback) callback(null, d);
      })
      .catch(err => {
        delete _erCache.inflightPost[d.id];
        if (callback) callback(err.message);
      });
  },

  // get all cached errors covering the viewport
  getErrors(projection) {
    let viewport = projection.clipExtent();
    let min = [viewport[0][0], viewport[1][1]];
    let max = [viewport[1][0], viewport[0][1]];
    let bbox = geoExtent(projection.invert(min), projection.invert(max)).bbox();

    return _erCache.rtree.search(bbox).map(d => {
      return d.data;
    });
  },

  // get a single error from the cache
  getError(id) {
    return _erCache.data[id];
  },

  // replace a single error in the cache
  replaceError(error) {
    if (!(error instanceof qaError) || !error.id) return;

    _erCache.data[error.id] = error;
    updateRtree(encodeErrorRtree(error), true); // true = replace
    return error;
  },

  // remove a single error from the cache
  removeError(error) {
    if (!(error instanceof qaError) || !error.id) return;

    delete _erCache.data[error.id];
    updateRtree(encodeErrorRtree(error), false); // false = remove
  },

  // Used to populate `closed:osmose:*` changeset tags
  getClosedCounts() {
    return _erCache.closed;
  }
};<commit_msg>Use latest Osmose API tiles endpoint<commit_after>import RBush from 'rbush';

import { dispatch as d3_dispatch } from 'd3-dispatch';
import { json as d3_json } from 'd3-fetch';

import { t } from '../util/locale';
import { geoExtent, geoVecAdd } from '../geo';
import { qaError } from '../osm';
import { utilRebind, utilTiler, utilQsString } from '../util';
import { services } from '../../data/qa_errors.json';

const tiler = utilTiler();
const dispatch = d3_dispatch('loaded');
const _osmoseUrlRoot = 'https://osmose.openstreetmap.fr/en/api/0.3beta/';
const _erZoom = 14;

// This gets reassigned if reset
let _erCache;

function abortRequest(controller) {
  if (controller) {
    controller.abort();
  }
}

function abortUnwantedRequests(cache, tiles) {
  Object.keys(cache.inflightTile).forEach(k => {
    let wanted = tiles.find(tile => k === tile.id);
    if (!wanted) {
      abortRequest(cache.inflightTile[k]);
      delete cache.inflightTile[k];
    }
  });
}

function encodeErrorRtree(d) {
  return { minX: d.loc[0], minY: d.loc[1], maxX: d.loc[0], maxY: d.loc[1], data: d };
}

// replace or remove error from rtree
function updateRtree(item, replace) {
  _erCache.rtree.remove(item, (a, b) => a.data.id === b.data.id);

  if (replace) {
    _erCache.rtree.insert(item);
  }
}

function linkEntity(d) {
  return `<a class="error_entity_link">${d}</a>`;
}

// Errors shouldn't obscure eachother
function preventCoincident(loc) {
  let coincident = false;
  do {
    // first time, move marker up. after that, move marker right.
    let delta = coincident ? [0.00001, 0] : [0, 0.00001];
    loc = geoVecAdd(loc, delta);
    let bbox = geoExtent(loc).bbox();
    coincident = _erCache.rtree.search(bbox).length;
  } while (coincident);

  return loc;
}

export default {
  init() {
    if (!_erCache) {
      this.reset();
    }

    this.event = utilRebind(this, dispatch, 'on');
  },

  reset() {
    if (_erCache) {
      Object.values(_erCache.inflightTile).forEach(abortRequest);
    }
    _erCache = {
      data: {},
      loadedTile: {},
      inflightTile: {},
      inflightPost: {},
      closed: {},
      rtree: new RBush()
    };
  },

  loadErrors(projection) {
    let params = {
      // Tiles return a maximum # of errors
      // So we want to filter our request for only types iD supports
      item: services.osmose.items.join()
    };

    // determine the needed tiles to cover the view
    let tiles = tiler
      .zoomExtent([_erZoom, _erZoom])
      .getTiles(projection);

    // abort inflight requests that are no longer needed
    abortUnwantedRequests(_erCache, tiles);

    // issue new requests..
    tiles.forEach(tile => {
      if (_erCache.loadedTile[tile.id] || _erCache.inflightTile[tile.id]) return;

      let [ x, y, z ] = tile.xyz;
      let url = _osmoseUrlRoot + `issues/${z}/${x}/${y}.json?` + utilQsString(params);

      let controller = new AbortController();
      _erCache.inflightTile[tile.id] = controller;

      d3_json(url, { signal: controller.signal })
        .then(data => {
          delete _erCache.inflightTile[tile.id];
          _erCache.loadedTile[tile.id] = true;

          if (data.features) {
            data.features.forEach(issue => {
              const { item, class: error_class, uuid: identifier } = issue.properties;
              // Item is the type of error, w/ class tells us the sub-type
              const error_type = [item, error_class].join('-');

              // Filter out unsupported error types (some are too specific or advanced)
              if (error_type in services.osmose.errorIcons) {
                let loc = issue.geometry.coordinates; // lon, lat
                loc = preventCoincident(loc);

                let d = new qaError({
                  // Info required for every error
                  loc,
                  service: 'osmose',
                  error_type,
                  // Extra details needed for this service
                  identifier, // needed to query and update the error
                  item // category of the issue for styling
                });

                // Special handling for some error types
                switch (d.item) {
                  case 8300:
                  case 8360: {
                    let k = error_class;

                    // First 17 classes are all speed limits
                    if (item === 8300 && error_class <= 17) {
                      k = 1;
                    }

                    // Setting elems here prevents UI error detail requests
                    d.replacements = [t(`QA.osmose.error_types.${d.item}.parts.${k}`)];
                    d.elems = [];
                    break;
                  }
                }

                _erCache.data[d.id] = d;
                _erCache.rtree.insert(encodeErrorRtree(d));
              }
            });
          }

          dispatch.call('loaded');
        })
        .catch(() => {
          delete _erCache.inflightTile[tile.id];
          _erCache.loadedTile[tile.id] = true;
        });
    });
  },

  loadErrorDetail(d, callback) {
    // Error details only need to be fetched once
    if (d.elems !== undefined) {
      if (callback) callback(null, d);
      return;
    }

    let url = _osmoseUrlRoot + `issue/${d.identifier}`;

    d3_json(url)
      .then(data => {
        // Associated elements used for highlighting
        // Assign directly for immediate use in the callback
        d.elems = data.elems.map(e => e.type.substring(0,1) + e.id);

        // Element links used in the error description
        d.replacements = d.elems.map(linkEntity);

        // Some error types have details in their subtitle
        const special = {
          '3040-3040': /Bad value for (.+)/i,
          '3090-3090': /Incorrect date "(.+)"/i,
          '4010-4010': /Tag (.+) is deprecated: (.+)/i,
          '4010-40102': /Tag (.+) is deprecated: (.+)/i,
          '4030-900': /Conflict between tags: (.+), (.+)/i,
          '5070-50703': /"(.+)"=".+" unexpected symbol char \(.+, (.+)\)/i,
          '5070-50704': /Umbalanced (.+)/i,
          '5070-50705': /Unexpected char (.+)/i,
          '9010-9010003': /(.+)/
        };
        if (d.error_type in special) {
          let [, ...details] = special[d.error_type].exec(data.subtitle);
          d.replacements.push(...details);

          if (d.error_type === '5070-50703') {
            d.replacements[2] = String.fromCharCode(details[1]);
          }
        } else if (d.error_type === '9010-9010001') {
          // This error has a rare subtitle variant
          let details = /(.+) is unnecessary/i.exec(data.subtitle);
          if (details == null) {
            details = /\. Remove (.+)/i.exec(data.subtitle);
          }
          d.replacements.push(details[1]);
        }

        this.replaceError(d);
        if (callback) callback(null, d);
      })
      .catch(err => {
        if (callback) callback(err.message);
      });
  },

  postUpdate(d, callback) {
    if (_erCache.inflightPost[d.id]) {
      return callback({ message: 'Error update already inflight', status: -2 }, d);
    }

    // UI sets the status to either 'done' or 'false'
    let url = _osmoseUrlRoot + `issue/${d.identifier}/${d.newStatus}`;

    let controller = new AbortController();
    _erCache.inflightPost[d.id] = controller;

    fetch(url, { signal: controller.signal })
      .then(() => {
        delete _erCache.inflightPost[d.id];

        this.removeError(d);
        if (d.newStatus === 'done') {
          // No error identifier, so we give a count of each category
          if (!(d.item in _erCache.closed)) {
            _erCache.closed[d.item] = 0;
          }
          _erCache.closed[d.item] += 1;
        }
        if (callback) callback(null, d);
      })
      .catch(err => {
        delete _erCache.inflightPost[d.id];
        if (callback) callback(err.message);
      });
  },

  // get all cached errors covering the viewport
  getErrors(projection) {
    let viewport = projection.clipExtent();
    let min = [viewport[0][0], viewport[1][1]];
    let max = [viewport[1][0], viewport[0][1]];
    let bbox = geoExtent(projection.invert(min), projection.invert(max)).bbox();

    return _erCache.rtree.search(bbox).map(d => {
      return d.data;
    });
  },

  // get a single error from the cache
  getError(id) {
    return _erCache.data[id];
  },

  // replace a single error in the cache
  replaceError(error) {
    if (!(error instanceof qaError) || !error.id) return;

    _erCache.data[error.id] = error;
    updateRtree(encodeErrorRtree(error), true); // true = replace
    return error;
  },

  // remove a single error from the cache
  removeError(error) {
    if (!(error instanceof qaError) || !error.id) return;

    delete _erCache.data[error.id];
    updateRtree(encodeErrorRtree(error), false); // false = remove
  },

  // Used to populate `closed:osmose:*` changeset tags
  getClosedCounts() {
    return _erCache.closed;
  }
};<|endoftext|>


<commit_before>/*
 * Cookie Calculator / scales/volume.js
 * copyright (c) 2016 Susisu
 */

"use strict";

import { SIUnit } from "../units.js";

let values = [
    {
        value: 2.82e-45,
        description:
            `Proton`
    },
    {
        value: 7.23e-30,
        description:
            `Hydrogen atom`
    },
    {
        value: 5e-21,
        description:
            `A virus`
    },
    {
        value: 9e-17,
        description:
            `Human red blood cell`
    },
    {
        value: 2e-15,
        description:
            `Ink drop of a printer`
    },
    {
        value: 6.2e-11,
        description:
            `A medium grain of sand`
    },
    {
        value: 2e-8,
        description:
            `A grain of rice`
    },
    {
        value: 2e-7,
        description:
            `Pea`
    },
    {
        value: 5e-6,
        description:
            `One teaspoon`
    },
    {
        value: 1.5e-5,
        description:
            `One tablespoon`
    },
    {
        value: 7.5e-4,
        description:
            `Wine bottle`
    },
    {
        value: 1.4e-3,
        description:
            `Human brain cavity`
    },
    {
        value: 5e-3,
        description:
            `Human blood`
    },
    {
        value: 6e-2,
        description:
            `Gasoline fuel tank in a car`
    },
    {
        value: 7.1e-2,
        description:
            `Human`
    },
    {
        value: 2e-1,
        description:
            `Drum`
    },
    {
        value: 1e0,
        description:
            `Domestic refrigerator`
    },
    {
        value: 3.31e+1,
        description:
            `20-foot cargo container`
    },
    {
        value: 6.75e+1,
        description:
            `40-foot cargo container`
    },
    {
        value: 2.5e+3,
        description:
            `Olympic size swimming pool`
    },
    {
        value: 2.11890e+5,
        description:
            `Gas in the Hindenburg zeppelin`
    },
    {
        value: 2.6006e+6,
        description:
            `The Great Pyramid of Giza`
    },
    {
        value: 4.3e+7,
        description:
            `Aswan Dam`
    },
    {
        value: 5e+8,
        description:
            `volume of Sydney Harbour`
    },
    {
        value: 3.2e+11,
        description:
            `Annual inflow of freshwater to the Black Sea`
    },
    {
        value: 1.1e+12,
        description:
            `Aral Sea (as of 1960)`
    },
    {
        value: 5.5e+14,
        description:
            `Black Sea`
    },
    {
        value: 3.7e+15,
        description:
            `Mediterranean Sea`
    },
    {
        value: 3e+17,
        description:
            `Atlantic Ocean`
    },
    {
        value: 4.5e+17,
        description:
            `Ceres`
    },
    {
        value: 1e+18,
        description:
            `Pacific Ocean`
    },
    {
        value: 6.4e+18,
        description:
            `Pluto`
    },
    {
        value: 2.2e+19,
        description:
            `The Moon`
    },
    {
        value: 6.1e+19,
        description:
            `Mercury`
    },
    {
        value: 1.6e+20,
        description:
            `Mars`
    },
    {
        value: 9.28e+20,
        description:
            `Venus`
    },
    {
        value: 1.08e+21,
        description:
            `Earth`
    },
    {
        value: 6.38e+22,
        description:
            `Neptune`
    },
    {
        value: 7.02e+22,
        description:
            `Uranus`
    },
    {
        value: 9.23e+23,
        description:
            `Saturn`
    },
    {
        value: 1.53e+24,
        description:
            `Jupiter`
    },
    {
        value: 1.41e+27,
        description:
            `The Sun`
    }
];

export default values.map(x => ({
    quantity   : SIUnit.CUBIC_METRE.value(x.value),
    description: x.description
}));
<commit_msg>Add volume scales<commit_after>/*
 * Cookie Calculator / scales/volume.js
 * copyright (c) 2016 Susisu
 */

"use strict";

import { SIUnit } from "../units.js";

let values = [
    {
        value: 2.82e-45,
        description:
            `Proton`
    },
    {
        value: 7.23e-30,
        description:
            `Hydrogen atom`
    },
    {
        value: 5e-21,
        description:
            `A virus`
    },
    {
        value: 9e-17,
        description:
            `Human red blood cell`
    },
    {
        value: 2e-15,
        description:
            `Ink drop of a printer`
    },
    {
        value: 6.2e-11,
        description:
            `A medium grain of sand`
    },
    {
        value: 2e-8,
        description:
            `A grain of rice`
    },
    {
        value: 2e-7,
        description:
            `Pea`
    },
    {
        value: 5e-6,
        description:
            `One teaspoon`
    },
    {
        value: 1.5e-5,
        description:
            `One tablespoon`
    },
    {
        value: 7.5e-4,
        description:
            `Wine bottle`
    },
    {
        value: 1.4e-3,
        description:
            `Human brain cavity`
    },
    {
        value: 5e-3,
        description:
            `Human blood`
    },
    {
        value: 6e-2,
        description:
            `Gasoline fuel tank in a car`
    },
    {
        value: 7.1e-2,
        description:
            `Human`
    },
    {
        value: 2e-1,
        description:
            `Drum`
    },
    {
        value: 1e0,
        description:
            `Domestic refrigerator`
    },
    {
        value: 3.31e+1,
        description:
            `20-foot cargo container`
    },
    {
        value: 6.75e+1,
        description:
            `40-foot cargo container`
    },
    {
        value: 2.5e+3,
        description:
            `Olympic size swimming pool`
    },
    {
        value: 2.11890e+5,
        description:
            `Gas in the Hindenburg zeppelin`
    },
    {
        value: 2.6006e+6,
        description:
            `The Great Pyramid of Giza`
    },
    {
        value: 4.3e+7,
        description:
            `Aswan Dam`
    },
    {
        value: 5e+8,
        description:
            `volume of Sydney Harbour`
    },
    {
        value: 3.2e+11,
        description:
            `Annual inflow of freshwater to the Black Sea`
    },
    {
        value: 1.1e+12,
        description:
            `Aral Sea (as of 1960)`
    },
    {
        value: 5.5e+14,
        description:
            `Black Sea`
    },
    {
        value: 3.7e+15,
        description:
            `Mediterranean Sea`
    },
    {
        value: 3e+17,
        description:
            `Atlantic Ocean`
    },
    {
        value: 4.5e+17,
        description:
            `Ceres`
    },
    {
        value: 1e+18,
        description:
            `Pacific Ocean`
    },
    {
        value: 6.4e+18,
        description:
            `Pluto`
    },
    {
        value: 2.2e+19,
        description:
            `The Moon`
    },
    {
        value: 6.1e+19,
        description:
            `Mercury`
    },
    {
        value: 1.6e+20,
        description:
            `Mars`
    },
    {
        value: 9.28e+20,
        description:
            `Venus`
    },
    {
        value: 1.08e+21,
        description:
            `Earth`
    },
    {
        value: 6.38e+22,
        description:
            `Neptune`
    },
    {
        value: 7.02e+22,
        description:
            `Uranus`
    },
    {
        value: 9.23e+23,
        description:
            `Saturn`
    },
    {
        value: 1.53e+24,
        description:
            `Jupiter`
    },
    {
        value: 1.41e+27,
        description:
            `The Sun`
    },
    {
        value: 3.4e+32,
        description:
            `Rigel`
    },
    {
        value: 1e+34,
        description:
            `Deneb`
    },
    {
        value: 2.75e+35,
        description:
            `Betelgeuse`
    },
    {
        value: 2.7e+46,
        description:
            `Bright inner nebula of the Cat's Eye Nebula`
    },
    {
        value: 8.47e+47,
        description:
            `1 cubic light-year`
    },
    {
        value: 1.7e+48,
        description:
            `Oort cloud`
    },
    {
        value: 3.3e+55,
        description:
            `Local bubble`
    },
    {
        value: 3.3e+61,
        description:
            `A galaxy like the Milky Way`
    },
    {
        value: 5e+68,
        description:
            `Local group`
    },
    {
        value: 1.2e+72,
        description:
            `Local void`
    },
    {
        value: 3.4e+80,
        description:
            `Volume of the observable universe`
    }
];

export default values.map(x => ({
    quantity   : SIUnit.CUBIC_METRE.value(x.value),
    description: x.description
}));
<|endoftext|>


<commit_before>describe("Main test suite", function() {
  var $rootScope, $controller, controller, successRequestHandler;

  beforeEach(module('app'));

  beforeEach(inject(function($injector) {
      $httpBackend = $injector.get('$httpBackend');

      // Get hold of a scope (i.e. the root scope)
      $rootScope = $injector.get('$rootScope');

      // The $controller service is used to create instances of controllers
      var $controller = $injector.get('$controller');

      createController = function() {
        return $controller('feedLoader', {'$scope' : $rootScope });
      };
  }));

  it("Check feedLoader controller has been defined.", function() {
      controller = createController();
      expect(controller).to.not.be.undefined;
  });

  describe("Testing suite for submitFeed function",function(){

    afterEach(function() {
      $httpBackend.verifyNoOutstandingExpectation();
      $httpBackend.verifyNoOutstandingRequest();
    });

    it("Check initial value of feedURL", function() {
      controller = createController();
      expect($rootScope.feedURL).to.equal('http://s3-ap-southeast-1.amazonaws.com/theincitement.com/exam/productfeed.xml');
    });

    it("Check on page load, products array is exists and its empty", function() {
      expect($rootScope.products).to.be.empty;
    });

    it("Check on page load, message variable is exists and its empty", function() {
      expect($rootScope.message).to.be.empty;
    });

    it("should post the request to server when we have a value in our feeds url input.", function(){
      successRequestHandler = $httpBackend.when('POST', './api/ttAPI.php')
                            .respond({status: true, "products":[{"productID":"eset_56062001usr-50-99","name":"ESET ESET NOD32 Secure Enterprise 2 jr 50 - 99 Workstations\/Gebruikers (LET (56062001USR-50-99)","currency":"EUR","price":"59.53","productURL":"http:\/\/www.centralpoint.nl\/tracker\/index.php?tt=534_251713_1_&r=https%3A%2F%2Fwww.centralpoint.nl%2Falgemene-utility-software%2Feset%2Feset-secure-enterprise-2-year-subscription-level-h-50-99-devices-prijs-per-device-engels-art-56062001usr-50-99-num-1743187%2F","imageURL":"http:\/\/www02.cp-static.com\/images\/pna_fo.jpg","description":"ESET NOD32 Secure Enterprise 2 jr 50 - 99 Workstations\/Gebruikers (LET OP: Prijs is per User!)","categories":"algemene utilities"}] });

      $httpBackend.expectPOST('./api/ttAPI.php'); //mock the http post
      controller = createController(); // make the controller
      $rootScope.submitFeed(); //run the function
      $httpBackend.flush();
      expect($rootScope.products).to.eql([{"productID":"eset_56062001usr-50-99","name":"ESET ESET NOD32 Secure Enterprise 2 jr 50 - 99 Workstations\/Gebruikers (LET (56062001USR-50-99)","currency":"EUR","price":"59.53","productURL":"http:\/\/www.centralpoint.nl\/tracker\/index.php?tt=534_251713_1_&r=https%3A%2F%2Fwww.centralpoint.nl%2Falgemene-utility-software%2Feset%2Feset-secure-enterprise-2-year-subscription-level-h-50-99-devices-prijs-per-device-engels-art-56062001usr-50-99-num-1743187%2F","imageURL":"http:\/\/www02.cp-static.com\/images\/pna_fo.jpg","description":"ESET NOD32 Secure Enterprise 2 jr 50 - 99 Workstations\/Gebruikers (LET OP: Prijs is per User!)","categories":"algemene utilities" }]);
    });

    it("Must show an error message when server response status is false", function(){
      successRequestHandler = $httpBackend.when('POST', './api/ttAPI.php')
                            .respond({status: false, "error":"Ooops, unfortunately, we couldn't retrieve any product from this XML file."});

      $httpBackend.expectPOST('./api/ttAPI.php'); //mock the http post
      controller = createController(); // make the controller
      $rootScope.submitFeed(); //run the function
      $httpBackend.flush();
      expect($rootScope.message).to.equal("Ooops, unfortunately, we couldn't retrieve any product from this XML file.");
    });

    it("Must show an error message when submitfeed() function runs with an empty feed's URL", function(){
      controller = createController(); // make the controller
      $rootScope.feedURL = ""; //clear the feedurl initial value
      $rootScope.submitFeed(); //run the function
      expect($rootScope.message).to.equal("Please insert an xml file's url.");
    });

  });

});<commit_msg>Test travis notification for successful tests<commit_after>describe("Main test suite", function() {
  var $rootScope, $controller, controller, successRequestHandler;

  beforeEach(module('app'));

  beforeEach(inject(function($injector) {
      $httpBackend = $injector.get('$httpBackend');

      // Get hold of a scope (i.e. the root scope)
      $rootScope = $injector.get('$rootScope');

      // The $controller service is used to create instances of controllers
      var $controller = $injector.get('$controller');

      createController = function() {
        return $controller('feedLoader', {'$scope' : $rootScope });
      };
  }));

  it("Check feedLoader controller has been defined.", function() {
      controller = createController();
      expect(controller).to.not.be.undefined;
  });

  describe("Testing suite for submitFeed function",function(){

    afterEach(function() {
      $httpBackend.verifyNoOutstandingExpectation();
      $httpBackend.verifyNoOutstandingRequest();
    });

    it("Check initial value of feedURL", function() {
      controller = createController();
      expect($rootScope.feedURL).to.equal('https://s3-ap-southeast-1.amazonaws.com/theincitement.com/exam/productfeed.xml');
    });

    it("Check on page load, products array is exists and its empty", function() {
      expect($rootScope.products).to.be.empty;
    });

    it("Check on page load, message variable is exists and its empty", function() {
      expect($rootScope.message).to.be.empty;
    });

    it("should post the request to server when we have a value in our feeds url input.", function(){
      successRequestHandler = $httpBackend.when('POST', './api/ttAPI.php')
                            .respond({status: true, "products":[{"productID":"eset_56062001usr-50-99","name":"ESET ESET NOD32 Secure Enterprise 2 jr 50 - 99 Workstations\/Gebruikers (LET (56062001USR-50-99)","currency":"EUR","price":"59.53","productURL":"http:\/\/www.centralpoint.nl\/tracker\/index.php?tt=534_251713_1_&r=https%3A%2F%2Fwww.centralpoint.nl%2Falgemene-utility-software%2Feset%2Feset-secure-enterprise-2-year-subscription-level-h-50-99-devices-prijs-per-device-engels-art-56062001usr-50-99-num-1743187%2F","imageURL":"http:\/\/www02.cp-static.com\/images\/pna_fo.jpg","description":"ESET NOD32 Secure Enterprise 2 jr 50 - 99 Workstations\/Gebruikers (LET OP: Prijs is per User!)","categories":"algemene utilities"}] });

      $httpBackend.expectPOST('./api/ttAPI.php'); //mock the http post
      controller = createController(); // make the controller
      $rootScope.submitFeed(); //run the function
      $httpBackend.flush();
      expect($rootScope.products).to.eql([{"productID":"eset_56062001usr-50-99","name":"ESET ESET NOD32 Secure Enterprise 2 jr 50 - 99 Workstations\/Gebruikers (LET (56062001USR-50-99)","currency":"EUR","price":"59.53","productURL":"http:\/\/www.centralpoint.nl\/tracker\/index.php?tt=534_251713_1_&r=https%3A%2F%2Fwww.centralpoint.nl%2Falgemene-utility-software%2Feset%2Feset-secure-enterprise-2-year-subscription-level-h-50-99-devices-prijs-per-device-engels-art-56062001usr-50-99-num-1743187%2F","imageURL":"http:\/\/www02.cp-static.com\/images\/pna_fo.jpg","description":"ESET NOD32 Secure Enterprise 2 jr 50 - 99 Workstations\/Gebruikers (LET OP: Prijs is per User!)","categories":"algemene utilities" }]);
    });

    it("Must show an error message when server response status is false", function(){
      successRequestHandler = $httpBackend.when('POST', './api/ttAPI.php')
                            .respond({status: false, "error":"Ooops, unfortunately, we couldn't retrieve any product from this XML file."});

      $httpBackend.expectPOST('./api/ttAPI.php'); //mock the http post
      controller = createController(); // make the controller
      $rootScope.submitFeed(); //run the function
      $httpBackend.flush();
      expect($rootScope.message).to.equal("Ooops, unfortunately, we couldn't retrieve any product from this XML file.");
    });

    it("Must show an error message when submitfeed() function runs with an empty feed's URL", function(){
      controller = createController(); // make the controller
      $rootScope.feedURL = ""; //clear the feedurl initial value
      $rootScope.submitFeed(); //run the function
      expect($rootScope.message).to.equal("Please insert an xml file's url.");
    });

  });

});<|endoftext|>


<commit_before>module.exports = function(grunt)
{

    'use strict';

    var async = require('async');
    var util = require('util');
    var exec = require('child_process').exec;
    var fs = require('fs');
    var manifest = eval('(' + fs.readFileSync('app.nw/package.json', {encoding: 'utf8'}) + ')');
    var source_app = '/Applications/node-webkit.app';
    var app_name = 'namagic.app'; // No capital letters allowed ? Makes the app crash when signed
    var identity = 'LK7U6U8DZ4' // @todo move this elsewhere
    var bundle_id = manifest.bundle_identifier;

    /**
     * Runs the app
     * Use the "--dev" option to enable toolbars and debug
     */
    grunt.registerTask('run', function()
    {
        setDevMode(grunt.option('dev') === true);
        var done = this.async();
        var child = exec(source_app + '/Contents/MacOS/node-webkit app.nw');
        child.stdout.on('data', grunt.log.write);
        child.stderr.on('data', grunt.log.write);
        child.on('close', done);
    });

    /**
     * Builds the app
     */
    grunt.registerTask('build', function()
    {
        var done = this.async();
        setDevMode(false);
        var series = [
            function(callback)
            {
                grunt.log.writeln('Cleaning...');
                exec('rm -r .mas; mkdir .mas', callback);
            },
            function(callback)
            {
                grunt.log.writeln('Creating empty application...');
                exec('cp -r ' + source_app + ' .mas/' + app_name, callback);
            },
            function(callback)
            {
                grunt.log.writeln('Installing icon...');
                exec('cp assets/icns/icon.icns .mas/' + app_name + '/Contents/Resources/nw.icns', callback);
            },
            function(callback)
            {
                grunt.log.writeln('Installing plist...');
                var plist = fs.readFileSync('assets/plist/info.plist', {encoding: 'utf8'});
                var stats = fs.statSync('.mas/' + app_name + '/Contents/Info.plist');
                for (var property in manifest)
                {
                    var regex = new RegExp('{{' + property + '}}', 'g');
                    plist = plist.replace(regex, manifest[property]);
                }
                fs.writeFile('.mas/' + app_name + '/Contents/Info.plist', plist, {
                    encoding: 'utf8',
                    mode: stats.mode
                }, callback);
            },
            function(callback)
            {
                grunt.log.writeln('Updating helpers...');
                updateHelperPlist('.mas/' + app_name + '/Contents/Frameworks/node-webkit Helper.app');
                updateHelperPlist('.mas/' + app_name + '/Contents/Frameworks/node-webkit Helper EH.app');
                updateHelperPlist('.mas/' + app_name + '/Contents/Frameworks/node-webkit Helper NP.app');
                callback();
            },
            function(callback)
            {
                grunt.log.writeln('Installing app files...');
                exec('cp -r app.nw .mas/' + app_name + '/Contents/Resources', callback);
            },
            function(callback)
            {
                grunt.log.writeln('Cleaning built app...');
                exec('cd .mas/' + app_name + ' && find . -name "*.DS_Store" -type f -delete', callback);
            }
        ];
        async.series(series, function()
        {
            done();
        });
    });

    /**
     * Signs the app
     */
    grunt.registerTask('sign', function()
    {
        var done = this.async();
        var series = [
            function(callback)
            {
                grunt.log.writeln('Signing node-webkit Helper.app...');
                exec(signCommand('assets/entitlements/child.plist', '.mas/' + app_name + '/Contents/Frameworks/node-webkit Helper.app'), callback);
            },
            function(callback)
            {
                grunt.log.writeln('Signing node-webkit Helper EH.app...');
                exec(signCommand('assets/entitlements/child.plist', '.mas/' + app_name + '/Contents/Frameworks/node-webkit Helper EH.app'), callback);
            },
            function(callback)
            {
                grunt.log.writeln('Signing node-webkit Helper NP.app...');
                exec(signCommand('assets/entitlements/child.plist', '.mas/' + app_name + '/Contents/Frameworks/node-webkit Helper NP.app'), callback);
            },
            function(callback)
            {
                grunt.log.writeln('Signing app...');
                exec(signCommand('assets/entitlements/parent.plist', '.mas/' + app_name), callback);
            }
        ];
        async.series(series, function()
        {
            done();
        });
    });

    /**
     * Gets a codesign command
     * @param entitlement_path
     * @param app_path
     */
    function signCommand(entitlement_path, app_path)
    {
        return 'codesign --deep -s ' + identity + ' -i ' + bundle_id + ' --entitlements ' + entitlement_path + ' "' + app_path + '"';
    }

    /**
     * Updates the Info.plist file of the needed helper app
     * @param helper_path
     */
    function updateHelperPlist(helper_path)
    {
        var plist = fs.readFileSync(helper_path + '/Contents/Info.plist', {encoding: 'utf8'});
        var stats = fs.statSync(helper_path + '/Contents/Info.plist');
        plist = plist.replace(/<key>CFBundleIdentifier<\/key>[^\/]*\/string>/g, '<key>CFBundleIdentifier<\/key>\n	<string>' + bundle_id + '</string>');
        fs.writeFileSync(helper_path + '/Contents/Info.plist', plist, {encoding: 'utf8', mode: stats.mode});
    }

    /**
     * Toggles dev mode
     * @param enable
     */
    function setDevMode(enable)
    {
        grunt.file.write('./app.nw/.dev', enable ? '1' : '0', {encoding: 'utf8'});
    }

};<commit_msg>Fixes build task<commit_after>module.exports = function(grunt)
{

    'use strict';

    var async = require('async');
    var util = require('util');
    var exec = require('child_process').exec;
    var fs = require('fs');
    var manifest = eval('(' + fs.readFileSync('app.nw/package.json', {encoding: 'utf8'}) + ')');
    var source_app = '/Applications/node-webkit.app';
    var app_name = 'namagic.app'; // No capital letters allowed ? Makes the app crash when signed
    var identity = 'LK7U6U8DZ4' // @todo move this elsewhere
    var bundle_id = manifest.bundle_identifier;

    /**
     * Runs the app
     * Use the "--dev" option to enable toolbars and debug
     */
    grunt.registerTask('run', function()
    {
        setDevMode(grunt.option('dev') === true);
        var done = this.async();
        var child = exec(source_app + '/Contents/MacOS/node-webkit app.nw');
        child.stdout.on('data', grunt.log.write);
        child.stderr.on('data', grunt.log.write);
        child.on('close', done);
    });

    /**
     * Builds the app
     */
    grunt.registerTask('build', function()
    {
        var done = this.async();
        setDevMode(false);
        var series = [
            function(callback)
            {
                grunt.log.writeln('Cleaning...');
                exec('rm -r .mas && mkdir .mas', callback);
            },
            function(callback)
            {
                grunt.log.writeln('Creating empty application...');
                exec('cp -r ' + source_app + ' .mas/' + app_name, callback);
            },
            function(callback)
            {
                grunt.log.writeln('Installing icon...');
                exec('cp assets/icns/icon.icns .mas/' + app_name + '/Contents/Resources/nw.icns', callback);
            },
            function(callback)
            {
                grunt.log.writeln('Installing plist...');
                var plist = fs.readFileSync('assets/plist/info.plist', {encoding: 'utf8'});
                var stats = fs.statSync('.mas/' + app_name + '/Contents/Info.plist');
                for (var property in manifest)
                {
                    var regex = new RegExp('{{' + property + '}}', 'g');
                    plist = plist.replace(regex, manifest[property]);
                }
                fs.writeFile('.mas/' + app_name + '/Contents/Info.plist', plist, {
                    encoding: 'utf8',
                    mode: stats.mode
                }, callback);
            },
            function(callback)
            {
                grunt.log.writeln('Updating helpers...');
                updateHelperPlist('.mas/' + app_name + '/Contents/Frameworks/node-webkit Helper.app');
                updateHelperPlist('.mas/' + app_name + '/Contents/Frameworks/node-webkit Helper EH.app');
                updateHelperPlist('.mas/' + app_name + '/Contents/Frameworks/node-webkit Helper NP.app');
                callback();
            },
            function(callback)
            {
                grunt.log.writeln('Installing app files...');
                exec('cp -r app.nw .mas/' + app_name + '/Contents/Resources', callback);
            },
            function(callback)
            {
                grunt.log.writeln('Cleaning built app...');
                exec('cd .mas/' + app_name + ' && find . -name "*.DS_Store" -type f -delete', callback);
            }
        ];
        async.series(series, function()
        {
            done();
        });
    });

    /**
     * Signs the app
     */
    grunt.registerTask('sign', function()
    {
        var done = this.async();
        var series = [
            function(callback)
            {
                grunt.log.writeln('Signing node-webkit Helper.app...');
                exec(signCommand('assets/entitlements/child.plist', '.mas/' + app_name + '/Contents/Frameworks/node-webkit Helper.app'), callback);
            },
            function(callback)
            {
                grunt.log.writeln('Signing node-webkit Helper EH.app...');
                exec(signCommand('assets/entitlements/child.plist', '.mas/' + app_name + '/Contents/Frameworks/node-webkit Helper EH.app'), callback);
            },
            function(callback)
            {
                grunt.log.writeln('Signing node-webkit Helper NP.app...');
                exec(signCommand('assets/entitlements/child.plist', '.mas/' + app_name + '/Contents/Frameworks/node-webkit Helper NP.app'), callback);
            },
            function(callback)
            {
                grunt.log.writeln('Signing app...');
                exec(signCommand('assets/entitlements/parent.plist', '.mas/' + app_name), callback);
            }
        ];
        async.series(series, function()
        {
            done();
        });
    });

    /**
     * Gets a codesign command
     * @param entitlement_path
     * @param app_path
     */
    function signCommand(entitlement_path, app_path)
    {
        return 'codesign --deep -s ' + identity + ' -i ' + bundle_id + ' --entitlements ' + entitlement_path + ' "' + app_path + '"';
    }

    /**
     * Updates the Info.plist file of the needed helper app
     * @param helper_path
     */
    function updateHelperPlist(helper_path)
    {
        var plist = fs.readFileSync(helper_path + '/Contents/Info.plist', {encoding: 'utf8'});
        var stats = fs.statSync(helper_path + '/Contents/Info.plist');
        plist = plist.replace(/<key>CFBundleIdentifier<\/key>[^\/]*\/string>/g, '<key>CFBundleIdentifier<\/key>\n	<string>' + bundle_id + '</string>');
        fs.writeFileSync(helper_path + '/Contents/Info.plist', plist, {encoding: 'utf8', mode: stats.mode});
    }

    /**
     * Toggles dev mode
     * @param enable
     */
    function setDevMode(enable)
    {
        grunt.file.write('./app.nw/.dev', enable ? '1' : '0', {encoding: 'utf8'});
    }

};<|endoftext|>