<commit_before>var fs      = require('fs');
var assert  = require('assert');
var Monocle = require('../monocle');

//
// setup
//
var monocle = null;
var sample_dir = __dirname + '/sample_files';
before(function(){ monocle = new Monocle(); });
after(function() {
  fs.unlinkSync(__dirname+"/sample_files/creation.txt");
  fs.unlinkSync(__dirname+"/sample_files/creation2.txt");
  fs.unlinkSync(__dirname+"/sample_files/nestedDir/creation3.txt");
});
//
// file change tests
//

describe("file changes", function() {

  it("should detect a change", function(complete) {
    monocle.watchDirectory({
      root: sample_dir,
      callback: function(f){ cb_helper('foo.txt', f, complete); },
      complete: function(){ complete_helper("/sample_files/foo.txt"); }
    });
  });

  it("should detect a change in a nested dir file", function(complete) {
    monocle.watchDirectory({
      root: sample_dir,
      callback: function(f) { cb_helper('servent.txt', f, complete); },
      complete: function() { complete_helper("/sample_files/nestedDir/servent.txt"); }
    });
  });

  it("should detect a change", function(complete) {
    monocle.watchDirectory({
      root: sample_dir,
      callback: function(f) { cb_helper('longbow.js', f, complete); },
      complete: function() { complete_helper('/sample_files/longbow.js'); }
    });
  });

});

//
// file add tests
//

describe("file added", function() {
  it("should detect a file added", function(complete) {
    monocle.watchDirectory({
      root: sample_dir,
      callback: function(f) {
        cb_helper("creation.txt", f, complete)
      },
      complete: function() {
        complete_helper('/sample_files/creation.txt');
      }
    });
  });

  it("should detect another file added", function(complete) {
    monocle.watchDirectory({
      root: sample_dir,
      callback: function(f) {
        cb_helper("creation2.txt", f, complete);
      },
      complete: function() {
        complete_helper('/sample_files/creation2.txt');
      }
    });
  });

  it("should detect another file added in a nested folder", function(complete) {
    monocle.watchDirectory({
      root: sample_dir,
      callback: function(f) {
        cb_helper("creation3.txt", f, complete);
      },
      complete: function() {
        complete_helper('/sample_files/nestedDir/creation3.txt');
      }
    });
  });
});

//
// watch an array of files
//
describe("files watched", function() {
  it("should detect a file changed of multiple", function(complete) {
    complete_helper('/sample_files/creation.txt');
    complete_helper('/sample_files/creation2.txt');

    monocle.watchFiles({
      files: [__dirname+"/sample_files/creation.txt", __dirname+"/sample_files/creation2.txt"],
      callback: function(f) {
        cb_helper("creation2.txt", f, complete)
      },
      complete: function() {
        complete_helper('/sample_files/creation2.txt');
      }
    });
  });

  it("should detect a file changed", function(complete) {
    complete_helper('/sample_files/creation.txt');
    monocle.watchFiles({
      files: [__dirname+"/sample_files/creation.txt"],
      callback: function(f) {
        cb_helper("creation.txt", f, complete)
      },
      complete: function() {
        complete_helper('/sample_files/creation.txt');
      }
    });
  });
});

//
// helpers
//

function cb_helper(name, file, done){
  if (file.name === name) { monocle.unwatchAll(); done(); }
}

function complete_helper(path){
  fs.writeFile(__dirname + path, (new Date).getTime() + "\n");
}<commit_msg>remove unneeded new statement<commit_after>var fs      = require('fs');
var assert  = require('assert');
var Monocle = require('../monocle');

//
// setup
//
var monocle = null;
var sample_dir = __dirname + '/sample_files';
before(function(){ monocle = Monocle(); });
after(function() {
  fs.unlinkSync(__dirname+"/sample_files/creation.txt");
  fs.unlinkSync(__dirname+"/sample_files/creation2.txt");
  fs.unlinkSync(__dirname+"/sample_files/nestedDir/creation3.txt");
});
//
// file change tests
//

describe("file changes", function() {

  it("should detect a change", function(complete) {
    monocle.watchDirectory({
      root: sample_dir,
      callback: function(f){ cb_helper('foo.txt', f, complete); },
      complete: function(){ complete_helper("/sample_files/foo.txt"); }
    });
  });

  it("should detect a change in a nested dir file", function(complete) {
    monocle.watchDirectory({
      root: sample_dir,
      callback: function(f) { cb_helper('servent.txt', f, complete); },
      complete: function() { complete_helper("/sample_files/nestedDir/servent.txt"); }
    });
  });

  it("should detect a change", function(complete) {
    monocle.watchDirectory({
      root: sample_dir,
      callback: function(f) { cb_helper('longbow.js', f, complete); },
      complete: function() { complete_helper('/sample_files/longbow.js'); }
    });
  });

});

//
// file add tests
//

describe("file added", function() {
  it("should detect a file added", function(complete) {
    monocle.watchDirectory({
      root: sample_dir,
      callback: function(f) {
        cb_helper("creation.txt", f, complete)
      },
      complete: function() {
        complete_helper('/sample_files/creation.txt');
      }
    });
  });

  it("should detect another file added", function(complete) {
    monocle.watchDirectory({
      root: sample_dir,
      callback: function(f) {
        cb_helper("creation2.txt", f, complete);
      },
      complete: function() {
        complete_helper('/sample_files/creation2.txt');
      }
    });
  });

  it("should detect another file added in a nested folder", function(complete) {
    monocle.watchDirectory({
      root: sample_dir,
      callback: function(f) {
        cb_helper("creation3.txt", f, complete);
      },
      complete: function() {
        complete_helper('/sample_files/nestedDir/creation3.txt');
      }
    });
  });
});

//
// watch an array of files
//
describe("files watched", function() {
  it("should detect a file changed of multiple", function(complete) {
    complete_helper('/sample_files/creation.txt');
    complete_helper('/sample_files/creation2.txt');

    monocle.watchFiles({
      files: [__dirname+"/sample_files/creation.txt", __dirname+"/sample_files/creation2.txt"],
      callback: function(f) {
        cb_helper("creation2.txt", f, complete)
      },
      complete: function() {
        complete_helper('/sample_files/creation2.txt');
      }
    });
  });

  it("should detect a file changed", function(complete) {
    complete_helper('/sample_files/creation.txt');
    monocle.watchFiles({
      files: [__dirname+"/sample_files/creation.txt"],
      callback: function(f) {
        cb_helper("creation.txt", f, complete)
      },
      complete: function() {
        complete_helper('/sample_files/creation.txt');
      }
    });
  });
});

//
// helpers
//

function cb_helper(name, file, done){
  if (file.name === name) { monocle.unwatchAll(); done(); }
}

function complete_helper(path){
  fs.writeFile(__dirname + path, (new Date).getTime() + "\n");
}
<|endoftext|>


<commit_before>'use strict';

var tape = require('../');
var tap = require('tap');
var concat = require('concat-stream');
var inspect = require('object-inspect');
var assign = require('object.assign');

var stripFullStack = require('./common').stripFullStack;

var getter = function () { return 'message'; };
var messageGetterError = Object.defineProperty(
    { custom: 'error' },
    'message',
    {
        configurable: true,
        enumerable: true,
        get: getter
    }
);
var thrower = function () { throw messageGetterError; };

