<commit_before>'use strict';

/**
 * Convert an array of parent-child relational objects to a tree.
 * Minimal implementation that provides a depth-first iterator.
 *
 * @param {Array} data Collection objects with parent-child relations.
 * @param {String} key Name of the property that has the name or id of the object.
 * @param {String} ref Name of the property that references the parent, see key.
 */
function Sapling(data, key, ref) {
  if (!this) return new Sapling(data, key, ref);

  //
  // Number of iterations in the worst case scenario: (n * 2 - 1).
  // Prepare several variables used in the loop.
  //
  var i = 2 * data.length - 1
    , map = {}, datum, parent, name, d;

  while (i-- && data.length > 0) {
    datum = data.pop();
    datum.children = datum.children || [];

    parent = datum[ref];
    name = datum[key];

    if (!parent) {
      map[name] = this;
      for (d in datum) this[d] = datum[d];
    } else {
      map[name] = datum;

      if (parent in map) map[parent].children.push(map[name]);
      else data.unshift(datum);
    }
  }
}

//
// Define the iterator as non-enumarable and -configurable.
//
Object.defineProperty(Sapling.prototype, 'iterate', {
  configurable: false,
  enumerable: false,

  /**
   * Depth first iterator. Call `next` to walk through the entire tree.
   * Will return child Node objects if available otherwise walks up the
   * tree to return Parent Node Object.s
   *
   * @param {Object} parent Parent node of the current child.
   * @return {Object} Child node.
   */
  value: function iterate(parent) {
    var node = this
      , i = 0
      , key;

    Object.defineProperty(node, 'next', {
      configurable: false,
      enumerable: false,
      value: function next() {
        var child = node.children[i++];

        if (!child && !parent) return void 0;
        if (!child) return parent;
        return iterate.call(child, node);
      }
    });

    return node;
  }
});

//
// Expose the module.
//
module.exports = Sapling;<commit_msg>[minor] add get<commit_after>'use strict';

/**
 * Convert an array of parent-child relational objects to a tree.
 * Minimal implementation that provides a depth-first iterator.
 *
 * @param {Array} data Collection objects with parent-child relations.
 * @param {String} key Name of the property that has the name or id of the object.
 * @param {String} ref Name of the property that references the parent, see key.
 */
function Sapling(data, key, ref) {
  if (!this) return new Sapling(data, key, ref);

  //
  // Number of iterations in the worst case scenario: (n * 2 - 1).
  // Prepare several variables used in the loop.
  //
  var i = 2 * data.length - 1
    , map = {}, datum, parent, name, d;

  while (i-- && data.length > 0) {
    datum = data.pop();
    datum.children = datum.children || [];

    parent = datum[ref];
    name = datum[key];

    if (!parent) {
      map[name] = this;
      for (d in datum) this[d] = datum[d];
    } else {
      map[name] = datum;

      if (parent in map) map[parent].children.push(map[name]);
      else data.unshift(datum);
    }
  }
}

//
// Define the iterator as non-enumarable and -configurable.
//
Object.defineProperties(Sapling.prototype, {
  get: {
    configurable: false,
    enumerable: false,

    /**
     * Simple get/search that uses the iterator.
     *
     * @param {String} name Node name.
     * @return {Object} Node.
     */
    value: function get(name) {
      var node = this.iterate();
      name = name.toString();

      do {
        if (node.name === name) {
          return node;
        }
      } while (node = node.next())
    }
  },

  iterate: {
    configurable: false,
    enumerable: false,

    /**
     * Depth first iterator. Call `next` to walk through the entire tree.
     * Will return child Node objects if available otherwise walks up the
     * tree to return Parent Node Object.s
     *
     * @param {Object} parent Parent node of the current child.
     * @return {Object} Child node.
     */
    value: function iterate(parent) {
      var node = this
        , i = 0
        , key;

      Object.defineProperty(node, 'next', {
        configurable: true,
        enumerable: false,
        value: function next() {
          var child = node.children[i++];

          if (!child && !parent) return void 0;
          if (!child) return parent;
          return iterate.call(child, node);
        }
      });

      return node;
    }
  }
});

//
// Expose the module.
//
module.exports = Sapling;<|endoftext|>


<commit_before>const fs = require('fs');
const glob = require('glob');
const Task = require('data.task');
const futurize = require('futurize').futurize(Task);
const IO = require('fantasy-io');
const { List } = require('immutable-ext');
const { __
      , chain
      , compose
      , curry
      , curryN
      , join: joinR
      , map
      , pipe
      , tap
      , traverse
      , trim
      , tryCatch
      , unary
      } = require('ramda');
const readFile = curryN(2, futurize(fs.readFile));
const writeFile = curryN(2, futurize(fs.writeFile));
const unsafePerform = io => io.unsafePerform();
const lines = unary(require('sanctuary').lines); // Why do I need unary here? seems like it should work without
const escape = require('escape-quotes');

//    getFileList :: IO List String
const getFileList = new IO(function () {
  return List(glob.sync(process.argv[2]));
});

//    ioToTask :: IO a -> Task a
const ioToTask = tryCatch(
  compose(Task.of, unsafePerform),
  Task.rejected
);

//    getFileContents :: Task List String -> Task List String
const getFileContents = traverse(Task.of, readFile(__, 'utf-8'));

//    wrapWithCachePuts :: String -> String
const wrapWithCachePuts = compose(
  s => `$templateCache.puts('${s}');`,
  escape,
  joinR(''),
  map(trim),
  lines
);

//    join :: List String -> String
const join = curry(function (separator, l) { return l.join(separator); });

const main = pipe(
  ioToTask,
  chain(getFileContents),
  map(map(wrapWithCachePuts)),
  map(join('\n')),
  chain(writeFile('out.js'))
);

main(getFileList).fork(console.error, () => console.log("Success!"));
<commit_msg>Removed extra join fn def<commit_after>const fs = require('fs');
const glob = require('glob');
const Task = require('data.task');
const futurize = require('futurize').futurize(Task);
const IO = require('fantasy-io');
const { List } = require('immutable-ext');
const { __
      , chain
      , compose
      , curry
      , curryN
      , join
      , map
      , pipe
      , tap
      , traverse
      , trim
      , tryCatch
      , unary
      } = require('ramda');
const readFile = curryN(2, futurize(fs.readFile));
const writeFile = curryN(2, futurize(fs.writeFile));
const unsafePerform = io => io.unsafePerform();
const lines = unary(require('sanctuary').lines); // Why do I need unary here? seems like it should work without
const escape = require('escape-quotes');

//    getFileList :: IO List String
const getFileList = new IO(function () {
  return List(glob.sync(process.argv[2]));
});

//    ioToTask :: IO a -> Task a
const ioToTask = tryCatch(
  compose(Task.of, unsafePerform),
  Task.rejected
);

//    getFileContents :: Task List String -> Task List String
const getFileContents = traverse(Task.of, readFile(__, 'utf-8'));

//    wrapWithCachePuts :: String -> String
const wrapWithCachePuts = compose(
  s => `$templateCache.puts('${s}');`,
  escape,
  join(''),
  map(trim),
  lines
);

const main = pipe(
  ioToTask,
  chain(getFileContents),
  map(map(wrapWithCachePuts)),
  map(join('\n')),
  chain(writeFile('out.js'))
);

main(getFileList).fork(console.error, () => console.log("Success!"));
<|endoftext|>


<commit_before>var isGeneratorFunction = require('is-generator-function')
var parallels = require('parallels')

function isFunction (val) {
  return typeof val === 'function'
}
function isGenerator (val) {
  return val && typeof val.next === 'function' && typeof val.throw === 'function'
}
function isPromise (val) {
  return val && typeof val.then === 'function'
}
function isObservable (val) {
  return val && typeof val.subscribe === 'function'
}
function noop () {}

