<commit_before>const Parser = require("tree-sitter");
const { assert } = require("chai");
const { dsl, generate, loadLanguage } = require("..");
const { choice, prec, repeat, seq, grammar } = dsl;
const ARITHMETIC = require('./fixtures/arithmetic_language');

describe("Tree", () => {
  let parser;

  beforeEach(() => {
    parser = new Parser();
    parser.setLanguage(ARITHMETIC)
  });

  describe('.edit', () => {
    let input, edit

    it('updates the positions of existing nodes', () => {
      input = 'abc + cde';

      tree = parser.parse(input);
      assert.equal(
        tree.rootNode.toString(),
        "(program (sum (variable) (variable)))"
      );

      let variableNode1 = tree.rootNode.firstChild.firstChild;
      let variableNode2 = tree.rootNode.firstChild.lastChild;
      assert.equal(variableNode1.startIndex, 0);
      assert.equal(variableNode1.endIndex, 3);
      assert.equal(variableNode2.startIndex, 6);
      assert.equal(variableNode2.endIndex, 9);

      ([input, edit] = spliceInput(input, input.indexOf('bc'), 0, ' * '));
      assert.equal(input, 'a * bc + cde');

      tree.edit(edit);
      assert.equal(variableNode1.startIndex, 0);
      assert.equal(variableNode1.endIndex, 6);
      assert.equal(variableNode2.startIndex, 9);
      assert.equal(variableNode2.endIndex, 12);

      tree = parser.parse(input, tree);
      assert.equal(
        tree.rootNode.toString(),
        "(program (sum (product (variable) (variable)) (variable)))"
      );
    });

    it("handles non-ascii characters", () => {
      input = 'αβδ + cde';

      tree = parser.parse(input);
      assert.equal(
        tree.rootNode.toString(),
        "(program (sum (variable) (variable)))"
      );

      const variableNode = tree.rootNode.firstChild.lastChild;

      ([input, edit] = spliceInput(input, input.indexOf('δ'), 0, '👍 * '));
      assert.equal(input, 'αβ👍 * δ + cde');

      tree.edit(edit);
      assert.equal(variableNode.startIndex, input.indexOf('cde'));

      tree = parser.parse(input, tree);
      assert.equal(
        tree.rootNode.toString(),
        "(program (sum (product (variable) (variable)) (variable)))"
      );
    });
  });

  describe('.getEditedRange()', () => {
    it('returns the range of tokens that have been edited', () => {
      const inputString = 'abc + def + ghi + jkl + mno';
      const tree = parser.parse(inputString);

      assert.equal(tree.getEditedRange(), null)

      tree.edit({
        startIndex: 7,
        oldEndIndex: 7,
        newEndIndex: 8,
        startPosition: { row: 0, column: 7 },
        oldEndPosition: { row: 0, column: 7 },
        newEndPosition: { row: 0, column: 8 }
      });

      tree.edit({
        startIndex: 21,
        oldEndIndex: 21,
        newEndIndex: 22,
        startPosition: { row: 0, column: 21 },
        oldEndPosition: { row: 0, column: 21 },
        newEndPosition: { row: 0, column: 22 }
      });

      assert.deepEqual(tree.getEditedRange(), {
        startIndex: 6,
        endIndex: 23,
        startPosition: {row: 0, column: 6},
        endPosition: {row: 0, column: 23},
      });
    })
  });

  describe(".getChangedRanges()", () => {
    let language

    before(() => {
      language = loadLanguage(
        generate(
          grammar({
            name: "test2",
            rules: {
              expression: $ =>
                choice(
                  prec.left(seq($.expression, "+", $.expression)),
                  $.variable
                ),

              variable: $ => /\w+/
            }
          })
        )
      );
    });

    it("reports the ranges of text whose syntactic meaning has changed", () => {
      parser.setLanguage(language);

      let sourceCode = "abcdefg + hij";
      const tree1 = parser.parse(sourceCode);

      assert.equal(
        tree1.rootNode.toString(),
        "(expression (expression (variable)) (expression (variable)))"
      );

      sourceCode = "abc + defg + hij";
      tree1.edit({
        startIndex: 2,
        oldEndIndex: 2,
        newEndIndex: 5,
        startPosition: { row: 0, column: 2 },
        oldEndPosition: { row: 0, column: 2 },
        newEndPosition: { row: 0, column: 5 }
      });

      const tree2 = parser.parse(sourceCode, tree1);
      assert.equal(
        tree2.rootNode.toString(),
        "(expression (expression (expression (variable)) (expression (variable))) (expression (variable)))"
      );

      const ranges = tree1.getChangedRanges(tree2);
      assert.deepEqual(ranges, [
        {
          startIndex: 0,
          endIndex: "abc + defg".length,
          startPosition: { row: 0, column: 0 },
          endPosition: { row: 0, column: "abc + defg".length }
        }
      ]);
    });

    it('throws an exception if the argument is not a tree', () => {
      parser.setLanguage(language);
      const tree1 = parser.parse("abcdefg + hij");

      assert.throws(() => {
        tree1.getChangedRanges({});
      }, /Argument must be a tree/);
    })
  });

  describe(".walk()", () => {
    it('returns a cursor that can be used to walk the tree', () => {
      const tree = parser.parse('a * b + c / d');

      const cursor = tree.walk();
      let expected = {
        nodeType: 'program',
        nodeIsNamed: true,
        startPosition: {row: 0, column: 0},
        endPosition: {row: 0, column: 13},
        startIndex: 0,
        endIndex: 13
      }
      checkCursorNode(cursor, expected);
      checkCursorNode(cursor.currentNode, expected);

      assert(cursor.gotoFirstChild());
      expected = {
        nodeType: 'sum',
        nodeIsNamed: true,
        startPosition: {row: 0, column: 0},
        endPosition: {row: 0, column: 13},
        startIndex: 0,
        endIndex: 13
      }
      checkCursorNode(cursor, expected);
      checkCursorNode(cursor.currentNode, expected);

      assert(cursor.gotoFirstChild());
      expected = {
        nodeType: 'product',
        nodeIsNamed: true,
        startPosition: {row: 0, column: 0},
        endPosition: {row: 0, column: 5},
        startIndex: 0,
        endIndex: 5
      }
      checkCursorNode(cursor, expected);
      checkCursorNode(cursor.currentNode, expected);

      assert(cursor.gotoFirstChild());
      expected = {
        nodeType: 'variable',
        nodeIsNamed: true,
        startPosition: {row: 0, column: 0},
        endPosition: {row: 0, column: 1},
        startIndex: 0,
        endIndex: 1
      }
      checkCursorNode(cursor, expected);
      checkCursorNode(cursor.currentNode, expected);

      assert(!cursor.gotoFirstChild())
      assert(cursor.gotoNextSibling());
      expected = {
        nodeType: '*',
        nodeIsNamed: false,
        startPosition: {row: 0, column: 2},
        endPosition: {row: 0, column: 3},
        startIndex: 2,
        endIndex: 3
      }
      checkCursorNode(cursor, expected);
      checkCursorNode(cursor.currentNode, expected);

      assert(cursor.gotoNextSibling());
      expected = {
        nodeType: 'variable',
        nodeIsNamed: true,
        startPosition: {row: 0, column: 4},
        endPosition: {row: 0, column: 5},
        startIndex: 4,
        endIndex: 5
      }
      checkCursorNode(cursor, expected);
      checkCursorNode(cursor.currentNode, expected);

      assert(!cursor.gotoNextSibling());
      assert(cursor.gotoParent());
      expected = {
        nodeType: 'product',
        nodeIsNamed: true,
        startPosition: {row: 0, column: 0},
        endPosition: {row: 0, column: 5},
        startIndex: 0,
        endIndex: 5
      }
      checkCursorNode(cursor, expected);
      checkCursorNode(cursor.currentNode, expected);

      assert(cursor.gotoNextSibling());
      expected = {
        nodeType: '+',
        nodeIsNamed: false,
        startPosition: {row: 0, column: 6},
        endPosition: {row: 0, column: 7},
        startIndex: 6,
        endIndex: 7
      }
      checkCursorNode(cursor, expected);
      checkCursorNode(cursor.currentNode, expected);

      assert(cursor.gotoNextSibling());
      expected = {
        nodeType: 'quotient',
        nodeIsNamed: true,
        startPosition: {row: 0, column: 8},
        endPosition: {row: 0, column: 13},
        startIndex: 8,
        endIndex: 13
      }
      checkCursorNode(cursor, expected);
      checkCursorNode(cursor.currentNode, expected);

      const childIndex = cursor.gotoFirstChildForIndex(12);
      expected = {
        nodeType: 'variable',
        nodeIsNamed: true,
        startPosition: {row: 0, column: 12},
        endPosition: {row: 0, column: 13},
        startIndex: 12,
        endIndex: 13
      }
      checkCursorNode(cursor, expected);
      checkCursorNode(cursor.currentNode, expected);
      assert.equal(childIndex, 2);

      assert(!cursor.gotoNextSibling());
      assert(cursor.gotoParent());
      assert(cursor.gotoParent());
      assert(cursor.gotoParent());
      assert(!cursor.gotoParent());
    });

    it('returns a cursor that can be reset anywhere in the tree', () => {
      const tree = parser.parse('a * b + c / d');
      const cursor = tree.walk();
      const root = tree.rootNode;

      // This should be the product node
      cursor.reset(root.children[0].children[0]);
      expected = {
        nodeType: 'product',
        nodeIsNamed: true,
        startPosition: {row: 0, column: 0},
        endPosition: {row: 0, column: 5},
        startIndex: 0,
        endIndex: 5
      }
      checkCursorNode(cursor, expected);
      checkCursorNode(cursor.currentNode, expected);

      cursor.reset(root);
      assert(!cursor.gotoParent());
    })
  });
});

function checkCursorNode(target, expected) {
  if (target instanceof Parser.SyntaxNode) {
    assert.equal(target.type, expected.nodeType);
    assert.equal(target.isNamed, expected.nodeIsNamed);
  } else {
    assert.equal(target.nodeType, expected.nodeType);
    assert.equal(target.nodeIsNamed, expected.nodeIsNamed);
  }
  assert.deepEqual(target.startPosition, expected.startPosition);
  assert.deepEqual(target.endPosition, expected.endPosition);
  assert.deepEqual(target.startIndex, expected.startIndex);
  assert.deepEqual(target.endIndex, expected.endIndex);
}

function spliceInput(input, startIndex, lengthRemoved, newText) {
  const oldEndIndex = startIndex + lengthRemoved;
  const newEndIndex = startIndex + newText.length;
  const startPosition = getExtent(input.slice(0, startIndex));
  const oldEndPosition = getExtent(input.slice(0, oldEndIndex));
  input = input.slice(0, startIndex) + newText + input.slice(oldEndIndex);
  const newEndPosition = getExtent(input.slice(0, newEndIndex));
  return [
    input,
    {
      startIndex, startPosition,
      oldEndIndex, oldEndPosition,
      newEndIndex, newEndPosition
    }
  ];
}

function getExtent(text) {
  let row = 0
  let index;
  for (index = 0; index != -1; index = text.indexOf('\n', index)) {
    index++
    row++;
  }
  return {row, column: text.length - index};
}
<commit_msg>Refactor tree cursor test<commit_after>const Parser = require("tree-sitter");
const { assert } = require("chai");
const { dsl, generate, loadLanguage } = require("..");
const { choice, prec, repeat, seq, grammar } = dsl;
const ARITHMETIC = require('./fixtures/arithmetic_language');