tap.test('failures', function (tt) {
    tt.plan(1);

    var test = tape.createHarness();
    test.createStream().pipe(concat(function (body) {
        tt.same(stripFullStack(body.toString('utf8')), [
            'TAP version 13',
            '# non functions',
            'ok 1 should throw',
            'ok 2 should throw',
            'ok 3 should throw',
            'ok 4 should throw',
            'ok 5 should throw',
            'ok 6 should throw',
            'ok 7 should throw',
            'ok 8 should throw',
            '# function',
            'not ok 9 should throw',
            '  ---',
            '    operator: throws',
            '    expected: undefined',
            '    actual:   undefined',
            '    at: Test.<anonymous> ($TEST/throws.js:$LINE:$COL)',
            '    stack: |-',
            '      Error: should throw',
            '          [... stack stripped ...]',
            '          at Test.<anonymous> ($TEST/throws.js:$LINE:$COL)',
            '          [... stack stripped ...]',
            '  ...',
            '# custom error messages',
            'ok 10 "message" is enumerable',
            "ok 11 { custom: 'error', message: 'message' }",
            'ok 12 getter is still the same',
            '# throws null',
            'ok 13 throws null',
            '# wrong type of error',
            'not ok 14 throws actual',
            '  ---',
            '    operator: throws',
            '    expected: |-',
            '      [Function: TypeError]',
            '    actual: |-',
            "      { [RangeError: actual!] message: 'actual!' }",
            '    at: Test.<anonymous> ($TEST/throws.js:$LINE:$COL)',
            '    stack: |-',
            '      RangeError: actual!',
            '          at Test.<anonymous> ($TEST/throws.js:$LINE:$COL)',
            '          [... stack stripped ...]',
            '  ...',
            '# object',
            'ok 15 object properties are validated',
            '# object with regexes',
            'ok 16 object with regex values is validated',
            '# similar error object',
            'ok 17 throwing a similar error',
            '# validate with regex',
            'ok 18 regex against toString of error',
            '# custom error validation',
            'ok 19 error is SyntaxError',
            'ok 20 error matches /value/',
            'ok 21 unexpected error',
            '# throwing primitives',
            'ok 22 primitive: null',
            'ok 23 primitive: undefined',
            'ok 24 primitive: 0',
            'ok 25 primitive: NaN',
            'ok 26 primitive: 42',
            'ok 27 primitive: Infinity',
            'ok 28 primitive: \'\'',
            'ok 29 primitive: \'foo\'',
            'ok 30 primitive: true',
            'ok 31 primitive: false',
            '# ambiguous arguments',
            'ok 32 Second',
            'ok 33 Second',
            'ok 34 Second',
            'ok 35 should throw',
            'not ok 36 should throw',
            '  ---',
            '    operator: throws',
            '    expected: |-',
            '      \'/Second$/\'',
            '    actual: |-',
            '      { [Error: First] message: \'First\' }',
            '    at: Test.<anonymous> ($TEST/throws.js:$LINE:$COL)',
            '    stack: |-',
            '      Error: First',
            '          at throwingFirst ($TEST/throws.js:$LINE:$COL)',
            '          [... stack stripped ...]',
            '          at Test.<anonymous> ($TEST/throws.js:$LINE:$COL)',
            '          [... stack stripped ...]',
            '  ...',
            '',
            '1..36',
            '# tests 36',
            '# pass  33',
            '# fail  3',
            ''
        ]);
    }));

    test('non functions', function (t) {
        t.plan(8);
        t.throws();
        t.throws(null);
        t.throws(true);
        t.throws(false);
        t.throws('abc');
        t.throws(/a/g);
        t.throws([]);
        t.throws({});
    });

    test('function', function (t) {
        t.plan(1);
        t.throws(function () {});
    });

    test('custom error messages', function (t) {
        t.plan(3);
        t.equal(Object.prototype.propertyIsEnumerable.call(messageGetterError, 'message'), true, '"message" is enumerable');
        t.throws(thrower, "{ custom: 'error', message: 'message' }");
        t.equal(Object.getOwnPropertyDescriptor(messageGetterError, 'message').get, getter, 'getter is still the same');
    });

    test('throws null', function (t) {
        t.plan(1);
        t.throws(function () { throw null; }, 'throws null');
        t.end();
    });

    test('wrong type of error', function (t) {
        t.plan(1);
        var actual = new RangeError('actual!');
        t.throws(function () { throw actual; }, TypeError, 'throws actual');
        t.end();
    });

    // taken from https://nodejs.org/api/assert.html#assert_assert_throws_fn_error_message
    var err = new TypeError('Wrong value');
    err.code = 404;
    err.foo = 'bar';
    err.info = {
        nested: true,
        baz: 'text'
    };
    err.reg = /abc/i;

    test('object', function (t) {
        t.plan(1);

        t.throws(
            function () { throw err; },
            {
                name: 'TypeError',
                message: 'Wrong value',
                info: {
                    nested: true,
                    baz: 'text'
                }
                // Only properties on the validation object will be tested for.
                // Using nested objects requires all properties to be present. Otherwise
                // the validation is going to fail.
            },
            'object properties are validated'
        );

        t.end();
    });

    test('object with regexes', function (t) {
        t.plan(1);
        t.throws(
            function () { throw err; },
            {
                // The `name` and `message` properties are strings and using regular
                // expressions on those will match against the string. If they fail, an
                // error is thrown.
                name: /^TypeError$/,
                message: /Wrong/,
                foo: 'bar',
                info: {
                    nested: true,
                    // It is not possible to use regular expressions for nested properties!
                    baz: 'text'
                },
                // The `reg` property contains a regular expression and only if the
                // validation object contains an identical regular expression, it is going
                // to pass.
                reg: /abc/i
            },
            'object with regex values is validated'
        );
        t.end();
    });

    test('similar error object', function (t) {
        t.plan(1);
        t.throws(
            function () {
                var otherErr = new TypeError('Not found');
                // Copy all enumerable properties from `err` to `otherErr`.
                assign(otherErr, err);
                throw otherErr;
            },
            // The error's `message` and `name` properties will also be checked when using
            // an error as validation object.
            err,
            'throwing a similar error'
        );
        t.end();
    });

    test('validate with regex', function (t) {
        t.plan(1);
        t.throws(
            function () { throw new Error('Wrong value'); },
            /^Error: Wrong value$/,
            'regex against toString of error'
        );
        t.end();
    });

    test('custom error validation', function (t) {
        t.plan(3);
        t.throws(
            function () { throw new SyntaxError('Wrong value'); },
            function (error) {
                t.ok(error instanceof SyntaxError, 'error is SyntaxError');
                t.ok((/value/).test(error), 'error matches /value/');
                // Avoid returning anything from validation functions besides `true`.
                // Otherwise, it's not clear what part of the validation failed. Instead,
                // throw an error about the specific validation that failed (as done in this
                // example) and add as much helpful debugging information to that error as
                // possible.
                return true;
            },
            'unexpected error'
        );
        t.end();
    });

    test('throwing primitives', function (t) {
        [null, undefined, 0, NaN, 42, Infinity, '', 'foo', true, false].forEach(function (primitive) {
            t.throws(function () { throw primitive; }, 'primitive: ' + inspect(primitive));
        });

        t.end();
    });

    test('ambiguous arguments', function (t) {
        function throwingFirst() {
            throw new Error('First');
        }

        function throwingSecond() {
            throw new Error('Second');
        }

        function notThrowing() {}

        // The second argument is a string and the input function threw an Error.
        // The first case will not throw as it does not match for the error message
        // thrown by the input function!
        t.throws(throwingFirst, 'Second');
        // In the next example the message has no benefit over the message from the
        // error and since it is not clear if the user intended to actually match
        // against the error message, Node.js throws an `ERR_AMBIGUOUS_ARGUMENT` error.
        t.throws(throwingSecond, 'Second');
        // TypeError [ERR_AMBIGUOUS_ARGUMENT]

        // The string is only used (as message) in case the function does not throw:
        t.doesNotThrow(notThrowing, 'Second');
        // AssertionError [ERR_ASSERTION]: Missing expected exception: Second

        // If it was intended to match for the error message do this instead:
        // It does not fail because the error messages match.
        t.throws(throwingSecond, /Second$/);

        // If the error message does not match, an AssertionError is thrown.
        t.throws(throwingFirst, /Second$/);
        // AssertionError [ERR_ASSERTION]
        t.end();
    });
});
<commit_msg>[Tests] handle a broken error `cause` in node 16.9/16.10<commit_after>'use strict';

var tape = require('../');
var tap = require('tap');
var concat = require('concat-stream');
var inspect = require('object-inspect');
var assign = require('object.assign');

var stripFullStack = require('./common').stripFullStack;

var getter = function () { return 'message'; };
var messageGetterError = Object.defineProperty(
    { custom: 'error' },
    'message',
    {
        configurable: true,
        enumerable: true,
        get: getter
    }
);
var thrower = function () { throw messageGetterError; };

tap.test('failures', function (tt) {
    tt.plan(1);

    var test = tape.createHarness();
    test.createStream().pipe(concat(function (body) {
        tt.same(stripFullStack(body.toString('utf8')), [
            'TAP version 13',
            '# non functions',
            'ok 1 should throw',
            'ok 2 should throw',
            'ok 3 should throw',
            'ok 4 should throw',
            'ok 5 should throw',
            'ok 6 should throw',
            'ok 7 should throw',
            'ok 8 should throw',
            '# function',
            'not ok 9 should throw',
            '  ---',
            '    operator: throws',
            '    expected: undefined',
            '    actual:   undefined',
            '    at: Test.<anonymous> ($TEST/throws.js:$LINE:$COL)',
            '    stack: |-',
            '      Error: should throw',
            '          [... stack stripped ...]',
            '          at Test.<anonymous> ($TEST/throws.js:$LINE:$COL)',
            '          [... stack stripped ...]',
            '  ...',
            '# custom error messages',
            'ok 10 "message" is enumerable',
            "ok 11 { custom: 'error', message: 'message' }",
            'ok 12 getter is still the same',
            '# throws null',
            'ok 13 throws null',
            '# wrong type of error',
            'not ok 14 throws actual',
            '  ---',
            '    operator: throws',
            '    expected: |-',
            '      [Function: TypeError]',
            '    actual: |-',
            '      { [RangeError: actual!] ' + ('cause' in Error.prototype ? '[cause]: undefined, ' : '') + "message: 'actual!' }",
            '    at: Test.<anonymous> ($TEST/throws.js:$LINE:$COL)',
            '    stack: |-',
            '      RangeError: actual!',
            '          at Test.<anonymous> ($TEST/throws.js:$LINE:$COL)',
            '          [... stack stripped ...]',
            '  ...',
            '# object',
            'ok 15 object properties are validated',
            '# object with regexes',
            'ok 16 object with regex values is validated',
            '# similar error object',
            'ok 17 throwing a similar error',
            '# validate with regex',
            'ok 18 regex against toString of error',
            '# custom error validation',
            'ok 19 error is SyntaxError',
            'ok 20 error matches /value/',
            'ok 21 unexpected error',
            '# throwing primitives',
            'ok 22 primitive: null',
            'ok 23 primitive: undefined',
            'ok 24 primitive: 0',
            'ok 25 primitive: NaN',
            'ok 26 primitive: 42',
            'ok 27 primitive: Infinity',
            'ok 28 primitive: \'\'',
            'ok 29 primitive: \'foo\'',
            'ok 30 primitive: true',
            'ok 31 primitive: false',
            '# ambiguous arguments',
            'ok 32 Second',
            'ok 33 Second',
            'ok 34 Second',
            'ok 35 should throw',
            'not ok 36 should throw',
            '  ---',
            '    operator: throws',
            '    expected: |-',
            '      \'/Second$/\'',
            '    actual: |-',
            '      { [Error: First] ' + ('cause' in Error.prototype ? '[cause]: undefined, ' : '') + 'message: \'First\' }',
            '    at: Test.<anonymous> ($TEST/throws.js:$LINE:$COL)',
            '    stack: |-',
            '      Error: First',
            '          at throwingFirst ($TEST/throws.js:$LINE:$COL)',
            '          [... stack stripped ...]',
            '          at Test.<anonymous> ($TEST/throws.js:$LINE:$COL)',
            '          [... stack stripped ...]',
            '  ...',
            '',
            '1..36',
            '# tests 36',
            '# pass  33',
            '# fail  3',
            ''
        ]);
    }));

    test('non functions', function (t) {
        t.plan(8);
        t.throws();
        t.throws(null);
        t.throws(true);
        t.throws(false);
        t.throws('abc');
        t.throws(/a/g);
        t.throws([]);
        t.throws({});
    });

    test('function', function (t) {
        t.plan(1);
        t.throws(function () {});
    });

    test('custom error messages', function (t) {
        t.plan(3);
        t.equal(Object.prototype.propertyIsEnumerable.call(messageGetterError, 'message'), true, '"message" is enumerable');
        t.throws(thrower, "{ custom: 'error', message: 'message' }");
        t.equal(Object.getOwnPropertyDescriptor(messageGetterError, 'message').get, getter, 'getter is still the same');
    });

    test('throws null', function (t) {
        t.plan(1);
        t.throws(function () { throw null; }, 'throws null');
        t.end();
    });

    test('wrong type of error', function (t) {
        t.plan(1);
        var actual = new RangeError('actual!');
        t.throws(function () { throw actual; }, TypeError, 'throws actual');
        t.end();
    });

    // taken from https://nodejs.org/api/assert.html#assert_assert_throws_fn_error_message
    var err = new TypeError('Wrong value');
    err.code = 404;
    err.foo = 'bar';
    err.info = {
        nested: true,
        baz: 'text'
    };
    err.reg = /abc/i;

    test('object', function (t) {
        t.plan(1);

        t.throws(
            function () { throw err; },
            {
                name: 'TypeError',
                message: 'Wrong value',
                info: {
                    nested: true,
                    baz: 'text'
                }
                // Only properties on the validation object will be tested for.
                // Using nested objects requires all properties to be present. Otherwise
                // the validation is going to fail.
            },
            'object properties are validated'
        );

        t.end();
    });

    test('object with regexes', function (t) {
        t.plan(1);
        t.throws(
            function () { throw err; },
            {
                // The `name` and `message` properties are strings and using regular
                // expressions on those will match against the string. If they fail, an
                // error is thrown.
                name: /^TypeError$/,
                message: /Wrong/,
                foo: 'bar',
                info: {
                    nested: true,
                    // It is not possible to use regular expressions for nested properties!
                    baz: 'text'
                },
                // The `reg` property contains a regular expression and only if the
                // validation object contains an identical regular expression, it is going
                // to pass.
                reg: /abc/i
            },
            'object with regex values is validated'
        );
        t.end();
    });

    test('similar error object', function (t) {
        t.plan(1);
        t.throws(
            function () {
                var otherErr = new TypeError('Not found');
                // Copy all enumerable properties from `err` to `otherErr`.
                assign(otherErr, err);
                throw otherErr;
            },
            // The error's `message` and `name` properties will also be checked when using
            // an error as validation object.
            err,
            'throwing a similar error'
        );
        t.end();
    });

    test('validate with regex', function (t) {
        t.plan(1);
        t.throws(
            function () { throw new Error('Wrong value'); },
            /^Error: Wrong value$/,
            'regex against toString of error'
        );
        t.end();
    });

    test('custom error validation', function (t) {
        t.plan(3);
        t.throws(
            function () { throw new SyntaxError('Wrong value'); },
            function (error) {
                t.ok(error instanceof SyntaxError, 'error is SyntaxError');
                t.ok((/value/).test(error), 'error matches /value/');
                // Avoid returning anything from validation functions besides `true`.
                // Otherwise, it's not clear what part of the validation failed. Instead,
                // throw an error about the specific validation that failed (as done in this
                // example) and add as much helpful debugging information to that error as
                // possible.
                return true;
            },
            'unexpected error'
        );
        t.end();
    });

    test('throwing primitives', function (t) {
        [null, undefined, 0, NaN, 42, Infinity, '', 'foo', true, false].forEach(function (primitive) {
            t.throws(function () { throw primitive; }, 'primitive: ' + inspect(primitive));
        });

        t.end();
    });

    test('ambiguous arguments', function (t) {
        function throwingFirst() {
            throw new Error('First');
        }

        function throwingSecond() {
            throw new Error('Second');
        }

        function notThrowing() {}

        // The second argument is a string and the input function threw an Error.
        // The first case will not throw as it does not match for the error message
        // thrown by the input function!
        t.throws(throwingFirst, 'Second');
        // In the next example the message has no benefit over the message from the
        // error and since it is not clear if the user intended to actually match
        // against the error message, Node.js throws an `ERR_AMBIGUOUS_ARGUMENT` error.
        t.throws(throwingSecond, 'Second');
        // TypeError [ERR_AMBIGUOUS_ARGUMENT]

        // The string is only used (as message) in case the function does not throw:
        t.doesNotThrow(notThrowing, 'Second');
        // AssertionError [ERR_ASSERTION]: Missing expected exception: Second

        // If it was intended to match for the error message do this instead:
        // It does not fail because the error messages match.
        t.throws(throwingSecond, /Second$/);

        // If the error message does not match, an AssertionError is thrown.
        t.throws(throwingFirst, /Second$/);
        // AssertionError [ERR_ASSERTION]
        t.end();
    });
});
<|endoftext|>


