<commit_before>/*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
*/

/*global _: false, js_cols: false, barycentricSubdivision: false*/

/* test barycentricSubdivision */

var canvas,ctx;

var point = [
  $V([0, 0])
];
// var line = [
//   $V([0, 0]),
//   $V([1, 0])
// ];
var line = [
  $V([0, 0]),
  $V([1, 0])
];
var triangle = [
  $V([0,0]),
  $V([1,0]),
  $V([0.5, (Math.sqrt(3)/2)])
];
var tetrahedron = [
  $V([0, 0, 0]),
  $V([1, 0, 0]),
  $V([0.5, (Math.sqrt(3)/2), 0]),
  $V([0.5, (Math.sqrt(3)/6), (Math.sqrt(6)/3)])
];

function runTest() {

  // drawLine(vectorsTo2DArrays(line), 80, 500, 500);
  // var line_subdivision = barycentricSubdivision(line);
  var line_subdivision = repeatedBarycentricSubdivision(line, 5);
  _.each(line_subdivision, function(segment) {
    drawLine(vectorsTo2DArrays(segment), 500, 50, 500);
  });

  // drawTriangle(vectorsTo2DArrays(triangle), 400, 10, 10);
  var triangle_subdivision = repeatedBarycentricSubdivision(triangle, 4);
  _.each(triangle_subdivision, function(triangle) {
    drawTriangle(vectorsTo2DArrays(triangle), 400, 10, 10);
  });
}

$(document).ready(function() {

  canvas = $("#basic")[0];
  ctx = canvas.getContext('2d');

  runTest();
});

function drawLine(line, scalefactor, x_offset, y_offset, clear) {
  if (!scalefactor) scalefactor = 1;
  if (!x_offset) x_offset = 0;
  if (!y_offset) y_offset = 0;
  if (clear === true) canvas.width = canvas.width; //clear canvas contents

  console.log("Drawing line:", line);

  ctx.beginPath();
  ctx.moveTo(x_offset+line[0][0]*scalefactor, y_offset+line[0][1]*scalefactor);
  ctx.lineTo(x_offset+line[1][0]*scalefactor, y_offset+line[1][1]*scalefactor);
  ctx.stroke();
  _.each(line, function(vertex) {
    drawPoint(x_offset+vertex[0]*scalefactor, y_offset+vertex[1]*scalefactor, 2);
  });
}
// triangle should be an
// array with 3 elements
// with each element being an array with two numbers
// representing the x,y coordinates of each vertex
function drawTriangle(triangle, scalefactor, x_offset, y_offset, clear) {
  if (!scalefactor) scalefactor = 1;
  if (!x_offset) x_offset = 0;
  if (!y_offset) y_offset = 0;
  if (clear === true) canvas.width = canvas.width; //clear canvas contents

  console.log("Drawing triangle:", triangle);

  ctx.beginPath();
  ctx.moveTo(x_offset+triangle[0][0]*scalefactor, y_offset+triangle[0][1]*scalefactor);
  ctx.lineTo(x_offset+triangle[1][0]*scalefactor, y_offset+triangle[1][1]*scalefactor);
  ctx.lineTo(x_offset+triangle[2][0]*scalefactor, y_offset+triangle[2][1]*scalefactor);
  ctx.lineTo(x_offset+triangle[0][0]*scalefactor, y_offset+triangle[0][1]*scalefactor);
  ctx.stroke();
  _.each(triangle, function(vertex) {
    drawPoint(x_offset+vertex[0]*scalefactor, y_offset+vertex[1]*scalefactor, 2);
  });
}
function drawPoint(x,y,size) {
  if (!size) size = 1;
  // ctx.fillRect(x*scalefactor, y*scalefactor, x+size, y+size);
  ctx.beginPath();
  ctx.arc(x, y, size, 0, 2*Math.PI, true);
  ctx.fill();
}
<commit_msg>cleanup<commit_after>/*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
*/

/*global _: false, js_cols: false, barycentricSubdivision: false*/

/* test barycentricSubdivision */

var canvas,ctx;

var point = [
  $V([0, 0])
];
// var line = [
//   $V([0, 0]),
//   $V([1, 0])
// ];
var line = [
  $V([0, 0]),
  $V([1, 0])
];
// var triangle = [
//   $V([0,0]),
//   $V([1,0]),
//   $V([0.5, (Math.sqrt(3)/2)])
// ];
var triangle = [
  $V([1,1]),
  $V([0,1]),
  $V([0,0])
];
var tetrahedron = [
  $V([0, 0, 0]),
  $V([1, 0, 0]),
  $V([0.5, (Math.sqrt(3)/2), 0]),
  $V([0.5, (Math.sqrt(3)/6), (Math.sqrt(6)/3)])
];

function runTest() {

  // drawLine(vectorsTo2DArrays(line), 80, 500, 500);
  // var line_subdivision = barycentricSubdivision(line);
  var line_subdivision = repeatedBarycentricSubdivision(line, 3);
  _.each(line_subdivision, function(segment) {
    drawLine(vectorsTo2DArrays(segment), 500, 50, 500);
  });

  // drawTriangle(vectorsTo2DArrays(triangle), 400, 10, 10);
  var triangle_subdivision = repeatedBarycentricSubdivision(triangle, 3);
  _.each(triangle_subdivision, function(triangle) {
    drawTriangle(vectorsTo2DArrays(triangle), 400, 10, 10);
  });
}

$(document).ready(function() {

  canvas = $("#basic")[0];
  ctx = canvas.getContext('2d');

  runTest();
});

function drawLine(line, scalefactor, x_offset, y_offset, clear) {
  if (!scalefactor) scalefactor = 1;
  if (!x_offset) x_offset = 0;
  if (!y_offset) y_offset = 0;
  if (clear === true) canvas.width = canvas.width; //clear canvas contents

  // console.log("Drawing line:", line);

  ctx.beginPath();
  ctx.moveTo(x_offset+line[0][0]*scalefactor, y_offset+line[0][1]*scalefactor);
  ctx.lineTo(x_offset+line[1][0]*scalefactor, y_offset+line[1][1]*scalefactor);
  ctx.stroke();
  _.each(line, function(vertex) {
    drawPoint(x_offset+vertex[0]*scalefactor, y_offset+vertex[1]*scalefactor, 2);
  });
}
// triangle should be an
// array with 3 elements
// with each element being an array with two numbers
// representing the x,y coordinates of each vertex
function drawTriangle(triangle, scalefactor, x_offset, y_offset, clear) {
  if (!scalefactor) scalefactor = 1;
  if (!x_offset) x_offset = 0;
  if (!y_offset) y_offset = 0;
  if (clear === true) canvas.width = canvas.width; //clear canvas contents

  // console.log("Drawing triangle:", triangle);

  ctx.beginPath();
  ctx.moveTo(x_offset+triangle[0][0]*scalefactor, y_offset+triangle[0][1]*scalefactor);
  ctx.lineTo(x_offset+triangle[1][0]*scalefactor, y_offset+triangle[1][1]*scalefactor);
  ctx.lineTo(x_offset+triangle[2][0]*scalefactor, y_offset+triangle[2][1]*scalefactor);
  ctx.lineTo(x_offset+triangle[0][0]*scalefactor, y_offset+triangle[0][1]*scalefactor);
  ctx.stroke();
  _.each(triangle, function(vertex) {
    drawPoint(x_offset+vertex[0]*scalefactor, y_offset+vertex[1]*scalefactor, 2);
  });
}
function drawPoint(x,y,size) {
  if (!size) size = 1;
  // ctx.fillRect(x*scalefactor, y*scalefactor, x+size, y+size);
  ctx.beginPath();
  ctx.arc(x, y, size, 0, 2*Math.PI, true);
  ctx.fill();
}
<|endoftext|>


<commit_before>'use strict';

var expect = require('chai').expect;
var ui = require('../lib/util/cli-ui.js');
var robot = require('robotjs');
var stdout = require('test-console').stdout;

describe('CLI utils', function() {
  describe('#ask', function() {
    var restoreStdout;
    it('should ask a question', function(done) {
      restoreStdout = stdout.ignore();

      var question = {
        name: 'name',
        message: 'question 1'
      };

      ui.ask(question).then(function(data) {
        restoreStdout();
        expect(data.name).to.equal('Hello World');
        done();
      });

      robot.typeString('Hello World');
      robot.keyTap('enter');
    });
  });
});
<commit_msg>Try without ignoring stdout<commit_after>'use strict';

var expect = require('chai').expect;
var ui = require('../lib/util/cli-ui.js');
var robot = require('robotjs');
var stdout = require('test-console').stdout;

describe('CLI utils', function() {
  describe('#ask', function() {
    var restoreStdout;
    it('should ask a question', function(done) {
      //restoreStdout = stdout.ignore();

      var question = {
        name: 'name',
        message: 'question 1'
      };

      ui.ask(question).then(function(data) {
        //restoreStdout();
        expect(data.name).to.equal('Hello World');
        done();
      });

      robot.typeString('Hello World');
      robot.keyTap('enter');
    });
  });
});
<|endoftext|>


<commit_before>/**!
 * Copyright(c) ali-sdk and other contributors.
 * MIT Licensed
 *
 * Authors:
 *   fengmk2 <m@fengmk2.com> (http://fengmk2.com)
 */

'use strict';

/**
 * Module dependencies.
 */

var assert = require('assert');
var oss = require('../');
var config = require('./config').oss;
var mm = require('mm');
var pkg = require('../package.json');

