<commit_before>import BaseGulp from './baseGulp'
import extend from 'extend'
import Util from 'gulp-util'
import stringify from 'stringify-object'

const Default = {
  debug: false,
  watch: true  // register a watch task that aggregates all watches and runs the full sequence
}

const TaskSeries = class extends BaseGulp {

  /**
   *
   * @param gulp - gulp instance
   * @param configs - customized overrides
   */
  constructor(gulp, taskName, recipes, ...configs) {
    super(gulp, extend(true, {}, Default, {task: {name: taskName}}, ...configs))
    this.recipes = recipes
    this.registerTask(this.taskName(), recipes)

    if (this.config.watch) {
      this.registerWatchTask(this.watchTaskName(), recipes)
    }
  }

  createHelpText() {
    let taskNames = this.flattenedRecipes().reduce((a, b) => {
      return a.concat(this.toTaskName(b))
    }, [])

    // use the config to generate the dynamic help
    return `Runs series [${taskNames.join(', ')}]`
  }

  createWatchHelpText() {
    let taskNames = this.watchableRecipes().reduce((a, b) => {
      return a.concat(b.taskName())
    }, [])

    return Util.colors.grey(`|___ aggregates watches from [${taskNames.join(', ')}] and runs full series`)
  }

  registerTask(taskName) {
    let tasks = this.toTaskNames(this.recipes)

    this.debug(`Registering task: ${Util.colors.green(taskName)} for ${stringify(tasks)}`)
    this.gulp.task(taskName, this.createHelpText(), () => {
      return this.run(tasks)
    })
  }

  flatten(list) {
    return list.reduce(
      (a, b) => a.concat(Array.isArray(b) ? this.flatten(b) : b), []
    )
  }

  flattenedRecipes() {
    let recipes = this.flatten(this.recipes)
    this.debugDump(`flattenedRecipes`, recipes)
    return recipes
  }

  watchableRecipes() {
    // create an array of watchable recipes
    let watchableRecipes = []
    for (let recipe of this.flattenedRecipes()) {
      if ((typeof recipe !== "string") && recipe.config.watch) {
        watchableRecipes.push(recipe)
      }
    }
    return watchableRecipes
  }

  registerWatchTask(taskName, recipes) {
    // generate watch task
    let watchableRecipes = this.watchableRecipes()
    if (watchableRecipes.length < 1) {
      this.debug(`No watchable recipes for task: ${Util.colors.green(taskName)}`)
      return
    }

    this.debug(`Registering task: ${Util.colors.green(taskName)}`)
    this.gulp.task(taskName, this.createWatchHelpText(), () => {

      // watch the watchable recipes and make them #run the series
      for (let recipe of watchableRecipes) {
        this.log(`[${Util.colors.green(taskName)}] watching ${recipe.taskName()} ${recipe.config.watch.glob}...`)
        this.gulp.watch(recipe.config.watch.glob, recipe.config.watch.options, (event) => {
          this.log(`[${Util.colors.green(taskName)}] ${event.path} was ${event.type}, running series...`);
          return Promise
            .resolve(this.run(recipes))
            .then(() => this.log(`[${Util.colors.green(taskName)}] finished`))
        })
      }
    })
  }

  run(tasks) {
    // generate the task sequence
    return this.runSequence(...tasks)
  }

  toTaskName(recipe) {
    let taskName = null
    if (typeof recipe === "string") {
      taskName = recipe
    }
    else {
      taskName = recipe.taskName()
    }
    return taskName
  }

  toTaskNames(recipes, tasks = []) {
    //this.debugDump(`toTaskNames`, recipes)
    for (let recipe of recipes) {
      //this.debugDump(`recipe taskName[${recipe.taskName? recipe.taskName() : ''}] isArray[${Array.isArray(recipe)}]`, recipe)
      if (Array.isArray(recipe)) {
        tasks.push(this.toTaskNames(recipe, []))
      }
      else {
        let taskName = this.toTaskName(recipe)
        this.validateTaskString(taskName)
        this.debug(`Adding to list ${taskName}`)
        tasks.push(taskName)
      }
    }

    return tasks
  }

  validateTaskString(taskName) {
    let isString = (typeof taskName === "string")

    if (!isString) {
      throw new Error(`Task ${taskName} is not a string.`)
    }

    if (isString && !this.gulp.hasTask(taskName)) {
      throw new Error(`Task ${taskName} is not configured task in gulp.`)
    }
  }

  // -----------------------------------
  // originally run-sequence code https://github.com/OverZealous/run-sequence
  // Copyright (c) 2014 [Phil DeJarnett](http://overzealous.com)
  // - Will be unnecessary with gulp 4.0
  // - Forced to include this/modify it as the #use(gulp) binding of the gulp instance didn't work with es class approach

  runSequence(...taskSets) {
    this.callBack = typeof taskSets[taskSets.length - 1] === 'function' ? taskSets.pop() : false
    this.debug(`currentTaskSet = null`)
    this.currentTaskSet = null
    this.verifyTaskSets(taskSets)
    this.taskSets = taskSets

    this.onEnd = (e) => this.onTaskEnd(e)
    this.onErr = (e) => this.onError(e)

    this.gulp.on('task_stop', this.onEnd)
    this.gulp.on('task_err', this.onErr)

    this.runNextSet()
  }

  finish(e) {
    this.debugDump(`finish`, e)
    this.gulp.removeListener('task_stop', this.onEnd)
    this.gulp.removeListener('task_err', this.onErr)

    let error = null
    if (e && e.err) {
      this.debugDump(`finish e`, e)
      //error = new Util.PluginError('run-sequence', {
      //  message: `An error occured in task [${e.task}].`
      //})
      error = {
        task: e.task,
        message: e.err,
        plugin: e.plugin || ''
      }
    }

    if (this.callback) {
      this.callback(error)
    }
    else if (error) {
      //this.log(Util.colors.red(error.toString()))
      this.notifyError(error)
    }
  }

  onError(err) {
    this.debugDump(`onError`, err)
    this.finish(err)
  }

  onTaskEnd(event) {
    this.debugDump(`onTaskEnd`, event)
    //this.debugDump(`this.currentTaskSet`, this.currentTaskSet)

    let i = this.currentTaskSet.indexOf(event.task)
    if (i > -1) {
      this.currentTaskSet.splice(i, 1)
    }
    if (this.currentTaskSet.length === 0) {
      this.runNextSet()
    }
  }

  runNextSet() {
    if (this.taskSets.length) {
      let command = this.taskSets.shift()
      if (!Array.isArray(command)) {
        command = [command]
      }
      this.debug(`gulp.start(currentTaskSet = ${command}) isArray: ${Array.isArray(command)}`)
      this.currentTaskSet = command
      this.gulp.start(command)
    }
    else {
      this.finish()
    }
  }

  verifyTaskSets(taskSets, foundTasks = {}) {

    this.debug(`verifyTaskSets: ${stringify(taskSets)}`)

    if (taskSets.length === 0) {
      throw new Error('No tasks were provided to run-sequence')
    }

    for (let nextEntry of taskSets) {
      let isString = (typeof nextEntry === "string")
      let isArray = Array.isArray(nextEntry)

      if (!isString && !isArray) {
        throw new Error(`Task \`${nextEntry}\` (${typeof nextEntry}) is neither a string nor an array: \n${stringify(nextEntry)}`)
      }

      if (isString && !this.gulp.hasTask(nextEntry)) {
        throw new Error(`Task ${nextEntry} is not configured as a task on gulp.`)
      }

      if (foundTasks[nextEntry]) {
        throw new Error(`Task ${nextEntry} is listed more than once. This is probably a typo.`)
      }
      foundTasks[nextEntry] = true

      if (isArray) {
        if (nextEntry.length === 0) {
          throw new Error(`An empty array was provided as a task set`)
        }
        this.verifyTaskSets(nextEntry, foundTasks)
      }
    }
  }
}

export default TaskSeries
<commit_msg>more debugging, about to switch to gulp-4 because the nested sequence/parallel just isn't working correctly<commit_after>import BaseGulp from './baseGulp'
import extend from 'extend'
import Util from 'gulp-util'
import stringify from 'stringify-object'

const Default = {
  debug: false,
  watch: true  // register a watch task that aggregates all watches and runs the full sequence
}