module.exports = (function factory () {
  /**
   * raco resolver
   * returns factory if no arguments
   *
   * @param {function*} genFn - generator function
   * @param {...*} args - optional arguments
   * @returns {promise} if no callback provided
   */
  function raco (genFn) {
    if (arguments.length === 0) return factory()
    var args = Array.prototype.slice.call(arguments, 1)
    return _raco.call(this, genFn, args)
  }

  /**
   * internal raco resolver
   *
   * @param {function*} genFn - generator function
   * @param {array} args - arguments in real array form
   * @returns {promise} if no callback provided
   */
  function _raco (genFn, args) {
    var self = this
    var done = false
    var trycatch = true
    var ticking = false
    var parallel = null
    var callback = null

    // pass raco next to generator function
    if (isFunction(args[args.length - 1])) callback = args.pop()
    args.push(next)

    var iter = isGenerator(genFn) ? genFn : genFn.apply(self, args)

    /**
     * internal callback stepper
     *
     * @param {*} err - callback error object
     * @param {...*} val - callback value(s)
     */
    function step (err, val) {
      if (!iter) {
        if (!done) {
          done = true
          callback.apply(self, arguments)
        }
      } else {
        // generator step
        var state
        if (trycatch) {
          try {
            state = err ? iter.throw(err) : iter.next(val)
          } catch (err) {
            // catch err, break iteration
            done = true
            return callback.call(self, err)
          }
        } else {
          state = err ? iter.throw(err) : iter.next(val)
        }
        if (state && state.done) iter = null

        // resolve yieldable
        var isYieldable = raco._yieldable(state.value, step)

        // next if generator returned non-yieldable
        if (!isYieldable && !iter) next(null, state.value)
      }
    }

    /**
     * next, callback stepper with nextTick
     *
     * @param {*} err - callback error object
     * @param {...*} val - callback value(s)
     */
    function next () {
      var args = Array.prototype.slice.call(arguments)
      if (!ticking) {
        ticking = true
        process.nextTick(function () {
          ticking = false
          step.apply(self, args)
        })
      } else if (iter) {
        // error on multiple callbacks wthin one iteration
        iter = null
        step.call(self, new Error('Multiple callbacks within one iteration'))
      } else {
        // callback and return, pick callback value
        iter = null
      }
    }

    /**
     * clear parallel queue
     */
    next.clear = function () {
      parallel = null
    }

    /**
     * next.push parallel callback queue
     *
     * @returns {function} callback function (err, val)
     */
    next.push = function () {
      parallel = parallel || parallels()
      return parallel.push()
    }

    /**
     * next.all parallel callback values aggregation and resets queue
     */
    next.all = function () {
      if (!parallel) return next(null, [])
      parallel.all(next)
      parallel = null
    }

    /**
     * next.all parallel callback values aggregation and resets queue
     */
    next.any = function () {
      if (!parallel) return next(null, null)
      parallel.any(next)
      parallel = null
    }

    if (callback) {
      // callback mode
      step()
    } else if (raco.Promise) {
      // return promise if callback not exists
      return new raco.Promise(function (resolve, reject) {
        callback = function (err, val) {
          if (err) return reject(err)
          resolve(val)
        }
        step()
      })
    } else {
      // callback and promise not exists,
      // no try catch wrap
      trycatch = false
      callback = noop
      step()
    }
  }

  /**
   * wraps a generator function into regular function that
   * optionally accepts callback or returns a promise.
   *
   * @param {function*} genFn - generator function
   * @returns {function} regular function
   */
  raco.wrap = function (genFn) {
    return function () {
      var args = Array.prototype.slice.call(arguments)
      return _raco.call(this, genFn, args)
    }
  }

  /**
   * wraps generator function properties of object
   *
   * @param {object} obj - object to raco.wrap
   * @returns {object} original object
   */
  raco.wrapAll = function (obj) {
    for (var key in obj) {
      if (
        obj.hasOwnProperty(key) &&
        (isGeneratorFunction(obj[key]) || isGenerator(obj[key]))
      ) {
        obj[key] = raco.wrap(obj[key])
      }
    }
    return obj
  }

  /**
   * Promise constructor of raco,
   * use native Promise by default
   *
   */
  raco.Promise = global.Promise

  /**
   * yieldable callback mapper
   *
   * @param {*} val - yielded value to resolve
   * @param {function} cb - resolver callback function
   * @returns {boolean} acknowledge yieldable
   */
  raco._yieldable = function (val, cb) {
    if (isPromise(val)) {
      // Promise
      val.then(function (value) {
        cb(null, value)
      }, function (err) {
        cb(err || new Error())
      })
      return true
    } else if (isGeneratorFunction(val) || isGenerator(val)) {
      // Generator
      raco(val, cb)
      return true
    } else if (isFunction(val)) {
      // Thunk
      val(cb)
      return true
    } else if (isObservable(val)) {
      // Observable
      var dispose = val.subscribe(function (val) {
        cb(null, val)
        dispose.dispose()
      }, function (err) {
        cb(err || new Error())
        dispose.dispose()
      })
      return true
    } else {
      // Not yieldable
      return false
    }
  }

  return raco
})()
<commit_msg>clean up<commit_after>var isGeneratorFunction = require('is-generator-function')
var parallels = require('parallels')

function isFunction (val) {
  return typeof val === 'function'
}
function isGenerator (val) {
  return val && typeof val.next === 'function' && typeof val.throw === 'function'
}
function isPromise (val) {
  return val && typeof val.then === 'function'
}
function isObservable (val) {
  return val && typeof val.subscribe === 'function'
}
function noop () {}

module.exports = (function factory () {
  /**
   * raco resolver
   * returns factory if no arguments
   *
   * @param {function*} genFn - generator function
   * @param {...*} args - optional arguments
   * @returns {promise} if no callback provided
   */
  function raco (genFn) {
    if (arguments.length === 0) return factory()
    var args = Array.prototype.slice.call(arguments, 1)
    return _raco.call(this, genFn, args)
  }

  /**
   * internal raco resolver
   *
   * @param {function*} genFn - generator function
   * @param {array} args - arguments in real array form
   * @returns {promise} if no callback provided
   */
  function _raco (genFn, args) {
    var self = this
    var done = false
    var trycatch = true
    var ticking = false
    var parallel = null
    var callback = null

    // pass raco next to generator function
    if (isFunction(args[args.length - 1])) callback = args.pop()
    args.push(next)

    var iter = isGenerator(genFn) ? genFn : genFn.apply(self, args)

    /**
     * internal callback stepper
     *
     * @param {*} err - callback error object
     * @param {...*} val - callback value(s)
     */
    function step (err, val) {
      if (!iter) {
        if (!done) {
          done = true
          callback.apply(self, arguments)
        }
      } else {
        // generator step
        var state
        if (trycatch) {
          try {
            state = err ? iter.throw(err) : iter.next(val)
          } catch (err) {
            // catch err, break iteration
            done = true
            return callback.call(self, err)
          }
        } else {
          state = err ? iter.throw(err) : iter.next(val)
        }
        if (state && state.done) iter = null
        // resolve yieldable
        var isYieldable = raco._yieldable(state.value, step)
        // next if generator returned non-yieldable
        if (!isYieldable && !iter) next(null, state.value)
      }
    }

    /**
     * next, callback stepper with nextTick
     *
     * @param {*} err - callback error object
     * @param {...*} val - callback value(s)
     */
    function next () {
      var args = Array.prototype.slice.call(arguments)
      if (!ticking) {
        ticking = true
        process.nextTick(function () {
          ticking = false
          step.apply(self, args)
        })
      } else if (iter) {
        // error on multiple callbacks wthin one iteration
        iter = null
        step.call(self, new Error('Multiple callbacks within one iteration'))
      } else {
        // callback and return, pick callback value
        iter = null
      }
    }

    /**
     * clear parallel queue
     */
    next.clear = function () {
      parallel = null
    }

    /**
     * push parallel callback queue
     *
     * @returns {function} callback function (err, val)
     */
    next.push = function () {
      parallel = parallel || parallels()
      return parallel.push()
    }

    /**
     * aggregate parallel values into array and resets queue
     */
    next.all = function () {
      if (!parallel) return next(null, [])
      parallel.all(next)
      parallel = null
    }

    /**
     * return first value of parallel and resets queue
     */
    next.any = function () {
      if (!parallel) return next(null, null)
      parallel.any(next)
      parallel = null
    }

    if (callback) {
      // callback mode
      step()
    } else if (raco.Promise) {
      // return promise if callback not exists
      return new raco.Promise(function (resolve, reject) {
        callback = function (err, val) {
          if (err) return reject(err)
          resolve(val)
        }
        step()
      })
    } else {
      // callback and promise not exists,
      // no try catch wrap
      trycatch = false
      callback = noop
      step()
    }
  }

  /**
   * wraps a generator function into regular function that
   * optionally accepts callback or returns a promise.
   *
   * @param {function*} genFn - generator function
   * @returns {function} regular function
   */
  raco.wrap = function (genFn) {
    return function () {
      var args = Array.prototype.slice.call(arguments)
      return _raco.call(this, genFn, args)
    }
  }

  /**
   * wraps generator function properties of object
   *
   * @param {object} obj - object to raco.wrap
   * @returns {object} original object
   */
  raco.wrapAll = function (obj) {
    for (var key in obj) {
      if (
        obj.hasOwnProperty(key) &&
        (isGeneratorFunction(obj[key]) || isGenerator(obj[key]))
      ) {
        obj[key] = raco.wrap(obj[key])
      }
    }
    return obj
  }

  /**
   * Promise constructor of raco,
   * use native Promise by default
   *
   */
  raco.Promise = global.Promise

  /**
   * yieldable callback mapper
   *
   * @param {*} val - yielded value to resolve
   * @param {function} cb - resolver callback function
   * @returns {boolean} acknowledge yieldable
   */
  raco._yieldable = function (val, cb) {
    if (isPromise(val)) {
      // Promise
      val.then(function (value) {
        cb(null, value)
      }, function (err) {
        cb(err || new Error())
      })
      return true
    } else if (isGeneratorFunction(val) || isGenerator(val)) {
      // Generator
      raco(val, cb)
      return true
    } else if (isFunction(val)) {
      // Thunk
      val(cb)
      return true
    } else if (isObservable(val)) {
      // Observable
      var dispose = val.subscribe(function (val) {
        cb(null, val)
        dispose.dispose()
      }, function (err) {
        cb(err || new Error())
        dispose.dispose()
      })
      return true
    } else {
      // Not yieldable
      return false
    }
  }

  return raco
})()
<|endoftext|>


<commit_before>var DEFAULT_PAGE = 'about';

// Given an HTML string response, set it as the page content.
var onChangePage = function(/*string*/ response) {
  var body = document.getElementById('body');
  body.innerHTML = response;
}

// Given a URL, load the contents into the body of the page.
var loadPage = function(/*string*/ url) {
  var request = new XMLHttpRequest();
  request.onreadystatechange = function() {
    if (request.readyState === 4) {
      onChangePage(request.responseText);
    }
  };
  request.open('GET', url, true);
  request.send();
};

var loadPageAndUpdateNavFromCurrentHash = function() {
  var hash = window.location.hash.replace('#', '') || DEFAULT_PAGE;

  var links = {
    about: document.getElementById('nav-about'),
    projects: document.getElementById('nav-projects')
  };

  for (var link_name in links) {
    if (links.hasOwnProperty(link_name)) {
      if (link_name === hash) {
        links[link_name].classList.add('selected');
      } else {
        links[link_name].classList.remove('selected');
      }
    }
  }

  loadPage(hash + '.html');
}

window.onhashchange = loadPageAndUpdateNavFromCurrentHash;
window.onload = loadPageAndUpdateNavFromCurrentHash;<commit_msg>Make hashes that are not valid redirect to DEFAULT_PAGE<commit_after>var DEFAULT_PAGE = 'about';

// Given an HTML string response, set it as the page content.
var onChangePage = function(/*string*/ response) {
  var body = document.getElementById('body');
  body.innerHTML = response;
}

// Given a URL, load the contents into the body of the page.
var loadPage = function(/*string*/ url) {
  var request = new XMLHttpRequest();
  request.onreadystatechange = function() {
    if (request.readyState === 4) {
      onChangePage(request.responseText);
    }
  };
  request.open('GET', url, true);
  request.send();
};

var loadPageAndUpdateNavFromCurrentHash = function() {

  var links = {
    about: document.getElementById('nav-about'),
    projects: document.getElementById('nav-projects')
  };

  var hash = window.location.hash.replace('#', '');
  hash = hash in links ? hash : DEFAULT_PAGE;

  for (var link_name in links) {
    if (links.hasOwnProperty(link_name)) {
      if (link_name === hash) {
        links[link_name].classList.add('selected');
      } else {
        links[link_name].classList.remove('selected');
      }
    }
  }

  loadPage(hash + '.html');
}