describe('test/client.test.js', function () {
  it('should init with region', function () {
    var store = oss({
      accessKeyId: 'foo',
      accessKeySecret: 'bar',
      region: 'oss-cn-hangzhou',
    });

    assert.equal(
      store.options.endpoint.format(),
      'http://oss-cn-hangzhou.aliyuncs.com/');

    store = oss({
      accessKeyId: 'foo',
      accessKeySecret: 'bar',
      region: 'oss-cn-hangzhou',
      internal: true,
    });

    assert.equal(
      store.options.endpoint.format(),
      'http://oss-cn-hangzhou-internal.aliyuncs.com/');

    store = oss({
      accessKeyId: 'foo',
      accessKeySecret: 'bar',
      region: 'oss-cn-hangzhou',
      internal: true,
      secure: true
    });

    assert.equal(
      store.options.endpoint.format(),
      'https://oss-cn-hangzhou-internal.aliyuncs.com/');
  });

  it('should init with cname: foo.bar.com', function () {
    var store = oss({
      accessKeyId: 'foo',
      accessKeySecret: 'bar',
      endpoint: 'foo.bar.com',
      cname: true
    });

    assert.equal(
      store.options.endpoint.format(),
      'http://foo.bar.com/');

    var store = oss({
      accessKeyId: 'foo',
      accessKeySecret: 'bar',
      endpoint: 'http://foo.bar.com',
      cname: true
    });

    assert.equal(
      store.options.endpoint.format(),
      'http://foo.bar.com/');
  });

  it('should init with endpoint: http://test.oss.com', function () {
    var store = oss({
      accessKeyId: 'foo',
      accessKeySecret: 'bar',
      endpoint: 'test.oss.com'
    });

    assert.equal(
      store.options.endpoint.format(),
      'http://test.oss.com/');

    store = oss({
      accessKeyId: 'foo',
      accessKeySecret: 'bar',
      endpoint: 'http://test.oss.com'
    });

    assert.equal(
      store.options.endpoint.format(),
      'http://test.oss.com/');

    store = oss({
      accessKeyId: 'foo',
      accessKeySecret: 'bar',
      endpoint: 'https://test.oss.com'
    });

    assert.equal(
      store.options.endpoint.format(),
      'https://test.oss.com/');
  });

  it('should init with ip address: http://127.0.0.1', function () {
    var store = oss({
      accessKeyId: 'foo',
      accessKeySecret: 'bar',
      endpoint: '127.0.0.1'
    });

    assert.equal(
      store.options.endpoint.format(),
      'http://127.0.0.1/');
  });

  it('should create request url with bucket', function() {
    var store = oss({
      accessKeyId: 'foo',
      accessKeySecret: 'bar',
      region: 'oss-cn-hangzhou',
    });

    var params = {
      bucket: 'gems'
    };

    var url = store._getReqUrl(params);
    assert.equal(url, 'http://gems.oss-cn-hangzhou.aliyuncs.com/');

    var store = oss({
      accessKeyId: 'foo',
      accessKeySecret: 'bar',
      endpoint: 'test.oss.com'
    });

    var params = {
      bucket: 'gems'
    };

    var url = store._getReqUrl(params);
    assert.equal(url, 'http://gems.test.oss.com/');

    var store = oss({
      accessKeyId: 'foo',
      accessKeySecret: 'bar',
      endpoint: 'foo.bar.com',
      cname: true
    });

    var params = {
      bucket: 'gems'
    };

    var url = store._getReqUrl(params);
    assert.equal(url, 'http://foo.bar.com/');

    var store = oss({
      accessKeyId: 'foo',
      accessKeySecret: 'bar',
      endpoint: 'http://127.0.0.1:6000'
    });

    var params = {
      bucket: 'gems'
    };

    var url = store._getReqUrl(params);
    assert.equal(url, 'http://127.0.0.1:6000/gems/');
  });

  it('should create request url with bucket/object/subres', function() {
    var store = oss({
      accessKeyId: 'foo',
      accessKeySecret: 'bar',
      region: 'oss-cn-hangzhou',
    });

    var params = {
      bucket: 'gems',
      object: 'hello'
    };

    var url = store._getReqUrl(params);
    assert.equal(url, 'http://gems.oss-cn-hangzhou.aliyuncs.com/hello');

    var params = {
      bucket: 'gems',
      object: 'hello',
      subres: {acl: '', mime: ''}
    };

    var url = store._getReqUrl(params);
    assert.equal(url, 'http://gems.oss-cn-hangzhou.aliyuncs.com/hello?acl=&mime=');

    var store = oss({
      accessKeyId: 'foo',
      accessKeySecret: 'bar',
      endpoint: 'test.oss.com'
    });

    var params = {
      bucket: 'gems',
      object: 'hello'
    };

    var url = store._getReqUrl(params);
    assert.equal(url, 'http://gems.test.oss.com/hello');

    var store = oss({
      accessKeyId: 'foo',
      accessKeySecret: 'bar',
      endpoint: 'foo.bar.com',
      cname: true
    });

    var params = {
      bucket: 'gems',
      object: 'hello'
    };

    var url = store._getReqUrl(params);
    assert.equal(url, 'http://foo.bar.com/hello');

    var store = oss({
      accessKeyId: 'foo',
      accessKeySecret: 'bar',
      endpoint: 'http://127.0.0.1:3000'
    });

    var params = {
      bucket: 'gems',
      object: 'hello'
    };

    var url = store._getReqUrl(params);
    assert.equal(url, 'http://127.0.0.1:3000/gems/hello');
  });

  it('should set User-Agent', function* () {
    after(mm.restore);

    var store = oss(config);
    var headers;
    var req = store.urllib.requestThunk;
    mm(store.urllib, 'requestThunk', function (url, args) {
      headers = args.headers;
      return req(url, args);
    });

    var result = yield store.listBuckets();
    assert.equal(result.res.status, 200);
    assert(headers['User-Agent']);
    assert(headers['User-Agent'].startsWith('aliyun-sdk-nodejs/' + pkg.version));
    assert(headers['x-oss-user-agent']);
    assert(headers['x-oss-user-agent'].startsWith('aliyun-sdk-nodejs/' + pkg.version));
  });
});
<commit_msg>improve user-agent test<commit_after>/**!
 * Copyright(c) ali-sdk and other contributors.
 * MIT Licensed
 *
 * Authors:
 *   fengmk2 <m@fengmk2.com> (http://fengmk2.com)
 */

'use strict';

/**
 * Module dependencies.
 */

var assert = require('assert');
var oss = require('../');
var config = require('./config').oss;
var mm = require('mm');
var pkg = require('../package.json');

describe('test/client.test.js', function () {
  it('should init with region', function () {
    var store = oss({
      accessKeyId: 'foo',
      accessKeySecret: 'bar',
      region: 'oss-cn-hangzhou',
    });

    assert.equal(
      store.options.endpoint.format(),
      'http://oss-cn-hangzhou.aliyuncs.com/');

    store = oss({
      accessKeyId: 'foo',
      accessKeySecret: 'bar',
      region: 'oss-cn-hangzhou',
      internal: true,
    });

    assert.equal(
      store.options.endpoint.format(),
      'http://oss-cn-hangzhou-internal.aliyuncs.com/');

    store = oss({
      accessKeyId: 'foo',
      accessKeySecret: 'bar',
      region: 'oss-cn-hangzhou',
      internal: true,
      secure: true
    });

    assert.equal(
      store.options.endpoint.format(),
      'https://oss-cn-hangzhou-internal.aliyuncs.com/');
  });

  it('should init with cname: foo.bar.com', function () {
    var store = oss({
      accessKeyId: 'foo',
      accessKeySecret: 'bar',
      endpoint: 'foo.bar.com',
      cname: true
    });

    assert.equal(
      store.options.endpoint.format(),
      'http://foo.bar.com/');

    var store = oss({
      accessKeyId: 'foo',
      accessKeySecret: 'bar',
      endpoint: 'http://foo.bar.com',
      cname: true
    });

    assert.equal(
      store.options.endpoint.format(),
      'http://foo.bar.com/');
  });

  it('should init with endpoint: http://test.oss.com', function () {
    var store = oss({
      accessKeyId: 'foo',
      accessKeySecret: 'bar',
      endpoint: 'test.oss.com'
    });

    assert.equal(
      store.options.endpoint.format(),
      'http://test.oss.com/');

    store = oss({
      accessKeyId: 'foo',
      accessKeySecret: 'bar',
      endpoint: 'http://test.oss.com'
    });

    assert.equal(
      store.options.endpoint.format(),
      'http://test.oss.com/');

    store = oss({
      accessKeyId: 'foo',
      accessKeySecret: 'bar',
      endpoint: 'https://test.oss.com'
    });

    assert.equal(
      store.options.endpoint.format(),
      'https://test.oss.com/');
  });

  it('should init with ip address: http://127.0.0.1', function () {
    var store = oss({
      accessKeyId: 'foo',
      accessKeySecret: 'bar',
      endpoint: '127.0.0.1'
    });

    assert.equal(
      store.options.endpoint.format(),
      'http://127.0.0.1/');
  });

  it('should create request url with bucket', function() {
    var store = oss({
      accessKeyId: 'foo',
      accessKeySecret: 'bar',
      region: 'oss-cn-hangzhou',
    });

    var params = {
      bucket: 'gems'
    };

    var url = store._getReqUrl(params);
    assert.equal(url, 'http://gems.oss-cn-hangzhou.aliyuncs.com/');

    var store = oss({
      accessKeyId: 'foo',
      accessKeySecret: 'bar',
      endpoint: 'test.oss.com'
    });

    var params = {
      bucket: 'gems'
    };

    var url = store._getReqUrl(params);
    assert.equal(url, 'http://gems.test.oss.com/');

    var store = oss({
      accessKeyId: 'foo',
      accessKeySecret: 'bar',
      endpoint: 'foo.bar.com',
      cname: true
    });

    var params = {
      bucket: 'gems'
    };

    var url = store._getReqUrl(params);
    assert.equal(url, 'http://foo.bar.com/');

    var store = oss({
      accessKeyId: 'foo',
      accessKeySecret: 'bar',
      endpoint: 'http://127.0.0.1:6000'
    });

    var params = {
      bucket: 'gems'
    };

    var url = store._getReqUrl(params);
    assert.equal(url, 'http://127.0.0.1:6000/gems/');
  });

  it('should create request url with bucket/object/subres', function() {
    var store = oss({
      accessKeyId: 'foo',
      accessKeySecret: 'bar',
      region: 'oss-cn-hangzhou',
    });

    var params = {
      bucket: 'gems',
      object: 'hello'
    };

    var url = store._getReqUrl(params);
    assert.equal(url, 'http://gems.oss-cn-hangzhou.aliyuncs.com/hello');

    var params = {
      bucket: 'gems',
      object: 'hello',
      subres: {acl: '', mime: ''}
    };

    var url = store._getReqUrl(params);
    assert.equal(url, 'http://gems.oss-cn-hangzhou.aliyuncs.com/hello?acl=&mime=');

    var store = oss({
      accessKeyId: 'foo',
      accessKeySecret: 'bar',
      endpoint: 'test.oss.com'
    });

    var params = {
      bucket: 'gems',
      object: 'hello'
    };

    var url = store._getReqUrl(params);
    assert.equal(url, 'http://gems.test.oss.com/hello');

    var store = oss({
      accessKeyId: 'foo',
      accessKeySecret: 'bar',
      endpoint: 'foo.bar.com',
      cname: true
    });

    var params = {
      bucket: 'gems',
      object: 'hello'
    };

    var url = store._getReqUrl(params);
    assert.equal(url, 'http://foo.bar.com/hello');

    var store = oss({
      accessKeyId: 'foo',
      accessKeySecret: 'bar',
      endpoint: 'http://127.0.0.1:3000'
    });

    var params = {
      bucket: 'gems',
      object: 'hello'
    };

    var url = store._getReqUrl(params);
    assert.equal(url, 'http://127.0.0.1:3000/gems/hello');
  });

  it('should set User-Agent', function* () {
    after(mm.restore);

    var store = oss(config);
    var headers;
    var req = store.urllib.requestThunk;
    mm(store.urllib, 'requestThunk', function (url, args) {
      headers = args.headers;
      return req(url, args);
    });

    var result = yield store.listBuckets();
    assert.equal(result.res.status, 200);
    assert(headers['User-Agent']);
    assert(headers['User-Agent'].startsWith(
      'aliyun-sdk-nodejs/' + pkg.version + ' Node.js ' + process.version.slice(1)));
    assert(headers['x-oss-user-agent']);
    assert(headers['x-oss-user-agent'].startsWith(
      'aliyun-sdk-nodejs/' + pkg.version + ' Node.js ' + process.version.slice(1)));
  });
});
<|endoftext|>


