<commit_before>import Bluebird from 'bluebird';
import createDebug from 'debug';
import { DepGraph } from 'dependency-graph';
import glob from 'glob';
import { attempt, defaults, set } from 'lodash';

import Component from './component';

const debug = createDebug('app-container');
const PLUGIN = /^(all|any)!.+/g;

export default class Container {
  /**
   * Constructor function
   * @param  {Object} [options={}]
   * @param  {String} options.namespace - namespace key
   * @param  {Object} options.defaults - default module options
   * @return {Container}
   */
  constructor(options = {}) {
    this.registry = {};
    this.options = options;
  }

  /**
   * adapted from http://stackoverflow.com/questions/16697791/nodejs-get-filename-of-caller-function
   * @return {String|Undefined}
   * @private
   */
  static _getCallerFile() {
    try {
      const err = new Error();
      const currentfile = err.stack.shift().getFileName();
      let callerfile;
      while (err.stack.length) {
        callerfile = err.stack.shift().getFileName();
        if (currentfile !== callerfile) return callerfile;
      }
    } catch (err) {
      return undefined;
    }
    return undefined;
  }

  /**
   * Register modules that match the specified pattern
   * @param  {String} pattern - glob pattern, see glob.js
   * @param  {Object} options
   * @param  {String} options.dir - the top level directory
   */
  glob(pattern, options = {}) {
    if (!options.dir) {
      throw new Error('Missing required \'dir\' option');
    }
    const opts = Object.assign({}, options, { cwd: options.dir });
    const filenames = glob.sync(pattern, opts);
    const namespace = this.options.namespace || 'inject';
    const caller = Container._getCallerFile();
    filenames.forEach((filename) => {
      if (`${opts.dir}/${filename}` === caller) {
        debug(`ignoring calling file: ${filename}`);
        return null;
      }
      debug(`registering component: ${filename}`);
      const result = attempt(() => {
        this._register({ filename, namespace, options: opts });
      });
      if (result instanceof Error) {
        debug(`error registering component: ${filename}`);
      }
      return null;
    });
    this._validateDependencyGraph();
  }

  /**
   * Load one or more modules
   * @example Load a single component
   *  container.load('my-module')
   *  .then((myModule) => {
   *    // ..
   *  });
   *
   * @example Load multiple components
   *  container.load('my-module', 'my-other-module')
   *  .spread((myModule, myOtherModule) => {
   *    // ..
   *  });
   *
   * @example Load in groups
   *  container.load({
   *    services: {
   *      foo: 'services/foo',
   *      bar: 'services/bar',
   *    },
   *    models: {
   *      users: 'models/users',
   *      comments: 'models/comments',
   *    },
   *  })
   *  .then(({ services, models }) => {
   *    const { foo, bar } = services;
   *    const { users, comments } = models;
   *  });
   * @param  {...String|Object} components - components to load
   * @return {Bluebird}
   */
  load(...components) {
    return Bluebird.try(() => {
      if (components.length === 1 && typeof components[0] === 'string') {
        return this._load(components[0]);
      } else if (components.length === 1 && typeof components[0] === 'object') {
        return this._loadRecursive(components[0]);
      } else if (Array.isArray(components)) {
        return Bluebird.mapSeries(components, name => this._load(name));
      }
      throw new Error('Invalid load signature');
    });
  }

  /**
   * Load a single component by name
   * @param  {String} name
   * @return {Bluebird}
   * @private
   */
  _load(name) {
    return Bluebird.try(() => {
      if (PLUGIN.test(name)) {
        const [plugin, n] = name.split('!');
        switch (plugin) {
          case 'all':
            return this._loadAll(n);
          case 'any':
            return this._loadAny(n);
          default:
            throw new Error(`Unknown plugin ${plugin}`);
        }
      }
      const component = this.registry[name];
      if (!component) {
        throw new Error(`Unknown Component: ${name}`);
      }
      return component.load(this);
    });
  }

  /**
   * Load all components matching a given pattern into a dependency object
   * @param  {String} pattern
   * @return {Bluebird}
   * @private
   */
  _loadAll(pattern) {
    const re = new RegExp(pattern);
    const matches = Object.keys(this.registry).reduce((memo, name) => {
      /* eslint-disable no-param-reassign */
      if (re.test(name)) {
        memo[name] = name;
      }
      return memo;
    }, {});
    return this._loadRecursive(matches);
  }

  /**
   * Load any components matching a given pattern into an array of dependencies
   * @param  {String} pattern
   * @return {Bluebird}
   * @private
   */
  _loadAny(pattern) {
    return this._loadAll(pattern)
    .then(deps => Object.keys(deps).reduce((memo, name) => [...memo, deps[name]], []));
  }

  /**
   * Load a component map (recursively) where string values are replaced with their
   * respective components
   * @param  {Object} map
   * @param  {Object} [accum={}] - object to assign components to
   * @return {Bluebird}
   * @private
   */
  _loadRecursive(map, accum = {}) {
    return _loadRecursive(this, map, accum);
  }

  /**
   * Register a module with the container
   * @param  {String} filename
   * @return {Function}
   * @private
   */
  _register({ filename, namespace, options }) {
    const mod = require(`${options.dir}/${filename}`); // eslint-disable-line
    let main = mod;
    if (mod.__esModule && mod.default) {
      main = mod.default;
    }
    if (mod[namespace]) {
      this._registerNamespaced({ filename, main, mod, namespace });
    } else {
      debug(`No namespace found for component, skipping: ${filename}`);
    }
    return null;
  }

  /**
   * Register a given component for modules that declare themselves via the namespaced
   * declaration style
   * @param  {Object} params
   * @param  {String} params.filename
   * @param  {*} params.main
   * @param  {Object|Function} params.mod
   * @param  {String} params.namespace
   * @private
   */
  _registerNamespaced({ filename, main, mod, namespace }) {
    let component;
    if (typeof mod[namespace] === 'function') {
      const register = this._register(filename);
      mod[namespace](register);
    } else {
      const options = mod[namespace];
      defaults(options, this.options.defaults || {});
      component = new Component({ filename, mod: main, options });
      this.registry[component.name] = component;
    }
  }

  /**
   * Build a dependency graph for all registered modules and ensure that a) there
   * are no circular dependencies and b) there are no missing modules
   * @private
   */
  _validateDependencyGraph() {
    // create a new dependency graph
    const graph = new DepGraph();

    // for every component in the registry, add each to the graph along along
    // with declaring its dependencies
    Object.keys(this.registry).forEach((name) => {
      const { options } = this.registry[name];
      if (!graph.hasNode(name)) {
        graph.addNode(name);
      }
      if (options.require) {
        if (Array.isArray(options.require)) {
          options.require.forEach((dep) => {
            if (PLUGIN.test(dep)) {
              return;
            }
            if (!graph.hasNode(dep)) {
              graph.addNode(dep);
            }
            graph.addDependency(name, dep);
          });
        } else if (typeof options.require === 'object') {
          _recursiveDeps(graph, name, options.require);
        }
      }
    });

    // ensure no circular dependencies and that we have a component registered
    // for every node in the graph
    const overallOrder = graph.overallOrder();
    overallOrder.forEach((name) => {
      if (!(this.registry[name] instanceof Component)) {
        throw new Error(`No component found for dependency (${name})`);
      }
    });
  }
}

/**
 * Recursively load a component map
 * @param  {Container} container
 * @param  {Object} map
 * @param  {Object} [accum={}]
 * @return {Bluebird}
 * @private
 */
function _loadRecursive(container, map, accum = {}) {
  return Bluebird.reduce(Object.keys(map), (memo, key) => {
    const path = map[key];
    if (typeof path === 'string') {
      return container._load(path)
      .then((mod) => {
        set(memo, key, mod);
        return memo;
      });
    }
    return _loadRecursive(container, path)
    .then((mods) => {
      set(memo, key, mods);
      return memo;
    });
  }, accum);
}

/**
 * Add recursive dependencies to dependency graph
 * @param  {DepGraph} graph
 * @param  {String} name - current node name
 * @param  {Object} deps - dependency map
 * @private
 */
function _recursiveDeps(graph, name, deps) {
  return Object.keys(deps).forEach((key) => {
    const dep = deps[key];
    if (PLUGIN.test(dep)) {
      return;
    }
    if (typeof dep === 'string') {
      if (!graph.hasNode(dep)) {
        graph.addNode(dep);
      }
      graph.addDependency(name, dep);
    } else if (typeof dep === 'object') {
      _recursiveDeps(graph, name, deps[key]);
    }
  });
}
<commit_msg>fix: remove last remaining remnants of legacy declaration style<commit_after>import Bluebird from 'bluebird';
import createDebug from 'debug';
import { DepGraph } from 'dependency-graph';
import glob from 'glob';
import { attempt, defaults, set } from 'lodash';

import Component from './component';

const debug = createDebug('app-container');
const PLUGIN = /^(all|any)!.+/g;

export default class Container {
  /**
   * Constructor function
   * @param  {Object} [options={}]
   * @param  {String} options.namespace - namespace key
   * @param  {Object} options.defaults - default module options
   * @return {Container}
   */
  constructor(options = {}) {
    this.registry = {};
    this.options = options;
  }

  /**
   * adapted from http://stackoverflow.com/questions/16697791/nodejs-get-filename-of-caller-function
   * @return {String|Undefined}
   * @private
   */
  static _getCallerFile() {
    try {
      const err = new Error();
      const currentfile = err.stack.shift().getFileName();
      let callerfile;
      while (err.stack.length) {
        callerfile = err.stack.shift().getFileName();
        if (currentfile !== callerfile) return callerfile;
      }
    } catch (err) {
      return undefined;
    }
    return undefined;
  }

  /**
   * Register modules that match the specified pattern
   * @param  {String} pattern - glob pattern, see glob.js
   * @param  {Object} options
   * @param  {String} options.dir - the top level directory
   */
  glob(pattern, options = {}) {
    if (!options.dir) {
      throw new Error('Missing required \'dir\' option');
    }
    const opts = Object.assign({}, options, { cwd: options.dir });
    const filenames = glob.sync(pattern, opts);
    const namespace = this.options.namespace || 'inject';
    const caller = Container._getCallerFile();
    filenames.forEach((filename) => {
      if (`${opts.dir}/${filename}` === caller) {
        debug(`ignoring calling file: ${filename}`);
        return null;
      }
      debug(`registering component: ${filename}`);
      const result = attempt(() => {
        this._register({ filename, namespace, options: opts });
      });
      if (result instanceof Error) {
        debug(`error registering component: ${filename}`);
      }
      return null;
    });
    this._validateDependencyGraph();
  }

  /**
   * Load one or more modules
   * @example Load a single component
   *  container.load('my-module')
   *  .then((myModule) => {
   *    // ..
   *  });
   *
   * @example Load multiple components
   *  container.load('my-module', 'my-other-module')
   *  .spread((myModule, myOtherModule) => {
   *    // ..
   *  });
   *
   * @example Load in groups
   *  container.load({
   *    services: {
   *      foo: 'services/foo',
   *      bar: 'services/bar',
   *    },
   *    models: {
   *      users: 'models/users',
   *      comments: 'models/comments',
   *    },
   *  })
   *  .then(({ services, models }) => {
   *    const { foo, bar } = services;
   *    const { users, comments } = models;
   *  });
   * @param  {...String|Object} components - components to load
   * @return {Bluebird}
   */
  load(...components) {
    return Bluebird.try(() => {
      if (components.length === 1 && typeof components[0] === 'string') {
        return this._load(components[0]);
      } else if (components.length === 1 && typeof components[0] === 'object') {
        return this._loadRecursive(components[0]);
      } else if (Array.isArray(components)) {
        return Bluebird.mapSeries(components, name => this._load(name));
      }
      throw new Error('Invalid load signature');
    });
  }