window.onhashchange = loadPageAndUpdateNavFromCurrentHash;
window.onload = loadPageAndUpdateNavFromCurrentHash;<|endoftext|>


<commit_before>/*jslint node:true indent:2 nomen:true*/
'use strict';
var arg = require("arg-err").config({ propErr: true }),
  assert = require('assert');

module.exports = function (req, res, next) {

  function sendResponse(code, json) {
    if (req.query.callback) {
      return res.jsonp(json);
    }
    return res.status(code).json(json);
  }

  function getSuccessCode() {
    return (req._method === 'POST' || req.method === 'POST') ? 201 : 200;
  }

  function getSuccessResponseData(data) {
    return (!data || (req._method === 'DELETE' || req.method === 'DELETE')) ? null : data;
  }

  res.jSend = function (data, metadata) {
    var payload = {
      status: 'success',
      data: getSuccessResponseData(data)
    };
    if (metadata) {
      payload.metadata = metadata;
    }
    return sendResponse(getSuccessCode(), payload);
  };

  function formatErrorObject(err) {
    return {
      message: String(err),
      stack: err.stack
    };
  }

  function validateErrorOptions(options) {
    assert(options, 'res.jSend.error invoked without options');
    var required = {
        message: "string"
      },
      optional = {
        code: "number",
        data: "object"
      },
      err = arg.err(options, required, optional);
    if (err) {
      throw new Error('res.jSend.error options validation: ' + err);
    }
  }

  res.jSend.error = function (options) {
    validateErrorOptions(options);
    if (options.data instanceof Error) {
      options.data = formatErrorObject(options.data);
    }
    if (options.code === undefined) {
      options.code = 500;
    }
    var responseData = {
      status: 'error',
      code: options.code,
      message: options.message
    };
    if (process.env.NODE_ENV !== 'production') {
      responseData.data = options.data || null;
    }
    if (module.exports.listeners('error').length) {
      module.exports.emit('error', responseData);
    }
    return sendResponse(options.code, responseData);
  };

  function validateFailOptions(options) {
    assert(options, 'res.jSend.fail invoked without options');
    var required = {},
      optional = {
        data: ["object", "string"],
        code: "number",
        message: "string",
      },
      err = arg.err(options, required, optional);
    assert(!err, 'res.jSend.fail options validation: ' + err);
  }

  res.jSend.fail = function (options) {
    validateFailOptions(options);
    if (options.code === undefined) {
      options.code = 400;
    }
    var responseData = {
      status: 'fail',
      code: options.code,
      data: options.data,
      message: options.message
    };
    return sendResponse(options.code, responseData);
  };

  return next();
};

// add events
module.exports.__proto__ = new (require('events').EventEmitter)();
<commit_msg>Change throw error to assert<commit_after>/*jslint node:true indent:2 nomen:true*/
'use strict';
var arg = require("arg-err").config({ propErr: true }),
  assert = require('assert');

module.exports = function (req, res, next) {

  function sendResponse(code, json) {
    if (req.query.callback) {
      return res.jsonp(json);
    }
    return res.status(code).json(json);
  }

  function getSuccessCode() {
    return (req._method === 'POST' || req.method === 'POST') ? 201 : 200;
  }

  function getSuccessResponseData(data) {
    return (!data || (req._method === 'DELETE' || req.method === 'DELETE')) ? null : data;
  }

  res.jSend = function (data, metadata) {
    var payload = {
      status: 'success',
      data: getSuccessResponseData(data)
    };
    if (metadata) {
      payload.metadata = metadata;
    }
    return sendResponse(getSuccessCode(), payload);
  };

  function formatErrorObject(err) {
    return {
      message: String(err),
      stack: err.stack
    };
  }

  function validateErrorOptions(options) {
    assert(options, 'res.jSend.error invoked without options');
    var required = {
        message: "string"
      },
      optional = {
        code: "number",
        data: "object"
      },
      err = arg.err(options, required, optional);
    assert(!err, 'res.jSend.error options validation: ' + err);
  }

  res.jSend.error = function (options) {
    validateErrorOptions(options);
    if (options.data instanceof Error) {
      options.data = formatErrorObject(options.data);
    }
    if (options.code === undefined) {
      options.code = 500;
    }
    var responseData = {
      status: 'error',
      code: options.code,
      message: options.message
    };
    if (process.env.NODE_ENV !== 'production') {
      responseData.data = options.data || null;
    }
    if (module.exports.listeners('error').length) {
      module.exports.emit('error', responseData);
    }
    return sendResponse(options.code, responseData);
  };

  function validateFailOptions(options) {
    assert(options, 'res.jSend.fail invoked without options');
    var required = {},
      optional = {
        data: ["object", "string"],
        code: "number",
        message: "string",
      },
      err = arg.err(options, required, optional);
    assert(!err, 'res.jSend.fail options validation: ' + err);
  }

  res.jSend.fail = function (options) {
    validateFailOptions(options);
    if (options.code === undefined) {
      options.code = 400;
    }
    var responseData = {
      status: 'fail',
      code: options.code,
      data: options.data,
      message: options.message
    };
    return sendResponse(options.code, responseData);
  };

  return next();
};

// add events
module.exports.__proto__ = new (require('events').EventEmitter)();
<|endoftext|>


<commit_before>/* jshint node: true */
'use strict';

module.exports = {

  name: 'ember-cli-summernote',

  included: function(app) {
    this._super.included(app);

    // <!-- include libraries(jQuery, bootstrap, fontawesome) -->
    app.import(app.bowerDirectory + '/jquery/dist/jquery.min.js');
    app.import(app.bowerDirectory + '/bootstrap/dist/css/bootstrap.min.css');
    app.import(app.bowerDirectory + '/bootstrap/dist/js/bootstrap.min.js');
    app.import(app.bowerDirectory + '/fontawesome/css/font-awesome.min.css');

    // <!-- include summernote css/js-->
    app.import(app.bowerDirectory + '/summernote/dist/summernote.css');
    app.import(app.bowerDirectory + '/summernote/dist/summernote.js');

  }
};
<commit_msg>Implement the included hook in index.js<commit_after>/* jshint node: true */
'use strict';

module.exports = {

  name: 'ember-cli-summernote',

  included: function(app) {
    this._super.included(app);

    // jQuery
    app.import(app.bowerDirectory + '/jquery/dist/jquery.js'); // jquery.min.js is not working...

    // Bootstrap
    app.import(app.bowerDirectory + '/bootstrap/dist/css/bootstrap.min.css');
    app.import(app.bowerDirectory + '/bootstrap/dist/js/bootstrap.min.js');

    // font awesome
    app.import(app.bowerDirectory + '/fontawesome/css/font-awesome.min.css');
    app.import(app.bowerDirectory + '/fontawesome/fonts/fontawesome-webfont.eot', { destDir: 'fonts' });
    app.import(app.bowerDirectory + '/fontawesome/fonts/fontawesome-webfont.svg', { destDir: 'fonts' });
    app.import(app.bowerDirectory + '/fontawesome/fonts/fontawesome-webfont.ttf', { destDir: 'fonts' });
    app.import(app.bowerDirectory + '/fontawesome/fonts/fontawesome-webfont.woff', { destDir: 'fonts' });
    app.import(app.bowerDirectory + '/fontawesome/fonts/FontAwesome.otf', { destDir: 'fonts' });

    // Summernote
    app.import(app.bowerDirectory + '/summernote/dist/summernote.css');
    app.import(app.bowerDirectory + '/summernote/dist/summernote.min.js');

  }
};
<|endoftext|>


<commit_before>'use strict';
const Path = require('path')
const webpack = require('webpack')
const express = require('express')
const app = express()
const self = this

module.exports = function (options) {
  return new Promise((resolve, reject) => {
    const port = options.port || 3001
    const config = options.config || {}
    const compiler = webpack(config)

    const devMiddleWare = require('webpack-dev-middleware')(compiler, Object.assign({}, {
      publicPath: config.output.publicPath,
      stats: {
        colors: true,
        modules: false,
        children: false,
        chunks: false,
        chunkModules: false
      }
    }, options.compiler || {}))

    app.use(self.middleware = devMiddleWare)

    app.use(require('webpack-hot-middleware')(compiler))

    app.get('*', (req, res) => {
      const fs = self.middleware.fileSystem
      self.middleware.waitUntilValid(() => {
        if (options.customIndex) {
          const fp = typeof options.customIndex === 'string'
            ? options.customIndex
            : config.output.path
          const filename = Path.join(fp, options.filename || 'index.html')
          const exists = fs.statSync(filename).isFile()
          if (exists) {
            res.end(fs.readFileSync(filename))
          } else {
            res.end('Refresh when bundle valid...')
          }
        } else {
          res.sendFile(Path.join(__dirname, 'index.html'))
        }
      })
    })

    app.listen(port, 'localhost', err => {
      if (err) {
        return reject(err)
      }
      return resolve(port)
    })
  })
}
<commit_msg>fix the way to check file exists<commit_after>'use strict';
const Path = require('path')
const webpack = require('webpack')
const express = require('express')
const app = express()
const self = this

module.exports = function (options) {
  return new Promise((resolve, reject) => {
    const port = options.port || 3001
    const config = options.config || {}
    const compiler = webpack(config)

    const devMiddleWare = require('webpack-dev-middleware')(compiler, Object.assign({}, {
      publicPath: config.output.publicPath,
      stats: {
        colors: true,
        modules: false,
        children: false,
        chunks: false,
        chunkModules: false
      }
    }, options.compiler || {}))

    const dist = Path.dirname(config.output.path)
    devMiddleWare.fileSystem.mkdirpSync(config.output.path)

    app.use(self.middleware = devMiddleWare)

    app.use(require('webpack-hot-middleware')(compiler))

    app.get('*', (req, res) => {
      const fs = self.middleware.fileSystem
      self.middleware.waitUntilValid(() => {
        if (options.customIndex) {
          const fp = typeof options.customIndex === 'string'
            ? options.customIndex
            : config.output.path
          const filename = options.filename || 'index.html'
          const filepath = Path.join(fp, filename)
          const contents = fs.readdirSync(dist)
          const exists = contents.indexOf(filename) !== -1
          if (exists) {
            res.end(fs.readFileSync(filepath))
          } else {
            res.end('Refresh when bundle is valid...')
          }
        } else {
          res.sendFile(Path.join(__dirname, 'index.html'))
        }
      })
    })

    app.listen(port, 'localhost', err => {
      if (err) {
        return reject(err)
      }
      resolve(port)
    })
  })
}
<|endoftext|>