const TaskSeries = class extends BaseGulp {

  /**
   *
   * @param gulp - gulp instance
   * @param configs - customized overrides
   */
  constructor(gulp, taskName, recipes, ...configs) {
    super(gulp, extend(true, {}, Default, {task: {name: taskName}}, ...configs))
    this.recipes = recipes
    this.registerTask(this.taskName(), recipes)

    if (this.config.watch) {
      this.registerWatchTask(this.watchTaskName(), recipes)
    }
  }

  createHelpText() {
    let taskNames = this.flattenedRecipes().reduce((a, b) => {
      return a.concat(this.toTaskName(b))
    }, [])

    // use the config to generate the dynamic help
    return `Runs series [${taskNames.join(', ')}]`
  }

  createWatchHelpText() {
    let taskNames = this.watchableRecipes().reduce((a, b) => {
      return a.concat(b.taskName())
    }, [])

    return Util.colors.grey(`|___ aggregates watches from [${taskNames.join(', ')}] and runs full series`)
  }

  registerTask(taskName) {
    let tasks = this.toTaskNames(this.recipes)

    this.debug(`Registering task: ${Util.colors.green(taskName)} for ${stringify(tasks)}`)
    this.gulp.task(taskName, this.createHelpText(), () => {
      return this.run(tasks)
    })
  }

  flatten(list) {
    return list.reduce(
      (a, b) => a.concat(Array.isArray(b) ? this.flatten(b) : b), []
    )
  }

  flattenedRecipes() {
    let recipes = this.flatten(this.recipes)
    this.debugDump(`flattenedRecipes`, recipes)
    return recipes
  }

  watchableRecipes() {
    // create an array of watchable recipes
    let watchableRecipes = []
    for (let recipe of this.flattenedRecipes()) {
      if ((typeof recipe !== "string") && recipe.config.watch) {
        watchableRecipes.push(recipe)
      }
    }
    return watchableRecipes
  }

  registerWatchTask(taskName, recipes) {
    // generate watch task
    let watchableRecipes = this.watchableRecipes()
    if (watchableRecipes.length < 1) {
      this.debug(`No watchable recipes for task: ${Util.colors.green(taskName)}`)
      return
    }

    this.debug(`Registering task: ${Util.colors.green(taskName)}`)
    this.gulp.task(taskName, this.createWatchHelpText(), () => {

      // watch the watchable recipes and make them #run the series
      for (let recipe of watchableRecipes) {
        this.log(`[${Util.colors.green(taskName)}] watching ${recipe.taskName()} ${recipe.config.watch.glob}...`)
        this.gulp.watch(recipe.config.watch.glob, recipe.config.watch.options, (event) => {
          this.log(`[${Util.colors.green(taskName)}] ${event.path} was ${event.type}, running series...`);
          return Promise
            .resolve(this.run(recipes))
            .then(() => this.log(`[${Util.colors.green(taskName)}] finished`))
        })
      }
    })
  }

  run(tasks) {
    // generate the task sequence
    return this.runSequence(...tasks)
  }

  toTaskName(recipe) {
    let taskName = null
    if (typeof recipe === "string") {
      taskName = recipe
    }
    else {
      taskName = recipe.taskName()
    }
    return taskName
  }

  toTaskNames(recipes, tasks = []) {
    //this.debugDump(`toTaskNames`, recipes)
    for (let recipe of recipes) {
      //this.debugDump(`recipe taskName[${recipe.taskName? recipe.taskName() : ''}] isArray[${Array.isArray(recipe)}]`, recipe)
      if (Array.isArray(recipe)) {
        tasks.push(this.toTaskNames(recipe, []))
      }
      else {
        let taskName = this.toTaskName(recipe)
        this.validateTaskString(taskName)
        this.debug(`Adding to list ${taskName}`)
        tasks.push(taskName)
      }
    }

    return tasks
  }

  validateTaskString(taskName) {
    let isString = (typeof taskName === "string")

    if (!isString) {
      throw new Error(`Task ${taskName} is not a string.`)
    }

    if (isString && !this.gulp.hasTask(taskName)) {
      throw new Error(`Task ${taskName} is not configured task in gulp.`)
    }
  }

  // -----------------------------------
  // originally run-sequence code https://github.com/OverZealous/run-sequence
  // Copyright (c) 2014 [Phil DeJarnett](http://overzealous.com)
  // - Will be unnecessary with gulp 4.0
  // - Forced to include this/modify it as the #use(gulp) binding of the gulp instance didn't work with es class approach

  runSequence(...taskSets) {
    this.debugDump(`runSequence`, taskSets)

    this.callBack = typeof taskSets[taskSets.length - 1] === 'function' ? taskSets.pop() : false
    this.debug(`currentTaskSet = null`)
    this.currentTaskSet = null
    this.verifyTaskSets(taskSets)
    this.taskSets = taskSets

    this._onTaskEnd = (e) => this.onTaskEnd(e)
    this._onError = (e) => this.onError(e)

    this.gulp.on('task_stop', this._onTaskEnd)
    this.gulp.on('task_err', this._onError)

    this.runNextSet()
  }

  finish(e) {
    this.debugDump(`finish`, e)
    this.gulp.removeListener('task_stop', this._onTaskEnd)
    this.gulp.removeListener('task_err', this._onError)

    let error = null
    if (e && e.err) {
      error = {
        task: e.task,
        message: e.err,
        plugin: e.plugin || ''
      }
    }

    if (this.callback) {
      this.callback(error)
    }
    else if (error) {
      this.notifyError(error)
    }
  }

  onError(err) {
    this.debugDump(`onError`, err)
    this.finish(err)
  }

  onTaskEnd(event) {
    this.debug(`onTaskEnd: ${event.task}`)
    //this.debugDump(`this.currentTaskSet`, this.currentTaskSet)

    let i = this.currentTaskSet.indexOf(event.task)
    if (i > -1) {
      this.currentTaskSet.splice(i, 1)
    }
    if (this.currentTaskSet.length === 0) {
      this.runNextSet()
    }
  }

  runNextSet() {
    if (this.taskSets.length) {
      let command = this.taskSets.shift()
      if (!Array.isArray(command)) {
        command = [command]
      }
      this.debugDump(`gulp.start(currentTaskSet = ${command}) isArray: ${Array.isArray(command)}`, command)
      this.currentTaskSet = command

      //this.debugDump('Available gulp tasks', Object.keys(this.gulp.tasks))
      this.gulp.start(command)
    }
    else {
      this.finish()
    }
  }

  verifyTaskSets(taskSets, foundTasks = {}) {

    this.debug(`verifyTaskSets: ${stringify(taskSets)}`)

    if (taskSets.length === 0) {
      throw new Error('No tasks were provided to run-sequence')
    }

    for (let nextEntry of taskSets) {
      let isString = (typeof nextEntry === "string")
      let isArray = Array.isArray(nextEntry)

      if (!isString && !isArray) {
        throw new Error(`Task \`${nextEntry}\` (${typeof nextEntry}) is neither a string nor an array: \n${stringify(nextEntry)}`)
      }

      if (isString && !this.gulp.hasTask(nextEntry)) {
        throw new Error(`Task ${nextEntry} is not configured as a task on gulp.`)
      }

      if (foundTasks[nextEntry]) {
        throw new Error(`Task ${nextEntry} is listed more than once. This is probably a typo.`)
      }
      foundTasks[nextEntry] = true

      if (isArray) {
        if (nextEntry.length === 0) {
          throw new Error(`An empty array was provided as a task set`)
        }
        this.verifyTaskSets(nextEntry, foundTasks)
      }
    }
  }
}

export default TaskSeries
<|endoftext|>


<commit_before>// ==UserScript==
// @name        HackerNews Comment Coloring
// @namespace   https://github.com/PauliusLabanauskis
// @version     0.1
// @include     http://news.ycombinator.com/*
// @include     https://news.ycombinator.com/*
// @grant       none
// ==/UserScript==

var $hn_coloring = {
    colors: ["f6f6ef", "fdfdfc"],

    init: function () {
        var elements = document.getElementsByClassName("default");

        for (var i = 0; i < elements.length; i++) {
            var color = this.colors[i % 2];
            elements[i].style.backgroundColor = color;
        }
    }
};

(function () {
    try {
        $hn_coloring.init();
    }
    catch (e) { console.log(e); }
})();<commit_msg>Apply coloring by indentation level.<commit_after>// ==UserScript==
// @name        HackerNews Comment Coloring
// @namespace   https://github.com/PauliusLabanauskis
// @version     0.2
// @include     http://news.ycombinator.com/*
// @include     https://news.ycombinator.com/*
// @grant       none
// ==/UserScript==

(function () {
    'use strict';

    const HIGHLIGHT_COLOR = 'fdfdfc';
    const BASE_INDENT_PX = 40;

    function getCommentIndentations() {
        var things = Array.prototype.slice.call(document.getElementsByClassName('athing'), 1);
        var indentations = Array.prototype.map.call(things, function(currentValue) {
            var indentation = currentValue.querySelector('.ind > img').width / BASE_INDENT_PX;
            return {
                indentation: indentation,
                comment: currentValue
            }
        });
        return indentations;
    }

    function init() {
        var comments = getCommentIndentations();
        var coloredComments = comments.filter(function(value) {
            return value.indentation % 2 != 0;
        });
        coloredComments.forEach(function(value) {
            var commentNode = value.comment.querySelector('.default');
            commentNode.style.backgroundColor = HIGHLIGHT_COLOR;
        });
    }

    try {
        init();
    }
    catch (e) { console.log(e); }
})();<|endoftext|>


<commit_before>import streamCreate from 'furnace-i18n/lib/stream';
import Ember from 'ember';
/**
 * @module furnace
 * @submodule furnace-i18n
 */

/**
 * @method i18n
 * @for Furnace.I18n.helpers
 * @param {String} path
 * @param {Hash} options
 * @return {String} HTML string
 */
export default Ember.Helper.extend({
	i18n : Ember.inject.service(),

	localeObserver : Ember.observer('i18n._locale',function() {
		this.recompute();
	}),

	compute: function(params,hash)  {
		return this.get('i18n').translate(params.shift(),params);
	}
});
<commit_msg>Fixed regression with helper attributes via hash<commit_after>import streamCreate from 'furnace-i18n/lib/stream';
import Ember from 'ember';
/**
 * @module furnace
 * @submodule furnace-i18n
 */

/**
 * @method i18n
 * @for Furnace.I18n.helpers
 * @param {String} path
 * @param {Hash} options
 * @return {String} HTML string
 */
export default Ember.Helper.extend({
	i18n : Ember.inject.service(),

	localeObserver : Ember.observer('i18n._locale',function() {
		this.recompute();
	}),

	compute: function(params,hash)  {
		return this.get('i18n').translate(params.shift(),hash.attributes ? hash.attributes : params);
	}
});
<|endoftext|>


<commit_before>/* eslint-env browser */
const Docker = require('dockerode');
const assert = require('assert');
const concatStream = require('concat-stream');
const Promise = require('bluebird');
const path = require('path');
const tmp = require('tmp');
const shellescape = require('shell-escape');
const fs = Promise.promisifyAll(require('fs'));

const docker = new Docker();

module.exports = ({ id, code, stdin }) => {
  assert(typeof id === 'string');
  assert(Buffer.isBuffer(code));
  assert(typeof stdin === 'string');
  assert(code.length < 10000);
  assert(stdin.length < 10000);

  return new Promise((resolve, reject) => {
    tmp.dir({ unsafeCleanup: true }, (error, tmpPath, cleanup) => {
      if (error) {
        reject(error);
      } else {
        resolve({ tmpPath, cleanup });
      }
    });
  }).then(({ tmpPath, cleanup }) => {
    const stdinPath = path.join(tmpPath, 'INPUT');
    const codePath = path.join(tmpPath, 'CODE');

    return Promise.all([
      fs.writeFileAsync(stdinPath, stdin),
      fs.writeFileAsync(codePath, code),
    ]).then(() => {
      let stdoutWriter;

      const stdoutPromise = new Promise((resolve) => {
        stdoutWriter = concatStream((stdout) => {
          resolve(stdout);
        });
      });

      let stderrWriter;

      const stderrPromise = new Promise((resolve) => {
        stderrWriter = concatStream((stderr) => {
          resolve(stderr);
        });
      });

      let container;

      const dockerVolumePath = (() => {
        if (path.sep === '\\') {
          return tmpPath.replace('C:\\', '/c/').replace(/\\/g, '/');
        }

        return tmpPath;
      })();

      const containerPromise = docker.createContainer({
        Hostname: '',
        User: '',
        AttachStdin: false,
        AttachStdout: true,
        AttachStderr: true,
        Tty: false,
        OpenStdin: false,
        StdinOnce: false,
        Env: null,
        Cmd: ['bash', '-c', `${shellescape([id, '/volume/CODE'])} < /volume/INPUT`],
        Image: 'hakatashi/esolang-box',
        Volumes: {
          '/volume': {}
        },
        VolumesFrom: [],
        HostConfig: {
          Binds: [`${dockerVolumePath}:/volume:ro`],
        },
      }).then((cont) => {
        container = cont;
        return container.attach({
          stream: true,
          stdout: true,
          stderr: true,
        });
      }).then((stream) => {
        container.modem.demuxStream(stream, stdoutWriter, stderrWriter);
        stream.on('end', () => {
          stdoutWriter.end();
          stderrWriter.end();
        });

        return container.start();
      })
      .then(() => container.wait())
      .then(() => container.remove());

      const runner = Promise.all([stdoutPromise, stderrPromise, containerPromise]);

      return runner.timeout(1000).then(([stdout, stderr]) => {
        cleanup();
        return {
          stdout: Buffer.isBuffer(stdout) ? stdout : Buffer.alloc(0),
          stderr: Buffer.isBuffer(stderr) ? stderr : Buffer.alloc(0),
        };
      }).catch(Promise.TimeoutError, (error) => {
        container.kill().then(() => container.remove()).then(() => Promise.reject(error));
      });
    });
  });
};
<commit_msg>temp fix for c-gcc<commit_after>/* eslint-env browser */
const Docker = require('dockerode');
const assert = require('assert');
const concatStream = require('concat-stream');
const Promise = require('bluebird');
const path = require('path');
const tmp = require('tmp');
const shellescape = require('shell-escape');
const fs = Promise.promisifyAll(require('fs'));