  /**
   * Load a single component by name
   * @param  {String} name
   * @return {Bluebird}
   * @private
   */
  _load(name) {
    return Bluebird.try(() => {
      if (PLUGIN.test(name)) {
        const [plugin, n] = name.split('!');
        switch (plugin) {
          case 'all':
            return this._loadAll(n);
          case 'any':
            return this._loadAny(n);
          default:
            throw new Error(`Unknown plugin ${plugin}`);
        }
      }
      const component = this.registry[name];
      if (!component) {
        throw new Error(`Unknown Component: ${name}`);
      }
      return component.load(this);
    });
  }

  /**
   * Load all components matching a given pattern into a dependency object
   * @param  {String} pattern
   * @return {Bluebird}
   * @private
   */
  _loadAll(pattern) {
    const re = new RegExp(pattern);
    const matches = Object.keys(this.registry).reduce((memo, name) => {
      /* eslint-disable no-param-reassign */
      if (re.test(name)) {
        memo[name] = name;
      }
      return memo;
    }, {});
    return this._loadRecursive(matches);
  }

  /**
   * Load any components matching a given pattern into an array of dependencies
   * @param  {String} pattern
   * @return {Bluebird}
   * @private
   */
  _loadAny(pattern) {
    return this._loadAll(pattern)
    .then(deps => Object.keys(deps).reduce((memo, name) => [...memo, deps[name]], []));
  }

  /**
   * Load a component map (recursively) where string values are replaced with their
   * respective components
   * @param  {Object} map
   * @param  {Object} [accum={}] - object to assign components to
   * @return {Bluebird}
   * @private
   */
  _loadRecursive(map, accum = {}) {
    return _loadRecursive(this, map, accum);
  }

  /**
   * Register a module with the container
   * @param  {String} filename
   * @return {Function}
   * @private
   */
  _register({ filename, namespace, options }) {
    const mod = require(`${options.dir}/${filename}`); // eslint-disable-line
    let main = mod;
    if (mod.__esModule && mod.default) {
      main = mod.default;
    }
    if (mod[namespace]) {
      this._registerNamespaced({ filename, main, mod, namespace });
    } else {
      debug(`No namespace found for component, skipping: ${filename}`);
    }
    return null;
  }

  /**
   * Register a given component for modules that declare themselves via the namespaced
   * declaration style
   * @param  {Object} params
   * @param  {String} params.filename
   * @param  {*} params.main
   * @param  {Object|Function} params.mod
   * @param  {String} params.namespace
   * @private
   */
  _registerNamespaced({ filename, main, mod, namespace }) {
    if (!(typeof mod[namespace] === 'object' && !Array.isArray(mod[namespace]))) {
      throw new Error(`Invalid namespace declaration found for component: ${filename}`);
    }
    const options = mod[namespace];
    defaults(options, this.options.defaults || {});
    const component = new Component({ filename, mod: main, options });
    this.registry[component.name] = component;
  }

  /**
   * Build a dependency graph for all registered modules and ensure that a) there
   * are no circular dependencies and b) there are no missing modules
   * @private
   */
  _validateDependencyGraph() {
    // create a new dependency graph
    const graph = new DepGraph();

    // for every component in the registry, add each to the graph along along
    // with declaring its dependencies
    Object.keys(this.registry).forEach((name) => {
      const { options } = this.registry[name];
      if (!graph.hasNode(name)) {
        graph.addNode(name);
      }
      if (options.require) {
        if (Array.isArray(options.require)) {
          options.require.forEach((dep) => {
            if (PLUGIN.test(dep)) {
              return;
            }
            if (!graph.hasNode(dep)) {
              graph.addNode(dep);
            }
            graph.addDependency(name, dep);
          });
        } else if (typeof options.require === 'object') {
          _recursiveDeps(graph, name, options.require);
        }
      }
    });

    // ensure no circular dependencies and that we have a component registered
    // for every node in the graph
    const overallOrder = graph.overallOrder();
    overallOrder.forEach((name) => {
      if (!(this.registry[name] instanceof Component)) {
        throw new Error(`No component found for dependency (${name})`);
      }
    });
  }
}

/**
 * Recursively load a component map
 * @param  {Container} container
 * @param  {Object} map
 * @param  {Object} [accum={}]
 * @return {Bluebird}
 * @private
 */
function _loadRecursive(container, map, accum = {}) {
  return Bluebird.reduce(Object.keys(map), (memo, key) => {
    const path = map[key];
    if (typeof path === 'string') {
      return container._load(path)
      .then((mod) => {
        set(memo, key, mod);
        return memo;
      });
    }
    return _loadRecursive(container, path)
    .then((mods) => {
      set(memo, key, mods);
      return memo;
    });
  }, accum);
}

/**
 * Add recursive dependencies to dependency graph
 * @param  {DepGraph} graph
 * @param  {String} name - current node name
 * @param  {Object} deps - dependency map
 * @private
 */
function _recursiveDeps(graph, name, deps) {
  return Object.keys(deps).forEach((key) => {
    const dep = deps[key];
    if (PLUGIN.test(dep)) {
      return;
    }
    if (typeof dep === 'string') {
      if (!graph.hasNode(dep)) {
        graph.addNode(dep);
      }
      graph.addDependency(name, dep);
    } else if (typeof dep === 'object') {
      _recursiveDeps(graph, name, deps[key]);
    }
  });
}
<|endoftext|>


<commit_before>var semver = require('semver'),
    path = require('path'),

    FN = 'function',
    BASE_CONVERTER_DIR = './converters',
    generateConverter; // constructor

/**
 * Prototype interface definition of a converter
 *
 * @param {string} name
 * @param {object} model
 * @param {string<semver>} model.input
 * @param {string<semver>} model.output
 * @param {function} model.convert
 * @param {function=} [model.init]
 *
 * @throws {Error} If model definition does not meet requirements
 */
generateConverter = function (model) {
    var error;

    // validate the model
    if (!model) {
        error = 'invalid definition of converter';
    }
    // ensure that the input version support is a valid semver
    else if (!semver.valid(model.input)) {
        error = 'input version support for converter is invalid';
    }
    // ensure that the output version support is a valid semver
    else if (!semver.valid(model.output)) {
        error = 'output version support for converter is invalid';
    }
    else if (typeof model.convert !== FN) {
        error = 'convert function is not defined';
    }

    if (semver.satisfies(model.input, model.output)) {
        error = 'input version ' + model.input + ' matches output version ' + model.output + ' for converter';
    }

    // If we had encountered any error during validation, we simply exit by executing the callback and forwarding the
    // error.
    if (error) {
        throw new Error(error);
    }

    return model;
};

module.exports = {
    /**
     * All converters
     * @type {object<Converter>}
     *
     * @note this form of loading is most likely not browser friendly, find browser alternative
     */
    converters: require('require-all')({
        dirname: path.join(__dirname, BASE_CONVERTER_DIR),
        excludeDirs: /^\.(git|svn)$/,
        filter: /(.+)\.js$/,

        map: function (name) {
            return name; // @todo map the semver name for better readibility
        },

        resolve: function (model) {
            try {
                return generateConverter(model);
            }
            catch (err) {
                console.log('Could not load module %s: ', 'some-name', err.message || err);
            }
        }
    }),

    /**
     * @returns {Converter}
     */
    get: function (inputVersion, outputVersion) {
        var converter;

        inputVersion = semver.clean(inputVersion);
        outputVersion = semver.clean(outputVersion);

        for (converter in this.converters) {
            converter = this.converters.hasOwnProperty(converter) && this.converters[converter];
            if (converter && semver.eq(converter.input, inputVersion) && semver.eq(converter.output, outputVersion)) {
                return converter;
            }
        }
    },

    convert: function (collection, options, callback) {
        var converter = this.get(options.inputVersion, options.outputVersion);

        if (!converter) {
            return callback(new Error('no conversion path found'));
        }
        converter.convert(collection, options, callback);
    }
};
<commit_msg>remove node specific code<commit_after>var semver = require('semver'),
    FN = 'function',
    generateConverter; // constructor

/**
 * Prototype interface definition of a converter
 *
 * @param {string} name
 * @param {object} model
 * @param {string<semver>} model.input
 * @param {string<semver>} model.output
 * @param {function} model.convert
 * @param {function=} [model.init]
 *
 * @throws {Error} If model definition does not meet requirements
 */
generateConverter = function (model) {
    var error;

    // validate the model
    if (!model) {
        error = 'invalid definition of converter';
    }
    // ensure that the input version support is a valid semver
    else if (!semver.valid(model.input)) {
        error = 'input version support for converter is invalid';
    }
    // ensure that the output version support is a valid semver
    else if (!semver.valid(model.output)) {
        error = 'output version support for converter is invalid';
    }
    else if (typeof model.convert !== FN) {
        error = 'convert function is not defined';
    }

    if (semver.satisfies(model.input, model.output)) {
        error = 'input version ' + model.input + ' matches output version ' + model.output + ' for converter';
    }

    // If we had encountered any error during validation, we simply exit by executing the callback and forwarding the
    // error.
    if (error) {
        throw new Error(error);
    }

    return model;
};

module.exports = {
    /**
     * All converters
     * @type {object<Converter>}
     *
     * @note this form of loading is most likely not browser friendly, find browser alternative
     */
    converters: {
        'converter-v1-to-v2': require('./converters/converter-v1-to-v2'),
        'converter-v2-to-v1': require('./converters/converter-v2-to-v1')
    },

    /**
     * @returns {Converter}
     */
    get: function (inputVersion, outputVersion) {
        var converter;

        inputVersion = semver.clean(inputVersion);
        outputVersion = semver.clean(outputVersion);

        for (converter in this.converters) {
            converter = this.converters.hasOwnProperty(converter) && this.converters[converter];
            if (converter && semver.eq(converter.input, inputVersion) && semver.eq(converter.output, outputVersion)) {
                return generateConverter(converter);
            }
        }
    },

    convert: function (collection, options, callback) {
        var converter = this.get(options.inputVersion, options.outputVersion);

        if (!converter) {
            return callback(new Error('no conversion path found'));
        }
        converter.convert(collection, options, callback);
    }
};
<|endoftext|>


<commit_before>"use strict"

const fs = require('fs'),
      helpers = require('helpers');

//TODO sanity checks
class CookieJar() {

    constructor() {
        this._cookiePath = helpers.getConfigPath() + 'cookies.yml';
        this._cookieJar = this._read();
    }

    getAll() {
        return this._cookieJar;
    }

    write(cookies) {
        this._cookieJar = Object.assign({}, this._cookieJar, cookies);
        // write new file
        fs.writeFile(this._cookiePath, yaml.safeDump(this._cookieJar);
    }

    _read() {
        return yaml.safeLoad(fs.readFileSync(this._cookiePath));
    }
}

module.exports = CookieJar;
<commit_msg>missed parnes<commit_after>"use strict"

const fs = require('fs'),
      helpers = require('helpers');

//TODO sanity checks
class CookieJar() {

    constructor() {
        this._cookiePath = helpers.getConfigPath() + 'cookies.yml';
        this._cookieJar = this._read();
    }

    getAll() {
        return this._cookieJar;
    }

    write(cookies) {
        this._cookieJar = Object.assign({}, this._cookieJar, cookies);
        // write new file
        fs.writeFile(this._cookiePath, yaml.safeDump(this._cookieJar));
    }