<commit_before>var NODE_WIDTH = 10;
var PIXI = require('pixi.js');

module.exports = function (graph, settings) {
  var merge = require('ngraph.merge');

  // Initialize default settings:
  settings = merge(settings, {
    // What is the background color of a graph?
    background: 0x000000,

    // Default physics engine settings
    physics: {
      springLength: 30,
      springCoeff: 0.0008,
      dragCoeff: 0.01,
      gravity: -1.2,
      theta: 1
    }
  });

  // Where do we render our graph?
  if (typeof settings.container === 'undefined') {
    settings.container = document.body;
  }

  // If client does not need custom layout algorithm, let's create default one:
  var layout = settings.layout;

  if (!layout) {
    var createLayout = require('ngraph.forcelayout'),
        physics = require('ngraph.physics.simulator');

    layout = createLayout(graph, physics(settings.physics));
  }

  var width = settings.container.clientWidth,
      height = settings.container.clientHeight;

  var stage = new PIXI.Container();
  var renderer = PIXI.autoDetectRenderer(width, height, null, false, true);

  settings.container.appendChild(renderer.view);

  var graphics = new PIXI.Graphics();
  graphics.position.x = width/2;
  graphics.position.y = height/2;
  graphics.scale.x = 1;
  graphics.scale.y = 1;
  stage.addChild(graphics);

  // Default callbacks to build/render nodes
  var nodeUIBuilder = defaultCreateNodeUI,
      nodeRenderer  = defaultNodeRenderer,
      linkUIBuilder = defaultCreateLinkUI,
      linkRenderer  = defaultLinkRenderer;

  // Storage for UI of nodes/links:
  var nodeUI = {}, linkUI = {};

  graph.forEachNode(initNode);
  graph.forEachLink(initLink);

  listenToGraphEvents();

  var pixiGraphics = {
    /**
     * Allows client to start animation loop, without worrying about RAF stuff.
     */
    run: animationLoop,

    /**
     * For more sophisticated clients we expose one frame rendering as part of
     * API. This may be useful for clients who have their own RAF pipeline.
     */
    renderOneFrame: renderOneFrame,

    /**
     * This callback creates new UI for a graph node. This becomes helpful
     * when you want to precalculate some properties, which otherwise could be
     * expensive during rendering frame.
     *
     * @callback createNodeUICallback
     * @param {object} node - graph node for which UI is required.
     * @returns {object} arbitrary object which will be later passed to renderNode
     */
    /**
     * This function allows clients to pass custom node UI creation callback
     *
     * @param {createNodeUICallback} createNodeUICallback - The callback that
     * creates new node UI
     * @returns {object} this for chaining.
     */
    createNodeUI : function (createNodeUICallback) {
      nodeUI = {};
      nodeUIBuilder = createNodeUICallback;
      graph.forEachNode(initNode);
      return this;
    },

    /**
     * This callback is called by pixiGraphics when it wants to render node on
     * a screen.
     *
     * @callback renderNodeCallback
     * @param {object} node - result of createNodeUICallback(). It contains anything
     * you'd need to render a node
     * @param {PIXI.Graphics} ctx - PIXI's rendering context.
     */
    /**
     * Allows clients to pass custom node rendering callback
     *
     * @param {renderNodeCallback} renderNodeCallback - Callback which renders
     * node.
     *
     * @returns {object} this for chaining.
     */
    renderNode: function (renderNodeCallback) {
      nodeRenderer = renderNodeCallback;
      return this;
    },

    /**
     * This callback creates new UI for a graph link. This becomes helpful
     * when you want to precalculate some properties, which otherwise could be
     * expensive during rendering frame.
     *
     * @callback createLinkUICallback
     * @param {object} link - graph link for which UI is required.
     * @returns {object} arbitrary object which will be later passed to renderNode
     */
    /**
     * This function allows clients to pass custom node UI creation callback
     *
     * @param {createLinkUICallback} createLinkUICallback - The callback that
     * creates new link UI
     * @returns {object} this for chaining.
     */
    createLinkUI : function (createLinkUICallback) {
      linkUI = {};
      linkUIBuilder = createLinkUICallback;
      graph.forEachLink(initLink);
      return this;
    },

    /**
     * This callback is called by pixiGraphics when it wants to render link on
     * a screen.
     *
     * @callback renderLinkCallback
     * @param {object} link - result of createLinkUICallback(). It contains anything
     * you'd need to render a link
     * @param {PIXI.Graphics} ctx - PIXI's rendering context.
     */
    /**
     * Allows clients to pass custom link rendering callback
     *
     * @param {renderLinkCallback} renderLinkCallback - Callback which renders
     * link.
     *
     * @returns {object} this for chaining.
     */
    renderLink: function (renderLinkCallback) {
      linkRenderer = renderLinkCallback;
      return this;
    },

    /**
     * Tries to get node at (x, y) graph coordinates. By default renderer assumes
     * width and height of the node is 10 pixels. But if your createNodeUICallback
     * returns object with `width` and `height` attributes, they are considered
     * as actual dimensions of a node
     *
     * @param {Number} x - x coordinate of a node in layout's coordinates
     * @param {Number} y - y coordinate of a node in layout's coordinates
     * @returns {Object} - actual graph node located at (x, y) coordinates.
     * If there is no node in that are `undefined` is returned.
     *
     * TODO: This should be part of layout itself
     */
    getNodeAt: getNodeAt,

    /**
     * [Read only] Current layout algorithm. If you want to pass custom layout
     * algorithm, do it via `settings` argument of ngraph.pixi.
     */
    layout: layout,

    // TODO: These properties seem to only be required of graph input. I'd really
    // like to hide them, but not sure how to do it nicely
    domContainer: renderer.view,
    graphGraphics: graphics,
    stage: stage
  };

  // listen to mouse events
  var graphInput = require('./lib/graphInput');
  graphInput(pixiGraphics, layout);

  return pixiGraphics;

///////////////////////////////////////////////////////////////////////////////
// Public API is over
///////////////////////////////////////////////////////////////////////////////

  function animationLoop() {
    requestAnimationFrame(animationLoop);
    layout.step();
    renderOneFrame();
  }

  function renderOneFrame() {
    graphics.clear();

    Object.keys(linkUI).forEach(renderLink);
    Object.keys(nodeUI).forEach(renderNode);

    renderer.render(stage);
  }

  function renderLink(linkId) {
    linkRenderer(linkUI[linkId], graphics);
  }

  function renderNode(nodeId) {
    nodeRenderer(nodeUI[nodeId], graphics);
  }

  function initNode(node) {
    var ui = nodeUIBuilder(node);
    // augment it with position data:
    ui.pos = layout.getNodePosition(node.id);
    // and store for subsequent use:
    nodeUI[node.id] = ui;
  }

  function initLink(link) {
    var ui = linkUIBuilder(link);
    ui.from = layout.getNodePosition(link.fromId);
    ui.to = layout.getNodePosition(link.toId);
    linkUI[link.id] = ui;
  }

  function defaultCreateNodeUI() {
    return {};
  }

  function defaultCreateLinkUI() {
    return {};
  }

  function defaultNodeRenderer(node) {
    var x = node.pos.x - NODE_WIDTH/2,
        y = node.pos.y - NODE_WIDTH/2;

    graphics.beginFill(0xFF3300);
    graphics.drawRect(x, y, NODE_WIDTH, NODE_WIDTH);
  }

  function defaultLinkRenderer(link) {
    graphics.lineStyle(1, 0xcccccc, 1);
    graphics.moveTo(link.from.x, link.from.y);
    graphics.lineTo(link.to.x, link.to.y);
  }

  function getNodeAt(x, y) {
    var half = NODE_WIDTH/2;
    // currently it's a linear search, but nothing stops us from refactoring
    // this into spatial lookup data structure in future:
    for (var nodeId in nodeUI) {
      if (nodeUI.hasOwnProperty(nodeId)) {
        var node = nodeUI[nodeId];
        var pos = node.pos;
        var width = node.width || NODE_WIDTH;
        half = width/2;
        var insideNode = pos.x - half < x && x < pos.x + half &&
                         pos.y - half < y && y < pos.y + half;

        if (insideNode) {
          return graph.getNode(nodeId);
        }
      }
    }
  }

  function listenToGraphEvents() {
    graph.on('changed', onGraphChanged);
  }

  function onGraphChanged(changes) {
    for (var i = 0; i < changes.length; ++i) {
      var change = changes[i];
      if (change.changeType === 'add') {
        if (change.node) {
          initNode(change.node);
        }
        if (change.link) {
          initLink(change.link);
        }
      } else if (change.changeType === 'remove') {
        if (change.node) {
          delete nodeUI[change.node.id];
        }
        if (change.link) {
          delete linkUI[change.link.id];
        }
      }
    }
  }
};
<commit_msg>Allow passing PixiJS renderer options in settings<commit_after>var NODE_WIDTH = 10;
var PIXI = require('pixi.js');

