<commit_before>'use strict';

// #region Imports
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var express = require('express');
var favicon = require('serve-favicon');
var lessMw = require('less-middleware');
var lodash = require('lodash');
var logger = require('morgan');
var path = require('path');
var StaticBuild = require('../../index.js');
// #endregion

var app = module.exports = express();
/** The target instance of StaticBuild. */
var build;
/** View Engine */
var veng = {
  jade: undefined,
  nunjucks: undefined
};

/**
 * Initializes the Express app without running it.
 * @param {StaticBuild} [targetBuild] The target build.
 */
function init(targetBuild) {
  // I'd like intellisense for `build` in the rest of this file, so I added
  // `|| StaticBuild.current` to the next line so I could get it, since VS is
  // not taking the hint from the jsdoc @param type. So, sue me :) targetBuild
  // is always passed, so it never really gets executed. - waynebloss
  // TODO: Remove the `|| StaticBuild.current` when possible.
  build = targetBuild || StaticBuild.current;
  initViewEngines();
  // Request Pipeline
  initFavicon();
  initLogging();
  initParsing();
  initCssLESS();
  initViewRouting();
  initErrorHandling();
}
app.init = init;

function verbose(data) {
  /*jshint unused:false*/
  if (build.verbose)
    console.log.apply(console, arguments);
}

// #region Features

function initFavicon() {
  app.use(favicon(build.resolveSrcPath(build.favicon)));
}

function initLogging() {
  app.use(logger('dev'));
}

function initParsing() {
  app.use(bodyParser.json());
  app.use(bodyParser.urlencoded({ extended: false }));
  app.use(cookieParser());
}

// #endregion

// #region CSS/LESS

function initCssLESS() {
  // Options for less-middleware.
  var opt = {
    debug: false,
    render: {
      compress: false
    }
  };
  var sm;
  if (build.engine.less.map.enabled === true) {
    // Less-middleware passes opt.render data to the less.render function.
    opt.render.sourceMap = sm = {
      sourceMapBasepath: build.sourcedir,
      sourceMapRootpath: '/'
    };
    if (build.engine.less.map.inline === true) {
      // BUG: External map files are still created, even when inline is enabled.
      sm.sourceMapFileInline = true;
      sm.sourceMapLessInline = true;
      sm.sourceMapMapInline = true;
      sm.outputSourceFiles = true;
    } else {
      // HACK: Specifying sourceMapFilename here causes less to put the same
      // sourceMappingURL in every css file, so instead we use a special token
      // and fix the situation during postprocess.css.
      sm.sourceMapFilename = initCssLESS.SOURCEMAP_FILENAME_TOKEN;
      opt.postprocess = {
        css: postprocessCss
      };
    }
  }
  app.use(lessMw(build.sourcedir, opt));
}
initCssLESS.SOURCEMAP_REQUESTPATH_TOKEN = '___req.path___';
initCssLESS.SOURCEMAP_FILENAME_TOKEN = initCssLESS.SOURCEMAP_REQUESTPATH_TOKEN + '.map';

function postprocessCss(css, req) {
  if (css && css.replace)
    css = css.replace(initCssLESS.SOURCEMAP_REQUESTPATH_TOKEN, req.path);
  return css;
}

// #endregion

// #region View Engines

function initViewEngines() {
  var relativePathToViews = path.relative(build.basedir, build.sourcedir);
  verbose('relativePathToViews: ' + relativePathToViews);

  app.set('views', relativePathToViews);
  app.set('view engine', build.engine[build.defaultEngineName].extension);
  app.locals = createViewContext();

  // TODO: Only init Jade and Nunjucks if they're enabled and/or installed.
  // TODO: Add config settings to enable or change the default view engines.
  // CONSIDER: Move jade and nunjucks into npm devDependencies in this project,
  // forcing the end-developer to install jade and/or nunjucks in their own
  // project.
  // TODO: Support other view engines like consolidate.js does, but with the
  // ability to configure them from the staticbuild.json file.

  initJade();
  //initNunjucks();
}

function initJade() {
  veng.jade = require('jade');
  app.engine(build.engine.jade.extension, veng.jade.__express);
}

function initNunjucks() {
  veng.nunjucks = require('nunjucks');
  var options = lodash.cloneDeep(build.engine.nunjucks.options);
  var relativePathToViews = app.get('views');
  options.express = app;
  var nunjucks_env = veng.nunjucks.configure(relativePathToViews, options);
  initNunjucksExtensions(nunjucks_env);
  initNunjucksFilters(nunjucks_env);
  app.engine(build.engine.nunjucks.extension, veng.nunjucks.render);
}

function initNunjucksExtensions(nunjucks_env) {
  var collection = build.engine.nunjucks.extensions;
  if (collection === undefined || collection === null)
    return;
  /*jshint -W089 */
  // https://jslinterrors.com/the-body-of-a-for-in-should-be-wrapped-in-an-if-statement
  for (var name in collection)
    nunjucks_env.addExtension(name, collection[name]);
}

function initNunjucksFilters(nunjucks_env) {
  var collection = build.engine.nunjucks.filters;
  if (collection === undefined || collection === null)
    return;
  /*jshint -W089 */
  // https://jslinterrors.com/the-body-of-a-for-in-should-be-wrapped-in-an-if-statement
  for (var name in collection)
    nunjucks_env.addFilter(name, collection[name]);
}

// #endregion

// #endregion

// TODO: Instead of using res.render, find the files and render with the
// specific view engine because express is not handling multiple engines well.

// #region View Routing

function createViewContext() {
  var context = build.context;
  if (build.autocontext) {
    // Add some stuff to the global context.
    if (build.buildvar)
      context[build.buildvar] = build;
    context.t = build.translate;
    context.tn = build.translateNumeric;
  }
  return context;
}

function normalizeViewPath(viewpath) {
  viewpath = '' + viewpath;

  // Remove the leading (or only) slash.
  if (viewpath.charAt(0) === '/')
    viewpath = viewpath.substr(1, viewpath.length - 1);

  // Remove any trailing slash.
  if (viewpath.charAt(viewpath.length - 1) === '/')
    viewpath = viewpath.substr(0, viewpath.length - 1);

  return viewpath;
}

function initViewRouting() {
  app.use(express.static(build.sourcedir));
  app.get('*', renderView);
}

function renderView(req, res, next) {
  var viewpath = normalizeViewPath(req.path);
  if (viewpath.length === 0)
    viewpath = 'index';
  renderViewAt(viewpath, req, res, next);
}

function renderViewAt(viewpath, req, res, next) {
  res.render(viewpath + '.' + build.engine.jade.extension, function (err, html) {
    if (renderViewCompleted(err, html, viewpath, req, res, next))
      return;
    res.render(viewpath + '.' + build.engine.nunjucks.extension, function (err, html) {
      if (renderViewCompleted(err, html, viewpath, req, res, next))
        return;
      if (path.basename(viewpath) === 'index')
        next();
      else
        renderViewAt(viewpath + '/index', req, res, next);
    });
  });
}

function renderViewCompleted(err, html, viewpath, req, res, next) {
  if (!err) {
    // No error? Great. Send the html and we're done.
    res.send(html);
    return true;
  }
  // 404? Continue trying to render.
  var msg = err.toString();
  if (msg.substr(0, 25) === 'Error: template not found')
    return false;
  // 500. Done.
  next(err);
  return true;
}

// #endregion

// #region Error Handling

var errfile = path.resolve(path.join(__dirname, '../../content/error.jade'));

function initErrorHandling() {
  app.use(error404Handler);
  app.use(errorHandler);
}

function error404Handler(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
}

function errorHandler(err, req, res, next) {
  /*jshint unused:false*/
  var msg = err.toString();
  console.error(msg);
  err.status = err.status || 500;
  res.status(err.status);
  var html = veng.jade.renderFile(errfile, {
    message: msg,
    error: err
  });
  res.send(html);
}

// #endregion
<commit_msg>Multiple view engines working.<commit_after>'use strict';

// #region Imports
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var express = require('express');
var favicon = require('serve-favicon');
var glob = require('glob');
var lessMw = require('less-middleware');
var lodash = require('lodash');
var logger = require('morgan');
var path = require('path');
var StaticBuild = require('../../index.js');
// #endregion

var app = module.exports = express();
/** The target instance of StaticBuild. */
var build;
/** View Engine */
var veng = {
  jade: undefined,
  nunjucks: undefined
};

/**
 * Initializes the Express app without running it.
 * @param {StaticBuild} [targetBuild] The target build.
 */
function init(targetBuild) {
  // I'd like intellisense for `build` in the rest of this file, so I added
  // `|| StaticBuild.current` to the next line so I could get it, since VS is
  // not taking the hint from the jsdoc @param type. So, sue me :) targetBuild
  // is always passed, so it never really gets executed. - waynebloss
  // TODO: Remove the `|| StaticBuild.current` when possible.
  build = targetBuild || StaticBuild.current;
  initViewEngines();
  // Request Pipeline
  initFavicon();
  initLogging();
  initParsing();
  initCssLESS();
  initViewRouting();
  initErrorHandling();
}
app.init = init;

function verbose(data) {
  /*jshint unused:false*/
  if (build.verbose)
    console.log.apply(console, arguments);
}

// #region Features

function initFavicon() {
  app.use(favicon(build.resolveSrcPath(build.favicon)));
}

function initLogging() {
  app.use(logger('dev'));
}

function initParsing() {
  app.use(bodyParser.json());
  app.use(bodyParser.urlencoded({ extended: false }));
  app.use(cookieParser());
}

// #endregion

// #region CSS/LESS

function initCssLESS() {
  // Options for less-middleware.
  var opt = {
    debug: false,
    render: {
      compress: false
    }
  };
  var sm;
  if (build.engine.less.map.enabled === true) {
    // Less-middleware passes opt.render data to the less.render function.
    opt.render.sourceMap = sm = {
      sourceMapBasepath: build.sourcedir,
      sourceMapRootpath: '/'
    };
    if (build.engine.less.map.inline === true) {
      // BUG: External map files are still created, even when inline is enabled.
      sm.sourceMapFileInline = true;
      sm.sourceMapLessInline = true;
      sm.sourceMapMapInline = true;
      sm.outputSourceFiles = true;
    } else {
      // HACK: Specifying sourceMapFilename here causes less to put the same
      // sourceMappingURL in every css file, so instead we use a special token
      // and fix the situation during postprocess.css.
      sm.sourceMapFilename = initCssLESS.SOURCEMAP_FILENAME_TOKEN;
      opt.postprocess = {
        css: postprocessCss
      };
    }
  }
  app.use(lessMw(build.sourcedir, opt));
}
initCssLESS.SOURCEMAP_REQUESTPATH_TOKEN = '___req.path___';
initCssLESS.SOURCEMAP_FILENAME_TOKEN = initCssLESS.SOURCEMAP_REQUESTPATH_TOKEN + '.map';