const docker = new Docker();

module.exports = ({ id, code, stdin }) => {
  assert(typeof id === 'string');
  assert(Buffer.isBuffer(code));
  assert(typeof stdin === 'string');
  assert(code.length < 10000);
  assert(stdin.length < 10000);

  return new Promise((resolve, reject) => {
    tmp.dir({ unsafeCleanup: true }, (error, tmpPath, cleanup) => {
      if (error) {
        reject(error);
      } else {
        resolve({ tmpPath, cleanup });
      }
    });
  }).then(({ tmpPath, cleanup }) => {
    const stdinPath = path.join(tmpPath, 'INPUT');
    const codePath = path.join(tmpPath, id === 'c-gcc' ? 'CODE.c' : 'CODE');

    return Promise.all([
      fs.writeFileAsync(stdinPath, stdin),
      fs.writeFileAsync(codePath, code),
    ]).then(() => {
      let stdoutWriter;

      const stdoutPromise = new Promise((resolve) => {
        stdoutWriter = concatStream((stdout) => {
          resolve(stdout);
        });
      });

      let stderrWriter;

      const stderrPromise = new Promise((resolve) => {
        stderrWriter = concatStream((stderr) => {
          resolve(stderr);
        });
      });

      let container;

      const dockerVolumePath = (() => {
        if (path.sep === '\\') {
          return tmpPath.replace('C:\\', '/c/').replace(/\\/g, '/');
        }

        return tmpPath;
      })();

      const containerPromise = docker.createContainer({
        Hostname: '',
        User: '',
        AttachStdin: false,
        AttachStdout: true,
        AttachStderr: true,
        Tty: false,
        OpenStdin: false,
        StdinOnce: false,
        Env: null,
        Cmd: ['bash', '-c', `${shellescape([id, id === 'c-gcc' ? '/volume/CODE.c' : '/volume/CODE'])} < /volume/INPUT`],
        Image: 'hakatashi/esolang-box',
        Volumes: {
          '/volume': {}
        },
        VolumesFrom: [],
        HostConfig: {
          Binds: [`${dockerVolumePath}:/volume:ro`],
        },
      }).then((cont) => {
        container = cont;
        return container.attach({
          stream: true,
          stdout: true,
          stderr: true,
        });
      }).then((stream) => {
        container.modem.demuxStream(stream, stdoutWriter, stderrWriter);
        stream.on('end', () => {
          stdoutWriter.end();
          stderrWriter.end();
        });

        return container.start();
      })
      .then(() => container.wait())
      .then(() => container.remove());

      const runner = Promise.all([stdoutPromise, stderrPromise, containerPromise]);

      return runner.timeout(1000).then(([stdout, stderr]) => {
        cleanup();
        return {
          stdout: Buffer.isBuffer(stdout) ? stdout : Buffer.alloc(0),
          stderr: Buffer.isBuffer(stderr) ? stderr : Buffer.alloc(0),
        };
      }).catch(Promise.TimeoutError, (error) => {
        container.kill().then(() => container.remove()).then(() => Promise.reject(error));
      });
    });
  });
};
<|endoftext|>


<commit_before>/**
 * @author Tom De Caluwé
 * @copyright 2016 Tom De Caluwé
 * @license Apache-2.0
 *
 * 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.
 */

'use strict'

var Configuration = require('./configuration.js');
var Tokenizer = require('./tokenizer.js');

var EventEmitter = require('events');

/**
 * The `Parser` class encapsulates an online parsing algorithm, similar to a
 * SAX-parser. By itself it doesn't do anything useful, however several
 * callbacks can be provided for different parsing events.
 *
 * @constructs Parser
 * @param {Validator} [validator] Accepts a validator class for handling
 * data validation.
 */
var Parser = function (validator) {
  EventEmitter.apply(this);
  this._validator = validator || Parser.defaultValidator;
  this._configuration = new Configuration();
  this._tokenizer = new Tokenizer(this._configuration);
  this.state = Parser.states.empty;
  this.buffer = '';
}

Parser.prototype = Object.create(EventEmitter.prototype);

Parser.prototype.onopensegment = function (segment) {
  this.emit('opensegment', segment);
}

Parser.prototype.onclosesegment = function () {
  this.emit('closesegment');
}

Parser.prototype.onelement = function () {
  this.emit('element');
}

Parser.prototype.oncomponent = function (data) {
  this.emit('component', data);
}

/**
 * Set an encoding level.
 * @param {String} level - The encoding level name.
 */
Parser.prototype.encoding = function (level) {
  var previous = this._configuration.level;

  this._configuration.encoding(level);
  if (this._configuration.level !== previous) {
    this._tokenizer.configure(this._configuration);
  }
}

/**
 * @summary Ends the EDI interchange.
 * @throws {Error} If more data is expected.
 */
Parser.prototype.end = function () {
  // The stream can only be closed if the last segment is complete. This
  // means the parser is currently in a state accepting segment data, but no
  // data was read so far.
  if (this.state !== Parser.states.segment || this._tokenizer.buffer !== '') {
    throw Parser.errors.incompleteMessage();
  } else {
    this.state = Parser.states.empty;
  }
}

Parser.prototype.una = function (chunk) {
  if (/^UNA....\ ./g.test(chunk)) {
    this._configuration.CDS = chunk.charCodeAt(3);
    this._configuration.DES = chunk.charCodeAt(4);
    this._configuration.DM = chunk.charCodeAt(5);
    this._configuration.RC = chunk.charCodeAt(6);
    this._configuration.ST = chunk.charCodeAt(8);
    return true;
  } else {
    return false;
  }
}

/* eslint-disable complexity */

/**
 * @summary Write some data to the parser.
 * @param {String} chunk A chunk of UN/EDIFACT data.
 */
Parser.prototype.write = function (chunk) {
  // The position of the parser.
  var index = 0;
  if (this.state === Parser.states.continued) {
    this.state = Parser.states.modeset;
  }
  while (index < chunk.length) {
    switch (this.state) {
    case Parser.states.empty:
      index = this.una(chunk) ? 9 : 0;
      // If the first segment is interrupted by, for example, a line break, the
      // parser will remain in the same state as it has here. Since we don't
      // want the parser to detect another UNA header, in such a case, we put it
      // in the segment state.
      this.state = Parser.states.segment;
      // Continue to read the first segment, otherwise the index increment add
      // the end of the loop would cause the parser to skip the first character.
    case Parser.states.segment:
      index = this._tokenizer.segment(chunk, index);
      // Determine the next parser state.
      switch (chunk.charCodeAt(index) || this._configuration.EOT) {
      case this._configuration.DES:
        this._validator.onopensegment(this._tokenizer.buffer);
        this.onopensegment(this._tokenizer.buffer);
        this.state = Parser.states.element;
        this._tokenizer.buffer = '';
        break;
      case this._configuration.ST:
        this._validator.onopensegment(this._tokenizer.buffer);
        this.onopensegment(this._tokenizer.buffer);
        this._validator.onclosesegment(this);
        this.onclosesegment();
        this.state = Parser.states.segment;
        this._tokenizer.buffer = '';
        break;
      case this._configuration.EOT:
      case this._configuration.CR:
      case this._configuration.LF:
        break;
      default:
        throw Parser.errors.invalidControlAfterSegment(this._tokenizer.buffer, chunk.charAt(index));
      }
      break;
    case Parser.states.element:
      // Start reading a new element.
      this._validator.onelement();
      this.onelement();
      // Fall through to process the first component.
    case Parser.states.component:
      // Start reading a new component.
      this._validator.onopencomponent(this._tokenizer);
      // Fall through to process the available component data.
    case Parser.states.modeset:
    case Parser.states.continued:
    case Parser.states.data:
      index = this._tokenizer.data(chunk, index);
      // Determine the next parser state.
      switch (chunk.charCodeAt(index) || this._configuration.EOT) {
      case this._configuration.CDS:
        this._validator.onclosecomponent(this._tokenizer);
        this.oncomponent(this._tokenizer.buffer);
        this.state = Parser.states.component;
        this._tokenizer.buffer = '';
        break;
      case this._configuration.DES:
        this._validator.onclosecomponent(this._tokenizer);
        this.oncomponent(this._tokenizer.buffer);
        this.state = Parser.states.element;
        this._tokenizer.buffer = '';
        break;
      case this._configuration.ST:
        this._validator.onclosecomponent(this._tokenizer);
        this.oncomponent(this._tokenizer.buffer);
        this._validator.onclosesegment();
        this.onclosesegment();
        this.state = Parser.states.segment;
        this._tokenizer.buffer = '';
        break;
      case this._configuration.DM:
        this._tokenizer.decimal(chunk, index);
        this.state = Parser.states.data;
        break;
      case this._configuration.RC:
        index++;
        this._tokenizer.release(chunk, index);
        this.state = Parser.states.data;
        break;
      case this._configuration.EOT:
      case this._configuration.CR:
      case this._configuration.LF:
        this.state = Parser.states.data;
        break;
      default:
        throw Parser.errors.invalidCharacter(chunk.charAt(index), index);
      }
    }
    // Consume the control character.
    index++;
  }
}

/* eslint-enable complexity */

Parser.states = {
  empty: 0,
  segment: 1,
  element: 2,
  component: 3,
  modeset: 4,
  data: 5
};

Parser.errors = {
  incompleteMessage: function () {
    return new Error('Cannot close an incomplete message');
  },
  invalidCharacter: function (character, index) {
    var message = '';
    message += 'Invalid character ' + character;
    message += ' at position ' + index;
    return new Error(message);
  },
  invalidControlAfterSegment: function (segment, character) {
    var message = '';
    message += 'Invalid character ' + character;
    message += ' after reading segment name ' + segment;
    return new Error(message);
  }
}

Parser.defaultValidator = {
  onopensegment: function () {},
  onelement: function () {},
  onopencomponent: function () {},
  onclosecomponent: function () {},
  onclosesegment: function () {}
};

module.exports = Parser;
<commit_msg>Fix 'Parser.write should use special characters as defined in the UNA header' test<commit_after>/**
 * @author Tom De Caluwé
 * @copyright 2016 Tom De Caluwé
 * @license Apache-2.0
 *
 * 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.
 */

'use strict'

var Configuration = require('./configuration.js');
var Tokenizer = require('./tokenizer.js');

var EventEmitter = require('events');

/**
 * The `Parser` class encapsulates an online parsing algorithm, similar to a
 * SAX-parser. By itself it doesn't do anything useful, however several
 * callbacks can be provided for different parsing events.
 *
 * @constructs Parser
 * @param {Validator} [validator] Accepts a validator class for handling
 * data validation.
 */
var Parser = function (validator) {
  EventEmitter.apply(this);
  this._validator = validator || Parser.defaultValidator;
  this._configuration = new Configuration();
  this._tokenizer = new Tokenizer(this._configuration);
  this.state = Parser.states.empty;
  this.buffer = '';
}

Parser.prototype = Object.create(EventEmitter.prototype);

Parser.prototype.onopensegment = function (segment) {
  this.emit('opensegment', segment);
}

Parser.prototype.onclosesegment = function () {
  this.emit('closesegment');
}

Parser.prototype.onelement = function () {
  this.emit('element');
}