module.exports = function (graph, settings) {
  var merge = require('ngraph.merge');

  // Initialize default settings:
  settings = merge(settings, {
    // Options for PixiJS renderer
    rendererOptions: {
      backgroundColor: 0x000000
    },
    // Default physics engine settings
    physics: {
      springLength: 30,
      springCoeff: 0.0008,
      dragCoeff: 0.01,
      gravity: -1.2,
      theta: 1
    }
  });

  // Where do we render our graph?
  if (typeof settings.container === 'undefined') {
    settings.container = document.body;
  }

  // If client does not need custom layout algorithm, let's create default one:
  var layout = settings.layout;

  if (!layout) {
    var createLayout = require('ngraph.forcelayout'),
        physics = require('ngraph.physics.simulator');

    layout = createLayout(graph, physics(settings.physics));
  }

  var width = settings.container.clientWidth,
      height = settings.container.clientHeight;

  var stage = new PIXI.Container();
  var renderer = PIXI.autoDetectRenderer(width, height, settings.rendererOptions, false, true);

  settings.container.appendChild(renderer.view);

  var graphics = new PIXI.Graphics();
  graphics.position.x = width/2;
  graphics.position.y = height/2;
  graphics.scale.x = 1;
  graphics.scale.y = 1;
  stage.addChild(graphics);

  // Default callbacks to build/render nodes
  var nodeUIBuilder = defaultCreateNodeUI,
      nodeRenderer  = defaultNodeRenderer,
      linkUIBuilder = defaultCreateLinkUI,
      linkRenderer  = defaultLinkRenderer;

  // Storage for UI of nodes/links:
  var nodeUI = {}, linkUI = {};

  graph.forEachNode(initNode);
  graph.forEachLink(initLink);

  listenToGraphEvents();

  var pixiGraphics = {
    /**
     * Allows client to start animation loop, without worrying about RAF stuff.
     */
    run: animationLoop,

    /**
     * For more sophisticated clients we expose one frame rendering as part of
     * API. This may be useful for clients who have their own RAF pipeline.
     */
    renderOneFrame: renderOneFrame,

    /**
     * This callback creates new UI for a graph node. This becomes helpful
     * when you want to precalculate some properties, which otherwise could be
     * expensive during rendering frame.
     *
     * @callback createNodeUICallback
     * @param {object} node - graph node for which UI is required.
     * @returns {object} arbitrary object which will be later passed to renderNode
     */
    /**
     * This function allows clients to pass custom node UI creation callback
     *
     * @param {createNodeUICallback} createNodeUICallback - The callback that
     * creates new node UI
     * @returns {object} this for chaining.
     */
    createNodeUI : function (createNodeUICallback) {
      nodeUI = {};
      nodeUIBuilder = createNodeUICallback;
      graph.forEachNode(initNode);
      return this;
    },

    /**
     * This callback is called by pixiGraphics when it wants to render node on
     * a screen.
     *
     * @callback renderNodeCallback
     * @param {object} node - result of createNodeUICallback(). It contains anything
     * you'd need to render a node
     * @param {PIXI.Graphics} ctx - PIXI's rendering context.
     */
    /**
     * Allows clients to pass custom node rendering callback
     *
     * @param {renderNodeCallback} renderNodeCallback - Callback which renders
     * node.
     *
     * @returns {object} this for chaining.
     */
    renderNode: function (renderNodeCallback) {
      nodeRenderer = renderNodeCallback;
      return this;
    },

    /**
     * This callback creates new UI for a graph link. This becomes helpful
     * when you want to precalculate some properties, which otherwise could be
     * expensive during rendering frame.
     *
     * @callback createLinkUICallback
     * @param {object} link - graph link for which UI is required.
     * @returns {object} arbitrary object which will be later passed to renderNode
     */
    /**
     * This function allows clients to pass custom node UI creation callback
     *
     * @param {createLinkUICallback} createLinkUICallback - The callback that
     * creates new link UI
     * @returns {object} this for chaining.
     */
    createLinkUI : function (createLinkUICallback) {
      linkUI = {};
      linkUIBuilder = createLinkUICallback;
      graph.forEachLink(initLink);
      return this;
    },

    /**
     * This callback is called by pixiGraphics when it wants to render link on
     * a screen.
     *
     * @callback renderLinkCallback
     * @param {object} link - result of createLinkUICallback(). It contains anything
     * you'd need to render a link
     * @param {PIXI.Graphics} ctx - PIXI's rendering context.
     */
    /**
     * Allows clients to pass custom link rendering callback
     *
     * @param {renderLinkCallback} renderLinkCallback - Callback which renders
     * link.
     *
     * @returns {object} this for chaining.
     */
    renderLink: function (renderLinkCallback) {
      linkRenderer = renderLinkCallback;
      return this;
    },

    /**
     * Tries to get node at (x, y) graph coordinates. By default renderer assumes
     * width and height of the node is 10 pixels. But if your createNodeUICallback
     * returns object with `width` and `height` attributes, they are considered
     * as actual dimensions of a node
     *
     * @param {Number} x - x coordinate of a node in layout's coordinates
     * @param {Number} y - y coordinate of a node in layout's coordinates
     * @returns {Object} - actual graph node located at (x, y) coordinates.
     * If there is no node in that are `undefined` is returned.
     *
     * TODO: This should be part of layout itself
     */
    getNodeAt: getNodeAt,

    /**
     * [Read only] Current layout algorithm. If you want to pass custom layout
     * algorithm, do it via `settings` argument of ngraph.pixi.
     */
    layout: layout,

    // TODO: These properties seem to only be required of graph input. I'd really
    // like to hide them, but not sure how to do it nicely
    domContainer: renderer.view,
    graphGraphics: graphics,
    stage: stage
  };

  // listen to mouse events
  var graphInput = require('./lib/graphInput');
  graphInput(pixiGraphics, layout);

  return pixiGraphics;

///////////////////////////////////////////////////////////////////////////////
// Public API is over
///////////////////////////////////////////////////////////////////////////////

  function animationLoop() {
    requestAnimationFrame(animationLoop);
    layout.step();
    renderOneFrame();
  }

  function renderOneFrame() {
    graphics.clear();

    Object.keys(linkUI).forEach(renderLink);
    Object.keys(nodeUI).forEach(renderNode);

    renderer.render(stage);
  }

  function renderLink(linkId) {
    linkRenderer(linkUI[linkId], graphics);
  }

  function renderNode(nodeId) {
    nodeRenderer(nodeUI[nodeId], graphics);
  }

  function initNode(node) {
    var ui = nodeUIBuilder(node);
    // augment it with position data:
    ui.pos = layout.getNodePosition(node.id);
    // and store for subsequent use:
    nodeUI[node.id] = ui;
  }

  function initLink(link) {
    var ui = linkUIBuilder(link);
    ui.from = layout.getNodePosition(link.fromId);
    ui.to = layout.getNodePosition(link.toId);
    linkUI[link.id] = ui;
  }

  function defaultCreateNodeUI() {
    return {};
  }

  function defaultCreateLinkUI() {
    return {};
  }

  function defaultNodeRenderer(node) {
    var x = node.pos.x - NODE_WIDTH/2,
        y = node.pos.y - NODE_WIDTH/2;

    graphics.beginFill(0xFF3300);
    graphics.drawRect(x, y, NODE_WIDTH, NODE_WIDTH);
  }

  function defaultLinkRenderer(link) {
    graphics.lineStyle(1, 0xcccccc, 1);
    graphics.moveTo(link.from.x, link.from.y);
    graphics.lineTo(link.to.x, link.to.y);
  }

  function getNodeAt(x, y) {
    var half = NODE_WIDTH/2;
    // currently it's a linear search, but nothing stops us from refactoring
    // this into spatial lookup data structure in future:
    for (var nodeId in nodeUI) {
      if (nodeUI.hasOwnProperty(nodeId)) {
        var node = nodeUI[nodeId];
        var pos = node.pos;
        var width = node.width || NODE_WIDTH;
        half = width/2;
        var insideNode = pos.x - half < x && x < pos.x + half &&
                         pos.y - half < y && y < pos.y + half;

        if (insideNode) {
          return graph.getNode(nodeId);
        }
      }
    }
  }

  function listenToGraphEvents() {
    graph.on('changed', onGraphChanged);
  }

  function onGraphChanged(changes) {
    for (var i = 0; i < changes.length; ++i) {
      var change = changes[i];
      if (change.changeType === 'add') {
        if (change.node) {
          initNode(change.node);
        }
        if (change.link) {
          initLink(change.link);
        }
      } else if (change.changeType === 'remove') {
        if (change.node) {
          delete nodeUI[change.node.id];
        }
        if (change.link) {
          delete linkUI[change.link.id];
        }
      }
    }
  }
};
<|endoftext|>


<commit_before>const mocha = require('mocha')
const inherits = require('util').inherits
const sync = require('./sync')
const stats = require('./gasStats.js')
const reqCwd = require('req-cwd')
const sha1 = require('sha1')
const Base = mocha.reporters.Base
const color = Base.color
const log = console.log

