<commit_before>'use strict';

const test = require('tape');
const fs = require('fs');
let roi = require('../lib/roi');

test('setup', t => {
  roi = roi({ port: 3000 });
  console.log('init.');
  t.end();
});

test('Should get.', t => {
  roi.get('/posts')
    .then(x => {
      t.equal(x[0].id, 1);
      t.end();
    }).catch(e => console.log(e));
});

test('Should delete.', t => {
  roi.del('/posts/1')
    .then(x => {
      t.equal(x.statusCode, 200);
      t.end();
    }).catch(e => console.log(e));
});

test('Should post.', t => {
  let foo = {
    title: 'foo-json',
    author: 'Panther-JS'
  };

  roi.post('/posts', foo)
    .then(x => {
      t.equal(x.statusCode, 201);
      t.end();
    }).catch(e => console.log(e));
});

test('Should put.', t => {
  let foo = {
    title: 'hail-json-server',
    author: 'Panther-JS'
  };

  roi.put('/posts/1', foo)
    .then(x => {
      t.equal(x.statusCode, 200);
      t.end();
    }).catch(e => console.log(e));
});

test('Should download.', t => {
  roi = roi({ host: 'central.maven.org' });
  roi.download('/maven2/org/jboss/aesh/aesh/0.66.8/aesh-0.66.8.jar', '/tmp/aesh.jar')
    .then(x => {
      try {
        fs.statSync('/tmp/aesh.jar');
        t.equal(1, 1);
      } catch (e) {
        console.log(e);
      }
      t.end();
    }).catch(e => console.log(e));
});
<commit_msg>test fix<commit_after>'use strict';

const test = require('tape');
const fs = require('fs');
const Roi = require('../lib/roi');

let roi = null;

test('setup', t => {
  roi = Roi({ port: 3000 });
  console.log('init.');
  t.end();
});

test('Should get.', t => {
  roi.get('/posts')
    .then(x => {
      t.equal(x[0].id, 1);
      t.end();
    }).catch(e => console.log(e));
});

test('Should delete.', t => {
  roi.del('/posts/1')
    .then(x => {
      t.equal(x.statusCode, 200);
      t.end();
    }).catch(e => console.log(e));
});

test('Should post.', t => {
  let foo = {
    title: 'foo-json',
    author: 'Panther-JS'
  };

  roi.post('/posts', foo)
    .then(x => {
      t.equal(x.statusCode, 201);
      t.end();
    }).catch(e => console.log(e));
});

test('Should put.', t => {
  let foo = {
    title: 'hail-json-server',
    author: 'Panther-JS'
  };

  roi.put('/posts/1', foo)
    .then(x => {
      t.equal(x.statusCode, 200);
      t.end();
    }).catch(e => console.log(e));
});

test('Should download.', t => {
  roi = Roi({ host: 'central.maven.org' });
  roi.download('/maven2/org/jboss/aesh/aesh/0.66.8/aesh-0.66.8.jar', '/tmp/aesh.jar')
    .then(x => {
      try {
        fs.statSync('/tmp/aesh.jar');
        t.equal(1, 1);
      } catch (e) {
        console.log(e);
      }
      t.end();
    }).catch(e => console.log(e));
});
<|endoftext|>


<commit_before>var fs = require("fs"), path = require("path");
var infer = require("../lib/infer");
var tern = require("../lib/tern");
var acorn = require("acorn");
var walk = require("acorn/util/walk");
require("../plugin/requirejs.js");
require("../plugin/node.js");
require("../plugin/doc_comment.js");
require("../plugin/component.js");
require("../plugin/angular.js");
var util = require("./util");

var defData = {
  browser: util.browser,
  jquery: util.jquery,
  underscore: util.underscore
};

function getDefs(text) {
  var spec = /\/\/ environment=(\w+)\n/g, m, defs = [util.ecma5];
  while (m = spec.exec(text)) {
    var data = defData[m[1]];
    if (!data) throw new Error("Unknown environment: " + m[1]);
    defs.push(data);
  }
  return defs;
}

function getPlugins(text) {
  var spec = /\/\/ plugin=(\w+)(?: (.*))?\n/g, m, plugins = {doc_comment: true};
  while (m = spec.exec(text))
    plugins[m[1]] = (m[2] && JSON.parse(m[2])) || (m[1] == "node" && {modules: nodeModules}) || {};
  return plugins;
}

fs.readdirSync(util.resolve("test/cases/defs")).forEach(function(name) {
  if (/\.json$/.test(name))
    defData[path.basename(name, ".json")] =
      JSON.parse(fs.readFileSync(util.resolve("test/cases/defs/" + name), "utf8"));
});

var nodeModules = {};
fs.readdirSync(util.resolve("test/cases/node_modules")).forEach(function(name) {
  if (/\.json$/.test(name))
    nodeModules[path.basename(name, ".json")] =
      JSON.parse(fs.readFileSync(util.resolve("test/cases/node_modules/" + name), "utf8"));
});

function serverOptions(context, text) {
  return {
    defs: getDefs(text),
    getFile: function(name) { return fs.readFileSync(path.resolve(context, name), "utf8"); },
    debug: true,
    projectDir: context,
    plugins: getPlugins(text)
  };
}

exports.runTests = function(filter) {
  var caseDir = util.resolve("test/cases");
  fs.readdirSync(caseDir).forEach(function(name) {
    if (filter && name.indexOf(filter) == -1) return;

    util.addFile();
    var fname = name, context = caseDir;
    if (fs.statSync(path.resolve(context, name)).isDirectory()) {
      if (name == "node_modules" || name == "defs") return;
      context = path.join(context, name);
      fname = "main.js";
    }

    var text = fs.readFileSync(path.join(context, fname), "utf8"), m;
    var server = new tern.Server(serverOptions(context, text));
    server.addFile(fname);
    var ast = server.files[0].ast;

    if (m = text.match(/\/\/ loadfiles=\s*(.*)\s*\n/))
      m[1].split(/,\s*/g).forEach(function(f) {server.addFile(f);});

    var typedef = /\/\/(<)?(\+\??|::?|:\?|doc:|loc:|refs:|exports:|origin:) *([^\r\n]*)/g;
    function fail(m, str) {
      util.failure(name + ", line " + acorn.getLineInfo(text, m.index).line + ": " + str);
    }

    while (m = typedef.exec(text)) (function(m) {
      var args = m[3], kind = m[2], directlyHere = m[1];
      util.addTest();
      if (kind == "+" || kind == "+?") { // Completion test
        var columnInfo = /\s*@(\d+)$/.exec(args), pos = m.index;
        if (columnInfo) {
          var line = acorn.getLineInfo(text, m.index).line;
          pos = {line: line - 1, ch: Number(columnInfo[1]) - 1};
          args = args.slice(0, columnInfo.index);
        } else {
          while (/\s/.test(text.charAt(pos - 1))) --pos;
        }
        var query = {type: "completions", end: pos, file: fname, guess: kind == "+?"};
        var andOthers = /,\s*\.\.\.$/.test(args);
        if (andOthers) args = args.slice(0, args.lastIndexOf(","));
        var parts = args ? args.split(/\s*,\s*/) : [];
        server.request({query: query}, function(err, resp) {
          if (err) throw err;
          var match = andOthers || parts.length == resp.completions.length;
          for (var i = 0; i < parts.length && match; ++i)
            if (resp.completions.indexOf(parts[i]) < 0) match = false;
          if (!match)
            fail(m, "Completion set failed at hint: " + parts[i - 1] +
                 "\n     got: " + resp.completions.join(", ") + "\n  wanted: " + args);
        });
      } else if (kind == "exports:") {
        server.request({query: {type: "node_exports", file: fname}}, function(err, resp) {
          if (err) throw err;
          if (resp.type != args) fail(m, "Export type failed. Got:\n    " + resp.type + "\nwanted:\n    " + args);
        });
      } else {
        var start, end;
        if (directlyHere) {
          for (end = m.index; end && /[\s:,;]/.test(text.charAt(end - 1)); --end) {}
          start = null;
        } else {
          var expr = walk.findNodeBefore(ast, m.index, "Expression");
          if (!expr) {
            fail(m, "No expresion found");
            return;
          }
          start = expr.node.start; end = expr.node.end;
        }
        var query = {type: kind == "doc:" ? "documentation" : kind == "loc:" ? "definition" : kind == "refs:" ? "refs" : "type",
                     start: start, end: end,
                     file: fname,
                     depth: kind == "::" ? 5 : null,
                     lineCharPositions: true};
        server.request({query: query}, function(err, resp) {
          if (err) throw err;

          if (kind == "doc:") { // Docstring test
            if (resp.doc != args) {
              fail(m, "Found " + (resp.doc ? "docstring\n  " + resp.doc + "\n" : "no docstring ") +
                   "instead of expected docstring\n  " + args);
            }
          } else if (kind == "loc:") { // Definition finding test
            var pos = args.match(/^\s*(\d+),\s*(\d+)/), line = Number(pos[1]), col = Number(pos[2]);
            if (!resp.start)
              fail(m, "Did not find a definition.");
            else if (resp.start.line + 1 != line || resp.start.ch != col)
              fail(m, "Found definition at " + (resp.start.line + 1) + ":" + resp.start.ch +
                   " instead of expected " + line + ":" + col);
          } else if (kind == "origin:") { // Origin finding test
            if (resp.origin != args)
              fail(m, "Found origin\n  " + resp.origin + "\ninstead of expected origin\n  " + args);
          } else if (kind == "refs:") { // Reference finding test
            var pos = /\s*(\d+),\s*(\d+)/g, mm;
            while (mm = pos.exec(args)) {
              var line = Number(mm[1]), col = Number(mm[2]), found = false;
              for (var i = 0; i < resp.refs.length; ++i) {
                var ref = resp.refs[i];
                if (ref.start.line + 1 == line && ref.start.ch == col) { found = true; break; }
              }
              if (!found) fail(m, "Did not find reference at line " + line + ", column " + col + ".");
            }
          } else { // Type test
            var type = resp.guess && kind != ":?" ? "?" : resp.type || "?";
            if (type != args)
              fail(m, "Expression has type\n  " + type + "\ninstead of expected type\n  " + args);
          }
        });
      }
    })(m);
  });
};
<commit_msg>Only run test case files ending in .js.<commit_after>var fs = require("fs"), path = require("path");
var infer = require("../lib/infer");
var tern = require("../lib/tern");
var acorn = require("acorn");
var walk = require("acorn/util/walk");
require("../plugin/requirejs.js");
require("../plugin/node.js");
require("../plugin/doc_comment.js");
require("../plugin/component.js");
require("../plugin/angular.js");
var util = require("./util");