    _read() {
        return yaml.safeLoad(fs.readFileSync(this._cookiePath));
    }
}

module.exports = CookieJar;
<|endoftext|>


<commit_before>/**
 * Game Constructor
 *
 * @class Roguelike.game
 * @classdesc The heart of this roguelike game! In here we provide access to
 * all the other objects and function, and we handle the startup of the game
 *
 * @param {Object} userSettings - The settings that the user provides
 */
Roguelike.Game = function(userSettings) {

	/**
	 * @property {Boolean} isInitialized - Boolean to see if the game is already initialized
	 */
	this.isInitialized = false;

	/**
	 * @property {Roguelike.Map} map - Reference to the current map
	 */
	this.map = null;

	/**
	 * @property {Roguelike.Keyboard} keyboard - Reference to the keyboard object
	 */
	this.keyboard = null;

	/**
	 * @property {Roguelike.Scheduler} scheduler - Reference to the scheduler object
	 */
	this.scheduler = null;

	/**
	 * @property {Roguelike.Systems.Movement} movementSystem - Reference to the movement system
	 */
	this.movementSystem = null;

	/**
	 * @property {Roguelike.Systems.PathFinding} pathfindingSystem - Reference to the pathfinding system
	 */
	this.pathfindingSystem = null;

	/**
	 * @property {Roguelike.Systems} dynamicSystems - An array with all the current systems that need to be looped
	 */
	this.dynamicSystems = [];

	/**
	 * @property {Roguelike.Camera} camera - Reference to the camera
	 */
	this.camera = null;

	/**
	 * @property {Roguelike.Entity} player - Reference to the player object
	 */
	this.player = null;

	/**
	 * @property {Object} settings - The default settings
	 */
	this.settings = {
		canvas: null,
		tilesX: 60,
		tilesY: 40,
		tileSize: 20,
		maxRooms: 10,
		minRoomWidth: 6,
		maxRoomWidth: 12,
		minRoomHeight: 6,
		maxRoomHeight: 12,
		debug: false
	};

	//Extend the default settings with those of the user
	this.settings = Roguelike.Utils.extend(this.settings, userSettings);

	//Initialize itself
	this.initialize();

};

Roguelike.Game.prototype = {

	/**
	 * Initialize the game, create all objects
	 * @protected
	 */
	initialize: function() {

		//Check if the game is already initialized
		if(this.isInitialized) {
			return;
		}

		//Create a new keyboard
		this.keyboard = new Roguelike.Keyboard();

		//Initialize the map
		this.map = new Roguelike.Map(this);

		//Add a new entity group to the map
		this.map.entities = new Roguelike.Group(this);

		//Create a new scheduler
		this.scheduler = new Roguelike.Scheduler();

		//Generate rooms for this map
		this.map.mapFactory.generateRooms();

		//Add the just generated rooms to the map
		this.map.addRooms();

		//Generate the corridors on this map
		this.map.mapFactory.generateCorridors();

		//Generate doors on this map
		this.map.mapFactory.generateDoors();

		//Add all objects to the map
		this.map.mapFactory.placeEntranceExitObjects();

		//Decorate the dungeon
		this.map.mapFactory.decorateDungeon();

		//Create the camera object
		this.camera = new Roguelike.Camera(this, {x: 0, y: 0});

		//Get the start position of the player
		var playerPosition = new Roguelike.Vector2(this.map.entrance.x, this.map.entrance.y);

		//Associative array with every control that this entity uses
		var playerControls = {};
		playerControls["left"] = 37;
		playerControls["right"] = 39;
		playerControls["up"] = 38;
		playerControls["down"] = 40;

		//Create the player entity
		this.player = Roguelike.PlayerFactory.newPlayerWarrior(this, playerPosition, playerControls);

		//Add the player to the entities list of the current map
		this.map.entities.addEntity(this.player);

		//Get the tile that the player is going to spawn on
		var startingTile = this.map.tiles[playerPosition.x][playerPosition.y];

		//Add the player to the tile it spawns on
		startingTile.addEntity(this.player);

		//Add the player to the scheduler
		this.scheduler.add(this.player, true);

		//Let the camera follow the player entity
		this.camera.follow(this.player, this.settings.canvas.width / 2, this.settings.canvas.height / 2);

		//Initialize the movement system
		this.movementSystem = new Roguelike.Systems.Movement(this);

		//Initialize the movement system
		this.pathfindingSystem = new Roguelike.Systems.PathFinding(this);

		//Add all systems to the game that need to be looped

		//Next up are the systems that handle specific queues like open or combat
		this.dynamicSystems.push(new Roguelike.Systems.Open(this));
		this.dynamicSystems.push(new Roguelike.Systems.Combat(this));

		//Last thing on the list are visual systems, these should always be updated last
		this.dynamicSystems.push(new Roguelike.Systems.LightMap(this));
		this.dynamicSystems.push(new Roguelike.Systems.Render(this));

		//Update the game for the first time
		this.update();

		//The game is fully initialized!
		this.isInitialized = true;

	},

	/**
	 * All the functions that need to be executed every time the game updates
	 * Basically the game loop
	 * @protected
	 */
	update: function() {

		var _this = this;
		requestAnimationFrame(function(){ _this.update()});

		//While the scheduler is locked, continue ticking
		while(!this.scheduler.lockCount){

			//Let the scheduler handle the next entity
			this.scheduler.tick();

		}

		//Loop through each dynamic system
		for(var s = 0; s < this.dynamicSystems.length; s++) {

			//Update the current system
			this.dynamicSystems[s].update();

		}

	}

};
<commit_msg>The combat system also needs to be a static system that only get's called by entities that need it.<commit_after>/**
 * Game Constructor
 *
 * @class Roguelike.game
 * @classdesc The heart of this roguelike game! In here we provide access to
 * all the other objects and function, and we handle the startup of the game
 *
 * @param {Object} userSettings - The settings that the user provides
 */
Roguelike.Game = function(userSettings) {

	/**
	 * @property {Boolean} isInitialized - Boolean to see if the game is already initialized
	 */
	this.isInitialized = false;

	/**
	 * @property {Roguelike.Map} map - Reference to the current map
	 */
	this.map = null;

	/**
	 * @property {Roguelike.Keyboard} keyboard - Reference to the keyboard object
	 */
	this.keyboard = null;

	/**
	 * @property {Roguelike.Scheduler} scheduler - Reference to the scheduler object
	 */
	this.scheduler = null;

	/**
	 * @property {Roguelike.Systems.Movement} movementSystem - Reference to the movement system
	 */
	this.movementSystem = null;

	/**
	 * @property {Roguelike.Systems.PathFinding} pathfindingSystem - Reference to the pathfinding system
	 */
	this.pathfindingSystem = null;

	/**
	 * @property {Roguelike.Systems.Combat} combatSystem - Reference to the combat system
	 */
	this.combatSystem = null;

	/**
	 * @property {Roguelike.Systems} dynamicSystems - An array with all the current systems that need to be looped
	 */
	this.dynamicSystems = [];

	/**
	 * @property {Roguelike.Camera} camera - Reference to the camera
	 */
	this.camera = null;

	/**
	 * @property {Roguelike.Entity} player - Reference to the player object
	 */
	this.player = null;

	/**
	 * @property {Object} settings - The default settings
	 */
	this.settings = {
		canvas: null,
		tilesX: 60,
		tilesY: 40,
		tileSize: 20,
		maxRooms: 10,
		minRoomWidth: 6,
		maxRoomWidth: 12,
		minRoomHeight: 6,
		maxRoomHeight: 12,
		debug: false
	};

	//Extend the default settings with those of the user
	this.settings = Roguelike.Utils.extend(this.settings, userSettings);

	//Initialize itself
	this.initialize();

};

Roguelike.Game.prototype = {

	/**
	 * Initialize the game, create all objects
	 * @protected
	 */
	initialize: function() {

		//Check if the game is already initialized
		if(this.isInitialized) {
			return;
		}

		//Create a new keyboard
		this.keyboard = new Roguelike.Keyboard();

		//Initialize the map
		this.map = new Roguelike.Map(this);

		//Add a new entity group to the map
		this.map.entities = new Roguelike.Group(this);

		//Create a new scheduler
		this.scheduler = new Roguelike.Scheduler();

		//Generate rooms for this map
		this.map.mapFactory.generateRooms();

		//Add the just generated rooms to the map
		this.map.addRooms();

		//Generate the corridors on this map
		this.map.mapFactory.generateCorridors();

		//Generate doors on this map
		this.map.mapFactory.generateDoors();

		//Add all objects to the map
		this.map.mapFactory.placeEntranceExitObjects();

		//Decorate the dungeon
		this.map.mapFactory.decorateDungeon();

		//Create the camera object
		this.camera = new Roguelike.Camera(this, {x: 0, y: 0});

		//Get the start position of the player
		var playerPosition = new Roguelike.Vector2(this.map.entrance.x, this.map.entrance.y);

		//Associative array with every control that this entity uses
		var playerControls = {};
		playerControls["left"] = 37;
		playerControls["right"] = 39;
		playerControls["up"] = 38;
		playerControls["down"] = 40;

		//Create the player entity
		this.player = Roguelike.PlayerFactory.newPlayerWarrior(this, playerPosition, playerControls);

		//Add the player to the entities list of the current map
		this.map.entities.addEntity(this.player);

		//Get the tile that the player is going to spawn on
		var startingTile = this.map.tiles[playerPosition.x][playerPosition.y];

		//Add the player to the tile it spawns on
		startingTile.addEntity(this.player);

		//Add the player to the scheduler
		this.scheduler.add(this.player, true);

		//Let the camera follow the player entity
		this.camera.follow(this.player, this.settings.canvas.width / 2, this.settings.canvas.height / 2);

		//Initialize the movement system
		this.movementSystem = new Roguelike.Systems.Movement(this);

		//Initialize the movement system
		this.pathfindingSystem = new Roguelike.Systems.PathFinding(this);

		//Initialize the combat system
		this.combatSystem = new Roguelike.Systems.Combat(this);

		//Add all systems to the game that need to be looped

		//Next up are the systems that handle specific queues like open or combat
		this.dynamicSystems.push(new Roguelike.Systems.Open(this));

		//Last thing on the list are visual systems, these should always be updated last
		this.dynamicSystems.push(new Roguelike.Systems.LightMap(this));
		this.dynamicSystems.push(new Roguelike.Systems.Render(this));

		//Update the game for the first time
		this.update();

		//The game is fully initialized!
		this.isInitialized = true;

	},

	/**
	 * All the functions that need to be executed every time the game updates
	 * Basically the game loop
	 * @protected
	 */
	update: function() {

		var _this = this;
		requestAnimationFrame(function(){ _this.update()});

		//While the scheduler is locked, continue ticking
		while(!this.scheduler.lockCount){

			//Let the scheduler handle the next entity
			this.scheduler.tick();

		}

		//Loop through each dynamic system
		for(var s = 0; s < this.dynamicSystems.length; s++) {

			//Update the current system
			this.dynamicSystems[s].update();

		}

	}

};
<|endoftext|>


<commit_before>import React, { PropTypes } from 'react'
import ListItem from 'material-ui/lib/lists/list-item'
import TextField from 'material-ui/lib/text-field'

class EditTodo extends React.Component {
  constructor (props) {
    super(props)
    this.state = {value: props.text}
  }

  handleChange = (event) => {
    this.setState({value: event.target.value})
  }

  handleSave = () => {
    this.props.onSave(this.props.id, this.state.value)
  }

  render = () => {
    return (
      <ListItem>
        <TextField
          value={this.state.value}
          onChange={this.handleChange}
          onBlur={this.handleSave}
          onKeyDown={(e) => {
            if (e.keyCode === 13) { this.handleSave() }
          }}
        />
      </ListItem>
    )
  }
}

EditTodo.propTypes = {
  onSave: PropTypes.func.isRequired
}

export default EditTodo
<commit_msg>Focus edit field on edit<commit_after>import React, { PropTypes } from 'react'
import ListItem from 'material-ui/lib/lists/list-item'
import TextField from 'material-ui/lib/text-field'

class EditTodo extends React.Component {
  constructor (props) {
    super(props)
    this.state = {value: props.text}
  }

  componentDidMount = () => {
    this.refs.input.focus()
  }

  handleChange = (event) => {
    this.setState({value: event.target.value})
  }

  handleSave = () => {
    this.props.onSave(this.props.id, this.state.value)
  }