// Based on the 'Spec' reporter
function Gas (runner, options) {

  if (!(web3.currentProvider.connection || web3.currentProvider.host)) {
    console.log('the provider use for the test does not support synchronous call but eth-gas-reporter requires it \n falling back on the Spec reporter');
    mocha.reporters.Spec.call(this, runner);
    return;
  }
  Base.call(this, runner);

  const self = this
  let indents = 0
  let n = 0
  let failed = false;
  let startBlock
  let deployStartBlock
  let methodMap
  let deployMap
  let contractNameFromCodeHash;

  // Load config / keep .ethgas.js for backward compatibility
  let config;
  if (options && options.reporterOptions){
    config = options.reporterOptions
  } else {
    config = reqCwd.silent('./.ethgas.js') || {}
  }

  config.src = config.src || 'contracts'; // default contracts folder
  // TODO grab the contract srcpath from truffle / truffle config ?

  // Start getting this data when the reporter loads.
  stats.getGasAndPriceRates(config);

  // ------------------------------------  Helpers -------------------------------------------------
  const indent = () => Array(indents).join('  ')

  const methodAnalytics = (methodMap) => {
    let gasUsed = 0
    const endBlock = sync.blockNumber();

    while (startBlock <= endBlock) {
      let block = sync.getBlockByNumber(startBlock);

      if (block) {
        // Add to running tally for this test
        gasUsed += parseInt(block.gasUsed, 16);

        // Compile per method stats
        methodMap && block.transactions.forEach(tx => {
          const transaction = sync.getTransactionByHash(tx);
          const receipt = sync.getTransactionReceipt(tx);

          // Don't count methods that throw
          const threw = parseInt(receipt.status) === 0 || receipt.status === false;
          if (threw) return

          const code = sync.getCode(transaction.to);
          const hash = sha1(code);

          let contractName = contractNameFromCodeHash[hash];

          // Handle cases where we don't have a deployment record for the contract
          if (!contractName) {
            let key = transaction.input.slice(2, 10);
            let matches = Object.values(methodMap).filter(el => el.key === key);

            if (matches.length === 1) {
              contractName = matches[0].contract;
            }
          }

          const id = stats.getMethodID(contractName, transaction.input)

          if (methodMap[id]) {
            methodMap[id].gasData.push(parseInt(receipt.gasUsed, 16))
            methodMap[id].numberOfCalls++
          }
        })
      }
      startBlock++
    }
    return gasUsed
  }

  const deployAnalytics = (deployMap) => {
    const endBlock = sync.blockNumber();

    while (deployStartBlock <= endBlock) {
      let block = sync.getBlockByNumber(deployStartBlock);

      block && block.transactions.forEach(tx => {
        const receipt = sync.getTransactionReceipt(tx);
        const threw = parseInt(receipt.status) === 0 || receipt.status === false;

        if (receipt.contractAddress && !threw) {
          const transaction = sync.getTransactionByHash(tx)

          const matches = deployMap.filter(contract => {
            return stats.matchBinaries(transaction.input, contract.binary);
          })

          if(matches && matches.length){
            const match = matches.find(item => item.binary !== '0x');

            if (match) {
              // We have to get code that might be linked here in
              // in order to match correctly at the method ids
              const code = sync.getCode(receipt.contractAddress);
              const hash = sha1(code);

              match.gasData.push(parseInt(receipt.gasUsed, 16));
              contractNameFromCodeHash[hash] = match.name;
            }
          }
        }
      })
      deployStartBlock++
    }
  }

  // ------------------------------------  Runners -------------------------------------------------
  runner.on('start', () => {
    ({ methodMap, deployMap, contractNameFromCodeHash } = stats.mapMethodsToContracts(artifacts, config.src))
  })

  runner.on('suite', suite => {
    ++indents
    log(color('suite', '%s%s'), indent(), suite.title)
  })

  runner.on('suite end', () => {
    --indents
    if (indents === 1) {
      log()
    }
  })

  runner.on('pending', test => {
    let fmt = indent() + color('pending', '  - %s')
    log(fmt, test.title)
  })

  runner.on('test', () => { deployStartBlock = sync.blockNumber() })

  runner.on('hook end', () => { startBlock = sync.blockNumber() + 1 })

  runner.on('pass', test => {
    let fmt
    let fmtArgs
    let gasUsedString
    deployAnalytics(deployMap)
    let gasUsed = methodAnalytics(methodMap)
    let showTimeSpent = config.showTimeSpent || false
    let timeSpentString = color(test.speed, '%dms')
    let consumptionString
    if (gasUsed) {
      gasUsedString = color('checkmark', '%d gas')

      if (showTimeSpent) {
        consumptionString = ' (' + timeSpentString + ', ' + gasUsedString + ')'
        fmtArgs = [test.title, test.duration, gasUsed]
      } else {
        consumptionString = ' (' + gasUsedString + ')'
        fmtArgs = [test.title, gasUsed]
      }

      fmt = indent() +
      color('checkmark', '  ' + Base.symbols.ok) +
      color('pass', ' %s') +
      consumptionString
    } else {
      if (showTimeSpent) {
        consumptionString = ' (' + timeSpentString + ')'
        fmtArgs = [test.title, test.duration]
      } else {
        consumptionString = ''
        fmtArgs = [test.title]
      }

      fmt = indent() +
        color('checkmark', '  ' + Base.symbols.ok) +
        color('pass', ' %s') +
        consumptionString
    }
    log.apply(null, [fmt, ...fmtArgs])
  })

  runner.on('fail', test => {
    failed = true;
    let fmt = indent() + color('fail', '  %d) %s')
    log()
    log(fmt, ++n, test.title)
  })

  runner.on('end', () => {
    stats.generateGasStatsReport(methodMap, deployMap, contractNameFromCodeHash)
    self.epilogue()
  });
}

/**
 * Inherit from `Base.prototype`.
 */
inherits(Gas, Base)

module.exports = Gas
<commit_msg>Capture data from proxies<commit_after>const mocha = require('mocha')
const inherits = require('util').inherits
const sync = require('./sync')
const stats = require('./gasStats.js')
const reqCwd = require('req-cwd')
const sha1 = require('sha1')
const Base = mocha.reporters.Base
const color = Base.color
const log = console.log

// Based on the 'Spec' reporter
function Gas (runner, options) {

  if (!(web3.currentProvider.connection || web3.currentProvider.host)) {
    console.log('the provider use for the test does not support synchronous call but eth-gas-reporter requires it \n falling back on the Spec reporter');
    mocha.reporters.Spec.call(this, runner);
    return;
  }
  Base.call(this, runner);

  const self = this
  let indents = 0
  let n = 0
  let failed = false;
  let startBlock
  let deployStartBlock
  let methodMap
  let deployMap
  let contractNameFromCodeHash;

  // Load config / keep .ethgas.js for backward compatibility
  let config;
  if (options && options.reporterOptions){
    config = options.reporterOptions
  } else {
    config = reqCwd.silent('./.ethgas.js') || {}
  }

  config.src = config.src || 'contracts'; // default contracts folder
  // TODO grab the contract srcpath from truffle / truffle config ?

  // Start getting this data when the reporter loads.
  stats.getGasAndPriceRates(config);

  // ------------------------------------  Helpers -------------------------------------------------
  const indent = () => Array(indents).join('  ')

  const methodAnalytics = (methodMap) => {
    let gasUsed = 0
    const endBlock = sync.blockNumber();

    while (startBlock <= endBlock) {
      let block = sync.getBlockByNumber(startBlock);

      if (block) {
        // Add to running tally for this test
        gasUsed += parseInt(block.gasUsed, 16);

        // Compile per method stats
        methodMap && block.transactions.forEach(tx => {
          const transaction = sync.getTransactionByHash(tx);
          const receipt = sync.getTransactionReceipt(tx);

          // Don't count methods that throw
          const threw = parseInt(receipt.status) === 0 || receipt.status === false;
          if (threw) return

          const code = sync.getCode(transaction.to);
          const hash = sha1(code);
          let contractName = contractNameFromCodeHash[hash];

          // Handle cases where we don't have a deployment record for the contract
          // or where we *do* (from migrations) but tx actually interacts with a
          // proxy / something doesn't match.
          let isProxied = false;

          if (contractName) {
            let candidateId = stats.getMethodID(contractName, transaction.input)
            isProxied = !methodMap[candidateId]
          }

          // If unfound, search by fnHash alone instead of contract_fnHash
          if (!contractName || isProxied ) {
            let key = transaction.input.slice(2, 10);
            let matches = Object.values(methodMap).filter(el => el.key === key);

            if (matches.length === 1) {
              contractName = matches[0].contract;
            }
          }

          const id = stats.getMethodID(contractName, transaction.input)

          if (methodMap[id]) {
            methodMap[id].gasData.push(parseInt(receipt.gasUsed, 16))
            methodMap[id].numberOfCalls++
          }
        })
      }
      startBlock++
    }
    return gasUsed
  }

  const deployAnalytics = (deployMap) => {
    const endBlock = sync.blockNumber();

    while (deployStartBlock <= endBlock) {
      let block = sync.getBlockByNumber(deployStartBlock);

      block && block.transactions.forEach(tx => {
        const receipt = sync.getTransactionReceipt(tx);
        const threw = parseInt(receipt.status) === 0 || receipt.status === false;

        if (receipt.contractAddress && !threw) {
          const transaction = sync.getTransactionByHash(tx)

          const matches = deployMap.filter(contract => {
            return stats.matchBinaries(transaction.input, contract.binary);
          })

          if(matches && matches.length){
            const match = matches.find(item => item.binary !== '0x');

            if (match) {
              // We have to get code that might be linked here in
              // in order to match correctly at the method ids
              const code = sync.getCode(receipt.contractAddress);
              const hash = sha1(code);

              match.gasData.push(parseInt(receipt.gasUsed, 16));
              contractNameFromCodeHash[hash] = match.name;
            }
          }
        }
      })
      deployStartBlock++
    }
  }

  // ------------------------------------  Runners -------------------------------------------------
  runner.on('start', () => {
    ({ methodMap, deployMap, contractNameFromCodeHash } = stats.mapMethodsToContracts(artifacts, config.src))
  })

  runner.on('suite', suite => {
    ++indents
    log(color('suite', '%s%s'), indent(), suite.title)
  })

  runner.on('suite end', () => {
    --indents
    if (indents === 1) {
      log()
    }
  })

  runner.on('pending', test => {
    let fmt = indent() + color('pending', '  - %s')
    log(fmt, test.title)
  })

  runner.on('test', () => { deployStartBlock = sync.blockNumber() })

  runner.on('hook end', () => { startBlock = sync.blockNumber() + 1 })

  runner.on('pass', test => {
    let fmt
    let fmtArgs
    let gasUsedString
    deployAnalytics(deployMap)
    let gasUsed = methodAnalytics(methodMap)
    let showTimeSpent = config.showTimeSpent || false
    let timeSpentString = color(test.speed, '%dms')
    let consumptionString
    if (gasUsed) {
      gasUsedString = color('checkmark', '%d gas')

      if (showTimeSpent) {
        consumptionString = ' (' + timeSpentString + ', ' + gasUsedString + ')'
        fmtArgs = [test.title, test.duration, gasUsed]
      } else {
        consumptionString = ' (' + gasUsedString + ')'
        fmtArgs = [test.title, gasUsed]
      }

      fmt = indent() +
      color('checkmark', '  ' + Base.symbols.ok) +
      color('pass', ' %s') +
      consumptionString
    } else {
      if (showTimeSpent) {
        consumptionString = ' (' + timeSpentString + ')'
        fmtArgs = [test.title, test.duration]
      } else {
        consumptionString = ''
        fmtArgs = [test.title]
      }

      fmt = indent() +
        color('checkmark', '  ' + Base.symbols.ok) +
        color('pass', ' %s') +
        consumptionString
    }
    log.apply(null, [fmt, ...fmtArgs])
  })

  runner.on('fail', test => {
    failed = true;
    let fmt = indent() + color('fail', '  %d) %s')
    log()
    log(fmt, ++n, test.title)
  })

  runner.on('end', () => {
    stats.generateGasStatsReport(methodMap, deployMap, contractNameFromCodeHash)
    self.epilogue()
  });
}