<commit_before>
var sdb = require('../');
var async = require('simpleasync');

var connection;

var adamId;

exports['get connection'] = function (test) {
    test.async();

    sdb.connection(function (err, conn) {
        test.ok(!err);
        test.ok(conn);

        test.equal(typeof conn, 'object');

        connection = conn;

        test.done();
    });
};

exports['create database'] = function (test) {
    test.async();

    sdb.dbCreate('company').run(connection, function (err, data) {
        test.ok(!err);
        test.ok(data);
        test.done();
    });
};

exports['create table'] = function (test) {
    test.async();

    async()
    .exec(function (next) { sdb.db('company').tableCreate('persons').run(connection, next); })
    .then(function (data, next) {
        test.ok(data);
        test.equal(typeof data, 'object');

        test.ok(data.config_changes);
        test.ok(Array.isArray(data.config_changes));
        test.ok(data.tables_created);
        test.equal(data.tables_created, 1);

        test.done();
    });
}

exports['insert document'] = function (test) {
    test.async();

    var doc = { name: 'Adam' };

    async()
    .exec(function (next) {
        sdb
        .db('company')
        .table('persons')
        .insert(doc)
        .run(connection, next);
    })
    .then(function (result, next) {
        test.ok(result);
        test.equal(result.inserted, 1);
        test.equal(result.errors, 0);
        test.ok(result.generated_keys);
        test.equal(result.generated_keys.length, 1);
        test.equal(result.generated_keys[0], 1);

        adamId = result.generated_keys[0];

        test.done();
    })
};

exports['update document with new value'] = function (test) {
    test.async();

    async()
    .exec(function (next) {
        sdb
        .db('company')
        .table('persons')
        .get(adamId)
        .update({ age: 800 })
        .run(connection, next);
    })
    .then(function (data, next) {
        test.ok(data);
        test.equal(data.deleted, 0);
        test.equal(data.errors, 0);
        test.equal(data.inserted, 0);
        test.ok(Array.isArray(data.changes));
        test.equal(data.changes.length, 0);
        test.deepEqual(data.changes, []);
        test.equal(data.replaced, 1);
        test.equal(data.skipped, 0);
        test.equal(data.unchanged, 0);

        sdb
        .db('company')
        .table('persons')
        .get(adamId)
        .run(connection, next);
    })
    .then(function (data, next) {
        test.ok(data);

        test.equal(data.id, adamId);
        test.equal(data.name, "Adam");
        test.equal(data.age, 800);

        test.done();
    });
};

exports['update column with column expression'] = function (test) {
    test.async();

    async()
    .exec(function (next) {
        sdb
        .db('company')
        .table('persons')
        .get(adamId)
        .update({ username: sdb.row('name') })
        .run(connection, next);
    })
    .then(function (data, next) {
        test.ok(data);
        test.equal(data.deleted, 0);
        test.equal(data.errors, 0);
        test.equal(data.inserted, 0);
        test.ok(Array.isArray(data.changes));
        test.equal(data.changes.length, 0);
        test.deepEqual(data.changes, []);
        test.equal(data.replaced, 1);
        test.equal(data.skipped, 0);
        test.equal(data.unchanged, 0);

        sdb
        .db('company')
        .table('persons')
        .get(adamId)
        .run(connection, next);
    })
    .then(function (data, next) {
        test.ok(data);

        test.equal(data.id, adamId);
        test.equal(data.name, "Adam");
        test.equal(data.username, "Adam");
        test.equal(data.age, 800);

        test.done();
    });
};

exports['Update Column with Add Expression'] = function (test) {
    var table = getTable();
	var result = table.insert({ name: 'Adam', age: 800 }).run();

    var id = result.keys[0];
    table.get(id).update({ age: sdb.row('age').add(100) }).run();

    var document = table.get(id).run();

    test.ok(document);
    test.equal(document.id, id);
    test.equal(document.name, 'Adam');
    test.equal(document.age, 900);

	test.done();
};

exports['Update Column with Sub Expression'] = function (test) {
    var table = getTable();
	var result = table.insert({ name: 'Adam', age: 800 }).run();

    var id = result.keys[0];
    table.get(id).update({ age: sdb.row('age').sub(100) }).run();

    var document = table.get(id).run();

    test.ok(document);
    test.equal(document.id, id);
    test.equal(document.name, 'Adam');
    test.equal(document.age, 700);

	test.done();
};
<commit_msg>Update column with add expression<commit_after>
var sdb = require('../');
var async = require('simpleasync');

var connection;

var adamId;

exports['get connection'] = function (test) {
    test.async();

    sdb.connection(function (err, conn) {
        test.ok(!err);
        test.ok(conn);

        test.equal(typeof conn, 'object');

        connection = conn;

        test.done();
    });
};

exports['create database'] = function (test) {
    test.async();

    sdb.dbCreate('company').run(connection, function (err, data) {
        test.ok(!err);
        test.ok(data);
        test.done();
    });
};

exports['create table'] = function (test) {
    test.async();

    async()
    .exec(function (next) { sdb.db('company').tableCreate('persons').run(connection, next); })
    .then(function (data, next) {
        test.ok(data);
        test.equal(typeof data, 'object');

        test.ok(data.config_changes);
        test.ok(Array.isArray(data.config_changes));
        test.ok(data.tables_created);
        test.equal(data.tables_created, 1);

        test.done();
    });
}

exports['insert document'] = function (test) {
    test.async();

    var doc = { name: 'Adam' };

    async()
    .exec(function (next) {
        sdb
        .db('company')
        .table('persons')
        .insert(doc)
        .run(connection, next);
    })
    .then(function (result, next) {
        test.ok(result);
        test.equal(result.inserted, 1);
        test.equal(result.errors, 0);
        test.ok(result.generated_keys);
        test.equal(result.generated_keys.length, 1);
        test.equal(result.generated_keys[0], 1);

        adamId = result.generated_keys[0];

        test.done();
    })
};

exports['update document with new value'] = function (test) {
    test.async();

    async()
    .exec(function (next) {
        sdb
        .db('company')
        .table('persons')
        .get(adamId)
        .update({ age: 800 })
        .run(connection, next);
    })
    .then(function (data, next) {
        test.ok(data);
        test.equal(data.deleted, 0);
        test.equal(data.errors, 0);
        test.equal(data.inserted, 0);
        test.ok(Array.isArray(data.changes));
        test.equal(data.changes.length, 0);
        test.deepEqual(data.changes, []);
        test.equal(data.replaced, 1);
        test.equal(data.skipped, 0);
        test.equal(data.unchanged, 0);

        sdb
        .db('company')
        .table('persons')
        .get(adamId)
        .run(connection, next);
    })
    .then(function (data, next) {
        test.ok(data);

        test.equal(data.id, adamId);
        test.equal(data.name, "Adam");
        test.equal(data.age, 800);

        test.done();
    });
};

exports['update column with column expression'] = function (test) {
    test.async();

    async()
    .exec(function (next) {
        sdb
        .db('company')
        .table('persons')
        .get(adamId)
        .update({ username: sdb.row('name') })
        .run(connection, next);
    })
    .then(function (data, next) {
        test.ok(data);
        test.equal(data.deleted, 0);
        test.equal(data.errors, 0);
        test.equal(data.inserted, 0);
        test.ok(Array.isArray(data.changes));
        test.equal(data.changes.length, 0);
        test.deepEqual(data.changes, []);
        test.equal(data.replaced, 1);
        test.equal(data.skipped, 0);
        test.equal(data.unchanged, 0);

        sdb
        .db('company')
        .table('persons')
        .get(adamId)
        .run(connection, next);
    })
    .then(function (data, next) {
        test.ok(data);

        test.equal(data.id, adamId);
        test.equal(data.name, "Adam");
        test.equal(data.username, "Adam");
        test.equal(data.age, 800);

        test.done();
    });
};

exports['update column with add expression'] = function (test) {
    test.async();

    async()
    .exec(function (next) {
        sdb
        .db('company')
        .table('persons')
        .get(adamId)
        .update({ age: sdb.row('age').add(100) })
        .run(connection, next);
    })
    .then(function (data, next) {
        test.ok(data);
        test.equal(data.deleted, 0);
        test.equal(data.errors, 0);
        test.equal(data.inserted, 0);
        test.ok(Array.isArray(data.changes));
        test.equal(data.changes.length, 0);
        test.deepEqual(data.changes, []);
        test.equal(data.replaced, 1);
        test.equal(data.skipped, 0);
        test.equal(data.unchanged, 0);

        sdb
        .db('company')
        .table('persons')
        .get(adamId)
        .run(connection, next);
    })
    .then(function (data, next) {
        test.ok(data);

        test.equal(data.id, adamId);
        test.equal(data.name, "Adam");
        test.equal(data.username, "Adam");
        test.equal(data.age, 900);

        test.done();
    });
};