function postprocessCss(css, req) {
  if (css && css.replace)
    css = css.replace(initCssLESS.SOURCEMAP_REQUESTPATH_TOKEN, req.path);
  return css;
}

// #endregion

// #region View Engines

function initViewEngines() {
  var relativePathToViews = path.relative(build.basedir, build.sourcedir);
  verbose('relativePathToViews: ' + relativePathToViews);

  app.set('views', relativePathToViews);
  //app.set('view engine', build.engine[build.defaultEngineName].extension);
  app.locals = createViewContext();

  // TODO: Only init Jade and Nunjucks if they're enabled and/or installed.
  // TODO: Add config settings to enable or change the default view engines.
  // CONSIDER: Move jade and nunjucks into npm devDependencies in this project,
  // forcing the end-developer to install jade and/or nunjucks in their own
  // project.
  // TODO: Support other view engines like consolidate.js does, but with the
  // ability to configure them from the staticbuild.json file.

  initJade();
  initNunjucks();
}

function initJade() {
  veng.jade = require('jade');
  // TODO: Configure jade `pretty` somewhere else as soon as possible,
  // because polluting locals data is a really bad idea IMO
  // see https://github.com/jadejs/jade/issues/2026
  if (build.engine.jade.options.pretty) {
    app.locals.pretty = true;
  }
  //app.engine(build.engine.jade.extension, veng.jade.__express);
}

function initNunjucks() {
  veng.nunjucks = require('nunjucks');
  var options = lodash.cloneDeep(build.engine.nunjucks.options);
  var relativePathToViews = app.get('views');
  options.express = app;
  var nunjucks_env = veng.nunjucks.configure(relativePathToViews, options);
  initNunjucksExtensions(nunjucks_env);
  initNunjucksFilters(nunjucks_env);
  //app.engine(build.engine.nunjucks.extension, veng.nunjucks.render);
}

function initNunjucksExtensions(nunjucks_env) {
  var collection = build.engine.nunjucks.extensions;
  if (collection === undefined || collection === null)
    return;
  /*jshint -W089 */
  // https://jslinterrors.com/the-body-of-a-for-in-should-be-wrapped-in-an-if-statement
  for (var name in collection)
    nunjucks_env.addExtension(name, collection[name]);
}

function initNunjucksFilters(nunjucks_env) {
  var collection = build.engine.nunjucks.filters;
  if (collection === undefined || collection === null)
    return;
  /*jshint -W089 */
  // https://jslinterrors.com/the-body-of-a-for-in-should-be-wrapped-in-an-if-statement
  for (var name in collection)
    nunjucks_env.addFilter(name, collection[name]);
}

// #endregion

// #endregion

// TODO: Instead of using res.render, find the files and render with the
// specific view engine because express is not handling multiple engines well.

// #region View Routing

function createViewContext() {
  var context = build.context;
  if (build.autocontext) {
    // Add some stuff to the global context.
    if (build.buildvar)
      context[build.buildvar] = build;
    context.t = build.translate;
    context.tn = build.translateNumeric;
  }
  return context;
}

// TODO: Make this function async.
// TODO: Generate pattern file extensions from list of configured engines.
function findView(req) {
  var viewpath = normalizeRequestPath(req.path, 'index');
  // This pattern finds all possible view files.
  var pattern = viewpath + '{/index.,.}+(jade|htm)';
  //
  // See https://github.com/isaacs/node-glob#glob-primer
  // (For the following examples to work, the files must exist.)
  //
  // Given a sourcedir of '/x/y/z' and a viewpath of 'hello':
  // > glob.sync('hello{/index.,.}+(jade|htm)', {cwd: sourcedir, nodir: true});
  // ['hello.jade', 'hello/index.jade']
  //
  // If the viewpath equals the word 'index':
  // > glob.sync('index{/index.,.}+(jade|htm)', {cwd: sourcedir, nodir: true});
  // ['index.htm', 'index.jade']
  //
  // If the viewpath is a directory like 'hello/goodbye':
  // > glob.sync('hello/goodbye{/index.,.}+(jade|htm)', {cwd: sourcedir, nodir: true});
  // ['hello/goodbye.jade', 'hello/goodbye/index.jade']
  //
  verbose('Finding views in: ', build.sourcedir, ' with pattern: ', pattern);
  var files = glob.sync(pattern, {
    cwd: build.sourcedir,
    nodir: true
  });
  if (files.length === 0)
    return false;
  req.viewpath = path.join(build.sourcedir, files[0]);
  console.log('Found view: ' + req.viewpath);
  return true;
}

function initViewRouting() {
  app.use(express.static(build.sourcedir));
  app.get('*', renderView);
}

function normalizeRequestPath(reqpath, defaultIfBlank) {
  reqpath = '' + reqpath;

  // Remove the leading (or only) slash.
  if (reqpath.charAt(0) === '/')
    reqpath = reqpath.substr(1, reqpath.length - 1);

  // Remove any trailing slash.
  if (reqpath.charAt(reqpath.length - 1) === '/')
    reqpath = reqpath.substr(0, reqpath.length - 1);

  if (reqpath.length === 0)
    return defaultIfBlank;

  return reqpath;
}

function renderView(req, res, next) {
  if (!findView(req))
    return next();
  var ext = path.extname(req.viewpath).toLowerCase();
  if (ext === '.jade') {
    veng.jade.renderFile(req.viewpath, app.locals, function (err, html) {
      if (!err)
        return res.send(html);
      return next(err);
    });
  } else if (ext === '.htm') {
    veng.nunjucks.render(req.viewpath, app.locals, function (err, html) {
      if (!err)
        return res.send(html);
      return next(err);
    });
  }
}

// #endregion

// #region Error Handling

var errfile = path.resolve(path.join(__dirname, '../../content/error.jade'));

function initErrorHandling() {
  app.use(error404Handler);
  app.use(errorHandler);
}

function error404Handler(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
}

function errorHandler(err, req, res, next) {
  /*jshint unused:false*/
  var msg = err.toString();
  console.error(msg);
  err.status = err.status || 500;
  res.status(err.status);
  var html = veng.jade.renderFile(errfile, {
    message: msg,
    error: err
  });
  res.send(html);
}

// #endregion
<|endoftext|>


<commit_before>// @flow

import type { ASTNode } from '../src/parser.js';
import {
  throwEmptyListError,
  throwEmptyApplicationError,
} from './errors';

const firstChildType =
  (node: ASTNode): string => node.children[0].body.type;

const isApplication =
  (node: ASTNode): boolean => firstChildType(node) !== 'VAR_DEC' && firstChildType(node) !== 'LAMBDA_DEC';

export const toJS = (node: ASTNode): ?string => {
  switch (node.body.type) {
  case 'PROGRAM':
    return node.children.map(toJS).join(';\n') + ';';
  case 'VAR_DEC':
    return `const ${node.body.name} = ${node.children.map(toJS).join('')}`;
  case 'LAMBDA_DEC':
    return `(${node.body.input} => ${node.children.map(toJS).join('')})`;
  case 'ATOM':
    return node.body.name;
  case 'LIST':
    if (node.children.length === 0) {
      throwEmptyListError();
    }
    if (isApplication(node)) {
      if (node.children.length < 2) {
        throwEmptyApplicationError();
      }
      const namedLambdaNode = node.children[0];
      const lambdaArgumentNode = node.children[1];
      return `${toJS(namedLambdaNode)}(${toJS(lambdaArgumentNode)})`;
    }
    return node.children.map(toJS).join('');
  }
};

const varMap = {};
export const toPointFreeJS = (node: ASTNode): ?string => {
  switch (node.body.type) {
  case 'PROGRAM':
    return node.children.map(toPointFreeJS).join('');
  case 'VAR_DEC':
    varMap[node.body.name] = node.children.map(toPointFreeJS).join('');
    return
  case 'LAMBDA_DEC':
    return `(${node.body.input} => ${node.children.map(toPointFreeJS).join('')})`;
  case 'ATOM':
    return varMap[node.body.name] || node.body.name;
  case 'LIST':
    if (node.children.length === 0) {
      throwEmptyListError();
    }
    if (isApplication(node)) {
      if (node.children.length < 2) {
        throwEmptyApplicationError();
      }
      const namedLambdaNode = node.children[0];
      const lambdaArgumentNode = node.children[1];
      return `${toPointFreeJS(namedLambdaNode)}(${toPointFreeJS(lambdaArgumentNode)})`;
    }
    return node.children.map(toPointFreeJS).join('');
  }
};

const churchVarMap = {};
export const toChurchNotation = (node: ASTNode): ?string => {
  switch (node.body.type) {
  case 'PROGRAM':
    return node.children.map(toChurchNotation).join('');
  case 'VAR_DEC':
    churchVarMap[node.body.name] = node.children.map(toChurchNotation).join('');
    return;
  case 'LAMBDA_DEC':
    return `(lambda ${node.body.input}.${node.children.map(toChurchNotation).join('')})`;
  case 'ATOM':
    return churchVarMap[node.body.name] || node.body.name;
  case 'LIST':
    if (node.children.length === 0) {
      throwEmptyListError();
    }
    if (isApplication(node)) {
      if (node.children.length < 2) {
        throwEmptyApplicationError();
      }
      const namedLambdaNode = node.children[0];
      const lambdaArgumentNode = node.children[1];
      return `(${toChurchNotation(namedLambdaNode)} (${toChurchNotation(lambdaArgumentNode)}))`;
    }
    return node.children.map(toChurchNotation).join('');
  }
}
<commit_msg>missing SC<commit_after>// @flow

import type { ASTNode } from '../src/parser.js';
import {
  throwEmptyListError,
  throwEmptyApplicationError,
} from './errors';