describe("Tree", () => {
  let parser;

  beforeEach(() => {
    parser = new Parser();
    parser.setLanguage(ARITHMETIC)
  });

  describe('.edit', () => {
    let input, edit

    it('updates the positions of existing nodes', () => {
      input = 'abc + cde';

      tree = parser.parse(input);
      assert.equal(
        tree.rootNode.toString(),
        "(program (sum (variable) (variable)))"
      );

      let variableNode1 = tree.rootNode.firstChild.firstChild;
      let variableNode2 = tree.rootNode.firstChild.lastChild;
      assert.equal(variableNode1.startIndex, 0);
      assert.equal(variableNode1.endIndex, 3);
      assert.equal(variableNode2.startIndex, 6);
      assert.equal(variableNode2.endIndex, 9);

      ([input, edit] = spliceInput(input, input.indexOf('bc'), 0, ' * '));
      assert.equal(input, 'a * bc + cde');

      tree.edit(edit);
      assert.equal(variableNode1.startIndex, 0);
      assert.equal(variableNode1.endIndex, 6);
      assert.equal(variableNode2.startIndex, 9);
      assert.equal(variableNode2.endIndex, 12);

      tree = parser.parse(input, tree);
      assert.equal(
        tree.rootNode.toString(),
        "(program (sum (product (variable) (variable)) (variable)))"
      );
    });

    it("handles non-ascii characters", () => {
      input = 'αβδ + cde';

      tree = parser.parse(input);
      assert.equal(
        tree.rootNode.toString(),
        "(program (sum (variable) (variable)))"
      );

      const variableNode = tree.rootNode.firstChild.lastChild;

      ([input, edit] = spliceInput(input, input.indexOf('δ'), 0, '👍 * '));
      assert.equal(input, 'αβ👍 * δ + cde');

      tree.edit(edit);
      assert.equal(variableNode.startIndex, input.indexOf('cde'));

      tree = parser.parse(input, tree);
      assert.equal(
        tree.rootNode.toString(),
        "(program (sum (product (variable) (variable)) (variable)))"
      );
    });
  });

  describe('.getEditedRange()', () => {
    it('returns the range of tokens that have been edited', () => {
      const inputString = 'abc + def + ghi + jkl + mno';
      const tree = parser.parse(inputString);

      assert.equal(tree.getEditedRange(), null)

      tree.edit({
        startIndex: 7,
        oldEndIndex: 7,
        newEndIndex: 8,
        startPosition: { row: 0, column: 7 },
        oldEndPosition: { row: 0, column: 7 },
        newEndPosition: { row: 0, column: 8 }
      });

      tree.edit({
        startIndex: 21,
        oldEndIndex: 21,
        newEndIndex: 22,
        startPosition: { row: 0, column: 21 },
        oldEndPosition: { row: 0, column: 21 },
        newEndPosition: { row: 0, column: 22 }
      });

      assert.deepEqual(tree.getEditedRange(), {
        startIndex: 6,
        endIndex: 23,
        startPosition: {row: 0, column: 6},
        endPosition: {row: 0, column: 23},
      });
    })
  });

  describe(".getChangedRanges()", () => {
    let language

    before(() => {
      language = loadLanguage(
        generate(
          grammar({
            name: "test2",
            rules: {
              expression: $ =>
                choice(
                  prec.left(seq($.expression, "+", $.expression)),
                  $.variable
                ),

              variable: $ => /\w+/
            }
          })
        )
      );
    });

    it("reports the ranges of text whose syntactic meaning has changed", () => {
      parser.setLanguage(language);

      let sourceCode = "abcdefg + hij";
      const tree1 = parser.parse(sourceCode);

      assert.equal(
        tree1.rootNode.toString(),
        "(expression (expression (variable)) (expression (variable)))"
      );

      sourceCode = "abc + defg + hij";
      tree1.edit({
        startIndex: 2,
        oldEndIndex: 2,
        newEndIndex: 5,
        startPosition: { row: 0, column: 2 },
        oldEndPosition: { row: 0, column: 2 },
        newEndPosition: { row: 0, column: 5 }
      });

      const tree2 = parser.parse(sourceCode, tree1);
      assert.equal(
        tree2.rootNode.toString(),
        "(expression (expression (expression (variable)) (expression (variable))) (expression (variable)))"
      );

      const ranges = tree1.getChangedRanges(tree2);
      assert.deepEqual(ranges, [
        {
          startIndex: 0,
          endIndex: "abc + defg".length,
          startPosition: { row: 0, column: 0 },
          endPosition: { row: 0, column: "abc + defg".length }
        }
      ]);
    });

    it('throws an exception if the argument is not a tree', () => {
      parser.setLanguage(language);
      const tree1 = parser.parse("abcdefg + hij");

      assert.throws(() => {
        tree1.getChangedRanges({});
      }, /Argument must be a tree/);
    })
  });

  describe(".walk()", () => {
    it('returns a cursor that can be used to walk the tree', () => {
      const tree = parser.parse('a * b + c / d');

      const cursor = tree.walk();
      assertCursorState(cursor, {
        nodeType: 'program',
        nodeIsNamed: true,
        startPosition: {row: 0, column: 0},
        endPosition: {row: 0, column: 13},
        startIndex: 0,
        endIndex: 13
      });

      assert(cursor.gotoFirstChild());
      assertCursorState(cursor, {
        nodeType: 'sum',
        nodeIsNamed: true,
        startPosition: {row: 0, column: 0},
        endPosition: {row: 0, column: 13},
        startIndex: 0,
        endIndex: 13
      });

      assert(cursor.gotoFirstChild());
      assertCursorState(cursor, {
        nodeType: 'product',
        nodeIsNamed: true,
        startPosition: {row: 0, column: 0},
        endPosition: {row: 0, column: 5},
        startIndex: 0,
        endIndex: 5
      });

      assert(cursor.gotoFirstChild());
      assertCursorState(cursor, {
        nodeType: 'variable',
        nodeIsNamed: true,
        startPosition: {row: 0, column: 0},
        endPosition: {row: 0, column: 1},
        startIndex: 0,
        endIndex: 1
      });

      assert(!cursor.gotoFirstChild())
      assert(cursor.gotoNextSibling());
      assertCursorState(cursor, {
        nodeType: '*',
        nodeIsNamed: false,
        startPosition: {row: 0, column: 2},
        endPosition: {row: 0, column: 3},
        startIndex: 2,
        endIndex: 3
      });

      assert(cursor.gotoNextSibling());
      assertCursorState(cursor, {
        nodeType: 'variable',
        nodeIsNamed: true,
        startPosition: {row: 0, column: 4},
        endPosition: {row: 0, column: 5},
        startIndex: 4,
        endIndex: 5
      });

      assert(!cursor.gotoNextSibling());
      assert(cursor.gotoParent());
      assertCursorState(cursor, {
        nodeType: 'product',
        nodeIsNamed: true,
        startPosition: {row: 0, column: 0},
        endPosition: {row: 0, column: 5},
        startIndex: 0,
        endIndex: 5
      });

      assert(cursor.gotoNextSibling());
      assertCursorState(cursor, {
        nodeType: '+',
        nodeIsNamed: false,
        startPosition: {row: 0, column: 6},
        endPosition: {row: 0, column: 7},
        startIndex: 6,
        endIndex: 7
      });

      assert(cursor.gotoNextSibling());
      assertCursorState(cursor, {
        nodeType: 'quotient',
        nodeIsNamed: true,
        startPosition: {row: 0, column: 8},
        endPosition: {row: 0, column: 13},
        startIndex: 8,
        endIndex: 13
      });

      const childIndex = cursor.gotoFirstChildForIndex(12);
      assertCursorState(cursor, {
        nodeType: 'variable',
        nodeIsNamed: true,
        startPosition: {row: 0, column: 12},
        endPosition: {row: 0, column: 13},
        startIndex: 12,
        endIndex: 13
      });
      assert.equal(childIndex, 2);

      assert(!cursor.gotoNextSibling());
      assert(cursor.gotoParent());
      assert(cursor.gotoParent());
      assert(cursor.gotoParent());
      assert(!cursor.gotoParent());
    });

    it('returns a cursor that can be reset anywhere in the tree', () => {
      const tree = parser.parse('a * b + c / d');
      const cursor = tree.walk();
      const root = tree.rootNode;

      cursor.reset(root.children[0].children[0]);
      assertCursorState(cursor, {
        nodeType: 'product',
        nodeIsNamed: true,
        startPosition: {row: 0, column: 0},
        endPosition: {row: 0, column: 5},
        startIndex: 0,
        endIndex: 5
      });

      cursor.gotoFirstChild()
      assertCursorState(cursor, {
        nodeType: 'variable',
        nodeIsNamed: true,
        startPosition: {row: 0, column: 0},
        endPosition: {row: 0, column: 1},
        startIndex: 0,
        endIndex: 1
      });

      cursor.reset(root);
      assert(!cursor.gotoParent());
    })
  });
});

function assertCursorState(cursor, params) {
  assert.equal(cursor.nodeType, params.nodeType);
  assert.equal(cursor.nodeIsNamed, params.nodeIsNamed);
  assert.deepEqual(cursor.startPosition, params.startPosition);
  assert.deepEqual(cursor.endPosition, params.endPosition);
  assert.deepEqual(cursor.startIndex, params.startIndex);
  assert.deepEqual(cursor.endIndex, params.endIndex);

  const node = cursor.currentNode
  assert.equal(node.type, cursor.nodeType);
  assert.equal(node.isNamed, cursor.nodeIsNamed);
  assert.deepEqual(node.startPosition, params.startPosition);
  assert.deepEqual(node.endPosition, params.endPosition);
  assert.deepEqual(node.startIndex, params.startIndex);
  assert.deepEqual(node.endIndex, params.endIndex);
}

function spliceInput(input, startIndex, lengthRemoved, newText) {
  const oldEndIndex = startIndex + lengthRemoved;
  const newEndIndex = startIndex + newText.length;
  const startPosition = getExtent(input.slice(0, startIndex));
  const oldEndPosition = getExtent(input.slice(0, oldEndIndex));
  input = input.slice(0, startIndex) + newText + input.slice(oldEndIndex);
  const newEndPosition = getExtent(input.slice(0, newEndIndex));
  return [
    input,
    {
      startIndex, startPosition,
      oldEndIndex, oldEndPosition,
      newEndIndex, newEndPosition
    }
  ];
}

function getExtent(text) {
  let row = 0
  let index;
  for (index = 0; index != -1; index = text.indexOf('\n', index)) {
    index++
    row++;
  }
  return {row, column: text.length - index};
}
<|endoftext|>