var defData = {
  browser: util.browser,
  jquery: util.jquery,
  underscore: util.underscore
};

function getDefs(text) {
  var spec = /\/\/ environment=(\w+)\n/g, m, defs = [util.ecma5];
  while (m = spec.exec(text)) {
    var data = defData[m[1]];
    if (!data) throw new Error("Unknown environment: " + m[1]);
    defs.push(data);
  }
  return defs;
}

function getPlugins(text) {
  var spec = /\/\/ plugin=(\w+)(?: (.*))?\n/g, m, plugins = {doc_comment: true};
  while (m = spec.exec(text))
    plugins[m[1]] = (m[2] && JSON.parse(m[2])) || (m[1] == "node" && {modules: nodeModules}) || {};
  return plugins;
}

fs.readdirSync(util.resolve("test/cases/defs")).forEach(function(name) {
  if (/\.json$/.test(name))
    defData[path.basename(name, ".json")] =
      JSON.parse(fs.readFileSync(util.resolve("test/cases/defs/" + name), "utf8"));
});

var nodeModules = {};
fs.readdirSync(util.resolve("test/cases/node_modules")).forEach(function(name) {
  if (/\.json$/.test(name))
    nodeModules[path.basename(name, ".json")] =
      JSON.parse(fs.readFileSync(util.resolve("test/cases/node_modules/" + name), "utf8"));
});

function serverOptions(context, text) {
  return {
    defs: getDefs(text),
    getFile: function(name) { return fs.readFileSync(path.resolve(context, name), "utf8"); },
    debug: true,
    projectDir: context,
    plugins: getPlugins(text)
  };
}

exports.runTests = function(filter) {
  var caseDir = util.resolve("test/cases");
  fs.readdirSync(caseDir).forEach(function(name) {
    if (filter && name.indexOf(filter) == -1) return;

    var fname = name, context = caseDir;
    if (fs.statSync(path.resolve(context, name)).isDirectory()) {
      if (name == "node_modules" || name == "defs") return;
      context = path.join(context, name);
      fname = "main.js";
    }
    if (!/\.js$/.test(fname)) return;
    util.addFile();

    var text = fs.readFileSync(path.join(context, fname), "utf8"), m;
    var server = new tern.Server(serverOptions(context, text));
    server.addFile(fname);
    var ast = server.files[0].ast;

    if (m = text.match(/\/\/ loadfiles=\s*(.*)\s*\n/))
      m[1].split(/,\s*/g).forEach(function(f) {server.addFile(f);});

    var typedef = /\/\/(<)?(\+\??|::?|:\?|doc:|loc:|refs:|exports:|origin:) *([^\r\n]*)/g;
    function fail(m, str) {
      util.failure(name + ", line " + acorn.getLineInfo(text, m.index).line + ": " + str);
    }

    while (m = typedef.exec(text)) (function(m) {
      var args = m[3], kind = m[2], directlyHere = m[1];
      util.addTest();
      if (kind == "+" || kind == "+?") { // Completion test
        var columnInfo = /\s*@(\d+)$/.exec(args), pos = m.index;
        if (columnInfo) {
          var line = acorn.getLineInfo(text, m.index).line;
          pos = {line: line - 1, ch: Number(columnInfo[1]) - 1};
          args = args.slice(0, columnInfo.index);
        } else {
          while (/\s/.test(text.charAt(pos - 1))) --pos;
        }
        var query = {type: "completions", end: pos, file: fname, guess: kind == "+?"};
        var andOthers = /,\s*\.\.\.$/.test(args);
        if (andOthers) args = args.slice(0, args.lastIndexOf(","));
        var parts = args ? args.split(/\s*,\s*/) : [];
        server.request({query: query}, function(err, resp) {
          if (err) throw err;
          var match = andOthers || parts.length == resp.completions.length;
          for (var i = 0; i < parts.length && match; ++i)
            if (resp.completions.indexOf(parts[i]) < 0) match = false;
          if (!match)
            fail(m, "Completion set failed at hint: " + parts[i - 1] +
                 "\n     got: " + resp.completions.join(", ") + "\n  wanted: " + args);
        });
      } else if (kind == "exports:") {
        server.request({query: {type: "node_exports", file: fname}}, function(err, resp) {
          if (err) throw err;
          if (resp.type != args) fail(m, "Export type failed. Got:\n    " + resp.type + "\nwanted:\n    " + args);
        });
      } else {
        var start, end;
        if (directlyHere) {
          for (end = m.index; end && /[\s:,;]/.test(text.charAt(end - 1)); --end) {}
          start = null;
        } else {
          var expr = walk.findNodeBefore(ast, m.index, "Expression");
          if (!expr) {
            fail(m, "No expresion found");
            return;
          }
          start = expr.node.start; end = expr.node.end;
        }
        var query = {type: kind == "doc:" ? "documentation" : kind == "loc:" ? "definition" : kind == "refs:" ? "refs" : "type",
                     start: start, end: end,
                     file: fname,
                     depth: kind == "::" ? 5 : null,
                     lineCharPositions: true};
        server.request({query: query}, function(err, resp) {
          if (err) throw err;

          if (kind == "doc:") { // Docstring test
            if (resp.doc != args) {
              fail(m, "Found " + (resp.doc ? "docstring\n  " + resp.doc + "\n" : "no docstring ") +
                   "instead of expected docstring\n  " + args);
            }
          } else if (kind == "loc:") { // Definition finding test
            var pos = args.match(/^\s*(\d+),\s*(\d+)/), line = Number(pos[1]), col = Number(pos[2]);
            if (!resp.start)
              fail(m, "Did not find a definition.");
            else if (resp.start.line + 1 != line || resp.start.ch != col)
              fail(m, "Found definition at " + (resp.start.line + 1) + ":" + resp.start.ch +
                   " instead of expected " + line + ":" + col);
          } else if (kind == "origin:") { // Origin finding test
            if (resp.origin != args)
              fail(m, "Found origin\n  " + resp.origin + "\ninstead of expected origin\n  " + args);
          } else if (kind == "refs:") { // Reference finding test
            var pos = /\s*(\d+),\s*(\d+)/g, mm;
            while (mm = pos.exec(args)) {
              var line = Number(mm[1]), col = Number(mm[2]), found = false;
              for (var i = 0; i < resp.refs.length; ++i) {
                var ref = resp.refs[i];
                if (ref.start.line + 1 == line && ref.start.ch == col) { found = true; break; }
              }
              if (!found) fail(m, "Did not find reference at line " + line + ", column " + col + ".");
            }
          } else { // Type test
            var type = resp.guess && kind != ":?" ? "?" : resp.type || "?";
            if (type != args)
              fail(m, "Expression has type\n  " + type + "\ninstead of expected type\n  " + args);
          }
        });
      }
    })(m);
  });
};
<|endoftext|>


<commit_before>'use strict';

var exec = require('child_process').exec;
var assert = require('assert');
var cli = require('./cli');

describe('CLI: \'s18n\'', function() {

  it('should return usage when no command is provided', function(done) {
    exec(cli(), function(err, out, stderr) {
      assert(out.includes('Usage: s18n [options] [command]'));
      done();
    });
  });

  it('should return the current version', function(done) {
    exec(cli('--version'), function(err, out, stderr) {
      assert(out.includes(require('../package.json').version));
      done();
    });
  });

});
<commit_msg>test(CLI): tests compatible back to node v0.10<commit_after>'use strict';

var exec = require('child_process').exec;
var assert = require('assert');
var cli = require('./cli');

describe('CLI: \'s18n\'', function() {

  it('should return usage when no command is provided', function(done) {
    exec(cli(), function(err, out, stderr) {
      assert(out.indexOf('Usage: s18n [options] [command]') !== -1);
      done();
    });
  });

  it('should return the current version', function(done) {
    exec(cli('--version'), function(err, out, stderr) {
      assert(out.indexOf(require('../package.json').version) !== -1);
      done();
    });
  });

});
<|endoftext|>


<commit_before>import Strategy from '../src/strategy';
import Query from '../src/query';