const firstChildType =
  (node: ASTNode): string => node.children[0].body.type;

const isApplication =
  (node: ASTNode): boolean => firstChildType(node) !== 'VAR_DEC' && firstChildType(node) !== 'LAMBDA_DEC';

export const toJS = (node: ASTNode): ?string => {
  switch (node.body.type) {
  case 'PROGRAM':
    return node.children.map(toJS).join(';\n') + ';';
  case 'VAR_DEC':
    return `const ${node.body.name} = ${node.children.map(toJS).join('')}`;
  case 'LAMBDA_DEC':
    return `(${node.body.input} => ${node.children.map(toJS).join('')})`;
  case 'ATOM':
    return node.body.name;
  case 'LIST':
    if (node.children.length === 0) {
      throwEmptyListError();
    }
    if (isApplication(node)) {
      if (node.children.length < 2) {
        throwEmptyApplicationError();
      }
      const namedLambdaNode = node.children[0];
      const lambdaArgumentNode = node.children[1];
      return `${toJS(namedLambdaNode)}(${toJS(lambdaArgumentNode)})`;
    }
    return node.children.map(toJS).join('');
  }
};

const varMap = {};
export const toPointFreeJS = (node: ASTNode): ?string => {
  switch (node.body.type) {
  case 'PROGRAM':
    return node.children.map(toPointFreeJS).join('');
  case 'VAR_DEC':
    varMap[node.body.name] = node.children.map(toPointFreeJS).join('');
    return;
  case 'LAMBDA_DEC':
    return `(${node.body.input} => ${node.children.map(toPointFreeJS).join('')})`;
  case 'ATOM':
    return varMap[node.body.name] || node.body.name;
  case 'LIST':
    if (node.children.length === 0) {
      throwEmptyListError();
    }
    if (isApplication(node)) {
      if (node.children.length < 2) {
        throwEmptyApplicationError();
      }
      const namedLambdaNode = node.children[0];
      const lambdaArgumentNode = node.children[1];
      return `${toPointFreeJS(namedLambdaNode)}(${toPointFreeJS(lambdaArgumentNode)})`;
    }
    return node.children.map(toPointFreeJS).join('');
  }
};

const churchVarMap = {};
export const toChurchNotation = (node: ASTNode): ?string => {
  switch (node.body.type) {
  case 'PROGRAM':
    return node.children.map(toChurchNotation).join('');
  case 'VAR_DEC':
    churchVarMap[node.body.name] = node.children.map(toChurchNotation).join('');
    return;
  case 'LAMBDA_DEC':
    return `(lambda ${node.body.input}.${node.children.map(toChurchNotation).join('')})`;
  case 'ATOM':
    return churchVarMap[node.body.name] || node.body.name;
  case 'LIST':
    if (node.children.length === 0) {
      throwEmptyListError();
    }
    if (isApplication(node)) {
      if (node.children.length < 2) {
        throwEmptyApplicationError();
      }
      const namedLambdaNode = node.children[0];
      const lambdaArgumentNode = node.children[1];
      return `(${toChurchNotation(namedLambdaNode)} (${toChurchNotation(lambdaArgumentNode)}))`;
    }
    return node.children.map(toChurchNotation).join('');
  }
};
<|endoftext|>


<commit_before>'use strict';

var util = require('./util.js'),
    extend = require('xtend'),
    componentCode = [],
    componentsByName = {},
    templateCode = [],
    templatesByName = {},
    systemCode = [],
    gameName = '',
    psykickVersion = 'psykick';

/**
 * Generates a filename based on the class name given
 * @param {string} className
 * @returns {string}
 */
function generateFileName(className) {
    return className
        .replace(/component/gi, '')
        .replace(/system/gi, '')
        .replace(/^[A-Z]/, function(c) {
            return c.toLowerCase();
        })
        .replace(/[A-Z]/g, function(c) {
            return '-' + c.toLowerCase();
        }) + '.js';
}

/**
 * Compile the components/templates/systems from the AST
 * @param ast
 * @param usingPsykick3D
 */
function compile(ast, usingPsykick3D) {
    if (usingPsykick3D) {
        psykickVersion = 'psykick3d';
    }

    gameName = ast.name;
    componentCode = generateComponents(ast.components);
    templateCode = generateTemplates(ast.templates);
    //systemCode = generateSystems(ast.systems);
    //console.log(JSON.stringify(ast, null, 4));

    templateCode.forEach(function(tmpl) {
        console.log(tmpl.code + ',');
    });
}

function generateComponents(components) {
    var code = [];

    for (var i = 0, len = components.length; i < len; i++) {
        var component = components[i],
            constructorCode = [],
            initCode = util.generateInitializerCode(component.properties);

        componentsByName[component.name] = component.properties;

        constructorCode.push(util.generateRequireStatements([
            {
                name: 'Component',
                baseModule: psykickVersion,
                moduleAttribute: 'Component'
            },
            {
                name: 'Helper',
                baseModule: psykickVersion,
                moduleAttribute: 'Helper'
            }
        ]) + '\n');
        constructorCode.push('var ' + component.name + ' = function(options) {');
        constructorCode.push(initCode);
        constructorCode.push('};');
        constructorCode.push('\n' + util.generateInheritanceCode(component.name, 'Component'));
        constructorCode.push('\n' + util.generateExportsCode(component.name));

        code.push({
            name: component.name,
            filename: generateFileName(component.name),
            code: constructorCode.join('\n')
        });

    }

    return code;
}

function generateTemplates(templates) {
    var code = [],
        requiredComponents = {};

    for (var i = 0, len = templates.length; i < len; i++) {
        var template = templates[i],
            tmplFunctionCode = ['\tcreate' + template.name + ': function() {'],
            components = template.components,
            storedTemplate = {};

        // Store the templates components for easy access and "inheritance"
        for (var j = 0, numOfComponents = components.length; j < numOfComponents; j++) {
            var component = components[j];
            storedTemplate[component.name] = {
                type: 'ObjectLiteral',
                properties: component.properties
            };
        }

        if (template.parent !== null) {
            var parentTemplate = templatesByName[template.parent];
            if (!parentTemplate) {
                throw new SyntaxError('Template parent \'' + template.parent + '\' not defined');
            }

            storedTemplate = extend(parentTemplate, storedTemplate);
        }

        templatesByName[template.name] = storedTemplate;

        tmplFunctionCode.push('\t\tvar entity = World.createEntity();');
        for (var componentName in storedTemplate) {
            requiredComponents[componentName] = generateFileName(componentName);
            tmplFunctionCode.push('\t\t' +
                'entity.addComponent(new ' + componentName +
                    '(' + util.formatValue(storedTemplate[componentName], 3) + ');'
                );
        }
        tmplFunctionCode.push('\t\treturn entity;');
        tmplFunctionCode.push('\t}');
        code.push({
            name: template.name,
            code: tmplFunctionCode.join('\n')
        });
    }

    return code;
}

function generateSystems(systems) {

}

module.exports = {
    compile: compile,
    getComponents: function() {
        return componentCode.slice(0);
    },
    getTemplates: function() {
        return templateCode.slice(0);
    },
    getSystems: function() {
        return systemCode.slice(0);
    }
};

/**
 * @name AST
 * @type {{
 *  type: string,
 *  components: Component[],
 *  templates: Template[],
 *  systems: System[]
 * }}
 */

/**
 * @name Component
 * @type {{
 *  name: string,
 *  properties: ComponentProperty[]
 * }}
 */

/**
 * @name ComponentProperty
 * @type {{
 *  name: string,
 *  value: ValueNode
 * }}
 */

/**
 * @name Template
 * @type {{
 *  name: string,
 *  parent: ?string,
 *  components: Component[]
 * }}
 */

/**
 * @name System
 * @type {{
 *  name: string,
 *  parent: ?string,
 *  properties: ComponentList|EntityList
 * }}
 */

/**
 * @name ComponentList
 * @type {{
 *  type: "ComponentList",
 *  components: string[]
 * }}
 */

/**
 * @name EntityList
 * @type {{
 *  type: "EntityList",
 *  entities: string[]
 * }}
 */<commit_msg>Created basic system code generation<commit_after>'use strict';

var util = require('./util.js'),
    extend = require('xtend'),
    componentCode = [],
    componentsByName = {},
    templateCode = [],
    templatesByName = {},
    systemCode = [],
    gameName = '',
    psykickVersion = 'psykick';

/**
 * Generates a filename based on the class name given
 * @param {string} className
 * @returns {string}
 */
function generateFileName(className) {
    return className
        .replace(/component/gi, '')
        .replace(/system/gi, '')
        .replace(/^[A-Z]/, function(c) {
            return c.toLowerCase();
        })
        .replace(/[A-Z]/g, function(c) {
            return '-' + c.toLowerCase();
        }) + '.js';
}

/**
 * Compile the components/templates/systems from the AST
 * @param ast
 * @param usingPsykick3D
 */
function compile(ast, usingPsykick3D) {
    if (usingPsykick3D) {
        psykickVersion = 'psykick3d';
    }

    gameName = ast.name;
    componentCode = generateComponents(ast.components);
    templateCode = generateTemplates(ast.templates);
    systemCode = generateSystems(ast.systems);
    //console.log(JSON.stringify(ast, null, 4));
}

function generateComponents(components) {
    var code = [];

    for (var i = 0, len = components.length; i < len; i++) {
        var component = components[i],
            constructorCode = [],
            initCode = util.generateInitializerCode(component.properties);

        componentsByName[component.name] = component.properties;

        constructorCode.push(util.generateRequireStatements([
            {
                name: 'Component',
                baseModule: psykickVersion,
                moduleAttribute: 'Component'
            },
            {
                name: 'Helper',
                baseModule: psykickVersion,
                moduleAttribute: 'Helper'
            }
        ]) + '\n');
        constructorCode.push('var ' + component.name + ' = function(options) {');
        constructorCode.push(initCode);
        constructorCode.push('};');
        constructorCode.push('\n' + util.generateInheritanceCode(component.name, 'Component'));
        constructorCode.push('\n' + util.generateExportsCode(component.name));

        code.push({
            name: component.name,
            filename: generateFileName(component.name),
            code: constructorCode.join('\n')
        });

    }

    return code;
}