Parser.prototype.oncomponent = function (data) {
  this.emit('component', data);
}

/**
 * Set an encoding level.
 * @param {String} level - The encoding level name.
 */
Parser.prototype.encoding = function (level) {
  var previous = this._configuration.level;

  this._configuration.encoding(level);
  if (this._configuration.level !== previous) {
    this._tokenizer.configure(this._configuration);
  }
}

/**
 * @summary Ends the EDI interchange.
 * @throws {Error} If more data is expected.
 */
Parser.prototype.end = function () {
  // The stream can only be closed if the last segment is complete. This
  // means the parser is currently in a state accepting segment data, but no
  // data was read so far.
  if (this.state !== Parser.states.segment || this._tokenizer.buffer !== '') {
    throw Parser.errors.incompleteMessage();
  } else {
    this.state = Parser.states.empty;
  }
}

Parser.prototype.una = function (chunk) {
  if (/^UNA....\ ./g.test(chunk)) {
    this._configuration.CDS = chunk.charCodeAt(3);
    this._configuration.DES = chunk.charCodeAt(4);
    this._configuration.DM = chunk.charCodeAt(5);
    this._configuration.RC = chunk.charCodeAt(6);
    this._configuration.ST = chunk.charCodeAt(8);

    this._tokenizer = new Tokenizer(this._configuration);
    return true;
  } else {
    return false;
  }
}

/* eslint-disable complexity */

/**
 * @summary Write some data to the parser.
 * @param {String} chunk A chunk of UN/EDIFACT data.
 */
Parser.prototype.write = function (chunk) {
  // The position of the parser.
  var index = 0;
  if (this.state === Parser.states.continued) {
    this.state = Parser.states.modeset;
  }
  while (index < chunk.length) {
    switch (this.state) {
    case Parser.states.empty:
      index = this.una(chunk) ? 9 : 0;
      // If the first segment is interrupted by, for example, a line break, the
      // parser will remain in the same state as it has here. Since we don't
      // want the parser to detect another UNA header, in such a case, we put it
      // in the segment state.
      this.state = Parser.states.segment;
      // Continue to read the first segment, otherwise the index increment add
      // the end of the loop would cause the parser to skip the first character.
    case Parser.states.segment:
      index = this._tokenizer.segment(chunk, index);
      // Determine the next parser state.
      switch (chunk.charCodeAt(index) || this._configuration.EOT) {
      case this._configuration.DES:
        this._validator.onopensegment(this._tokenizer.buffer);
        this.onopensegment(this._tokenizer.buffer);
        this.state = Parser.states.element;
        this._tokenizer.buffer = '';
        break;
      case this._configuration.ST:
        this._validator.onopensegment(this._tokenizer.buffer);
        this.onopensegment(this._tokenizer.buffer);
        this._validator.onclosesegment(this);
        this.onclosesegment();
        this.state = Parser.states.segment;
        this._tokenizer.buffer = '';
        break;
      case this._configuration.EOT:
      case this._configuration.CR:
      case this._configuration.LF:
        break;
      default:
        throw Parser.errors.invalidControlAfterSegment(this._tokenizer.buffer, chunk.charAt(index));
      }
      break;
    case Parser.states.element:
      // Start reading a new element.
      this._validator.onelement();
      this.onelement();
      // Fall through to process the first component.
    case Parser.states.component:
      // Start reading a new component.
      this._validator.onopencomponent(this._tokenizer);
      // Fall through to process the available component data.
    case Parser.states.modeset:
    case Parser.states.continued:
    case Parser.states.data:
      index = this._tokenizer.data(chunk, index);
      // Determine the next parser state.
      switch (chunk.charCodeAt(index) || this._configuration.EOT) {
      case this._configuration.CDS:
        this._validator.onclosecomponent(this._tokenizer);
        this.oncomponent(this._tokenizer.buffer);
        this.state = Parser.states.component;
        this._tokenizer.buffer = '';
        break;
      case this._configuration.DES:
        this._validator.onclosecomponent(this._tokenizer);
        this.oncomponent(this._tokenizer.buffer);
        this.state = Parser.states.element;
        this._tokenizer.buffer = '';
        break;
      case this._configuration.ST:
        this._validator.onclosecomponent(this._tokenizer);
        this.oncomponent(this._tokenizer.buffer);
        this._validator.onclosesegment();
        this.onclosesegment();
        this.state = Parser.states.segment;
        this._tokenizer.buffer = '';
        break;
      case this._configuration.DM:
        this._tokenizer.decimal(chunk, index);
        this.state = Parser.states.data;
        break;
      case this._configuration.RC:
        index++;
        this._tokenizer.release(chunk, index);
        this.state = Parser.states.data;
        break;
      case this._configuration.EOT:
      case this._configuration.CR:
      case this._configuration.LF:
        this.state = Parser.states.data;
        break;
      default:
        throw Parser.errors.invalidCharacter(chunk.charAt(index), index);
      }
    }
    // Consume the control character.
    index++;
  }
}

/* eslint-enable complexity */

Parser.states = {
  empty: 0,
  segment: 1,
  element: 2,
  component: 3,
  modeset: 4,
  data: 5
};

Parser.errors = {
  incompleteMessage: function () {
    return new Error('Cannot close an incomplete message');
  },
  invalidCharacter: function (character, index) {
    var message = '';
    message += 'Invalid character ' + character;
    message += ' at position ' + index;
    return new Error(message);
  },
  invalidControlAfterSegment: function (segment, character) {
    var message = '';
    message += 'Invalid character ' + character;
    message += ' after reading segment name ' + segment;
    return new Error(message);
  }
}

Parser.defaultValidator = {
  onopensegment: function () {},
  onelement: function () {},
  onopencomponent: function () {},
  onclosecomponent: function () {},
  onclosesegment: function () {}
};

module.exports = Parser;
<|endoftext|>


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

    describe('ngApimock - protractor.mock.js', function () {
        var ngApimock = require('../../.tmp/some-other-dir/protractor.mock.js');

        describe('when provided without any selected scenarios', function () {
            beforeAll(function () {
                ngApimock.addMockModule();
                browser.get('/index.html');
            });

            describe('when fetching data with a service', function() {
                it('should not show any data', function () {
                    expect(element(by.binding('ctrl.data')).getText()).toBe('[{"a":"b"}]');
                });

                it('should not show any errors', function () {
                    expect(element(by.binding('ctrl.error')).getText()).toBe('');
                });
            });

            describe('when posting data with a service', function() {
                beforeAll(function() {
                    element(by.buttonText('post me')).click();
                });

                it('should not show any data', function () {
                    expect(element(by.binding('ctrl.postedData')).getText()).toBe('{"some":"thing"}' );
                });

                it('should not show any errors', function () {
                    expect(element(by.binding('ctrl.postedError')).getText()).toBe('');
                });
            });

            afterAll(function () {
                ngApimock.removeMockModule();
                ngApimock.resetScenarios();
            });
        });

        describe('when provided with some selected scenarios', function () {
            beforeAll(function () {
                ngApimock.selectScenario(require('../mocks/some-api-get.json'), 'some-meaningful-scenario-name');
                ngApimock.selectScenario(require('../mocks/some-api-post.json'), 'successful');
                ngApimock.addMockModule();
                browser.get('/index.html');
            });

            describe('when fetching data with a service', function() {
                it('should show data', function () {
                    expect(element(by.binding('ctrl.data')).getText()).toBe('[{"x":"y"}]');
                });

                it('should not show any errors', function () {
                    expect(element(by.binding('ctrl.error')).getText()).toBe('');
                });
            });

            describe('when posting data with a service', function() {
                beforeAll(function() {
                    element(by.buttonText('post me')).click();
                });

                it('should show data', function () {
                    expect(element(by.binding('ctrl.postedData')).getText()).toBe('{"some":"thing"}');
                });

                it('should not show any errors', function () {
                    expect(element(by.binding('ctrl.postedError')).getText()).toBe('');
                });
            });

            afterAll(function () {
                ngApimock.removeMockModule();
                ngApimock.resetScenarios();
            });
        });

        describe('when provided with some selected error scenarios', function () {

            beforeAll(function () {
                ngApimock.selectScenario(require('../mocks/some-api-get.json'), 'internal-server-error');
                ngApimock.selectScenario(require('../mocks/some-api-post.json'), 'internal-server-error');
                ngApimock.addMockModule();

                browser.get('/index.html');
            });

            describe('when fetching data with a service', function() {
                it('should not show any data', function () {
                    expect(element(by.binding('ctrl.data')).getText()).toBe('');
                });

                it('should not show any errors', function () {
                    expect(element(by.binding('ctrl.error')).getText()).toBe('500');
                });
            });

            describe('when posting data with a service', function() {
                beforeAll(function() {
                    element(by.buttonText('post me')).click();
                });

                it('should not show any data', function () {
                    expect(element(by.binding('ctrl.postedData')).getText()).toBe('');
                });

                it('should not show any errors', function () {
                    expect(element(by.binding('ctrl.postedError')).getText()).toBe('500');
                });
            });

            afterAll(function () {
                ngApimock.removeMockModule();
                ngApimock.resetScenarios();
            });

        });
    })
})();<commit_msg>Add tests for changing scenarios at runtime<commit_after>(function () {
    'use strict';

    describe('ngApimock - protractor.mock.js', function () {
        var ngApimock = require('../../.tmp/some-other-dir/protractor.mock.js');

        describe('when provided without any selected scenarios', function () {
            beforeAll(function () {
                ngApimock.addMockModule();
                browser.get('/index.html');
            });

            describe('when fetching data with a service', function() {
                it('should not show any data', function () {
                    expect(element(by.binding('ctrl.data')).getText()).toBe('[{"a":"b"}]');
                });

                it('should not show any errors', function () {
                    expect(element(by.binding('ctrl.error')).getText()).toBe('');
                });
            });

            describe('when posting data with a service', function() {
                beforeAll(function() {
                    element(by.buttonText('post me')).click();
                });

                it('should not show any data', function () {
                    expect(element(by.binding('ctrl.postedData')).getText()).toBe('{"some":"thing"}' );
                });

                it('should not show any errors', function () {
                    expect(element(by.binding('ctrl.postedError')).getText()).toBe('');
                });
            });

            afterAll(function () {
                ngApimock.removeMockModule();
                ngApimock.resetScenarios();
            });
        });

        describe('when provided with some selected scenarios', function () {
            beforeAll(function () {
                ngApimock.selectScenario(require('../mocks/some-api-get.json'), 'some-meaningful-scenario-name');
                ngApimock.selectScenario(require('../mocks/some-api-post.json'), 'successful');
                ngApimock.addMockModule();
                browser.get('/index.html');
            });

            describe('when fetching data with a service', function() {
                it('should show data', function () {
                    expect(element(by.binding('ctrl.data')).getText()).toBe('[{"x":"y"}]');
                });

                it('should not show any errors', function () {
                    expect(element(by.binding('ctrl.error')).getText()).toBe('');
                });
            });

            describe('when posting data with a service', function() {
                beforeAll(function() {
                    element(by.buttonText('post me')).click();
                });

                it('should show data', function () {
                    expect(element(by.binding('ctrl.postedData')).getText()).toBe('{"some":"thing"}');
                });

                it('should not show any errors', function () {
                    expect(element(by.binding('ctrl.postedError')).getText()).toBe('');
                });
            });

            afterAll(function () {
                ngApimock.removeMockModule();
                ngApimock.resetScenarios();
            });
        });

        describe('when changing some selected scenarios', function () {
            beforeAll(function () {
                ngApimock.selectScenario(require('../mocks/some-api-get.json'), 'some-meaningful-scenario-name');
                ngApimock.selectScenario(require('../mocks/some-api-post.json'), 'successful');
                ngApimock.addMockModule();
                browser.get('/index.html');
            });

            describe('when fetching data with a service', function() {
                it('should show data', function () {
                    expect(element(by.binding('ctrl.data')).getText()).toBe('[{"x":"y"}]');
                    ngApimock.selectScenario(require('../mocks/some-api-get.json'), 'another-meaningful-scenario-name');
                    element(by.buttonText('refresh')).click();
                    expect(element(by.binding('ctrl.data')).getText()).toBe('[{"a":"b"}]');
                });

                it('should not show any errors', function () {
                    expect(element(by.binding('ctrl.error')).getText()).toBe('');
                });
            });

            describe('when posting data with a service', function() {
                beforeAll(function() {
                    element(by.buttonText('post me')).click();
                });

                it('should show data', function () {
                    expect(element(by.binding('ctrl.postedData')).getText()).toBe('{"some":"thing"}');
                    ngApimock.selectScenario(require('../mocks/some-api-post.json'), 'internal-server-error');
                    element(by.buttonText('post me')).click();
                    expect(element(by.binding('ctrl.postedData')).getText()).toBe('');
                });

                it('should not show any errors', function () {
                    expect(element(by.binding('ctrl.postedError')).getText()).toBe('500');
                });
            });

            afterAll(function () {
                ngApimock.removeMockModule();
                ngApimock.resetScenarios();
            });
        });

        describe('when provided with some selected error scenarios', function () {

            beforeAll(function () {
                ngApimock.selectScenario(require('../mocks/some-api-get.json'), 'internal-server-error');
                ngApimock.selectScenario(require('../mocks/some-api-post.json'), 'internal-server-error');
                ngApimock.addMockModule();

                browser.get('/index.html');
            });

            describe('when fetching data with a service', function() {
                it('should not show any data', function () {
                    expect(element(by.binding('ctrl.data')).getText()).toBe('');
                });

                it('should not show any errors', function () {
                    expect(element(by.binding('ctrl.error')).getText()).toBe('500');
                });
            });

            describe('when posting data with a service', function() {
                beforeAll(function() {
                    element(by.buttonText('post me')).click();
                });

                it('should not show any data', function () {
                    expect(element(by.binding('ctrl.postedData')).getText()).toBe('');
                });

                it('should not show any errors', function () {
                    expect(element(by.binding('ctrl.postedError')).getText()).toBe('500');
                });
            });

            afterAll(function () {
                ngApimock.removeMockModule();
                ngApimock.resetScenarios();
            });

        });
    })
})();<|endoftext|>