/**
 * Inherit from `Base.prototype`.
 */
inherits(Gas, Base)

module.exports = Gas
<|endoftext|>


<commit_before>const Discord = require('discord.js');
const client = new Discord.Client();
const Gamedig = require('gamedig');
const clientID = '***YourID***';
const prefix = '!';
const game = 'arma3',
      host = '***YorServerIP***',
      port = '***YourServerPort***';

client.on('ready', () => {
  console.log(`ArmaBot has started, with ${client.users.size} users, and ${client.channels.size} channels.`)
});

function timeFormat(time) {
  var hrs = ~~(time / 3600);
  var mins = ~~((time % 3600) / 60);
  var secs = Math.round(time % 60);
  var ret = "";
  if (hrs > 1) {
    ret += "" + hrs + " Hrs " + (mins < 10 ? "0" : "");
  } else
  if (hrs > 0) {
    ret += "" + hrs + " Hr " + (mins < 10 ? "0" : "");
  }
  ret += "" + mins + " Mins " + (secs < 10 ? "0" : "");
  ret += "" + secs + " Secs";
  return ret;
};

client.on('message', message => {
  const args = message.content.slice(prefix.length).trim().split(/ +/g);
  const command = args.shift().toLowerCase();

  if (command === 'help') {
    message.channel.send('```' + 'Commands are: \n!info for server info \n!Players for a list of online players \n!stats for info/players \n!search for other server stats expample: !search 45.121.211.65 2302' + '```');
  }

  if (command === 'info') {
    Gamedig.query({
      type: game,
      host: host,
      port: port
    },
    function(err, data) {
      if (err) {
        message.channel.send('```' + 'Server is offline or restarting' + '```');
      } else {
        message.channel.send('```' + 'Server Name: ' + data.name + '\n' + 'Map: ' + data.map + '\n' + 'players online: ' + data.raw.numplayers + '/' + data.maxplayers + '\n' + 'Server Ip/Port: ' + data.query.host + ':' + data.query.port + '```');
      }
    });
  }

  if (command === 'players') {
    Gamedig.query({
      type: game,
      host: host,
      port: port
    },
    function(err, data) {
      if (err) {
        message.channel.send('```' + 'Server is offline or restarting' + '```');
      } else {
        var player = data.players;
        if (player == 0) {
          message.channel.send('There is currently no players on the server :frowning:');
        } else
          message.channel.send('```' + 'Number of players online: ' + data.raw.numplayers + '/' + data.maxplayers + '```');
        for (var i in player) {
          message.channel.send('```' + player[i].name + ' - Score: ' + player[i].score + ' - Time In Game: ' + timeFormat(player[i].time) + '```');
        }
      }
    });
  }

  if (command === 'stats') {
    Gamedig.query({
      type: game,
      host: host,
      port: port
    },
    function(err, data) {
      if (err) {
        message.channel.send('```' + 'Server is offline or restarting' + '```');
      } else {
        message.channel.send('```' + 'Server Name: ' + data.name + '\n' + 'Map: ' + data.map + '\n' + 'players online: ' + data.raw.numplayers + '/' + data.maxplayers + '\n' + 'Server Ip/Port: ' + data.query.host + ':' + data.query.port + '```');
        var player = data.players;
        for (var i in player) {
          console.log(player[i].time);
          message.channel.send('```' + player[i].name + ' - Score: ' + player[i].score + ' - Time In Game: ' + timeFormat(player[i].time) + '```');
        }
      }
    });
  }

  if (command === "search") {
    var ip = args.slice(0, 1).join(' ').toUpperCase();
    var p = args.slice(1, 2).join(' ').toUpperCase();
    if ( !ip && !p || ip && p < 2 ) {
      message.channel.send('Error! make sure the servers ip and port are correct  \nPlease use example ' + '`!search 45.121.211.65 2302`');
    } else
    if ( !p.match(/^\d+$/) ) {
      message.channel.send('Error port is numeric only');
    } else
    Gamedig.query({
      type: game,
      host: ip,
      port: p
    },
    function(err, data) {
      if (err) {
        message.channel.send('```' + 'Server is offline or restarting' + '```');
      } else {
        message.channel.send('```' + 'Server Name: ' + data.name + '\n' + 'Map: ' + data.map + '\n' + 'players online: ' + data.raw.numplayers + '/' + data.maxplayers + '\n' + 'Server Ip/Port: ' + data.query.host + ':' + data.query.port + '```');
      }
    });
  }
});

client.login(clientID);
<commit_msg>[FIX] Better timeFormat & fix indent<commit_after>const Discord = require('discord.js');
const client = new Discord.Client();
const Gamedig = require('gamedig');
const clientID = '***YourID***';
const prefix = '!';
const game = 'arma3',
      host = '***YorServerIP***',
      port = '***YourServerPort***';

client.on('ready', () => {
  console.log(`ArmaBot has started, with ${client.users.size} users, and ${client.channels.size} channels.`)
});

function timeFormat(time) {
  var hrs = ~~(time / 3600);
  var mins = ~~((time % 3600) / 60);
  var secs = Math.round(time % 60);
  var ret = "";
  if (hrs > 1) {
    ret += "" + hrs + " Hrs " + (mins < 10 ? "0" : "");
  } else
  if (hrs > 0) {
    ret += "" + hrs + " Hr " + (mins < 10 ? "0" : "");
  }
  ret += "" + mins + " Mins " + (secs < 10 ? "0" : "");
  ret += "" + secs + " Secs";
  return ret;
};

client.on('message', message => {
  const args = message.content.slice(prefix.length).trim().split(/ +/g);
  const command = args.shift().toLowerCase();

  if (command === 'help') {
    message.channel.send('```' + 'Commands are: \n!info for server info \n!Players for a list of online players \n!stats for info/players \n!search for other server stats expample: !search 45.121.211.65 2302' + '```');
  }

  if (command === 'info') {
    Gamedig.query({
      type: game,
      host: host,
      port: port
    },
    function(err, data) {
      if (err) {
        message.channel.send('```' + 'Server is offline or restarting' + '```');
      } else {
        message.channel.send('```' + 'Server Name: ' + data.name + '\n' + 'Map: ' + data.map + '\n' + 'players online: ' + data.raw.numplayers + '/' + data.maxplayers + '\n' + 'Server Ip/Port: ' + data.query.host + ':' + data.query.port + '```');
      }
    });
  }

  if (command === 'players') {
    Gamedig.query({
      type: game,
      host: host,
      port: port
    },
    function(err, data) {
      if (err) {
        message.channel.send('```' + 'Server is offline or restarting' + '```');
      } else {
        var player = data.players;
        if (player == 0) {
          message.channel.send('There is currently no players on the server :frowning:');
        } else
          message.channel.send('```' + 'Number of players online: ' + data.raw.numplayers + '/' + data.maxplayers + '```');
        for (var i in player) {
          message.channel.send('```' + player[i].name + ' - Score: ' + player[i].score + ' - Time In Game: ' + timeFormat(player[i].time) + '```');
        }
      }
    });
  }

  if (command === 'stats') {
    Gamedig.query({
      type: game,
      host: host,
      port: port
    },
    function(err, data) {
      if (err) {
        message.channel.send('```' + 'Server is offline or restarting' + '```');
      } else {
        message.channel.send('```' + 'Server Name: ' + data.name + '\n' + 'Map: ' + data.map + '\n' + 'players online: ' + data.raw.numplayers + '/' + data.maxplayers + '\n' + 'Server Ip/Port: ' + data.query.host + ':' + data.query.port + '```');
        var player = data.players;
        for (var i in player) {
          message.channel.send('```' + player[i].name + ' - Score: ' + player[i].score + ' - Time In Game: ' + timeFormat(player[i].time) + '```');
        }
      }
    });
  }

  if (command === "search") {
    var ip = args.slice(0, 1).join(' ').toUpperCase();
    var p = args.slice(1, 2).join(' ').toUpperCase();
    if ( !ip && !p || ip && p < 2 ) {
      message.channel.send('Error! make sure the servers ip and port are correct  \nPlease use example ' + '`!search 45.121.211.65 2302`');
    } else
    if ( !p.match(/^\d+$/) ) {
      message.channel.send('Error port is numeric only');
    } else
    Gamedig.query({
      type: game,
      host: ip,
      port: p
    },
    function(err, data) {
      if (err) {
        message.channel.send('```' + 'Server is offline or restarting' + '```');
      } else {
        message.channel.send('```' + 'Server Name: ' + data.name + '\n' + 'Map: ' + data.map + '\n' + 'players online: ' + data.raw.numplayers + '/' + data.maxplayers + '\n' + 'Server Ip/Port: ' + data.query.host + ':' + data.query.port + '```');
      }
    });
  }
});

client.login(clientID);
<|endoftext|>


<commit_before>'use strict';

var util = require('./lib/util');
var primitives = /undefined|null|string|number|boolean|symbol/;

function type(src){

  var that = { };
  var classType = util.getClassType(src);
  that[classType] = src || Boolean(src + '') || ' ';

  // primitives
  if(primitives.test(classType)) {
    if(that.number){
      var strRep = src + '';
      if(parseInt(strRep) === src){
        that.integer = src;
      } else if(/\./.test(strRep)){
        that.float = src;
      } else if(src){
        that.infinity = src;
      } else {
        that.nan = true;
        delete that.number;
      }
    }
    return that;
  }

  // everything else is an object
  var ctorName = (src.constructor.name || classType).toLowerCase();
  if (!that.object) {
    that.object = src;
  } else if(classType !== ctorName){
    that[ctorName] = src;
  } else {
    that.plainObject = src;
    return that;
  }

  // exploit the util.inherits pattern
  var super_ = src.constructor.super_;
  while(super_){
    that[super_.name.toLowerCase()] = src;
    super_ = super_.super_;
  }
  return that;
}

type.match = function typeMatch(src, pattern){
  var types = Object.keys(type(src));
  if(RegExp(pattern).test(types.join(' '))){
    return src || Boolean(src + '') || true;
  }
  return null;
};

exports = module.exports = type;
<commit_msg>ok, its better to return an space, if you want to use it for type checking is consistent and if you are using it to operate you can be sure it was a string, so it is more consistent<commit_after>'use strict';