function generateTemplates(templates) {
    var code = [],
        requiredComponents = {};

    for (var i = 0, len = templates.length; i < len; i++) {
        var template = templates[i],
            tmplFunctionCode = ['\tcreate' + template.name + ': function() {'],
            components = template.components,
            storedTemplate = {};

        // Store the templates components for easy access and "inheritance"
        for (var j = 0, numOfComponents = components.length; j < numOfComponents; j++) {
            var component = components[j];
            storedTemplate[component.name] = {
                type: 'ObjectLiteral',
                properties: component.properties
            };
        }

        if (template.parent !== null) {
            var parentTemplate = templatesByName[template.parent];
            if (!parentTemplate) {
                throw new SyntaxError('Template parent \'' + template.parent + '\' not defined');
            }

            storedTemplate = extend(parentTemplate, storedTemplate);
        }

        templatesByName[template.name] = storedTemplate;

        tmplFunctionCode.push('\t\tvar entity = World.createEntity();');
        for (var componentName in storedTemplate) {
            requiredComponents[componentName] = generateFileName(componentName);
            tmplFunctionCode.push('\t\t' +
                'entity.addComponent(new ' + componentName +
                    '(' + util.formatValue(storedTemplate[componentName], 3) + ');'
                );
        }
        tmplFunctionCode.push('\t\treturn entity;');
        tmplFunctionCode.push('\t}');
        code.push({
            name: template.name,
            code: tmplFunctionCode.join('\n')
        });
    }

    return code;
}

function generateSystems(systems) {
    var code = [];

    for (var i = 0, len = systems.length; i < len; i++) {
        var system = systems[i],
            requiredModuleCode = [],
            systemCode = ['var ' + system.name + ' = function() {'],
            requiredComponents = [],
            inheritanceCode = [];

        if (psykickVersion === 'psykick3d') {
            requiredModuleCode.push(util.generateRequireStatements([
                {
                    name: 'System',
                    baseModule: 'psykick3d',
                    moduleAttribute: 'System'
                }
            ]));
            inheritanceCode.push(util.generateInheritanceCode(system.name, 'System'));

            if (system.parent !== null) {
                console.warn('Ignoring system inheritance on \'' + system.name + '\'');
            }
        } else if (system.parent !== null) {
            switch (system.parent) {
                case 'RenderSystem':
                    requiredModuleCode.push(util.generateRequireStatements([
                        {
                            name: 'RenderSystem',
                            baseModule: 'psykick',
                            moduleAttribute: 'RenderSystem'
                        }
                    ]));
                    inheritanceCode.push(util.generateInheritanceCode(system.name, 'RenderSystem'));
                    break;

                case 'BehaviorSystem':
                    requiredModuleCode.push(util.generateRequireStatements([
                        {
                            name: 'BehaviorSystem',
                            baseModule: 'psykick',
                            moduleAttribute: 'BehaviorSystem'
                        }
                    ]));
                    inheritanceCode.push(util.generateInheritanceCode(system.name, 'BehaviorSystem'));
                    break;

                default:
                    throw new SyntaxError('Expected \'RenderSystem\' or \'BehaviorSystem\' but got \'' +
                            system.parent + '\'');
            }
        } else {
            throw new SyntaxError('System \'' + system.name + '\' not specified as RenderSystem or BehaviorSystem');
        }

        // Only adds on \n when we join it all at the end
        requiredModuleCode.push('');
        inheritanceCode.push('');

        if (system.properties.type === 'ComponentList') {
            requiredComponents = system.properties.components;
        } else {
            var templates = system.properties.entities;
            for (var j = 0, numOfTmpls = templates.length; j < numOfTmpls; j++) {
                var templateName = templates[j];
                for (var componentName in templatesByName[templateName]) {
                    if (requiredComponents.indexOf(componentName) === -1) {
                        requiredComponents.push(componentName);
                    }
                }
            }
        }

        if (requiredComponents.length === 0) {
            throw new SyntaxError('System \'' + system.name +'\' does not have required components or entities');
        }

        systemCode.push('\tthis.requiredComponents =[');
        for (var j = 0, numOfComponents = requiredComponents.length; j < numOfComponents; j++) {
            var separator = (j < numOfComponents - 1) ? '\',' : '\'';
            systemCode.push('\t\t\'' + requiredComponents[j] + separator);
        }
        systemCode.push('\t];');
        systemCode.push('};\n');

        var exportCode = [util.generateExportsCode(system.name)];

        code.push({
            name: system.name,
            code: requiredModuleCode.concat(systemCode).concat(inheritanceCode).concat(exportCode).join('\n')
        });
    }

    code.forEach(function(val) {
        console.log(val.code);
    });

    return code;
}

module.exports = {
    compile: compile,
    getComponents: function() {
        return componentCode.slice(0);
    },
    getTemplates: function() {
        return templateCode.slice(0);
    },
    getSystems: function() {
        return systemCode.slice(0);
    }
};

/**
 * @name AST
 * @type {{
 *  type: string,
 *  components: Component[],
 *  templates: Template[],
 *  systems: System[]
 * }}
 */

/**
 * @name Component
 * @type {{
 *  name: string,
 *  properties: ComponentProperty[]
 * }}
 */

/**
 * @name ComponentProperty
 * @type {{
 *  name: string,
 *  value: ValueNode
 * }}
 */

/**
 * @name Template
 * @type {{
 *  name: string,
 *  parent: ?string,
 *  components: Component[]
 * }}
 */

/**
 * @name System
 * @type {{
 *  name: string,
 *  parent: ?string,
 *  properties: ComponentList|EntityList
 * }}
 */

/**
 * @name ComponentList
 * @type {{
 *  type: "ComponentList",
 *  components: string[]
 * }}
 */

/**
 * @name EntityList
 * @type {{
 *  type: "EntityList",
 *  entities: string[]
 * }}
 */<|endoftext|>


<commit_before>// Copyright (c) 2015 Uber Technologies, Inc.

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

'use strict';

var parseArgs = require('minimist');
var process = require('process');
var assert = require('assert');
var path = require('path');
var StaticConfig = require('static-config');

var HyperbahnApplication = require('../app.js');

function HyperbahnWorker(opts) {
    /*eslint max-statements: [2, 25]*/
    if (!(this instanceof HyperbahnWorker)) {
        return new HyperbahnWorker(opts);
    }

    var self = this;

    assert(opts.serverPort, 'serverPort required');
    assert(opts.serverServiceName, 'serverServiceName required');
    assert(opts.instances, 'instances required');
    assert(opts.workerPort, 'workerPort required');

    assert(opts.sentryPort, 'sentryPort required');
    assert(opts.kafkaPort, 'kafkaPort required');

    self.statsdPort = Number(opts.statsdPort);
    self.kafkaPort = Number(opts.kafkaPort);
    self.sentryPort = Number(opts.sentryPort);
    self.config = self.createConfig();
    self.app = HyperbahnApplication(self.config, {
        processTitle: process.title,
        argv: {
            port: Number(opts.workerPort)
        }
    });

    self.instances = Number(opts.instances);
    self.serverServiceName = opts.serverServiceName;
    self.serverPort = Number(opts.serverPort);
}

HyperbahnWorker.prototype.start = function start() {
    var self = this;

    // attach before throwing exception
    process.on('uncaughtException', self.app.clients.onError);

    self.app.bootstrapAndListen(onAppReady);

    function onAppReady(err) {
        if (err) {
            throw err;
        }

        var basePort = self.serverPort;
        var serviceProxy = self.app.clients.serviceProxy;

        for (var i = 0; i < self.instances; i++) {
            var targetHostPort = '127.0.0.1:' + (basePort + i);

            serviceProxy.refreshServicePeer(
                self.serverServiceName, targetHostPort
            );
        }
    }
};

HyperbahnWorker.prototype.createConfig = function createConfig() {
    var self = this;

    var configDir = path.join(__dirname, '..', 'config');
    var remoteConfigFile = path.join(__dirname, 'remote_config.json');

    return StaticConfig({
        files: [
            path.join(configDir, 'production.json')
        ],
        seedConfig: {
            'clients.remote-config.file': remoteConfigFile,

            'clients.uber-statsd-client': {
                host: '127.0.0.1',
                port: self.statsdPort
            },
            'clients.logtron.kafka': {
                leafHost: '127.0.0.1',
                leafPort: self.kafkaPort
            },
            'clients.logtron.sentry': {
                id: 'http://bs:bs@localhost:' + self.sentryPort
            },
            'tchannel.host': '127.0.0.1'
        }
    });
};

if (require.main === module) {
    var argv = parseArgs(process.argv.slice(2));
    process.title = 'nodejs-benchmarks-hyperbahn_worker';

    var worker = HyperbahnWorker(argv);
    worker.start();
}
<commit_msg>benchmarks/hyperbahn-worker: no logFile<commit_after>// Copyright (c) 2015 Uber Technologies, Inc.

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

'use strict';

var parseArgs = require('minimist');
var process = require('process');
var assert = require('assert');
var path = require('path');
var StaticConfig = require('static-config');

var HyperbahnApplication = require('../app.js');

function HyperbahnWorker(opts) {
    /*eslint max-statements: [2, 25]*/
    if (!(this instanceof HyperbahnWorker)) {
        return new HyperbahnWorker(opts);
    }

    var self = this;

    assert(opts.serverPort, 'serverPort required');
    assert(opts.serverServiceName, 'serverServiceName required');
    assert(opts.instances, 'instances required');
    assert(opts.workerPort, 'workerPort required');

    assert(opts.sentryPort, 'sentryPort required');
    assert(opts.kafkaPort, 'kafkaPort required');

    self.statsdPort = Number(opts.statsdPort);
    self.kafkaPort = Number(opts.kafkaPort);
    self.sentryPort = Number(opts.sentryPort);
    self.config = self.createConfig();
    self.app = HyperbahnApplication(self.config, {
        processTitle: process.title,
        argv: {
            port: Number(opts.workerPort)
        }
    });

    self.instances = Number(opts.instances);
    self.serverServiceName = opts.serverServiceName;
    self.serverPort = Number(opts.serverPort);
}

HyperbahnWorker.prototype.start = function start() {
    var self = this;

    // attach before throwing exception
    process.on('uncaughtException', self.app.clients.onError);

    self.app.bootstrapAndListen(onAppReady);

    function onAppReady(err) {
        if (err) {
            throw err;
        }

        var basePort = self.serverPort;
        var serviceProxy = self.app.clients.serviceProxy;

        for (var i = 0; i < self.instances; i++) {
            var targetHostPort = '127.0.0.1:' + (basePort + i);

            serviceProxy.refreshServicePeer(
                self.serverServiceName, targetHostPort
            );
        }
    }
};