<commit_before>function PagamentoDao(connection) {
    this._connection = connection;
}

PagamentoDao.prototype.salva = function(pagamento,callback) {
    this._connection.query('INSERT INTO pagamentos SET ?', pagamento, callback);
}

PagamentoDao.prototype.atualiza = function(pagamento,callback) {
    this._connection.query('UPDATE pagamentos SET status = ? where id = ?', [pagamento.status, pagamento.id], callback);
}

PagamentoDao.prototype.lista = function(callback) {
    this._connection.query('select * from pagamentos',callback);
}

PagamentoDao.prototype.buscaPorId = function (id,callback) {
    this._connection.query("select * from pagamentos where id = ?",[id],callback);
}

module.exports = function(){
    return PagamentoDao;
};
<commit_msg>add log<commit_after>function PagamentoDao(connection) {
    this._connection = connection;
}

PagamentoDao.prototype.salva = function(pagamento,callback) {
	console.log('pagamento a inserir: ' + JSON.stringify(pagamento));
    this._connection.query('INSERT INTO pagamentos SET ?', pagamento, callback);
}

PagamentoDao.prototype.atualiza = function(pagamento,callback) {
    this._connection.query('UPDATE pagamentos SET status = ? where id = ?', [pagamento.status, pagamento.id], callback);
}

PagamentoDao.prototype.lista = function(callback) {
    this._connection.query('select * from pagamentos',callback);
}

PagamentoDao.prototype.buscaPorId = function (id,callback) {
    this._connection.query("select * from pagamentos where id = ?",[id],callback);
}

module.exports = function(){
    return PagamentoDao;
};
<|endoftext|>


<commit_before>/*

Gribbagrab
lovingly made by Evan Hahn
dedicated to burritos
unlicensed

Some implementation details:

- The gribbagrab function is intentionally plopped into the window namespace.
  This decision makes sense given the intended use case: it's meant to be
  inlined on your page. It's not meant to be loaded with another loader so it
  isn't AMD-compatible, nor is it meant to be CommonJS compatible. That's not
  to say you couldn't use Gribbagrab to load AMD-compatible stuff (even other
  loaders) -- go APESHIT. YOU CAN DO ANYTHING.

- "use strict" while you're developing, but not in the real world. It's an easy
  way to eliminate 13 characters.

- I'm cool with formal JSHint support, but JSLint is my enemy. I haven't added
  either, but you could submit a pull request. I'll love it.

- I thought about adding element.type = "text/javascript" or "text/css", but I
  figured that if you're using this, you're smart enough not to serve the wrong
  MIME types. I didn't want to add the extra bytes.

*/

;(function(win, doc) {

	// configurations
	var IMAGE_EXTENSIONS = ['.png', '.gif', '.jpg', '.jpeg', '.svg'];

	// document.head isn't always defined
	var head = doc.head || (doc.getElementsByTagName('head')[0]);

	// sometimes you want to do nothing
	var noop = function() {};

	// utility function to inject a .css or .js file
	var inject = function(src, options) {
		options = options || {};
		var element;
		var extension = src.substr(src.lastIndexOf('.'));
		if (extension === '.css') {
			element = doc.createElement('link');
			element.rel = 'stylesheet';
			element.href = src;
		} else if (IMAGE_EXTENSIONS.indexOf(extension) !== -1) {
			element = new Image;
			element.src = src;
		} else {
			element = doc.createElement('script');
			element.src = src;
		}
		element.onload = options.success || noop;
		element.onerror = options.failure || noop;
		if (!(element instanceof Image))
			head.appendChild(element);
	};

	// the big kahuna
	win.gribbagrab = function(dependencies, allDone) {

		// if it's passed a string, run that file last
		var callback;
		if (!(allDone instanceof Function)) {
			callback = function() { inject(allDone); };
		} else {
			callback = allDone;
		}

		// if we're not passed anything, let's just quit now
		if (dependencies.length === 0)
			callback([]);

		// so far, we have nothing to load, but we'll increment this
		var toLoad = 0;

		// keep track of failures
		var failures = [];

		dependencies.forEach(function(dependency) {

			// if it's "load X, then Y"...
			if (dependency instanceof Array) {
				toLoad += dependency.length;
				var done = function() {
					toLoad --;
					if (dependency.length)
						gribbagrab([dependency.shift()], done);
					else if (toLoad === 0)
						callback(failures);
				};
				gribbagrab([dependency.shift()], done);
			}

			// if it's a single file, load only one of them
			else {
				toLoad ++;
				var srcs = dependency.split(/\s+/g);
				var tryNext = function() {
					if (srcs.length) {
						inject(srcs.shift(), {
							success: function() {
								toLoad --;
								if (toLoad === 0)
									callback(failures);
							},
							failure: tryNext
						});
					} else {
						toLoad --;
						failures.push(dependency);
						if (toLoad === 0)
							callback(failures);
					}
				};
				tryNext();
			}

		});

	};

})(window, document);
<commit_msg>you don't need a callback<commit_after>/*

Gribbagrab
lovingly made by Evan Hahn
dedicated to burritos
unlicensed

Some implementation details:

- The gribbagrab function is intentionally plopped into the window namespace.
  This decision makes sense given the intended use case: it's meant to be
  inlined on your page. It's not meant to be loaded with another loader so it
  isn't AMD-compatible, nor is it meant to be CommonJS compatible. That's not
  to say you couldn't use Gribbagrab to load AMD-compatible stuff (even other
  loaders) -- go APESHIT. YOU CAN DO ANYTHING.

- "use strict" while you're developing, but not in the real world. It's an easy
  way to eliminate 13 characters.

- I'm cool with formal JSHint support, but JSLint is my enemy. I haven't added
  either, but you could submit a pull request. I'll love it.

- I thought about adding element.type = "text/javascript" or "text/css", but I
  figured that if you're using this, you're smart enough not to serve the wrong
  MIME types. I didn't want to add the extra bytes.

*/

;(function(win, doc) {

	// configurations
	var IMAGE_EXTENSIONS = ['.png', '.gif', '.jpg', '.jpeg', '.svg'];

	// document.head isn't always defined
	var head = doc.head || (doc.getElementsByTagName('head')[0]);

	// sometimes you want to do nothing
	var noop = function() {};

	// utility function to inject a .css or .js file
	var inject = function(src, options) {
		options = options || {};
		var element;
		var extension = src.substr(src.lastIndexOf('.'));
		if (extension === '.css') {
			element = doc.createElement('link');
			element.rel = 'stylesheet';
			element.href = src;
		} else if (IMAGE_EXTENSIONS.indexOf(extension) !== -1) {
			element = new Image;
			element.src = src;
		} else {
			element = doc.createElement('script');
			element.src = src;
		}
		element.onload = options.success || noop;
		element.onerror = options.failure || noop;
		if (!(element instanceof Image))
			head.appendChild(element);
	};

	// the big kahuna
	win.gribbagrab = function(dependencies, allDone) {

		// if it's passed a string, run that file last
		var callback;
		if (allDone instanceof Function) {
			callback = allDone;
		} else if (!allDone) {
			callback = noop;
		} else {
			callback = function() { inject(allDone); };
		}

		// if we're not passed anything, let's just quit now
		if (dependencies.length === 0)
			callback([]);

		// so far, we have nothing to load, but we'll increment this
		var toLoad = 0;

		// keep track of failures
		var failures = [];

		dependencies.forEach(function(dependency) {

			// if it's "load X, then Y"...
			if (dependency instanceof Array) {
				toLoad += dependency.length;
				var done = function() {
					toLoad --;
					if (dependency.length)
						gribbagrab([dependency.shift()], done);
					else if (toLoad === 0)
						callback(failures);
				};
				gribbagrab([dependency.shift()], done);
			}

			// if it's a single file, load only one of them
			else {
				toLoad ++;
				var srcs = dependency.split(/\s+/g);
				var tryNext = function() {
					if (srcs.length) {
						inject(srcs.shift(), {
							success: function() {
								toLoad --;
								if (toLoad === 0)
									callback(failures);
							},
							failure: tryNext
						});
					} else {
						toLoad --;
						failures.push(dependency);
						if (toLoad === 0)
							callback(failures);
					}
				};
				tryNext();
			}

		});

	};

})(window, document);
<|endoftext|>


<commit_before>const cluster = require('cluster');
const Winston = require('winston');
const WinstonDailyRotateFile = require('winston-daily-rotate-file');
const nconf = require('../../config/index');