exports['Update Column with Sub Expression'] = function (test) {
    var table = getTable();
	var result = table.insert({ name: 'Adam', age: 800 }).run();

    var id = result.keys[0];
    table.get(id).update({ age: sdb.row('age').sub(100) }).run();

    var document = table.get(id).run();

    test.ok(document);
    test.equal(document.id, id);
    test.equal(document.name, 'Adam');
    test.equal(document.age, 700);

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


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

  var vectorious = require('../vectorious'),
      assert = require('assert');

  var Matrix = vectorious.Matrix;
  var Vector = vectorious.Vector;

  describe('Vector', function() {
    describe('.add()', function() {
      it('should return empty vector if adding two empty vectors', function() {
        var a = new Vector();
        var b = new Vector();

        assert.deepEqual(new Vector(), a.add(b));
      });

      it('should throw error if sizes do not match', function() {
        var a = new Vector(1);
        var b = new Vector(1, 2);

        assert.throws(a.add.bind(a, b), Error);
      });

      it('should work as expected', function() {
        var a = new Vector(1, 2, 3);
        var b = new Vector(4, 5, 6);
        var c = new Vector(5, 7, 9);

        assert.deepEqual(c, a.add(b));
      });
    });

    describe('.subtract()', function() {
      it('should return empty vector if subtracting two empty vectors', function() {
        var a = new Vector();
        var b = new Vector();

        assert.deepEqual(new Vector(), a.subtract(b));
      });

      it('should throw error if sizes do not match', function() {
        var a = new Vector(1);
        var b = new Vector(1, 2);

        assert.throws(a.subtract.bind(a, b), Error);
      });

      it('should work as expected', function() {
        var a = new Vector(1, 2, 3);
        var b = new Vector(4, 5, 6);
        var c = new Vector(-3, -3, -3);

        assert.deepEqual(c, a.subtract(b));
      });
    });

    describe('.scale()', function() {
      it('should work as expected', function() {
        var a = new Vector(1, 2, 3);
        var b = new Vector(2, 4, 6);

        assert.deepEqual(b, a.scale(2));
      });
    });

    describe('.normalize()', function() {
      it('should work as expected', function() {
        var a = new Vector(1, 1);
        var b = new Vector(1 / Math.sqrt(2), 1 / Math.sqrt(2));

        assert.deepEqual(b, a.normalize());
      });
    });

    describe('.project()', function() {
      it('should throw error if sizes do not match', function() {
        var a = new Vector(1);
        var b = new Vector(1, 2);

        assert.throws(a.project.bind(a, b), Error);
      });

      it('should work as expected', function() {
        var a = new Vector(2, 1);
        var b = new Vector(-3, 4);
        var c = new Vector(6 / 25, -8 / 25);

        assert.deepEqual(c, a.project(b));
      });
    });

    describe('.zeros()', function() {
      it('should throw error if argument < 0', function() {
        assert.throws(new Vector().zeros.bind(new Vector(), -1), Error);
      });

      it('should return empty vector if argument === 0', function() {
        assert.deepEqual(new Vector(), new Vector().zeros(0));
      });

      it('should work as expected', function() {
        assert.deepEqual(new Vector(0, 0, 0), new Vector().zeros(3));
      });
    });

    describe('.ones()', function() {
      it('should throw error if argument < 0', function() {
        assert.throws(new Vector().ones.bind(new Vector(), -1), Error);
      });

      it('should return empty vector if argument === 0', function() {
        assert.deepEqual(new Vector(), new Vector().ones(0));
      });

      it('should work as expected', function() {
        assert.deepEqual(new Vector(1, 1, 1), new Vector().ones(3));
      });
    });

    describe('.range()', function() {
      it('should throw error if wrong number or arguments supplied', function() {
        assert.throws(Vector.range.bind(new Vector(), 1), Error);
        assert.throws(Vector.range.bind(new Vector(), 1, 2, 3, 4), Error);
      });

      it('should throw error if step > start - end', function() {
        assert.throws(Vector.range.bind(new Vector(), 0, 0), Error);
        assert.throws(Vector.range.bind(new Vector(), 1, 3, 2), Error);
      });

      it('should work as expected', function() {
        var a = Vector.range(0, 5);
        var b = Vector.range(5, 2, 10);
        var c = Vector.range(5, 0);
        var d = Vector.range(5, 2, 0);

        assert.deepEqual(new Vector(0, 1, 2, 3, 4), a);
        assert.deepEqual(new Vector(5, 7, 9), b);
        assert.deepEqual(new Vector(5, 4, 3, 2, 1), c);
        assert.deepEqual(new Vector(5, 3, 1), d);
      });
    });

    describe('.dot()', function() {
      it('should throw error if sizes do not match', function() {
        var a = new Vector(1);
        var b = new Vector(1, 2);

        assert.throws(a.dot.bind(a, b), Error);
      });

      it('should work as expected', function() {
        var a = new Vector(1, 2, 3);
        var b = new Vector(4, 5, 6);

        assert.equal(32, a.dot(b));
      });
    });

    describe('.magnitude()', function() {
      it('should return 0 if empty vector', function() {
        assert.equal(0, new Vector().magnitude());
      });

      it('should work as expected', function() {
        assert.equal(4, new Vector(1, 1, 1, 2, 3).magnitude());
      });
    });

    describe('.angle()', function() {
      it('should work as expected', function() {
        var a = new Vector(1, 0);
        var b = new Vector(0, 1);

        assert.equal(Math.PI / 2, a.angle(b));
      });
    });

    describe('.equals()', function() {
      it('should work as expected', function() {
        assert.equal(true, new Vector(1, 3, 2).equals(new Vector(1, 3, 2)));
        assert.equal(true, new Vector().equals(new Vector()));
        assert.equal(false, new Vector(1, 2, 3).equals(new Vector(1, 3, 2)));
      });
    });

    describe('.get()', function() {
      it('should throw error if index out of bounds', function() {
        var a = new Vector(1, 2, 3);
        assert.throws(a.get.bind(a, -1), Error);
        assert.throws(a.get.bind(a, 3), Error);
      });

      it('should work as expected', function() {
        var a = new Vector(1, 3, 2, 4);
        assert.equal(1, a.get(0));
        assert.equal(3, a.get(1));
        assert.equal(2, a.get(2));
        assert.equal(4, a.get(3));
      });
    });

    describe('.min()', function() {
      it('should work as expected', function() {
        var a = new Vector(1, 2, 3);
        var b = new Vector(3, -1, 1);
        var c = new Vector(2, 5, 1);

        assert.equal(1, a.min());
        assert.equal(-1, b.min());
        assert.equal(1, c.min());
      });
    });

    describe('.max()', function() {
      it('should work as expected', function() {
        var a = new Vector(1, 2, 3);
        var b = new Vector(3, -1, 1);
        var c = new Vector(2, 5, 1);

        assert.equal(3, a.max());
        assert.equal(3, b.max());
        assert.equal(5, c.max());
      });
    });

    describe('.set()', function() {
      it('should throw error if index out of bounds', function() {
        var a = new Vector(1, 2);
        assert.throws(a.set.bind(a, -1, 0), Error);
        assert.throws(a.set.bind(a, 2, 0), Error);
      });

      it('should work as expected', function() {
        var a = new Vector(1, 2);
        a.set(0, 0);
        a.set(1, 1);
        assert.equal(0, a.get(0));
        assert.equal(1, a.get(1));
      });
    });

    describe('.combine()', function() {
      it('should return current vector if combined with empty vector', function() {
        assert.deepEqual(new Vector(1, 2, 3), new Vector(1, 2, 3).combine(new Vector()));
      });

      it('should work as expected', function() {
        assert.deepEqual(new Vector(1, 2, 3, 0, 1), new Vector(1, 2, 3).combine(new Vector(0, 1)));
      });
    });

    describe('.push()', function() {
      it('should work as expected', function() {
        assert.deepEqual(new Vector(1, 2, 3), new Vector(1, 2).push(3));
      });
    });

    describe('.map()', function() {
      it('should work as expected', function() {
        var a = new Vector(1, 2, 3);
        var b = a.map(function(value) { return value * value });

        assert.deepEqual(new Vector(1, 4, 9), b);
      });
    });

    describe('.each()', function() {
      it('should work as expected', function() {
        var a = new Vector(1, 2, 3);
        var b = new Vector();
        a.each(function(value, index) {
          b.push(value * index);
        });

        assert.deepEqual(new Vector(0, 2, 6), b);
      });
    });

    describe('.toString()', function() {
      it('should work as expected', function() {
        assert.equal('[1, 2, 3]', new Vector(1, 2, 3).toString());
      });
    });

    describe('.toArray()', function() {
      it('should work as expected', function() {
        assert.deepEqual([1, 2, 3], new Vector(1, 2, 3).toArray());
      });
    });
  });
})();<commit_msg>More information on what the tests are actually doing (shows in mocha output)<commit_after>(function() {
  'use strict';

  var vectorious = require('../vectorious'),
      assert = require('assert');

  var Matrix = vectorious.Matrix;
  var Vector = vectorious.Vector;

  describe('Vector', function() {
    describe('.add()', function() {
      it('should return empty vector if adding two empty vectors', function() {
        var a = new Vector();
        var b = new Vector();

        assert.deepEqual(new Vector(), a.add(b));
      });

      it('should throw error if sizes do not match', function() {
        var a = new Vector(1);
        var b = new Vector(1, 2);

        assert.throws(a.add.bind(a, b), Error);
      });

      it('should produce Vector(5, 7, 9) from Vector(1, 2, 3) and Vector(4, 5, 6)', function() {
        var a = new Vector(1, 2, 3);
        var b = new Vector(4, 5, 6);
        var c = new Vector(5, 7, 9);

        assert.deepEqual(c, a.add(b));
      });
    });

    describe('.subtract()', function() {
      it('should return empty vector if subtracting two empty vectors', function() {
        var a = new Vector();
        var b = new Vector();

        assert.deepEqual(new Vector(), a.subtract(b));
      });

      it('should throw error if sizes do not match', function() {
        var a = new Vector(1);
        var b = new Vector(1, 2);

        assert.throws(a.subtract.bind(a, b), Error);
      });

      it('should produce Vector(-3, -3, -3) from Vector(1, 2, 3) and Vector(4, 5, 6)', function() {
        var a = new Vector(1, 2, 3);
        var b = new Vector(4, 5, 6);
        var c = new Vector(-3, -3, -3);

        assert.deepEqual(c, a.subtract(b));
      });
    });

    describe('.scale()', function() {
      it('should scale Vector(1, 2, 3) by 2 to Vector(2, 4, 6)', function() {
        var a = new Vector(1, 2, 3);
        var b = new Vector(2, 4, 6);

        assert.deepEqual(b, a.scale(2));
      });
    });

    describe('.normalize()', function() {
      it('should work as expected', function() {
        var a = new Vector(1, 1);
        var b = new Vector(1 / Math.sqrt(2), 1 / Math.sqrt(2));

        assert.deepEqual(b, a.normalize());
      });
    });

    describe('.project()', function() {
      it('should throw error if sizes do not match', function() {
        var a = new Vector(1);
        var b = new Vector(1, 2);

        assert.throws(a.project.bind(a, b), Error);
      });

      it('should work as expected', function() {
        var a = new Vector(2, 1);
        var b = new Vector(-3, 4);
        var c = new Vector(6 / 25, -8 / 25);

        assert.deepEqual(c, a.project(b));
      });
    });

    describe('.zeros()', function() {
      it('should throw error if argument < 0', function() {
        assert.throws(new Vector().zeros.bind(new Vector(), -1), Error);
      });

      it('should return empty vector if argument === 0', function() {
        assert.deepEqual(new Vector(), new Vector().zeros(0));
      });

      it('should create Vector(0, 0, 0)', function() {
        assert.deepEqual(new Vector(0, 0, 0), new Vector().zeros(3));
      });
    });

    describe('.ones()', function() {
      it('should throw error if argument < 0', function() {
        assert.throws(new Vector().ones.bind(new Vector(), -1), Error);
      });

      it('should return empty vector if argument === 0', function() {
        assert.deepEqual(new Vector(), new Vector().ones(0));
      });

      it('should create Vector(1, 1, 1)', function() {
        assert.deepEqual(new Vector(1, 1, 1), new Vector().ones(3));
      });
    });

    describe('.range()', function() {
      it('should throw error if wrong number or arguments supplied', function() {
        assert.throws(Vector.range.bind(new Vector(), 1), Error);
        assert.throws(Vector.range.bind(new Vector(), 1, 2, 3, 4), Error);
      });

      it('should throw error if step > start - end', function() {
        assert.throws(Vector.range.bind(new Vector(), 0, 0), Error);
        assert.throws(Vector.range.bind(new Vector(), 1, 3, 2), Error);
      });

      it('should work as expected', function() {
        var a = Vector.range(0, 5);
        var b = Vector.range(5, 2, 10);
        var c = Vector.range(5, 0);
        var d = Vector.range(5, 2, 0);

        assert.deepEqual(new Vector(0, 1, 2, 3, 4), a);
        assert.deepEqual(new Vector(5, 7, 9), b);
        assert.deepEqual(new Vector(5, 4, 3, 2, 1), c);
        assert.deepEqual(new Vector(5, 3, 1), d);
      });
    });

    describe('.dot()', function() {
      it('should throw error if sizes do not match', function() {
        var a = new Vector(1);
        var b = new Vector(1, 2);

        assert.throws(a.dot.bind(a, b), Error);
      });

      it('should work as expected', function() {
        var a = new Vector(1, 2, 3);
        var b = new Vector(4, 5, 6);

        assert.equal(32, a.dot(b));
      });
    });

    describe('.magnitude()', function() {
      it('should return 0 if empty vector', function() {
        assert.equal(0, new Vector().magnitude());
      });

      it('should work as expected', function() {
        assert.equal(4, new Vector(1, 1, 1, 2, 3).magnitude());
      });
    });

    describe('.angle()', function() {
      it('should work as expected', function() {
        var a = new Vector(1, 0);
        var b = new Vector(0, 1);

        assert.equal(Math.PI / 2, a.angle(b));
      });
    });

    describe('.equals()', function() {
      it('should work as expected', function() {
        assert.equal(true, new Vector(1, 3, 2).equals(new Vector(1, 3, 2)));
        assert.equal(true, new Vector().equals(new Vector()));
        assert.equal(false, new Vector(1, 2, 3).equals(new Vector(1, 3, 2)));
      });
    });

    describe('.get()', function() {
      it('should throw error if index out of bounds', function() {
        var a = new Vector(1, 2, 3);
        assert.throws(a.get.bind(a, -1), Error);
        assert.throws(a.get.bind(a, 3), Error);
      });

      it('should work as expected', function() {
        var a = new Vector(1, 3, 2, 4);
        assert.equal(1, a.get(0));
        assert.equal(3, a.get(1));
        assert.equal(2, a.get(2));
        assert.equal(4, a.get(3));
      });
    });

    describe('.min()', function() {
      it('should work as expected', function() {
        var a = new Vector(1, 2, 3);
        var b = new Vector(3, -1, 1);
        var c = new Vector(2, 5, 1);

        assert.equal(1, a.min());
        assert.equal(-1, b.min());
        assert.equal(1, c.min());
      });
    });

    describe('.max()', function() {
      it('should work as expected', function() {
        var a = new Vector(1, 2, 3);
        var b = new Vector(3, -1, 1);
        var c = new Vector(2, 5, 1);

        assert.equal(3, a.max());
        assert.equal(3, b.max());
        assert.equal(5, c.max());
      });
    });

    describe('.set()', function() {
      it('should throw error if index out of bounds', function() {
        var a = new Vector(1, 2);
        assert.throws(a.set.bind(a, -1, 0), Error);
        assert.throws(a.set.bind(a, 2, 0), Error);
      });

      it('should work as expected', function() {
        var a = new Vector(1, 2);
        a.set(0, 0);
        a.set(1, 1);
        assert.equal(0, a.get(0));
        assert.equal(1, a.get(1));
      });
    });

    describe('.combine()', function() {
      it('should return current vector if combined with empty vector', function() {
        assert.deepEqual(new Vector(1, 2, 3), new Vector(1, 2, 3).combine(new Vector()));
      });

      it('should work as expected', function() {
        assert.deepEqual(new Vector(1, 2, 3, 0, 1), new Vector(1, 2, 3).combine(new Vector(0, 1)));
      });
    });

    describe('.push()', function() {
      it('should start with Vector(1, 2), push(3) to get Vector(1, 2, 3)', function() {
        assert.deepEqual(new Vector(1, 2, 3), new Vector(1, 2).push(3));
      });
    });

    describe('.map()', function() {
      it('should work as expected', function() {
        var a = new Vector(1, 2, 3);
        var b = a.map(function(value) { return value * value });

        assert.deepEqual(new Vector(1, 4, 9), b);
      });
    });

    describe('.each()', function() {
      it('should work as expected', function() {
        var a = new Vector(1, 2, 3);
        var b = new Vector();
        a.each(function(value, index) {
          b.push(value * index);
        });

        assert.deepEqual(new Vector(0, 2, 6), b);
      });
    });

    describe('.toString()', function() {
      it('should work as expected', function() {
        assert.equal('[1, 2, 3]', new Vector(1, 2, 3).toString());
      });
    });

    describe('.toArray()', function() {
      it('should work as expected', function() {
        assert.deepEqual([1, 2, 3], new Vector(1, 2, 3).toArray());
      });
    });
  });
})();<|endoftext|>