HyperbahnWorker.prototype.createConfig = function createConfig() {
    var self = this;

    var configDir = path.join(__dirname, '..', 'config');
    var remoteConfigFile = path.join(__dirname, 'remote_config.json');

    return StaticConfig({
        files: [
            path.join(configDir, 'production.json')
        ],
        seedConfig: {
            'clients.remote-config.file': remoteConfigFile,

            'clients.uber-statsd-client': {
                host: '127.0.0.1',
                port: self.statsdPort
            },
            'clients.logtron.kafka': {
                leafHost: '127.0.0.1',
                leafPort: self.kafkaPort
            },
            'clients.logtron.logFile': null,
            'clients.logtron.sentry': {
                id: 'http://bs:bs@localhost:' + self.sentryPort
            },
            'tchannel.host': '127.0.0.1'
        }
    });
};

if (require.main === module) {
    var argv = parseArgs(process.argv.slice(2));
    process.title = 'nodejs-benchmarks-hyperbahn_worker';

    var worker = HyperbahnWorker(argv);
    worker.start();
}
<|endoftext|>


<commit_before>/**
 * Created by nathandunn on 6/10/17.
 */
import {AnnotationCommand, request, SelectionState} from "substance";

class MarkupApp {

    constructor() {
        this.words = [];
    }

    render(data, callback) {

        // let words = ['organism','unc-5','elegans','epidermal'];
        // alert('rendering with dat: ' + JSON.stringify(data));
        // alert('rendering with words: ' + data.length);

        let cmd = new ToggleStrongCommand();
        let documentSession = window.app.state.documentSession;
        let selectionState = documentSession.getSelectionState();
        let nodes = window.doc.getNodes();

        // n.startsWith('article') // article junk
        // || n.startsWith('ext-link') // what we are tring to create
        // n.startsWith('body') // this is just the intro
        // || n.startsWith('heading') // this is the heading for each paragraph
        let numErrors = 0 ;
        let totalWordsFound = 0;
        for (let n in nodes) {
            // console.log(n);
            if (n.startsWith('paragraph')
            ) {
                let p = window.doc.get(n);
                // just find the first one
                for (let w in data) {
                    let wordHits = 0;
                    let word = data[w];
                    let found = 0;
                    found = p.content.indexOf(word,found);
                    if(found>0){
                        console.log("looking for: "+word + " found "+(found>0));
                    }
                    while (found >= 0) {
                        documentSession.setSelection({
                            type: 'property',
                            path: [p.id, 'content'],
                            startOffset: found,
                            endOffset: found + word.length
                        });
                        let sel = documentSession.getSelection();
                        selectionState.setSelection(sel);
                        try {
                            let res = cmd.execute({
                                commandState: {
                                    mode: 'create'
                                },
                                documentSession: documentSession,
                                selectionState: documentSession.getSelectionState()
                            });
                        } catch (e) {
                            console.log('error trying to annotate: '+sel + '\n'+e);
                            ++numErrors;
                        }
                        found = p.content.indexOf(word,found+1);
                        ++wordHits ;
                    }
                    if(wordHits>0){
                        console.log(word + ' found: '+wordHits);
                        ++totalWordsFound ;
                    }
                }
            }
        }

        console.log('total found: '+totalWordsFound);
        console.log('total errors: '+numErrors);

        if (callback) callback();
    }

    getWords(callback) {
        let serverURL = window.location.protocol + '//' + window.location.hostname + ':8080/keyWordSet/sampleKeyWordSet';
        console.log('server URL: '+serverURL);
        request('GET', serverURL, null, function (err, data) {
            if (err) {
                console.error(err);
                this.setState({
                    error: new Error('Loading failed')
                });
                return
            }
            if (data) {
                this.words = [];
                for (let d in data) {
                    this.words.push(data[d].value);
                }
                console.log('finished processing with words: ' + this.words.length);
                // this.render(this.words, cb);
                if (callback) callback(this.words);

                return this.words;
            }
        });
    }

}

class ToggleStrongCommand extends AnnotationCommand {

    // type = 'bold';
    // tagName = 'bold';

    constructor() {
        // super({name: 'bold', nodeType: 'bold'})
        super({name: 'ext-link', nodeType: 'ext-link'})
    }
}

// ToggleStrongCommand.define({
//     attributes: { type: 'object', default: {} }
// });

// export default ToggleStrongCommand

export default MarkupApp
<commit_msg>markup whole words only<commit_after>/**
 * Created by nathandunn on 6/10/17.
 */
import {AnnotationCommand, request, SelectionState} from "substance";

class MarkupApp {

    constructor() {
        this.words = [];
    }

    render(data, callback) {

        // let words = ['organism','unc-5','elegans','epidermal'];
        // alert('rendering with dat: ' + JSON.stringify(data));
        // alert('rendering with words: ' + data.length);

        let cmd = new ToggleStrongCommand();
        let documentSession = window.app.state.documentSession;
        let selectionState = documentSession.getSelectionState();
        let nodes = window.doc.getNodes();

        // n.startsWith('article') // article junk
        // || n.startsWith('ext-link') // what we are tring to create
        // n.startsWith('body') // this is just the intro
        // || n.startsWith('heading') // this is the heading for each paragraph
        let numErrors = 0 ;
        let totalWordsFound = 0;
        for (let n in nodes) {
            // console.log(n);
            if (n.startsWith('paragraph')
            ) {
                let p = window.doc.get(n);
                // just find the first one
                for (let w in data) {
                    let wordHits = 0;
                    let word = data[w];
                    let found = 0;
                    //found = p.content.indexOf(word,found);
                    //if(found>0){
                    //    console.log("looking for: "+word + " found "+(found>0));
                    //}
                    //while (found >= 0) {
					//
					// Escape string for regular expression
					var reWord = word.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
					var re = new RegExp("\\W" + reWord + "\\W", "g");
					var hits;
					while(hits = re.exec(p.content)) {

                        documentSession.setSelection({
                            type: 'property',
                            path: [p.id, 'content'],
                            startOffset: hits.index + 1,
                            endOffset: hits.index + 1 + word.length
                        });
                        let sel = documentSession.getSelection();
                        selectionState.setSelection(sel);
                        try {
                            let res = cmd.execute({
                                commandState: {
                                    mode: 'create'
                                },
                                documentSession: documentSession,
                                selectionState: documentSession.getSelectionState()
                            });
                        } catch (e) {
                            console.log('error trying to annotate: '+sel + '\n'+e);
                            ++numErrors;
                        }
                        //found = p.content.indexOf(word,found+1);
                        ++wordHits ;
                    }
                    if(wordHits>0){
                        console.log(word + ' found: '+wordHits);
                        ++totalWordsFound ;
                    }
                }
            }
        }

        console.log('total found: '+totalWordsFound);
        console.log('total errors: '+numErrors);

        if (callback) callback();
    }

    getWords(callback) {
        let serverURL = window.location.protocol + '//' + window.location.hostname + ':8080/keyWordSet/sampleKeyWordSet';
        console.log('server URL: '+serverURL);
        request('GET', serverURL, null, function (err, data) {
            if (err) {
                console.error(err);
                this.setState({
                    error: new Error('Loading failed')
                });
                return
            }
            if (data) {
                this.words = [];
                for (let d in data) {
                    this.words.push(data[d].value);
                }
                console.log('finished processing with words: ' + this.words.length);
                // this.render(this.words, cb);
                if (callback) callback(this.words);

                return this.words;
            }
        });
    }

}

class ToggleStrongCommand extends AnnotationCommand {

    // type = 'bold';
    // tagName = 'bold';

    constructor() {
        // super({name: 'bold', nodeType: 'bold'})
        super({name: 'ext-link', nodeType: 'ext-link'})
    }
}

// ToggleStrongCommand.define({
//     attributes: { type: 'object', default: {} }
// });

// export default ToggleStrongCommand

export default MarkupApp
<|endoftext|>


<commit_before>var fs = require('fs');
var config = require('./config');
var path = require('path');
var child_process = require('child_process');
var Q = require('q');
var spawn = child_process.spawn;
var location = path.join(__dirname, config.key.filename);
var readFile = Q.nfbind(fs.readFile);
var stat = Q.nfbind(fs.stat);

Q.all([
    stat(location),
    stat(location + ".pub")
])
.then(function(){
    return Q("");
}, function(){
    var deferred = Q.defer();

    var sshKeygen = spawn('ssh-keygen', [
        '-t','rsa',
        '-C', config.key.comment,
        '-f', location
    ]);

    var message = "\n";

    sshKeygen.stdout.on('data', function(data){
        message += data.toString();
    });

    sshKeygen.stderr.on('data', function(data){
        message += data.toString();
    });

    sshKeygen.on('close', function(code){
        if(code !== 0){
            deferred.reject(new Error(message));
        } else {
            deferred.resolve(message);
        }
    });

    return deferred.promise;
})
.then(console.log, console.error);
<commit_msg>optimized postinstall script<commit_after>var fs = require('fs');
var config = require('./config');
var path = require('path');
var child_process = require('child_process');
var Q = require('q');
var spawn = child_process.spawn;
var location = path.join(__dirname, config.key.filename);
var readFile = Q.nfbind(fs.readFile);
var stat = Q.nfbind(fs.stat);

Q.all([
    stat(location),
    stat(location + ".pub")
])
.then(function(){
    console.log("SSH-Key does already exist");
}, function(){
    var sshKeygen = spawn('ssh-keygen', [
        '-t','rsa',
        '-C', config.key.comment,
        '-f', location
    ]);

    sshKeygen.stdout.on('data', function(data){
        console.log(data.toString());
    });

    sshKeygen.stderr.on('data', function(data){
        console.error(data.toString());
    });
});
<|endoftext|>


<commit_before>// mongodatabank.js
//
// Implementation of Databank interface for MongoDB
//
// Copyright 2011, StatusNet Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