<commit_before>// Karma configuration
// Generated on Mon Feb 17 2014 14:35:28 GMT-0600 (Central Standard Time)

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

    // base path, that will be used to resolve files and exclude
    basePath: '',

    // frameworks to use
    frameworks: ['qunit', 'requirejs'],

    // list of files / patterns to load in the browser
    files: [
      'src/test/karma-test-main.js',
      {pattern: 'src/js/**/*.js', included: false},
      {pattern: 'src/test/**/*.js', included: false}
    ],

    // list of files to exclude
    exclude: [

    ],

    preprocessors: {
        'src/js/**/*.js': ['coverage']
    },

    // test results reporter to use
    // possible values: 'dots', 'progress', 'junit', 'growl', 'coverage'
    reporters: ['progress','junit', 'coverage'],

    // web server port
    port: 9876,

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

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

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

    // Start these browsers, currently available:
    // - Chrome
    // - ChromeCanary
    // - Firefox
    // - Opera (has to be installed with `npm install karma-opera-launcher`)
    // - Safari (only Mac; has to be installed with `npm install karma-safari-launcher`)
    // - PhantomJS
    // - IE (only Windows; has to be installed with `npm install karma-ie-launcher`)
    browsers: ['PhantomJS'],

    // If browser does not capture in given timeout [ms], kill it
    captureTimeout: 60000,

    // Continuous Integration mode
    // if true, it capture browsers, run tests and exit
    singleRun: false
  });
};
<commit_msg>lcov coverage report<commit_after>// Karma configuration
// Generated on Mon Feb 17 2014 14:35:28 GMT-0600 (Central Standard Time)

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

        // base path, that will be used to resolve files and exclude
        basePath: '',

        // frameworks to use
        frameworks: ['qunit', 'requirejs'],

        // list of files / patterns to load in the browser
        files: [
            'src/test/karma-test-main.js',
            {pattern: 'src/js/**/*.js', included: false},
            {pattern: 'src/test/**/*.js', included: false}
        ],

        // list of files to exclude
        exclude: [

        ],

        preprocessors: {
            'src/js/**/*.js': ['coverage']
        },

        // test results reporter to use
        // possible values: 'dots', 'progress', 'junit', 'growl', 'coverage'
        reporters: ['progress', 'junit', 'coverage'],

        coverageReporter: {
            reporters: [
                {type: 'lcov'},
                {type: 'html'},
                {type: 'cobertura'},
                {type: 'text-summary'}
            ]
        },

        // web server port
        port: 9876,

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

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

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

        // Start these browsers, currently available:
        // - Chrome
        // - ChromeCanary
        // - Firefox
        // - Opera (has to be installed with `npm install karma-opera-launcher`)
        // - Safari (only Mac; has to be installed with `npm install karma-safari-launcher`)
        // - PhantomJS
        // - IE (only Windows; has to be installed with `npm install karma-ie-launcher`)
        browsers: ['PhantomJS'],

        // If browser does not capture in given timeout [ms], kill it
        captureTimeout: 60000,

        // Continuous Integration mode
        // if true, it capture browsers, run tests and exit
        singleRun: false
    });
};
<|endoftext|>


<commit_before>'use strict';

var fs = require('fs'),
	jQueryExtend = require('extend');

/**
 *
 * @class Utils
 * @namespace node-mock-server
 * @constructor
 *
 * Swagger importer
 */
function Utils() {
	this.init();
}

Utils.prototype = {

	constructor : Utils,

	/**
	 *
	 * @method init
	 * called by constructor
	 * @returns void
	 * @public
	 */
	init: function () {
	},

	/**
	 *
	 * @method forIn
	 * @param {object} obj
	 * @param {function} callback
	 * @returns void
	 * @public
	 */
	forIn: function (obj, callback) {
		for (var key in obj) {
			if (obj.hasOwnProperty(key)) {
				callback.call(this, key, obj[key]);
			}
		}
	},

	/**
	 *
	 * @method for
	 * @param {Array} arr
	 * @param {function} callback
	 * @returns void
	 * @public
	 */
	for: function (arr, callback) {

		var i, len = arr.length;

		for (i = 0; i < len; i +=1) {
			callback.call({}, arr[i], i);
		}
	},

	/**
	 *
	 * @method isFilledString
	 * @param {string} value
	 * @returns {boolean} isFilledString
	 * @public
	 */
	isFilledString: function (value) {
		return (typeof value === 'string' && value !== '');
	},

	/**
	 *
	 * @method getStats
	 * @param {string} dirFileName
	 * @returns {object} getStats
	 * @public
	 */
	getStats: function (dirFileName) {
		return fs.statSync(dirFileName);
	},

	/**
	 *
	 * @method isDir
	 * @param {string} dirName
	 * @returns {boolean} isDir
	 * @public
	 */
	existDir: function (dirName) {

		var isDir = false;

		try {
			isDir = this.getStats(dirName).isDirectory();
		} catch (err) {}

		return isDir;
	},

	/**
	 *
	 * @method existFile
	 * @param {string} path
	 * @returns {boolean} isFile
	 * @public
	 */
	existFile: function (path) {

		var isFile = false;

		try {
			isFile = this.getStats(path).isFile();
		} catch (err) {}

		return isFile;
	},

	/**
	 *
	 * @method writeDir
	 * @param {string} dirName
	 * @public
	 */
	writeDir: function (dirName) {
		if (!this.existDir(dirName)) {
			fs.mkdirSync(dirName);
		}
	},

	/**
	 *
	 * @method writeFile
	 * @param {string} path
	 * @param {object} data
	 * @public
	 */
	writeFile: function (path, data) {
		fs.writeFileSync(path, data);
	},

	/**
	 *
	 * @method readFile
	 * @param {string} path
	 * @returns {string}
	 * @public
	 */
	readFile: function (path) {
		return fs.readFileSync(path, 'utf8');
	},

	/**
	 *
	 * @method removeFile
	 * @param {string} path
	 * @public
	 */
	removeFile: function (path) {
		try {
			fs.unlinkSync(path);
		} catch (err) {}
	},

	/**
	 *
	 * @method writeFile
	 * @param {string} dir
	 * @param {Array|undefined} ignoreFiles
	 * @public
	 */
	readDir: function (dir, ignoreFiles) {
		var results = [],
			list = [];

		ignoreFiles = ignoreFiles || [];

		try {
			list = fs.readdirSync(dir);
		} catch (err) {
			if (process.env.NODE_ENV !== 'test') {
				console.log('Folder "' + err.path + '" not found!');
			}
		}

		list.forEach(function(file) {
			if (ignoreFiles.indexOf(file) < 0) {
				results.push({
					path: dir + '/' + file,
					file: file
				});
			}
		});
		return results;
	},
	/**
	 * Capitalizes the first letter of the given string.
	 *
	 * @method capitalize
	 * @param {String} str
	 *      The original string
	 * @return {String}
	 *      The capitalized string
	 */
	capitalize: function(str) {
		// Capitalize the first letter
		return str.substr(0, 1).toUpperCase().concat(str.substr(1));
	},

	/**
	 * Camelizes the given string.
	 *
	 * @method toCamel
	 * @param {String} str
	 *      The original string
	 * @return {String}
	 *      The camelized string
	 */
	toCamel: function(str) {
		return str.replace(/(\-[A-Za-z])/g, function($1) {
			return $1.toUpperCase().replace('-', '');
		});
	},

	/**
	 *
	 * @method getPreferences
	 * @param {object} obj
	 * @returns {object} preferences
	 * @public
	 */
	getPreferences: function (obj) {
		var data = {},
			file = obj.restPath + '/preferences.json';

		try {
			data = JSON.parse(this.readFile(file));
		} catch (err) {}

		return data;
	},

	/**
	 *
	 * @method getMethodStore
	 * @param {string} path
	 * @returns {object}
	 * @public
	 */
	getMethodStore: function (path) {

		var pathFull = path + '/.store.json';

		if (!this.existFile(pathFull)) {
			return {};
		}

		try {
			return JSON.parse(this.readFile(pathFull));
		} catch (err) {}

		return {};
	},

	/**
	 *
	 * @method setMethodStore
	 * @param {string} path
	 * @param {object} data
	 * @returns {void}
	 * @public
	 */
	setMethodStore: function (path, data) {

		var pathFull = path + '/.store.json',
			originalData = this.getMethodStore(path),
			outData = jQueryExtend(true, originalData, data);

		this.writeFile(pathFull, JSON.stringify(outData, null, 2));
	}

};

module.exports = Utils;<commit_msg>[new] #4: add removeDir Util<commit_after>'use strict';

var fs = require('fs'),
	jQueryExtend = require('extend');

/**
 *
 * @class Utils
 * @namespace node-mock-server
 * @constructor
 *
 * Swagger importer
 */
function Utils() {
	this.init();
}

Utils.prototype = {

	constructor : Utils,

	/**
	 *
	 * @method init
	 * called by constructor
	 * @returns void
	 * @public
	 */
	init: function () {
	},

	/**
	 *
	 * @method forIn
	 * @param {object} obj
	 * @param {function} callback
	 * @returns void
	 * @public
	 */
	forIn: function (obj, callback) {
		for (var key in obj) {
			if (obj.hasOwnProperty(key)) {
				callback.call(this, key, obj[key]);
			}
		}
	},

	/**
	 *
	 * @method for
	 * @param {Array} arr
	 * @param {function} callback
	 * @returns void
	 * @public
	 */
	for: function (arr, callback) {

		var i, len = arr.length;

		for (i = 0; i < len; i +=1) {
			callback.call({}, arr[i], i);
		}
	},

	/**
	 *
	 * @method isFilledString
	 * @param {string} value
	 * @returns {boolean} isFilledString
	 * @public
	 */
	isFilledString: function (value) {
		return (typeof value === 'string' && value !== '');
	},

	/**
	 *
	 * @method getStats
	 * @param {string} dirFileName
	 * @returns {object} getStats
	 * @public
	 */
	getStats: function (dirFileName) {
		return fs.statSync(dirFileName);
	},

	/**
	 *
	 * @method isDir
	 * @param {string} dirName
	 * @returns {boolean} isDir
	 * @public
	 */
	existDir: function (dirName) {

		var isDir = false;

		try {
			isDir = this.getStats(dirName).isDirectory();
		} catch (err) {}

		return isDir;
	},

	/**
	 *
	 * @method existFile
	 * @param {string} path
	 * @returns {boolean} isFile
	 * @public
	 */
	existFile: function (path) {

		var isFile = false;

		try {
			isFile = this.getStats(path).isFile();
		} catch (err) {}

		return isFile;
	},

	/**
	 *
	 * @method writeDir
	 * @param {string} dirName
	 * @public
	 */
	writeDir: function (dirName) {
		if (!this.existDir(dirName)) {
			fs.mkdirSync(dirName);
		}
	},

	/**
	 *
	 * @method writeFile
	 * @param {string} path
	 * @param {object} data
	 * @public
	 */
	writeFile: function (path, data) {
		fs.writeFileSync(path, data);
	},

	/**
	 *
	 * @method readFile
	 * @param {string} path
	 * @returns {string}
	 * @public
	 */
	readFile: function (path) {
		return fs.readFileSync(path, 'utf8');
	},

	/**
	 *
	 * @method removeFile
	 * @param {string} path
	 * @public
	 */
	removeFile: function (path) {
		try {
			fs.unlinkSync(path);
		} catch (err) {}
	},

	/**
	 *
	 * @method writeFile
	 * @param {string} dir
	 * @param {Array|undefined} ignoreFiles
	 * @public
	 */
	readDir: function (dir, ignoreFiles) {
		var results = [],
			list = [];

		ignoreFiles = ignoreFiles || [];

		try {
			list = fs.readdirSync(dir);
		} catch (err) {
			if (process.env.NODE_ENV !== 'test') {
				console.log('Folder "' + err.path + '" not found!');
			}
		}

		list.forEach(function(file) {
			if (ignoreFiles.indexOf(file) < 0) {
				results.push({
					path: dir + '/' + file,
					file: file
				});
			}
		});
		return results;
	},

	/**
	 *
	 * @method removeDir
	 * @param {string} path
	 * @public
	 */
	removeDir: function (path) {
		try {
			if( fs.existsSync(path) ) {
				fs.readdirSync(path).forEach(function(file){
					var curPath = path + "/" + file;
					if(fs.lstatSync(curPath).isDirectory()) { // recurse
						this.removeDir(curPath);
					} else { // delete file
						fs.unlinkSync(curPath);
					}
				});
				fs.rmdirSync(path);
			}
		} catch (err) {}
	},

	/**
	 * Capitalizes the first letter of the given string.
	 *
	 * @method capitalize
	 * @param {String} str
	 *      The original string
	 * @return {String}
	 *      The capitalized string
	 */
	capitalize: function(str) {
		// Capitalize the first letter
		return str.substr(0, 1).toUpperCase().concat(str.substr(1));
	},

	/**
	 * Camelizes the given string.
	 *
	 * @method toCamel
	 * @param {String} str
	 *      The original string
	 * @return {String}
	 *      The camelized string
	 */
	toCamel: function(str) {
		return str.replace(/(\-[A-Za-z])/g, function($1) {
			return $1.toUpperCase().replace('-', '');
		});
	},

	/**
	 *
	 * @method getPreferences
	 * @param {object} obj
	 * @returns {object} preferences
	 * @public
	 */
	getPreferences: function (obj) {
		var data = {},
			file = obj.restPath + '/preferences.json';

		try {
			data = JSON.parse(this.readFile(file));
		} catch (err) {}

		return data;
	},

	/**
	 *
	 * @method getMethodStore
	 * @param {string} path
	 * @returns {object}
	 * @public
	 */
	getMethodStore: function (path) {

		var pathFull = path + '/.store.json';

		if (!this.existFile(pathFull)) {
			return {};
		}

		try {
			return JSON.parse(this.readFile(pathFull));
		} catch (err) {}

		return {};
	},

	/**
	 *
	 * @method setMethodStore
	 * @param {string} path
	 * @param {object} data
	 * @returns {void}
	 * @public
	 */
	setMethodStore: function (path, data) {

		var pathFull = path + '/.store.json',
			originalData = this.getMethodStore(path),
			outData = jQueryExtend(true, originalData, data);

		this.writeFile(pathFull, JSON.stringify(outData, null, 2));
	}

};