import {isArray} from 'lodash';

const assert = require('power-assert');

describe('Strategy', function () {
  describe('#strategy', function () {
    it('should be an object', function () {
      var object = {};
      var strategy = new Strategy(object);
      assert.strictEqual(strategy.strategy, object);
    });
  });

  describe('#buildQuery()', function () {
    function sharedExamples() {
      context("and given text matches to the function's result", function () {
        it('should return a Query object', function () {
          var result = this.strategy.buildQuery('@hello');
          assert.ok(result instanceof Query);
          assert.strictEqual(result.strategy, this.strategy);
          assert.strictEqual(result.term, 'hello');
          assert.ok(isArray(result.match));
        });
      });

      context("and given text does not match to the function's result", function () {
        it('should return null', function () {
          assert.equal(this.strategy.buildQuery('hello'), null);
        });
      });
    }

    context('when match param is a function' , function () {
      beforeEach(function () {
        var object = {
          match: function () { return /(^|\s)@(\w+)$/; },
        };
        this.strategy = new Strategy(object);
      });

      sharedExamples.call(this);
    });

    context('when match param is a regexp', function () {
      beforeEach(function () {
        var object = {
          match: /(^|\s)@(\w+)$/,
        };
        this.strategy = new Strategy(object);
      });

      sharedExamples.call(this);
    });
  });
});
<commit_msg>Fix broken spec<commit_after>import Strategy from '../src/strategy';
import Query from '../src/query';

const assert = require('power-assert');

describe('Strategy', function () {
  describe('#strategy', function () {
    it('should be an object', function () {
      var object = {};
      var strategy = new Strategy(object);
      assert.strictEqual(strategy.strategy, object);
    });
  });

  describe('#buildQuery()', function () {
    function sharedExamples() {
      context("and given text matches to the function's result", function () {
        it('should return a Query object', function () {
          var result = this.strategy.buildQuery('@hello');
          assert.ok(result instanceof Query);
          assert.strictEqual(result.strategy, this.strategy);
          assert.strictEqual(result.term, 'hello');
          assert.ok(Array.isArray(result.match));
        });
      });

      context("and given text does not match to the function's result", function () {
        it('should return null', function () {
          assert.equal(this.strategy.buildQuery('hello'), null);
        });
      });
    }

    context('when match param is a function' , function () {
      beforeEach(function () {
        var object = {
          match: function () { return /(^|\s)@(\w+)$/; },
        };
        this.strategy = new Strategy(object);
      });

      sharedExamples.call(this);
    });

    context('when match param is a regexp', function () {
      beforeEach(function () {
        var object = {
          match: /(^|\s)@(\w+)$/,
        };
        this.strategy = new Strategy(object);
      });

      sharedExamples.call(this);
    });
  });
});
<|endoftext|>


<commit_before>(function (ns) {
    var parser = require('esprima'),
        codegen = require('escodegen'),
        parameters = require("./analyze/parameters.js"),
        interfaces = require("./interfaces.js"),
        inference = require("./analyze/typeinference/typeinference.js"),
        sanitizer = require("./analyze/sanitizer/sanitizer.js"),
        Base = require("./base/index.js"),
        GLSLCompiler = require("./generate/glsl/compiler.js").GLSLCompiler,
        GLMatrixCompiler = require("./generate/glmatrix/compiler.js").GLMatrixCompiler,
        LightPassGenerator = require("./generate/light-pass/light-pass-generator.js"),
        resolver = require("./resolve/resolve.js"),
        SpaceTransformer = require("./generate/space/transform.js").SpaceTransformer,
        validator = require("./analyze/validator.js"),
        analyzer = require("./analyze/analyze.js"),
        SpaceVectorType = interfaces.SpaceVectorType,
        SpaceType = interfaces.SpaceType,
        VectorType = interfaces.VectorType,
        SnippetList = require("./generate/snippets/snippet-list.js").SnippetList,
        SnippetEntry = require("./generate/snippets/snippet-list.js").SnippetEntry,
        SnippetConnector = require("./generate/snippets/snippet-connector"),
        GlMatrix = require("./contrib/gl-matrix.js");

    require("./contrib/gl-matrix-extend.js").extend(GlMatrix);

    var WorkingSet = function(){
        this.ast = null;
        this.aast = null;
        this.result = null;
        this.processingData = {};
    };
    Base.extend(WorkingSet.prototype, {
        setAst: function(ast){
            this.ast = ast;
        },
        parse: function(code, opt){
            opt = opt || {};
            this.ast = ns.parse(code, opt);
        },
        analyze: function(inject, implementation, opt){
            opt = opt || {};
            opt.entry = opt.entry || "global.shade";
            opt.validate = opt.validate !== undefined ? opt.validate : true;
            opt.throwOnError = opt.throwOnError !== undefined ? opt.throwOnError : true;
            opt.implementation = implementation;
            opt.inject = inject;
            this.aast = analyzer.analyze(this.ast, this.processingData, opt).ast;
            return this.aast;
        },
        getProcessingData: function(key){
            return this.processingData[key];
        },
        compileFragmentShader: function(opt){
            this.result = ns.compileFragmentShader(this.aast, opt);
            return this.result;
        }
    });

    Base.extend(ns, {

        parse: function(ast, opt) {
            if (typeof ast == 'string') {
                return parser.parse(ast, {raw: true, loc: opt.loc || false });
            }
            return ast;
        },

        /**
         * Analyze the given source and extract all used shader and system parameters
         *
         * @param {function|string} input The function of source code to analyze
         * @param opt Options
         * @returns {{shaderParameters: Array, systemParameters: Array}}
         */
        extractParameters: function (input, opt) {
            if (typeof input == 'function') {
                input = input.toString();
            }
            var ast = parser.parse(input);
            return parameters.extractParameters(ast, opt);
        },

        getSanitizedAst: function(str, opt){
            var ast = this.parse(str, opt);
            return sanitizer.sanitize(ast, opt);
        },

        parseAndInferenceExpression: function (ast, opt) {
            opt = opt || {};
            opt.entry = opt.entry || "global.shade";
            opt.validate = opt.validate !== undefined ? opt.validate : true;
            opt.throwOnError = opt.throwOnError !== undefined ? opt.throwOnError : true;

            ast = ns.parse(ast, opt);
            return analyzer.analyze(ast, {}, opt).ast;
        },

        analyze: function(ast, opt) {
            opt = opt || {};
            ast = ns.parse(ast, opt);

            return analyzer.analyze(ast, {}, opt)
        },

        resolveClosures: function(ast, implementation, processData, opt) {
            opt = opt || {};
            processData = processData || {};
            return resolver.resolveClosuresPreTypeInference(ast, implementation, processData, opt);
        },

        resolveSpaces: function(aast, opt){
            opt = opt || {};
            return SpaceTransformer.transformAast(aast, opt);
        },

        getLightPassAast: function(colorClosureSignatures, inject, opt){
            return LightPassGenerator.generateLightPassAast(colorClosureSignatures, inject)
        },

        compileFragmentShader: function(aast, opt){
            return new GLSLCompiler().compileFragmentShader(aast, opt);
        },

        toJavaScript: function(aast, opt){
            return codegen.generate(aast, opt);
        },

        excludeEnv:function(snippetAst,params){
        	for (obj in snippetAst){
        		if ((typeof (snippetAst[obj]) == 'object' || Array.isArray(snippetAst[obj])) && snippetAst[obj])
	    			if (snippetAst[obj]["type"]!= "MemberExpression"){
	    				this.excludeEnv(snippetAst[obj],params);
	    				}
	    			else{
	    				if (snippetAst[obj]["object"]["name"]== "env"){
	    					params.push(snippetAst[obj]["property"]["name"]);
	    					snippetAst[obj] = snippetAst[obj]["property"];
	    				}
	    				this.excludeEnv(snippetAst[obj],params);
	    			}

        	}
        },

        getSnippetAst: function(code){
            var fullAst;
            if(typeof(code) == "function"){
                code = "METHOD=" + code.toString();
                fullAst = this.getSanitizedAst(code, {}).body[0].expression.right;
            }
            else{
                fullAst = this.getSanitizedAst(Base.deepExtend({}, code), {});
            }
            return fullAst;
        },

        convertShaderToSnippedAst : function(code){
            var fullAst;
            if(typeof(code) == "function"){
                code = "METHOD=" + code.toString();
                fullAst = this.getSanitizedAst(code, {}).body[0].expression.right;
            }
            else{
                fullAst = this.getSanitizedAst(Base.deepExtend({}, code), {});
            }
            var duplicatedParams = [];
            this.excludeEnv(fullAst,duplicatedParams);

            //deleting the duplicated parameters
            var tmpParams={};
            for (var i = 0; i < duplicatedParams.length; i++) {
            	tmpParams[duplicatedParams[i]] = duplicatedParams[i];
            }
            params = [];
            for (var key in tmpParams) {
                params.push(key);
            }
            fullAst["params"]=[];
            for (i in params){
            	fullAst["params"].push({"name":params[i],"type":"Identifier"})
            }
            return fullAst;
        },

        compileJsProgram: function(snippetList, systemParams, defaultIteration){
            var result = SnippetConnector.connectSnippets(snippetList, {
                mode: defaultIteration ? SnippetConnector.MODE.JS_ITERATE : SnippetConnector.MODE.JS_NO_ITERATE});

            var aast = this.parseAndInferenceExpression(result.ast, {
                entry: "global.main",
                validate: true,
                inject: {
                    "this": systemParams,
                    "global.main": result.argTypes
                }
            });

            var compiled = new GLMatrixCompiler().compile(aast, {});
            return {
                code: compiled
            }
        },

        compileVertexShader: function(snippetList, systemParams){
            var result = SnippetConnector.connectSnippets(snippetList, { mode: SnippetConnector.MODE.GLSL_VS });

            var aast = this.parseAndInferenceExpression(result.ast, {
                entry: "global.main",
                validate: true,
                inject: {
                    "this": systemParams,
                    "global.main": result.argTypes
                }
            });

            var inputIndices = {};
            for(var inputName in result.inputIndices){
                inputIndices["_env_" + inputName] =  result.inputIndices[inputName];
            }

            var compiled = new GLSLCompiler().compileVertexShader(aast, {});
            return {
                code: compiled.source,
                inputIndices: inputIndices
            }
        },

        TYPES : interfaces.TYPES,
        OBJECT_KINDS : interfaces.OBJECT_KINDS,
        SOURCES: interfaces.SOURCES,
        SPACE_VECTOR_TYPES: SpaceVectorType,
        Vec2: interfaces.Vec2,
        Vec3: interfaces.Vec3,
        Vec4: interfaces.Vec4,
        Texture: interfaces.Texture,
        Color: interfaces.Color,
        Mat3: interfaces.Mat3,
        Mat4: interfaces.Mat4,
        WorkingSet: WorkingSet,
        SnippetList: SnippetList,
        SnippetEntry: SnippetEntry,
        Math: GlMatrix

});
    /**
     * Library version:
     */
    ns.version = '0.0.1';

}(exports));
<commit_msg>convertShaderToSnippedAst modified and works properly<commit_after><|endoftext|>