var databank = require('../databank'),
    Databank = databank.Databank,
    DatabankError = databank.DatabankError,
    AlreadyExistsError = databank.AlreadyExistsError,
    NoSuchThingError = databank.NoSuchThingError,
    NotImplementedError = databank.NotImplementedError,
    AlreadyConnectedError = databank.AlreadyConnectedError,
    NotConnectedError = databank.NotConnectedError;

var mongodb = require('mongodb'),
    Db = mongodb.Db,
    Server = mongodb.Server;

var MongoDatabank = function(params) {

    this.db = null;
    this.host = params.host || 'localhost';
    this.port = params.port || 27017;
    this.dbname = params.dbname || 'test';
    this.checkSchema = params.checkSchema || true;

    this.schema = params.schema || {};
};

MongoDatabank.prototype = new Databank();
MongoDatabank.prototype.constructor = MongoDatabank;

MongoDatabank.prototype.connect = function(params, onCompletion) {

    var host = params.host || this.host,
        port = params.port || this.port,
        dbname = params.dbname || this.dbname,
        server = new Server(host, port, params),
        checkSchema = params.checkSchema || this.checkSchema,
        bank = this;

    if (this.db) {
        if (onCompletion) {
            onCompletion(new AlreadyConnectedError());
        }
        return;
    }

    this.db = new Db(dbname, server);

    this.db.open(function(err, newDb) {
        if (err) {
            if (onCompletion) {
                onCompletion(err);
            }
        } else {
            if (checkSchema) {
                bank.checkBankSchema(function(err) {
                    if (err) {
                        if (onCompletion) {
                            onCompletion(err);
                        }
                    } else {
                        if (onCompletion) {
                            onCompletion(null);
                        }
                    }
                });
            } else {
                if (onCompletion) {
                    onCompletion(null);
                }
            }
        }
    });
};

// Disconnect yourself.
// onCompletion(err): function to call on completion

MongoDatabank.prototype.disconnect = function(onCompletion) {
    if (!this.db) {
        if (onCompletion) {
            onCompletion(new NotConnectedError());
        }
        return;
    }
    this.db.close(function() {
        this.db     = null;
        this.server = null;
        if (onCompletion) {
            onCompletion(null);
        }
    });
};

MongoDatabank.prototype._valueToRec = function(type, id, value) {

    var pkey = this.getPrimaryKey(type);

    if (typeof value === 'object' && !(value instanceof Array)) {
        value._id = id;
        if (value.hasOwnProperty(pkey)) {
            delete value[pkey];
        }
    } else {
        value = {_v: value, _s: true, _id: id};
    }

    return value;
};

MongoDatabank.prototype._recToValue = function(type, rec) {

    var pkey = this.getPrimaryKey(type), value;

    if (rec._s) {
        value = rec._v;
    } else {
        value = rec;
        value[pkey] = rec._id;
    }

    return value;
};

// Create a new thing
// type: string, type of thing, usually 'user' or 'activity'
// id: a unique ID, like a nickname or a UUID
// value: JavaScript value; will be JSONified
// onCompletion(err, value): function to call on completion

MongoDatabank.prototype.create = function(type, id, value, onCompletion) {

    var that = this;

    if (!this.db) {
        if (onCompletion) {
            onCompletion(new NotConnectedError());
        }
        return;
    }

    value = this._valueToRec(type, id, value);

    this.db.collection(type, function(err, coll) {
        if (err) {
            if (onCompletion) {
                onCompletion(err, null);
            }
        }
        coll.insert(value, {safe: true}, function(err, newValues) {
            if (err) {
                if (err.name && err.name == 'MongoError' && err.code && err.code == 11000) {
                    if (onCompletion) {
                        onCompletion(new AlreadyExistsError(type, id), null);
                    }
                } else {
                    if (onCompletion) {
                        onCompletion(err, null);
                    }
                }
            } else {
                // Mongo returns an array of values
                value = that._recToValue(type, newValues[0]);
                if (onCompletion) {
                    onCompletion(null, value);
                }
            }
        });
    });
};

// Read an existing thing
// type: the type of thing; 'user', 'activity'
// id: a unique ID -- nickname or UUID or URI
// onCompletion(err, value): function to call on completion

MongoDatabank.prototype.read = function(type, id, onCompletion) {

    var that = this;

    if (!this.db) {
        if (onCompletion) {
            onCompletion(new NotConnectedError());
        }
        return;
    }

    this.db.collection(type, function(err, coll) {
        var sel = {};
        if (err) {
            if (onCompletion) {
                onCompletion(err, null);
            }
        }
        sel._id = id;
        coll.findOne(sel, function(err, value) {
            if (err) {
                // FIXME: find key-miss errors and return a NotExistsError
                if (onCompletion) {
                    onCompletion(err, null);
                }
            } else if (!value) {
                if (onCompletion) {
                    onCompletion(new NoSuchThingError(type, id), null);
                }
            } else {
                value = that._recToValue(type, value);
                if (onCompletion) {
                    onCompletion(null, value);
                }
            }
        });
    });
};

// Update an existing thing
// type: the type of thing; 'user', 'activity'
// id: a unique ID -- nickname or UUID or URI
// value: the new value of the thing
// onCompletion(err, value): function to call on completion

MongoDatabank.prototype.update = function(type, id, value, onCompletion) {

    var that = this;

    if (!this.db) {
        if (onCompletion) {
            onCompletion(new NotConnectedError());
        }
        return;
    }

    value = this._valueToRec(type, id, value);

    this.db.collection(type, function(err, coll) {
        var sel = {};
        if (err) {
            if (onCompletion) {
                onCompletion(err, null);
            }
        }
        sel._id = id;
        coll.findAndModify(sel, [['_id', 'ascending']], value, {safe: true, 'new': true}, function(err, result) {
            if (err) {
                // FIXME: find key-miss errors and return a NotExistsError
                if (onCompletion) {
                    onCompletion(err, null);
                }
            } else {
                result = that._recToValue(type, result);
                if (onCompletion) {
                    onCompletion(null, result);
                }
            }
        });
    });
};

MongoDatabank.prototype.save = function(type, id, value, onCompletion) {

    var that = this;

    if (!this.db) {
        if (onCompletion) {
            onCompletion(new NotConnectedError());
        }
        return;
    }

    value = this._valueToRec(type, id, value);

    this.db.collection(type, function(err, coll) {
        var sel = {};
        if (err) {
            if (onCompletion) {
                onCompletion(err, null);
            }
        }
        sel._id = id;
        coll.update(sel, value, {upsert: true}, function(err) {
            if (err) {
                // FIXME: find key-miss errors and return a NotExistsError
                if (onCompletion) {
                    onCompletion(err, null);
                }
            } else {
                value = that._recToValue(type, value);
                if (onCompletion) {
                    onCompletion(null, value);
                }
            }
        });
    });
};

// Delete an existing thing
// type: the type of thing; 'user', 'activity'
// id: a unique ID -- nickname or UUID or URI
// value: the new value of the thing
// onCompletion(err): function to call on completion

MongoDatabank.prototype.del = function(type, id, onCompletion) {

    if (!this.db) {
        if (onCompletion) {
            onCompletion(new NotConnectedError());
        }
        return;
    }

    this.db.collection(type, function(err, coll) {

        var sel = {};

        if (err) {
            if (onCompletion) {
                onCompletion(err, null);
            }
        }

        sel._id = id;
        coll.remove(sel, {}, function(err) {
            if (err) {
                // FIXME: find key-miss errors and return a NotExistsError
                if (onCompletion) {
                    onCompletion(err);
                }
            } else {
                if (onCompletion) {
                    onCompletion(null);
                }
            }
        });
    });
};

// Search for things
// type: type of thing
// criteria: map of criteria, with exact matches, like {'subject.id':'tag:example.org,2011:evan' }
// onResult(value): called once per result found
// onCompletion(err): called once at the end of results

MongoDatabank.prototype.search = function(type, criteria, onResult, onCompletion) {

    var pkey = this.getPrimaryKey(type), that = this;

    if (!this.db) {
        if (onCompletion) {
            onCompletion(new NotConnectedError());
        }
        return;
    }

    if (criteria.hasOwnProperty(pkey)) {
        criteria._id = criteria[pkey];
        delete criteria[pkey];
    }

    this.db.collection(type, function(err, coll) {
        if (err) {
            if (onCompletion) {
                onCompletion(err, null);
            }
        } else {
            coll.find(criteria, function(err, cursor) {
                if (err) {
                    if (onCompletion) {
                        onCompletion(err);
                    }
                } else {
                    var lastErr = null;

                    cursor.each(function(err, value) {
                        if (err) {
                            lastErr = err;
                        } else if (value && !lastErr) {
                            value = that._recToValue(type, value);
                            onResult(value);
                        } else if (value === null) { // called after last value
                            onCompletion(lastErr);
                        }
                    });
                }
            });
        }
    });
};

MongoDatabank.prototype.getPrimaryKey = function(type) {
    return (this.schema && this.schema[type]) ? this.schema[type].pkey : '_id';
};

// XXX: this got weird. Not sure why.

MongoDatabank.prototype.checkBankSchema = function(onCompletion) {

    var pairs = [];
    var pair;
    var type;
    var bank = this;

    var checkType = function(type, schema, next) {
        bank.db.collection(type, function(err, coll) {
            var keys = {},
                total = 0,
                cnt = 0,
                i = 0,
                hadErr = false,
                indexDone = function(err) {
                    if (err) {
                        next(err);
                        hadErr = true;
                    } else {
                        cnt++;
                        if (cnt >= total && !hadErr) {
                            next(null);
                        }
                    }
                };

            if (err) {
                next(err);
            } else {
                if (schema.indices) {
                    total += schema.indices.length;
                }
                if (total === 0) {
                    next(null);
                } else {
                    if (schema.indices) {
                        for (i = 0; i < schema.indices.length; i++) {
                            keys = {};
                            keys[schema.indices[i]] = 1;
                            coll.ensureIndex(keys, {}, indexDone);
                        }
                    }
                }
            }
        });
    };

    var checkNextType = function(pairsLeft, next) {
        var pair;
        if (pairsLeft.length === 0) {
            next(null);
        } else {
            pair = pairsLeft.pop();
            checkType(pair[0], pair[1], function(err) {
                if (err) {
                    next(err);
                } else {
                    checkNextType(pairsLeft, next);
                }
            });
        }
    };

    for (type in this.schema) {
        pair = [type, this.schema[type]];
        pairs.push(pair);
    }

    checkNextType(pairs, onCompletion);
};