const verbose = nconf.get('verbose');
const silent = nconf.get('silent');
const environment = nconf.get('env');

function _parseError(error) {
  const jsonObj = {
    name: error.name,
    message: error.message,
    stack: error.stack,
    __error__: true
  };

  Object.keys(error).forEach((key) => {
    if (!jsonObj[key]) { jsonObj[key] = error[key]; }
  });

  return jsonObj;
}

class MasterLogger {
  constructor() {
    this.logger = Winston;
    // Define logger behaviour
    this.logger.cli(); // activates colors

    // define console logging level
    this.logger.level = silent ? 'error' : ['info', 'debug', 'verbose', 'silly'][verbose % 4];
    this.logger.debug(`Using cfg: ${environment}`);

    // @todo File logging options should be fetched from config file
    // Add winston file logger, which rotates daily
    const fileLevel = 'silly';
    this.logger.add(WinstonDailyRotateFile, {
      filename: '../log/app.log',
      json: false,
      handleExceptions: false,
      level: fileLevel,
      datePatter: '.yyyy-MM-dd_HH-mm'
    });
  }
  set level(level) {
    this.logger.level = level;
  }

  handleWorkerLog(worker, data) {
    const level = data['level'] || 'debug';
    const args = data['args'] || [];
    args.unshift(`<Worker#${worker.id}>`);
    try {
      this.logger[level](...args);
    } catch (error) {
      this.logger.error(data);
      this.logger.error(error);
    }
  }
  log(level, ...args) {
    args.unshift('<Master>');
    this.logger.log(level, ...args);
  }
  error(...args) {
    this.log('error', ...args);
  }
  warn(...args) {
    this.log('warn', ...args);
  }
  info(...args) {
    this.log('info', ...args);
  }
  debug(...args) {
    this.log('debug', ...args);
  }
  verbose(...args) {
    this.log('verbose', ...args);
  }
  silly(...args) {
    this.log('silly', ...args);
  }
}

class WorkerLogger {
  constructor() {
    this._emitter = process;
  }

  _proxy(level, ...args) {
    const editedArgs = args;
    Object.keys(args).forEach((key) => {
      if (args[key] instanceof Error) {
        editedArgs[key] = _parseError(args[key]);
      }
    });
    if (process.connected) {
      // @todo better intercommunication..
      this._emitter.send({type: 'log', level, args: editedArgs});
    }
  }

  set level(level) {
    this.warn('Not implemented');
  }

  log(level, ...args) {
    this._proxy(level, ...args);
  }
  error(...args) {
    this._proxy('error', ...args);
  }
  debug(...args) {
    this._proxy('debug', ...args);
  }
  info(...args) {
    this._proxy('info', ...args);
  }
  warn(...args) {
    this._proxy('warn', ...args);
  }
  silly(...args) {
    this._proxy('silly', ...args);
  }
  verbose(...args) {
    this._proxy('verbose', ...args);
  }
}

if (cluster.isMaster) {
  module.exports = new MasterLogger();
} else {
  module.exports = new WorkerLogger();
}
<commit_msg>restructured winston init to use distinct transports, one for console and one for file.<commit_after>// Native components
const cluster = require('cluster');

// Third party components
const Winston = require('winston');
require('winston-daily-rotate-file');

// Application components
const config = require('../../config/index');

// Setup
const verbose = config.get('verbose');
const silent = config.get('silent');
const environment = config.get('env');

function _parseError(error) {
  const jsonObj = {
    name: error.name,
    message: error.message,
    stack: error.stack,
    __error__: true
  };

  Object.keys(error).forEach((key) => {
    if (!jsonObj[key]) { jsonObj[key] = error[key]; }
  });

  return jsonObj;
}

class MasterLogger {
  constructor() {
    this.logger = Winston;

    // @todo File logging options should be fetched from config file
    // Add winston file logger, which rotates daily
    const fileLevel = 'silly';
    this.logger.configure({
      transports: [
        new (Winston.transports.Console)({
          colorize: true,
          level: silent ? 'error' : ['info', 'debug', 'verbose', 'silly'][verbose % 4]
        }),
        new (Winston.transports.DailyRotateFile)({
          filename: './log/app.log',
          json: false,
          handleExceptions: false,
          level: fileLevel,
          datePatter: '.yyyy-MM-dd_HH-mm.log'
        })
      ]
    });

    // Print current config
    this.logger.debug(`Using cfg: ${environment}.`);
  }
  set level(level) {
    this.logger.level = level;
  }

  handleWorkerLog(worker, data) {
    const level = data['level'] || 'debug';
    const args = data['args'] || [];
    args.unshift(`<Worker#${worker.id}>`);
    try {
      this.logger[level](...args);
    } catch (error) {
      this.logger.error(data);
      this.logger.error(error);
    }
  }
  log(level, ...args) {
    args.unshift('<Master>');
    this.logger.log(level, ...args);
  }
  error(...args) {
    this.log('error', ...args);
  }
  warn(...args) {
    this.log('warn', ...args);
  }
  info(...args) {
    this.log('info', ...args);
  }
  debug(...args) {
    this.log('debug', ...args);
  }
  verbose(...args) {
    this.log('verbose', ...args);
  }
  silly(...args) {
    this.log('silly', ...args);
  }
}

class WorkerLogger {
  constructor() {
    this._emitter = process;
  }

  _proxy(level, ...args) {
    const editedArgs = args;
    Object.keys(args).forEach((key) => {
      if (args[key] instanceof Error) {
        editedArgs[key] = _parseError(args[key]);
      }
    });
    if (process.connected) {
      // @todo better intercommunication..
      this._emitter.send({type: 'log', level, args: editedArgs});
    }
  }

  set level(level) {
    this.warn('Not implemented');
  }

  log(level, ...args) {
    this._proxy(level, ...args);
  }
  error(...args) {
    this._proxy('error', ...args);
  }
  debug(...args) {
    this._proxy('debug', ...args);
  }
  info(...args) {
    this._proxy('info', ...args);
  }
  warn(...args) {
    this._proxy('warn', ...args);
  }
  silly(...args) {
    this._proxy('silly', ...args);
  }
  verbose(...args) {
    this._proxy('verbose', ...args);
  }
}

module.exports = cluster.isMaster ? new MasterLogger() : new WorkerLogger();
<|endoftext|>


<commit_before>//global varibles
var width = 400;
var height = 400;
var bn = 8;		//number of boxs
var bs = 400/8; 		//boxsize

var board;			//canvas
var context;		//canvas context
var cArray = [];	//array of placed chits
var vArray = [];	//array of valid moves
var blackTurn;

var log;
var log1;
//initilizes empty arrays representing game state
function startGame()
{
	board = document.getElementById("board");
	context = board.getContext("2d");
	context.font = "50pt Calibri";

	//fills cArray with 0s
	for (var x = 0; x < bn; x++) {
		cArray[x] = [];
		vArray[x] = [];
		for (var y = 0; y < bn; y++) {
			cArray[x][y] = 0;
			vArray[x][y] = 0;
		}
	}

	//places starting pieces
	cArray[3][3] = -1;
	cArray[4][4] = -1;
	cArray[3][4] = 1;
	cArray[4][3] = 1;

	//sets starting player
	blackTurn = true;

	createValidMoveArray();

	//listens for clicks on the board
	board.addEventListener("mousedown",click,false);
	drawBoard();
}

//clears canvas and redraws board
function drawBoard()
{
	//clear and resize canvas
	//board.width = width;
	//board.height = height;

	//clears canvas
	context.fillStyle = "rgb(255,255,255)";
	context.fillRect(0, 0, width, height);
	context.fillStyle = "rgb(0,200,0)";
	context.fillRect(0, 0, bn*bs, bn*bs);

	//draw grid
	drawGrid();

	//draw pieces placed by players
	createValidMoveArray();
	drawPieces();

	drawScore();
}

//draws grid of lines
function drawGrid()
{
	//draw vertical lines
	for (var x=0; x<=bn*bs; x+= bs) {
		context.moveTo(x,0);
		context.lineTo(x,bn*bs);
	}

	//draw horizontal lines
	for (var y=0; y<=bn*bs; y+= bs) {
		context.moveTo(0,y);
		context.lineTo(bn*bs,y);
	}

	//fills in lines in offwhite
	context.strokeStyle = "rgb(190,190,190)";
	context.stroke();
}

//draw pieces placed by players
function drawPieces()
{
	for (var x = 0; x < bn; x++) {
		for (var y = 0; y < bn; y++) {
			if (cArray[x][y] != 0) {
				drawPiece(x,y,cArray[x][y],8);
			}
			else if (vArray[x][y] != 0) {
				drawPiece(x,y,vArray[x][y],30);
			}
		}
	}
}

//draws a single piece at x, y with color and size passed
//larger size values make smaller pieces
function drawPiece(x, y, color, size)
{
	if (color == 1) {
		context.fillStyle = "rgb(0,0,0)";
	}
	else {
		context.fillStyle = "rgb(255,255,255)";
	}

	context.fillRect(x*bs + size, y*bs + size, bs - size*2, bs - size*2);
}

//displays filled box count at the bottom of the screen
function drawScore()
{
	var redScore = findScore(1);
	context.fillStyle = "rgb(00,0,0)";
	context.fillText(redScore, 100, 660);

	var blueScore = findScore(-1);
	context.fillStyle = "rgb(200,200,200)";
	context.fillText(blueScore, 500, 660);

	//underlines the score if it is that players turn
	context.fillStyle = "rgb(200,0,0)";
	if (blackTurn) {
		context.fillRect(90, 670, 62, 4);
	}
	else {
		context.fillRect(490, 670, 62, 4);
	}
}

//counts the total boxes by the passed player color
function findScore(color) {
	score = 0;
	for (var x = 0; x < bn; x++) {
		for (var y = 0; y < bn; y++) {
			if (cArray[x][y] == color) {
				score++;
			}
		}
	}
	return score;
}

//called when the page is clicked
function click(e)
{
	var color = currentColor();
	var pos = findPos(this);
	var cord = findCord(e.pageX - pos.x, e.pageY - pos.y);
	if (cord) {
		//if line is added to board, redraw lines
		if (vArray[cord.x][cord.y] != 0) {
			var flippedChips = findFlipDirections(cord.x, cord.y, color);
			log = flippedChips;
			for (var i = 0; i < flippedChips.length; i++) {
				cArray[flippedChips[i].x][flippedChips[i].y] = color;
			}
			cArray[cord.x][cord.y] = color;

			blackTurn = !blackTurn;

			//uploads newboard state
			gapi.hangout.data.submitDelta({cArray:JSON.stringify(cArray), blackTurn:JSON.stringify(blackTurn)});

			//drawBoard();
		}
	}
}

//finds which line the passed cord is closest to
function findCord(x, y)
{
	var RV = new Object; 	//return value

	//true if point is inside grid
	if (0 < x && x < bs*bn && 0 < y && y < bs*bn){
		xs = Math.floor(x/bs);
		ys = Math.floor(y/bs);

		RV.x = xs;
		RV.y = ys;
	}
	//cord not on grid; return false
	else {
		RV = false;
	}

	return RV;
}