<commit_before>/**
 * myDoublerange
 *
 */
var INTEGER_MAX = 2147483647;

angular.module(PKG.name+'.directives').directive('myDoublerange',
function myDoublerangeDirective ($log) {
  return {
    restrict: 'E',
    templateUrl: 'doublerange/doublerange.html',
    replace: true,
    scope: {
      model: '=',
      inputMin: '=min',
      inputMax: '=max'
    },
    link: function(scope, element, attrs) {
      scope.model = scope.model || {};

      scope.html5 = attrs.html5 && attrs.html5!=='false';

      if(scope.html5) {

        // the almost-max value for the max slider in html5 mode
        scope.maxThreshold = parseInt(attrs.maxThreshold, 10) || 100;

        // the real max value
        function maxoutValue() {
          var max = parseInt(scope.inputMax, 10);
          return isNaN(max) ? INTEGER_MAX : max;
        }

        // the checkbox to go beyond the threshold
        scope.maxout = (maxoutValue() === scope.model.max) || null;

        scope.$watch('maxout', function (newVal) {
          if(newVal === null) {
            return;
          }
          if(newVal) { // checkbox checked
            scope.model.max = maxoutValue();
          }
          else { // checkbox unchecked
            scope.model.max = Math.max(
              Math.ceil(scope.maxThreshold/2),
              scope.model.min+1
            );
          }
        });

        scope.$watch('model.max', function (newVal, oldVal) {
          if(newVal < oldVal) {
            if(scope.maxout) {
              scope.maxout = false;
            }
          }
          else if(attrs.maxThreshold) {
            if(newVal >= scope.maxThreshold) {
              scope.maxout = true;
            }
          }
        });

      }

      scope.getConstraint = function (constraint, range) {
        var min = parseInt(scope.inputMin, 10),
            max = parseInt(scope.inputMax, 10);

        if(isNaN(min)) {
          min = 0;
        }
        if(isNaN(max)) {
          max = INTEGER_MAX;
        }

        if(range === 'min') {
          if(constraint === 'min') {
            return min;
          }
          else { // constraint === 'max'
            return Math.min(max, scope.model ? scope.model.max : max);
          }
        }
        else {  // range === 'max'
          if(constraint === 'min') {
            return Math.max(min, scope.model ? scope.model.min : min);
          }
          else { // constraint === 'max'
            if(!scope.html5 || !attrs.maxThreshold || scope.maxout) {
              return max;
            }
            else {
              return scope.maxThreshold;
            }
          }
        }
      };

    }

  };
});
<commit_msg>fix jshint<commit_after>/**
 * myDoublerange
 *
 */
var INTEGER_MAX = 2147483647;

angular.module(PKG.name+'.directives').directive('myDoublerange',
function myDoublerangeDirective ($log) {
  return {
    restrict: 'E',
    templateUrl: 'doublerange/doublerange.html',
    replace: true,
    scope: {
      model: '=',
      inputMin: '=min',
      inputMax: '=max'
    },
    link: function(scope, element, attrs) {
      scope.model = scope.model || {};

      scope.html5 = attrs.html5 && attrs.html5!=='false';

      // the almost-max value for the max slider in html5 mode
      scope.maxThreshold = parseInt(attrs.maxThreshold, 10) || 100;

      // the real max value
      function maxoutValue() {
        var max = parseInt(scope.inputMax, 10);
        return isNaN(max) ? INTEGER_MAX : max;
      }

      // the checkbox to go beyond the threshold
      scope.maxout = (maxoutValue() === scope.model.max) || null;

      if(scope.html5) {

        scope.$watch('maxout', function (newVal) {
          if(newVal === null) {
            return;
          }
          if(newVal) { // checkbox checked
            scope.model.max = maxoutValue();
          }
          else { // checkbox unchecked
            scope.model.max = Math.max(
              Math.ceil(scope.maxThreshold/2),
              scope.model.min+1
            );
          }
        });

        scope.$watch('model.max', function (newVal, oldVal) {
          if(newVal < oldVal) {
            if(scope.maxout) {
              scope.maxout = false;
            }
          }
          else if(attrs.maxThreshold) {
            if(newVal >= scope.maxThreshold) {
              scope.maxout = true;
            }
          }
        });

      }

      scope.getConstraint = function (constraint, range) {
        var min = parseInt(scope.inputMin, 10),
            max = parseInt(scope.inputMax, 10);

        if(isNaN(min)) {
          min = 0;
        }
        if(isNaN(max)) {
          max = INTEGER_MAX;
        }

        if(range === 'min') {
          if(constraint === 'min') {
            return min;
          }
          else { // constraint === 'max'
            return Math.min(max, scope.model ? scope.model.max : max);
          }
        }
        else {  // range === 'max'
          if(constraint === 'min') {
            return Math.max(min, scope.model ? scope.model.min : min);
          }
          else { // constraint === 'max'
            if(!scope.html5 || !attrs.maxThreshold || scope.maxout) {
              return max;
            }
            else {
              return scope.maxThreshold;
            }
          }
        }
      };

    }

  };
});
<|endoftext|>


<commit_before>'use strict';

var path    = require('path');
var assert  = require('yeoman-generator').assert;
var helpers = require('yeoman-generator').test;
var base    = require('yeoman-generator').generators.Base;
var sinon   = require('sinon');
var os      = require('os');

var stub;
var configFiles = [
    'config/.csslintrc',
    'config/.jscsrc',
    'config/.jscsrc-jsdoc',
    'config/.jshintrc',
    'config/default.js',
    'config/karma.conf.js',
    '.gitignore'
];
var projectFiles = [
    'package.json',
    'Gruntfile.js',
    'README.md',
    'LICENSE'
];
var files = [
    'tasks/main.js',
    'tasks/build.js',
    'tasks/test.js',
    'app/index.html',
    'app/app.js',
    'app/main.js',
    'app/config.js',
    'app/router.js',
    'assets/less/reset.less',
    'assets/less/style.less',
    'assets/images/logo.png',
    'app/modules/umd.boilerplate.js',
    'app/modules/webworker.boilerplate.js'
];
var dependencies = [
    '"jsinspect": ',
    'grunt-jsinspect',
    'grunt-buddyjs',
    'grunt-contrib-imagemin',
    'grunt-a11y',
    'grunt-accessibility',
    'grunt-karma-coveralls',
    'grunt-benchmark'
];