module.exports = Utils;<|endoftext|>


<commit_before>$(function() {
  // Warning: The following code is extremely macaronic
  var datasource = 'data/precipitation.json';
  var datessource = 'data/precipitation-dates.json';
  var colors = ['#EDECEA',  '#C8E1E7',  '#ADD8EA',  '#7FB8D4',  '#4EA3C8',  '#2586AB'];

  var animation_delay = 200;
  var yearskip = 3;
  var scale = [];
  var timeline_width = 0;
  var current_frame = 0;
  var dates_count = 0;
  var frames_count = 0;

  var playing = false;

  // http://stackoverflow.com/questions/14034455/translating-lat-long-to-actual-screen-x-y-coordinates-on-a-equirectangular-map
  var equirectangular = function(latitude, longitude) {
    var x = ((longitude + 180) * (width  / 360));
    var y = (((latitude * -1) + 90) * (height/ 180));
    return [x, y]
  };

  // http://stackoverflow.com/questions/14329691/covert-latitude-longitude-point-to-a-pixels-x-y-on-mercator-projection
  var mercator = function(latitude, longitude) {
    var x = (width*(180+longitude)/360)%width+(width/2);

    // convert from degrees to radians
    var latRad = latitude*Math.PI/180;

    // get y value
    var mercN = Math.log(Math.tan((Math.PI/4)+(latRad/2)));
    var y     = (height/2)-(width*mercN/(2*PI));
    return [x - width / 2, y]
  };

  // returns [x, y] which corresponds to latitude and longitude
  var convert_coordinates = function(latitude, longitude) {
    return equirectangular(latitude, longitude);
  };

  // returns an array [value, color], sorted by value
  // All values <= value, have color color
  // result: [1, 'red'], [3, blue], [5, green] means:
  //   (-infinity, 1] -> red
  //   (1, 3]         -> blue
  //   (3, 5]         -> blue
  var get_color_scale = function(data, colors) {
    var min = Infinity;
    var max = -Infinity;
    for(var i = 0; i < data.length; ++i) {
      values = data[i];
      for (i in values) {
        v = values[i].value;
        if (v > max) { max = v; }
        if (v < min) { min = v; }
      }
    }
    var size = max - min;
    var step = size/(colors.length-1);
    scale = [[min, colors[0]]]
    for (var i=1; i<colors.length; i++) {
      scale.push([min + i * step, colors[i]]);
    }
    return scale;
  }

  var get_color = function(value, scale) {
    var max;
    for (var i=0; i<scale.length; i++) {
      max = scale[i][0];
      if (value <= max) {
        return scale[i][1];
      }
    }
  }

  var plot_array = function(ctx, array, resolution, color_scale) {
    ctx.clearRect(0, 0, width, height);
    for (var i = 0; i < array.length; ++i) {
      var obj = array[i];

      var coords = convert_coordinates(obj['lat'], obj['lon']);
      var x = Math.round(coords[0]); var y = Math.round(coords[1]);
      var coords2 = convert_coordinates(obj['lat'] + resolution, obj['lon'] + resolution);
      var x2 = Math.round(coords2[0]); var y2 = Math.round(coords2[1]);
      var color = get_color(obj['value'], color_scale)

      ctx.beginPath();
      ctx.moveTo(x, y);
      ctx.lineTo(x2, y);
      ctx.lineTo(x2, y2);
      ctx.lineTo(x, y2);
      ctx.lineTo(x, y);
      ctx.fillStyle = color;
      ctx.fill();
    }
  };

  var move_pointer = function(x, nodraw) {
    var pointer = $('#pointer');
    if (x <= timeline_width) {
      pointer.stop().animate({
        'left': x + 'px'
      });
      if (!nodraw) {
        frame = Math.round((x / timeline_width) * (frames_count - 1));
        show_frame(frame);
      }
    }
    var hover = $('.hover');
    if (!hover.is(':visible')) {
      hover.fadeIn('slow');
    }
    hover.animate({
      'left': x + 'px',
      'top': ($('#pointer').offset.top - 20) + 'px'
    });
  }

  var show_frame = function(frame) {
    current_frame = frame;
    if (current_frame < frames_count) {
      plot_array(window.ctx, window.data[frame], 2.5, scale);
      var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
      date = months[frame % 12] + ' ' + window.years[Math.floor(frame / 12)];
      $('.hover').html(date);
    }
  };

  var next_frame = function(link) {
    if (current_frame < frames_count) {
      current_frame++;
      move_pointer((current_frame / frames_count) * timeline_width, true);
      show_frame(current_frame);
    } else {
      playing = false;
      $('.animation-controls .play').show();
      $('.animation-controls .stop').hide();
    }
    if (link) {
      clearTimeout(window.frame_timeout);
      window.frame_timeout = setTimeout(function() {
         next_frame(true);
      }, animation_delay);
    }
  }

  var start_animation = function() {
    playing = true;
    window.frame_timeout = setTimeout(function() {
      next_frame(true);
    }, animation_delay);
  };

  var stop_animation = function() {
    clearTimeout(window.frame_timeout);
  }

  $.getJSON(datasource, function(data) {
    window.data = data;
    frames_count = Object.keys(data).length;

    // displaying years in timeline
    $.getJSON(datessource, function(years) {
      window.years = years;
      for (var i = 0; i < years.length; ++i) {
        if (parseInt(years[i]) % yearskip == 0) {
          dates_count++;
          var year = $('

').html(years[i]);
          $('#slider .timeline').append(year);
        }
      }
      timeline_width = $('#slider .timeline').width();
    });
    $('#slider').fadeIn('slow');
    $('.animation-controls .play').fadeIn('slow');

    var pointer = $('')
              .attr('id', 'pointer')
    $('#slider').append(pointer);

    $('#slider .timeline').click(function(e) {
      playing = false;
      $('.animation-controls .play').show();
      $('.animation-controls .stop').hide();
      clearTimeout(window.frame_timeout);
      move_pointer(e.pageX);
    });
    $('body').bind('mousemove click', function(e) {
      var controls = $('.animation-controls');
      controls.fadeIn('fast');
      clearTimeout(window.fade_timeout);
      window.fade_timeout = setTimeout(function() {
        controls.fadeOut('slow');
      }, 750);
    });
    $('.animation-controls .play').click(function(){
      start_animation();
      $('.animation-controls .play').hide();
      $('.animation-controls .stop').show();
    })
    $('.animation-controls .stop').click(function(){
      stop_animation();
      $('.animation-controls .play').show();
      $('.animation-controls .stop').hide();
    });

    // setting map
    var ratio = 1 / 2;
    window.width = window.innerWidth,
    window.height = ratio * width;

    var canvas = $('<canvas></canvas>')
        .addClass('map')
        .attr("width", width)
        .attr("height", height);
    $("body").prepend(canvas);

    window.ctx = canvas[0].getContext("2d");

    scale = get_color_scale(data, colors);
    $('body').addClass('loaded');
    show_frame(0);
  });
});
<commit_msg>Refactoring<commit_after>;(function($) {
    'use strict';

    $(function() {
        // Warning: The following code is extremely spaghetti
        // Done in 1.5 day on NASA Space Challenge Hackathon

        // Configuration
        var datasource = 'data/precipitation.json',
            datessource = 'data/precipitation-dates.json',
            colors = ['#EDECEA',  '#C8E1E7',  '#ADD8EA',
                      '#7FB8D4',  '#4EA3C8',  '#2586AB'],
            animationDelay = 200,
            yearskip = 3,
            ratio = 1 / 2;

        // Globals
        var common = {
            scale: [],

            timelineWidth: 0,
            currentFrame: 0,
            framesCount: 0,
            datesCount: 0,

            years: 0,

            playing: false,

            width: window.innerWidth,
            height: ratio * window.innerWidth,

            ctx: null,

            fadeTimeout: null,
            frameTimeout: null,

            data: null
        };

        // http://stackoverflow.com/questions/14034455/translating-lat-long-to-actual-screen-x-y-coordinates-on-a-equirectangular-map
        var equirectangular = function(latitude, longitude) {
            var x = ((longitude + 180) * (common.width  / 360));
            var y = (((latitude * -1) + 90) * (common.height/ 180));
            return [x, y];
        };

        // http://stackoverflow.com/questions/14329691/covert-latitude-longitude-point-to-a-pixels-x-y-on-mercator-projection
        var mercator = function(latitude, longitude) {
            var x = (common.width*(180+longitude)/360)%common.width+(common.width/2);

            // convert from degrees to radians
            var latRad = latitude*Math.PI/180;

            // get y value
            var mercN = Math.log(Math.tan((Math.PI/4)+(latRad/2)));
            var y     = (common.height/2)-(common.width*mercN/(2*Math.PI));
            return [x - common.width / 2, y];
        };

        // returns [x, y] which corresponds to latitude and longitude
        var convertCoordinates = function(latitude, longitude) {
            return equirectangular(latitude, longitude);
        };

        // returns an array [value, color], sorted by value
        // All values <= value, have color color
        // result: [1, 'red'], [3, blue], [5, green] means:
        //   (-infinity, 1] -> red
        //   (1, 3]         -> blue
        //   (3, 5]         -> blue
        var getColorScale = function(data, colors) {
            var min = Infinity,
                max = -Infinity;
            for(var i = 0; i < data.length; ++i) {
                var values = data[i];
                for (i in values) {
                    var v = values[i].value;
                    if (v > max) { max = v; }
                    if (v < min) { min = v; }
                }
            }
            var size = max - min,
                step = size/(colors.length-1),
                scale = [[min, colors[0]]];
            for (var i = 1; i < colors.length; i++) {
                scale.push([min + i * step, colors[i]]);
            }
            return scale;
        };

        var getColor = function(value, scale) {
            var max;
            for (var i=0; i < scale.length; i++) {
                max = scale[i][0];
                if (value <= max) {
                    return scale[i][1];
                }
            }
        };

        var plotArray = function(ctx, array, resolution, colorScale) {
            ctx.clearRect(0, 0, common.width, common.height);
            for (var i = 0; i < array.length; ++i) {
                var obj = array[i];

                var coords = convertCoordinates(obj.lat, obj.lon),
                    x = Math.round(coords[0]),
                    y = Math.round(coords[1]),

                    coords2 = convertCoordinates(obj.lat +
                                resolution, obj.lon + resolution),
                    x2 = Math.round(coords2[0]),
                    y2 = Math.round(coords2[1]),
                    color = getColor(obj.value, colorScale);

                ctx.beginPath();
                ctx.moveTo(x, y);
                ctx.lineTo(x2, y);
                ctx.lineTo(x2, y2);
                ctx.lineTo(x, y2);
                ctx.lineTo(x, y);
                ctx.fillStyle = color;
                ctx.fill();
            }
        };

        var movePointer = function(x, nodraw) {
            var pointer = $('#pointer');
            if (x <= common.timelineWidth) {
                pointer.stop().animate({
                    'left': x + 'px'
                });
                if (!nodraw) {
                    var frame = Math.round((x / common.timelineWidth) *
                        (common.framesCount - 1));
                    showFrame(frame);
                }
            }
            var hover = $('.hover');
            if (!hover.is(':visible')) {
                hover.fadeIn('slow');
            }
            hover.animate({
                'left': x + 'px',
                'top': ($('#pointer').offset.top - 20) + 'px'
            });
        };

        var showFrame = function(frame) {
            common.currentFrame = frame;
            if (common.currentFrame < common.framesCount) {
                var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
                              'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
                plotArray(common.ctx, common.data[frame], 2.5, common.scale);

                var date = months[frame % 12] + ' ' +
                              common.years[Math.floor(frame / 12)];
                $('.hover').html(date);
            }
        };

        var nextFrame = function(link) {
            if (common.currentFrame < common.framesCount) {
                common.currentFrame++;
                movePointer((common.currentFrame / common.framesCount) * common.timelineWidth, true);
                showFrame(common.currentFrame);
            } else {
                common.playing = false;
                $('.animation-controls .play').show();
                $('.animation-controls .stop').hide();
            }
            if (link) {
                clearTimeout(common.frameTimeout);
                common.frameTimeout = setTimeout(function() {
                    nextFrame(true);
                }, animationDelay);
            }
        };

        var startAnimation = function() {
            common.playing = true;
            common.frameTimeout = setTimeout(function() {
                nextFrame(true);
            }, animationDelay);
        };

        var stopAnimation = function() {
            clearTimeout(common.frameTimeout);
        };

        $.getJSON(datasource, function(data) {
            common.data = data;
            common.framesCount = Object.keys(data).length;

            $.getJSON(datessource, function(years) {
                common.years = years;
                for (var i = 0; i < years.length; ++i) {
                    if (parseInt(years[i], 10) % yearskip === 0) {
                        common.datesCount++;
                        var year = $('

').html(years[i]);
                        $('#slider .timeline').append(year);
                    }
                }
                common.timelineWidth = $('#slider .timeline').width();
            });

            $('#slider').fadeIn('slow');
            $('.animation-controls .play').fadeIn('slow');

            var pointer = $('')
                  .attr('id', 'pointer');
            $('#slider').append(pointer);

            $('#slider .timeline').click(function(e) {
                common.playing = false;
                $('.animation-controls .play').show();
                $('.animation-controls .stop').hide();

                clearTimeout(common.frameTimeout);
                movePointer(e.pageX);
            });

            $('body').bind('mousemove click', function() {
                var controls = $('.animation-controls');
                controls.fadeIn('fast');
                clearTimeout(common.fadeTimeout);
                common.fadeTimeout = setTimeout(function() {
                    controls.fadeOut('slow');
                }, 750);
            });

            $('.animation-controls .play').click(function() {
                startAnimation();
                $('.animation-controls .play').hide();
                $('.animation-controls .stop').show();
            });

            $('.animation-controls .stop').click(function() {
                stopAnimation();
                $('.animation-controls .play').show();
                $('.animation-controls .stop').hide();
            });

            var canvas = $('<canvas></canvas>')
                  .addClass('map')
                  .attr('width', common.width)
                  .attr('height', common.height);

            $('body').prepend(canvas);

            common.ctx = canvas[0].getContext('2d');
            common.scale = getColorScale(data, colors);

            $('body').addClass('loaded');
            showFrame(0);
        });
    });
})(jQuery);
<|endoftext|>


<commit_before>/*!
 * mongoskin - admin.js
 *
 * Copyright(c) 2011 - 2012 kissjs.org
 * Copyright(c) 2012 fengmk2 <fengmk2@gmail.com>
 * MIT Licensed
 */

"use strict";

var SkinAdmin = exports.SkinAdmin = function(db) {
  return db.db('admin');
}
<commit_msg>Fix #177<commit_after>/*!
 * mongoskin - admin.js
 *
 * Copyright(c) 2011 - 2012 kissjs.org
 * Copyright(c) 2012 fengmk2 <fengmk2@gmail.com>
 * MIT Licensed
 */

"use strict";

var SkinAdmin = exports.SkinAdmin = function(db) {
  return db.admin();
}
<|endoftext|>


<commit_before>const test = require('ava');
const sinon = require('sinon');
const proxyquire = require('proxyquire');

test.beforeEach('setup', t => {
    t.context.stub = sinon.stub().returns('type');
    t.context.BemEntityName = proxyquire('../index', {
        'bem-naming': {
            typeOf: t.context.stub
        }
    });
});

test('should use `naming.typeOf()` for block', t => {
    const entity = new t.context.BemEntityName({ block: 'block' });

    /*eslint no-unused-expressions: "off"*/
    entity.type;

    t.ok(t.context.stub.calledWith({ block: 'block' }));
});

test('should use `naming.typeOf()` for elem', t => {
    const entity = new t.context.BemEntityName({ block: 'block', elem: 'elem' });

    /*eslint no-unused-expressions: "off"*/
    entity.type;

    t.ok(t.context.stub.calledWith({ block: 'block', elem: 'elem' }));
});

test('should use `naming.typeOf()` for block modifier', t => {
    const entity = new t.context.BemEntityName({ block: 'block', modName: 'mod', modVal: 'val' });

    /*eslint no-unused-expressions: "off"*/
    entity.type;

    t.ok(t.context.stub.calledWith({ block: 'block', modName: 'mod', modVal: 'val' }));
});

test('should use naming.typeOf() for element modifier', t => {
    const entity = new t.context.BemEntityName({ block: 'block', elem: 'elem', modName: 'mod', modVal: 'val' });

    /*eslint no-unused-expressions: "off"*/
    entity.type;

    t.ok(t.context.stub.calledWith({ block: 'block', elem: 'elem', modName: 'mod', modVal: 'val' }));
});

test('should cache type value', t => {
    const entity = new t.context.BemEntityName({ block: 'block' });

    /*eslint no-unused-expressions: "off"*/
    entity.type;
    entity.type;

    t.is(t.context.stub.callCount, 1);
});
<commit_msg>Update ava tests<commit_after>const test = require('ava');
const sinon = require('sinon');
const proxyquire = require('proxyquire');

test.beforeEach('setup', t => {
    t.context.stub = sinon.stub().returns('type');
    t.context.BemEntityName = proxyquire('../index', {
        'bem-naming': {
            typeOf: t.context.stub
        }
    });
});

test('should use `naming.typeOf()` for block', t => {
    const entity = new t.context.BemEntityName({ block: 'block' });

    /*eslint no-unused-expressions: "off"*/
    entity.type;

    t.truthy(t.context.stub.calledWith({ block: 'block' }));
});

test('should use `naming.typeOf()` for elem', t => {
    const entity = new t.context.BemEntityName({ block: 'block', elem: 'elem' });

    /*eslint no-unused-expressions: "off"*/
    entity.type;

    t.truthy(t.context.stub.calledWith({ block: 'block', elem: 'elem' }));
});

test('should use `naming.typeOf()` for block modifier', t => {
    const entity = new t.context.BemEntityName({ block: 'block', modName: 'mod', modVal: 'val' });

    /*eslint no-unused-expressions: "off"*/
    entity.type;

    t.truthy(t.context.stub.calledWith({ block: 'block', modName: 'mod', modVal: 'val' }));
});

test('should use naming.typeOf() for element modifier', t => {
    const entity = new t.context.BemEntityName({ block: 'block', elem: 'elem', modName: 'mod', modVal: 'val' });

    /*eslint no-unused-expressions: "off"*/
    entity.type;

    t.truthy(t.context.stub.calledWith({ block: 'block', elem: 'elem', modName: 'mod', modVal: 'val' }));
});

test('should cache type value', t => {
    const entity = new t.context.BemEntityName({ block: 'block' });

    /*eslint no-unused-expressions: "off"*/
    entity.type;
    entity.type;

    t.is(t.context.stub.callCount, 1);
});
<|endoftext|>


<commit_before>// Karma configuration
// http://karma-runner.github.io/0.10/config/configuration-file.html

module.exports = function (config) {
  config.set({
    // testing framework to use (jasmine/mocha/qunit/...)
    frameworks: ['jasmine'],

    // list of files / patterns to load in the browser
    files: [
        'bower_components/angular/angular.js',
        'bower_components/angular-mocks/angular-mocks.js',
        'bower_components/leaflet/dist/leaflet.js',
        'bower_components/redux/index.js',
        'modules/shared/shared.module.js',

        'modules/header/header.module.js',
        'modules/detail/detail.module.js',
        'modules/layer-selection/layer-selection.module.js',
        'modules/map/map.module.js',
        'modules/page/page.module.js',
        'modules/search-results/search-results.module.js',
        'modules/straatbeeld/straatbeeld.module.js',

        'modules/atlas/atlas.module.js',
        'modules/**/*.js',

        'templates.js'
    ],

    plugins: [
      'karma-jasmine',
      'karma-mocha-reporter',
      'karma-coverage',
      'karma-phantomjs-launcher'
    ],

    // level of logging
    // possible values: OFF, ERROR, WARN, INFO, DEBUG
    logLevel: 'ERROR',

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

    // Reporters
    // - dots
    // - progress
    // - junit
    // - growl
    // - coverage
    reporters: ['coverage'],
    preprocessors: {
      // source files, that you wanna generate coverage for
      // do not include tests or libraries
      // (these files will be instrumented by Istanbul)
      'modules/**/*.js': ['coverage'],
      '!**/*.test.js': ['coverage'],
    },

    // optionally, configure the reporter
    // type can also be 'cobertura' which should be understand by Jenkins
    coverageReporter: {
      type: 'html',
      dir: 'reports/coverage/'
    },

    // Start these browsers, currently available:
    // - Chrome
    // - ChromeCanary
    // - Firefox
    // - Opera
    // - Safari (only Mac)
    // - PhantomJS
    // - IE (only Windows)
    browsers: ['PhantomJS'],

    // Continuous Integration mode
    // if true, it capture browsers, run tests and exit
    singleRun: true
  });
};
<commit_msg>karma coverage zonder .test files<commit_after>// Karma configuration
// http://karma-runner.github.io/0.10/config/configuration-file.html

module.exports = function (config) {
  config.set({
    // testing framework to use (jasmine/mocha/qunit/...)
    frameworks: ['jasmine'],

    // list of files / patterns to load in the browser
    files: [
        'bower_components/angular/angular.js',
        'bower_components/angular-mocks/angular-mocks.js',
        'bower_components/leaflet/dist/leaflet.js',
        'bower_components/redux/index.js',

        'modules/shared/shared.module.js',

        'modules/header/header.module.js',
        'modules/detail/detail.module.js',
        'modules/layer-selection/layer-selection.module.js',
        'modules/map/map.module.js',
        'modules/page/page.module.js',
        'modules/search-results/search-results.module.js',
        'modules/straatbeeld/straatbeeld.module.js',

        'modules/atlas/atlas.module.js',

        'modules/**/*.js',

        'templates.js'
    ],

    plugins: [
      'karma-jasmine',
      'karma-mocha-reporter',
      'karma-coverage',
      'karma-phantomjs-launcher'
    ],

    // level of logging
    // possible values: OFF, ERROR, WARN, INFO, DEBUG
    logLevel: 'ERROR',

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

    // Reporters
    // - dots
    // - progress
    // - junit
    // - growl
    // - coverage
    reporters: ['coverage'],

    preprocessors: {
      // source files, that you wanna generate coverage for
      // do not include tests or libraries
      // (these files will be instrumented by Istanbul)
      'modules/**/!(*.test).js': ['coverage']
    },

    // optionally, configure the reporter
    // type can also be 'cobertura' which should be understand by Jenkins
    coverageReporter: {
      type: 'html',
      dir: 'reports/coverage/'
    },

    // Start these browsers, currently available:
    // - Chrome
    // - ChromeCanary
    // - Firefox
    // - Opera
    // - Safari (only Mac)
    // - PhantomJS
    // - IE (only Windows)
    browsers: ['PhantomJS'],

    // Continuous Integration mode
    // if true, it capture browsers, run tests and exit
    singleRun: true
  });
};
<|endoftext|>


<commit_before>/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var d3 = require('d3');

var Fx = require('../../components/fx');
var dragElement = require('../../components/dragelement');
var setCursor = require('../../lib/setcursor');

var makeDragBox = require('./dragbox').makeDragBox;
var DRAGGERSIZE = require('./constants').DRAGGERSIZE;

exports.initInteractions = function initInteractions(gd) {
    var fullLayout = gd._fullLayout;

    if(gd._context.staticPlot) {
        // this sweeps up more than just cartesian drag elements...
        d3.select(gd).selectAll('.drag').remove();
        return;
    }

    if(!fullLayout._has('cartesian') && !fullLayout._has('gl2d') && !fullLayout._has('splom')) return;

    var subplots = Object.keys(fullLayout._plots || {}).sort(function(a, b) {
        // sort overlays last, then by x axis number, then y axis number
        if((fullLayout._plots[a].mainplot && true) ===
            (fullLayout._plots[b].mainplot && true)) {
            var aParts = a.split('y'),
                bParts = b.split('y');
            return (aParts[0] === bParts[0]) ?
                (Number(aParts[1] || 1) - Number(bParts[1] || 1)) :
                (Number(aParts[0] || 1) - Number(bParts[0] || 1));
        }
        return fullLayout._plots[a].mainplot ? 1 : -1;
    });

    subplots.forEach(function(subplot) {
        var plotinfo = fullLayout._plots[subplot];
        var xa = plotinfo.xaxis;
        var ya = plotinfo.yaxis;

        // main and corner draggers need not be repeated for
        // overlaid subplots - these draggers drag them all
        if(!plotinfo.mainplot) {
            // main dragger goes over the grids and data, so we use its
            // mousemove events for all data hover effects
            var maindrag = makeDragBox(gd, plotinfo, xa._offset, ya._offset,
                xa._length, ya._length, 'ns', 'ew');

            maindrag.onmousemove = function(evt) {
                // This is on `gd._fullLayout`, *not* fullLayout because the reference
                // changes by the time this is called again.
                gd._fullLayout._rehover = function() {
                    if(gd._fullLayout._hoversubplot === subplot) {
                        Fx.hover(gd, evt, subplot);
                    }
                };

                Fx.hover(gd, evt, subplot);

                // Note that we have *not* used the cached fullLayout variable here
                // since that may be outdated when this is called as a callback later on
                gd._fullLayout._lasthover = maindrag;
                gd._fullLayout._hoversubplot = subplot;
            };

            /*
             * IMPORTANT:
             * We must check for the presence of the drag cover here.
             * If we don't, a 'mouseout' event is triggered on the
             * maindrag before each 'click' event, which has the effect
             * of clearing the hoverdata; thus, cancelling the click event.
             */
            maindrag.onmouseout = function(evt) {
                if(gd._dragging) return;

                // When the mouse leaves this maindrag, unset the hovered subplot.
                // This may cause problems if it leaves the subplot directly *onto*
                // another subplot, but that's a tiny corner case at the moment.
                gd._fullLayout._hoversubplot = null;

                dragElement.unhover(gd, evt);
            };

            // corner draggers
            if(gd._context.showAxisDragHandles) {
                makeDragBox(gd, plotinfo, xa._offset - DRAGGERSIZE, ya._offset - DRAGGERSIZE,
                    DRAGGERSIZE, DRAGGERSIZE, 'n', 'w');
                makeDragBox(gd, plotinfo, xa._offset + xa._length, ya._offset - DRAGGERSIZE,
                    DRAGGERSIZE, DRAGGERSIZE, 'n', 'e');
                makeDragBox(gd, plotinfo, xa._offset - DRAGGERSIZE, ya._offset + ya._length,
                    DRAGGERSIZE, DRAGGERSIZE, 's', 'w');
                makeDragBox(gd, plotinfo, xa._offset + xa._length, ya._offset + ya._length,
                    DRAGGERSIZE, DRAGGERSIZE, 's', 'e');
            }
        }
        if(gd._context.showAxisDragHandles) {
            // x axis draggers - if you have overlaid plots,
            // these drag each axis separately
            if(subplot === xa._mainSubplot) {
                // the y position of the main x axis line
                var y0 = xa._mainLinePosition;
                if(xa.side === 'top') y0 -= DRAGGERSIZE;
                makeDragBox(gd, plotinfo, xa._offset + xa._length * 0.1, y0,
                    xa._length * 0.8, DRAGGERSIZE, '', 'ew');
                makeDragBox(gd, plotinfo, xa._offset, y0,
                    xa._length * 0.1, DRAGGERSIZE, '', 'w');
                makeDragBox(gd, plotinfo, xa._offset + xa._length * 0.9, y0,
                    xa._length * 0.1, DRAGGERSIZE, '', 'e');
            }
            // y axis draggers
            if(subplot === ya._mainSubplot) {
                // the x position of the main y axis line
                var x0 = ya._mainLinePosition;
                if(ya.side !== 'right') x0 -= DRAGGERSIZE;
                makeDragBox(gd, plotinfo, x0, ya._offset + ya._length * 0.1,
                    DRAGGERSIZE, ya._length * 0.8, 'ns', '');
                makeDragBox(gd, plotinfo, x0, ya._offset + ya._length * 0.9,
                    DRAGGERSIZE, ya._length * 0.1, 's', '');
                makeDragBox(gd, plotinfo, x0, ya._offset,
                    DRAGGERSIZE, ya._length * 0.1, 'n', '');
            }
        }
    });

    // In case you mousemove over some hovertext, send it to Fx.hover too
    // we do this so that we can put the hover text in front of everything,
    // but still be able to interact with everything as if it isn't there
    var hoverLayer = fullLayout._hoverlayer.node();

    hoverLayer.onmousemove = function(evt) {
        evt.target = gd._fullLayout._lasthover;
        Fx.hover(gd, evt, fullLayout._hoversubplot);
    };

    hoverLayer.onclick = function(evt) {
        evt.target = gd._fullLayout._lasthover;
        Fx.click(gd, evt);
    };

    // also delegate mousedowns... TODO: does this actually work?
    hoverLayer.onmousedown = function(evt) {
        gd._fullLayout._lasthover.onmousedown(evt);
    };

    exports.updateFx(fullLayout);
};

// Minimal set of update needed on 'modebar' edits.
// We only need to update the <g .draglayer> cursor style.
//
// Note that changing the axis configuration and/or the fixedrange attribute
// should trigger a full initInteractions.
exports.updateFx = function(fullLayout) {
    var cursor = fullLayout.dragmode === 'pan' ? 'move' : 'crosshair';
    setCursor(fullLayout._draggers, cursor);
};
<commit_msg>rm old hack that got selection gl2d subplots working<commit_after>/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var d3 = require('d3');

var Fx = require('../../components/fx');
var dragElement = require('../../components/dragelement');
var setCursor = require('../../lib/setcursor');

var makeDragBox = require('./dragbox').makeDragBox;
var DRAGGERSIZE = require('./constants').DRAGGERSIZE;

exports.initInteractions = function initInteractions(gd) {
    var fullLayout = gd._fullLayout;

    if(gd._context.staticPlot) {
        // this sweeps up more than just cartesian drag elements...
        d3.select(gd).selectAll('.drag').remove();
        return;
    }

    if(!fullLayout._has('cartesian') && !fullLayout._has('splom')) return;

    var subplots = Object.keys(fullLayout._plots || {}).sort(function(a, b) {
        // sort overlays last, then by x axis number, then y axis number
        if((fullLayout._plots[a].mainplot && true) ===
            (fullLayout._plots[b].mainplot && true)) {
            var aParts = a.split('y'),
                bParts = b.split('y');
            return (aParts[0] === bParts[0]) ?
                (Number(aParts[1] || 1) - Number(bParts[1] || 1)) :
                (Number(aParts[0] || 1) - Number(bParts[0] || 1));
        }
        return fullLayout._plots[a].mainplot ? 1 : -1;
    });

    subplots.forEach(function(subplot) {
        var plotinfo = fullLayout._plots[subplot];
        var xa = plotinfo.xaxis;
        var ya = plotinfo.yaxis;

        // main and corner draggers need not be repeated for
        // overlaid subplots - these draggers drag them all
        if(!plotinfo.mainplot) {
            // main dragger goes over the grids and data, so we use its
            // mousemove events for all data hover effects
            var maindrag = makeDragBox(gd, plotinfo, xa._offset, ya._offset,
                xa._length, ya._length, 'ns', 'ew');

            maindrag.onmousemove = function(evt) {
                // This is on `gd._fullLayout`, *not* fullLayout because the reference
                // changes by the time this is called again.
                gd._fullLayout._rehover = function() {
                    if(gd._fullLayout._hoversubplot === subplot) {
                        Fx.hover(gd, evt, subplot);
                    }
                };

                Fx.hover(gd, evt, subplot);

                // Note that we have *not* used the cached fullLayout variable here
                // since that may be outdated when this is called as a callback later on
                gd._fullLayout._lasthover = maindrag;
                gd._fullLayout._hoversubplot = subplot;
            };

            /*
             * IMPORTANT:
             * We must check for the presence of the drag cover here.
             * If we don't, a 'mouseout' event is triggered on the
             * maindrag before each 'click' event, which has the effect
             * of clearing the hoverdata; thus, cancelling the click event.
             */
            maindrag.onmouseout = function(evt) {
                if(gd._dragging) return;

                // When the mouse leaves this maindrag, unset the hovered subplot.
                // This may cause problems if it leaves the subplot directly *onto*
                // another subplot, but that's a tiny corner case at the moment.
                gd._fullLayout._hoversubplot = null;

                dragElement.unhover(gd, evt);
            };

            // corner draggers
            if(gd._context.showAxisDragHandles) {
                makeDragBox(gd, plotinfo, xa._offset - DRAGGERSIZE, ya._offset - DRAGGERSIZE,
                    DRAGGERSIZE, DRAGGERSIZE, 'n', 'w');
                makeDragBox(gd, plotinfo, xa._offset + xa._length, ya._offset - DRAGGERSIZE,
                    DRAGGERSIZE, DRAGGERSIZE, 'n', 'e');
                makeDragBox(gd, plotinfo, xa._offset - DRAGGERSIZE, ya._offset + ya._length,
                    DRAGGERSIZE, DRAGGERSIZE, 's', 'w');
                makeDragBox(gd, plotinfo, xa._offset + xa._length, ya._offset + ya._length,
                    DRAGGERSIZE, DRAGGERSIZE, 's', 'e');
            }
        }
        if(gd._context.showAxisDragHandles) {
            // x axis draggers - if you have overlaid plots,
            // these drag each axis separately
            if(subplot === xa._mainSubplot) {
                // the y position of the main x axis line
                var y0 = xa._mainLinePosition;
                if(xa.side === 'top') y0 -= DRAGGERSIZE;
                makeDragBox(gd, plotinfo, xa._offset + xa._length * 0.1, y0,
                    xa._length * 0.8, DRAGGERSIZE, '', 'ew');
                makeDragBox(gd, plotinfo, xa._offset, y0,
                    xa._length * 0.1, DRAGGERSIZE, '', 'w');
                makeDragBox(gd, plotinfo, xa._offset + xa._length * 0.9, y0,
                    xa._length * 0.1, DRAGGERSIZE, '', 'e');
            }
            // y axis draggers
            if(subplot === ya._mainSubplot) {
                // the x position of the main y axis line
                var x0 = ya._mainLinePosition;
                if(ya.side !== 'right') x0 -= DRAGGERSIZE;
                makeDragBox(gd, plotinfo, x0, ya._offset + ya._length * 0.1,
                    DRAGGERSIZE, ya._length * 0.8, 'ns', '');
                makeDragBox(gd, plotinfo, x0, ya._offset + ya._length * 0.9,
                    DRAGGERSIZE, ya._length * 0.1, 's', '');
                makeDragBox(gd, plotinfo, x0, ya._offset,
                    DRAGGERSIZE, ya._length * 0.1, 'n', '');
            }
        }
    });

    // In case you mousemove over some hovertext, send it to Fx.hover too
    // we do this so that we can put the hover text in front of everything,
    // but still be able to interact with everything as if it isn't there
    var hoverLayer = fullLayout._hoverlayer.node();

    hoverLayer.onmousemove = function(evt) {
        evt.target = gd._fullLayout._lasthover;
        Fx.hover(gd, evt, fullLayout._hoversubplot);
    };

    hoverLayer.onclick = function(evt) {
        evt.target = gd._fullLayout._lasthover;
        Fx.click(gd, evt);
    };

    // also delegate mousedowns... TODO: does this actually work?
    hoverLayer.onmousedown = function(evt) {
        gd._fullLayout._lasthover.onmousedown(evt);
    };

    exports.updateFx(fullLayout);
};

// Minimal set of update needed on 'modebar' edits.
// We only need to update the <g .draglayer> cursor style.
//
// Note that changing the axis configuration and/or the fixedrange attribute
// should trigger a full initInteractions.
exports.updateFx = function(fullLayout) {
    var cursor = fullLayout.dragmode === 'pan' ? 'move' : 'crosshair';
    setCursor(fullLayout._draggers, cursor);
};
<|endoftext|>


<commit_before>'use strict';

/**
 */
angular.module('openolitor-admin')
  .controller('OpenOlitorRootController', ['$scope', '$rootScope',
    'ServerService', 'ProjektService', 'gettextCatalog', 'amMoment',
    '$location', 'msgBus', 'checkSize', '$window', '$timeout', 'BUILD_NR',
    'appConfig', 'cssInjector', '$route',
    'ooAuthService', '$cookies', 'moment', 'dialogService', 'alertService','tmhDynamicLocale','uiDatetimePickerConfig', 'dateTimePickerValues',
    function($scope, $rootScope, ServerService, ProjektService,
      gettextCatalog, amMoment, $location, msgBus, checkSize, $window,
      $timeout, BUILD_NR, appConfig, cssInjector, $route,
      ooAuthService, $cookies, moment, dialogService, alertService, tmhDynamicLocale,uiDatetimePickerConfig, dateTimePickerValues) {
      angular.element($window).bind('resize', function() {
        checkSize();
      });

      $rootScope.viewId = 'Init';
      $scope.welcomeMessageDisplayed = false;

      $scope.currentPathContains = function(pathJunk) {
        var currentUrl = $location.url();
        if(currentUrl.indexOf('?') !== -1) {
          return currentUrl.indexOf('/' + pathJunk + '?') !== -1;
        } else {
          return currentUrl === ('/' + pathJunk) || currentUrl.indexOf('/' + pathJunk + '/') !== -1;
        }
      };

      $scope.getCurrentViewId = function() {
        return $rootScope.viewId;
      };

      $scope.loadedProjectLoggedInOnce = false;
      $scope.loaded = false;

      //initial launch
      checkSize();

      $rootScope.translateCalendar = function(){
        uiDatetimePickerConfig.buttonBar.close.text = gettextCatalog.getString(dateTimePickerValues.close);
        uiDatetimePickerConfig.buttonBar.clear.text = gettextCatalog.getString(dateTimePickerValues.clear);
        uiDatetimePickerConfig.buttonBar.now.text = gettextCatalog.getString(dateTimePickerValues.now);
        uiDatetimePickerConfig.buttonBar.today.text = gettextCatalog.getString(dateTimePickerValues.today);
        uiDatetimePickerConfig.buttonBar.date.text = gettextCatalog.getString(dateTimePickerValues.date);
        uiDatetimePickerConfig.buttonBar.time.text = gettextCatalog.getString(dateTimePickerValues.time);
        uiDatetimePickerConfig.buttonBar.cancel.text = gettextCatalog.getString(dateTimePickerValues.cancel);
      }

      $scope.connected = false;
      $scope.showConnectionErrorMessage = false;

      var unwatchLoggedIn = $scope.$watch(function() {
        return ooAuthService.getUser();
      }, function(user) {
        $scope.loggedIn = ooAuthService.isUserLoggedIn(user);
        $scope.user = user;
        $scope.unwatchStaticServerInfo = $scope.$watch(ServerService.getStaticServerInfo,
          function(info) {
            if (!angular.isUndefined(info)) {
              $scope.serverInfo = info;
              $scope.connected = true;
            }
          });
        if ($scope.loggedIn) {
          //$scope.secondFactorType = ooAuthService.getSecondFactorType();
          ProjektService.resolveProjekt(false, !$scope.loadedProjectLoggedInOnce).then(function(projekt) {
            $scope.loadedProjectLoggedInOnce = true;
            $scope.projekt = projekt;
            $rootScope.projekt = projekt;
            $scope.checkWelcomeMessage();
          });
        } else {
          ProjektService.resolveProjekt(true).then(function(projekt) {
            $scope.projekt = projekt;
            $rootScope.projekt = projekt;
          });
        }
      });

      $timeout(function() {
        $scope.menushow[angular.element('.sidebar-nav .active').parent()
          .attr(
            'activate-id')] = true;
      }, 1);

      $scope.buildNr = BUILD_NR;
      $scope.sendStats = false;

      $scope.loadAppConfig = function(count) {
        if(appConfig.isLoaded()) {
          $scope.env = appConfig.get().ENV;
          $scope.version = appConfig.get().version;
          $scope.API_URL = appConfig.get().API_URL;
          $scope.sendStats = appConfig.get().sendStats;
          $scope.loaded = true;
          ServerService.initialize();

        } else {
          if(count < 100) {
            $timeout(function() {
              $scope.loadAppConfig(count++);
            }, 100);
          }
        }
      };

      $scope.loadAppConfig(0);

      msgBus.onMsg('WebSocketClosed', $rootScope, function(event, msg) {
        $scope.connected = false;
        $scope.messagingSocketClosedReason = msg.reason;
        if (angular.isUndefined($scope.messagingSocketClosedSetter)) {
          $scope.messagingSocketClosedSetter = $timeout(function() {
            $scope.showConnectionErrorMessage = true;
            $scope.messagingSocketClosedSetter = undefined;
          }, 30000);
        }
        $scope.$apply();
      });

      msgBus.onMsg('WebSocketOpen', $rootScope, function() {
        $scope.connected = true;
        $scope.showConnectionErrorMessage = false;
        if (!angular.isUndefined($scope.messagingSocketClosedSetter) &&
          !angular.isUndefined($scope.messagingSocketClosedSetter.close)) {
          $scope.messagingSocketClosedSetter.close();
          $scope.messagingSocketClosedSetter = undefined;
        }
        $scope.messagingSocketClosedReason = '';
        $scope.$apply();
      });

      $scope.changeLang = function(lang) {
        if (!angular.isUndefined(lang)) {

          msgBus.emitMsg({
            type: 'ChangeLang',
            reason: lang
          });
          $scope.storeActiveLang(lang);
          tmhDynamicLocale.set(lang);
          $scope.$emit('languageChanged');
          moment.locale(lang);
          $rootScope.translateCalendar();
        }
      };

      msgBus.onMsg('ChangeLang', $rootScope, function(event, msg) {
        gettextCatalog.setCurrentLanguage(msg.reason);
      });

      $scope.displayActiveLang = function() {
        switch(gettextCatalog.getCurrentLanguage()){
          case 'en_US': return 'en';
          case 'cs_CZ': return 'cs';
          case 'es_ES': return 'es';
          case 'hu_HU': return 'hu';
          default: return(gettextCatalog.getCurrentLanguage());
        }
      };

      $scope.activeLang = function() {
        return gettextCatalog.getCurrentLanguage();
      };

      $scope.storedActiveLang = function() {
        return $cookies.get('activeLang');
      };

      $scope.storeActiveLang = function(lang) {
        var expireDate = new Date();
        expireDate.setDate(expireDate.getDate() + 3650);
        $cookies.put('activeLang', lang, {'expires':expireDate});
      };

      if (angular.isUndefined($scope.storedActiveLang())) {
        var lang = $window.navigator.language || $window.navigator.userLanguage;
        if (lang.startsWith('de-CH')) {
          $scope.changeLang('de_CH');
        } else if (lang.startsWith('de-DE')) {
          $scope.changeLang('de_DE');
        } else if (lang.startsWith('de-DO')) {
          $scope.changeLang('de_DO');
        } else if (lang.startsWith('de')) {
          $scope.changeLang('de_DE');
        } else if (lang.startsWith('fr-BE')) {
          $scope.changeLang('fr_BE');
        } else if (lang.startsWith('fr-CH')) {
          $scope.changeLang('fr_CH');
        } else if (lang.startsWith('fr')) {
          $scope.changeLang('fr_CH');
        } else if (lang.startsWith('en')) {
          $scope.changeLang('en');
        } else if (lang.startsWith('es')) {
          $scope.changeLang('es');
        } else if (lang.startsWith('cs')) {
          $scope.changeLang('cs');
        } else if (lang.startsWith('hu')) {
          $scope.changeLang('hu');
        } else {
          $scope.changeLang('en');
        }
      } else {
        $scope.changeLang($scope.storedActiveLang());
      }

      $scope.checkWelcomeMessage = function() {
        if ($scope.projekt.welcomeMessage2 && !$scope.welcomeMessageDisplayed) {
          $scope.welcomeMessageDisplayed = true;
          dialogService.displayDialogOkAbort(
            $scope.projekt.welcomeMessage2,
            function() {},
            'Mitteilung',
            true,
            'Schliessen'
          );
        }
      };

      $rootScope.$on('$routeChangeStart', function (event, next, prev) {
        alertService.clearAll();
      });

      $scope.$on('destroy', function() {
        unwatchLoggedIn();
        if($scope.unwatchStaticServerInfo) {
          $scope.unwatchStaticServerInfo();
        }
      });

      cssInjector.add(appConfig.get().API_URL + 'ressource/style/admin');
    }
  ]);
<commit_msg>removed warnings<commit_after>'use strict';

/**
 */
angular.module('openolitor-admin')
  .controller('OpenOlitorRootController', ['$scope', '$rootScope',
    'ServerService', 'ProjektService', 'gettextCatalog', 'amMoment',
    '$location', 'msgBus', 'checkSize', '$window', '$timeout', 'BUILD_NR',
    'appConfig', 'cssInjector', '$route',
    'ooAuthService', '$cookies', 'moment', 'dialogService', 'alertService','tmhDynamicLocale','uiDatetimePickerConfig', 'dateTimePickerValues',
    function($scope, $rootScope, ServerService, ProjektService,
      gettextCatalog, amMoment, $location, msgBus, checkSize, $window,
      $timeout, BUILD_NR, appConfig, cssInjector, $route,
      ooAuthService, $cookies, moment, dialogService, alertService, tmhDynamicLocale,uiDatetimePickerConfig, dateTimePickerValues) {
      angular.element($window).bind('resize', function() {
        checkSize();
      });

      $rootScope.viewId = 'Init';
      $scope.welcomeMessageDisplayed = false;

      $scope.currentPathContains = function(pathJunk) {
        var currentUrl = $location.url();
        if(currentUrl.indexOf('?') !== -1) {
          return currentUrl.indexOf('/' + pathJunk + '?') !== -1;
        } else {
          return currentUrl === ('/' + pathJunk) || currentUrl.indexOf('/' + pathJunk + '/') !== -1;
        }
      };

      $scope.getCurrentViewId = function() {
        return $rootScope.viewId;
      };

      $scope.loadedProjectLoggedInOnce = false;
      $scope.loaded = false;

      //initial launch
      checkSize();

      $rootScope.translateCalendar = function(){
        uiDatetimePickerConfig.buttonBar.close.text = gettextCatalog.getString(dateTimePickerValues.close);
        uiDatetimePickerConfig.buttonBar.clear.text = gettextCatalog.getString(dateTimePickerValues.clear);
        uiDatetimePickerConfig.buttonBar.now.text = gettextCatalog.getString(dateTimePickerValues.now);
        uiDatetimePickerConfig.buttonBar.today.text = gettextCatalog.getString(dateTimePickerValues.today);
        uiDatetimePickerConfig.buttonBar.date.text = gettextCatalog.getString(dateTimePickerValues.date);
        uiDatetimePickerConfig.buttonBar.time.text = gettextCatalog.getString(dateTimePickerValues.time);
        uiDatetimePickerConfig.buttonBar.cancel.text = gettextCatalog.getString(dateTimePickerValues.cancel);
      };

      $scope.connected = false;
      $scope.showConnectionErrorMessage = false;

      var unwatchLoggedIn = $scope.$watch(function() {
        return ooAuthService.getUser();
      }, function(user) {
        $scope.loggedIn = ooAuthService.isUserLoggedIn(user);
        $scope.user = user;
        $scope.unwatchStaticServerInfo = $scope.$watch(ServerService.getStaticServerInfo,
          function(info) {
            if (!angular.isUndefined(info)) {
              $scope.serverInfo = info;
              $scope.connected = true;
            }
          });
        if ($scope.loggedIn) {
          //$scope.secondFactorType = ooAuthService.getSecondFactorType();
          ProjektService.resolveProjekt(false, !$scope.loadedProjectLoggedInOnce).then(function(projekt) {
            $scope.loadedProjectLoggedInOnce = true;
            $scope.projekt = projekt;
            $rootScope.projekt = projekt;
            $scope.checkWelcomeMessage();
          });
        } else {
          ProjektService.resolveProjekt(true).then(function(projekt) {
            $scope.projekt = projekt;
            $rootScope.projekt = projekt;
          });
        }
      });

      $timeout(function() {
        $scope.menushow[angular.element('.sidebar-nav .active').parent()
          .attr(
            'activate-id')] = true;
      }, 1);

      $scope.buildNr = BUILD_NR;
      $scope.sendStats = false;

      $scope.loadAppConfig = function(count) {
        if(appConfig.isLoaded()) {
          $scope.env = appConfig.get().ENV;
          $scope.version = appConfig.get().version;
          $scope.API_URL = appConfig.get().API_URL;
          $scope.sendStats = appConfig.get().sendStats;
          $scope.loaded = true;
          ServerService.initialize();

        } else {
          if(count < 100) {
            $timeout(function() {
              $scope.loadAppConfig(count++);
            }, 100);
          }
        }
      };

      $scope.loadAppConfig(0);

      msgBus.onMsg('WebSocketClosed', $rootScope, function(event, msg) {
        $scope.connected = false;
        $scope.messagingSocketClosedReason = msg.reason;
        if (angular.isUndefined($scope.messagingSocketClosedSetter)) {
          $scope.messagingSocketClosedSetter = $timeout(function() {
            $scope.showConnectionErrorMessage = true;
            $scope.messagingSocketClosedSetter = undefined;
          }, 30000);
        }
        $scope.$apply();
      });

      msgBus.onMsg('WebSocketOpen', $rootScope, function() {
        $scope.connected = true;
        $scope.showConnectionErrorMessage = false;
        if (!angular.isUndefined($scope.messagingSocketClosedSetter) &&
          !angular.isUndefined($scope.messagingSocketClosedSetter.close)) {
          $scope.messagingSocketClosedSetter.close();
          $scope.messagingSocketClosedSetter = undefined;
        }
        $scope.messagingSocketClosedReason = '';
        $scope.$apply();
      });

      $scope.changeLang = function(lang) {
        if (!angular.isUndefined(lang)) {

          msgBus.emitMsg({
            type: 'ChangeLang',
            reason: lang
          });
          $scope.storeActiveLang(lang);
          tmhDynamicLocale.set(lang);
          $scope.$emit('languageChanged');
          moment.locale(lang);
          $rootScope.translateCalendar();
        }
      };

      msgBus.onMsg('ChangeLang', $rootScope, function(event, msg) {
        gettextCatalog.setCurrentLanguage(msg.reason);
      });

      $scope.displayActiveLang = function() {
        switch(gettextCatalog.getCurrentLanguage()){
          case 'en_US': return 'en';
          case 'cs_CZ': return 'cs';
          case 'es_ES': return 'es';
          case 'hu_HU': return 'hu';
          default: return(gettextCatalog.getCurrentLanguage());
        }
      };

      $scope.activeLang = function() {
        return gettextCatalog.getCurrentLanguage();
      };

      $scope.storedActiveLang = function() {
        return $cookies.get('activeLang');
      };

      $scope.storeActiveLang = function(lang) {
        var expireDate = new Date();
        expireDate.setDate(expireDate.getDate() + 3650);
        $cookies.put('activeLang', lang, {'expires':expireDate});
      };

      if (angular.isUndefined($scope.storedActiveLang())) {
        var lang = $window.navigator.language || $window.navigator.userLanguage;
        if (lang.startsWith('de-CH')) {
          $scope.changeLang('de_CH');
        } else if (lang.startsWith('de-DE')) {
          $scope.changeLang('de_DE');
        } else if (lang.startsWith('de-DO')) {
          $scope.changeLang('de_DO');
        } else if (lang.startsWith('de')) {
          $scope.changeLang('de_DE');
        } else if (lang.startsWith('fr-BE')) {
          $scope.changeLang('fr_BE');
        } else if (lang.startsWith('fr-CH')) {
          $scope.changeLang('fr_CH');
        } else if (lang.startsWith('fr')) {
          $scope.changeLang('fr_CH');
        } else if (lang.startsWith('en')) {
          $scope.changeLang('en');
        } else if (lang.startsWith('es')) {
          $scope.changeLang('es');
        } else if (lang.startsWith('cs')) {
          $scope.changeLang('cs');
        } else if (lang.startsWith('hu')) {
          $scope.changeLang('hu');
        } else {
          $scope.changeLang('en');
        }
      } else {
        $scope.changeLang($scope.storedActiveLang());
      }

      $scope.checkWelcomeMessage = function() {
        if ($scope.projekt.welcomeMessage2 && !$scope.welcomeMessageDisplayed) {
          $scope.welcomeMessageDisplayed = true;
          dialogService.displayDialogOkAbort(
            $scope.projekt.welcomeMessage2,
            function() {},
            'Mitteilung',
            true,
            'Schliessen'
          );
        }
      };

      $rootScope.$on('$routeChangeStart', function () { // event, next, prev) {
        alertService.clearAll();
      });

      $scope.$on('destroy', function() {
        unwatchLoggedIn();
        if($scope.unwatchStaticServerInfo) {
          $scope.unwatchStaticServerInfo();
        }
      });

      cssInjector.add(appConfig.get().API_URL + 'ressource/style/admin');
    }
  ]);
<|endoftext|>