<commit_before>( function($) {
	$.fn.activesearch = function(options) {
		var options = $.extend({
			'type' : 'GET',
			'dataType' : 'json',
			'error' : function(d, e, x) {
				console.log("E: " + e);
				console.log("X: " + x);
				console.log("D: " + d);
			}
		}, options);

		return this.each(function() {
			var $this = $(this);

			$this.bind("keyup.activesearch", function(event) {
				var value = $this.val();
				if(value && value.length > 0) {
					$.ajax({ // TODO: cater for progressive loading
						url : options.url,
						data : options.params(value),
						type : options.type,
						dataType : options.dataType,
						success : function(data, xhr, status) {
							options.success(data, xhr, status);
						},
						error : function(d, e, x) {
							options.error(d, e, x);
						}
					});
				}
			});
		});
	}
}(jQuery));
<commit_msg>cleaned up the error functions<commit_after>( function($) {
	$.fn.activesearch = function(options) {
		var options = $.extend({
			'type' : 'GET',
			'dataType' : 'json',
			'error' : function(xhr, status, error) {
				console.log("Status: " + status);
				console.log("Error: " + error);
				console.log("XHR: " + xhr);
			}
		}, options);

		return this.each(function() {
			var $this = $(this);

			$this.bind("keyup.activesearch", function(event) {
				var value = $this.val();
				if(value && value.length > 0) {
					$.ajax({ // TODO: cater for progressive loading
						url : options.url,
						data : options.params(value),
						type : options.type,
						dataType : options.dataType,
						success : function(data, xhr, status) {
							options.success(data, xhr, status);
						},
						error : function(xhr, status, error) {
							options.error(xhr, status, error);
						}
					});
				}
			});
		});
	}
}(jQuery));
<|endoftext|>


<commit_before>'use strict'
process.env.NODE_ENV = 'production'

/**
 * --locale='zh-CN'
 * --namespace='vux'
 * --components=Group,Cell
 */

var argv = require('yargs').argv
var namespace = argv.namespace || 'vux'

var isBuildAll = !argv.components
var buildComponents = argv.components ? argv.components.split(',') : []

let config = require('./webpack.prod.conf.js')
const vuxConfig = require('./vux-config')
vuxConfig.plugins.forEach(function (plugin) {
  if (plugin.name === 'i18n') {
    plugin.vuxStaticReplace = true
    plugin.vuxLocale = argv['locale'] || 'zh-CN'
  }
})

const webpack = require('webpack')
const mkdirp = require('mkdirp')
const fs = require('fs')
const touch = require('touch')
const path = require('path')

mkdirp.sync(path.resolve(__dirname, '../dist/plugins'))
mkdirp.sync(path.resolve(__dirname, '../dist/styles'))

let list = require(path.resolve(__dirname, '../src/datas/vux_component_list.json'))
const maps = require(path.resolve(__dirname, '../src/components/map.json'))

// 查找在maps里但不在list里的组件
let others = []
for (let i in maps) {
  let match = list.filter(function (one) {
    return _camelCase(one.name) === i
  })
  if (match.length === 0 && !/Plugin|Data|Directive|Filter|Item|NOTICE|Demo|Dev|Tool|String|Number|md5|base64|cookie/.test(i)) {
    others.push({
      name: toDash(i),
      importName: i,
      path: maps[i]
    })
  }
}

others.push({
  name: 'swiper-item',
  importName: 'SwiperItem',
  path: maps['SwiperItem']
})

var ExtractTextPlugin = require('extract-text-webpack-plugin')
var co = require('co')
var thunkify = require('thunkify')
var pkg = require(path.resolve(__dirname, '../package.json'))

var build = thunkify(function (config, name, cb) {
  let start = new Date().getTime()
  console.log(`start:${name}`)
  webpack(config, function (err, stats) {
    if (!config.entry.vux) {
      mkdirp.sync(path.resolve(config.output.path))
        // touch.sync(path.resolve(config.output.path, './index.min.css'))
    }
    var jsonStats = stats.toJson()
    var assets = jsonStats.assets[0]
    var size = assets.size / 1024
    size = size.toFixed(2) + 'k'
    console.log('size', size)
    console.log('time', (new Date().getTime() - start) / 1000 + 's')
    console.log('----------------')
    cb && cb(err)
  })
})

var utils = require('./utils')
config.devtool = false
config.plugins = config.plugins.slice(0, -2)
config.plugins.forEach((one, index) => {
  if (one.constructor.name === 'HtmlWebpackPlugin') {
    config.plugins.splice(index, 1)
  }
  if (one.constructor.name === 'ExtractTextPlugin') {
    config.plugins.splice(index, 1)
  }
})