describe('app', function() {
    describe('when all options are true', function() {
        before(function(done) {
            stub = sinon.stub(base.prototype.user.git, 'name');
            stub.returns(null);
            helpers.run(path.join(__dirname, '../generators/app'))
                .withOptions({skipInstall: true})
                .withPrompts({
                    appDir: './',
                    autoFix: true,
                    useJsinspect: true,
                    useBuddyjs: true,
                    useA11y: true,
                    compressImages: true,
                    benchmarks: true,
                    useCoveralls: true
                })
                .on('end', done);
        });
        after(function() {
            stub.restore();
        });
        it('creates files', function() {
            assert.file(configFiles);
            assert.file(projectFiles);
            assert.file(files);
            assert.file('test/benchmarks/example.benchmark.js');
        });
        it('configures files', function() {
            assert.fileContent('.gitignore', 'app/templates.js');
            assert.fileContent('.gitignore', 'app/styles.css');
        });
        dependencies.forEach(function(dep) {
            it('adds ' + dep + ' to package.json', function() {
                assert.fileContent('package.json', dep);
            });
        });
        it('customizes work-flow tasks', function() {
            assert.fileContent('Gruntfile.js', 'fix: true');
            assert.fileContent('Gruntfile.js', 'jsinspect: {');
            assert.fileContent('Gruntfile.js', 'buddyjs: {');
            assert.fileContent('Gruntfile.js', 'imagemin: {');
            assert.fileContent('Gruntfile.js', 'a11y: {');
            assert.fileContent('Gruntfile.js', 'accessibility: {');
            assert.fileContent('Gruntfile.js', 'benchmark: {');
            assert.fileContent('Gruntfile.js', 'coveralls: {');
        });
    });
    describe('when all options are false', function() {
        before(function(done) {
            helpers.run(path.join(__dirname, '../generators/app'))
                .withOptions({skipInstall: true})
                .withPrompts({
                    appDir: './',
                    autoFix: false,
                    useJsinspect: false,
                    useBuddyjs: false,
                    useA11y: false,
                    compressImages: false,
                    benchmarks: false,
                    useCoveralls: false
                })
                .on('end', done);
        });

        it('creates files', function() {
            assert.file(configFiles);
            assert.file(projectFiles);
            assert.file(files);
            assert.noFile('test/benchmarks/example.benchmark.js');
        });
        it('configures files', function() {
            assert.fileContent('.gitignore', 'app/templates.js');
            assert.fileContent('.gitignore', 'app/styles.css');
        });
        dependencies.forEach(function(dep) {
            it('DOES NOT add ' + dep + ' to package.json', function() {
                assert.noFileContent('package.json', dep);
            });
        });
        it('customizes work-flow tasks', function() {
            assert.fileContent('Gruntfile.js', 'fix: false');
            assert.noFileContent('Gruntfile.js', 'jsinspect: {');
            assert.noFileContent('Gruntfile.js', 'buddyjs: {');
            assert.noFileContent('Gruntfile.js', 'imagemin: {');
            assert.noFileContent('Gruntfile.js', 'a11y: {');
            assert.noFileContent('Gruntfile.js', 'accessibility: {');
            assert.noFileContent('Gruntfile.js', 'benchmark: {');
            assert.noFileContent('Gruntfile.js', 'coveralls: {');
        });
    });
    describe('when the application directory is changed', function() {
        var appDirectory;
        before(function(done) {
            appDirectory = 'webapp';
            helpers.run(path.join(__dirname, '../generators/app'))
                .withOptions({skipInstall: true})
                .withPrompts({
                    appDir: appDirectory,
                    autoFix: false,
                    useJsinspect: false,
                    useBuddyjs: false,
                    useA11y: false,
                    compressImages: false,
                    benchmarks: false,
                    useCoveralls: false
                })
                .on('end', done);
        });
        it('creates files', function() {
            assert.file(configFiles);
            assert.file(projectFiles);
            assert.file(files.map(function(file) {
                return appDirectory + '/' + file;
            }));
            assert.noFile('test/benchmarks/example.benchmark.js');
        });
        it('configures files', function() {
            assert.fileContent('.gitignore', appDirectory + '/app/templates.js');
            assert.fileContent('.gitignore', appDirectory + '/app/styles.css');
        });
        dependencies.forEach(function(dep) {
            it('DOES NOT add ' + dep + ' to package.json', function() {
                assert.noFileContent('package.json', dep);
            });
        });
        it('customizes work-flow tasks', function() {
            assert.fileContent('Gruntfile.js', 'fix: false');
            assert.noFileContent('Gruntfile.js', 'jsinspect: {');
            assert.noFileContent('Gruntfile.js', 'buddyjs: {');
            assert.noFileContent('Gruntfile.js', 'imagemin: {');
            assert.noFileContent('Gruntfile.js', 'a11y: {');
            assert.noFileContent('Gruntfile.js', 'accessibility: {');
            assert.noFileContent('Gruntfile.js', 'benchmark: {');
            assert.noFileContent('Gruntfile.js', 'coveralls: {');
        });
    });
});
<commit_msg>Fixed failing test<commit_after>'use strict';

var path    = require('path');
var assert  = require('yeoman-generator').assert;
var helpers = require('yeoman-generator').test;
var base    = require('yeoman-generator').generators.Base;
var sinon   = require('sinon');
var os      = require('os');

var stub;
var configFiles = [
    'config/.csslintrc',
    'config/.jscsrc',
    'config/.jscsrc-jsdoc',
    'config/.jshintrc',
    'config/default.js',
    'config/karma.conf.js',
    '.gitignore'
];
var projectFiles = [
    'package.json',
    'Gruntfile.js',
    'README.md',
    'LICENSE'
];
var files = [
    'tasks/main.js',
    'tasks/build.js',
    'tasks/test.js',
    'app/index.html',
    'app/app.js',
    'app/main.js',
    'app/config.js',
    'app/router.js',
    'assets/less/reset.less',
    'assets/less/style.less',
    'assets/images/logo.png',
    'app/modules/umd.boilerplate.js',
    'app/modules/webworker.boilerplate.js'
];
var dependencies = [
    '"jsinspect": ',
    'grunt-jsinspect',
    'grunt-buddyjs',
    'grunt-contrib-imagemin',
    'grunt-a11y',
    'grunt-accessibility',
    'grunt-karma-coveralls',
    'grunt-benchmark'
];

describe('app', function() {
    describe('when all options are true', function() {
        before(function(done) {
            stub = sinon.stub(base.prototype.user.git, 'name');
            stub.returns(null);
            helpers.run(path.join(__dirname, '../generators/app'))
                .withOptions({skipInstall: true})
                .withPrompts({
                    appDir: './',
                    autoFix: true,
                    useJsinspect: true,
                    useBuddyjs: true,
                    useA11y: true,
                    compressImages: true,
                    benchmarks: true,
                    useCoveralls: true
                })
                .on('end', done);
        });
        after(function() {
            stub.restore();
        });
        it('creates files', function() {
            assert.file(configFiles);
            assert.file(projectFiles);
            assert.file(files);
            assert.file('test/benchmarks/example.benchmark.js');
        });
        it('configures files', function() {
            assert.fileContent('.gitignore', 'app/templates.js');
            assert.fileContent('.gitignore', 'app/style.css');
        });
        dependencies.forEach(function(dep) {
            it('adds ' + dep + ' to package.json', function() {
                assert.fileContent('package.json', dep);
            });
        });
        it('customizes work-flow tasks', function() {
            assert.fileContent('Gruntfile.js', 'fix: true');
            assert.fileContent('Gruntfile.js', 'jsinspect: {');
            assert.fileContent('Gruntfile.js', 'buddyjs: {');
            assert.fileContent('Gruntfile.js', 'imagemin: {');
            assert.fileContent('Gruntfile.js', 'a11y: {');
            assert.fileContent('Gruntfile.js', 'accessibility: {');
            assert.fileContent('Gruntfile.js', 'benchmark: {');
            assert.fileContent('Gruntfile.js', 'coveralls: {');
        });
    });
    describe('when all options are false', function() {
        before(function(done) {
            helpers.run(path.join(__dirname, '../generators/app'))
                .withOptions({skipInstall: true})
                .withPrompts({
                    appDir: './',
                    autoFix: false,
                    useJsinspect: false,
                    useBuddyjs: false,
                    useA11y: false,
                    compressImages: false,
                    benchmarks: false,
                    useCoveralls: false
                })
                .on('end', done);
        });

        it('creates files', function() {
            assert.file(configFiles);
            assert.file(projectFiles);
            assert.file(files);
            assert.noFile('test/benchmarks/example.benchmark.js');
        });
        it('configures files', function() {
            assert.fileContent('.gitignore', 'app/templates.js');
            assert.fileContent('.gitignore', 'app/style.css');
        });
        dependencies.forEach(function(dep) {
            it('DOES NOT add ' + dep + ' to package.json', function() {
                assert.noFileContent('package.json', dep);
            });
        });
        it('customizes work-flow tasks', function() {
            assert.fileContent('Gruntfile.js', 'fix: false');
            assert.noFileContent('Gruntfile.js', 'jsinspect: {');
            assert.noFileContent('Gruntfile.js', 'buddyjs: {');
            assert.noFileContent('Gruntfile.js', 'imagemin: {');
            assert.noFileContent('Gruntfile.js', 'a11y: {');
            assert.noFileContent('Gruntfile.js', 'accessibility: {');
            assert.noFileContent('Gruntfile.js', 'benchmark: {');
            assert.noFileContent('Gruntfile.js', 'coveralls: {');
        });
    });
    describe('when the application directory is changed', function() {
        var appDirectory;
        before(function(done) {
            appDirectory = 'webapp';
            helpers.run(path.join(__dirname, '../generators/app'))
                .withOptions({skipInstall: true})
                .withPrompts({
                    appDir: appDirectory,
                    autoFix: false,
                    useJsinspect: false,
                    useBuddyjs: false,
                    useA11y: false,
                    compressImages: false,
                    benchmarks: false,
                    useCoveralls: false
                })
                .on('end', done);
        });
        it('creates files', function() {
            assert.file(configFiles);
            assert.file(projectFiles);
            assert.file(files.map(function(file) {
                return appDirectory + '/' + file;
            }));
            assert.noFile('test/benchmarks/example.benchmark.js');
        });
        it('configures files', function() {
            assert.fileContent('.gitignore', appDirectory + '/app/templates.js');
            assert.fileContent('.gitignore', appDirectory + '/app/style.css');
        });
        dependencies.forEach(function(dep) {
            it('DOES NOT add ' + dep + ' to package.json', function() {
                assert.noFileContent('package.json', dep);
            });
        });
        it('customizes work-flow tasks', function() {
            assert.fileContent('Gruntfile.js', 'fix: false');
            assert.noFileContent('Gruntfile.js', 'jsinspect: {');
            assert.noFileContent('Gruntfile.js', 'buddyjs: {');
            assert.noFileContent('Gruntfile.js', 'imagemin: {');
            assert.noFileContent('Gruntfile.js', 'a11y: {');
            assert.noFileContent('Gruntfile.js', 'accessibility: {');
            assert.noFileContent('Gruntfile.js', 'benchmark: {');
            assert.noFileContent('Gruntfile.js', 'coveralls: {');
        });
    });
});
<|endoftext|>