//find valid moves
function createValidMoveArray() {
	var color = currentColor();
	for (var x = 0; x < bn; x++) {
		for (var y = 0; y < bn; y++) {
			vArray[x][y] = 0;
			if (cArray[x][y] == 0) {
				if (findFlipDirections(x,y,color).length>0){
					vArray[x][y] = color;
				}
			}
		}
	}
}

//from a given location, trys all flip directions
//returns an array of all the pieces that will be flipped if move is valid
//returns false otherwise
function findFlipDirections(x,y,color)
{
	var rv = [];
	var flippedChips;
	for (var dx	= -1;  dx<=1; dx++){
		for (var dy	= -1;  dy<=1; dy++){
			if (dx != 0 || dy != 0) {
				flippedChips = findFlipLength(x,y,dx,dy,color);
				for (var i = 0; i < flippedChips.length; i++) {
					log1 = flippedChips;
					rv[rv.length] = flippedChips[i];

				}
			}
		}
	}
	return rv;
}

//passed a location and direction
function findFlipLength(x,y,dx,dy,color)
{
	var rv = [];
	var i = 1;
	while (onBoard(x+i*dx,y+i*dy) && cArray[x+dx*i][y+dy*i] == -1*color) {
		i++;
	}

	if (i>1 && onBoard(x+i*dx,y+i*dy) && cArray[x+dx*i][y+dy*i] == color) {

		for (var j = 0; j<i; j++) {
			rv[j] = new Object;
			rv[j].x = x+j*dx;
			rv[j].y = y+j*dy;
		}
	}

	return rv;
}

//returns true if the cord is on the board
function onBoard(x, y) {
	return (0 <= x && x <= 7 && 0 <= y && y <= 7);
}

//finds color of the player
function currentColor(){
	var color;
	if (blackTurn) {
		color = 1;
	}
	else {
		color = -1 ;
	}
	return color;
}

//finds how much the canvas is offset in the frame
function findPos(obj) {
	var curleft = 0, curtop = 0;
	if (obj.offsetParent) {
		do {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		} while (obj = obj.offsetParent);
		return { x: curleft, y: curtop };
	}
	return undefined;
}

//game starts when hangout API is ready
gapi.hangout.onApiReady.add(function(eventObj){
	if (eventObj.isApiReady) {
		startGame();
		gapi.hangout.data.onStateChanged.add(function(stateChangeEvent) {
          serverUpdate(stateChangeEvent.state);
		});
	}
});

//if global state is changed, update global varibles and redraw board
function serverUpdate(){
	var state = gapi.hangout.data.getState();
	saveState = state;
	blackTurn = JSON.parse(state.blackTurn);
 	cArray = JSON.parse(state.cArray);
    drawBoard();
}
<commit_msg>new game won't be started if one already exists<commit_after>//global varibles
var width = 400;
var height = 400;
var bn = 8;		//number of boxs
var bs = 400/8; 		//boxsize

var board;			//canvas
var context;		//canvas context
var container;		//holds color score, player names and join button

var cArray = [];	//array of placed chits
var vArray = [];	//array of valid moves
var blackTurn;

var log;
var log1;

//initilizes empty arrays representing game state
function startGame()
{
	//fills cArray with 0s
	for (var x = 0; x < bn; x++) {
		cArray[x] = [];
		vArray[x] = [];
		for (var y = 0; y < bn; y++) {
			cArray[x][y] = 0;
			vArray[x][y] = 0;
		}
	}

	//places starting pieces
	cArray[3][3] = -1;
	cArray[4][4] = -1;
	cArray[3][4] = 1;
	cArray[4][3] = 1;

	//sets starting player
	blackTurn = true;

	setupCanvasObjects();
}

//creates on context object and listener
function setupCanvasObjects() {
	board = document.getElementById("board");
	context = board.getContext("2d");
	context.font = "50pt Calibri";

	container = document.getElementById("container");
	//listens for clicks on the board
	board.addEventListener("mousedown",click,false);
}

//clears canvas and redraws board
function drawBoard()
{
	//clear and resize canvas
	//board.width = width;
	//board.height = height;

	//clears canvas
	context.fillStyle = "rgb(255,255,255)";
	context.fillRect(0, 0, width, height);
	context.fillStyle = "rgb(0,200,0)";
	context.fillRect(0, 0, bn*bs, bn*bs);

	//draw grid
	drawGrid();

	//draw pieces placed by players
	createValidMoveArray();
	drawPieces();

	drawScore();
}

//draws grid of lines
function drawGrid()
{
	//draw vertical lines
	for (var x=0; x<=bn*bs; x+= bs) {
		context.moveTo(x,0);
		context.lineTo(x,bn*bs);
	}

	//draw horizontal lines
	for (var y=0; y<=bn*bs; y+= bs) {
		context.moveTo(0,y);
		context.lineTo(bn*bs,y);
	}

	//fills in lines in offwhite
	context.strokeStyle = "rgb(190,190,190)";
	context.stroke();
}

//draw pieces placed by players
function drawPieces()
{
	for (var x = 0; x < bn; x++) {
		for (var y = 0; y < bn; y++) {
			if (cArray[x][y] != 0) {
				drawPiece(x,y,cArray[x][y],8);
			}
			else if (vArray[x][y] != 0) {
				drawPiece(x,y,vArray[x][y],30);
			}
		}
	}
}

//draws a single piece at x, y with color and size passed
//larger size values make smaller pieces
function drawPiece(x, y, color, size)
{
	if (color == 1) {
		context.fillStyle = "rgb(0,0,0)";
	}
	else {
		context.fillStyle = "rgb(255,255,255)";
	}

	context.fillRect(x*bs + size, y*bs + size, bs - size*2, bs - size*2);
}

//displays filled box count at the bottom of the screen
function drawScore()
{
	var redScore = findScore(1);

	var blueScore = findScore(-1);
	context.fillStyle = "rgb(200,200,200)";
	context.fillText(blueScore, 500, 660);

	//underlines the score if it is that players turn
	context.fillStyle = "rgb(200,0,0)";
	if (blackTurn) {
		context.fillRect(90, 670, 62, 4);
	}
	else {
		context.fillRect(490, 670, 62, 4);
	}
}

//counts the total boxes by the passed player color
function findScore(color) {
	score = 0;
	for (var x = 0; x < bn; x++) {
		for (var y = 0; y < bn; y++) {
			if (cArray[x][y] == color) {
				score++;
			}
		}
	}
	return score;
}

//called when the page is clicked
function click(e)
{
	var color = currentColor();
	var pos = findPos(this);
	var cord = findCord(e.pageX - pos.x, e.pageY - pos.y);
	if (cord) {
		//if line is added to board, redraw lines
		if (vArray[cord.x][cord.y] != 0) {
			var flippedChips = findFlipDirections(cord.x, cord.y, color);
			log = flippedChips;
			for (var i = 0; i < flippedChips.length; i++) {
				cArray[flippedChips[i].x][flippedChips[i].y] = color;
			}
			cArray[cord.x][cord.y] = color;

			blackTurn = !blackTurn;

			//uploads newboard state
			gapi.hangout.data.submitDelta({cArray:JSON.stringify(cArray), blackTurn:JSON.stringify(blackTurn)});

			//drawBoard();
		}
	}
}

//finds which line the passed cord is closest to
function findCord(x, y)
{
	var RV = new Object; 	//return value

	//true if point is inside grid
	if (0 < x && x < bs*bn && 0 < y && y < bs*bn){
		xs = Math.floor(x/bs);
		ys = Math.floor(y/bs);

		RV.x = xs;
		RV.y = ys;
	}
	//cord not on grid; return false
	else {
		RV = false;
	}

	return RV;
}

//find valid moves
function createValidMoveArray() {
	var color = currentColor();
	for (var x = 0; x < bn; x++) {
		for (var y = 0; y < bn; y++) {
			vArray[x][y] = 0;
			if (cArray[x][y] == 0) {
				if (findFlipDirections(x,y,color).length>0){
					vArray[x][y] = color;
				}
			}
		}
	}
}

//from a given location, trys all flip directions
//returns an array of all the pieces that will be flipped if move is valid
//returns false otherwise
function findFlipDirections(x,y,color)
{
	var rv = [];
	var flippedChips;
	for (var dx	= -1;  dx<=1; dx++){
		for (var dy	= -1;  dy<=1; dy++){
			if (dx != 0 || dy != 0) {
				flippedChips = findFlipLength(x,y,dx,dy,color);
				for (var i = 0; i < flippedChips.length; i++) {
					log1 = flippedChips;
					rv[rv.length] = flippedChips[i];

				}
			}
		}
	}
	return rv;
}

//passed a location and direction
function findFlipLength(x,y,dx,dy,color)
{
	var rv = [];
	var i = 1;
	while (onBoard(x+i*dx,y+i*dy) && cArray[x+dx*i][y+dy*i] == -1*color) {
		i++;
	}

	if (i>1 && onBoard(x+i*dx,y+i*dy) && cArray[x+dx*i][y+dy*i] == color) {

		for (var j = 0; j<i; j++) {
			rv[j] = new Object;
			rv[j].x = x+j*dx;
			rv[j].y = y+j*dy;
		}
	}

	return rv;
}

//returns true if the cord is on the board
function onBoard(x, y) {
	return (0 <= x && x <= 7 && 0 <= y && y <= 7);
}

//finds color of the player
function currentColor(){
	var color;
	if (blackTurn) {
		color = 1;
	}
	else {
		color = -1 ;
	}
	return color;
}

//finds how much the canvas is offset in the frame
function findPos(obj) {
	var curleft = 0, curtop = 0;
	if (obj.offsetParent) {
		do {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		} while (obj = obj.offsetParent);
		return { x: curleft, y: curtop };
	}
	return undefined;
}

//game starts when hangout API is ready
gapi.hangout.onApiReady.add(function(eventObj){
	if (eventObj.isApiReady) {
		var state = gapi.hangout.data.getState();

		if (state.cArray) {
			//game already running, join it
			setupCanvasObjects();
			serverUpdate();
		}
		else {
			//no game running, start a new one
			startGame();
		}
		gapi.hangout.data.onStateChanged.add(function(stateChangeEvent) {
          serverUpdate(stateChangeEvent.state);
		});
	}
});

//if global state is changed, update global varibles and redraw board
function serverUpdate(){
	var state = gapi.hangout.data.getState();
	blackTurn = JSON.parse(state.blackTurn);
 	cArray = JSON.parse(state.cArray);
    drawBoard();
}
<|endoftext|>