  render = () => {
    return (
      <ListItem>
        <TextField
          name={`todo-edit-${this.props.id}`}
          ref='input'
          value={this.state.value}
          onChange={this.handleChange}
          onBlur={this.handleSave}
          onKeyDown={(e) => {
            if (e.keyCode === 13) { this.handleSave() }
          }}
        />
      </ListItem>
    )
  }
}

EditTodo.propTypes = {
  id: PropTypes.number.isRequired,
  onSave: PropTypes.func.isRequired
}

export default EditTodo
<|endoftext|>


<commit_before>const path = require('path');  // eslint-disable-line

const packageInfo = require(path.resolve('package.json')); // eslint-disable-line import/no-dynamic-require
const isCommon = packageInfo.name === 'omni-common-ui';
const contextFolder = isCommon ? 'sample' : 'app';

module.exports = {
  plugins: [
    require('postcss-import')({
      path: [
        'node_modules',
        contextFolder,
        `${contextFolder}/assets/styles`,
        process.cwd(),
      ],
    }),
    require('postcss-mixins'),
    require('postcss-nested-ancestors'),
    require('postcss-nested'),
    require('postcss-current-selector'),
    require('postcss-nesting'),
    require('postcss-custom-properties'),
    require('postcss-custom-media'),
    require('postcss-custom-selectors'),
    require('postcss-url')({ url: 'rebase' }),
    require('cq-prolyfill/postcss-plugin'),
    require('postcss-selector-not'),
    require('postcss-color-function'),
    require('postcss-color-hex-alpha'),
    require('postcss-gradient-transparency-fix'),
    require('postcss-calc'),
    require('postcss-pxtorem')({
      rootValue: 14,
      unitPrecision: 5,
      propWhiteList: [],
      selectorBlackList: [],
      replace: true,
      mediaQuery: false,
      minPixelValue: 0,
    }),
    require('autoprefixer')({
      browsers: [
        '> 0%',
        'last 2 versions',
        'Firefox ESR',
        'Opera 12.1',
        'Android 2.3',
        'iOS 7',
      ],
    }),
    require('postcss-reporter'),
  ],
};
<commit_msg>postcss.config: excluding :exported vars in px to rem conversion<commit_after>const path = require('path');  // eslint-disable-line

const packageInfo = require(path.resolve('package.json')); // eslint-disable-line import/no-dynamic-require
const isCommon = packageInfo.name === 'omni-common-ui';
const contextFolder = isCommon ? 'sample' : 'app';

module.exports = {
  plugins: [
    require('postcss-import')({
      path: [
        'node_modules',
        contextFolder,
        `${contextFolder}/assets/styles`,
        process.cwd(),
      ],
    }),
    require('postcss-mixins'),
    require('postcss-nested-ancestors'),
    require('postcss-nested'),
    require('postcss-current-selector'),
    require('postcss-nesting'),
    require('postcss-custom-properties'),
    require('postcss-custom-media'),
    require('postcss-custom-selectors'),
    require('postcss-url')({ url: 'rebase' }),
    require('cq-prolyfill/postcss-plugin'),
    require('postcss-selector-not'),
    require('postcss-color-function'),
    require('postcss-color-hex-alpha'),
    require('postcss-gradient-transparency-fix'),
    require('postcss-calc'),
    require('postcss-pxtorem')({
      rootValue: 14,
      unitPrecision: 5,
      propWhiteList: [],
      selectorBlackList: [':export'],
      replace: true,
      mediaQuery: false,
      minPixelValue: 0,
    }),
    require('autoprefixer')({
      browsers: [
        '> 0%',
        'last 2 versions',
        'Firefox ESR',
        'Opera 12.1',
        'Android 2.3',
        'iOS 7',
      ],
    }),
    require('postcss-reporter'),
  ],
};
<|endoftext|>


<commit_before>import Ember from 'ember';

export default Ember.Component.extend({
  content: function(key, val) {
    if (!this.editor) {
      this.preset = val;
      return val;
    }
    if (arguments.length === 1) {
      return this.editor.getSession().getValue();
    }
    var cursor = this.editor.getCursorPosition();
    this.editor.getSession().setValue(val);
    this.editor.moveCursorToPosition(cursor);
    return val;
  }.property(),

  didInsertElement: function() {
    this.editor = window.ace.edit('editor');
    this.editor.setTheme('ace/theme/monokai');
    this.editor.getSession().setMode('ace/mode/ruby');

    var self = this;
    this.editor.on('change', function() {
      self.notifyPropertyChange('content');
    });

    if (this.preset) {
      this.set('content', this.preset);
      this.preset = null;
    }
  },

  actions: {
    createSolution: function() {
      this.sendAction('submit', this.editor.getValue());
    },

    run: function() {
      var answer = this.get('answer')
      //  get the code from the div
      var code = this.editor.getValue();
      //  send request to Rails/Eval.in via AJAX
      $.ajax({
        type: 'GET',
        url: 'http://0.0.0.0:3000/api/v1/coderunner',
        data:{code: code},
        dataType: 'jsonp'
        })
        .done(function(data){
          var solution = data;
          if(solution === answer){
            alert('success!');
            //activate submit button
          }
          else{
            alert("you're wrong!");
          }
        })
        .fail(function(){
          alert("error");
        });
    }
  }
});
<commit_msg>fix code-runner<commit_after>import Ember from 'ember';

export default Ember.Component.extend({
  content: function(key, val) {
    if (!this.editor) {
      this.preset = val;
      return val;
    }
    if (arguments.length === 1) {
      return this.editor.getSession().getValue();
    }
    var cursor = this.editor.getCursorPosition();
    this.editor.getSession().setValue(val);
    this.editor.moveCursorToPosition(cursor);
    return val;
  }.property(),

  didInsertElement: function() {
    this.editor = window.ace.edit('editor');
    this.editor.setTheme('ace/theme/monokai');
    this.editor.getSession().setMode('ace/mode/ruby');

    var self = this;
    this.editor.on('change', function() {
      self.notifyPropertyChange('content');
    });

    if (this.preset) {
      this.set('content', this.preset);
      this.preset = null;
    }
  },

  actions: {
    createSolution: function() {
      this.sendAction('submit', this.editor.getValue());
    },

    run: function() {
      var answer = this.get('answer')
      //  get the code from the div
      var code = this.editor.getValue();
      //  send request to Rails/Eval.in via AJAX
      $.ajax({
        type: 'GET',
        url: 'api/v1/coderunner',
        data:{code: code},
        dataType: 'jsonp'
        })
        .done(function(data){
          var solution = data;
          if(solution === answer){
            alert('success!');
            //activate submit button
          }
          else{
            alert("you're wrong!");
          }
        })
        .fail(function(){
          alert("error");
        });
    }
  }
});
<|endoftext|>


<commit_before>/*!
 * qwebs
 * Copyright(c) 2015 Benoît Claveau <benoit.claveau@gmail.com>
 * MIT Licensed
 */
 "use strict";
var http = require("http");

class DataError extends Error {
    constructor(options) {
        super(options.message || "Qwebs error");
        if (Error.captureStackTrace) Error.captureStackTrace(this, this.constructor);
        if (this.message[this.message.length - 1] !== ".") this.message += ".";

        this.name = this.constructor.name;

        if (options.stack) this.stack = options.stack;
        if (options.fileName) this.fileName = options.fileName;
        if (options.lineNumber) this.lineNumber = options.lineNumber;
        if (options.columnNumber) this.columnNumber = options.columnNumber;
        if (options.request) this.request = options.request;

        if (!options.data) this.data = {};
        else if (options.data instanceof Array) this.data = { array: options.data };
        else this.data = options.data;

        this.headers = options.headers || {};
        this.headers["Content-Type"] = this.headers["Content-Type"] || "application/json";

        this.statusCode = options.statusCode || 500;
    };

    toString() {
        let data = [];
        data.push({key: "statusCode", value: this.statusCode });
        data.push({key: "data", value: JSON.stringify(this.data) });
        data.push({key: "headers", value: JSON.stringify(this.headers) });
        if (this.fileName) data.push({key: "fileName", value: this.fileName });
        if (this.lineNumber) data.push({key: "lineNumber", value: this.lineNumber });
        if (this.columnNumber) data.push({key: "columnNumber", value: this.columnNumber });
        data.push({key: "stack", value: this.stack });

        return `${this.name}: ${this.message} ${data.map(e => `
    - ${e.key}: ${e.value}`)}`
        };
}

exports = module.exports = DataError;<commit_msg>display error<commit_after>/*!
 * qwebs
 * Copyright(c) 2015 Benoît Claveau <benoit.claveau@gmail.com>
 * MIT Licensed
 */
 "use strict";
var http = require("http");

class DataError extends Error {
    constructor(options) {
        super(options.message || "Qwebs error");
        if (Error.captureStackTrace) Error.captureStackTrace(this, this.constructor);
        if (this.message[this.message.length - 1] !== ".") this.message += ".";

        this.name = this.constructor.name;

        if (options.stack) this.stack = options.stack;
        if (options.fileName) this.fileName = options.fileName;
        if (options.lineNumber) this.lineNumber = options.lineNumber;
        if (options.columnNumber) this.columnNumber = options.columnNumber;
        if (options.request) this.request = options.request;

        if (!options.data) this.data = {};
        else if (options.data instanceof Array) this.data = { array: options.data };
        else this.data = options.data;

        this.headers = options.headers || {};
        this.headers["Content-Type"] = this.headers["Content-Type"] || "application/json";

        this.statusCode = options.statusCode || 500;
    };

    //use by request.send
    get content() {
        if (data.headers["Content-Type"].match(/application\/json/)) return this;
        if (data.headers["Content-Type"].match(/text\/html/)) return `

${this.message}

${this.data}

${this.stack}

`;
        return this.message;
    }