<commit_before>
var fs = require("fs");
var assert = require("assert");
var dsx = require ("../damn-simple-xml");

describe("DamnSimpleXml.deserialize()", function() {

    describe("simple.xml", function() {
        var expected = {
            id          : "jpg",
            firstName   : "Jean-Philippe",
            lastName    : "Gravel",
            email       : "jeanphilippe.gravel@gmail.com"
        };

        it("should be equal to the expected object", function(done) {
            fs.readFile("test/simple.xml", {encoding: "utf8"},
            function(err, data) {
                if (err) return done(err);
                dsx.deserialize(data, function(pair) {
                    assert.deepEqual(pair.data, expected);
                    done();
                });
            });
        });
    });

    describe("attr-types.xml", function() {

        var expected = {
            numeric: 10
        }

        describe(".number", function() {
            it("should be a number equal to 10", function(done) {
                fs.readFile("test/attr-types.xml", { encoding: "utf8" },
                function(err, data) {
                    if (err) done(err);
                    dsx.deserialize(data, function(pair) {
                        assert.strictEqual(pair.data.numeric, 10);
                        done();
                    });
                });
            });
        });

        describe(".boolTrue", function() {
            it("should be a boolean equal to true", function(done) {
                fs.readFile("test/attr-types.xml", { encoding: "utf8" },
                function(err, data) {
                    if (err) done(err);
                    dsx.deserialize(data, function(pair) {
                        assert.strictEqual(pair.data.boolTrue, true);
                        done();
                    });
                });
            });
        });

        describe(".boolFalse", function() {
            it("should be a boolean equal to false", function(done) {
                fs.readFile("test/attr-types.xml", { encoding: "utf8" },
                function(err, data) {
                    if (err) done(err);
                    dsx.deserialize(data, function(pair) {
                        assert.strictEqual(pair.data.boolFalse, false);
                        done();
                    });
                });
            });
        });

        describe(".date", function() {
            it("should be a date equal to 2014-08-31T13:00:00.000Z",
            function(done) {
                fs.readFile("test/attr-types.xml", {
                    encoding: "utf8"
                }, function(err, data) {
                    if (err) done(err);
                    dsx.deserialize(data, function(pair) {
                        var expected = new Date("2014-08-31T13:00:00.000Z");
                        assert.strictEqual(
                            pair.data.date.toISOString(),
                            expected.toISOString());
                        done();
                    });
                });
            });
        });

    });

    describe("typed-nodes.xml", function() {
        var data = fs.readFileSync("test/typed-nodes.xml", {
            encoding: "utf8"
        });
        var expected = {
            string: "This is a string",
            number: 125.3,
            bool: false,
            date1: new Date("2014-08-31T00:00:00.000Z"),
            date2: new Date("2014-08-31T22:38"),
            date3: new Date("2014-08-31T22:38:45"),
            date4: new Date("2014-08-31T22:38:45.123Z")
        }
        it("should correspond to expected types", function(done) {
            dsx.deserialize(data, function(pair) {
                assert.deepEqual(pair.data, expected);
                done();
            });
        });
    });

    describe("array.xml", function() {
        var data = fs.readFileSync("test/array.xml", {
            encoding: "utf8"
        });

        it("should be an array containing two items", function(done) {
            dsx.deserialize(data, function(pair) {
                assert.equal(pair.data.length, 2);
                done();
            });
        });

        it("should contains an employee with only one language as an " +
                "object.", function(done) {
            dsx.deserialize(data, function(pair) {
                assert.ok(pair.data[0].languages["language"]);
                done();
            });
        });

        it("should contains an employee with only one language as an " +
                "array", function(done) {
            dsx.deserialize({
                xml: data,
                arrayNames: ["languages"]
            }, function(pair) {
                assert.ok(pair.data[0].languages.length == 1);
                done();
            });
        });

        it("should contains an employee with many languages as an " +
                "array.", function(done) {
            dsx.deserialize(data, function(pair) {
                assert.ok(pair.data[1].languages.length > 0);
                done();
            });
        });

    });

    describe("cdata.xml", function() {

        var data = fs.readFileSync("test/cdata.xml", {
            encoding: "utf8"
        });

        it("should contain a string with invalid xml " +
                "characters", function(done) {
            dsx.deserialize(data, function(pair) {
                assert.equal(pair.data,
                        "This is an <unparsed /> cdata block.");
                done();
            });
        });

    });

    describe("mixed-attribute-text.xml"), function() {
        var expected = {
            root: "employee",
            data: {
                name: "John Doe",
                emails: [{
                    type: "home",
                    _text: "jdoe@home.com"
                }, {
                    type: "work",
                    _text: "john.doe@work.com"
                }]
            }
        };

    });

});

<commit_msg>Modified some tests<commit_after>
var fs = require("fs");
var assert = require("assert");
var dsx = require ("../damn-simple-xml");

describe("DamnSimpleXml.deserialize()", function() {

    describe("simple.xml", function() {
        var expected = {
            id          : "jpg",
            firstName   : "Jean-Philippe",
            lastName    : "Gravel",
            email       : "jeanphilippe.gravel@gmail.com"
        };

        it("should be equal to the expected object", function(done) {
            fs.readFile("test/simple.xml", {encoding: "utf8"},
            function(err, data) {
                if (err) return done(err);
                dsx.deserialize(data, function(pair) {
                    assert.deepEqual(pair.data, expected);
                    done();
                });
            });
        });
    });

    describe("attr-types.xml", function() {

        var expected = {
            numeric: 10
        }

        describe(".number", function() {
            it("should be a number equal to 10", function(done) {
                fs.readFile("test/attr-types.xml", { encoding: "utf8" },
                function(err, data) {
                    if (err) done(err);
                    dsx.deserialize(data, function(pair) {
                        assert.strictEqual(pair.data.numeric, 10);
                        done();
                    });
                });
            });
        });

        describe(".boolTrue", function() {
            it("should be a boolean equal to true", function(done) {
                fs.readFile("test/attr-types.xml", { encoding: "utf8" },
                function(err, data) {
                    if (err) done(err);
                    dsx.deserialize(data, function(pair) {
                        assert.strictEqual(pair.data.boolTrue, true);
                        done();
                    });
                });
            });
        });

        describe(".boolFalse", function() {
            it("should be a boolean equal to false", function(done) {
                fs.readFile("test/attr-types.xml", { encoding: "utf8" },
                function(err, data) {
                    if (err) done(err);
                    dsx.deserialize(data, function(pair) {
                        assert.strictEqual(pair.data.boolFalse, false);
                        done();
                    });
                });
            });
        });

        describe(".date", function() {
            it("should be a date equal to 2014-08-31T13:00:00.000Z",
            function(done) {
                fs.readFile("test/attr-types.xml", {
                    encoding: "utf8"
                }, function(err, data) {
                    if (err) done(err);
                    dsx.deserialize(data, function(pair) {
                        var expected = new Date("2014-08-31T13:00:00.000Z");
                        assert.strictEqual(
                            pair.data.date.toISOString(),
                            expected.toISOString());
                        done();
                    });
                });
            });
        });

    });

    describe("typed-nodes.xml", function() {
        var data = fs.readFileSync("test/typed-nodes.xml", {
            encoding: "utf8"
        });
        var expected = {
            string: "This is a string",
            number: 125.3,
            bool: false,
            date1: new Date("2014-08-31T00:00:00.000Z"),
            date2: new Date("2014-08-31T22:38"),
            date3: new Date("2014-08-31T22:38:45"),
            date4: new Date("2014-08-31T22:38:45.123Z")
        }
        it("should correspond to expected types", function(done) {
            dsx.deserialize(data, function(pair) {
                assert.deepEqual(pair.data, expected);
                done();
            });
        });
    });

    describe("array.xml", function() {
        var data = fs.readFileSync("test/array.xml", {
            encoding: "utf8"
        });

        it("should be an array containing two items", function(done) {
            dsx.deserialize(data, function(pair) {
                assert.equal(pair.data.length, 2);
                done();
            });
        });

        it("should contains an employee with only one language as an " +
                "object.", function(done) {
            dsx.deserialize(data, function(pair) {
                assert.ok(pair.data[0].languages["language"]);
                done();
            });
        });

        it("should contains an employee with only one language as an " +
                "array", function(done) {
            dsx.deserialize({
                xml: data,
                arrayNames: ["languages"]
            }, function(pair) {
                assert.ok(pair.data[0].languages.length == 1);
                done();
            });
        });

        it("should contains an employee with many languages as an " +
                "array.", function(done) {
            dsx.deserialize(data, function(pair) {
                assert.ok(pair.data[1].languages.length > 0);
                done();
            });
        });

    });

    describe("cdata.xml", function() {

        var data = fs.readFileSync("test/cdata.xml", {
            encoding: "utf8"
        });

        it("should contain a string with invalid xml " +
                "characters", function(done) {
            dsx.deserialize(data, function(pair) {
                assert.equal(pair.data,
                        "This is an <unparsed /> cdata block.");
                done();
            });
        });

    });

    describe("mixed-attribute-text.xml", function() {
        var expected = {
            root: "employee",
            data: {
                name: "John Doe",
                emails: [{
                    type: "home",
                    _text: "jdoe@home.com"
                }, {
                    type: "work",
                    _text: "john.doe@work.com"
                }]
            }
        };

        it("should correspond to the expected object", function(done) {
            var data = fs.readFileSync("test/mixed-attribute-text.xml", {
                encoding: "utf8"
            });
            dsx.deserialize(data, function(pair) {
                assert.deepEqual(pair, expected);
                done();
            });
        });

    });

});