<commit_before>(function (window, $, undefined) {

    function DeferredLocalFileSystem() {
        this.TEMPORARY = window.TEMPORARY;
        this.PERSISTENT = window.PERSISTENT;
    };

    DeferredLocalFileSystem.prototype.requestFileSystem = function requestFileSystem(type, size) {
        var self = this,
            d = $.Deferred(),
            errorCallback = function (error) {
                d.reject(error);
            },
            successCallback = function (fileSystem) {
                d.resolve(new DeferredFileSystem(fileSystem));
            };

        window.requestFileSystem(type, size, successCallback, errorCallback);

        return d.promise();
    };

    DeferredLocalFileSystem.prototype.resolveLocalFileSystemURL = function resolveLocalFileSystemURL(url) {
        var self = this,
            d = $.Deferred(),
            errorCallback = function (error) {
                d.reject(error);
            },
            successCallback = function (entry) {
                d.resolve(new DeferredEntry(entry));
            };

        window.resolveLocalFileSystemURL(url, successCallback, errorCallback);

        return d.promise();
    };

    function DeferredFileSystem(fileSystem) {
        var self = this;

        //
        self.fileSystem = fileSystem;

        //
        self.name = fileSystem.name;
        self.root = fileSystem.root;
    };

    function DeferredEntry(entry) {
        var self = this;

        //
        self.entry = entry;

        //
        self.isFile = entry.isFile;
        self.isDirectory = entry.isDirectory;
        self.name = entry.name;
        self.fullPath = entry.fullPath;
        self.filesystem = entry.filesystem;
    };

    DeferredEntry.prototype.getMetadata = function getMetadata() {
        var self = this,
            d = $.Deferred(),
            errorCallback = function (error) {
                d.reject(error);
            },
            successCallback = function (metadata) {
                d.resolve(metadata);
            };

        self.entry.getMetadata(successCallback, errorCallback);

        return d.promise();
    };

    DeferredEntry.prototype.copyTo = function copyTo(parent, newName) {
        var self = this,
            d = $.Deferred(),
            errorCallback = function (error) {
                d.reject(error);
            },
            successCallback = function (entry) {
                d.resolve(new DeferredEntry(entry));
            };

        self.entry.copyTo(parent, newName, successCallback, errorCallback);

        return d.promise();
    };

    DeferredEntry.prototype.moveTo = function moveTo(parent, newName) {
        var self = this,
            d = $.Deferred(),
            errorCallback = function (error) {
                d.reject(error);
            },
            successCallback = function (entry) {
                d.resolve(new DeferredEntry(entry));
            };

        self.entry.moveTo(parent, newName, successCallback, errorCallback);

        return d.promise();
    };

    DeferredEntry.prototype.remove = function remove() {
        var self = this,
            d = $.Deferred(),
            errorCallback = function (error) {
                d.reject(error);
            },
            successCallback = function () {
                d.resolve();
            };

        self.entry.remove(successCallback, errorCallback);

        return d.promise();
    };

    DeferredEntry.prototype.toURL = function toURL() {
        var self = this;

        return self.entry.toURL();
    };

    DeferredEntry.prototype.getParent = function getParent() {
        var self = this,
            d = $.Deferred(),
            errorCallback = function (error) {
                d.reject(error);
            },
            successCallback = function (entry) {
                d.resolve(new DeferredEntry(entry));
            };

        self.entry.remove(successCallback, errorCallback);

        return d.promise();
    };

    function DeferredFileEntry(fileEntry) {
        this.entry = fileEntry;
    };

    DeferredFileEntry.prototype.createWriter = function createWriter() {
        var self = this,
            d = $.Deferred(),
            errorCallback = function (error) {
                d.reject(error);
            },
            successCallback = function (fileWriter) {
                d.resolve(fileWriter);
            };

        self.entry.createWriter(successCallback, errorCallback);

        return d.promise();
    };

    DeferredFileEntry.prototype.file = function file() {
        var self = this,
            d = $.Deferred(),
            errorCallback = function (error) {
                d.reject(error);
            },
            successCallback = function (file) {
                d.resolve(file);
            };

        self.entry.file(successCallback, errorCallback);

        return d.promise();
    };

    function DeferredDirectoryEntry(directoryEntry) {
        this.entry = directoryEntry;
    };

    DeferredDirectoryEntry.prototype.createReader = function createReader() {
        return new DeferredDirectoryReader(self.directoryEntry.createReader());
    };

    DeferredDirectoryEntry.prototype.getFile = function getFile(path, options) {
        var self = this,
            d = $.Deferred(),
            errorCallback = function (error) {
                d.reject(error);
            },
            successCallback = function (entry) {
                d.resolve(new DeferredEntry(entry));
            };

        self.entry.getFile(path, options, successCallback, errorCallback);

        return d.promise();
    };

    DeferredDirectoryEntry.prototype.getDirectory = function getDirectory(path, options) {
        var self = this,
            d = $.Deferred(),
            errorCallback = function (error) {
                d.reject(error);
            },
            successCallback = function (entry) {
                d.resolve(new DeferredEntry(entry));
            };

        self.entry.getDirectory(path, options, successCallback, errorCallback);

        return d.promise();
    };

    DeferredDirectoryEntry.prototype.removeRecursively = function removeRecursively() {
        var self = this,
            d = $.Deferred(),
            errorCallback = function (error) {
                d.reject(error);
            },
            successCallback = function () {
                d.resolve();
            };

        self.entry.remove(successCallback, errorCallback);

        return d.promise();
    };

    function DeferredDirectoryReader(directoryReader) {
        this.directoryReader = directoryReader;
    };

    DeferredDirectoryReader.prototype.readEntries = function readEntries() {
        var self = this,
            d = $.Deferred(),
            errorCallback = function (error) {
                d.reject(error);
            },
            successCallback = function (entries) {
                //wrap entries in 'Deferred' object.

                d.resolve(entries);
            };

        self.directoryReader.readEntries(successCallback, errorCallback);

        return d.promise();
    };

})(window, jQuery);
<commit_msg>Move FileSystem entry points from DeferredFileSystem to window<commit_after>(function (window, $, undefined) {

    function DeferredLocalFileSystem() {
        this.TEMPORARY = window.TEMPORARY;
        this.PERSISTENT = window.PERSISTENT;
    };

    var requestFileSystemDeferred = function requestFileSystemDeferred(type, size) {
        var self = this,
            d = $.Deferred(),
            errorCallback = function (error) {
                d.reject(error);
            },
            successCallback = function (fileSystem) {
                d.resolve(new DeferredFileSystem(fileSystem));
            };

        window.requestFileSystem(type, size, successCallback, errorCallback);

        return d.promise();
    };

    var resolveLocalFileSystemURLDeferred = function resolveLocalFileSystemURLDeferred(url) {
        var self = this,
            d = $.Deferred(),
            errorCallback = function (error) {
                d.reject(error);
            },
            successCallback = function (entry) {
                d.resolve(new DeferredEntry(entry));
            };

        window.resolveLocalFileSystemURL(url, successCallback, errorCallback);

        return d.promise();
    };

    function DeferredFileSystem(fileSystem) {
        var self = this;

        //
        self.fileSystem = fileSystem;

        //
        self.name = fileSystem.name;
        self.root = new DeferredEntry(fileSystem.root);
    };

    function DeferredEntry(entry) {
        var self = this;

        //
        self.entry = entry;

        //
        self.isFile = entry.isFile;
        self.isDirectory = entry.isDirectory;
        self.name = entry.name;
        self.fullPath = entry.fullPath;
        self.filesystem = entry.filesystem;
    };

    DeferredEntry.prototype.getMetadata = function getMetadata() {
        var self = this,
            d = $.Deferred(),
            errorCallback = function (error) {
                d.reject(error);
            },
            successCallback = function (metadata) {
                d.resolve(metadata);
            };

        self.entry.getMetadata(successCallback, errorCallback);

        return d.promise();
    };

    DeferredEntry.prototype.copyTo = function copyTo(parent, newName) {
        var self = this,
            d = $.Deferred(),
            errorCallback = function (error) {
                d.reject(error);
            },
            successCallback = function (entry) {
                d.resolve(new DeferredEntry(entry));
            };

        self.entry.copyTo(parent, newName, successCallback, errorCallback);

        return d.promise();
    };

    DeferredEntry.prototype.moveTo = function moveTo(parent, newName) {
        var self = this,
            d = $.Deferred(),
            errorCallback = function (error) {
                d.reject(error);
            },
            successCallback = function (entry) {
                d.resolve(new DeferredEntry(entry));
            };

        self.entry.moveTo(parent, newName, successCallback, errorCallback);

        return d.promise();
    };

    DeferredEntry.prototype.remove = function remove() {
        var self = this,
            d = $.Deferred(),
            errorCallback = function (error) {
                d.reject(error);
            },
            successCallback = function () {
                d.resolve();
            };

        self.entry.remove(successCallback, errorCallback);

        return d.promise();
    };

    DeferredEntry.prototype.toURL = function toURL() {
        var self = this;

        return self.entry.toURL();
    };

    DeferredEntry.prototype.getParent = function getParent() {
        var self = this,
            d = $.Deferred(),
            errorCallback = function (error) {
                d.reject(error);
            },
            successCallback = function (entry) {
                d.resolve(new DeferredEntry(entry));
            };

        self.entry.remove(successCallback, errorCallback);

        return d.promise();
    };

    function DeferredFileEntry(fileEntry) {
        this.entry = fileEntry;
    };

    DeferredFileEntry.prototype.createWriter = function createWriter() {
        var self = this,
            d = $.Deferred(),
            errorCallback = function (error) {
                d.reject(error);
            },
            successCallback = function (fileWriter) {
                d.resolve(fileWriter);
            };

        self.entry.createWriter(successCallback, errorCallback);

        return d.promise();
    };

    DeferredFileEntry.prototype.file = function file() {
        var self = this,
            d = $.Deferred(),
            errorCallback = function (error) {
                d.reject(error);
            },
            successCallback = function (file) {
                d.resolve(file);
            };

        self.entry.file(successCallback, errorCallback);

        return d.promise();
    };

    function DeferredDirectoryEntry(directoryEntry) {
        this.entry = directoryEntry;
    };

    DeferredDirectoryEntry.prototype.createReader = function createReader() {
        return new DeferredDirectoryReader(self.directoryEntry.createReader());
    };

    DeferredDirectoryEntry.prototype.getFile = function getFile(path, options) {
        var self = this,
            d = $.Deferred(),
            errorCallback = function (error) {
                d.reject(error);
            },
            successCallback = function (entry) {
                d.resolve(new DeferredEntry(entry));
            };

        self.entry.getFile(path, options, successCallback, errorCallback);

        return d.promise();
    };

    DeferredDirectoryEntry.prototype.getDirectory = function getDirectory(path, options) {
        var self = this,
            d = $.Deferred(),
            errorCallback = function (error) {
                d.reject(error);
            },
            successCallback = function (entry) {
                d.resolve(new DeferredEntry(entry));
            };

        self.entry.getDirectory(path, options, successCallback, errorCallback);

        return d.promise();
    };

    DeferredDirectoryEntry.prototype.removeRecursively = function removeRecursively() {
        var self = this,
            d = $.Deferred(),
            errorCallback = function (error) {
                d.reject(error);
            },
            successCallback = function () {
                d.resolve();
            };

        self.entry.remove(successCallback, errorCallback);

        return d.promise();
    };

    function DeferredDirectoryReader(directoryReader) {
        this.directoryReader = directoryReader;
    };

    DeferredDirectoryReader.prototype.readEntries = function readEntries() {
        var self = this,
            d = $.Deferred(),
            errorCallback = function (error) {
                d.reject(error);
            },
            successCallback = function (entries) {
                //wrap entries in 'Deferred' object.

                d.resolve(entries);
            };

        self.directoryReader.readEntries(successCallback, errorCallback);

        return d.promise();
    };

    window.requestFileSystemDeferred = requestFileSystemDeferred;
    window.resolveLocalFileSystemURLDeferred = resolveLocalFileSystemURLDeferred;

})(window, jQuery);
<|endoftext|>