<commit_before>var assert = require('assert');
var sinon = require('sinon');
var support = require('./support');
var check_err = support.check_err;
var simple_es = require('../index');
var http_client = require('../lib/http_client');

var server_options = {
    host: 'localhost',
    port: 9200
};

var index_name = 'simple-elasticsearch-test';
var type = 'foo';

function create_doc() {
    return {name: support.random.string(), description: support.random.string()};
}

describe("client.js", function () {
    describe("instantiating", function () {
        it("doesn't blow up when no args passed in", function () {
            simple_es.client.create();
        });
    });

    describe("admin methods", function () {
        var client;

        before(function () {
            client = simple_es.client.create(server_options);
        });

        describe("indices", function () {
            describe("create()", function () {
                context("when no args passed in", function () {
                    it("returns an error", function (done) {
                        client.indices.create(null, function (err) {
                            assert.ok(err.message.match(/args required/));
                            done();
                        });
                    });
                });

                context("when no index passed in", function () {
                    it("returns an error", function (done) {
                        client.indices.create({}, function (err) {
                            assert.ok(err.message.match(/missing arg: index/));
                            done();
                        });
                    });
                });

                context("when index does not yet exist", function () {
                    var new_index_name;

                    beforeEach(function () {
                        new_index_name = index_name + support.random.string();
                    });

                    afterEach(function (done) {
                        client.indices.del({index: new_index_name}, done);
                    });

                    it("returns success response", function (done) {
                        client.indices.create({index: new_index_name}, function (err, result) {
                            check_err(err);
                            assert.strictEqual(result.ok, true);
                            assert.strictEqual(result.acknowledged, true);
                            done();
                        });
                    });

                    it("creates the new index", function (done) {
                        client.indices.create({index: new_index_name}, function (err) {
                            check_err(err);

                            client.indices.status({index: new_index_name}, function (err, result) {
                                check_err(err);
                                assert.ok(result.indices[new_index_name]);
                                done();
                            });
                        });
                    });

                    it("passes options hash to http request as JSON string", function (done) {
                        sinon.spy(http_client, 'put');

                        var options = {
                            settings: {
                                number_of_shards: 1
                            }
                        };

                        var expected_url = client.url + new_index_name;
                        var expected_json = JSON.stringify(options);

                        client.indices.create({index: new_index_name, options: options}, function (err) {
                            check_err(err);

                            assert.ok(http_client.put.calledWithMatch({url: expected_url, method: 'PUT', body: expected_json}));
                            http_client.put.restore();
                            done();
                        });
                    });
                });
            });

            describe("status()", function () {
                context("when 'index' arg passed in ", function () {
                    context("and index exists", function () {
                        it("returns status for that index", function (done) {
                            client.indices.status({index: index_name}, function (err, result) {
                                check_err(err);
                                assert.strictEqual(result.ok, true);
                                assert.ok(result.indices[index_name]);

                                var expected_keys = ['translog', 'docs', 'merges', 'refresh', 'flush', 'shards'];
                                expected_keys.forEach(function (key) {
                                    assert.ok(result.indices[index_name].hasOwnProperty(key));
                                });

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

                    context("and index does not exist", function () {
                        it("returns result with IndexMissingException and status 404", function (done) {
                            var non_existent_index = index_name + support.random.string(20);
                            client.indices.status({index: non_existent_index}, function (err, result) {
                                check_err(err);
                                assert.ok(result.error.match(/IndexMissingException/));
                                assert.strictEqual(result.status, 404);
                                done();
                            });
                        });
                    });
                });

                context("when no args passed in", function () {
                    it("returns all index statuses", function (done) {
                        client.indices.status(function (err, result) {
                            check_err(err);
                            assert.strictEqual(result.ok, true);
                            done();
                        });
                    });
                });
            });

            describe("del()", function () {
                context("when no args passed in", function () {
                    it("returns an error", function (done) {
                        client.indices.del(null, function (err) {
                            assert.ok(err.message.match(/args required/));
                            done();
                        });
                    });
                });

                context("when no index passed in", function () {
                    it("returns an error", function (done) {
                        client.indices.del({}, function (err) {
                            assert.ok(err.message.match(/missing arg: index/));
                            done();
                        });
                    });
                });

                context("when index does not exist", function () {
                    it("returns result with IndexMissingException and status 404", function (done) {
                        var non_existent_index = index_name + support.random.string(20);
                        client.indices.del({index: non_existent_index}, function (err, result) {
                            assert.ok(result.error.match(/IndexMissingException/));
                            assert.strictEqual(result.status, 404);
                            done();
                        });
                    });
                });
            });
        });
    });

    describe("main instance methods", function () {
        var client;

        before(function () {
            client = simple_es.client.create(server_options);
        });

        describe("index()", function () {
            context("when no args passed in", function () {
                it("returns an error", function (done) {
                    client.index(null, function (err) {
                        assert.ok(err.message.match(/args required/));
                        done();
                    });
                });
            });

            context("when no doc passed in", function () {
                it("returns an error", function (done) {
                    client.index({index: index_name, type: type}, function (err) {
                        assert.ok(err.message.match(/missing arg: doc/));
                        done();
                    });
                });
            });

            context("when no id passed in", function () {
                it("adds object to index", function (done) {
                    var doc = create_doc();
                    client.index({index: index_name, type: type, doc: doc}, function (err, result) {
                        check_err(err);
                        assert.strictEqual(result.ok, true);
                        done();
                    });
                });
            });

            context("when id is passed in", function () {
                it("adds object to index with specified id", function (done) {
                    var doc = create_doc();
                    var id = support.random.number();

                    client.index({index: index_name, type: type, doc: doc, id: id}, function (err, result) {
                        check_err(err);
                        assert.strictEqual(result.ok, true);
                        assert.strictEqual(result._id, id.toString());
                        done();
                    });
                });
            });
        });

        describe("get()", function () {
            var id;

            context("when no args passed in", function () {
                it("returns an error", function (done) {
                    client.get(null, function (err) {
                        assert.ok(err.message.match(/args required/));
                        done();
                    });
                });
            });

            context("when no id passed in", function () {
                it("returns an error", function (done) {
                    client.get({index: index_name, type: type}, function (err) {
                        assert.ok(err.message.match(/missing arg: id/));
                        done();
                    });
                });
            });

            context("when HTTP request returns an error", function () {
                it.skip("bubbles up that error", function (done) {
                    done();
                });
            });

            context("when id is passed in", function () {
                context("and id is not found", function () {
                    it("returns null result", function (done) {
                        var id = support.random.number();

                        client.get({index: index_name, type: type, id: id}, function (err, result, raw) {
                            raw = JSON.parse(raw);
                            assert.strictEqual(raw.exists, false);
                            assert.strictEqual(result, null);
                            check_err(err);
                            done();
                        });
                    });
                });

                context("and id is found", function () {
                    var doc;

                    beforeEach(function (done) {
                        id = support.random.number();
                        doc = create_doc();
                        client.index({index: index_name, type: type, doc: doc, id: id}, done);
                    });

                    it("returns the requested doc", function (done) {
                        client.get({index: index_name, type: type, id: id}, function (err, obj, raw) {
                            check_err(err);
                            raw = JSON.parse(raw);
                            assert.strictEqual(raw.exists, true);
                            assert.strictEqual(raw._id, id.toString());
                            assert.deepEqual(obj, doc);
                            done();
                        });
                    });
                });
            });
        });
    });
});
<commit_msg>setting up indices.status() tests to actually create index first<commit_after>var assert = require('assert');
var sinon = require('sinon');
var support = require('./support');
var check_err = support.check_err;
var simple_es = require('../index');
var http_client = require('../lib/http_client');

var server_options = {
    host: 'localhost',
    port: 9200
};

var index_name = 'simple-elasticsearch-test';
var type = 'foo';

function create_doc() {
    return {name: support.random.string(), description: support.random.string()};
}

describe("client.js", function () {
    describe("instantiating", function () {
        it("doesn't blow up when no args passed in", function () {
            simple_es.client.create();
        });
    });

    describe("admin methods", function () {
        var client;

        before(function () {
            client = simple_es.client.create(server_options);
        });

        describe("indices", function () {
            describe("create()", function () {
                context("when no args passed in", function () {
                    it("returns an error", function (done) {
                        client.indices.create(null, function (err) {
                            assert.ok(err.message.match(/args required/));
                            done();
                        });
                    });
                });

                context("when no index passed in", function () {
                    it("returns an error", function (done) {
                        client.indices.create({}, function (err) {
                            assert.ok(err.message.match(/missing arg: index/));
                            done();
                        });
                    });
                });

                context("when index does not yet exist", function () {
                    var new_index_name;

                    beforeEach(function () {
                        new_index_name = index_name + support.random.string();
                    });

                    afterEach(function (done) {
                        client.indices.del({index: new_index_name}, done);
                    });

                    it("returns success response", function (done) {
                        client.indices.create({index: new_index_name}, function (err, result) {
                            check_err(err);
                            assert.strictEqual(result.ok, true);
                            assert.strictEqual(result.acknowledged, true);
                            done();
                        });
                    });

                    it("creates the new index", function (done) {
                        client.indices.create({index: new_index_name}, function (err) {
                            check_err(err);

                            client.indices.status({index: new_index_name}, function (err, result) {
                                check_err(err);
                                assert.ok(result.indices[new_index_name]);
                                done();
                            });
                        });
                    });

                    it("passes options hash to http request as JSON string", function (done) {
                        sinon.spy(http_client, 'put');

                        var options = {
                            settings: {
                                number_of_shards: 1
                            }
                        };

                        var expected_url = client.url + new_index_name;
                        var expected_json = JSON.stringify(options);

                        client.indices.create({index: new_index_name, options: options}, function (err) {
                            check_err(err);

                            assert.ok(http_client.put.calledWithMatch({url: expected_url, method: 'PUT', body: expected_json}));
                            http_client.put.restore();
                            done();
                        });
                    });
                });
            });

            describe("status()", function () {
                context("when 'index' arg passed in ", function () {
                    context("and index exists", function () {
                        var new_index_name;

                        beforeEach(function (done) {
                            new_index_name = index_name + support.random.string();
                            client.indices.create({index: new_index_name}, done);
                        });

                        afterEach(function (done) {
                            client.indices.del({index: new_index_name}, done);
                        });

                        it("returns status for that index", function (done) {
                            client.indices.status({index: new_index_name}, function (err, result) {
                                check_err(err);
                                assert.strictEqual(result.ok, true);
                                assert.ok(result.indices[new_index_name]);

                                var expected_keys = ['translog', 'docs', 'merges', 'refresh', 'flush', 'shards'];
                                expected_keys.forEach(function (key) {
                                    assert.ok(result.indices[new_index_name].hasOwnProperty(key));
                                });

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

                    context("and index does not exist", function () {
                        it("returns result with IndexMissingException and status 404", function (done) {
                            var non_existent_index = index_name + support.random.string(20);
                            client.indices.status({index: non_existent_index}, function (err, result) {
                                check_err(err);
                                assert.ok(result.error.match(/IndexMissingException/));
                                assert.strictEqual(result.status, 404);
                                done();
                            });
                        });
                    });
                });

                context("when no args passed in", function () {
                    it("returns all index statuses", function (done) {
                        client.indices.status(function (err, result) {
                            check_err(err);
                            assert.strictEqual(result.ok, true);
                            done();
                        });
                    });
                });
            });

            describe("del()", function () {
                context("when no args passed in", function () {
                    it("returns an error", function (done) {
                        client.indices.del(null, function (err) {
                            assert.ok(err.message.match(/args required/));
                            done();
                        });
                    });
                });

                context("when no index passed in", function () {
                    it("returns an error", function (done) {
                        client.indices.del({}, function (err) {
                            assert.ok(err.message.match(/missing arg: index/));
                            done();
                        });
                    });
                });

                context("when index does not exist", function () {
                    it("returns result with IndexMissingException and status 404", function (done) {
                        var non_existent_index = index_name + support.random.string(20);
                        client.indices.del({index: non_existent_index}, function (err, result) {
                            assert.ok(result.error.match(/IndexMissingException/));
                            assert.strictEqual(result.status, 404);
                            done();
                        });
                    });
                });
            });
        });
    });

    describe("main instance methods", function () {
        var client;

        before(function () {
            client = simple_es.client.create(server_options);
        });

        describe("index()", function () {
            context("when no args passed in", function () {
                it("returns an error", function (done) {
                    client.index(null, function (err) {
                        assert.ok(err.message.match(/args required/));
                        done();
                    });
                });
            });

            context("when no doc passed in", function () {
                it("returns an error", function (done) {
                    client.index({index: index_name, type: type}, function (err) {
                        assert.ok(err.message.match(/missing arg: doc/));
                        done();
                    });
                });
            });

            context("when no id passed in", function () {
                it("adds object to index", function (done) {
                    var doc = create_doc();
                    client.index({index: index_name, type: type, doc: doc}, function (err, result) {
                        check_err(err);
                        assert.strictEqual(result.ok, true);
                        done();
                    });
                });
            });

            context("when id is passed in", function () {
                it("adds object to index with specified id", function (done) {
                    var doc = create_doc();
                    var id = support.random.number();

                    client.index({index: index_name, type: type, doc: doc, id: id}, function (err, result) {
                        check_err(err);
                        assert.strictEqual(result.ok, true);
                        assert.strictEqual(result._id, id.toString());
                        done();
                    });
                });
            });
        });

        describe("get()", function () {
            var id;

            context("when no args passed in", function () {
                it("returns an error", function (done) {
                    client.get(null, function (err) {
                        assert.ok(err.message.match(/args required/));
                        done();
                    });
                });
            });

            context("when no id passed in", function () {
                it("returns an error", function (done) {
                    client.get({index: index_name, type: type}, function (err) {
                        assert.ok(err.message.match(/missing arg: id/));
                        done();
                    });
                });
            });

            context("when HTTP request returns an error", function () {
                it.skip("bubbles up that error", function (done) {
                    done();
                });
            });

            context("when id is passed in", function () {
                context("and id is not found", function () {
                    it("returns null result", function (done) {
                        var id = support.random.number();

                        client.get({index: index_name, type: type, id: id}, function (err, result, raw) {
                            raw = JSON.parse(raw);
                            assert.strictEqual(raw.exists, false);
                            assert.strictEqual(result, null);
                            check_err(err);
                            done();
                        });
                    });
                });

                context("and id is found", function () {
                    var doc;

                    beforeEach(function (done) {
                        id = support.random.number();
                        doc = create_doc();
                        client.index({index: index_name, type: type, doc: doc, id: id}, done);
                    });

                    it("returns the requested doc", function (done) {
                        client.get({index: index_name, type: type, id: id}, function (err, obj, raw) {
                            check_err(err);
                            raw = JSON.parse(raw);
                            assert.strictEqual(raw.exists, true);
                            assert.strictEqual(raw._id, id.toString());
                            assert.deepEqual(obj, doc);
                            done();
                        });
                    });
                });
            });
        });
    });
});
<|endoftext|>


<commit_before>'use strict';

const path = require('path');
const helper = require('./helper');

describe('success', () => {
    it('non-concurrent', () => {
        var config = {
            threads: 2
        };

        var schedule = [
            {
                id: 'p1',
                worker: path.join(__dirname, 'workers/success.js')
            },
            {
                id: 'p2',
                worker: path.join(__dirname, 'workers/success.js')
            }
        ];

        var expect = {
            change: {
                p1: [
                    {status: 'queued', id: 'p1'},
                    {status: 'running', id: 'p1'},
                    {status: 'success', id: 'p1'}
                ],
                p2: [
                    {status: 'queued', id: 'p2'},
                    {status: 'running', id: 'p2'},
                    {status: 'success', id: 'p2'}
                ]
            }
        };

        return helper.testSchedule({config, schedule, expect, groupById: true});
    });

    it('non-concurrent thread-limited', function () {
        var config = {
            threads: 1
        };

        var schedule = [
            {
                id: 'p1',
                worker: path.join(__dirname, 'workers/success.js')
            },
            {
                id: 'p2',
                worker: path.join(__dirname, 'workers/success.js')
            }
        ];

        var expect = {
            change: [
                {status: 'queued', id: 'p1'},
                {status: 'running', id: 'p1'},
                {status: 'queued', id: 'p2'},
                {status: 'success', id: 'p1'},
                {status: 'running', id: 'p2'},
                {status: 'success', id: 'p2'}
            ]
        };

        return helper.testSchedule({config, schedule, expect});
    });

    it('thread-limited by type', function () {
        return helper.testSchedule({
            config: {
                threads: {
                    a: 1,
                    b: 1
                }
            },
            schedule: [
                {
                    id: 'p1',
                    worker: path.join(__dirname, 'workers/timeout.js'),
                    type: 'a',
                    arg: {timeout: 50}
                },
                {
                    id: 'p2',
                    worker: path.join(__dirname, 'workers/success.js'),
                    type: 'a'
                },
                {
                    id: 'p3',
                    worker: path.join(__dirname, 'workers/success.js'),
                    type: 'b'
                }
            ],
            expect: {
                change: [
                    {id: 'p1', status: 'queued'},
                    {id: 'p1', status: 'running'},
                    {id: 'p2', status: 'queued'},
                    {id: 'p3', status: 'queued'},
                    {id: 'p3', status: 'running'},
                    {id: 'p3', status: 'success'},
                    {id: 'p1', status: 'success'},
                    {id: 'p2', status: 'running'},
                    {id: 'p2', status: 'success'}
                ]
            }
        });
    });

    it('concurrent', function () {
        var config = {
            threads: 2
        };

        var schedule = [
            {
                id: 'p1',
                worker: path.join(__dirname, 'workers/success.js'),
                noConcurrency: ['p2']
            },
            {
                id: 'p2',
                worker: path.join(__dirname, 'workers/success.js')
            }
        ];

        var expect = {
            change: [
                {status: 'queued', id: 'p1'},
                {status: 'running', id: 'p1'},
                {status: 'queued', id: 'p2'},
                {status: 'success', id: 'p1'},
                {status: 'running', id: 'p2'},
                {status: 'success', id: 'p2'}
            ]
        };

        return helper.testSchedule({config, schedule, expect});
    });

});
<commit_msg>add test<commit_after>'use strict';

const path = require('path');
const helper = require('./helper');

describe('success', () => {
    it('non-concurrent', () => {
        var config = {
            threads: 2
        };

        var schedule = [
            {
                id: 'p1',
                worker: path.join(__dirname, 'workers/success.js')
            },
            {
                id: 'p2',
                worker: path.join(__dirname, 'workers/success.js')
            }
        ];

        var expect = {
            change: {
                p1: [
                    {status: 'queued', id: 'p1'},
                    {status: 'running', id: 'p1'},
                    {status: 'success', id: 'p1'}
                ],
                p2: [
                    {status: 'queued', id: 'p2'},
                    {status: 'running', id: 'p2'},
                    {status: 'success', id: 'p2'}
                ]
            }
        };

        return helper.testSchedule({config, schedule, expect, groupById: true});
    });

    it('non-concurrent thread-limited', function () {
        var config = {
            threads: 1
        };

        var schedule = [
            {
                id: 'p1',
                worker: path.join(__dirname, 'workers/success.js')
            },
            {
                id: 'p2',
                worker: path.join(__dirname, 'workers/success.js')
            }
        ];

        var expect = {
            change: [
                {status: 'queued', id: 'p1'},
                {status: 'running', id: 'p1'},
                {status: 'queued', id: 'p2'},
                {status: 'success', id: 'p1'},
                {status: 'running', id: 'p2'},
                {status: 'success', id: 'p2'}
            ]
        };

        return helper.testSchedule({config, schedule, expect});
    });

    it('thread-limited by type', function () {
        return helper.testSchedule({
            config: {
                threads: {
                    a: 1,
                    b: 1
                }
            },
            schedule: [
                {
                    id: 'p1',
                    worker: path.join(__dirname, 'workers/timeout.js'),
                    type: 'a',
                    arg: {timeout: 50}
                },
                {
                    id: 'p2',
                    worker: path.join(__dirname, 'workers/success.js'),
                    type: 'a'
                },
                {
                    id: 'p3',
                    worker: path.join(__dirname, 'workers/success.js'),
                    type: 'b'
                }
            ],
            expect: {
                change: [
                    {id: 'p1', status: 'queued'},
                    {id: 'p1', status: 'running'},
                    {id: 'p2', status: 'queued'},
                    {id: 'p3', status: 'queued'},
                    {id: 'p3', status: 'running'},
                    {id: 'p3', status: 'success'},
                    {id: 'p1', status: 'success'},
                    {id: 'p2', status: 'running'},
                    {id: 'p2', status: 'success'}
                ]
            }
        });
    });

    it('concurrent', function () {
        var config = {
            threads: 2
        };

        var schedule = [
            {
                id: 'p1',
                worker: path.join(__dirname, 'workers/success.js'),
                noConcurrency: ['p2']
            },
            {
                id: 'p2',
                worker: path.join(__dirname, 'workers/success.js')
            }
        ];

        var expect = {
            change: [
                {status: 'queued', id: 'p1'},
                {status: 'running', id: 'p1'},
                {status: 'queued', id: 'p2'},
                {status: 'success', id: 'p1'},
                {status: 'running', id: 'p2'},
                {status: 'success', id: 'p2'}
            ]
        };

        return helper.testSchedule({config, schedule, expect});
    });

    it('same task', function () {
        var config = {
            threads: 2
        };

        var schedule = [
            {
                id: 'p1',
                worker: path.join(__dirname, 'workers/success.js'),
            },
            {
                id: 'p1',
                worker: path.join(__dirname, 'workers/success.js')
            }
        ];

        var expect = {
            change: [
                {status: 'queued', id: 'p1'},
                {status: 'running', id: 'p1'},
                {status: 'success', id: 'p1'}
            ]
        };

        return helper.testSchedule({config, schedule, expect});
    });

});
<|endoftext|>


<commit_before>'use strict';

describe('PIXI.Matrix', function ()
{
    it('should create a new matrix', function ()
    {
        const matrix = new PIXI.Matrix();

        expect(matrix.a).to.equal(1);
        expect(matrix.b).to.equal(0);
        expect(matrix.c).to.equal(0);
        expect(matrix.d).to.equal(1);
        expect(matrix.tx).to.equal(0);
        expect(matrix.ty).to.equal(0);

        const input = [0, 1, 2, 3, 4, 5];

        matrix.fromArray(input);

        expect(matrix.a).to.equal(0);
        expect(matrix.b).to.equal(1);
        expect(matrix.c).to.equal(3);
        expect(matrix.d).to.equal(4);
        expect(matrix.tx).to.equal(2);
        expect(matrix.ty).to.equal(5);

        let output = matrix.toArray(true);

        expect(output.length).to.equal(9);
        expect(output[0]).to.equal(0);
        expect(output[1]).to.equal(1);
        expect(output[3]).to.equal(3);
        expect(output[4]).to.equal(4);
        expect(output[6]).to.equal(2);
        expect(output[7]).to.equal(5);

        output = matrix.toArray(false);

        expect(output.length).to.equal(9);
        expect(output[0]).to.equal(0);
        expect(output[1]).to.equal(3);
        expect(output[2]).to.equal(2);
        expect(output[3]).to.equal(1);
        expect(output[4]).to.equal(4);
        expect(output[5]).to.equal(5);
    });

    it('should apply different transforms', function ()
    {
        const matrix = new PIXI.Matrix();

        matrix.translate(10, 20);
        matrix.translate(1, 2);
        expect(matrix.tx).to.equal(11);
        expect(matrix.ty).to.equal(22);

        matrix.scale(2, 4);
        expect(matrix.a).to.equal(2);
        expect(matrix.b).to.equal(0);
        expect(matrix.c).to.equal(0);
        expect(matrix.d).to.equal(4);
        expect(matrix.tx).to.equal(22);
        expect(matrix.ty).to.equal(88);

        const m2 = matrix.clone();

        expect(m2).to.not.equal(matrix);
        expect(m2.a).to.equal(2);
        expect(m2.b).to.equal(0);
        expect(m2.c).to.equal(0);
        expect(m2.d).to.equal(4);
        expect(m2.tx).to.equal(22);
        expect(m2.ty).to.equal(88);

        matrix.setTransform(14, 15, 0, 0, 4, 2, 0, 0, 0);
        expect(matrix.a).to.equal(4);
        expect(matrix.b).to.equal(0);
        expect(matrix.c).to.equal(0);
        expect(matrix.d).to.equal(2);
        expect(matrix.tx).to.equal(14);
        expect(matrix.ty).to.equal(15);
    });

    it('should get IDENTITY and TEMP_MATRIX', function ()
    {
        expect(PIXI.Matrix.IDENTITY instanceof PIXI.Matrix).to.be.true;
        expect(PIXI.Matrix.TEMP_MATRIX instanceof PIXI.Matrix).to.be.true;
    });
});

<commit_msg>More Matrix<commit_after>'use strict';

describe('PIXI.Matrix', function ()
{
    it('should create a new matrix', function ()
    {
        const matrix = new PIXI.Matrix();

        expect(matrix.a).to.equal(1);
        expect(matrix.b).to.equal(0);
        expect(matrix.c).to.equal(0);
        expect(matrix.d).to.equal(1);
        expect(matrix.tx).to.equal(0);
        expect(matrix.ty).to.equal(0);

        const input = [0, 1, 2, 3, 4, 5];

        matrix.fromArray(input);

        expect(matrix.a).to.equal(0);
        expect(matrix.b).to.equal(1);
        expect(matrix.c).to.equal(3);
        expect(matrix.d).to.equal(4);
        expect(matrix.tx).to.equal(2);
        expect(matrix.ty).to.equal(5);

        let output = matrix.toArray(true);

        expect(output.length).to.equal(9);
        expect(output[0]).to.equal(0);
        expect(output[1]).to.equal(1);
        expect(output[3]).to.equal(3);
        expect(output[4]).to.equal(4);
        expect(output[6]).to.equal(2);
        expect(output[7]).to.equal(5);

        output = matrix.toArray(false);

        expect(output.length).to.equal(9);
        expect(output[0]).to.equal(0);
        expect(output[1]).to.equal(3);
        expect(output[2]).to.equal(2);
        expect(output[3]).to.equal(1);
        expect(output[4]).to.equal(4);
        expect(output[5]).to.equal(5);
    });

    it('should apply different transforms', function ()
    {
        const matrix = new PIXI.Matrix();

        matrix.translate(10, 20);
        matrix.translate(1, 2);
        expect(matrix.tx).to.equal(11);
        expect(matrix.ty).to.equal(22);

        matrix.scale(2, 4);
        expect(matrix.a).to.equal(2);
        expect(matrix.b).to.equal(0);
        expect(matrix.c).to.equal(0);
        expect(matrix.d).to.equal(4);
        expect(matrix.tx).to.equal(22);
        expect(matrix.ty).to.equal(88);

        const m2 = matrix.clone();

        expect(m2).to.not.equal(matrix);
        expect(m2.a).to.equal(2);
        expect(m2.b).to.equal(0);
        expect(m2.c).to.equal(0);
        expect(m2.d).to.equal(4);
        expect(m2.tx).to.equal(22);
        expect(m2.ty).to.equal(88);

        matrix.setTransform(14, 15, 0, 0, 4, 2, 0, 0, 0);
        expect(matrix.a).to.equal(4);
        expect(matrix.b).to.equal(0);
        expect(matrix.c).to.equal(0);
        expect(matrix.d).to.equal(2);
        expect(matrix.tx).to.equal(14);
        expect(matrix.ty).to.equal(15);
    });

    it('should allow rotatation', function ()
    {
        const matrix = new PIXI.Matrix();

        matrix.rotate(Math.PI);

        expect(matrix.a).to.equal(-1);
        expect(matrix.b).to.equal(Math.sin(Math.PI));
        expect(matrix.c).to.equal(-Math.sin(Math.PI));
        expect(matrix.d).to.equal(-1);
    });

    it('should append matrix', function ()
    {
        const m1 = new PIXI.Matrix();
        const m2 = new PIXI.Matrix();

        m2.tx = 100;
        m2.ty = 200;

        m1.append(m2);

        expect(m1.tx).to.equal(m2.tx);
        expect(m1.ty).to.equal(m2.ty);
    });

    it('should get IDENTITY and TEMP_MATRIX', function ()
    {
        expect(PIXI.Matrix.IDENTITY instanceof PIXI.Matrix).to.be.true;
        expect(PIXI.Matrix.TEMP_MATRIX instanceof PIXI.Matrix).to.be.true;
    });
});

<|endoftext|>


<commit_before>'use strict';

var lib = require('../lib');

try {
    var FFT = require('fft.js');
} catch(err) {
    console.log('Nope, the runtime is too old');
    console.log(err);
}

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

describe('DFT 4096', function () {
    var i,
        inpReal,
        inpImag,
        fn,
        stdlib,
        heap,
        len = 4096,
        compare = function (a, b, label) {
            var i,
                err = 0;

            expect(a.length, label + 'length').to.be.equal(b.length);

            label += ' error:';
            for (i = 0; i < a.length; i++) {
                if (isNaN(a[i])) {
                    console.log(a);
                    return;
                }
                if (isNaN(b[i])) {
                    console.log(b);
                    return;
                }
                err += Math.abs(a[i] - b[i]);
            }
            err /= a.length;
            console.log(label, err);
            expect(err, label).to.be.at.most(0.0000001);
        },
        add = function (a, b) { return a + b; };

    if (typeof window === 'undefined') {
        stdlib = {
            Math: Math,
            Float64Array: Float64Array,
            Float32Array: Float32Array
        };
        if (stdlib.Math.fround === undefined) {
            stdlib.Math.fround = function (n) { return n; };
        }
    } else {
        stdlib = window;
    }

    it('dft, zeros', function (done) {
        var res;

        inpReal = [];
        inpImag = [];
        for (i = 0; i < len; i++) {
            inpReal.push(0);
            inpImag.push(0);
        }

        res = lib.dft(inpReal, inpImag);

        expect(res[0]).to.be.an('array');
        expect(res[1]).to.be.an('array');
        expect(res[0].reduce(add, 0)).to.be.equal(0);
        expect(res[1].reduce(add, 0)).to.be.equal(0);
        done();
    });

    it('idft, zeros', function (done) {
        var res;

        inpReal = [];
        inpImag = [];
        for (i = 0; i < len; i++) {
            inpReal.push(0);
            inpImag.push(0);
        }

        res = lib.idft(inpReal, inpImag);

        compare(res[0], inpReal, 'real');
        compare(res[1], inpImag, 'imag');
        done();
    });

    it('lib.custom, zeros', function (done) {
        inpReal = [];
        inpImag = [];
        for (i = 0; i < len; i++) {
            inpReal.push(0);
            inpImag.push(0);
        }

        lib.fft(inpReal, inpImag);

        expect(inpReal.reduce(add, 0)).to.be.equal(0);
        expect(inpImag.reduce(add, 0)).to.be.equal(0);
        done();
    });

    it('dft, DC = 1', function (done) {
        var res;

        inpReal[0] = 1;

        res = lib.dft(inpReal, inpImag);

        expect(res[0].reduce(add, 0)).to.be.equal(len);
        expect(res[1].reduce(add, 0)).to.be.equal(0);
        done();
    });

    it('random dft / idft', function (done) {
        var res;

        inpReal = [];
        inpImag = [];
        for (i = 0; i < len; i++) {
            inpReal.push(Math.random() - 0.5);
            inpImag.push(Math.random() - 0.5);
        }

        res = lib.dft(inpReal, inpImag);
        res = lib.idft(res[0], res[1]);

        compare(res[0], inpReal, 'real');
        compare(res[1], inpImag, 'imag');
        done();
    });

    it('random fft.js / idft', function (done) {
        try {
            var f = new FFT(len);
            var a = f.createComplexArray();
            var b = f.createComplexArray();
            var re, im, res;

            inpReal = [];
            inpImag = [];
            for (i = 0; i < (2 * len); i += 2) {
                re = Math.random() - 0.5;
                im = Math.random() - 0.5;
                a[i] = re;
                a[i + 1] = im;
                inpReal.push(re);
                inpImag.push(im);
            }

            f.transform(b, a);

            res = [[], []];
            for (i = 0; i < (2 * len); i += 2) {
                res[0].push(b[i]);
                res[1].push(b[i + 1]);
            }

            res = lib.idft(res[0], res[1]);

            compare(res[0], inpReal, 'real');
            compare(res[1], inpImag, 'imag');
        } catch(err) {
            console.log('Nope, the runtime is too old');
            console.log(err);
        }
        done();
    });

    it('random fft / idft', function (done) {
        var res;

        res = [[], []];
        inpReal = [];
        inpImag = [];
        for (i = 0; i < len; i++) {
            inpReal.push(Math.random() - 0.5);
            inpImag.push(Math.random() - 0.5);
            res[0].push(inpReal[i]);
            res[1].push(inpImag[i]);
        }

        lib.fft()(res[0], res[1]);
        res = lib.idft(res[0], res[1]);

        compare(res[0], inpReal, 'real');
        compare(res[1], inpImag, 'imag');
        done();
    });

    it('random fft-f64-raw vs. idft-double', function (done) {
        this.timeout(5000);
        var refReal,
            refImag,
            real,
            imag,
            res;

        refReal = new Float64Array(len);
        refImag = new Float64Array(len);
        real = new Float64Array(len);
        imag = new Float64Array(len);

        for (i = 0; i < len; i++) {
            real[i] = refReal[i] = Math.random() - 0.5;
            imag[i] = refImag[i] = Math.random() - 0.5;
        }

        heap = lib.custom.alloc(len, 3);

        fn = lib.custom['fft_f64_' + len + '_raw'](stdlib, null, heap);
        fn.init();

        lib.custom.array2heap(real, new Float64Array(heap), len, 0);
        lib.custom.array2heap(imag, new Float64Array(heap), len, len);

        fn.transform();

        lib.custom.heap2array(new Float64Array(heap), real, len, 0);
        lib.custom.heap2array(new Float64Array(heap), imag, len, len);

        res = lib.idft(real, imag);

        compare(res[0], refReal, 'real');
        compare(res[1], refImag, 'imag');
        done();
    });

    it('random fft-f32-raw vs. idft-double', function (done) {
        this.timeout(5000);
        var refReal,
            refImag,
            real,
            imag,
            res;

        refReal = new Float32Array(len);
        refImag = new Float32Array(len);
        real = new Float32Array(len);
        imag = new Float32Array(len);

        for (i = 0; i < len; i++) {
            real[i] = refReal[i] = Math.random() - 0.5;
            imag[i] = refImag[i] = Math.random() - 0.5;
        }

        heap = lib.custom.alloc(len, 3);

        fn = lib.custom['fft_f32_' + len + '_raw'](stdlib, null, heap);
        fn.init();

        lib.custom.array2heap(real, new Float32Array(heap), len, 0);
        lib.custom.array2heap(imag, new Float32Array(heap), len, len);

        fn.transform();

        lib.custom.heap2array(new Float32Array(heap), real, len, 0);
        lib.custom.heap2array(new Float32Array(heap), imag, len, len);

        res = lib.idft(real, imag);

        compare(res[0], refReal, 'real');
        compare(res[1], refImag, 'imag');
        done();
    });

    it('random lib.custom-f64-asm vs. idft-double', function (done) {
        this.timeout(5000);
        var refReal,
            refImag,
            real,
            imag,
            res;

        refReal = new Float64Array(len);
        refImag = new Float64Array(len);
        real = new Float64Array(len);
        imag = new Float64Array(len);

        for (i = 0; i < len; i++) {
            real[i] = refReal[i] = Math.random() - 0.5;
            imag[i] = refImag[i] = Math.random() - 0.5;
        }

        heap = lib.custom.alloc(len, 3);

        fn = lib.custom['fft_f64_' + len + '_asm'](stdlib, null, heap);
        fn.init();

        lib.custom.array2heap(real, new Float64Array(heap), len, 0);
        lib.custom.array2heap(imag, new Float64Array(heap), len, len);

        fn.transform();

        lib.custom.heap2array(new Float64Array(heap), real, len, 0);
        lib.custom.heap2array(new Float64Array(heap), imag, len, len);

        res = lib.idft(real, imag);

        compare(res[0], refReal, 'real');
        compare(res[1], refImag, 'imag');
        done();
    });

    it('random fft-f32-asm vs. idft-double', function (done) {
        this.timeout(5000);
        var refReal,
            refImag,
            real,
            imag,
            res;

        refReal = new Float32Array(len);
        refImag = new Float32Array(len);
        real = new Float32Array(len);
        imag = new Float32Array(len);

        for (i = 0; i < len; i++) {
            real[i] = refReal[i] = Math.random() - 0.5;
            imag[i] = refImag[i] = Math.random() - 0.5;
        }

        heap = lib.custom.alloc(len, 3);

        fn = lib.custom['fft_f32_' + len + '_asm'](stdlib, null, heap);
        fn.init();

        lib.custom.array2heap(real, new Float32Array(heap), len, 0);
        lib.custom.array2heap(imag, new Float32Array(heap), len, len);

        fn.transform();

        lib.custom.heap2array(new Float32Array(heap), real, len, 0);
        lib.custom.heap2array(new Float32Array(heap), imag, len, len);

        res = lib.idft(real, imag);

        compare(res[0], refReal, 'real');
        compare(res[1], refImag, 'imag');
        done();
    });
});

/* eslint no-console: 0 */
<commit_msg>timeout fix<commit_after>'use strict';

var lib = require('../lib');

try {
    var FFT = require('fft.js');
} catch(err) {
    console.log('Nope, the runtime is too old');
    console.log(err);
}

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

describe('DFT 4096', function () {
    this.timeout(5000);
    var i,
        inpReal,
        inpImag,
        fn,
        stdlib,
        heap,
        len = 4096,
        compare = function (a, b, label) {
            var i,
                err = 0;

            expect(a.length, label + 'length').to.be.equal(b.length);

            label += ' error:';
            for (i = 0; i < a.length; i++) {
                if (isNaN(a[i])) {
                    console.log(a);
                    return;
                }
                if (isNaN(b[i])) {
                    console.log(b);
                    return;
                }
                err += Math.abs(a[i] - b[i]);
            }
            err /= a.length;
            console.log(label, err);
            expect(err, label).to.be.at.most(0.0000001);
        },
        add = function (a, b) { return a + b; };

    if (typeof window === 'undefined') {
        stdlib = {
            Math: Math,
            Float64Array: Float64Array,
            Float32Array: Float32Array
        };
        if (stdlib.Math.fround === undefined) {
            stdlib.Math.fround = function (n) { return n; };
        }
    } else {
        stdlib = window;
    }

    it('dft, zeros', function (done) {
        var res;

        inpReal = [];
        inpImag = [];
        for (i = 0; i < len; i++) {
            inpReal.push(0);
            inpImag.push(0);
        }

        res = lib.dft(inpReal, inpImag);

        expect(res[0]).to.be.an('array');
        expect(res[1]).to.be.an('array');
        expect(res[0].reduce(add, 0)).to.be.equal(0);
        expect(res[1].reduce(add, 0)).to.be.equal(0);
        done();
    });

    it('idft, zeros', function (done) {
        var res;

        inpReal = [];
        inpImag = [];
        for (i = 0; i < len; i++) {
            inpReal.push(0);
            inpImag.push(0);
        }

        res = lib.idft(inpReal, inpImag);

        compare(res[0], inpReal, 'real');
        compare(res[1], inpImag, 'imag');
        done();
    });

    it('lib.custom, zeros', function (done) {
        inpReal = [];
        inpImag = [];
        for (i = 0; i < len; i++) {
            inpReal.push(0);
            inpImag.push(0);
        }

        lib.fft(inpReal, inpImag);

        expect(inpReal.reduce(add, 0)).to.be.equal(0);
        expect(inpImag.reduce(add, 0)).to.be.equal(0);
        done();
    });

    it('dft, DC = 1', function (done) {
        var res;

        inpReal[0] = 1;

        res = lib.dft(inpReal, inpImag);

        expect(res[0].reduce(add, 0)).to.be.equal(len);
        expect(res[1].reduce(add, 0)).to.be.equal(0);
        done();
    });

    it('random dft / idft', function (done) {
        var res;

        inpReal = [];
        inpImag = [];
        for (i = 0; i < len; i++) {
            inpReal.push(Math.random() - 0.5);
            inpImag.push(Math.random() - 0.5);
        }

        res = lib.dft(inpReal, inpImag);
        res = lib.idft(res[0], res[1]);

        compare(res[0], inpReal, 'real');
        compare(res[1], inpImag, 'imag');
        done();
    });

    it('random fft.js / idft', function (done) {
        try {
            var f = new FFT(len);
            var a = f.createComplexArray();
            var b = f.createComplexArray();
            var re, im, res;

            inpReal = [];
            inpImag = [];
            for (i = 0; i < (2 * len); i += 2) {
                re = Math.random() - 0.5;
                im = Math.random() - 0.5;
                a[i] = re;
                a[i + 1] = im;
                inpReal.push(re);
                inpImag.push(im);
            }

            f.transform(b, a);

            res = [[], []];
            for (i = 0; i < (2 * len); i += 2) {
                res[0].push(b[i]);
                res[1].push(b[i + 1]);
            }

            res = lib.idft(res[0], res[1]);

            compare(res[0], inpReal, 'real');
            compare(res[1], inpImag, 'imag');
        } catch(err) {
            console.log('Nope, the runtime is too old');
            console.log(err);
        }
        done();
    });

    it('random fft / idft', function (done) {
        var res;

        res = [[], []];
        inpReal = [];
        inpImag = [];
        for (i = 0; i < len; i++) {
            inpReal.push(Math.random() - 0.5);
            inpImag.push(Math.random() - 0.5);
            res[0].push(inpReal[i]);
            res[1].push(inpImag[i]);
        }

        lib.fft()(res[0], res[1]);
        res = lib.idft(res[0], res[1]);

        compare(res[0], inpReal, 'real');
        compare(res[1], inpImag, 'imag');
        done();
    });

    it('random fft-f64-raw vs. idft-double', function (done) {
        var refReal,
            refImag,
            real,
            imag,
            res;

        refReal = new Float64Array(len);
        refImag = new Float64Array(len);
        real = new Float64Array(len);
        imag = new Float64Array(len);

        for (i = 0; i < len; i++) {
            real[i] = refReal[i] = Math.random() - 0.5;
            imag[i] = refImag[i] = Math.random() - 0.5;
        }

        heap = lib.custom.alloc(len, 3);

        fn = lib.custom['fft_f64_' + len + '_raw'](stdlib, null, heap);
        fn.init();

        lib.custom.array2heap(real, new Float64Array(heap), len, 0);
        lib.custom.array2heap(imag, new Float64Array(heap), len, len);

        fn.transform();

        lib.custom.heap2array(new Float64Array(heap), real, len, 0);
        lib.custom.heap2array(new Float64Array(heap), imag, len, len);

        res = lib.idft(real, imag);

        compare(res[0], refReal, 'real');
        compare(res[1], refImag, 'imag');
        done();
    });

    it('random fft-f32-raw vs. idft-double', function (done) {
        var refReal,
            refImag,
            real,
            imag,
            res;

        refReal = new Float32Array(len);
        refImag = new Float32Array(len);
        real = new Float32Array(len);
        imag = new Float32Array(len);

        for (i = 0; i < len; i++) {
            real[i] = refReal[i] = Math.random() - 0.5;
            imag[i] = refImag[i] = Math.random() - 0.5;
        }

        heap = lib.custom.alloc(len, 3);

        fn = lib.custom['fft_f32_' + len + '_raw'](stdlib, null, heap);
        fn.init();

        lib.custom.array2heap(real, new Float32Array(heap), len, 0);
        lib.custom.array2heap(imag, new Float32Array(heap), len, len);

        fn.transform();

        lib.custom.heap2array(new Float32Array(heap), real, len, 0);
        lib.custom.heap2array(new Float32Array(heap), imag, len, len);

        res = lib.idft(real, imag);

        compare(res[0], refReal, 'real');
        compare(res[1], refImag, 'imag');
        done();
    });

    it('random lib.custom-f64-asm vs. idft-double', function (done) {
        var refReal,
            refImag,
            real,
            imag,
            res;

        refReal = new Float64Array(len);
        refImag = new Float64Array(len);
        real = new Float64Array(len);
        imag = new Float64Array(len);

        for (i = 0; i < len; i++) {
            real[i] = refReal[i] = Math.random() - 0.5;
            imag[i] = refImag[i] = Math.random() - 0.5;
        }

        heap = lib.custom.alloc(len, 3);

        fn = lib.custom['fft_f64_' + len + '_asm'](stdlib, null, heap);
        fn.init();

        lib.custom.array2heap(real, new Float64Array(heap), len, 0);
        lib.custom.array2heap(imag, new Float64Array(heap), len, len);

        fn.transform();

        lib.custom.heap2array(new Float64Array(heap), real, len, 0);
        lib.custom.heap2array(new Float64Array(heap), imag, len, len);

        res = lib.idft(real, imag);

        compare(res[0], refReal, 'real');
        compare(res[1], refImag, 'imag');
        done();
    });

    it('random fft-f32-asm vs. idft-double', function (done) {
        var refReal,
            refImag,
            real,
            imag,
            res;

        refReal = new Float32Array(len);
        refImag = new Float32Array(len);
        real = new Float32Array(len);
        imag = new Float32Array(len);

        for (i = 0; i < len; i++) {
            real[i] = refReal[i] = Math.random() - 0.5;
            imag[i] = refImag[i] = Math.random() - 0.5;
        }

        heap = lib.custom.alloc(len, 3);

        fn = lib.custom['fft_f32_' + len + '_asm'](stdlib, null, heap);
        fn.init();

        lib.custom.array2heap(real, new Float32Array(heap), len, 0);
        lib.custom.array2heap(imag, new Float32Array(heap), len, len);

        fn.transform();

        lib.custom.heap2array(new Float32Array(heap), real, len, 0);
        lib.custom.heap2array(new Float32Array(heap), imag, len, len);

        res = lib.idft(real, imag);

        compare(res[0], refReal, 'real');
        compare(res[1], refImag, 'imag');
        done();
    });
});

/* eslint no-console: 0 */
<|endoftext|>


<commit_before>// TODO: Test toggle method of service
describe('unit:angularQuickDialog:service', function() {
    var scope, $quickDialog, dialog;
    var dialogName = 'randomDialogName';

    beforeEach(angular.mock.module('angularQuickDialog'));

    beforeEach(inject(function(_$rootScope_,  _$quickDialog_) {
        $quickDialog = _$quickDialog_;
        scope = _$rootScope_.$new();
        scope.$digest();
        dialog = $quickDialog.create(dialogName);
    }));

    it('$quickDialog should be defined', function() {
        expect($quickDialog).toBeDefined();
    });

    it('$quickDialog should have a map of dialog objects based on names', function() {
        expect($quickDialog.dialogs).toBeDefined();
    });

    it('$quickDialog.create should add a new dialog', function() {
        // create() already called beforeEach above
        expect($quickDialog.dialogs[dialogName]).toBeDefined();
    });

    it('$quickDialog.create should return a dialog with properties', function() {
        var hasAllProps = true,
            dialog = $quickDialog.create(dialogName);

        if (dialog.name !== dialogName)
            hasAllProps = false;
        if (!dialog.open)
            hasAllProps = false;
        if (!dialog.close)
            hasAllProps = false;

        expect(hasAllProps).toBe(true);
    });

    it('$quickDialog.create should save new dialogs with an isVisible value of false', function() {
        expect($quickDialog.dialogs[dialogName].isVisible).toBe(false);
    });

    it('$quickDialog.get should return the dialog with the name entered', function() {
        expect($quickDialog.get(dialogName) === dialog).toBe(true);
    })

    it('$quickDialog.open should set the dialog\'s visibility to true', function() {
        $quickDialog.open(dialogName);

        expect($quickDialog.dialogs[dialogName].isVisible).toBe(true);
    });

    it('$quickDialog.close should set the dialog\'s visibility to false', function() {
        // Set it to true before trying to set it to false
        $quickDialog.open(dialogName);
        $quickDialog.close(dialogName);

        expect($quickDialog.dialogs[dialogName].isVisible).toBe(false);
    });

    // Probably get rid of it once stack functionality works.
    // it('dialog.open should set the dialog\'s visibility to true', function() {
    //     dialog.open();
    //
    //     expect(dialog.isVisible).toBe(true);
    // });
    //
    // it('dialog.close should set the dialog\'s visibility to false', function() {
    //     // Set it to true before trying to set it to false
    //     dialog.open();
    //     dialog.close();
    //
    //     expect(dialog.isVisible).toBe(false);
    // });
    //
    // it('$quickDialog should work within a scope', function() {
    //     scope.$quickDialog = $quickDialog;
    //
    //     scope.dialog = scope.$quickDialog.create(dialogName);
    //     expect(scope.dialog.name).toBe(dialogName);
    //     expect(scope.dialog.isVisible).toBe(false);
    //
    //     scope.$quickDialog.open(dialogName);
    //     expect(scope.dialog.isVisible).toBe(true);
    //
    //     scope.$quickDialog.close(dialogName);
    //     expect(scope.dialog.isVisible).toBe(false);
    //
    //     expect(scope.$quickDialog.get(dialogName)).toBe(scope.dialog);
    // });
    //
    // it('dialog should work within a scope', function() {
    //     scope.dialog = dialog;
    //
    //     expect(scope.dialog).toBe(dialog);
    //
    //     scope.dialog.open();
    //     expect(scope.dialog.isVisible).toBe(true);
    //
    //     scope.dialog.close();
    //     expect(scope.dialog.isVisible).toBe(false);
    // });
});

describe('unit:angularQuickDialog:directive', function () {
    var scope, element, $quickDialog;
    var dialogName = 'randomDialog-Name';
    beforeEach(angular.mock.module('angularQuickDialog'));

    beforeEach(inject(function(_$rootScope_, _$compile_, _$quickDialog_) {
        $quickDialog = _$quickDialog_;
        scope = _$rootScope_.$new();
        element = '<quick-dialog dialog-name="'+dialogName+'"></quick-dialog>';
        element = _$compile_(element)(scope);
        scope.$digest();
    }));

    it('should have angular defined', function() {
        expect(angular).toBeDefined();
    });

    it('should have a dialog directive', function() {
        expect(element).toBeDefined();
    });

    it('using the directive should save to service', function() {
        expect($quickDialog.dialogs[dialogName].name).toBe(dialogName);
    });
});

<commit_msg>Refactored unit test.<commit_after>describe('unit:angularQuickDialog', function() {
	var scope, $quickDialog, dialog;
    var dialogName = 'randomDialogName';

    beforeEach(angular.mock.module('angularQuickDialog'));

    describe('unit:angularQuickDialog:service', function() {
	    beforeEach(inject(function(_$rootScope_,  _$quickDialog_) {
	        $quickDialog = _$quickDialog_;
	        scope = _$rootScope_.$new();
	        scope.$digest();
	        dialog = $quickDialog.create(dialogName);
	    }));

	    it('$quickDialog should be defined', function() {
	        expect($quickDialog).toBeDefined();
	    });

	    it('$quickDialog.create should return a dialog with properties', function() {
	        var hasAllProps = true,
	            dialog = $quickDialog.create(dialogName);

	        if (dialog.name !== dialogName)
	            hasAllProps = false;
	        if (!dialog.open)
	            hasAllProps = false;
	        if (!dialog.close)
	            hasAllProps = false;

	        expect(hasAllProps).toBe(true);
	    });

	    it('$quickDialog.create should save new dialogs with an isVisible value of false', function() {
	        expect(dialog.isVisible).toBe(false);
	    });

	    it('$quickDialog.open should set the dialog\'s visibility to true', function() {
	        $quickDialog.open(dialogName);

	        expect(dialog.isVisible).toBe(true);
	    });

	    it('$quickDialog.close should set the dialog\'s visibility to false', function() {
	        // Set it to true before trying to set it to false
	        $quickDialog.open(dialogName);
	        $quickDialog.close(dialogName);

	        expect(dialog.isVisible).toBe(false);
	    });

	    it('dialog.open should set the dialog\'s visibility to true', function() {
	        dialog.open();

	        expect(dialog.isVisible).toBe(true);
	    });

	    it('dialog.close should set the dialog\'s visibility to false', function() {
	        // Set it to true before trying to set it to false
	        dialog.open();
	        dialog.close();

	        expect(dialog.isVisible).toBe(false);
	    });

	    it('$quickDialog should work within a scope', function() {
	        scope.$quickDialog = $quickDialog;

	        scope.$quickDialog.open(dialogName);
	        expect(dialog.isVisible).toBe(true);

	        scope.$quickDialog.close(dialogName);
	        expect(dialog.isVisible).toBe(false);
	    });

	    it('dialog should work within a scope', function() {
	    	scope.$quickDialog = $quickDialog;
	        scope.dialog = scope.$quickDialog.create(dialogName);

	        expect(scope.dialog.name).toBe(dialogName);
	        expect(scope.dialog.isVisible).toBe(false);

	        scope.dialog.open();
	        expect(scope.dialog.isVisible).toBe(true);

	        scope.dialog.close();
	        expect(scope.dialog.isVisible).toBe(false);
	    });
	});  // End service describe

	describe('unit:angularQuickDialog:directive', function () {
	    beforeEach(inject(function(_$rootScope_, _$compile_, _$quickDialog_) {
	        $quickDialog = _$quickDialog_;
	        scope = _$rootScope_.$new();
	        dialogEl = '<quick-dialog dialog-name="'+dialogName+'"></quick-dialog>';
	        dialogEl = _$compile_(dialogEl)(scope);
	        scope.$digest();
	    }));

	    it('should have angular defined', function() {
	        expect(angular).toBeDefined();
	    });

	    it('should have a dialog directive', function() {
	        expect(dialogEl).toBeDefined();
	    });

	    it('using the directive should save to service', function() {
	    	// Check for default value
	    	expect(dialogEl.isolateScope().dialog.isVisible).toBe(false);
	    });
	});  // End directive describe
});
<|endoftext|>


<commit_before>(function (module) {
    module.factory('gridFiles', gridFiles);

    function gridFiles() {
        function compareFileEntry(fentry1, fentry2) {
            if (fentry1.name < fentry2.name) {
                return -1;
            } else if (fentry1.name > fentry2.name) {
                return 1;
            } else {
                return 0;
            }
        }

        function createGridChildren(filesChildren) {
            var children = [];
            filesChildren.forEach(function (entry) {
                var centry;
                if (entry._type == 'directory') {
                    centry = createDirectoryEntry(entry);
                } else {
                    centry = createFileEntry(entry);
                }
                children.push(centry);
            });
            return children;
        }

        function createDirectoryEntry(entry) {
            return {
                group: true,
                expanded: false,
                data: {
                    name: entry.name,
                    _type: 'directory',
                    id: entry.id,
                    size: '',
                    childrenLoaded: false
                },
                children: []
            };
        }

        function createFileEntry(entry) {
            return {
                group: false,
                data: {
                    name: entry.name,
                    _type: 'file',
                    size: entry.size,
                    mediatype: entry.mediatype,
                    id: entry.id
                }
            };
        }

        return {
            toGrid: function (files) {
                var gridData = [
                    {
                        group: true,
                        expanded: true,
                        data: {
                            name: files.name,
                            _type: files._type,
                            id: files.id,
                            childrenLoaded: true
                        },
                        children: []
                    }
                ];
                files.children.sort(compareFileEntry);
                gridData[0].children = createGridChildren(files.children);
                return gridData;
            },

            toGridChildren(fentry) {
                fentry.children.sort(compareFileEntry);
                return createGridChildren(fentry.children);
            },

            findEntry(files, id) {
                var treeModel = new TreeModel(),
                    root = treeModel.parse(files);
                var entry = root.first({strategy: 'pre'}, function (node) {
                    return node.model.data.id === id;
                });
                return entry;
            }
        }
    }
}(angular.module('materialscommons')));
<commit_msg>Set path for top level directory.<commit_after>(function (module) {
    module.factory('gridFiles', gridFiles);

    function gridFiles() {
        function compareFileEntry(fentry1, fentry2) {
            if (fentry1.name < fentry2.name) {
                return -1;
            } else if (fentry1.name > fentry2.name) {
                return 1;
            } else {
                return 0;
            }
        }

        function createGridChildren(filesChildren) {
            var children = [];
            filesChildren.forEach(function (entry) {
                var centry;
                if (entry._type == 'directory') {
                    centry = createDirectoryEntry(entry);
                } else {
                    centry = createFileEntry(entry);
                }
                children.push(centry);
            });
            return children;
        }

        function createDirectoryEntry(entry) {
            console.dir(entry);
            return {
                group: true,
                expanded: false,
                data: {
                    name: entry.name,
                    path: entry.path,
                    _type: 'directory',
                    id: entry.id,
                    size: '',
                    childrenLoaded: false
                },
                children: []
            };
        }

        function createFileEntry(entry) {
            return {
                group: false,
                data: {
                    name: entry.name,
                    _type: 'file',
                    path: entry.path,
                    size: entry.size,
                    mediatype: entry.mediatype,
                    id: entry.id
                }
            };
        }

        return {
            toGrid: function (files) {
                var gridData = [
                    {
                        group: true,
                        expanded: true,
                        data: {
                            name: files.name,
                            path: files.path,
                            _type: files._type,
                            id: files.id,
                            childrenLoaded: true
                        },
                        children: []
                    }
                ];
                files.children.sort(compareFileEntry);
                gridData[0].children = createGridChildren(files.children);
                return gridData;
            },

            toGridChildren(fentry) {
                fentry.children.sort(compareFileEntry);
                return createGridChildren(fentry.children);
            },

            findEntry(files, id) {
                var treeModel = new TreeModel(),
                    root = treeModel.parse(files);
                return root.first({strategy: 'pre'}, function (node) {
                    return node.model.data.id === id;
                });
            }
        }
    }
}(angular.module('materialscommons')));
<|endoftext|>


<commit_before>// Valid Word Abbreviation

// Given a non-empty string s and an abbreviation abbr, return whether the string matches with the given abbreviation.

// A string such as "word" contains only the following valid abbreviations:

// ["word", "1ord", "w1rd", "wo1d", "wor1", "2rd", "w2d", "wo2", "1o1d", "1or1", "w1r1", "1o2", "2r1", "3d", "w3", "4"]
// Notice that only the above abbreviations are valid abbreviations of the string "word".
// Any other string is not a valid abbreviation of "word".

// Note:
// Assume s contains only lowercase letters and abbr contains only lowercase letters and digits.

// Example 1:
// Given s = "internationalization", abbr = "i12iz4n":

// Return true.
// Example 2:
// Given s = "apple", abbr = "a2e":

// Return false.

/**
 * @param {string} word
 * @param {string} abbr
 * @return {boolean}
 */

var validWordAbbreviation = function(word, abbr) {
    if(word.length < 1) return false;
    var stack = '';
    for( var i=0, j=0, k; i< word.length || j < abbr.length; ){// j = abbr | i = word
        if( Number(abbr[j]) ){
            k = j+1;
            stack = abbr[j];
            while( Number(abbr[k]) || abbr[k] < 1 ){ // check for double digits
                stack += abbr[k]; // add extra digits to stack
                k++;
                j++;
            }
            i+=Number(stack);
            j++;
            if( i > word.length ) return false; // false if number is is bigger than word length
            continue;
        }

        if( word[i] !== abbr[j] ) return false;
        i++;
        j++;
    }
    return true;
};

var ex1 = ["internationalization", "i12iz4n"]
console.log(validWordAbbreviation(ex1[0], ex1[1]))

var ex2 = ["apple", "appl1"]
console.log(validWordAbbreviation(ex2[0], ex2[1]))

var ex3 = ["apple", "a2e"]
console.log(validWordAbbreviation(ex3[0], ex3[1]))
<commit_msg>add notes<commit_after>// Valid Word Abbreviation

// Given a non-empty string s and an abbreviation abbr, return whether the string matches with the given abbreviation.

// A string such as "word" contains only the following valid abbreviations:

// ["word", "1ord", "w1rd", "wo1d", "wor1", "2rd", "w2d", "wo2", "1o1d", "1or1", "w1r1", "1o2", "2r1", "3d", "w3", "4"]
// Notice that only the above abbreviations are valid abbreviations of the string "word".
// Any other string is not a valid abbreviation of "word".

// Note:
// Assume s contains only lowercase letters and abbr contains only lowercase letters and digits.

// Example 1:
// Given s = "internationalization", abbr = "i12iz4n":

// Return true.
// Example 2:
// Given s = "apple", abbr = "a2e":

// Return false.

/**
 * @param {string} word
 * @param {string} abbr
 * @return {boolean}
 */

var validWordAbbreviation = function(word, abbr) {
    if(word.length < 1) return false;
    var stack = '';
    for( var i=0, j=0, k; i< word.length || j < abbr.length; ){// j = abbr | i = word
        if( Number(abbr[j]) ){ // when abbr pointer is on an Integer
            k = j+1; // k pointer checks for double, triple, etc. digits
            stack = abbr[j];
            while( Number(abbr[k]) || abbr[k] < 1 ){ // check for double digits
                stack += abbr[k]; // add extra digits to stack
                k++;
                j++;
            }
            i+=Number(stack);
            j++;
            if( i > word.length ) return false; // false if number is is bigger than word length
            continue;
        }

        if( word[i] !== abbr[j] ) return false; // once index's are adjusted we check if elements match
        i++;
        j++;
    }
    return true;
};

var ex1 = ["internationalization", "i12iz4n"]
console.log(validWordAbbreviation(ex1[0], ex1[1]))

var ex2 = ["apple", "appl1"]
console.log(validWordAbbreviation(ex2[0], ex2[1]))

var ex3 = ["apple", "a2e"]
console.log(validWordAbbreviation(ex3[0], ex3[1]))
<|endoftext|>