<|endoftext|>


<commit_before>var cdb = require('cartodb.js');
var MapCardPreview = require('../mapcard_preview');
var ScrollableHeader = require('../scrollable_header');
var VisualizationDropdown = require('./dropdown');
var Visualizations = require('./feed_collection');

var Feed = require('../feed/view');

module.exports = Feed.extend({
  tagName: 'div',

  _LIMIT: 4,

  _SMALL_WIDTH: 544,
  _MEDIUM_WIDTH: 900,

  _CARD_HEIGHT: 220,
  _LOADER_TITLE: 'Exploring',

  _DROPDOWN_TEXT: {
    null: 'Maps and datasets',
    'table': 'Datasets',
    'derived': 'Maps'
  },

  events: {
    'click .js-more': '_onClickMore',
    'click .js-likes': '_onClickLikes',
    'click .js-updated_at': '_onClickUpdatedAt',
    'click .js-mapviews': '_onClickMapViews',
    'click .js-maps-datasets': '_onClickMapsAndDatasets',
    'click .js-maps': '_onClickMaps',
    'click .js-datasets': '_onClickDatasets'
  },

  initialize: function() {
    _.bindAll(this, '_initLike', '_onWindowResize', '_renderStaticMaps');

    this._initTemplates();
    this._initModels();
    this._initBindings();
    this._fetchItems();
  },

  render: function() {
    this.$el.html(this.template());
    this._renderLoader();

    this._setupVisualizationDropdown();
    this._setupScrollableHeader();

    return this;
  },

  _setupScrollableHeader: function() {
    this.scrollableHeader = new ScrollableHeader({
      el: $('.Filters-explore'),
      anchorPoint: $('.Header').height() + $('.FavMap').height()
    });
  },

  _setupVisualizationDropdown: function() {
    this.visualizationDropdown = new VisualizationDropdown({
      target: this.$('.js-dropdown'),
      horizontal_position: 'horizontal_left',
      horizontal_offset: -110,
      tick: 'center',
      model: this.model,
      position: 'offset',
      vertical_offset: 0
    });

    this.addView(this.visualizationDropdown);
    cdb.god.bind('closeDialogs', this.visualizationDropdown.hide, this.visualizationDropdown);
    this.add_related_model(cdb.god);
    $('body').append(this.visualizationDropdown.render().el);
  },

  _onWindowResize: function() {
    var width = $(window).width();

    if (width <= this._SMALL_WIDTH) {
      this.model.set('size', 'small');
    } else if (width <= this._MEDIUM_WIDTH) {
      this.model.set('size', 'medium');
    } else {
      this.model.set('size', 'big');
    }

    this._renderStaticMaps();
  },

  _initTemplates: function() {
    this.template = cdb.templates.getTemplate('common/views/explore/template');
    this.mapTemplate = cdb.templates.getTemplate('common/views/explore/map_item_template');
    this.datasetTemplate = cdb.templates.getTemplate('common/views/explore/dataset_item_template');
    this.loaderTemplatePath = 'common/views/explore/loading';
  },

  _initModels: function() {
    var size = 'big';
    var wWidth = $(window).width();

    if (wWidth <= this._SMALL_WIDTH) {
      size = 'small';
    } else if (wWidth <= this._MEDIUM_WIDTH) {
      size = 'medium';
    }

    this.model = new cdb.Backbone.Model({
      rendered_big: false,
      rendered_medium: false,
      rendered_small: false,
      type: '',
      size: size,
      page: 0,
      order_by: 'likes'
    });

    this.collection = new Visualizations();
    this.collection.bind('reset', this._renderVisualizations, this);
    this._likeModels = new Backbone.Collection();
  },

  _initBindings: function() {
    var self = this;

    this.model.bind('change:show_more', this._onChangeShowMore, this);
    this.model.bind('change:show_loader', this._onChangeShowLoader, this);
    this.model.bind('change:show_filters', this._onChangeShowFilters, this);
    this.model.bind('change:show_mast', this._onChangeShowMast, this);
    this.model.bind('change:order_by', this._onChangeOrderBy, this);
    this.model.bind('change:type', this._onChangeType, this);

    this.options.authenticatedUser.bind('change', function() {
      self._onAuthenticatedUserChange();
      self._initLikes();
    }, this);

    $(window).bind('resize', this._onWindowResize);
  },

  _getGeometryType: function(geomTypes) {
    if (geomTypes && geomTypes.length > 0) {
      var types = ['point', 'polygon', 'line', 'raster'];
      var geomType = geomTypes[0];

      return _.find(types, function(type) {
        return geomType.toLowerCase().indexOf(type) !== -1;
      });

    } else {
      return null;
    }
  },

  _getDatasetSize: function(item) {
    var size = item.get('table_size');
    return size ? cdb.Utils.readablizeBytes(size, true).split(' ') : 0;
  },

  _renderVisualizations: function() {

    this.model.set({ show_loader: false, show_more: true, show_filters: true, show_mast: true });

    this.collection.each(function(item) {
      var template = item.get('type') === 'derived' ? this.mapTemplate : this.datasetTemplate;

      var el = template({
        vis: item.attributes,
        datasetSize: this._getDatasetSize(item),
        geomType: this._getGeometryType(item.get('geom_types')),
        account_host: 'cartodb.com' //, config.account_host
      });

      this.$('.js-items').append(el);

      var $item = this.$('.js-items').find('[data-vis-id="' + item.get('id') + '"]');

      if (item.get('type') === 'derived' && !item.get('rendered_' + this.model.get('size'))) {
        this._renderStaticMap(item, $item);
      }

    }, this);

    this._initLikes();
  },

  _renderStaticMap: function(vis, $el) {

    var visId = vis.get('id');
    var username = vis.get('username');

    var width = 860;

    if (this.model.get('size') === 'small') {
      width = 288;
    } else if (this.model.get('size') === 'medium') {
      width = 540;
    }

    var className = 'is-' + this.model.get('size');

    if (visId && username) {

      vis.set('rendered_' + this.model.get('size'), true);

      new MapCardPreview({
        el: $el.find('.js-header'),
        width: width,
        height: this._CARD_HEIGHT,
        username: username,
        visId: visId,
        className: className,
        account_host: 'cartodb.com'
      }).load();
    }
  },

  _getLikesEndpoint: function(vis) {
    var username = this.options.authenticatedUser.get('username');
    return '/user/' + username + '/u/' + vis.get('username') + '/api/v1/viz/' + vis.get('id') + '/like';
  },

  _selectType: function(what) {
    var self = this;

    this.model.set({ show_more: false });

    $('body').animate({ scrollTop: 150 }, { duration: 250, complete: function() {
      self.model.set({ type: what });
    }});
  },

  _sort: function(method) {
    var self = this;

    this.model.set({ show_more: false });

    $('body').animate({ scrollTop: 150 }, { duration: 250, complete: function() {
      self.model.set({ order_by: method });
    }});
  },

  _fetchItems: function(params, reset) {

    if (reset) {
      this.model.set({ page: 0, show_more: false, show_loader: true, show_mast: false });
      this.$('.js-items').empty();
    }

    var type = this.model.get('type');
    var orderBy = this.model.get('order_by');
    var page = this.model.get('page');
    var limit = this._LIMIT;

    this.collection.fetch({
      data: _.extend({ q: this.collection.generateQuery(type, orderBy, page, limit) }, params),
      reset: reset
    });
  },

  _onClickMore: function(e) {
    this.killEvent(e);
    this.model.set({ page: this.model.get('page') + 1, show_loader: true, show_more: false });
    this._fetchItems({}, false);
  },

  _onChangeType: function() {
    this.$('.js-dropdownLabel').text(this._DROPDOWN_TEXT[this.model.get('type')]);
    this._fetchItems({}, true);
  },

  _onChangeOrderBy: function() {
    $('.js-order-link').removeClass('is-selected');
    $('.js-' + this.model.get('order_by')).addClass('is-selected');
    this._fetchItems({}, true);
  },

  _onChangeShowFilters: function() {
    if (this.model.get('show_filters')) {
      this.$('.js-filters').removeClass('is-hidden');
    } else {
      this.$('.js-filters').addClass('is-hidden');
    }
  },

  _onClickLikes: function(e) {
    this.killEvent(e);
    this._sort('likes');
  },

  _onClickUpdatedAt: function(e) {
    this.killEvent(e);
    this._sort('updated_at');
  },

  _onClickMapViews: function(e) {
    this.killEvent(e);
    this._sort('mapviews');
  },

  _onClickMapsAndDatasets: function(e) {
    this.killEvent(e);
    this._selectType(null);
  },

  _onClickMaps: function(e) {
    this.killEvent(e);
    this._selectType('derived');
  },

  _onClickDatasets: function(e) {
    this.killEvent(e);
    this._selectType('table');
  }
});
<commit_msg>Increases the limit to 8 elements<commit_after>var cdb = require('cartodb.js');
var MapCardPreview = require('../mapcard_preview');
var ScrollableHeader = require('../scrollable_header');
var VisualizationDropdown = require('./dropdown');
var Visualizations = require('./feed_collection');