var util = require('./lib/util');
var primitives = /undefined|null|string|number|boolean|symbol/;

function type(src){

  var that = { };
  var classType = util.getClassType(src);
  that[classType] = src || Boolean(src + '') || ' ';

  // primitives
  if(primitives.test(classType)) {
    if(that.number){
      var strRep = src + '';
      if(parseInt(strRep) === src){
        that.integer = src;
      } else if(/\./.test(strRep)){
        that.float = src;
      } else if(src){
        that.infinity = src;
      } else {
        that.nan = true;
        delete that.number;
      }
    }
    return that;
  }

  // everything else is an object
  var ctorName = (src.constructor.name || classType).toLowerCase();
  if (!that.object) {
    that.object = src;
  } else if(classType !== ctorName){
    that[ctorName] = src;
  } else {
    that.plainObject = src;
    return that;
  }

  // exploit the util.inherits pattern
  var super_ = src.constructor.super_;
  while(super_){
    that[super_.name.toLowerCase()] = src;
    super_ = super_.super_;
  }
  return that;
}

type.match = function typeMatch(src, pattern){
  var types = Object.keys(type(src));
  if(RegExp(pattern).test(types.join(' '))){
    return src || Boolean(src + '') || ' ';
  }
  return null;
};

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


<commit_before>// app start entry:

var
    fs = require('fs'),
    express = require('express'),
    ejs = require('ejs'),
    _ = require('lodash');

// load config:
var
    config = require('./config'),
    api = require('./api'),
    db = require('./db'),
    api_console = require('./api_console');

// init http server:
var app = express();

// set engine to ejs:
app.engine('html', ejs.__express);

// set for production:
if ('production' === app.get('env')) {
    app.enable('trust proxy');
}

// set for development:
if ('development' === app.get('env')) {
    app.use('/static', express.static(__dirname + '/static'));
    app.use('/api/', function(req, res, next) {
        setTimeout(function() {
            next(null);
        }, 250 + Math.floor(Math.random() * 250));
    });
}

app.use(express.cookieParser());

// set upload dir:
var tmp_upload_dir = '/tmp/itranswarp';
if (! fs.existsSync(tmp_upload_dir)) {
    console.log('creating tmp upload dir: ' + tmp_upload_dir);
    fs.mkdirSync(tmp_upload_dir);
}
app.use(express.urlencoded());
app.use(express.json());
app.use(express.multipart({ keepExtensions: true, uploadDir: tmp_upload_dir }));

// set content type: json for api:
app.use('/api/', function(req, res, next) {
    console.log('set api response type: application/json');
    res.type('application/json');
    next();
});

// auto set current user with each request:
app.use(require('./controllers/_utils').userIdentityParser);

// api error handling:
app.use(app.router);
app.use(function(err, req, res, next) {
    if (err instanceof api.APIError) {
        console.log('send api error to client: ' + err.error);
        return res.send(err);
    }
    console.log('ERROR >>> ' + JSON.stringify(err));
    next(err);
});

function load_controller_filenames() {
    var files = require('fs').readdirSync(__dirname + '/controllers');
    var re = new RegExp("^[A-Za-z][A-Za-z0-9\\_]*\\.js$");
    var jss = _.filter(files, function(f) {
        return re.test(f);
    });
    return _.map(jss, function(f) {
        return f.substring(0, f.length - 3);
    });
}

// scan all modules:

function load_controllers() {
    var ctrls = {};
    _.each(load_controller_filenames(), function(filename) {
        ctrls[filename] = require('./controllers/' + filename);
    });
    return ctrls;
}

var controllers = load_controllers();

_.each(controllers, function(ctrl, fname) {
    _.each(ctrl, function(fn, path) {
        var ss = path.split(' ', 2);
        if (ss.length != 2) {
            console.log('ERROR in route definition: ' + path);
            return;
        }
        var verb = ss[0];
        var route = ss[1];
        if (verb=='GET') {
            console.log('found api: GET ' + route + ' in ' + fname + '.js');
            app.get(route, fn);
        }
        else if (verb=='POST') {
            console.log('found api: POST ' + route + ' in ' + fname + '.js');
            app.post(route, fn);
        }
        else {
            console.log('error: Invalid verb: ' + verb);
            return;
        }
        if (route.indexOf('/api/')==0) {
            var docs = fn.toString().match(/.*\/\*\*?([\d\D]*)\*?\*\/.*/);
            if (docs) {
                api_console.process_api_doc(fname, verb, route, docs[1]);
            }
            else {
                console.log('WARNING: no api docs found for api: ' + route);
            }
        }
    });
});

app.get('/error', function(req, res, next) {
    next(new Error('test error.'));
});

app.listen(3000);
console.log('Start app on port 3000...');
<commit_msg>rename refactor<commit_after>// app start entry:

var
    fs = require('fs'),
    express = require('express'),
    ejs = require('ejs'),
    _ = require('lodash');

// load config:
var
    config = require('./config'),
    api = require('./api'),
    db = require('./db'),
    api_console = require('./api_console');

// init http server:
var app = express();

// set engine to ejs:
app.engine('html', ejs.__express);

// set for production:
if ('production' === app.get('env')) {
    app.enable('trust proxy');
}

// set for development:
if ('development' === app.get('env')) {
    app.use('/static', express.static(__dirname + '/static'));
    app.use('/api/', function(req, res, next) {
        setTimeout(function() {
            next(null);
        }, 250 + Math.floor(Math.random() * 250));
    });
}

app.use(express.cookieParser());

// set upload dir:
var tmp_upload_dir = '/tmp/itranswarp';
if (! fs.existsSync(tmp_upload_dir)) {
    console.log('creating tmp upload dir: ' + tmp_upload_dir);
    fs.mkdirSync(tmp_upload_dir);
}
app.use(express.urlencoded());
app.use(express.json());
app.use(express.multipart({ keepExtensions: true, uploadDir: tmp_upload_dir }));

// set content type: json for api:
app.use('/api/', function(req, res, next) {
    console.log('set api response type: application/json');
    res.type('application/json');
    next();
});

// auto set current user with each request:
app.use(require('./controllers/_utils').userIdentityParser);

// api error handling:
app.use(app.router);
app.use(function(err, req, res, next) {
    if (err instanceof api.APIError) {
        console.log('send api error to client: ' + err.error);
        return res.send(err);
    }
    console.log('ERROR >>> ' + JSON.stringify(err));
    next(err);
});

// scan all modules:

function loadControllerFilenames() {
    var files = require('fs').readdirSync(__dirname + '/controllers');
    var re = new RegExp("^[A-Za-z][A-Za-z0-9\\_]*\\.js$");
    var jss = _.filter(files, function(f) {
        return re.test(f);
    });
    return _.map(jss, function(f) {
        return f.substring(0, f.length - 3);
    });
}

function loadControllers() {
    var ctrls = {};
    _.each(loadControllerFilenames(), function(filename) {
        ctrls[filename] = require('./controllers/' + filename);
    });
    return ctrls;
}

var controllers = loadControllers();

_.each(controllers, function(ctrl, fname) {
    _.each(ctrl, function(fn, path) {
        var ss = path.split(' ', 2);
        if (ss.length != 2) {
            console.log('ERROR in route definition: ' + path);
            return;
        }
        var verb = ss[0];
        var route = ss[1];
        if (verb=='GET') {
            console.log('found api: GET ' + route + ' in ' + fname + '.js');
            app.get(route, fn);
        }
        else if (verb=='POST') {
            console.log('found api: POST ' + route + ' in ' + fname + '.js');
            app.post(route, fn);
        }
        else {
            console.log('error: Invalid verb: ' + verb);
            return;
        }
        if (route.indexOf('/api/')==0) {
            var docs = fn.toString().match(/.*\/\*\*?([\d\D]*)\*?\*\/.*/);
            if (docs) {
                api_console.process_api_doc(fname, verb, route, docs[1]);
            }
            else {
                console.log('WARNING: no api docs found for api: ' + route);
            }
        }
    });
});

app.get('/error', function(req, res, next) {
    next(new Error('test error.'));
});

app.listen(3000);
console.log('Start app on port 3000...');
<|endoftext|>


<commit_before>/*
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
 * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

'use strict';

var async = require('async');

function build(dockerSupport, system) {

  var fetchImages = require('./lib/images')(dockerSupport);
  var fetchContainers = require('./lib/containers')(dockerSupport);
  var match = require('./lib/match')(system);

  function dockerAnalyzer(config, result, done) {
    async.eachSeries([
      fetchImages,
      fetchContainers,
      match
    ], function(func, cb) {
      func(config, result, function(err) {
        if (err) { return cb(err); }
        cb(null);
      });
    }, function(err) {
      if (err) { return done(err); }
      done(null, result);
    });
  }

  return dockerAnalyzer;
}

module.exports = build;
<commit_msg>added docker filter handling<commit_after>/*
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
 * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

'use strict';

var async = require('async');
var _ = require('lodash');

function initFilters(config, system) {
  var cnames = _.map(system.containerDefinitions, function(cdef) { return {name: cdef.name, type: cdef.type}; });
  cnames = _.filter(cnames, function(name) { return name.type === 'docker'; });

  config.dockerFilters = config.dockerFilters || [];

  if (system.name) {
    if (!_.find(config.dockerFilters, function(filter) { return filter === system.name; })) {
      config.dockerFilters.push(system.name);
    }
  }

  _.each(cnames, function(name) {
    if (!_.find(config.dockerFilters, function(filter) { return filter === name.name; })) {
      if (system.name && name.name.indexOf(system.name) !== 0) {
        config.dockerFilters.push(name.name);
      }
    }
  });
}

function build(dockerSupport, config, system) {
  var fetchImages = require('./lib/images')(dockerSupport);
  var fetchContainers = require('./lib/containers')(dockerSupport);
  var match = require('./lib/match')(system);

  initFilters(config, system);

  function dockerAnalyzer(config, result, done) {
    async.eachSeries([
      fetchImages,
      fetchContainers,
      match
    ], function(func, cb) {
      func(config, result, function(err) {
        if (err) { return cb(err); }
        cb(null);
      });
    }, function(err) {
      if (err) { return done(err); }
      done(null, result);
    });
  }

  return dockerAnalyzer;
}

module.exports = build;

<|endoftext|>