exports.MongoDatabank = MongoDatabank;

<commit_msg>Atomic incr, decr, append<commit_after>// mongodatabank.js
//
// Implementation of Databank interface for MongoDB
//
// Copyright 2011, StatusNet Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

var databank = require('../databank'),
    Databank = databank.Databank,
    DatabankError = databank.DatabankError,
    AlreadyExistsError = databank.AlreadyExistsError,
    NoSuchThingError = databank.NoSuchThingError,
    NotImplementedError = databank.NotImplementedError,
    AlreadyConnectedError = databank.AlreadyConnectedError,
    NotConnectedError = databank.NotConnectedError;

var mongodb = require('mongodb'),
    Db = mongodb.Db,
    Server = mongodb.Server;

var MongoDatabank = function(params) {

    this.db = null;
    this.host = params.host || 'localhost';
    this.port = params.port || 27017;
    this.dbname = params.dbname || 'test';
    this.checkSchema = params.checkSchema || true;

    this.schema = params.schema || {};
};

MongoDatabank.prototype = new Databank();
MongoDatabank.prototype.constructor = MongoDatabank;

MongoDatabank.prototype.connect = function(params, onCompletion) {

    var host = params.host || this.host,
        port = params.port || this.port,
        dbname = params.dbname || this.dbname,
        server = new Server(host, port, params),
        checkSchema = params.checkSchema || this.checkSchema,
        bank = this;

    if (this.db) {
        if (onCompletion) {
            onCompletion(new AlreadyConnectedError());
        }
        return;
    }

    this.db = new Db(dbname, server);

    this.db.open(function(err, newDb) {
        if (err) {
            if (onCompletion) {
                onCompletion(err);
            }
        } else {
            if (checkSchema) {
                bank.checkBankSchema(function(err) {
                    if (err) {
                        if (onCompletion) {
                            onCompletion(err);
                        }
                    } else {
                        if (onCompletion) {
                            onCompletion(null);
                        }
                    }
                });
            } else {
                if (onCompletion) {
                    onCompletion(null);
                }
            }
        }
    });
};

// Disconnect yourself.
// onCompletion(err): function to call on completion

MongoDatabank.prototype.disconnect = function(onCompletion) {
    if (!this.db) {
        if (onCompletion) {
            onCompletion(new NotConnectedError());
        }
        return;
    }
    this.db.close(function() {
        this.db     = null;
        this.server = null;
        if (onCompletion) {
            onCompletion(null);
        }
    });
};

MongoDatabank.prototype._valueToRec = function(type, id, value) {

    var pkey = this.getPrimaryKey(type);

    if (typeof value === 'object' && !(value instanceof Array)) {
        value._id = id;
        if (value.hasOwnProperty(pkey)) {
            delete value[pkey];
        }
    } else {
        value = {_v: value, _s: true, _id: id};
    }

    return value;
};

MongoDatabank.prototype._recToValue = function(type, rec) {

    var pkey = this.getPrimaryKey(type), value;

    if (rec._s) {
        value = rec._v;
    } else {
        value = rec;
        value[pkey] = rec._id;
    }

    return value;
};

// Create a new thing
// type: string, type of thing, usually 'user' or 'activity'
// id: a unique ID, like a nickname or a UUID
// value: JavaScript value; will be JSONified
// onCompletion(err, value): function to call on completion

MongoDatabank.prototype.create = function(type, id, value, onCompletion) {

    var that = this;

    if (!this.db) {
        if (onCompletion) {
            onCompletion(new NotConnectedError());
        }
        return;
    }

    value = this._valueToRec(type, id, value);

    this.db.collection(type, function(err, coll) {
        if (err) {
            if (onCompletion) {
                onCompletion(err, null);
            }
        }
        coll.insert(value, {safe: true}, function(err, newValues) {
            if (err) {
                if (err.name && err.name == 'MongoError' && err.code && err.code == 11000) {
                    if (onCompletion) {
                        onCompletion(new AlreadyExistsError(type, id), null);
                    }
                } else {
                    if (onCompletion) {
                        onCompletion(err, null);
                    }
                }
            } else {
                // Mongo returns an array of values
                value = that._recToValue(type, newValues[0]);
                if (onCompletion) {
                    onCompletion(null, value);
                }
            }
        });
    });
};

// Read an existing thing
// type: the type of thing; 'user', 'activity'
// id: a unique ID -- nickname or UUID or URI
// onCompletion(err, value): function to call on completion

MongoDatabank.prototype.read = function(type, id, onCompletion) {

    var that = this;

    if (!this.db) {
        if (onCompletion) {
            onCompletion(new NotConnectedError());
        }
        return;
    }

    this.db.collection(type, function(err, coll) {
        var sel = {};
        if (err) {
            if (onCompletion) {
                onCompletion(err, null);
            }
        }
        sel._id = id;
        coll.findOne(sel, function(err, value) {
            if (err) {
                // FIXME: find key-miss errors and return a NotExistsError
                if (onCompletion) {
                    onCompletion(err, null);
                }
            } else if (!value) {
                if (onCompletion) {
                    onCompletion(new NoSuchThingError(type, id), null);
                }
            } else {
                value = that._recToValue(type, value);
                if (onCompletion) {
                    onCompletion(null, value);
                }
            }
        });
    });
};

// Update an existing thing
// type: the type of thing; 'user', 'activity'
// id: a unique ID -- nickname or UUID or URI
// value: the new value of the thing
// onCompletion(err, value): function to call on completion

MongoDatabank.prototype.update = function(type, id, value, onCompletion) {

    var that = this;

    if (!this.db) {
        if (onCompletion) {
            onCompletion(new NotConnectedError());
        }
        return;
    }

    value = this._valueToRec(type, id, value);

    this.db.collection(type, function(err, coll) {
        var sel = {};
        if (err) {
            if (onCompletion) {
                onCompletion(err, null);
            }
        }
        sel._id = id;
        coll.findAndModify(sel, [['_id', 'ascending']], value, {safe: true, 'new': true}, function(err, result) {
            if (err) {
                // FIXME: find key-miss errors and return a NotExistsError
                if (onCompletion) {
                    onCompletion(err, null);
                }
            } else {
                result = that._recToValue(type, result);
                if (onCompletion) {
                    onCompletion(null, result);
                }
            }
        });
    });
};

MongoDatabank.prototype.save = function(type, id, value, onCompletion) {

    var that = this;

    if (!this.db) {
        if (onCompletion) {
            onCompletion(new NotConnectedError());
        }
        return;
    }

    value = this._valueToRec(type, id, value);

    this.db.collection(type, function(err, coll) {
        var sel = {};
        if (err) {
            if (onCompletion) {
                onCompletion(err, null);
            }
        }
        sel._id = id;
        coll.update(sel, value, {upsert: true}, function(err) {
            if (err) {
                // FIXME: find key-miss errors and return a NotExistsError
                if (onCompletion) {
                    onCompletion(err, null);
                }
            } else {
                value = that._recToValue(type, value);
                if (onCompletion) {
                    onCompletion(null, value);
                }
            }
        });
    });
};

// Delete an existing thing
// type: the type of thing; 'user', 'activity'
// id: a unique ID -- nickname or UUID or URI
// value: the new value of the thing
// onCompletion(err): function to call on completion

MongoDatabank.prototype.del = function(type, id, onCompletion) {

    if (!this.db) {
        if (onCompletion) {
            onCompletion(new NotConnectedError());
        }
        return;
    }

    this.db.collection(type, function(err, coll) {

        var sel = {};

        if (err) {
            if (onCompletion) {
                onCompletion(err, null);
            }
        }

        sel._id = id;
        coll.remove(sel, {}, function(err) {
            if (err) {
                // FIXME: find key-miss errors and return a NotExistsError
                if (onCompletion) {
                    onCompletion(err);
                }
            } else {
                if (onCompletion) {
                    onCompletion(null);
                }
            }
        });
    });
};

// Search for things
// type: type of thing
// criteria: map of criteria, with exact matches, like {'subject.id':'tag:example.org,2011:evan' }
// onResult(value): called once per result found
// onCompletion(err): called once at the end of results

MongoDatabank.prototype.search = function(type, criteria, onResult, onCompletion) {

    var pkey = this.getPrimaryKey(type), that = this;

    if (!this.db) {
        if (onCompletion) {
            onCompletion(new NotConnectedError());
        }
        return;
    }

    if (criteria.hasOwnProperty(pkey)) {
        criteria._id = criteria[pkey];
        delete criteria[pkey];
    }

    this.db.collection(type, function(err, coll) {
        if (err) {
            if (onCompletion) {
                onCompletion(err, null);
            }
        } else {
            coll.find(criteria, function(err, cursor) {
                if (err) {
                    if (onCompletion) {
                        onCompletion(err);
                    }
                } else {
                    var lastErr = null;

                    cursor.each(function(err, value) {
                        if (err) {
                            lastErr = err;
                        } else if (value && !lastErr) {
                            value = that._recToValue(type, value);
                            onResult(value);
                        } else if (value === null) { // called after last value
                            onCompletion(lastErr);
                        }
                    });
                }
            });
        }
    });
};

MongoDatabank.prototype.incr = function(type, id, onCompletion) {

    var that = this;

    if (!this.db) {
        if (onCompletion) {
            onCompletion(new NotConnectedError());
        }
        return;
    }

    this.db.collection(type, function(err, coll) {
        if (err) {
            if (onCompletion) {
                onCompletion(err, null);
            }
        } else {
            coll.update({_id: id}, {"$inc": {"_v": 1}}, {upsert: true, multi: false}, function(err) {
                if (err) {
                    if (onCompletion) {
                        onCompletion(err, null);
                    }
                } else {
                    that.read(type, id, onCompletion);
                }
            });
        }
    });
};

MongoDatabank.prototype.decr = function(type, id, onCompletion) {

    var that = this;

    if (!this.db) {
        if (onCompletion) {
            onCompletion(new NotConnectedError());
        }
        return;
    }

    this.db.collection(type, function(err, coll) {
        if (err) {
            if (onCompletion) {
                onCompletion(err, null);
            }
        } else {
            coll.update({_id: id}, {"$inc": {"_v": -1}}, {upsert: true, multi: false}, function(err) {
                if (err) {
                    if (onCompletion) {
                        onCompletion(err, null);
                    }
                } else {
                    that.read(type, id, onCompletion);
                }
            });
        }
    });
};