config.output.assetsPublicPath = '/'

let isBuilding = false

co(function* () {
  if (!isBuildAll) {
    return
  }
  try {
    for (let n = 0; n < others.length; n++) {
      yield build(buildConfig(others[n]), others[n].name)
    }
  } catch (e) {}
})

co(function* () {
  if (!isBuildAll) {
    return
  }
  try {
    yield build(buildMainConfig(), 'vux')
  } catch (e) {
    console.log(e)
  }
})

co(function* () {
  if (!isBuildAll) {
    return
  }
  try {
    const pluginList = ['Confirm', 'Toast', 'Device', 'Alert', 'Loading', ' Wechat', 'Ajax']
    for (let j = 0; j < pluginList.length; j++) {
      yield build(buildPlugin(pluginList[j]), `Plugin ${pluginList[j]}`)
    }
  } catch (e) {
    console.log(e)
  }
})

co(function* () {

  if (buildComponents.length) {
    list = list.filter(function (one) {
      return buildComponents.indexOf(_camelCase(one.name)) > -1
    })
  }

  try {
    for (let i = 0; i < list.length; i++) {
      let one = list[i]
      const name = list[i].name
      if (one.items) {
        // build a commonjs bundle
        yield build(buildConfig({
          name: list[i].name + '-pack',
          importName: _camelCase(list[i].name),
          path: `src/components/${name}/index.js`
        }), `pack: ${list[i].name}`)

        for (let j = 0; j < one.items.length; j++) {
          one.name = one.items[j]
          yield build(buildConfig(one), one.items[j])
        }
      } else {
        yield build(buildConfig(one), one.name)
      }
    }
  } catch (e) {
    console.log(e)
  }

})

function camelCase(input) {
  let str = input.toLowerCase().replace(/-(.)/g, function (match, group1) {
    return group1.toUpperCase();
  })
  str = str.replace(/_(.)/g, function (match, group1) {
    return group1.toUpperCase()
  });
  return str
}

function _camelCase(input) {
  let str = camelCase(input)
  return str.slice(0, 1).toUpperCase() + str.slice(1)
}

function buildMainConfig() {

  // list all components
  const list = require('../src/components/map.json')
  let code = 'const vux = {}\n'
  code += `/* only for building vux.css */
import Style from '../styles/index.vue'\n`

  delete list['NOTICE']
  delete list['ChinaAddressV1Data']

  for (let i in list) {
    const name = `${namespace}${i}`
    code += `import ${name} from '${list[i]}'\n
vux['${name}'] = ${name}\n`
  }

  code += `
if (!!window) {
  for (let i in vux) {
    window[i] = vux[i]
  }
}\n`
  code += `module.exports = vux`

  fs.writeFileSync(path.resolve(__dirname, '../src/components/index.js'), code)

  delete config.entry

  config.plugins.forEach((one, index) => {
    if (one.constructor.name === 'ExtractTextPlugin') {
      config.plugins.splice(index, 1)
    }
  })

  config.plugins.push(new ExtractTextPlugin({
    filename: `vux.min.css`
  }))

  config.entry = config.entry || {}
  config.entry['vux'] = 'src/components/index.js'
  config.output = {}
  config.output.libraryTarget = 'umd'
  config.output.library = `vux`
  config.output.filename = `vux.min.js`
  config.output.path = path.resolve(__dirname, `../dist/`)
  delete config.__vueOptions__
  return config
}

// build plugins
function buildPlugin(name) {
  delete config.entry

  config.plugins.forEach((one, index) => {
    if (one.constructor.name === 'ExtractTextPlugin') {
      config.plugins.splice(index, 1)
    }
  })

  config.plugins.push(new ExtractTextPlugin({
    filename: 'index.min.css'
  }))
  config.entry = config.entry || {}
  config.entry['plugin'] = `src/plugins/${name.toLowerCase()}/index.js`
  config.output = {}
  config.output.libraryTarget = 'umd'
  config.output.library = `${namespace}${name}Plugin`
  config.output.filename = `index.min.js`
  config.output.path = path.resolve(__dirname, `../dist/plugins/${name.toLowerCase()}`)
  delete config.__vueOptions__
  return config
}

function buildConfig(one, opts) {
  opts = opts || {}
  one.importName = one.importName || _camelCase(one.name)
  one.path = path.resolve(__dirname, '../' + (one.path || maps[one.importName]))

  delete config.entry

  config.plugins.forEach((one, index) => {
    if (one.constructor.name === 'ExtractTextPlugin') {
      config.plugins.splice(index, 1)
    }
  })

  config.plugins.push(new ExtractTextPlugin({
    filename: 'index.min.css'
  }))

  config.entry = {}
  config.entry[one.name] = one.path
  config.output = {}
  config.output.libraryTarget = 'umd'
  config.output.library = `${namespace}${one.importName}`
  config.output.filename = `index.min.js`
  config.output.path = path.resolve(__dirname, `../dist/components/${one.name}/`)
  delete config.__vueOptions__
  return config
}

function toDash(str) {
  return str.replace(/([A-Z])/g, function (m, w) {
    return '-' + w.toLowerCase();
  }).replace('-', '')
}<commit_msg>组件中的xxx-xxx-item文件夹下js未生成成功<commit_after>'use strict'
process.env.NODE_ENV = 'production'

/**
 * --locale='zh-CN'
 * --namespace='vux'
 * --components=Group,Cell
 */

var argv = require('yargs').argv
var namespace = argv.namespace || 'vux'

var isBuildAll = !argv.components
var buildComponents = argv.components ? argv.components.split(',') : []

let config = require('./webpack.prod.conf.js')
const vuxConfig = require('./vux-config')
vuxConfig.plugins.forEach(function (plugin) {
  if (plugin.name === 'i18n') {
    plugin.vuxStaticReplace = true
    plugin.vuxLocale = argv['locale'] || 'zh-CN'
  }
})

const webpack = require('webpack')
const mkdirp = require('mkdirp')
const fs = require('fs')
const touch = require('touch')
const path = require('path')

mkdirp.sync(path.resolve(__dirname, '../dist/plugins'))
mkdirp.sync(path.resolve(__dirname, '../dist/styles'))

let list = require(path.resolve(__dirname, '../src/datas/vux_component_list.json'))
const maps = require(path.resolve(__dirname, '../src/components/map.json'))

// 查找在maps里但不在list里的组件
let others = []
for (let i in maps) {
  let match = list.filter(function (one) {
    return _camelCase(one.name) === i
  })
  if (match.length === 0 && !/Plugin|Data|Directive|Filter|Item|NOTICE|Demo|Dev|Tool|String|Number|md5|base64|cookie/.test(i)) {
    others.push({
      name: toDash(i),
      importName: i,
      path: maps[i]
    })
  }
}

others.push({
  name: 'swiper-item',
  importName: 'SwiperItem',
  path: maps['SwiperItem']
})

var ExtractTextPlugin = require('extract-text-webpack-plugin')
var co = require('co')
var thunkify = require('thunkify')
var pkg = require(path.resolve(__dirname, '../package.json'))

var build = thunkify(function (config, name, cb) {
  let start = new Date().getTime()
  console.log(`start:${name}`)
  webpack(config, function (err, stats) {
    if (!config.entry.vux) {
      mkdirp.sync(path.resolve(config.output.path))
        // touch.sync(path.resolve(config.output.path, './index.min.css'))
    }
    var jsonStats = stats.toJson()
    var assets = jsonStats.assets[0]
    var size = assets.size / 1024
    size = size.toFixed(2) + 'k'
    console.log('size', size)
    console.log('time', (new Date().getTime() - start) / 1000 + 's')
    console.log('----------------')
    cb && cb(err)
  })
})

var utils = require('./utils')
config.devtool = false
config.plugins = config.plugins.slice(0, -2)
config.plugins.forEach((one, index) => {
  if (one.constructor.name === 'HtmlWebpackPlugin') {
    config.plugins.splice(index, 1)
  }
  if (one.constructor.name === 'ExtractTextPlugin') {
    config.plugins.splice(index, 1)
  }
})

config.output.assetsPublicPath = '/'

let isBuilding = false

co(function* () {
  if (!isBuildAll) {
    return
  }
  try {
    for (let n = 0; n < others.length; n++) {
      yield build(buildConfig(others[n]), others[n].name)
    }
  } catch (e) {}
})

co(function* () {
  if (!isBuildAll) {
    return
  }
  try {
    yield build(buildMainConfig(), 'vux')
  } catch (e) {
    console.log(e)
  }
})

co(function* () {
  if (!isBuildAll) {
    return
  }
  try {
    const pluginList = ['Confirm', 'Toast', 'Device', 'Alert', 'Loading', ' Wechat', 'Ajax']
    for (let j = 0; j < pluginList.length; j++) {
      yield build(buildPlugin(pluginList[j]), `Plugin ${pluginList[j]}`)
    }
  } catch (e) {
    console.log(e)
  }
})

co(function* () {

  if (buildComponents.length) {
    list = list.filter(function (one) {
      return buildComponents.indexOf(_camelCase(one.name)) > -1
    })
  }

  try {
    for (let i = 0; i < list.length; i++) {
      let one = list[i]
      const name = list[i].name
      if (one.items) {
        // build a commonjs bundle
        yield build(buildConfig({
          name: list[i].name + '-pack',
          importName: _camelCase(list[i].name),
          path: `src/components/${name}/index.js`
        }), `pack: ${list[i].name}`)

        for (let j = 0; j < one.items.length; j++) {
          one.name = one.items[j]
          one.path = maps[one.importName]
          yield build(buildConfig(one), one.items[j])
        }
      } else {
        yield build(buildConfig(one), one.name)
      }
    }
  } catch (e) {
    console.log(e)
  }

})

function camelCase(input) {
  let str = input.toLowerCase().replace(/-(.)/g, function (match, group1) {
    return group1.toUpperCase();
  })
  str = str.replace(/_(.)/g, function (match, group1) {
    return group1.toUpperCase()
  });
  return str
}

function _camelCase(input) {
  let str = camelCase(input)
  return str.slice(0, 1).toUpperCase() + str.slice(1)
}

function buildMainConfig() {

  // list all components
  const list = require('../src/components/map.json')
  let code = 'const vux = {}\n'
  code += `/* only for building vux.css */
import Style from '../styles/index.vue'\n`

  delete list['NOTICE']
  delete list['ChinaAddressV1Data']

  for (let i in list) {
    const name = `${namespace}${i}`
    code += `import ${name} from '${list[i]}'\n
vux['${name}'] = ${name}\n`
  }

  code += `
if (!!window) {
  for (let i in vux) {
    window[i] = vux[i]
  }
}\n`
  code += `module.exports = vux`

  fs.writeFileSync(path.resolve(__dirname, '../src/components/index.js'), code)

  delete config.entry

  config.plugins.forEach((one, index) => {
    if (one.constructor.name === 'ExtractTextPlugin') {
      config.plugins.splice(index, 1)
    }
  })

  config.plugins.push(new ExtractTextPlugin({
    filename: `vux.min.css`
  }))

  config.entry = config.entry || {}
  config.entry['vux'] = 'src/components/index.js'
  config.output = {}
  config.output.libraryTarget = 'umd'
  config.output.library = `vux`
  config.output.filename = `vux.min.js`
  config.output.path = path.resolve(__dirname, `../dist/`)
  delete config.__vueOptions__
  return config
}