    toString() {
        let data = [];
        data.push({key: "statusCode", value: this.statusCode });
        data.push({key: "data", value: JSON.stringify(this.data) });
        data.push({key: "headers", value: JSON.stringify(this.headers) });
        if (this.fileName) data.push({key: "fileName", value: this.fileName });
        if (this.lineNumber) data.push({key: "lineNumber", value: this.lineNumber });
        if (this.columnNumber) data.push({key: "columnNumber", value: this.columnNumber });
        data.push({key: "stack", value: this.stack });

        return `${this.name}: ${this.message} ${data.map(e => `
    - ${e.key}: ${e.value}`)}`
        };
}

exports = module.exports = DataError;<|endoftext|>


<commit_before>/* global TravisTracer */

import Component from '@ember/component';
import { action } from 'ember-decorators/object';

export default Component.extend({
  tagName: 'div',
  panelIsOpen: true,
  requests: [],

  init() {
    this._super(...arguments);

    TravisTracer.onRequest = req => {
      this.get('requests').pushObject(req);

      Ember.run.next(() => {
        let panel = document.getElementById('tracer-panel');
        panel.scrollTop = panel.scrollHeight + 20;
      })
    };
  },

  @action
  toggleOpen() {
    this.toggleProperty('panelIsOpen');
  }
});
<commit_msg>remember panel open state in localStorage<commit_after>/* global TravisTracer, window */

import Component from '@ember/component';
import { action } from 'ember-decorators/object';

export default Component.extend({
  tagName: 'div',
  panelIsOpen: false,
  requests: [],

  init() {
    this._super(...arguments);

    if (window.localStorage.TravisTracerIsOpen) {
      this.panelIsOpen = true;
    }

    TravisTracer.onRequest = req => {
      this.get('requests').pushObject(req);

      Ember.run.next(() => {
        let panel = document.getElementById('tracer-panel');
        panel.scrollTop = panel.scrollHeight + 20;
      })
    };
  },

  @action
  toggleOpen() {
    this.toggleProperty('panelIsOpen');
    if (this.get('panelIsOpen')) {
      window.localStorage.TravisTracerIsOpen = 'true';
    } else {
      delete window.localStorage.TravisTracerIsOpen;
    }
  }
});
<|endoftext|>


<commit_before>/**
 * Copyright 2014 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @fileoverview Implements log functions which can be compiled out.
 */

goog.provide('shaka.log');

/**
 * @namespace shaka.log
 * @summary A console logging framework which is compiled out for deployment.
 */

/**
 * Log levels.
 * @enum {number}
 */
shaka.log.Level = {
  NONE: 0,
  ERROR: 1,
  WARNING: 2,
  INFO: 3,
  DEBUG: 4,
  V1: 5,
  V2: 6
};

/**
 * @define {number} the maximum log level.
 */
goog.define('shaka.log.MAX_LOG_LEVEL', 3);

/** @type {function(*, ...[*])} */
shaka.log.error = function() {};

/** @type {function(*, ...[*])} */
shaka.log.warning = function() {};

/** @type {function(*, ...[*])} */
shaka.log.info = function() {};

/** @type {function(*, ...[*])} */
shaka.log.debug = function() {};

/** @type {function(*, ...[*])} */
shaka.log.v1 = function() {};

/** @type {function(*, ...[*])} */
shaka.log.v2 = function() {};

if (!COMPILED) {
  /**
   * Change the log level.  Useful for debugging in uncompiled mode.
   *
   * @param {number} level
   */
  shaka.log.setLevel = function(level) {
    var nop = function() {};
    var log = shaka.log;
    var Level = shaka.log.Level;

    log.error = (level >= Level.ERROR) ? console.error.bind(console) : nop;
    log.warning = (level >= Level.WARNING) ? console.warn.bind(console) : nop;
    log.info = (level >= Level.INFO) ? console.info.bind(console) : nop;
    log.debug = (level >= Level.DEBUG) ? console.log.bind(console) : nop;
    log.v1 = (level >= Level.V1) ? console.debug.bind(console) : nop;
    log.v2 = (level >= Level.V2) ? console.debug.bind(console) : nop;
  };
}

// Although these bindings are redundant with setLevel() above, refactoring to
// call a method here makes it so that the log messages themselves cannot be
// compiled out.

if (shaka.log.MAX_LOG_LEVEL >= shaka.log.Level.ERROR) {
  shaka.log.error = console.error.bind(console);
}

if (shaka.log.MAX_LOG_LEVEL >= shaka.log.Level.WARNING) {
  shaka.log.warning = console.warn.bind(console);
}

if (shaka.log.MAX_LOG_LEVEL >= shaka.log.Level.INFO) {
  shaka.log.info = console.info.bind(console);
}

if (shaka.log.MAX_LOG_LEVEL >= shaka.log.Level.DEBUG) {
  shaka.log.debug = console.log.bind(console);
}

if (shaka.log.MAX_LOG_LEVEL >= shaka.log.Level.V1) {
  shaka.log.v1 = console.debug.bind(console);
}

if (shaka.log.MAX_LOG_LEVEL >= shaka.log.Level.V2) {
  shaka.log.v2 = console.debug.bind(console);
}

<commit_msg>Patching console logging functions when they do not exist, or when bind is not implemented on them (IE 9 with F12 Developer Tools open)<commit_after>/**
 * Copyright 2014 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @fileoverview Implements log functions which can be compiled out.
 */

goog.provide('shaka.log');

/**
 * @namespace shaka.log
 * @summary A console logging framework which is compiled out for deployment.
 */

/**
 * Log levels.
 * @enum {number}
 */
shaka.log.Level = {
  NONE: 0,
  ERROR: 1,
  WARNING: 2,
  INFO: 3,
  DEBUG: 4,
  V1: 5,
  V2: 6
};

/**
 * @define {number} the maximum log level.
 */
goog.define('shaka.log.MAX_LOG_LEVEL', 3);

/** @type {function(*, ...[*])} */
shaka.log.error = function() {};

/** @type {function(*, ...[*])} */
shaka.log.warning = function() {};

/** @type {function(*, ...[*])} */
shaka.log.info = function() {};

/** @type {function(*, ...[*])} */
shaka.log.debug = function() {};

/** @type {function(*, ...[*])} */
shaka.log.v1 = function() {};

/** @type {function(*, ...[*])} */
shaka.log.v2 = function() {};

shaka.log.patchConsole_ = function(logName) {
  var nop = function() {};
  var logFunction = console[logName];

  if (!logFunction) {
    console[logName] = nop;
  } else if (!logFunction.bind) {
    console[logName] = function() {
      logFunction.apply(console, arguments);
    }
  }
};

shaka.log.patchConsole_("error");
shaka.log.patchConsole_("warn");
shaka.log.patchConsole_("info");
shaka.log.patchConsole_("log");
shaka.log.patchConsole_("debug");

if (!COMPILED) {
  /**
   * Change the log level.  Useful for debugging in uncompiled mode.
   *
   * @param {number} level
   */
  shaka.log.setLevel = function(level) {
    var nop = function() {};
    var log = shaka.log;
    var Level = shaka.log.Level;

    log.error = (level >= Level.ERROR) ? console.error.bind(console) : nop;
    log.warning = (level >= Level.WARNING) ? console.warn.bind(console) : nop;
    log.info = (level >= Level.INFO) ? console.info.bind(console) : nop;
    log.debug = (level >= Level.DEBUG) ? console.log.bind(console) : nop;
    log.v1 = (level >= Level.V1) ? console.debug.bind(console) : nop;
    log.v2 = (level >= Level.V2) ? console.debug.bind(console) : nop;
  };
}

// Although these bindings are redundant with setLevel() above, refactoring to
// call a method here makes it so that the log messages themselves cannot be
// compiled out.

if (shaka.log.MAX_LOG_LEVEL >= shaka.log.Level.ERROR) {
  shaka.log.error = console.error.bind(console);
}

if (shaka.log.MAX_LOG_LEVEL >= shaka.log.Level.WARNING) {
  shaka.log.warning = console.warn.bind(console);
}

if (shaka.log.MAX_LOG_LEVEL >= shaka.log.Level.INFO) {
  shaka.log.info = console.info.bind(console);
}

if (shaka.log.MAX_LOG_LEVEL >= shaka.log.Level.DEBUG) {
  shaka.log.debug = console.log.bind(console);
}

if (shaka.log.MAX_LOG_LEVEL >= shaka.log.Level.V1) {
  shaka.log.v1 = console.debug.bind(console);
}

if (shaka.log.MAX_LOG_LEVEL >= shaka.log.Level.V2) {
  shaka.log.v2 = console.debug.bind(console);
}
<|endoftext|>


<commit_before>const { blue } = require("chalk");
const logger = require("morgan");
const webpack = require("webpack");
const webpackDevMiddleware = require("webpack-dev-middleware");
const webpackHotMiddleware = require("webpack-hot-middleware");

const devConfig = require("../../scripts/webpack/webpack.config.dev");

/**
 * inject debug settings to express app.
 */
module.exports.inject = (app, options = {}) =>
{
    console.log(blue("Environment: development\n"));

    // set logger.
    app.use(logger("dev"));

    // set webpack.
    const compiler = webpack(devConfig);
    const instance = webpackDevMiddleware(
        compiler,
        {
            stats:
                {
                    children: false,
                    colors: true,
                    modules: false
                },
            publicPath: devConfig.output.publicPath
        }
    );
    instance.waitUntilValid(() =>
    {
        // assets map setup.
        app.locals.map = require(options.assetsPath);
    });

    app.use(instance);
    app.use(webpackHotMiddleware(compiler));
};
<commit_msg>rename to devMiddleware<commit_after>const { blue } = require("chalk");
const logger = require("morgan");
const webpack = require("webpack");
const webpackDevMiddleware = require("webpack-dev-middleware");
const webpackHotMiddleware = require("webpack-hot-middleware");

const devConfig = require("../../scripts/webpack/webpack.config.dev");

/**
 * inject debug settings to express app.
 */
module.exports.inject = (app, options = {}) =>
{
    console.log(blue("Environment: development\n"));

    // set logger.
    app.use(logger("dev"));

    // set webpack.
    const compiler = webpack(devConfig);
    const devMiddleware = webpackDevMiddleware(
        compiler,
        {
            stats:
                {
                    children: false,
                    colors: true,
                    modules: false
                },
            publicPath: devConfig.output.publicPath
        }
    );
    devMiddleware.waitUntilValid(() =>
    {
        // assets map setup.
        app.locals.map = require(options.assetsPath);
    });

    app.use(devMiddleware);
    app.use(webpackHotMiddleware(compiler));
};
<|endoftext|>


<commit_before>var agnat_priority_queue = (function() { // namespace

var exports = (typeof module !== 'undefined' && module.exports) ? module.exports : {};

exports.PriorityQueue = function PriorityQueue(compare, queue) {
  if (!(this instanceof PriorityQueue)) return new PriorityQueue(compare, queue);

  compare = compare || min_first;
  queue   = queue   || [];

  function swap(i, j) { var t = queue[i]; queue[i] = queue[j]; queue[j] = t; }

  function heapify(i) {
    var length = queue.length, x, l, r;
    while (true) {
      x = i; l = left(i); r = right(i);
      if (l < length && compare(queue[l], queue[x]) < 0) x = l;
      if (r < length && compare(queue[r], queue[x]) < 0) x = r;
      if (x === i) break;
      swap(i, x);
      i = x;
    }
  }

  function remove(i) {
    var t = queue[i], b = queue.pop();
    if (queue.length > 0) {
      queue[i] = b;
      heapify(i);
    }
    return t;
  }

  this.push = function push(/* element, ... */) {
    var i = queue.length, e = i + arguments.length, j, p;
    queue.push.apply(queue, arguments);
    for (; i < e; ++i) {
      j = i; p = parent(i);
      for(; j >= 0 && compare(queue[j], queue[p]) < 0; j = p, p = parent(j)) {
        swap(j, p);
      }
    }
    return queue.length;
  }

  this.shift = function shift() { return remove(0); }
  this.__defineGetter__('length', function length() { return queue.length });

  for (var i = parent(queue.length - 1); i >= 0; --i) { heapify(i) }
}

function left(i)   { return 2 * i + 1 }
function right(i)  { return 2 * i + 2 }
function parent(i) { return Math.floor((i + 1) / 2) - 1 }

var max_first = exports.max_first = function max_first(a, b) { return b - a }
  , min_first = exports.min_first = function min_first(a, b) { return a - b }
  ;

return exports; })(); // end of namespace
<commit_msg>fixed index glitch in push()<commit_after>(function() { // namespace

var exports = (typeof module !== 'undefined' && module.exports) ?
    module.exports : window.priority_queue = {};

exports.PriorityQueue = function PriorityQueue(compare, queue) {
  if (!(this instanceof PriorityQueue)) return new PriorityQueue(compare, queue);

  compare = compare || min_first;
  queue   = queue   || [];

  function swap(i, j) { var t = queue[i]; queue[i] = queue[j]; queue[j] = t; }

  function heapify(i) {
    var length = queue.length, x, l, r;
    while (true) {
      x = i; l = left(i); r = right(i);
      if (l < length && compare(queue[l], queue[x]) < 0) x = l;
      if (r < length && compare(queue[r], queue[x]) < 0) x = r;
      if (x === i) break;
      swap(i, x);
      i = x;
    }
  }

  function remove(i) {
    var t = queue[i], b = queue.pop();
    if (queue.length > 0) {
      queue[i] = b;
      heapify(i);
    }
    return t;
  }

  this.push = function push(/* element, ... */) {
    var i = queue.length, e = i + arguments.length, j, p;
    queue.push.apply(queue, arguments);
    for (; i < e; ++i) {
      j = i; p = parent(i);
      for (; j > 0 && compare(queue[j], queue[p]) < 0; j = p, p = parent(j)) {
        swap(j, p);
      }
    }
    return queue.length;
  }

  this.shift = function shift() { return remove(0); }
  this.__defineGetter__('length', function length() { return queue.length });

  for (var i = parent(queue.length - 1); i >= 0; --i) { heapify(i) }
}

function left(i)   { return 2 * i + 1 }
function right(i)  { return 2 * i + 2 }
function parent(i) { return Math.floor((i + 1) / 2) - 1 }

var max_first = exports.max_first = function max_first(a, b) { return b - a }
  , min_first = exports.min_first = function min_first(a, b) { return a - b }
  ;

})(); // end of namespace
<|endoftext|>


<commit_before>//
// officegen: docx table.
//
// Please refer to README.md for this module's documentations.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//

'use strict'

var debug = require('debug')('officegen-linebreaks-within-table-cell:docxtable')

module.exports = {
  // assume passed in an array of row objects
  getTable: function (rows, tblOpts) {
    tblOpts = tblOpts || {}

    var self = this

    return self._getBase(
      rows.map(function (row) {
        return self._getRow(
          row.map(function (cell) {
            cell = cell || {}
            if (typeof cell === 'string' || typeof cell === 'number') {
              var val = cell
              cell = {
                val: val
              }
            }

            return self._getCell(cell.val, cell.opts, tblOpts)
          }),
          tblOpts
        )
      }),
      self._getColSpecs(rows, tblOpts),
      tblOpts
    )
  },

  _getBase: function (rowSpecs, colSpecs, opts) {
    var baseTable = {
      'w:tbl': {
        'w:tblPr': {
          'w:tblStyle': {
            '@w:val': 'a3'
          },
          'w:tblW': {
            '@w:w': '0',
            '@w:type': 'auto'
          },
          'w:tblLook': {
            '@w:val': '04A0',
            '@w:firstRow': '1',
            '@w:lastRow': '0',
            '@w:firstColumn': '1',
            '@w:lastColumn': '0',
            '@w:noHBand': '0',
            '@w:noVBand': '1'
          }
        },
        'w:tblGrid': {
          '#list': colSpecs
        },
        '#list': [rowSpecs]
      }
    }
    if (opts.borders) {
      baseTable['w:tbl']['w:tblPr']['w:tblBorders'] = {
        'w:top': {
          '@w:val': 'single',
          '@w:sz': '12',
          '@w:space': '0',
          '@w:color': '000000'
        },
        'w:bottom': {
          '@w:val': 'single',
          '@w:sz': '12',
          '@w:space': '0',
          '@w:color': '000000'
        },
        'w:left': {
          '@w:val': 'single',
          '@w:sz': '12',
          '@w:space': '0',
          '@w:color': '000000'
        },
        'w:right': {
          '@w:val': 'single',
          '@w:sz': '12',
          '@w:space': '0',
          '@w:color': '000000'
        },
        'w:insideH': {
          '@w:val': 'single',
          '@w:sz': '12',
          '@w:space': '0',
          '@w:color': '000000'
        },
        'w:insideV': {
          '@w:val': 'single',
          '@w:sz': '12',
          '@w:space': '0',
          '@w:color': '000000'
        }
      }
    }
    if (opts.rtl) {
      baseTable['w:tbl']['w:tblPr']['w:bidiVisual'] = {}
    }
    return baseTable
  },

  _getColSpecs: function (cols, opts) {
    var self = this
    return cols[0].map(function (col, idx) {
      return self._tblGrid(opts, col)
    })
  },

  // TODO
  _tblGrid: function (opts, col) {
    return {
      'w:gridCol': {
        '@w:w': col.opts.cellColWidth || opts.tableColWidth || '1'
      }
    }
  },

  _getRow: function (cells, opts) {
    return {
      'w:tr': {
        '@w:rsidR': '00995B51',
        '@w:rsidTr': '007F1D13',
        '#list': [cells] // populate this with an array of table cell objects
      }
    }
  },

  _getCell: function (val, opts, tblOpts) {
    opts = opts || {}
    // var b = {};

    // if (opts.b) {
    //   b = {
    //     "w:tc": {
    //       "w:p": {
    //         "w:r": {
    //           "w:rPr": {
    //             "w:b": {}
    //           }
    //         }
    //       }
    //     }
    //   }
    // }

    debug('Cell value is ' + val);
    console.log('Cell value is ' + val);
    splitLines = val.split(/\r?\n/);
    for (var i = 0; i < splitLines.length; i++)
    {
      debug('split line is' + splitLines[i]);
    }

    var cellObj = {
      'w:tc': {
        'w:tcPr': {
          'w:tcW': {
            '@w:w': opts.cellColWidth || tblOpts.tableColWidth || '0',
            '@w:type': 'dxa'
          },
          'w:gridSpan': {
            '@w:val': opts.gridSpan || '1'
          },
          'w:vAlign': {
            '@w:val': opts.vAlign || 'top'
          },
          'w:shd': {
            '@w:val': 'clear',
            '@w:color': 'auto',
            '@w:fill': (opts.shd && opts.shd.fill) || '',
            '@w:themeFill': (opts.shd && opts.shd.themeFill) || '',
            '@w:themeFillTint': (opts.shd && opts.shd.themeFillTint) || ''
          }
        },
        'w:p': {
          '@w:rsidR': '00995B51',
          '@w:rsidRPr': '00722E63',
          '@w:rsidRDefault': '00995B51',
          'w:pPr': {
            'w:jc': {
              '@w:val': opts.align || tblOpts.tableAlign || 'center'
            }
            // "w:rPr": {
            //   "w:rFonts": {
            //     "@w:asciiTheme": "majorEastAsia",
            //     "@w:eastAsiaTheme": "majorEastAsia",
            //     "@w:hAnsiTheme": "majorEastAsia"
            //   },
            //   // "w:b": {},
            //   "w:sz": {
            //     "@w:val": "24"
            //   },
            //   "w:szCs": {
            //     "@w:val": "24"
            //   }
            // }
          },
          'w:r': {
            '@w:rsidRPr': '00722E63',
            'w:rPr': {
              'w:rFonts': {
                '@w:ascii': opts.fontFamily || tblOpts.tableFontFamily || '宋体',
                '@w:hAnsi': opts.fontFamily || tblOpts.tableFontFamily || '宋体'
              },
              'w:color': {
                '@w:val': opts.color || tblOpts.tableColor || '000'
              },
              'w:b': {},
              'w:sz': {
                '@w:val': opts.sz || tblOpts.sz || '24'
              },
              'w:szCs': {
                '@w:val': opts.sz || tblOpts.sz || '24'
              }
            },
            'w:t': val
          }
        }
      }
    }

    if (!opts.b) {
      delete cellObj['w:tc']['w:p']['w:r']['w:rPr']['w:b']
    }
    if (tblOpts.rtl) {
      cellObj['w:tc']['w:p']['w:pPr']['w:bidi'] = { '@w:val': '1' }
    }
    if (opts.rtl) {
      cellObj['w:tc']['w:p']['w:r']['w:rPr']['w:rtl'] = { '@w:val': '1' }
    }

    return cellObj
  }
}
<commit_msg>Update docxtable.js<commit_after>//
// officegen: docx table.
//
// Please refer to README.md for this module's documentations.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//

'use strict'

var debug = require('debug')('officegen-linebreaks-within-table-cell:docxtable')

module.exports = {
  // assume passed in an array of row objects
  getTable: function (rows, tblOpts) {
    tblOpts = tblOpts || {}

    var self = this

    return self._getBase(
      rows.map(function (row) {
        return self._getRow(
          row.map(function (cell) {
            cell = cell || {}
            if (typeof cell === 'string' || typeof cell === 'number') {
              var val = cell
              cell = {
                val: val
              }
            }

            return self._getCell(cell.val, cell.opts, tblOpts)
          }),
          tblOpts
        )
      }),
      self._getColSpecs(rows, tblOpts),
      tblOpts
    )
  },

  _getBase: function (rowSpecs, colSpecs, opts) {
    var baseTable = {
      'w:tbl': {
        'w:tblPr': {
          'w:tblStyle': {
            '@w:val': 'a3'
          },
          'w:tblW': {
            '@w:w': '0',
            '@w:type': 'auto'
          },
          'w:tblLook': {
            '@w:val': '04A0',
            '@w:firstRow': '1',
            '@w:lastRow': '0',
            '@w:firstColumn': '1',
            '@w:lastColumn': '0',
            '@w:noHBand': '0',
            '@w:noVBand': '1'
          }
        },
        'w:tblGrid': {
          '#list': colSpecs
        },
        '#list': [rowSpecs]
      }
    }
    if (opts.borders) {
      baseTable['w:tbl']['w:tblPr']['w:tblBorders'] = {
        'w:top': {
          '@w:val': 'single',
          '@w:sz': '12',
          '@w:space': '0',
          '@w:color': '000000'
        },
        'w:bottom': {
          '@w:val': 'single',
          '@w:sz': '12',
          '@w:space': '0',
          '@w:color': '000000'
        },
        'w:left': {
          '@w:val': 'single',
          '@w:sz': '12',
          '@w:space': '0',
          '@w:color': '000000'
        },
        'w:right': {
          '@w:val': 'single',
          '@w:sz': '12',
          '@w:space': '0',
          '@w:color': '000000'
        },
        'w:insideH': {
          '@w:val': 'single',
          '@w:sz': '12',
          '@w:space': '0',
          '@w:color': '000000'
        },
        'w:insideV': {
          '@w:val': 'single',
          '@w:sz': '12',
          '@w:space': '0',
          '@w:color': '000000'
        }
      }
    }
    if (opts.rtl) {
      baseTable['w:tbl']['w:tblPr']['w:bidiVisual'] = {}
    }
    return baseTable
  },

  _getColSpecs: function (cols, opts) {
    var self = this
    return cols[0].map(function (col, idx) {
      return self._tblGrid(opts, col)
    })
  },

  // TODO
  _tblGrid: function (opts, col) {
    return {
      'w:gridCol': {
        '@w:w': col.opts.cellColWidth || opts.tableColWidth || '1'
      }
    }
  },

  _getRow: function (cells, opts) {
    return {
      'w:tr': {
        '@w:rsidR': '00995B51',
        '@w:rsidTr': '007F1D13',
        '#list': [cells] // populate this with an array of table cell objects
      }
    }
  },

  _getCell: function (val, opts, tblOpts) {
    opts = opts || {}
    // var b = {};

    // if (opts.b) {
    //   b = {
    //     "w:tc": {
    //       "w:p": {
    //         "w:r": {
    //           "w:rPr": {
    //             "w:b": {}
    //           }
    //         }
    //       }
    //     }
    //   }
    // }

    debug('Cell value is ' + val);
    console.log('Cell value is ' + val);
    var splitLines = val.split(/\r?\n/);
    for (var i = 0; i < splitLines.length; i++)
    {
      debug('split line is' + splitLines[i]);
    }

    var cellObj = {
      'w:tc': {
        'w:tcPr': {
          'w:tcW': {
            '@w:w': opts.cellColWidth || tblOpts.tableColWidth || '0',
            '@w:type': 'dxa'
          },
          'w:gridSpan': {
            '@w:val': opts.gridSpan || '1'
          },
          'w:vAlign': {
            '@w:val': opts.vAlign || 'top'
          },
          'w:shd': {
            '@w:val': 'clear',
            '@w:color': 'auto',
            '@w:fill': (opts.shd && opts.shd.fill) || '',
            '@w:themeFill': (opts.shd && opts.shd.themeFill) || '',
            '@w:themeFillTint': (opts.shd && opts.shd.themeFillTint) || ''
          }
        },
        'w:p': {
          '@w:rsidR': '00995B51',
          '@w:rsidRPr': '00722E63',
          '@w:rsidRDefault': '00995B51',
          'w:pPr': {
            'w:jc': {
              '@w:val': opts.align || tblOpts.tableAlign || 'center'
            }
            // "w:rPr": {
            //   "w:rFonts": {
            //     "@w:asciiTheme": "majorEastAsia",
            //     "@w:eastAsiaTheme": "majorEastAsia",
            //     "@w:hAnsiTheme": "majorEastAsia"
            //   },
            //   // "w:b": {},
            //   "w:sz": {
            //     "@w:val": "24"
            //   },
            //   "w:szCs": {
            //     "@w:val": "24"
            //   }
            // }
          },
          'w:r': {
            '@w:rsidRPr': '00722E63',
            'w:rPr': {
              'w:rFonts': {
                '@w:ascii': opts.fontFamily || tblOpts.tableFontFamily || '宋体',
                '@w:hAnsi': opts.fontFamily || tblOpts.tableFontFamily || '宋体'
              },
              'w:color': {
                '@w:val': opts.color || tblOpts.tableColor || '000'
              },
              'w:b': {},
              'w:sz': {
                '@w:val': opts.sz || tblOpts.sz || '24'
              },
              'w:szCs': {
                '@w:val': opts.sz || tblOpts.sz || '24'
              }
            },
            'w:t': val
          }
        }
      }
    }

    if (!opts.b) {
      delete cellObj['w:tc']['w:p']['w:r']['w:rPr']['w:b']
    }
    if (tblOpts.rtl) {
      cellObj['w:tc']['w:p']['w:pPr']['w:bidi'] = { '@w:val': '1' }
    }
    if (opts.rtl) {
      cellObj['w:tc']['w:p']['w:r']['w:rPr']['w:rtl'] = { '@w:val': '1' }
    }

    return cellObj
  }
}
<|endoftext|>


<commit_before>"use strict";
// Generated by CoffeeScript 1.3.3
(typeof exports !== "undefined" && exports !== null ? exports : window).DomUtils = {
  documentReady: (function() {
    var loaded = document.readyState !== "loading", listeners, eventHandler = function() {
      var ref, i, len;
      loaded = true;
      ref = listeners;
      window.removeEventListener("DOMContentLoaded", eventHandler);
      listeners = eventHandler = null;
      for (i = 0, len = ref.length; i < len; i++) {
        ref[i].call();
      }
    };
    return function(callback) {
      if (typeof callback !== "function") {}
      else if (loaded || document.readyState !== "loading") {
        loaded = true;
        callback();
      } else if (listeners) {
        listeners.push(callback);
      } else {
        window.addEventListener("DOMContentLoaded", eventHandler);
        listeners = [callback];
      }
    };
  })(),
  addElementList: function(els, overlayOptions) {
    var parent, _i, _len;
    parent = document.createElement("div");
    if (overlayOptions.id != null) {
      parent.id = overlayOptions.id;
    }
    if (overlayOptions.className != null) {
      parent.className = overlayOptions.className;
    }
    for (_i = 0, _len = els.length; _i < _len; _i++) {
      parent.appendChild(els[_i]);
    }
    document.documentElement.appendChild(parent);
    return parent;
  },
  removeNode: function(el) {
    el.parentNode.removeChild(el);
  },
  makeXPath: function(elementArray) {
    for (var _i = 0, _len = elementArray.length * 2, element, xpath = new Array(_len); _i < _len; _i += 2) {
      element = elementArray[_i / 2];
      xpath[_i] = ".//" + element, xpath[_i + 1] = ".//xhtml:" + element;
    }
    return xpath.join(" | ");
  },
  namespaceResolver: function(namespace) {
    return (namespace === "xhtml") ? "http://www.w3.org/1999/xhtml" : null;
  },
  evaluateXPath: function(xpath, resultType) {
    return document.evaluate(xpath, document.webkitIsFullScreen ? document.webkitFullscreenElement
      : document.documentElement, this.namespaceResolver, resultType, null);
  },
  getVisibleClientRect: function(element) {
    var child, cr, rect0, arr, style, _i, _j, _len, _len1, _ref;
    arr = element.getClientRects();
    for (_i = 0, _len = arr.length; _i < _len; _i++) {
      rect0 = arr[_i];
      if (rect0.width <= 0 || rect0.height <= 0) {
        _ref = element.children;
        for (_j = 0, _len1 = _ref.length; _j < _len1; _j++) {
          child = _ref[_j];
          style = window.getComputedStyle(child, null);
          if (style.getPropertyValue('float') === 'none' && style.getPropertyValue('position') !== 'absolute') {
            continue;
          }
          if (cr = this.getVisibleClientRect(child)) {
            return cr;
          }
        }
      } else {
        cr = VRect.cropRectToVisible(rect0.left, rect0.top, rect0.right, rect0.bottom);
        if (cr == null || cr[2] - cr[0] < 3 || cr[3] - cr[1] < 3) {
          continue;
        }
        style = window.getComputedStyle(element, null);
        if (style.getPropertyValue('visibility') !== 'visible' || style.getPropertyValue('display') === 'none') {
          continue;
        }
        return cr;
      }
    }
    return null;
  },
  getClientRectsForAreas: function(output, cr, areas) {
    var area, coords, diff, sqrt2 = Math.sqrt(2), rect, x1, x2, y1, y2, _i, _len;
    for (_i = 0, _len = areas.length; _i < _len; _i++) {
      area = areas[_i];
      coords = area.coords.split(",").map(parseInt);
      if (isNaN(coords[1])) {
        continue;
      }
      switch (area.shape.toLowerCase()) {
      case "circle": case "circ":
        y1 = coords[0], y2 = coords[1], diff = coords[2] / sqrt2;
        x1 = y1 - diff, x2 = y1 + diff, y1 = y2 - diff;
        y2 = y2 + diff;
        break;
      case "default":
        x1 = 0, y1 = 0, x2 = cr.width, y2 = cr.height;
        break;
      case "rect": case "rectangle": default:
        x1 = coords[0], y1 = coords[1], x2 = coords[2], y2 = coords[3];
        break;
      }
      rect = VRect.cropRectToVisible(x1 + cr.left, y1 + cr.top //
        , x2 + cr.left, y2 + cr.top);
      if (rect) {
        output.push({
          element: area,
          rect: rect,
          notSecond: true
        });
      }
    }
  },
  isVisibile: function(element) {
    var rect = element.getBoundingClientRect();
    return !(rect.bottom <= 0 || rect.top >= window.innerHeight || rect.right <= 0
      || rect.left >= window.innerWidth || rect.height < 0.5 || rect.width < 0.5);
  },
  _unselectableTypes: ["button", "checkbox", "color", "file", "hidden", "image", "radio", "reset", "submit"],
  isSelectable: function(element) {
    var str;
    return element.isContentEditable || (str = element.nodeName.toLowerCase()) === "textarea" || //
      (str === "input" && this._unselectableTypes.indexOf(element.type) === -1);
  },
  simulateSelect: function(element) {
    element.focus();
    try {
      var len = element.value ? +element.value.length : -1;
      if (len >= 0 && element.setSelectionRange) {
        element.setSelectionRange(len, len);
      }
    } catch (e) {
    }
  },
  _eventSequence: ["mouseover", "mousedown", "mouseup", "click"],
  simulateClick: function(element, modifiers) {
    var eventSequence = this._eventSequence, mouseEvent, _i, _len;
    modifiers || (modifiers = {});
    for (_i = 0, _len = eventSequence.length; _i < _len; _i++) {
      mouseEvent = document.createEvent("MouseEvents");
      mouseEvent.initMouseEvent(eventSequence[_i], true, true, window, 1, 0, 0, 0, 0, modifiers.ctrlKey, modifiers.altKey, modifiers.shiftKey, modifiers.metaKey, 0, null);
      element.dispatchEvent(mouseEvent);
    }
  },
  simulateHover: function(element) {
    var mouseEvent = document.createEvent("MouseEvents");
    mouseEvent.initMouseEvent("mouseover", true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
    element.dispatchEvent(mouseEvent);
    element.focus();
  },
  simulateBackspace: function(element) {
    var start = element.selectionStart, end = element.selectionEnd, event;
    if (!element.setRangeText) {
      return;
    }
    if (start >= end && element.setSelectionRange) {
      element.setSelectionRange(start - 1, start);
    }
    element.setRangeText("");
    event = document.createEvent("HTMLEvents");
    event.initEvent("input", true, false);
    element.dispatchEvent(event);
  },
  markVRect: function(rect) {
    var flashEl = document.createElement("div");
    flashEl.className = "vimB vimR vimFlash";
    flashEl.style.left = rect[0] + window.scrollX + "px";
    flashEl.style.top = rect[1] + window.scrollY + "px";
    flashEl.style.width = (rect[2] - rect[0]) + "px";
    flashEl.style.height = (rect[3] - rect[1]) + "px";
    document.documentElement.appendChild(flashEl);
    return flashEl;
  },
  _flashLastingTime: 400,
  flashVRect: function(rect, time) {
    var flashEl = this.markVRect(rect);
    return setTimeout(this.removeNode.bind(this, flashEl), time != null ? time : this._flashLastingTime);
  },
  flashClientRect: function(rect, time) {
    return this.flashVRect(VRect.copy(rect), time);
  },
  suppressPropagation: function(event) {
    event.stopImmediatePropagation();
  },
  suppressEvent: function(event) {
    event.preventDefault();
    this.suppressPropagation(event);
  }
};

/* VRect: int[4], [left, top, right, bottom] */
(typeof exports !== "undefined" && exports !== null ? exports : window).VRect = {
  create: function(x1, y1, x2, y2) {
    return [x1, y1, x2, y2];
  },
  copy: function(rect) {
    if (rect instanceof ClientRect) {
      return [rect.left, rect.top, rect.right, rect.bottom];
    }
    return [rect[0], rect[1], rect[2], rect[3]];
  },
  cropRectToVisible: function(left, top, right, bottom) {
    var iw = window.innerWidth, ih;
    return (left < iw - 4 && top < (ih = window.innerHeight) - 4) ? [ //
      left  >=  0 ? left  :  0, //
      top   >=  0 ? top   :  0, //
      right <= iw ? right : iw, //
      bottom<= ih ? bottom: ih  //
    ] : null;
  },
  SubtractSequence: function(rect2, rect1) { // rect1 - rect2
    var x1 = Math.max(rect1[0], rect2[0]), x2 = Math.min(rect1[2], rect2[2]) //
      , y1 = Math.max(rect1[1], rect2[1]), y2 = Math.min(rect1[3], rect2[3]);
    if (!(x2 > x1 && y2 > y1)) {
      this.push(rect1);
      return;
    }
    // 1 2 4
    // 3   5
    // 6 7 8
    var x0 = rect1[0], x3 = rect1[2], y0 = rect1[1], y3 = rect1[3];
    if (y0 < y1) {
      if (y2 < y3) {
        if (x0 < x1) {
          if (x2 < x3) {
            this.push([x0, y0, x1, y1], [x1, y0, x2, y1], [x0, y1, x1, y2], [x2, y0, x3, y1], [x2, y1, x3, y2], [x0, y2, x1, y3], [x1, y2, x2, y3], [x2, y2, x3, y3]); // 1 2 3 4 5 6 7 8
          } else {
            this.push([x0, y0, x1, y1], [x1, y0, x2, y1], [x0, y1, x1, y2], [x0, y2, x1, y3], [x1, y2, x2, y3]); // 1 2 3 6 7
          }
        } else if (x2 < x3) {
          this.push([x1, y0, x2, y1], [x2, y0, x3, y1], [x2, y1, x3, y2], [x1, y2, x2, y3], [x2, y2, x3, y3]); // 2 4 5 7 8
        } else {
          this.push([x1, y0, x2, y1], [x1, y2, x2, y3]); // 2 7
        }
      } else if (x0 < x1) {
        if (x2 < x3) {
          this.push([x0, y0, x1, y1], [x1, y0, x2, y1], [x0, y1, x1, y2], [x2, y0, x3, y1], [x2, y1, x3, y2]); // 1 2 3 4 5
        } else {
          this.push([x0, y0, x1, y1], [x1, y0, x2, y1], [x0, y1, x1, y2]); // 1 2 3
        }
      } else if (x2 < x3) {
        this.push([x1, y0, x2, y1], [x2, y0, x3, y1], [x2, y1, x3, y2]); // 2 4 5
      } else {
        this.push([x1, y0, x2, y1]); // 2
      }
    } else if (y2 < y3) {
      if (x0 < x1) {
        if (x2 < x3) {
          this.push([x0, y1, x1, y2], [x2, y1, x3, y2], [x0, y2, x1, y3], [x1, y2, x2, y3], [x2, y2, x3, y3]); // 3 5 6 7 8
        } else {
          this.push([x0, y1, x1, y2], [x0, y2, x1, y3], [x1, y2, x2, y3]); // 3 6 7
        }
      } else if (x2 < x3) {
        this.push([x2, y1, x3, y2], [x1, y2, x2, y3], [x2, y2, x3, y3]); // 5 7 8
      } else {
        this.push([x1, y2, x2, y3]); // 7
      }
    } else if (x0 < x1) {
      if (x2 < x3) {
        this.push([x0, y1, x1, y2], [x2, y1, x3, y2]); // 3 5
      } else {
        this.push([x0, y1, x1, y2]); // 3
      }
    } else if (x2 < x3) {
      this.push([x2, y1, x3, y2]); // 5
    }
  }
};<commit_msg>DomUtils.simulateClick add a "mouseout" event<commit_after>"use strict";
// Generated by CoffeeScript 1.3.3
(typeof exports !== "undefined" && exports !== null ? exports : window).DomUtils = {
  documentReady: (function() {
    var loaded = document.readyState !== "loading", listeners, eventHandler = function() {
      var ref, i, len;
      loaded = true;
      ref = listeners;
      window.removeEventListener("DOMContentLoaded", eventHandler);
      listeners = eventHandler = null;
      for (i = 0, len = ref.length; i < len; i++) {
        ref[i].call();
      }
    };
    return function(callback) {
      if (typeof callback !== "function") {}
      else if (loaded || document.readyState !== "loading") {
        loaded = true;
        callback();
      } else if (listeners) {
        listeners.push(callback);
      } else {
        window.addEventListener("DOMContentLoaded", eventHandler);
        listeners = [callback];
      }
    };
  })(),
  addElementList: function(els, overlayOptions) {
    var parent, _i, _len;
    parent = document.createElement("div");
    if (overlayOptions.id != null) {
      parent.id = overlayOptions.id;
    }
    if (overlayOptions.className != null) {
      parent.className = overlayOptions.className;
    }
    for (_i = 0, _len = els.length; _i < _len; _i++) {
      parent.appendChild(els[_i]);
    }
    document.documentElement.appendChild(parent);
    return parent;
  },
  removeNode: function(el) {
    el.parentNode.removeChild(el);
  },
  makeXPath: function(elementArray) {
    for (var _i = 0, _len = elementArray.length * 2, element, xpath = new Array(_len); _i < _len; _i += 2) {
      element = elementArray[_i / 2];
      xpath[_i] = ".//" + element, xpath[_i + 1] = ".//xhtml:" + element;
    }
    return xpath.join(" | ");
  },
  namespaceResolver: function(namespace) {
    return (namespace === "xhtml") ? "http://www.w3.org/1999/xhtml" : null;
  },
  evaluateXPath: function(xpath, resultType) {
    return document.evaluate(xpath, document.webkitIsFullScreen ? document.webkitFullscreenElement
      : document.documentElement, this.namespaceResolver, resultType, null);
  },
  getVisibleClientRect: function(element) {
    var child, cr, rect0, arr, style, _i, _j, _len, _len1, _ref;
    arr = element.getClientRects();
    for (_i = 0, _len = arr.length; _i < _len; _i++) {
      rect0 = arr[_i];
      if (rect0.width <= 0 || rect0.height <= 0) {
        _ref = element.children;
        for (_j = 0, _len1 = _ref.length; _j < _len1; _j++) {
          child = _ref[_j];
          style = window.getComputedStyle(child, null);
          if (style.getPropertyValue('float') === 'none' && style.getPropertyValue('position') !== 'absolute') {
            continue;
          }
          if (cr = this.getVisibleClientRect(child)) {
            return cr;
          }
        }
      } else {
        cr = VRect.cropRectToVisible(rect0.left, rect0.top, rect0.right, rect0.bottom);
        if (cr == null || cr[2] - cr[0] < 3 || cr[3] - cr[1] < 3) {
          continue;
        }
        style = window.getComputedStyle(element, null);
        if (style.getPropertyValue('visibility') !== 'visible' || style.getPropertyValue('display') === 'none') {
          continue;
        }
        return cr;
      }
    }
    return null;
  },
  getClientRectsForAreas: function(output, cr, areas) {
    var area, coords, diff, sqrt2 = Math.sqrt(2), rect, x1, x2, y1, y2, _i, _len;
    for (_i = 0, _len = areas.length; _i < _len; _i++) {
      area = areas[_i];
      coords = area.coords.split(",").map(parseInt);
      if (isNaN(coords[1])) {
        continue;
      }
      switch (area.shape.toLowerCase()) {
      case "circle": case "circ":
        y1 = coords[0], y2 = coords[1], diff = coords[2] / sqrt2;
        x1 = y1 - diff, x2 = y1 + diff, y1 = y2 - diff;
        y2 = y2 + diff;
        break;
      case "default":
        x1 = 0, y1 = 0, x2 = cr.width, y2 = cr.height;
        break;
      case "rect": case "rectangle": default:
        x1 = coords[0], y1 = coords[1], x2 = coords[2], y2 = coords[3];
        break;
      }
      rect = VRect.cropRectToVisible(x1 + cr.left, y1 + cr.top //
        , x2 + cr.left, y2 + cr.top);
      if (rect) {
        output.push({
          element: area,
          rect: rect,
          notSecond: true
        });
      }
    }
  },
  isVisibile: function(element) {
    var rect = element.getBoundingClientRect();
    return !(rect.bottom <= 0 || rect.top >= window.innerHeight || rect.right <= 0
      || rect.left >= window.innerWidth || rect.height < 0.5 || rect.width < 0.5);
  },
  _unselectableTypes: ["button", "checkbox", "color", "file", "hidden", "image", "radio", "reset", "submit"],
  isSelectable: function(element) {
    var str;
    return element.isContentEditable || (str = element.nodeName.toLowerCase()) === "textarea" || //
      (str === "input" && this._unselectableTypes.indexOf(element.type) === -1);
  },
  simulateSelect: function(element) {
    element.focus();
    try {
      var len = element.value ? +element.value.length : -1;
      if (len >= 0 && element.setSelectionRange) {
        element.setSelectionRange(len, len);
      }
    } catch (e) {
    }
  },
  _eventSequence: ["mouseover", "mousedown", "mouseup", "click", "mouseout"],
  simulateClick: function(element, modifiers) {
    var eventSequence = this._eventSequence, mouseEvent, _i, _len;
    modifiers || (modifiers = {});
    for (_i = 0, _len = eventSequence.length; _i < _len; _i++) {
      mouseEvent = document.createEvent("MouseEvents");
      mouseEvent.initMouseEvent(eventSequence[_i], true, true, window, 1, 0, 0, 0, 0, modifiers.ctrlKey, modifiers.altKey, modifiers.shiftKey, modifiers.metaKey, 0, null);
      element.dispatchEvent(mouseEvent);
    }
  },
  simulateHover: function(element) {
    var mouseEvent = document.createEvent("MouseEvents");
    mouseEvent.initMouseEvent("mouseover", true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
    element.dispatchEvent(mouseEvent);
    element.focus();
  },
  simulateBackspace: function(element) {
    var start = element.selectionStart, end = element.selectionEnd, event;
    if (!element.setRangeText) {
      return;
    }
    if (start >= end && element.setSelectionRange) {
      element.setSelectionRange(start - 1, start);
    }
    element.setRangeText("");
    event = document.createEvent("HTMLEvents");
    event.initEvent("input", true, false);
    element.dispatchEvent(event);
  },
  markVRect: function(rect) {
    var flashEl = document.createElement("div");
    flashEl.className = "vimB vimR vimFlash";
    flashEl.style.left = rect[0] + window.scrollX + "px";
    flashEl.style.top = rect[1] + window.scrollY + "px";
    flashEl.style.width = (rect[2] - rect[0]) + "px";
    flashEl.style.height = (rect[3] - rect[1]) + "px";
    document.documentElement.appendChild(flashEl);
    return flashEl;
  },
  _flashLastingTime: 400,
  flashVRect: function(rect, time) {
    var flashEl = this.markVRect(rect);
    return setTimeout(this.removeNode.bind(this, flashEl), time != null ? time : this._flashLastingTime);
  },
  flashClientRect: function(rect, time) {
    return this.flashVRect(VRect.copy(rect), time);
  },
  suppressPropagation: function(event) {
    event.stopImmediatePropagation();
  },
  suppressEvent: function(event) {
    event.preventDefault();
    this.suppressPropagation(event);
  }
};

/* VRect: int[4], [left, top, right, bottom] */
(typeof exports !== "undefined" && exports !== null ? exports : window).VRect = {
  create: function(x1, y1, x2, y2) {
    return [x1, y1, x2, y2];
  },
  copy: function(rect) {
    if (rect instanceof ClientRect) {
      return [rect.left, rect.top, rect.right, rect.bottom];
    }
    return [rect[0], rect[1], rect[2], rect[3]];
  },
  cropRectToVisible: function(left, top, right, bottom) {
    var iw = window.innerWidth, ih;
    return (left < iw - 4 && top < (ih = window.innerHeight) - 4) ? [ //
      left  >=  0 ? left  :  0, //
      top   >=  0 ? top   :  0, //
      right <= iw ? right : iw, //
      bottom<= ih ? bottom: ih  //
    ] : null;
  },
  SubtractSequence: function(rect2, rect1) { // rect1 - rect2
    var x1 = Math.max(rect1[0], rect2[0]), x2 = Math.min(rect1[2], rect2[2]) //
      , y1 = Math.max(rect1[1], rect2[1]), y2 = Math.min(rect1[3], rect2[3]);
    if (!(x2 > x1 && y2 > y1)) {
      this.push(rect1);
      return;
    }
    // 1 2 4
    // 3   5
    // 6 7 8
    var x0 = rect1[0], x3 = rect1[2], y0 = rect1[1], y3 = rect1[3];
    if (y0 < y1) {
      if (y2 < y3) {
        if (x0 < x1) {
          if (x2 < x3) {
            this.push([x0, y0, x1, y1], [x1, y0, x2, y1], [x0, y1, x1, y2], [x2, y0, x3, y1], [x2, y1, x3, y2], [x0, y2, x1, y3], [x1, y2, x2, y3], [x2, y2, x3, y3]); // 1 2 3 4 5 6 7 8
          } else {
            this.push([x0, y0, x1, y1], [x1, y0, x2, y1], [x0, y1, x1, y2], [x0, y2, x1, y3], [x1, y2, x2, y3]); // 1 2 3 6 7
          }
        } else if (x2 < x3) {
          this.push([x1, y0, x2, y1], [x2, y0, x3, y1], [x2, y1, x3, y2], [x1, y2, x2, y3], [x2, y2, x3, y3]); // 2 4 5 7 8
        } else {
          this.push([x1, y0, x2, y1], [x1, y2, x2, y3]); // 2 7
        }
      } else if (x0 < x1) {
        if (x2 < x3) {
          this.push([x0, y0, x1, y1], [x1, y0, x2, y1], [x0, y1, x1, y2], [x2, y0, x3, y1], [x2, y1, x3, y2]); // 1 2 3 4 5
        } else {
          this.push([x0, y0, x1, y1], [x1, y0, x2, y1], [x0, y1, x1, y2]); // 1 2 3
        }
      } else if (x2 < x3) {
        this.push([x1, y0, x2, y1], [x2, y0, x3, y1], [x2, y1, x3, y2]); // 2 4 5
      } else {
        this.push([x1, y0, x2, y1]); // 2
      }
    } else if (y2 < y3) {
      if (x0 < x1) {
        if (x2 < x3) {
          this.push([x0, y1, x1, y2], [x2, y1, x3, y2], [x0, y2, x1, y3], [x1, y2, x2, y3], [x2, y2, x3, y3]); // 3 5 6 7 8
        } else {
          this.push([x0, y1, x1, y2], [x0, y2, x1, y3], [x1, y2, x2, y3]); // 3 6 7
        }
      } else if (x2 < x3) {
        this.push([x2, y1, x3, y2], [x1, y2, x2, y3], [x2, y2, x3, y3]); // 5 7 8
      } else {
        this.push([x1, y2, x2, y3]); // 7
      }
    } else if (x0 < x1) {
      if (x2 < x3) {
        this.push([x0, y1, x1, y2], [x2, y1, x3, y2]); // 3 5
      } else {
        this.push([x0, y1, x1, y2]); // 3
      }
    } else if (x2 < x3) {
      this.push([x2, y1, x3, y2]); // 5
    }
  }
};<|endoftext|>