var Feed = require('../feed/view');

module.exports = Feed.extend({
  tagName: 'div',

  _LIMIT: 8,

  _SMALL_WIDTH: 544,
  _MEDIUM_WIDTH: 900,

  _CARD_HEIGHT: 220,
  _LOADER_TITLE: 'Exploring',

  _DROPDOWN_TEXT: {
    null: 'Maps and datasets',
    'table': 'Datasets',
    'derived': 'Maps'
  },

  events: {
    'click .js-more': '_onClickMore',
    'click .js-likes': '_onClickLikes',
    'click .js-updated_at': '_onClickUpdatedAt',
    'click .js-mapviews': '_onClickMapViews',
    'click .js-maps-datasets': '_onClickMapsAndDatasets',
    'click .js-maps': '_onClickMaps',
    'click .js-datasets': '_onClickDatasets'
  },

  initialize: function() {
    _.bindAll(this, '_initLike', '_onWindowResize', '_renderStaticMaps');

    this._initTemplates();
    this._initModels();
    this._initBindings();
    this._fetchItems();
  },

  render: function() {
    this.$el.html(this.template());
    this._renderLoader();

    this._setupVisualizationDropdown();
    this._setupScrollableHeader();

    return this;
  },

  _setupScrollableHeader: function() {
    this.scrollableHeader = new ScrollableHeader({
      el: $('.Filters-explore'),
      anchorPoint: $('.Header').height() + $('.FavMap').height()
    });
  },

  _setupVisualizationDropdown: function() {
    this.visualizationDropdown = new VisualizationDropdown({
      target: this.$('.js-dropdown'),
      horizontal_position: 'horizontal_left',
      horizontal_offset: -110,
      tick: 'center',
      model: this.model,
      position: 'offset',
      vertical_offset: 0
    });

    this.addView(this.visualizationDropdown);
    cdb.god.bind('closeDialogs', this.visualizationDropdown.hide, this.visualizationDropdown);
    this.add_related_model(cdb.god);
    $('body').append(this.visualizationDropdown.render().el);
  },

  _onWindowResize: function() {
    var width = $(window).width();

    if (width <= this._SMALL_WIDTH) {
      this.model.set('size', 'small');
    } else if (width <= this._MEDIUM_WIDTH) {
      this.model.set('size', 'medium');
    } else {
      this.model.set('size', 'big');
    }

    this._renderStaticMaps();
  },

  _initTemplates: function() {
    this.template = cdb.templates.getTemplate('common/views/explore/template');
    this.mapTemplate = cdb.templates.getTemplate('common/views/explore/map_item_template');
    this.datasetTemplate = cdb.templates.getTemplate('common/views/explore/dataset_item_template');
    this.loaderTemplatePath = 'common/views/explore/loading';
  },

  _initModels: function() {
    var size = 'big';
    var wWidth = $(window).width();

    if (wWidth <= this._SMALL_WIDTH) {
      size = 'small';
    } else if (wWidth <= this._MEDIUM_WIDTH) {
      size = 'medium';
    }

    this.model = new cdb.Backbone.Model({
      rendered_big: false,
      rendered_medium: false,
      rendered_small: false,
      type: '',
      size: size,
      page: 0,
      order_by: 'likes'
    });

    this.collection = new Visualizations();
    this.collection.bind('reset', this._renderVisualizations, this);
    this._likeModels = new Backbone.Collection();
  },

  _initBindings: function() {
    var self = this;

    this.model.bind('change:show_more', this._onChangeShowMore, this);
    this.model.bind('change:show_loader', this._onChangeShowLoader, this);
    this.model.bind('change:show_filters', this._onChangeShowFilters, this);
    this.model.bind('change:show_mast', this._onChangeShowMast, this);
    this.model.bind('change:order_by', this._onChangeOrderBy, this);
    this.model.bind('change:type', this._onChangeType, this);

    this.options.authenticatedUser.bind('change', function() {
      self._onAuthenticatedUserChange();
      self._initLikes();
    }, this);

    $(window).bind('resize', this._onWindowResize);
  },

  _getGeometryType: function(geomTypes) {
    if (geomTypes && geomTypes.length > 0) {
      var types = ['point', 'polygon', 'line', 'raster'];
      var geomType = geomTypes[0];

      return _.find(types, function(type) {
        return geomType.toLowerCase().indexOf(type) !== -1;
      });

    } else {
      return null;
    }
  },

  _getDatasetSize: function(item) {
    var size = item.get('table_size');
    return size ? cdb.Utils.readablizeBytes(size, true).split(' ') : 0;
  },

  _renderVisualizations: function() {

    this.model.set({ show_loader: false, show_more: true, show_filters: true, show_mast: true });

    this.collection.each(function(item) {
      var template = item.get('type') === 'derived' ? this.mapTemplate : this.datasetTemplate;

      var el = template({
        vis: item.attributes,
        datasetSize: this._getDatasetSize(item),
        geomType: this._getGeometryType(item.get('geom_types')),
        account_host: 'cartodb.com' //, config.account_host
      });

      this.$('.js-items').append(el);

      var $item = this.$('.js-items').find('[data-vis-id="' + item.get('id') + '"]');

      if (item.get('type') === 'derived' && !item.get('rendered_' + this.model.get('size'))) {
        this._renderStaticMap(item, $item);
      }

    }, this);

    this._initLikes();
  },

  _renderStaticMap: function(vis, $el) {

    var visId = vis.get('id');
    var username = vis.get('username');

    var width = 860;

    if (this.model.get('size') === 'small') {
      width = 288;
    } else if (this.model.get('size') === 'medium') {
      width = 540;
    }

    var className = 'is-' + this.model.get('size');

    if (visId && username) {

      vis.set('rendered_' + this.model.get('size'), true);

      new MapCardPreview({
        el: $el.find('.js-header'),
        width: width,
        height: this._CARD_HEIGHT,
        username: username,
        visId: visId,
        className: className,
        account_host: 'cartodb.com'
      }).load();
    }
  },

  _getLikesEndpoint: function(vis) {
    var username = this.options.authenticatedUser.get('username');
    return '/user/' + username + '/u/' + vis.get('username') + '/api/v1/viz/' + vis.get('id') + '/like';
  },

  _selectType: function(what) {
    var self = this;

    this.model.set({ show_more: false });

    $('body').animate({ scrollTop: 150 }, { duration: 250, complete: function() {
      self.model.set({ type: what });
    }});
  },

  _sort: function(method) {
    var self = this;

    this.model.set({ show_more: false });

    $('body').animate({ scrollTop: 150 }, { duration: 250, complete: function() {
      self.model.set({ order_by: method });
    }});
  },

  _fetchItems: function(params, reset) {

    if (reset) {
      this.model.set({ page: 0, show_more: false, show_loader: true, show_mast: false });
      this.$('.js-items').empty();
    }

    var type = this.model.get('type');
    var orderBy = this.model.get('order_by');
    var page = this.model.get('page');
    var limit = this._LIMIT;

    this.collection.fetch({
      data: _.extend({ q: this.collection.generateQuery(type, orderBy, page, limit) }, params),
      reset: reset
    });
  },

  _onClickMore: function(e) {
    this.killEvent(e);
    this.model.set({ page: this.model.get('page') + 1, show_loader: true, show_more: false });
    this._fetchItems({}, false);
  },

  _onChangeType: function() {
    this.$('.js-dropdownLabel').text(this._DROPDOWN_TEXT[this.model.get('type')]);
    this._fetchItems({}, true);
  },

  _onChangeOrderBy: function() {
    $('.js-order-link').removeClass('is-selected');
    $('.js-' + this.model.get('order_by')).addClass('is-selected');
    this._fetchItems({}, true);
  },

  _onChangeShowFilters: function() {
    if (this.model.get('show_filters')) {
      this.$('.js-filters').removeClass('is-hidden');
    } else {
      this.$('.js-filters').addClass('is-hidden');
    }
  },

  _onClickLikes: function(e) {
    this.killEvent(e);
    this._sort('likes');
  },

  _onClickUpdatedAt: function(e) {
    this.killEvent(e);
    this._sort('updated_at');
  },

  _onClickMapViews: function(e) {
    this.killEvent(e);
    this._sort('mapviews');
  },

  _onClickMapsAndDatasets: function(e) {
    this.killEvent(e);
    this._selectType(null);
  },

  _onClickMaps: function(e) {
    this.killEvent(e);
    this._selectType('derived');
  },

  _onClickDatasets: function(e) {
    this.killEvent(e);
    this._selectType('table');
  }
});
<|endoftext|>