// build plugins
function buildPlugin(name) {
  delete config.entry

  config.plugins.forEach((one, index) => {
    if (one.constructor.name === 'ExtractTextPlugin') {
      config.plugins.splice(index, 1)
    }
  })

  config.plugins.push(new ExtractTextPlugin({
    filename: 'index.min.css'
  }))
  config.entry = config.entry || {}
  config.entry['plugin'] = `src/plugins/${name.toLowerCase()}/index.js`
  config.output = {}
  config.output.libraryTarget = 'umd'
  config.output.library = `${namespace}${name}Plugin`
  config.output.filename = `index.min.js`
  config.output.path = path.resolve(__dirname, `../dist/plugins/${name.toLowerCase()}`)
  delete config.__vueOptions__
  return config
}

function buildConfig(one, opts) {
  opts = opts || {}
  one.importName = one.importName || _camelCase(one.name)
  one.path = path.resolve(__dirname, '../' + (one.path || maps[one.importName]))

  delete config.entry

  config.plugins.forEach((one, index) => {
    if (one.constructor.name === 'ExtractTextPlugin') {
      config.plugins.splice(index, 1)
    }
  })

  config.plugins.push(new ExtractTextPlugin({
    filename: 'index.min.css'
  }))

  config.entry = {}
  config.entry[one.name] = one.path
  config.output = {}
  config.output.libraryTarget = 'umd'
  config.output.library = `${namespace}${one.importName}`
  config.output.filename = `index.min.js`
  config.output.path = path.resolve(__dirname, `../dist/components/${one.name}/`)
  delete config.__vueOptions__
  return config
}

function toDash(str) {
  return str.replace(/([A-Z])/g, function (m, w) {
    return '-' + w.toLowerCase();
  }).replace('-', '')
}<|endoftext|>


<commit_before>import React, { Component } from 'react';
require('./businessProfileCss.css');

class BusinessLandingPage extends Component {
  render() {
    return(

{window.businessInfo.name}

 {window.businessInfo.phone}

Address: {window.businessInfo.address} {window.businessInfo.city}, {window.businessInfo.state} {window.businessInfo.country} {window.businessInfo.zip}

Website: {window.businessInfo.website}

{console.log(window.businessInfo)}

    )
  }
}

export default BusinessLandingPage;
<commit_msg>conditionally render business landing page address2<commit_after>import React, { Component } from 'react';
require('./businessProfileCss.css');

class BusinessLandingPage extends Component {
  render() {
    let businessInfo = null;
    if(window.businessInfo.address2 === null) {
      businessInfo =

{window.businessInfo.name}

 {window.businessInfo.phone}

Address:  {window.businessInfo.address} {window.businessInfo.city}, {window.businessInfo.state} {window.businessInfo.country} {window.businessInfo.zip}

Website: {window.businessInfo.website}

{console.log(window.businessInfo)}

    } else {
      businessInfo =

{window.businessInfo.name}

 {window.businessInfo.phone}

Address:  {window.businessInfo.address} {window.businessInfo.address2} {window.businessInfo.city}, {window.businessInfo.state} {window.businessInfo.country} {window.businessInfo.zip}

Website: {window.businessInfo.website}

{console.log(window.businessInfo)}

    }
    return(

        {businessInfo}

    )
  }
}

export default BusinessLandingPage;
<|endoftext|>


<commit_before>var XWiki = (function defineUserPicker(XWiki) {

// Start XWiki augmentation.
var widgets = XWiki.widgets;
// TODO: Use require.js here when we move away from Prototype.js
if (!widgets || !widgets.SuggestPicker) {
  var tryCount = arguments[1] || 0;
  if (tryCount > 5) {
    console.error('Failed to define the UserPicker module: required dependency SuggestPicker is missing.');
  } else {
    setTimeout(defineUserPicker.bind(window, XWiki, tryCount + 1), 0);
  }
  return XWiki;
}

/**
 * Extends the SuggestPicker to customize the way the selected users are displayed.
 */
var SelectionManager = Class.create(widgets.SuggestPicker, {
  // @Override
  matchesSelectedValue: function(value, suggestion) {
    // The given value can be a relative user reference. We need to parse it and match only the user alias.
    return XWiki.Model.resolve(value, XWiki.EntityType.DOCUMENT).name == suggestion.id;
  },

  // @Override
  getDefaultSuggestion: function(value) {
    var userReference = XWiki.Model.resolve(value, XWiki.EntityType.DOCUMENT);
    return {
      id: userReference.name,
      value: value,
      info: userReference.name,
      icon: "$xwiki.getSkinFile('icons/xwiki/noavatar.png')"
    };
  },

  // @Override
  addItem: function($super, suggestion) {
    // Clear the previously selected user in single selection mode.
    this.input.hasClassName('multipleSelection') || this.list.update('');
    $super(suggestion);
  },

  // @Override
  displayItem: function(suggestion) {
    var itemDisplay = this.suggest.createItemDisplay(suggestion, {});
    itemDisplay.down('.user-name').insert(this.createDeleteTool());
    return new Element('li').insert(itemDisplay).insert(this.createItemInput(suggestion));
  }
});

/**
 * Enhances a plain HTML text input with the ability to suggest users.
 */
widgets.UserPicker = Class.create(widgets.Suggest, {
  // @Override
  initialize: function($super, input, options) {
    $super(input, Object.extend({
      varname: "input",
      enableHideButton: false,
      timeout: 30000
    }, options || {}));

    var listInsertionElement = input;
    // The scope toggle doesn't make sense when global users are required.
    if (input.hasClassName('withScope') && !input.hasClassName('global')) {
      this._sourceURL = options.script;
      this._createScope();
      listInsertionElement = input.up();
    }
    this._selectionManager = this._createSelectionManager({
      listInsertionElement: listInsertionElement,
      listInsertionPosition : 'before',
      acceptFreeText : true
    });
    this.multipleSelection = input.hasClassName('multipleSelection');
    // Keep a reference to this user picker instance if the target input has the ID attribute specified.
    if (input.id != '') {
      widgets.UserPicker.instances[input.id] = this;
    }
  },

  // @Override
  createItemDisplay: function(data, source) {
    var container = new Element('div', {'class': 'user'});
    var avatarWrapper = new Element('div', {'class': 'user-avatar-wrapper'});
    avatarWrapper.insert(new Element('img', {src: data.icon, alt: data.info, 'class': 'icon'}));
    container.insert(avatarWrapper);
    var userName = source.highlight ? this.emphasizeMatches(this.sInput, data.info) : data.info;
    container.insert(new Element('div', {'class': 'user-name'}).update(userName));
    var userAlias = source.highlight ? this.emphasizeMatches(this.sInput, data.id) : data.id;
    container.insert(new Element('div', {'class': 'user-alias'}).update(userAlias));
    return container;
  },

  /**
   * Clears the content of the target input and the current selection.
   */
  clear : function() {
    this.fld.clear();
    this._selectionManager.clearAcceptedList();
  },

  /**
   * Determines the selection manager that is going to be used. Derived classes can override this method if they want
   * to use a different selection manager.
   */
  _createSelectionManager: function(options) {
    return new SelectionManager(this.fld, this, options);
  },

  _createScope: function() {
    this._scope = new Element('input', {
      type: 'image',
      'class': 'scope',
      alt: "$services.localization.render('core.widgets.userPicker.scopeHint')",
      title: "$services.localization.render('core.widgets.userPicker.scopeHint')"
    });
    // Group the scope and the input.
    var wrapper = new Element('span').insert(this._scope);
    this.fld.insert({before: wrapper});
    wrapper.insert(this.fld);
    // Add click handler.
    this._scope.observe('click', this._toggleScope.bindAsEventListener(this));
    // Initialize the scope value.
    this._toggleScope();
  },

  /**
   * Toggles between local and global scope.
   */
  _toggleScope: function(event) {
    event && event.stop();
    if (this._scope.value == 'local') {
      this._scope.value = 'global';
      this._scope.src = "$xwiki.getSkinFile('icons/silk/world.png')";
    } else {
      this._scope.value = 'local';
      this._scope.src = "$xwiki.getSkinFile('icons/silk/world_delete.png')";
    }
    this.sources[0].script = this._sourceURL + 'wiki=' + this._scope.value + '&';
  },

  // @Override
  detach: function($super) {
    // Remove the list of accepted suggestions.
    this._selectionManager && this._selectionManager.detach();

    // Remove the scope toggle.
    this._scope && this._scope.stopObserving('click').up().insert({before: this.fld}).remove();

    $super();
  }
});
// Used to access the created user pickers.
widgets.UserPicker.instances = {};

var init = function(event) {
  var suggestionsMapping = {
    users: {
      script: XWiki.currentDocument.getURL('get', 'xpage=uorgsuggest&uorg=user&'),
      noresults: "$services.localization.render('core.widgets.userPicker.noResults')"
    },
    groups: {
      script: XWiki.currentDocument.getURL('get', 'xpage=uorgsuggest&uorg=group&'),
      noresults: "$services.localization.render('core.widgets.groupPicker.noResults')"
    }
  }
  var containers = (event && event.memo.elements) || [$('body')];
  Object.keys(suggestionsMapping).each(function(key) {
    containers.each(function(container) {
      container.select('input.suggest' + key.capitalize()).each(function(input) {
        if (!input.hasClassName('initialized')) {
          var options = Object.clone(suggestionsMapping[key]);
          // The picker suggests by default local users or groups.
          if (input.hasClassName('global')) {
            // Suggest global users or groups.
            options.script = options.script + 'wiki=global&';
          }
          new widgets.UserPicker(input, options);
          input.addClassName('initialized');
        }
      });
    });
  });
  return true;
};
(XWiki.domIsLoaded && init()) || document.observe('xwiki:dom:loaded', init);
document.observe('xwiki:dom:updated', init);

// End XWiki augmentation.
return XWiki;
})(XWiki || {});
<commit_msg>XWIKI-11813: Be able to see the user reference in the user displayer in edit mode<commit_after>var XWiki = (function defineUserPicker(XWiki) {

// Start XWiki augmentation.
var widgets = XWiki.widgets;
// TODO: Use require.js here when we move away from Prototype.js
if (!widgets || !widgets.SuggestPicker) {
  var tryCount = arguments[1] || 0;
  if (tryCount > 5) {
    console.error('Failed to define the UserPicker module: required dependency SuggestPicker is missing.');
  } else {
    setTimeout(defineUserPicker.bind(window, XWiki, tryCount + 1), 0);
  }
  return XWiki;
}

/**
 * Extends the SuggestPicker to customize the way the selected users are displayed.
 */
var SelectionManager = Class.create(widgets.SuggestPicker, {
  // @Override
  matchesSelectedValue: function(value, suggestion) {
    // The given value can be a relative user reference. We need to parse it and match only the user alias.
    return XWiki.Model.resolve(value, XWiki.EntityType.DOCUMENT).name == suggestion.id;
  },

  // @Override
  getDefaultSuggestion: function(value) {
    var userReference = XWiki.Model.resolve(value, XWiki.EntityType.DOCUMENT);
    return {
      id: userReference.name,
      value: value,
      info: userReference.name,
      icon: "$xwiki.getSkinFile('icons/xwiki/noavatar.png')"
    };
  },

  // @Override
  addItem: function($super, suggestion) {
    // Clear the previously selected user in single selection mode.
    this.input.hasClassName('multipleSelection') || this.list.update('');
    $super(suggestion);
  },

  // @Override
  displayItem: function(suggestion) {
    var itemDisplay = this.suggest.createItemDisplay(suggestion, {});
    itemDisplay.down('.user-name').insert(this.createDeleteTool());
    return new Element('li').insert(itemDisplay).insert(this.createItemInput(suggestion));
  }
});

/**
 * Enhances a plain HTML text input with the ability to suggest users.
 */
widgets.UserPicker = Class.create(widgets.Suggest, {
  // @Override
  initialize: function($super, input, options) {
    $super(input, Object.extend({
      varname: "input",
      enableHideButton: false,
      timeout: 30000
    }, options || {}));

    var listInsertionElement = input;
    // The scope toggle doesn't make sense when global users are required.
    if (input.hasClassName('withScope') && !input.hasClassName('global')) {
      this._sourceURL = options.script;
      this._createScope();
      listInsertionElement = input.up();
    }
    this._selectionManager = this._createSelectionManager({
      listInsertionElement: listInsertionElement,
      listInsertionPosition : 'before',
      acceptFreeText : true
    });
    this.multipleSelection = input.hasClassName('multipleSelection');
    // Keep a reference to this user picker instance if the target input has the ID attribute specified.
    if (input.id != '') {
      widgets.UserPicker.instances[input.id] = this;
    }
  },

  // @Override
  createItemDisplay: function(data, source) {
    var container = new Element('div', {'class': 'user'});
    var avatarWrapper = new Element('div', {'class': 'user-avatar-wrapper'});
    avatarWrapper.insert(new Element('img', {src: data.icon, alt: data.info, 'class': 'icon'}));
    container.insert(avatarWrapper);
    var userName = source.highlight ? this.emphasizeMatches(this.sInput, data.info) : data.info;
    container.insert(new Element('div', {'class': 'user-name'}).update(userName));
    var referenceWrapper = new Element('div');
    var userAlias = source.highlight ? this.emphasizeMatches(this.sInput, data.id) : data.id;
    referenceWrapper.insert(new Element('span', {'class': 'user-alias'}).update(userAlias));
    var userReference = XWiki.Model.resolve(data.value, XWiki.EntityType.DOCUMENT);
    var wiki = userReference.extractReferenceValue(XWiki.EntityType.WIKI) || XWiki.currentWiki;
    // Display the wiki only for local users (in order to be consistent with the display in view mode).
    if (wiki !== '$xcontext.mainWikiName') {
      referenceWrapper.insert(new Element('span', {'class': 'user-wiki'}).update(wiki));
    }
    container.insert(referenceWrapper);
    return container;
  },

  /**
   * Clears the content of the target input and the current selection.
   */
  clear : function() {
    this.fld.clear();
    this._selectionManager.clearAcceptedList();
  },

  /**
   * Determines the selection manager that is going to be used. Derived classes can override this method if they want
   * to use a different selection manager.
   */
  _createSelectionManager: function(options) {
    return new SelectionManager(this.fld, this, options);
  },

  _createScope: function() {
    this._scope = new Element('input', {
      type: 'image',
      'class': 'scope',
      alt: "$services.localization.render('core.widgets.userPicker.scopeHint')",
      title: "$services.localization.render('core.widgets.userPicker.scopeHint')"
    });
    // Group the scope and the input.
    var wrapper = new Element('span').insert(this._scope);
    this.fld.insert({before: wrapper});
    wrapper.insert(this.fld);
    // Add click handler.
    this._scope.observe('click', this._toggleScope.bindAsEventListener(this));
    // Initialize the scope value.
    this._toggleScope();
  },

  /**
   * Toggles between local and global scope.
   */
  _toggleScope: function(event) {
    event && event.stop();
    if (this._scope.value == 'local') {
      this._scope.value = 'global';
      this._scope.src = "$xwiki.getSkinFile('icons/silk/world.png')";
    } else {
      this._scope.value = 'local';
      this._scope.src = "$xwiki.getSkinFile('icons/silk/world_delete.png')";
    }
    this.sources[0].script = this._sourceURL + 'wiki=' + this._scope.value + '&';
  },

  // @Override
  detach: function($super) {
    // Remove the list of accepted suggestions.
    this._selectionManager && this._selectionManager.detach();

    // Remove the scope toggle.
    this._scope && this._scope.stopObserving('click').up().insert({before: this.fld}).remove();

    $super();
  }
});
// Used to access the created user pickers.
widgets.UserPicker.instances = {};

var init = function(event) {
  var suggestionsMapping = {
    users: {
      script: XWiki.currentDocument.getURL('get', 'xpage=uorgsuggest&uorg=user&'),
      noresults: "$services.localization.render('core.widgets.userPicker.noResults')"
    },
    groups: {
      script: XWiki.currentDocument.getURL('get', 'xpage=uorgsuggest&uorg=group&'),
      noresults: "$services.localization.render('core.widgets.groupPicker.noResults')"
    }
  }
  var containers = (event && event.memo.elements) || [$('body')];
  Object.keys(suggestionsMapping).each(function(key) {
    containers.each(function(container) {
      container.select('input.suggest' + key.capitalize()).each(function(input) {
        if (!input.hasClassName('initialized')) {
          var options = Object.clone(suggestionsMapping[key]);
          // The picker suggests by default local users or groups.
          if (input.hasClassName('global')) {
            // Suggest global users or groups.
            options.script = options.script + 'wiki=global&';
          }
          new widgets.UserPicker(input, options);
          input.addClassName('initialized');
        }
      });
    });
  });
  return true;
};
(XWiki.domIsLoaded && init()) || document.observe('xwiki:dom:loaded', init);
document.observe('xwiki:dom:updated', init);

// End XWiki augmentation.
return XWiki;
})(XWiki || {});
<|endoftext|>