MongoDatabank.prototype.append = function(type, id, toAppend, onCompletion) {
    var that = this;

    if (!this.db) {
        if (onCompletion) {
            onCompletion(new NotConnectedError());
        }
        return;
    }

    this.db.collection(type, function(err, coll) {
        if (err) {
            if (onCompletion) {
                onCompletion(err, null);
            }
        } else {
            coll.update({_id: id}, {"$push": {"_v": toAppend}}, {upsert: true, multi: false}, function(err) {
                if (err) {
                    if (onCompletion) {
                        onCompletion(err, null);
                    }
                } else {
                    that.read(type, id, onCompletion);
                }
            });
        }
    });
};

MongoDatabank.prototype.getPrimaryKey = function(type) {
    return (this.schema && this.schema[type]) ? this.schema[type].pkey : '_id';
};

// XXX: this got weird. Not sure why.

MongoDatabank.prototype.checkBankSchema = function(onCompletion) {

    var pairs = [];
    var pair;
    var type;
    var bank = this;

    var checkType = function(type, schema, next) {
        bank.db.collection(type, function(err, coll) {
            var keys = {},
                total = 0,
                cnt = 0,
                i = 0,
                hadErr = false,
                indexDone = function(err) {
                    if (err) {
                        next(err);
                        hadErr = true;
                    } else {
                        cnt++;
                        if (cnt >= total && !hadErr) {
                            next(null);
                        }
                    }
                };

            if (err) {
                next(err);
            } else {
                if (schema.indices) {
                    total += schema.indices.length;
                }
                if (total === 0) {
                    next(null);
                } else {
                    if (schema.indices) {
                        for (i = 0; i < schema.indices.length; i++) {
                            keys = {};
                            keys[schema.indices[i]] = 1;
                            coll.ensureIndex(keys, {}, indexDone);
                        }
                    }
                }
            }
        });
    };

    var checkNextType = function(pairsLeft, next) {
        var pair;
        if (pairsLeft.length === 0) {
            next(null);
        } else {
            pair = pairsLeft.pop();
            checkType(pair[0], pair[1], function(err) {
                if (err) {
                    next(err);
                } else {
                    checkNextType(pairsLeft, next);
                }
            });
        }
    };

    for (type in this.schema) {
        pair = [type, this.schema[type]];
        pairs.push(pair);
    }

    checkNextType(pairs, onCompletion);
};

exports.MongoDatabank = MongoDatabank;

<|endoftext|>


<commit_before>var preferWs = true;
var data = null;
var webSocket = null;
var request = null;
var identifier = null;

	function isWsSupported() {
		return ("WebSocket" in window);
	}

	function useWs() {
		return (isWsSupported() && preferWs);
	}

	// common functions

	function connect() {
		useWs() ? openSocket() : openComet();
	}

	function send() {
		data = document.getElementById("input").value;
		if (data != "") {
			useWs() ? sendSocket(data) : sendComet(data);
		}
	}

	function disconnect() {
		useWs() ? closeSocket() : closeComet();
	}

	// comet functions

	function createXmlRequest() {
		return new XMLHttpRequest();
	}

	function cometUrl() {
		if (identifier != null) return document.location.href + "/xhr?id=" + identifier;
		return document.location.href+"/xhr";
	}

	function openComet() {
		if (request == null) poll();
	}

	function poll() {
		request = createXmlRequest();
		request.open("GET", cometUrl(), true);
		request.onreadystatechange = pollResponseHandler;
		request.send(null);
	}

	function pollResponseHandler() {
		if (request.readyState == 4) {
			if (request.status == 200) {
				var content = request.responseText;
				log(request.status, content);
				poll();
			}
			else if (request.status == 202) {
				identifier = request.responseText;
				info("Registered with id " + identifier);
				poll();
			}
			else info("disconnected");
		}
	}

	function sendComet(data) {
		stop();
		request = createXmlRequest();
		request.open("POST", cometUrl(), true);
		request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		request.onreadystatechange = sendResponseHandler;
		request.send(encodeURIComponent(data));
	}

	function sendResponseHandler() {
		if ((request.readyState == 4) && (request.status == 201)) {
			log(201, data);
			poll();
		}
	}

	function closeComet() {
		if (request != null) {
			request.abort();
			request = null;
		}
	}

	// WebSocket

	function openSocket() {

		webSocket = new WebSocket("ws://" + document.location.href.split("//")[1] + "/ws");

		webSocket.onopen = function(event) {
			info("Successfully opened WebSocket.");
		}

		webSocket.onerror = function(event) {
			log("WebSocket failed.");
		}

		webSocket.onmessage = function(event) {
			log(200, event.data);
		}

		webSocket.onclose = function() {
			info("WebSocket received close event.");
		}
	}

	function sendSocket(message) {
		if (webSocket != null) {
			webSocket.send(message);
			log(200, message);
		}
	}

	function closeSocket() {
		if (webSocket != null) {
			info("WebSocket closed by client.");
			webSocket.close();
			webSocket = null;
		}
	}
	<commit_msg>checked out bidi_comm.js from the canvasSpike... hope this is correct now<commit_after>var preferWs = true;
var data = null;
var webSocket = null;
var request = null;
var identifier = null;

	function isWsSupported() {
		return ("WebSocket" in window);
	}

	function useWs() {
		return (isWsSupported() && preferWs);
	}

	// common functions

	function connect() {
		useWs() ? openSocket() : openComet();
	}

	function send() {
		data = document.getElementById("input").value;
		if (data != "") {
			useWs() ? sendSocket(data) : sendComet(data);
		}
	}

	function disconnect() {
		useWs() ? closeSocket() : closeComet();
	}

	// comet functions

	function createXmlRequest() {
		return new XMLHttpRequest();
	}

	function cometUrl() {
		if (identifier != null) return document.location.href + "/xhr?id=" + identifier;
		return document.location.href+"/xhr";
	}

	function openComet() {
		if (request == null) poll();
	}

	function poll() {
		request = createXmlRequest();
		request.open("GET", cometUrl(), true);
		request.onreadystatechange = pollResponseHandler;
		request.send(null);
	}

	function pollResponseHandler() {
		if (request.readyState == 4) {
			if (request.status == 200) {
				var content = request.responseText;
				log(request.status, content);
				poll();
			}
			else if (request.status == 202) {
				identifier = request.responseText;
				info("Registered with id " + identifier);
				poll();
			}
			else info("disconnected");
		}
	}

	function sendComet(data) {
		stop();
		request = createXmlRequest();
		request.open("POST", cometUrl(), true);
		request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		request.onreadystatechange = sendResponseHandler;
		request.send(encodeURIComponent(data));
	}

	function sendResponseHandler() {
		if ((request.readyState == 4) && (request.status == 201)) {
			log(201, data);
			poll();
		}
	}

	function closeComet() {
		if (request != null) {
			request.abort();
			request = null;
		}
	}

	// WebSocket

	function openSocket() {

		webSocket = new WebSocket("ws://" + document.location.href.split("//")[1] + "/ws");

		webSocket.onopen = function(event) {
			info("Successfully opened WebSocket.");
		}

		webSocket.onerror = function(event) {
			log("WebSocket failed.");
		}

		webSocket.onmessage = function(event) {
			log(200, event.data);
		}

		webSocket.onclose = function() {
			info("WebSocket received close event.");
		}
	}

	function sendSocket(message) {
		if (webSocket != null) {
			webSocket.send(message);
			log(200, message);
		}
	}

	function closeSocket() {
		if (webSocket != null) {
			info("WebSocket closed by client.");
			webSocket.close();
			webSocket = null;
		}
	}

	function info(message) {
		alert(message);
	}
	function log(message) {
		alert(message);
	}
	<|endoftext|>


<commit_before>var BME280 = require('node-bme280');
var barometer = new BME280({address: 0x77});

module.exports = function () {
	return new Promise(function (resolve, reject) {
		barometer.begin(function(err) {
			if (err) {
				console.info('error initializing barometer', err);
				reject();
			} else {
				console.info('barometer running');
				resolve(new Promise(function (resolve, reject) {
					barometer.readPressureAndTemparature(function(err, pressure, temperature, humidity) {
						latestTemp = temperature.toFixed(2);
						latestPressure = (pressure / 100).toFixed(2);
						latestHumidity = humidity.toFixed(2);
						resolve([
							{
								sensorID: 1,
								value: latestTemp,
								unit: "°C",
								measurement: "Temperature",
								location: "ICT office",
								htmlDecimal: 1
							},
							{
								sensorID: 2,
								value: latestHumidity,
								unit: "%",
								measurement: "Humidity",
								location: "ICT office",
								htmlDecimal: 1
							},
							{
								sensorID: 3,
								value: latestPressure,
								unit: "hPa",
								small: true,
								measurement: "Pressure",
								location: "ICT office",
								htmlDecimal: 0
							}
						]);
					});
				});
			}
		});
	});
}
<commit_msg>Update bme280.js<commit_after>var BME280 = require('node-bme280');
var barometer = new BME280({address: 0x77});

module.exports = function () {
	return new Promise(function (resolve, reject) {
		barometer.begin(function(err) {
			if (err) {
				console.info('error initializing barometer', err);
				reject();
			} else {
				console.info('barometer running');
				resolve(new Promise(function (resolve, reject) {
					barometer.readPressureAndTemparature(function(err, pressure, temperature, humidity) {
						latestTemp = temperature.toFixed(2);
						latestPressure = (pressure / 100).toFixed(2);
						latestHumidity = humidity.toFixed(2);
						resolve([
							{
								sensorID: 1,
								value: latestTemp,
								unit: "°C",
								measurement: "Temperature",
								location: "ICT office",
								htmlDecimal: 1
							},
							{
								sensorID: 2,
								value: latestHumidity,
								unit: "%",
								measurement: "Humidity",
								location: "ICT office",
								htmlDecimal: 1
							},
							{
								sensorID: 3,
								value: latestPressure,
								unit: "hPa",
								small: true,
								measurement: "Pressure",
								location: "ICT office",
								htmlDecimal: 0
							}
						]);
					});
				}));
			}
		});
	});
}
<|endoftext|>