<commit_before>const { Mixin } = require('hops-mixin');
const {
  internal: { createWebpackMiddleware, StatsFilePlugin },
} = require('@untool/webpack');

function exists(path) {
  try {
    require.resolve(path);
    return true;
  } catch (e) {
    return false;
  }
}

class GraphQLMixin extends Mixin {
  configureServer(rootApp, middleware, mode) {
    if (
      !exists(this.config.graphqlMockSchemaFile) ||
      process.env.NODE_ENV === 'production'
    ) {
      return;
    }

    middleware.initial.push({
      path: this.config.graphqlMockServerPath,
      handler: createWebpackMiddleware(
        ['graphql-mock-server', 'node'],
        mode === 'develop',
        this
      ),
    });
  }

  configureBuild(webpackConfig, loaderConfigs, target) {
    const { allLoaderConfigs } = loaderConfigs;

    allLoaderConfigs.splice(allLoaderConfigs.length - 1, 0, {
      test: /\.(graphql|gql)$/,
      loader: 'graphql-tag/loader',
    });

    webpackConfig.externals.push('encoding');

    if (process.env.NODE_ENV === 'production') {
      return;
    }

    if (exists(this.config.graphqlMockSchemaFile)) {
      webpackConfig.resolve.alias[
        'hops-apollo-mock-server/schema'
      ] = require.resolve(this.config.graphqlMockSchemaFile);
    }

    if (exists(this.config.graphqlMockContextExtenderFile)) {
      webpackConfig.resolve.alias[
        'hops-apollo-mock-server/context-extender'
      ] = require.resolve(this.config.graphqlMockContextExtenderFile);
    }

    if (target === 'graphql-mock-server') {
      webpackConfig.externals.push(
        'apollo-server-express',
        'express',
        'graphql'
      );

      webpackConfig.output.filename = 'hops-graphql-mock-server.js';
      webpackConfig.resolve.alias['@untool/entrypoint'] = require.resolve(
        './lib/mock-server-middleware'
      );

      webpackConfig.plugins = webpackConfig.plugins.filter(
        p => !(p instanceof StatsFilePlugin)
      );
    }
  }

  diagnose({ detectDuplicatePackages }) {
    detectDuplicatePackages('graphql');
  }
}

module.exports = GraphQLMixin;
<commit_msg>fix(apollo-mock-server): check if graphql-tag/loader is already added<commit_after>const { Mixin } = require('hops-mixin');
const {
  internal: { createWebpackMiddleware, StatsFilePlugin },
} = require('@untool/webpack');

function exists(path) {
  try {
    require.resolve(path);
    return true;
  } catch (e) {
    return false;
  }
}

class GraphQLMixin extends Mixin {
  configureServer(rootApp, middleware, mode) {
    if (
      !exists(this.config.graphqlMockSchemaFile) ||
      process.env.NODE_ENV === 'production'
    ) {
      return;
    }

    middleware.initial.push({
      path: this.config.graphqlMockServerPath,
      handler: createWebpackMiddleware(
        ['graphql-mock-server', 'node'],
        mode === 'develop',
        this
      ),
    });
  }

  configureBuild(webpackConfig, loaderConfigs, target) {
    const { allLoaderConfigs } = loaderConfigs;

    if (
      !allLoaderConfigs.find(({ loader }) => loader === 'graphql-tag/loader')
    ) {
      allLoaderConfigs.splice(allLoaderConfigs.length - 1, 0, {
        test: /\.(graphql|gql)$/,
        loader: 'graphql-tag/loader',
      });
    }

    webpackConfig.externals.push('encoding');

    if (process.env.NODE_ENV === 'production') {
      return;
    }

    if (exists(this.config.graphqlMockSchemaFile)) {
      webpackConfig.resolve.alias[
        'hops-apollo-mock-server/schema'
      ] = require.resolve(this.config.graphqlMockSchemaFile);
    }

    if (exists(this.config.graphqlMockContextExtenderFile)) {
      webpackConfig.resolve.alias[
        'hops-apollo-mock-server/context-extender'
      ] = require.resolve(this.config.graphqlMockContextExtenderFile);
    }

    if (target === 'graphql-mock-server') {
      webpackConfig.externals.push(
        'apollo-server-express',
        'express',
        'graphql'
      );

      webpackConfig.output.filename = 'hops-graphql-mock-server.js';
      webpackConfig.resolve.alias['@untool/entrypoint'] = require.resolve(
        './lib/mock-server-middleware'
      );

      webpackConfig.plugins = webpackConfig.plugins.filter(
        p => !(p instanceof StatsFilePlugin)
      );
    }
  }

  diagnose({ detectDuplicatePackages }) {
    detectDuplicatePackages('graphql');
  }
}

module.exports = GraphQLMixin;
<|endoftext|>