<commit_before>import commander from 'commander';
import Fakeit from './index.js';
import updateNotifier from 'update-notifier';
import pkg from './../package.json';
import path from 'path';
import { extend, flattenDeep, pick } from 'lodash';
import chalk from 'chalk';

export default async function() {
  // check for update and notify
  updateNotifier({ pkg }).notify();
  const base_options = [
    'root',
    'babel',
    'count',
    'verbose',
    'log',
    'spinners',
    'timestamp',
    'seed',
  ];

  const output_options = [
    // global options
    'format',
    'spacing',
    'limit',
    // action specific options
    'highlight',
    'archive',
    'server',
    'bucket',
    'username',
    'password',
    'timeout',
    // gets set based off the command that's used
    'output',
  ];

  // get the inputs
  commander
    .version(pkg.version)
    .usage('[command] [<file|directory|glob> ...]')
    .option('--root <directory>', `Defines the root directory from which paths are resolve from (${dim('process.cwd()')})`, process.cwd())
    .option('--babel <glob>', `The location to the babel config (${dim('+(.babelrc|package.json)')})`, '+(.babelrc|package.json)')
    .option('-c, --count <n>', 'Overrides the number of documents to generate specified by the model. Defaults to model defined count', parseInt)
    .option('-v, --verbose', `Enables verbose logging mode (${dim(false)})`)
    .option('-S, --no-spinners', 'Disables progress spinners', false)
    .option('-L, --no-log', 'Disables all logging except for errors', false)
    .option('-T, --no-timestamp', 'Disables timestamps from logging output', false)
    // global output options
    .option('-f, --format <type>', `this determins the output format to use. Supported formats: ${code('json', 'csv', 'yaml', 'yml', 'cson')}. (${dim('json')})`, 'json') // eslint-disable-line
    .option('-n, --spacing <n>', `the number of spaces to use for indention (${dim('2')})`, 2)
    .option('-l, --limit <n>', `limit how many files are output at a time (${dim('100')})`, 100)
    .option('-x, --seed <seed>', 'The global seed to use for repeatable data', (seed) => {
      const number = parseInt(seed);

      if (number > 0 || seed === '0') {
        return number;
      }
      return seed;
    });

  commander
    .command('console')
    .option('-h, --no-highlight', 'This turns off the cli-table when a csv format', Boolean, false)
    .description('outputs the result to the console')
    .action(async (...args) => {
      const { highlight } = args.pop();

      await run({ output: 'console', highlight });
    });

  function runServer(output) {
    /* istanbul ignore next : too difficult to test the servers via the cli */
    return async (...args) =>{
      const options = pick(args.pop(), [ 'server', 'bucket', 'username', 'password', 'timeout' ]);
      options.output = output;
      await run(options);
    };
  }

  commander
    .command('couchbase')
    .option('-s, --server [server]', `The server address (${dim('127.0.0.1')})`)
    .option('-b, --bucket [bucket]', `The bucket name (${dim('default')})`)
    .option('-p, --password [password]', 'the password for the account (optional)')
    .option('-t, --timeout [timeout]', `timeout for the servers (${dim(5000)})`)
    .description('This will output to couchbase')
    .action(runServer('couchbase'));

  commander
    .command('sync-gateway')
    .option('-s, --server [server]', `The server address (${dim('127.0.0.1')})`)
    .option('-b, --bucket [bucket]', `The bucket name (${dim('default')})`)
    .option('-u, --username [username]', 'the username to use (optional)')
    .option('-p, --password [password]', 'the password for the account (optional)')
    .option('-t, --timeout [timeout]', 'timeout for the servers')
    .description('no idea')
    .action(runServer('sync-gateway'));

  commander
    .command('directory [<dir|file.zip>] [<models...>]')
    .alias('folder')
    .option('-a, --archive [file.zip]', 'If an archive file is passed then the data will be output as a zip file', '')
    .description('Output the file(s) into a directory')
    .action(async (output, models, { archive }) => {
      const parsed = path.parse(output);

      if (parsed.ext) {
        archive = parsed.base;
        output = parsed.dir || commander.root;
      }

      // update the commander args to be correct
      commander.args = process.argv.slice(4);
      await run({ archive, output });
    });

  commander
    .command('help')
    .action(() => {
      commander.help();
    });

  commander.parse(process.argv);

  if (!commander.args.length) {
    commander.help();
  }

  // this function is used as a helper to run the different actions
  async function run(output = {}, opts = {}) {
    output = typeof output === 'string' ? { output } : output;

    opts = pick(extend(pick(commander, base_options), opts), base_options);
    opts.babel_config = opts.babel;
    delete opts.babel;

    output = extend(pick(commander, output_options), pick(output, output_options));

    const output_path = path.join(output.output, output.archive || '');
    const models = commander.args.filter((str, i, args) => {
      const prev = args[i - 1] || '';
      if (
        typeof str !== 'string' ||
        // if the previous str was one of these commands that has options then remove it
        /^(\-\-(?:commander|root|babel|count|format|spacing|seed|limit)|(?:\-[cfnxl]{1,}))$/.test(prev) ||
        // if the str is one of the commands then remove it
        /^(([-]{1,2}[a-zA-Z]+)|\-\-no\-[a-z]+)$/.test(str) ||
        // if the str is the same as the output path then remove it
        str === output_path
      ) {
        return false;
      }
      return true;
    });

    const fakeit = new Fakeit(opts);
    if (!models.length) {
      fakeit.log('warning', 'you must pass in models to use');
      commander.help();
      return;
    }

    try {
      await fakeit.generate(models, output);
      process.exit();
    } catch (err) {
      process.exit(1);
      throw err;
    }
  }
}

/* istanbul ignore next : too hard to test */
process.on('uncaughtException', (err) => {
  console.log('An uncaughtException was found:', err);
  process.exit(1);
});

export function code(...args) {
  return flattenDeep(args).map((str) => chalk.bold(str)).join(', ');
}

export function dim(...args) {
  return flattenDeep(args).map((str) => chalk.dim(str)).join(', ');
}
<commit_msg>Updated cli to show help when no models are passed<commit_after>import commander from 'commander';
import Fakeit from './index.js';
import updateNotifier from 'update-notifier';
import pkg from './../package.json';
import path from 'path';
import { extend, flattenDeep, pick, find } from 'lodash';
import chalk from 'chalk';

export default async function() {
  // check for update and notify
  updateNotifier({ pkg }).notify();
  const base_options = [
    'root',
    'babel',
    'count',
    'verbose',
    'log',
    'spinners',
    'timestamp',
    'seed',
  ];

  const output_options = [
    // global options
    'format',
    'spacing',
    'limit',
    // action specific options
    'highlight',
    'archive',
    'server',
    'bucket',
    'username',
    'password',
    'timeout',
    // gets set based off the command that's used
    'output',
  ];

  // get the inputs
  commander
    .version(pkg.version)
    .usage('[command] [<file|directory|glob> ...]')
    .option('--root <directory>', `Defines the root directory from which paths are resolve from (${dim('process.cwd()')})`, process.cwd())
    .option('--babel <glob>', `The location to the babel config (${dim('+(.babelrc|package.json)')})`, '+(.babelrc|package.json)')
    .option('-c, --count <n>', 'Overrides the number of documents to generate specified by the model. Defaults to model defined count', parseInt)
    .option('-v, --verbose', `Enables verbose logging mode (${dim(false)})`)
    .option('-S, --no-spinners', 'Disables progress spinners', false)
    .option('-L, --no-log', 'Disables all logging except for errors', false)
    .option('-T, --no-timestamp', 'Disables timestamps from logging output', false)
    // global output options
    .option('-f, --format <type>', `this determins the output format to use. Supported formats: ${code('json', 'csv', 'yaml', 'yml', 'cson')}. (${dim('json')})`, 'json') // eslint-disable-line
    .option('-n, --spacing <n>', `the number of spaces to use for indention (${dim('2')})`, 2)
    .option('-l, --limit <n>', `limit how many files are output at a time (${dim('100')})`, 100)
    .option('-x, --seed <seed>', 'The global seed to use for repeatable data', (seed) => {
      const number = parseInt(seed);

      if (number > 0 || seed === '0') {
        return number;
      }
      return seed;
    });

  commander
    .command('console')
    .option('-h, --no-highlight', 'This turns off the cli-table when a csv format', Boolean, false)
    .description('outputs the result to the console')
    .action(async (...args) => {
      const { highlight } = args.pop();

      await run({ output: 'console', highlight });
    });

  function runServer(output) {
    /* istanbul ignore next : too difficult to test the servers via the cli */
    return async (...args) =>{
      const options = pick(args.pop(), [ 'server', 'bucket', 'username', 'password', 'timeout' ]);
      options.output = output;
      await run(options);
    };
  }

  commander
    .command('couchbase')
    .option('-s, --server [server]', `The server address (${dim('127.0.0.1')})`)
    .option('-b, --bucket [bucket]', `The bucket name (${dim('default')})`)
    .option('-p, --password [password]', 'the password for the account (optional)')
    .option('-t, --timeout [timeout]', `timeout for the servers (${dim(5000)})`)
    .description('This will output to a Couchbase Server')
    .action(runServer('couchbase'));

  commander
    .command('sync-gateway')
    .option('-s, --server [server]', `The server address (${dim('127.0.0.1')})`)
    .option('-b, --bucket [bucket]', `The bucket name (${dim('default')})`)
    .option('-u, --username [username]', 'the username to use (optional)')
    .option('-p, --password [password]', 'the password for the account (optional)')
    .option('-t, --timeout [timeout]', 'timeout for the servers')
    .description('This will output to a Couchbase Sync-Gateway Server')
    .action(runServer('sync-gateway'));

  commander
    .command('directory [<dir|file.zip>] [<models...>]')
    .alias('folder')
    .option('-a, --archive [file.zip]', 'If an archive file is passed then the data will be output as a zip file', '')
    .description('Output the file(s) into a directory')
    .action(async (output, models, { archive }) => {
      const parsed = path.parse(output);

      if (parsed.ext) {
        archive = parsed.base;
        output = parsed.dir || commander.root;
      }

      // update the commander args to be correct
      commander.args = process.argv.slice(4);
      await run({ archive, output });
    });

  commander
    .command('help')
    .action(() => {
      commander.help();
    });

  commander.parse(process.argv);

  if (!commander.args.length) {
    commander.help();
  }

  // this function is used as a helper to run the different actions
  async function run(output = {}, opts = {}) {
    output = typeof output === 'string' ? { output } : output;

    opts = pick(extend(pick(commander, base_options), opts), base_options);
    opts.babel_config = opts.babel;
    delete opts.babel;

    output = extend(pick(commander, output_options), pick(output, output_options));

    const output_path = path.join(output.output, output.archive || '');
    const models = commander.args.filter((str, i, args) => {
      const prev = args[i - 1] || '';
      if (
        typeof str !== 'string' ||
        // if the previous str was one of these commands that has options then remove it
        /^(\-\-(?:commander|root|babel|count|format|spacing|seed|limit)|(?:\-[cfnxl]{1,}))$/.test(prev) ||
        // if the str is one of the commands then remove it
        /^(([-]{1,2}[a-zA-Z]+)|\-\-no\-[a-z]+)$/.test(str) ||
        // if the str is the same as the output path then remove it
        str === output_path
      ) {
        return false;
      }
      return true;
    });

    const fakeit = new Fakeit(opts);
    if (!models.length) {
      fakeit.log('warning', 'you must pass in models to use');
      find(commander.commands, [ '_name', output.output ]).help();
      return;
    }

    try {
      await fakeit.generate(models, output);
      process.exit();
    } catch (err) {
      process.exit(1);
      throw err;
    }
  }
}

/* istanbul ignore next : too hard to test */
process.on('uncaughtException', (err) => {
  console.log('An uncaughtException was found:', err);
  process.exit(1);
});

export function code(...args) {
  return flattenDeep(args).map((str) => chalk.bold(str)).join(', ');
}

export function dim(...args) {
  return flattenDeep(args).map((str) => chalk.dim(str)).join(', ');
}
<|endoftext|>


<commit_before>var select = require("dom-select");
var layout = require("./layout");
var socket = require("./socket");

module.exports = start;

function start (url) {
  window.addEventListener("message", receiveMessage, false);
  layout.run(url);
}

function receiveMessage (message) {
  if (message.data.type == 'error') {
    fail(message.data);
  }

  if (message.data.type == 'test') {
    layout.markTest(message.data);
  }

  if (message.data.type == 'end') {
    end(message.data);
  }
}

function fail (error) {
  socket.send({ fail: error, userAgent: navigator.userAgent });
  layout.addError(error);
}

function end (result) {
  socket.send({ userAgent: navigator.userAgent, result: result });

  if (!result.failed) layout.pass(result.passed);
  layout.list(result.tests);
}
<commit_msg>clear the console on each run<commit_after>var select = require("dom-select");
var layout = require("./layout");
var socket = require("./socket");

module.exports = start;

function start (url) {
  window.addEventListener("message", receiveMessage, false);

  // clear the console on each run so that previous messages don't show
  if (console.clear) {
    console.clear();
  }
  layout.run(url);
}

function receiveMessage (message) {
  if (message.data.type == 'error') {
    fail(message.data);
  }

  if (message.data.type == 'test') {
    layout.markTest(message.data);
  }

  if (message.data.type == 'end') {
    end(message.data);
  }
}

function fail (error) {
  socket.send({ fail: error, userAgent: navigator.userAgent });
  layout.addError(error);
}

function end (result) {
  socket.send({ userAgent: navigator.userAgent, result: result });

  if (!result.failed) layout.pass(result.passed);
  layout.list(result.tests);
}
<|endoftext|>


<commit_before>(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
!function(n,t){"use strict";var e=n("lodash");"function"!=typeof e.flow?"function"==typeof e.mixin?e.mixin({complement:e.negate}):e.constant=e.always:(e.any=e.some,e.complement=e.negate,e.compose=e.flowRight),Math.sign=Math.sign||function(n){return n=+n,0===n||isNaN(n)?n:n>0?1:-1},Math.trunc=Math.trunc||function(n){return Math.sign(n)*e.compose(Math.floor,Math.abs)(n)},Array.prototype.findIndex||(Array.prototype.findIndex=function(n){if(null===this)throw new TypeError("Array.prototype.findIndex called on null or undefined");if("function"!=typeof n)throw new TypeError("predicate must be a function");for(var t,e=Object(this),o=e.length,r=arguments[1],i=0;i<o;i++)if(t=e[i],n.call(r,t,i,e))return i;return-1}),t.common=n("./common"),t.geodetic=n("./geodetic")}(require,exports);
},{}]},{},[1]);
<commit_msg>New build<commit_after>(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
!function(n,t){"use strict";var e=n("lodash");"function"!=typeof e.flow?"function"==typeof e.mixin&&e.mixin({complement:e.negate}):(e.any=e.some,e.complement=e.negate,e.compose=e.flowRight),Math.sign=Math.sign||function(n){return n=+n,0===n||isNaN(n)?n:n>0?1:-1},Math.trunc=Math.trunc||function(n){return Math.sign(n)*e.compose(Math.floor,Math.abs)(n)},Array.prototype.findIndex||(Array.prototype.findIndex=function(n){if(null===this)throw new TypeError("Array.prototype.findIndex called on null or undefined");if("function"!=typeof n)throw new TypeError("predicate must be a function");for(var t,e=Object(this),o=e.length,r=arguments[1],i=0;i<o;i++)if(t=e[i],n.call(r,t,i,e))return i;return-1}),t.common=n("./common"),t.geodetic=n("./geodetic")}(require,exports);
},{}]},{},[1]);
<|endoftext|>


<commit_before>const Token = require('./../token/token').Token;
const Types = require('./../token/token').Types;

class Node {

    constructor(token) {
        this.token;
    }

    tokenLiteral() {
        this.token.literal;
    }
}

class Statement extends Node {
    statementNode() {
        return 'hotdog';
    }
}

class Expression extends Node {
    expressionNode() {
        return 'hotdog';
    }
}

class LetStatement extends Statement {
    constructor(token) {
        super(token);
        this.name; //Identifier
        this.value; //Expression
    }
}

module.exports = {
    LetStatement: LetStatement,
}<commit_msg>Added Identifier class to the the ast file.<commit_after>const Token = require('./../token/token').Token;
const Types = require('./../token/token').Types;

class Node {

    constructor(token) {
        this.token;
    }

    tokenLiteral() {
        this.token.literal;
    }
}

class Statement extends Node {
    statementNode() {
        return 'hotdog';
    }
}

class Expression extends Node {
    expressionNode() {
        return 'hotdog';
    }
}

class LetStatement extends Statement {
    constructor(token) {
        super(token);
        this.name; //Identifier
        this.value; //Expression
    }
}

class Identifier {
    constructor(t, string){
        this.token = t;
        this.value = string;
    }
}

module.exports = {
    LetStatement: LetStatement,
    Identifier: Identifier,
}<|endoftext|>


<commit_before>/*global cosh, tanh, toRadians*/

function getSpeedWithoutAirResistance(f_Res, weight, init_velo, terrain_length, points_max) {
    "use strict";
    var i = 0,
        acceleration = f_Res / weight,
        max_time = (-init_velo / acceleration) + Math.sqrt(init_velo * init_velo + 2 * acceleration * terrain_length / (acceleration * acceleration)),

        res = [];
    for (i; i <= points_max - 1; i = i + 1) {
        res[i] = {};
        res[i].time = max_time / (points_max) * (i + 1);
        res[i].speed = acceleration * res[i].time + init_velo;
        res[i].path = 0.5 * acceleration * res[i].time * res[i].time + init_velo * res[i].time;
    }
    res[res.length - 1].path = terrain_length;
    return res;
}

function getSpeedApproximateAirResistance(steps, f_Res, wheight, init_velo, terrain_length, area, density, cw, f_Gleit, f_Hangab) {
    "use strict";
    var i = 0,
        acceleration = f_Res / wheight,
        last_velo = init_velo,
        pastPath = 0,
        pastSpeed = 0,
        f_Air = 0,
        res = [];
    do {
        res[i] = {};
        res[i].time = (i + 1) * steps;
        res[i].speed = acceleration * steps + last_velo;
        res[i].path = pastPath + 0.5 * acceleration * steps * steps + last_velo * steps;
        last_velo = res[i].speed;
        f_Air = area * density * cw * res[i].speed * res[i].speed / 2;
        f_Res = f_Hangab - f_Air - f_Gleit;
        acceleration = f_Res / wheight;
        pastPath = res[i].path;
        i = i + 1;
    } while (res[res.length - 1].path < terrain_length);
    res[res.length - 1].path = terrain_length;

    return res;
}

function getWithAirResistance(steps, f_Res, weight, init_velo, area, density, cw, terrain_length) {
    "use strict";
    var i = 0,

        res = [];
    do {
        res[i] = {};
        res[i].time = (i + 1) * steps;
        res[i].speed = init_velo + Math.sqrt(f_Res / (0.5 * area * cw * density)) * tanh(res[i].time * Math.sqrt((f_Res / weight) * 0.5 * area * cw * density / weight));
        res[i].path = weight / (0.5 * area * cw * density) * Math.log(cosh(res[i].time * Math.sqrt((f_Res / weight) * 0.5 * area * cw * density / weight)));
        i = i + 1;
    } while (res[res.length - 1].path < terrain_length);
    res[res.length - 1].path = terrain_length;

    return res;
}

function analyze(requestJSon) {
    "use strict";
    var res = {
            forRequestID: requestJSon.requestID
        },
        f_Gewicht = 0,
        f_Hangab = 0,
        f_Normal = 0,

        f_Haft = 0,
        f_Gleit = 0,

        f_Air = 0,

        f_Res = 0;

    if (!isNaN(requestJSon.terrain.angle) && !isNaN(requestJSon.terrain.gravitation) && !isNaN(requestJSon.terrain.length) && !isNaN(requestJSon.subject.weight) && !isNaN(requestJSon.subject.area) && !isNaN(requestJSon.subject.cw) && !isNaN(requestJSon.subject.init_velo) && !isNaN(requestJSon.force) && !isNaN(requestJSon.resistance_stationary) && !isNaN(requestJSon.resistance_underway) && !isNaN(requestJSon.fluid.resitancy) && !isNaN(requestJSon.fluid.density) && !isNaN(requestJSon.points.max) && !isNaN(requestJSon.points.steps)) {
        f_Gewicht = requestJSon.subject.weight * requestJSon.terrain.gravitation; //Gewichtskraft in Newton [N]
        f_Hangab = f_Gewicht * Math.sin(toRadians(requestJSon.terrain.angle)); //Hangabtriebskraft in [N]
        f_Normal = f_Gewicht * Math.cos(toRadians(requestJSon.terrain.angle)); //Normalkraft in [N]

        f_Haft = f_Normal * requestJSon.resistance.stationary; //Haftreibungskraft in [N]
        f_Gleit = f_Normal * requestJSon.resistance.underway; //Gleitreibungskraft in [N]

        f_Air = requestJSon.subject.area * requestJSon.fluid.density * requestJSon.subject.cw * requestJSon.subject.init_velo * requestJSon.subject.init_velo / 2;

        f_Res = f_Hangab - f_Haft;

        if (requestJSon.subject.init_velo > 0 || f_Res > 0) {
            f_Res = f_Hangab - f_Gleit + requestJSon.subject.force;

            res.withoutAirResistance = getSpeedWithoutAirResistance(f_Res, requestJSon.subject.weight, requestJSon.subject.init_velo, requestJSon.terrain.length, requestJSon.points.max);

            f_Res = f_Hangab - f_Air - f_Haft;
            if (f_Res > 0) {
                f_Res = f_Hangab - f_Air - f_Gleit + requestJSon.subject.force;

                res.approximateAirResistance = getSpeedApproximateAirResistance(requestJSon.points.steps, f_Res, requestJSon.subject.weight, requestJSon.subject.init_velo, requestJSon.terrain.length, requestJSon.subject.area, requestJSon.fluid.density, requestJSon.subject.cw, f_Gleit, f_Hangab);

                f_Res = requestJSon.subject.force + f_Hangab - f_Gleit;
                res.withAirResistance = getWithAirResistance(requestJSon.points.steps, f_Res, requestJSon.subject.weight, requestJSon.subject.init_velo, requestJSon.subject.area, requestJSon.fluid.density, requestJSon.subject.cw, requestJSon.terrain.length);
            }
        }
    }
    if (res.approximateAirResistance === null) {
        res.approximateAirResistance = [];
        res.approximateAirResistance = [{
            speed: 0,
            path: 0,
            time: 0
        }];
    }

    if (res.withAirResistance === null) {
        res.withAirResistance = [{
            speed: 0,
            path: 0,
            time: 0
        }];
    }

    if (res.withoutAirResistance === null) {
        res.withoutAirResistance = [{
            speed: 0,
            path: 0,
            time: 0
        }];
    }

    return res;
}<commit_msg>fixed checks (doku was old)<commit_after>/*global cosh, tanh, toRadians*/

function getSpeedWithoutAirResistance(f_Res, weight, init_velo, terrain_length, points_max) {
    "use strict";
    var i = 0,
        acceleration = f_Res / weight,
        max_time = (-init_velo / acceleration) + Math.sqrt(init_velo * init_velo + 2 * acceleration * terrain_length / (acceleration * acceleration)),

        res = [];
    for (i; i <= points_max - 1; i = i + 1) {
        res[i] = {};
        res[i].time = max_time / (points_max) * (i + 1);
        res[i].speed = acceleration * res[i].time + init_velo;
        res[i].path = 0.5 * acceleration * res[i].time * res[i].time + init_velo * res[i].time;
    }
    res[res.length - 1].path = terrain_length;
    return res;
}

function getSpeedApproximateAirResistance(steps, f_Res, wheight, init_velo, terrain_length, area, density, cw, f_Gleit, f_Hangab) {
    "use strict";
    var i = 0,
        acceleration = f_Res / wheight,
        last_velo = init_velo,
        pastPath = 0,
        pastSpeed = 0,
        f_Air = 0,
        res = [];
    do {
        res[i] = {};
        res[i].time = (i + 1) * steps;
        res[i].speed = acceleration * steps + last_velo;
        res[i].path = pastPath + 0.5 * acceleration * steps * steps + last_velo * steps;
        last_velo = res[i].speed;
        f_Air = area * density * cw * res[i].speed * res[i].speed / 2;
        f_Res = f_Hangab - f_Air - f_Gleit;
        acceleration = f_Res / wheight;
        pastPath = res[i].path;
        i = i + 1;
    } while (res[res.length - 1].path < terrain_length);
    res[res.length - 1].path = terrain_length;

    return res;
}

function getWithAirResistance(steps, f_Res, weight, init_velo, area, density, cw, terrain_length) {
    "use strict";
    var i = 0,

        res = [];
    do {
        res[i] = {};
        res[i].time = (i + 1) * steps;
        res[i].speed = init_velo + Math.sqrt(f_Res / (0.5 * area * cw * density)) * tanh(res[i].time * Math.sqrt((f_Res / weight) * 0.5 * area * cw * density / weight));
        res[i].path = weight / (0.5 * area * cw * density) * Math.log(cosh(res[i].time * Math.sqrt((f_Res / weight) * 0.5 * area * cw * density / weight)));
        i = i + 1;
    } while (res[res.length - 1].path < terrain_length);
    res[res.length - 1].path = terrain_length;

    return res;
}

function analyze(requestJSon) {
    "use strict";
    var res = {
            forRequestID: requestJSon.requestID
        },
        f_Gewicht = 0,
        f_Hangab = 0,
        f_Normal = 0,

        f_Haft = 0,
        f_Gleit = 0,

        f_Air = 0,

        f_Res = 0;

    if (!isNaN(requestJSon.terrain.angle) && !isNaN(requestJSon.terrain.gravitation) && !isNaN(requestJSon.terrain.length) && !isNaN(requestJSon.subject.weight) && !isNaN(requestJSon.subject.area) && !isNaN(requestJSon.subject.cw) && !isNaN(requestJSon.subject.init_velo) && !isNaN(requestJSon.subject.force) && !isNaN(requestJSon.resistance.stationary) && !isNaN(requestJSon.resistance.underway) && !isNaN(requestJSon.fluid.density) && !isNaN(requestJSon.points.max) && !isNaN(requestJSon.points.steps)) {
        f_Gewicht = requestJSon.subject.weight * requestJSon.terrain.gravitation; //Gewichtskraft in Newton [N]
        f_Hangab = f_Gewicht * Math.sin(toRadians(requestJSon.terrain.angle)); //Hangabtriebskraft in [N]
        f_Normal = f_Gewicht * Math.cos(toRadians(requestJSon.terrain.angle)); //Normalkraft in [N]

        f_Haft = f_Normal * requestJSon.resistance.stationary; //Haftreibungskraft in [N]
        f_Gleit = f_Normal * requestJSon.resistance.underway; //Gleitreibungskraft in [N]

        f_Air = requestJSon.subject.area * requestJSon.fluid.density * requestJSon.subject.cw * requestJSon.subject.init_velo * requestJSon.subject.init_velo / 2;

        f_Res = f_Hangab - f_Haft;

        if (requestJSon.subject.init_velo > 0 || f_Res > 0) {
            f_Res = f_Hangab - f_Gleit + requestJSon.subject.force;

            res.withoutAirResistance = getSpeedWithoutAirResistance(f_Res, requestJSon.subject.weight, requestJSon.subject.init_velo, requestJSon.terrain.length, requestJSon.points.max);

            f_Res = f_Hangab - f_Air - f_Haft;
            if (f_Res > 0) {
                f_Res = f_Hangab - f_Air - f_Gleit + requestJSon.subject.force;

                res.approximateAirResistance = getSpeedApproximateAirResistance(requestJSon.points.steps, f_Res, requestJSon.subject.weight, requestJSon.subject.init_velo, requestJSon.terrain.length, requestJSon.subject.area, requestJSon.fluid.density, requestJSon.subject.cw, f_Gleit, f_Hangab);

                f_Res = requestJSon.subject.force + f_Hangab - f_Gleit;
                res.withAirResistance = getWithAirResistance(requestJSon.points.steps, f_Res, requestJSon.subject.weight, requestJSon.subject.init_velo, requestJSon.subject.area, requestJSon.fluid.density, requestJSon.subject.cw, requestJSon.terrain.length);
            }
        }
    }
    if (res.approximateAirResistance === null) {
        res.approximateAirResistance = [];
        res.approximateAirResistance = [{
            speed: 0,
            path: 0,
            time: 0
        }];
    }

    if (res.withAirResistance === null) {
        res.withAirResistance = [{
            speed: 0,
            path: 0,
            time: 0
        }];
    }

    if (res.withoutAirResistance === null) {
        res.withoutAirResistance = [{
            speed: 0,
            path: 0,
            time: 0
        }];
    }

    return res;
}<|endoftext|>


<commit_before>const BinaryPjax           = require('../../../../base/binary_pjax');
const showLocalTimeOnHover = require('../../../../base/clock').showLocalTimeOnHover;
const localize             = require('../../../../base/localize').localize;
const FlexTableUI          = require('../../../../common_functions/attach_dom/flextable');
const jpClient             = require('../../../../common_functions/country_base').jpClient;
const FormManager          = require('../../../../common_functions/form_manager');
const toTitleCase          = require('../../../../common_functions/string_util').toTitleCase;

const APIToken = (() => {
    'use strict';

    const hidden_class = 'invisible';
    const error_class  = 'errorfield';
    const form_id      = '#token_form';
    const max_tokens   = 30;

    let $table_container,
        $form;

    const onLoad = () => {
        if (jpClient()) {
            BinaryPjax.load('user/settingsws');
            return;
        }

        $table_container = $('#tokens_list');
        $form = $(form_id);

        BinarySocket.send({ api_token: 1 }).then(populateTokensList);

        const regex_msg = localize('Only [_1] are allowed.', [['letters', 'numbers', 'space', '_'].join(', ')]);
        FormManager.init(form_id, [
            { selector: '#txt_name',           request_field: 'new_token',        validations: ['req', ['regular', { regex: /^[\w\s]+$/, message: regex_msg }], ['length', { min: 2, max: 32 }]] },
            { selector: '[id*="chk_scopes_"]', request_field: 'new_token_scopes', validations: [['req', { message: localize('Please select at least one scope') }]], value: getScopes },

            { request_field: 'api_token', value: 1 },
        ]);
        FormManager.handleSubmit({
            form_selector       : form_id,
            fnc_response_handler: newTokenResponse,
            enable_button       : true,
        });
    };

    const newTokenResponse = (response) => {
        showSubmitSuccess('New token created.');
        $('#txt_name').val('');

        populateTokensList(response);
    };

    const getScopes = () => (
        $form.find('[id*="chk_scopes_"]:checked').map(function() { return $(this).val(); }).get()
    );

    // -----------------------
    // ----- Tokens List -----
    // -----------------------
    const populateTokensList = (response) => {
        if ('error' in response) {
            showErrorMessage(response.error.message);
            return;
        }

        clearMessages();

        const tokens = response.api_token.tokens;
        if (tokens.length === 0) {
            $table_container.addClass(hidden_class);
            return;
        } else if (tokens.length >= max_tokens) {
            $form.addClass(hidden_class);
            showErrorMessage(localize('The maximum number of tokens ([_1]) has been reached.', [max_tokens]));
        } else {
            $form.removeClass(hidden_class);
        }

        $table_container.removeClass(hidden_class).empty();

        const headers = ['Name', 'Token', 'Scopes', 'Last Used', 'Action'];
        FlexTableUI.init({
            id       : 'tokens_table',
            container: $table_container,
            header   : headers.map(localize),
            cols     : headers.map(title => title.toLowerCase().replace(/\s/g, '-')),
            data     : tokens,
            formatter: formatToken,
            style    : ($row, token) => {
                if (token.display_name === response.echo_req.new_token) {
                    $row.addClass('new');
                }
                $row.attr('id', token.token);
                createDeleteButton($row, token);
            },
        });
        showLocalTimeOnHover('td.last-used');
    };

    const createDeleteButton = ($row, token) => {
        const message = localize('Are you sure that you want to permanently delete token');
        const $button = $('<button/>', { class: 'button btn_delete', text: localize('Delete') });
        $button.click((e) => {
            e.preventDefault();
            e.stopPropagation();
            if (!window.confirm(`${message}: "${token.display_name}"?`)) {
                return;
            }
            deleteToken(token.token);
        });
        $row.children('.action').html($button);
    };

    const formatToken = (token) => {
        const last_used = (token.last_used ? token.last_used + ' GMT' : localize('Never Used'));
        const scopes = token.scopes.map(scope => localize(toTitleCase(scope))).join(', ');
        return [
            token.display_name,
            token.token,
            scopes,
            last_used,
            '',  // btn_delete
        ];
    };

    const deleteToken = (token) => {
        BinarySocket.send({
            api_token   : 1,
            delete_token: token,
        }).then((response) => {
            $(`#${response.echo_req.delete_token}`)
                .removeClass('new')
                .addClass('deleting')
                .fadeOut(700, function() {
                    $(this).remove();
                    populateTokensList(response);
                });
        });
    };

    // -----------------------------
    // ----- Message Functions -----
    // -----------------------------
    const showErrorMessage = (msg) => {
        $('#token_message').removeClass(hidden_class)
            .find('p')
            .attr('class', error_class)
            .html(localize(msg));
    };

    const showSubmitSuccess = (msg) => {
        $('#msg_form')
            .attr('class', 'success-msg')
            .html('

' + localize(msg) + '

')
            .css('display', 'block')
            .delay(3000)
            .fadeOut(1000);
    };

    const clearMessages = () => {
        $('#token_message').addClass(hidden_class);
    };

    return {
        onLoad: onLoad,
    };
})();

module.exports = APIToken;
<commit_msg>Display 'new token created' when no error in response<commit_after>const BinaryPjax           = require('../../../../base/binary_pjax');
const showLocalTimeOnHover = require('../../../../base/clock').showLocalTimeOnHover;
const localize             = require('../../../../base/localize').localize;
const FlexTableUI          = require('../../../../common_functions/attach_dom/flextable');
const jpClient             = require('../../../../common_functions/country_base').jpClient;
const FormManager          = require('../../../../common_functions/form_manager');
const toTitleCase          = require('../../../../common_functions/string_util').toTitleCase;

const APIToken = (() => {
    'use strict';

    const hidden_class = 'invisible';
    const error_class  = 'errorfield';
    const form_id      = '#token_form';
    const max_tokens   = 30;

    let $table_container,
        $form;

    const onLoad = () => {
        if (jpClient()) {
            BinaryPjax.load('user/settingsws');
            return;
        }

        $table_container = $('#tokens_list');
        $form = $(form_id);

        BinarySocket.send({ api_token: 1 }).then(populateTokensList);

        const regex_msg = localize('Only [_1] are allowed.', [['letters', 'numbers', 'space', '_'].join(', ')]);
        FormManager.init(form_id, [
            { selector: '#txt_name',           request_field: 'new_token',        validations: ['req', ['regular', { regex: /^[\w\s]+$/, message: regex_msg }], ['length', { min: 2, max: 32 }]] },
            { selector: '[id*="chk_scopes_"]', request_field: 'new_token_scopes', validations: [['req', { message: localize('Please select at least one scope') }]], value: getScopes },

            { request_field: 'api_token', value: 1 },
        ]);
        FormManager.handleSubmit({
            form_selector       : form_id,
            fnc_response_handler: newTokenResponse,
            enable_button       : true,
        });
    };

    const newTokenResponse = (response) => {
        if (!response.error) showSubmitSuccess('New token created.');
        $('#txt_name').val('');

        populateTokensList(response);
    };

    const getScopes = () => (
        $form.find('[id*="chk_scopes_"]:checked').map(function() { return $(this).val(); }).get()
    );

    // -----------------------
    // ----- Tokens List -----
    // -----------------------
    const populateTokensList = (response) => {
        if ('error' in response) {
            showErrorMessage(response.error.message);
            return;
        }

        clearMessages();

        const tokens = response.api_token.tokens;
        if (tokens.length === 0) {
            $table_container.addClass(hidden_class);
            return;
        } else if (tokens.length >= max_tokens) {
            $form.addClass(hidden_class);
            showErrorMessage(localize('The maximum number of tokens ([_1]) has been reached.', [max_tokens]));
        } else {
            $form.removeClass(hidden_class);
        }

        $table_container.removeClass(hidden_class).empty();

        const headers = ['Name', 'Token', 'Scopes', 'Last Used', 'Action'];
        FlexTableUI.init({
            id       : 'tokens_table',
            container: $table_container,
            header   : headers.map(localize),
            cols     : headers.map(title => title.toLowerCase().replace(/\s/g, '-')),
            data     : tokens,
            formatter: formatToken,
            style    : ($row, token) => {
                if (token.display_name === response.echo_req.new_token) {
                    $row.addClass('new');
                }
                $row.attr('id', token.token);
                createDeleteButton($row, token);
            },
        });
        showLocalTimeOnHover('td.last-used');
    };

    const createDeleteButton = ($row, token) => {
        const message = localize('Are you sure that you want to permanently delete token');
        const $button = $('<button/>', { class: 'button btn_delete', text: localize('Delete') });
        $button.click((e) => {
            e.preventDefault();
            e.stopPropagation();
            if (!window.confirm(`${message}: "${token.display_name}"?`)) {
                return;
            }
            deleteToken(token.token);
        });
        $row.children('.action').html($button);
    };

    const formatToken = (token) => {
        const last_used = (token.last_used ? token.last_used + ' GMT' : localize('Never Used'));
        const scopes = token.scopes.map(scope => localize(toTitleCase(scope))).join(', ');
        return [
            token.display_name,
            token.token,
            scopes,
            last_used,
            '',  // btn_delete
        ];
    };

    const deleteToken = (token) => {
        BinarySocket.send({
            api_token   : 1,
            delete_token: token,
        }).then((response) => {
            $(`#${response.echo_req.delete_token}`)
                .removeClass('new')
                .addClass('deleting')
                .fadeOut(700, function() {
                    $(this).remove();
                    populateTokensList(response);
                });
        });
    };

    // -----------------------------
    // ----- Message Functions -----
    // -----------------------------
    const showErrorMessage = (msg) => {
        $('#token_message').removeClass(hidden_class)
            .find('p')
            .attr('class', error_class)
            .html(localize(msg));
    };

    const showSubmitSuccess = (msg) => {
        $('#msg_form')
            .attr('class', 'success-msg')
            .html('

' + localize(msg) + '

')
            .css('display', 'block')
            .delay(3000)
            .fadeOut(1000);
    };

    const clearMessages = () => {
        $('#token_message').addClass(hidden_class);
    };

    return {
        onLoad: onLoad,
    };
})();

module.exports = APIToken;
<|endoftext|>


<commit_before>(function ($) {
var tooltip_references, initReferenceTooltip;

  function getMediaCoverageCount(almData) {
    if(almData.sources !== undefined) {
      for (var i = 0; i < almData.sources.length; i++) {
        if (almData.sources[i].name == 'articlecoveragecurated') {
          return almData.sources[i].metrics.total;
        }
      }
    }
    return 0;
  }

  function addMediaCoverageLink() {
    var $media = $('#nav-media');
    if ($media.length) {
      var doi = $media.data('doi');
      $media.getArticleSummary(doi,
        function (data) {
          var mediaCoverageCount = getMediaCoverageCount(data);
          $media.find('#media-coverage-count').text('(' + mediaCoverageCount + ')');
        }, function() {
          //todo: error handling
        });
    }
  }

  /// write article nav
  var $article = $('.article-content');

  $('#nav-article').buildNav({
    content: $article
  });

  $('#nav-article').floatingNav({
    content: $article
  });

  addMediaCoverageLink();
  figshareWidget();

  var hasFigures = $('#artText .figure').length;

  if(hasFigures){

    $('#figure-carousel-section').buildFigureCarousel({});

  };

  function formatHumanReadableByteSize(bytes) {
    // Space before "Bytes". All others are concatenated to number with no space.
    var units = [' Bytes', 'KB', 'MB', 'GB', 'TB', 'PB'];

    var increment = 1000; // could change to 1024
    var roundingThreshold = units.indexOf('MB'); // for smaller units than this, show integers
    var precision = 100; // round to this precision if unit is >= roundingThreshold

    var n = bytes;
    var unitIndex = 0;
    for (; unitIndex < units.length; unitIndex++) {
      if (n >= increment) {
        n /= increment;
      } else break;
    }

    n = (unitIndex < roundingThreshold) ? Math.round(n) : Math.round(n * precision) / precision;

    return n + units[unitIndex];
  }

  // Will be invoked directly from article HTML, where the templating engine will inject the fileSizeTable data.
  $.fn.populateFileSizes = function (fileSizeTable) {

    if(hasFigures){
      $('.file-size').each(function (index, element) {
        var $el = $(element);
        var doi = $el.attr('data-doi');
        var fileSize = $el.attr('data-size');
        var size = fileSizeTable[ doi][ /**/fileSize];
        $el.text('(' + formatHumanReadableByteSize(size) + ')');
      });
    }
  };

  $('.table-download').on('click', function(){
    var table = $(this).parent(),
      figId = $(this).data('tableopen');
    return tableOpen(figId, "CSV", table);
  });

  $('.table-wrap .expand').on('click', function(){
    var table = $(this).parent(),
      figId = $(this).data('tableopen');
    return tableOpen(figId, "HTML", table);
  });

// tooltips for the links to references in the article body eg '[4]'
  tooltip_references = function () {

    function removeBrackets(content) {
      var contentReady;

      var checkFirst = content.indexOf('[');
      var checkLast = content.indexOf(']');

      if (checkFirst === -1 && checkLast === -1) {

        contentReady = content;
      } else if (checkFirst === 0 && checkLast === -1) {

        contentReady = content.slice(1);
      } else if (checkFirst === -1 && checkLast !== -1) {

        contentReady = content.slice(0,-1);
      } else {

        contentReady = content.slice(1,-1);
      }
      return contentReady;

    }

    function slice_o_matic(copy, charFind, sliceStart, sliceEnd){
      var checky = copy.indexOf(charFind);
      var contentReady;

      if (checky === -1) {

        contentReady = copy;
        return contentReady;
      } else {

        sliceEnd = checky - sliceEnd;
        contentReady = copy.slice(sliceStart, sliceEnd);
        return contentReady;
      }

    }

  $('.ref-tip').hover(
    function () {
      var $ref_link = $(this);  // hovered over link
      var $position = $ref_link.position(); // find out where it is so the tooltip can show up above it
      var $link_width = $ref_link.width();
      var ref_number = $ref_link.text();
      ref_number = removeBrackets(ref_number);

      var ref_label = '#ref' + ref_number;  // form the References section li id eg 'id=ref4'
      var matching_ref = $(ref_label).html(); // get the reference content
      matching_ref = slice_o_matic(matching_ref, 'reflinks', 0, 11);

      var $ref_tooltip = $('.ref-tooltip');  //find the tooltip div
      var $ref_content = $ref_tooltip.find('.ref_tooltip-content').html(matching_ref); //add the references content
      var $ref_link_top = $position.top;
      var $ref_link_left = $position.left;
      var $tooltip_height = $ref_tooltip.height();
      var $tooltip_width = $ref_tooltip.width();

      $ref_link_top = ($ref_link_top - $tooltip_height)-20;//top of ref link - height of the tooltip - 20px margin
      //left position of ref link - tooltip width - link width/2 so can center over link:
      $ref_link_left = $ref_link_left - ($tooltip_width - $link_width)/2;

      $ref_tooltip.css({ //place the tooltip 20px above & centered over the ref link
        'top': $ref_link_top,
        'left': $ref_link_left}).html($ref_content).fadeIn('fast');
    },
    function () {
      $('.ref-tooltip').fadeOut('fast');
    });
  };
  initReferenceTooltip = tooltip_references();

})(jQuery);
<commit_msg>DPRO-3065 - Remove old figshare call in article body js<commit_after>(function ($) {
var tooltip_references, initReferenceTooltip;

  function getMediaCoverageCount(almData) {
    if(almData.sources !== undefined) {
      for (var i = 0; i < almData.sources.length; i++) {
        if (almData.sources[i].name == 'articlecoveragecurated') {
          return almData.sources[i].metrics.total;
        }
      }
    }
    return 0;
  }

  function addMediaCoverageLink() {
    var $media = $('#nav-media');
    if ($media.length) {
      var doi = $media.data('doi');
      $media.getArticleSummary(doi,
        function (data) {
          var mediaCoverageCount = getMediaCoverageCount(data);
          $media.find('#media-coverage-count').text('(' + mediaCoverageCount + ')');
        }, function() {
          //todo: error handling
        });
    }
  }

  /// write article nav
  var $article = $('.article-content');

  $('#nav-article').buildNav({
    content: $article
  });

  $('#nav-article').floatingNav({
    content: $article
  });

  addMediaCoverageLink();

  var hasFigures = $('#artText .figure').length;

  if(hasFigures){

    $('#figure-carousel-section').buildFigureCarousel({});

  };

  function formatHumanReadableByteSize(bytes) {
    // Space before "Bytes". All others are concatenated to number with no space.
    var units = [' Bytes', 'KB', 'MB', 'GB', 'TB', 'PB'];

    var increment = 1000; // could change to 1024
    var roundingThreshold = units.indexOf('MB'); // for smaller units than this, show integers
    var precision = 100; // round to this precision if unit is >= roundingThreshold

    var n = bytes;
    var unitIndex = 0;
    for (; unitIndex < units.length; unitIndex++) {
      if (n >= increment) {
        n /= increment;
      } else break;
    }

    n = (unitIndex < roundingThreshold) ? Math.round(n) : Math.round(n * precision) / precision;

    return n + units[unitIndex];
  }

  // Will be invoked directly from article HTML, where the templating engine will inject the fileSizeTable data.
  $.fn.populateFileSizes = function (fileSizeTable) {

    if(hasFigures){
      $('.file-size').each(function (index, element) {
        var $el = $(element);
        var doi = $el.attr('data-doi');
        var fileSize = $el.attr('data-size');
        var size = fileSizeTable[ doi][ /**/fileSize];
        $el.text('(' + formatHumanReadableByteSize(size) + ')');
      });
    }
  };

  $('.table-download').on('click', function(){
    var table = $(this).parent(),
      figId = $(this).data('tableopen');
    return tableOpen(figId, "CSV", table);
  });

  $('.table-wrap .expand').on('click', function(){
    var table = $(this).parent(),
      figId = $(this).data('tableopen');
    return tableOpen(figId, "HTML", table);
  });

// tooltips for the links to references in the article body eg '[4]'
  tooltip_references = function () {

    function removeBrackets(content) {
      var contentReady;

      var checkFirst = content.indexOf('[');
      var checkLast = content.indexOf(']');

      if (checkFirst === -1 && checkLast === -1) {

        contentReady = content;
      } else if (checkFirst === 0 && checkLast === -1) {

        contentReady = content.slice(1);
      } else if (checkFirst === -1 && checkLast !== -1) {

        contentReady = content.slice(0,-1);
      } else {

        contentReady = content.slice(1,-1);
      }
      return contentReady;

    }

    function slice_o_matic(copy, charFind, sliceStart, sliceEnd){
      var checky = copy.indexOf(charFind);
      var contentReady;

      if (checky === -1) {

        contentReady = copy;
        return contentReady;
      } else {

        sliceEnd = checky - sliceEnd;
        contentReady = copy.slice(sliceStart, sliceEnd);
        return contentReady;
      }

    }

  $('.ref-tip').hover(
    function () {
      var $ref_link = $(this);  // hovered over link
      var $position = $ref_link.position(); // find out where it is so the tooltip can show up above it
      var $link_width = $ref_link.width();
      var ref_number = $ref_link.text();
      ref_number = removeBrackets(ref_number);

      var ref_label = '#ref' + ref_number;  // form the References section li id eg 'id=ref4'
      var matching_ref = $(ref_label).html(); // get the reference content
      matching_ref = slice_o_matic(matching_ref, 'reflinks', 0, 11);

      var $ref_tooltip = $('.ref-tooltip');  //find the tooltip div
      var $ref_content = $ref_tooltip.find('.ref_tooltip-content').html(matching_ref); //add the references content
      var $ref_link_top = $position.top;
      var $ref_link_left = $position.left;
      var $tooltip_height = $ref_tooltip.height();
      var $tooltip_width = $ref_tooltip.width();

      $ref_link_top = ($ref_link_top - $tooltip_height)-20;//top of ref link - height of the tooltip - 20px margin
      //left position of ref link - tooltip width - link width/2 so can center over link:
      $ref_link_left = $ref_link_left - ($tooltip_width - $link_width)/2;

      $ref_tooltip.css({ //place the tooltip 20px above & centered over the ref link
        'top': $ref_link_top,
        'left': $ref_link_left}).html($ref_content).fadeIn('fast');
    },
    function () {
      $('.ref-tooltip').fadeOut('fast');
    });
  };
  initReferenceTooltip = tooltip_references();

})(jQuery);
<|endoftext|>


<commit_before>/* global _ */
'use strict';

angular.module('metadatamanagementApp').service('ShoppingCartService',
  function(OrderResource, StudyResource, localStorageService,
           SimpleMessageToastService, $rootScope) {

    var SHOPPING_CART_KEY = 'shoppingCart';
    var ORDER_ID_KEY = 'shoppingCart.orderId';
    var VERSION_KEY = 'shoppingCart.version';

    var products = localStorageService.get(SHOPPING_CART_KEY) || [];
    var orderId = localStorageService.get(ORDER_ID_KEY);
    var version = localStorageService.get(VERSION_KEY);

    var _incrementOrderVersion = function() {
      version = version + 1;
      localStorageService.set(VERSION_KEY, version);
    };

    var _broadcastShoppingCartChanged = function() {
      $rootScope.$broadcast('shopping-cart-changed', products.length);
    };

    var _displayUpdateOrderError = function() {
      SimpleMessageToastService.openAlertMessageToast(
        'shopping-cart.toasts.error-on-saving-order');
    };

    var _displayProductAlreadyInShoppingCart = function(product) {
      SimpleMessageToastService.openSimpleMessageToast(
        'shopping-cart.toasts.study-already-in-cart',
        {id: product.study.id}
      );
    };

    var _isProductInShoppingCart = function(products, product) {
      return _.findIndex(products, function(item) {
        return item.study.id === product.study.id &&
          item.version === product.version;
      }) !== -1;
    };

    var _addProductToLocalShoppingCart = function(product) {
      if (_isProductInShoppingCart(products, product)) {
        _displayProductAlreadyInShoppingCart(product);
      } else {
        products.push(product);
        localStorageService.set(SHOPPING_CART_KEY, products);
        SimpleMessageToastService.openSimpleMessageToast(
          'shopping-cart.toasts.study-added',
          {id: product.study.id});
        _broadcastShoppingCartChanged();
      }
    };

    var _removeProductFromLocalShoppingCart = function(product) {
      _.remove(products, function(item) {
        return angular.equals(item, product);
      });
      localStorageService.set(SHOPPING_CART_KEY, products);
      _broadcastShoppingCartChanged();
    };

    var _clearLocalShoppingCart = function() {
      products = [];
      localStorageService.set(SHOPPING_CART_KEY, products);
      _broadcastShoppingCartChanged();
    };

    var _addProductToExistingOrder = function(product) {
      OrderResource.get({id: orderId}).$promise.then(function(order) {
        if (_isProductInShoppingCart(products, product)) {
          _displayProductAlreadyInShoppingCart(product);
        } else {
          StudyResource.get({id: product.study.id}).$promise
            .then(function(study) {
              var newProduct = {
                dataAcquisitionProjectId: product.dataAcquisitionProjectId,
                study: study,
                accessWay: product.accessWay,
                version: product.version
              };

              order.products.push(newProduct);
              OrderResource.update(order).$promise
                .then(function() {
                    _incrementOrderVersion();
                    _addProductToLocalShoppingCart(product);
                  },
                  _displayUpdateOrderError);
            }, _displayUpdateOrderError);
        }
      }, _displayUpdateOrderError);
    };

    var _removeProductFromExistingOrder = function(product) {
      OrderResource.get({id: orderId}).$promise.then(function(order) {
        var removed = _.remove(order.products, function(productInOrder) {
          return productInOrder.study.id === product.study.id &&
            productInOrder.version === product.version;
        });

        if (removed.length > 0) {
          OrderResource.update(order).$promise
            .then(function() {
                _incrementOrderVersion();
                _removeProductFromLocalShoppingCart(product);
              },
              _displayUpdateOrderError);
        }
      }, _displayUpdateOrderError);
    };

    var _clearProductsFromExistingOrder = function() {
      OrderResource.get({id: orderId}).$promise.then(function(order) {
        order.products = [];
        return OrderResource.update(order).$promise
          .then(function() {
            _incrementOrderVersion();
            _clearLocalShoppingCart();
          }, _displayUpdateOrderError);
      }, _displayUpdateOrderError);
    };

    var add = function(product) {
      if (orderId) {
        _addProductToExistingOrder(product);
      } else {
        _addProductToLocalShoppingCart(product);
      }
    };

    var remove = function(product) {
      if (orderId) {
        _removeProductFromExistingOrder(product);
      } else {
        _removeProductFromLocalShoppingCart(product);
      }
    };

    var clearProducts = function() {
      if (orderId) {
        _clearProductsFromExistingOrder();
      } else {
        _clearLocalShoppingCart();
      }
    };

    var getProducts = function() {
      return _.cloneDeep(products);
    };

    var count = function() {
      return products.length;
    };

    var initShoppingCartProducts = function(initProducts, initOrderId,
                                            initVersion) {
      var copy = _.cloneDeep(initProducts);
      localStorageService.set(SHOPPING_CART_KEY, copy);
      localStorageService.set(ORDER_ID_KEY, initOrderId);
      localStorageService.set(VERSION_KEY, initVersion);
      orderId = initOrderId;
      products = copy;
      version = initVersion;
      _broadcastShoppingCartChanged();
    };

    var migrateStoredData = function() {
      var storedProducts = this.getProducts();
      var migratedProducts = [];
      storedProducts.forEach(function(product) {
        if (_.has(product, 'projectId')) {
          var newProduct = {
            dataAcquisitionProjectId: product.projectId,
            accessWay: product.accessWay,
            version: product.version,
            study: {
              id: product.studyId
            }
          };
          migratedProducts.push(newProduct);
        } else {
          migratedProducts.push(product);
        }
      });
      localStorageService.set(SHOPPING_CART_KEY, migratedProducts);
      products = migratedProducts;
    };

    var clearOrderData = function() {
      orderId = '';
      localStorageService.set(ORDER_ID_KEY, orderId);
      version = '';
      localStorageService.set(VERSION_KEY, version);
    };

    var completeOrder = function() {
      clearOrderData();
      _clearLocalShoppingCart();
    };

    var getOrderId = function() {
      return orderId;
    };

    var getVersion = function() {
      return version;
    };

    return {
      add: add,
      remove: remove,
      getProducts: getProducts,
      count: count,
      clearLocalOrderId: clearOrderData,
      clearProducts: clearProducts,
      completeOrder: completeOrder,
      initShoppingCartProducts: initShoppingCartProducts,
      migrateStoredData: migrateStoredData,
      getOrderId: getOrderId,
      getVersion: getVersion
    };
  });
<commit_msg>Include accessWay to determine if product is already in shopping cart or which one to remove.<commit_after>/* global _ */
'use strict';

angular.module('metadatamanagementApp').service('ShoppingCartService',
  function(OrderResource, StudyResource, localStorageService,
           SimpleMessageToastService, $rootScope) {

    var SHOPPING_CART_KEY = 'shoppingCart';
    var ORDER_ID_KEY = 'shoppingCart.orderId';
    var VERSION_KEY = 'shoppingCart.version';

    var products = localStorageService.get(SHOPPING_CART_KEY) || [];
    var orderId = localStorageService.get(ORDER_ID_KEY);
    var version = localStorageService.get(VERSION_KEY);

    var _incrementOrderVersion = function() {
      version = version + 1;
      localStorageService.set(VERSION_KEY, version);
    };

    var _broadcastShoppingCartChanged = function() {
      $rootScope.$broadcast('shopping-cart-changed', products.length);
    };

    var _displayUpdateOrderError = function() {
      SimpleMessageToastService.openAlertMessageToast(
        'shopping-cart.toasts.error-on-saving-order');
    };

    var _displayProductAlreadyInShoppingCart = function(product) {
      SimpleMessageToastService.openSimpleMessageToast(
        'shopping-cart.toasts.study-already-in-cart',
        {id: product.study.id}
      );
    };

    var _isProductInShoppingCart = function(products, product) {
      return _.findIndex(products, function(item) {
        return item.study.id === product.study.id &&
          item.version === product.version &&
          item.accessWay === product.accessWay;
      }) !== -1;
    };

    var _addProductToLocalShoppingCart = function(product) {
      if (_isProductInShoppingCart(products, product)) {
        _displayProductAlreadyInShoppingCart(product);
      } else {
        products.push(product);
        localStorageService.set(SHOPPING_CART_KEY, products);
        SimpleMessageToastService.openSimpleMessageToast(
          'shopping-cart.toasts.study-added',
          {id: product.study.id});
        _broadcastShoppingCartChanged();
      }
    };

    var _removeProductFromLocalShoppingCart = function(product) {
      _.remove(products, function(item) {
        return angular.equals(item, product);
      });
      localStorageService.set(SHOPPING_CART_KEY, products);
      _broadcastShoppingCartChanged();
    };

    var _clearLocalShoppingCart = function() {
      products = [];
      localStorageService.set(SHOPPING_CART_KEY, products);
      _broadcastShoppingCartChanged();
    };

    var _addProductToExistingOrder = function(product) {
      OrderResource.get({id: orderId}).$promise.then(function(order) {
        if (_isProductInShoppingCart(products, product)) {
          _displayProductAlreadyInShoppingCart(product);
        } else {
          StudyResource.get({id: product.study.id}).$promise
            .then(function(study) {
              var newProduct = {
                dataAcquisitionProjectId: product.dataAcquisitionProjectId,
                study: study,
                accessWay: product.accessWay,
                version: product.version
              };

              order.products.push(newProduct);
              OrderResource.update(order).$promise
                .then(function() {
                    _incrementOrderVersion();
                    _addProductToLocalShoppingCart(product);
                  },
                  _displayUpdateOrderError);
            }, _displayUpdateOrderError);
        }
      }, _displayUpdateOrderError);
    };

    var _removeProductFromExistingOrder = function(product) {
      OrderResource.get({id: orderId}).$promise.then(function(order) {
        var removed = _.remove(order.products, function(productInOrder) {
          return productInOrder.study.id === product.study.id &&
            productInOrder.version === product.version &&
          productInOrder.accessWay === product.accessWay;
        });

        if (removed.length > 0) {
          OrderResource.update(order).$promise
            .then(function() {
                _incrementOrderVersion();
                _removeProductFromLocalShoppingCart(product);
              },
              _displayUpdateOrderError);
        }
      }, _displayUpdateOrderError);
    };

    var _clearProductsFromExistingOrder = function() {
      OrderResource.get({id: orderId}).$promise.then(function(order) {
        order.products = [];
        return OrderResource.update(order).$promise
          .then(function() {
            _incrementOrderVersion();
            _clearLocalShoppingCart();
          }, _displayUpdateOrderError);
      }, _displayUpdateOrderError);
    };

    var add = function(product) {
      if (orderId) {
        _addProductToExistingOrder(product);
      } else {
        _addProductToLocalShoppingCart(product);
      }
    };

    var remove = function(product) {
      if (orderId) {
        _removeProductFromExistingOrder(product);
      } else {
        _removeProductFromLocalShoppingCart(product);
      }
    };

    var clearProducts = function() {
      if (orderId) {
        _clearProductsFromExistingOrder();
      } else {
        _clearLocalShoppingCart();
      }
    };

    var getProducts = function() {
      return _.cloneDeep(products);
    };

    var count = function() {
      return products.length;
    };

    var initShoppingCartProducts = function(initProducts, initOrderId,
                                            initVersion) {
      var copy = _.cloneDeep(initProducts);
      localStorageService.set(SHOPPING_CART_KEY, copy);
      localStorageService.set(ORDER_ID_KEY, initOrderId);
      localStorageService.set(VERSION_KEY, initVersion);
      orderId = initOrderId;
      products = copy;
      version = initVersion;
      _broadcastShoppingCartChanged();
    };

    var migrateStoredData = function() {
      var storedProducts = this.getProducts();
      var migratedProducts = [];
      storedProducts.forEach(function(product) {
        if (_.has(product, 'projectId')) {
          var newProduct = {
            dataAcquisitionProjectId: product.projectId,
            accessWay: product.accessWay,
            version: product.version,
            study: {
              id: product.studyId
            }
          };
          migratedProducts.push(newProduct);
        } else {
          migratedProducts.push(product);
        }
      });
      localStorageService.set(SHOPPING_CART_KEY, migratedProducts);
      products = migratedProducts;
    };

    var clearOrderData = function() {
      orderId = '';
      localStorageService.set(ORDER_ID_KEY, orderId);
      version = '';
      localStorageService.set(VERSION_KEY, version);
    };

    var completeOrder = function() {
      clearOrderData();
      _clearLocalShoppingCart();
    };

    var getOrderId = function() {
      return orderId;
    };

    var getVersion = function() {
      return version;
    };

    return {
      add: add,
      remove: remove,
      getProducts: getProducts,
      count: count,
      clearLocalOrderId: clearOrderData,
      clearProducts: clearProducts,
      completeOrder: completeOrder,
      initShoppingCartProducts: initShoppingCartProducts,
      migrateStoredData: migrateStoredData,
      getOrderId: getOrderId,
      getVersion: getVersion
    };
  });
<|endoftext|>


<commit_before>/**
 * @file The starting point of Bastion
 * @author Sankarsan Kampa (a.k.a k3rn31p4nic)
 * @license MIT
 */

const Discord = require('discord.js');
const BASTION = new Discord.Client({
  disabledEvents: [
    'USER_NOTE_UPDATE',
    'TYPING_START',
    'RELATIONSHIP_ADD',
    'RELATIONSHIP_REMOVE'
  ]
});

BASTION.package = require('./package.json');
BASTION.credentials = require('./settings/credentials.json');
BASTION.config = require('./settings/config.json');
BASTION.colors = require('./settings/colors.json');
BASTION.commands = new Discord.Collection();
BASTION.aliases = new Discord.Collection();

/** Log handler */
require('./handlers/logHandler')(BASTION);
/** Event handler */
require('./handlers/eventHandler')(BASTION);
/** Module handler */
require('./handlers/moduleHandler')(BASTION);

// Will use after updating to `discord.js v11.2.0+` as `discord.js v11.1.0` has problems with send() when using array prototypes
// require('./functions/Array.prototype');

BASTION.login(BASTION.credentials.token).catch(e => {
  BASTION.log.error(e.stack);
});

process.on('unhandledRejection', rejection => {
  // eslint-disable-next-line no-console
  console.warn('\n[unhandledRejection]\n\n', rejection, '\n\n[/unhandledRejection]\n');
});
<commit_msg>Added comments<commit_after>/**
 * @file The starting point of Bastion
 * @author Sankarsan Kampa (a.k.a k3rn31p4nic)
 * @license MIT
 */

const Discord = require('discord.js');
const BASTION = new Discord.Client({
  disabledEvents: [
    'USER_NOTE_UPDATE',
    'TYPING_START',
    'RELATIONSHIP_ADD',
    'RELATIONSHIP_REMOVE'
  ]
});

/**
 * Add necessary files as a global object.
 */
BASTION.package = require('./package.json');
BASTION.credentials = require('./settings/credentials.json');
BASTION.config = require('./settings/config.json');
BASTION.colors = require('./settings/colors.json');
BASTION.commands = new Discord.Collection();
BASTION.aliases = new Discord.Collection();

/**
 * Log handler
 */
require('./handlers/logHandler')(BASTION);
/**
 * Event handler
 */
require('./handlers/eventHandler')(BASTION);
/**
 * Module handler
 */
require('./handlers/moduleHandler')(BASTION);

// Will use after updating to `discord.js v11.2.0+` as `discord.js v11.1.0` has problems with send() when using array prototypes
// require('./functions/Array.prototype');

/**
 * Log Bastion in as a Discord client.
 */
BASTION.login(BASTION.credentials.token).catch(e => {
  BASTION.log.error(e.stack);
});

/**
 * Handle unhandled rejections
 */
process.on('unhandledRejection', rejection => {
  // eslint-disable-next-line no-console
  console.warn('\n[unhandledRejection]\n\n', rejection, '\n\n[/unhandledRejection]\n');
});
<|endoftext|>


<commit_before>var NorrisBot = require('../lib/norrisbot');

var token = process.env.BOT_API_KEY;
var dbPath = process.env.BOT_DB_PATH;
var name = process.env.BOT_NAME;

var norrisbot = new NorrisBot({
    token: token,
    dbPath: dbPath,
    name: name
});

norrisbot.run();
socket = io.listen(process.env.PORT);
<commit_msg>Removed socket<commit_after>var NorrisBot = require('../lib/norrisbot');

var token = process.env.BOT_API_KEY;
var dbPath = process.env.BOT_DB_PATH;
var name = process.env.BOT_NAME;

var norrisbot = new NorrisBot({
    token: token,
    dbPath: dbPath,
    name: name
});

norrisbot.run();
<|endoftext|>


<commit_before>#!/usr/bin/env node

// Dependencies
var geddy = require('../lib/geddy')
  , exec = require('child_process').exec
  , path = require('path')
  , utils = require('utilities')
  , parseopts = require('../lib/parseopts');

// Variables
var cwd = process.cwd()
  , args = process.argv.slice(2)
  , parser
  , optsMap
  , cmds
  , opts
  , usage
  , cmd
  , engineCmd
  , modelCmd
  , filepath
  , die
  , start;

// Usage dialog
usage = [
    'Geddy web framework for Node.js'
  , ''
  , 'Usage:'
  , '  geddy [options/commands] [arguments]'
  , ''
  , 'Options:'
  , '  --environment, -e   Environment to use'
  , '  --port, -p          Port to connect to'
  , '  --workers, -w       Number of worker processes to start(Default: 2)'
  , '  --debug, -d         Sets the log level to output debug messages to'
  , '                        the console'
  , '  --jade, -j          When generating views this will create Jade'
  , '                        templates(Default: EJS)'
  , '  --handle, -H        When generating views this will create Handlebars'
  , '                        templates(Default: EJS)'
  , '  --mustache, -m      When generating views this will create Mustache'
  , '                        templates(Default: EJS)'
  , '  --help, -h          Output this usage dialog'
  , '  --version, -v       Output the version of Geddy that\'s installed'
  , ''
  , 'Commands:'
  , '  app <name>                  Create a new Geddy application'
  , '  resource <name> [attrs]     Create a new resource. A resource includes'
  , '                                a model, controller and route'
  , '  scaffold <name> [attrs]     Create a new scaffolding. Scaffolding includes'
  , '                                the views, a model, controller and route'
  , '  secret                      Generate a new application secret in'
  , '                                `congig/environment`'
  , '  controller <name>          Generate a new controller including an index view'
  , '                                and and a route'
  , '  model <name> [attrs]        Generate a new model'
  , ''
  , 'Examples:'
  , '  geddy                    Start Geddy on localhost:4000 in development mode'
  , '                             or if the directory isn\'t a Geddy app it\'ll'
  , '                             this usage dialog'
  , '  geddy -p 3000            Start Geddy on port 3000'
  , '  geddy -e production      Start Geddy in production mode'
  , '  geddy -j scaffold user   Generate a users scaffolding using Jade templates'
  , '  geddy resource user name admin:boolean'
  , '                           Generate a users resource with the model properties'
  , '                             name as a string and admin as a boolean'
  , '  geddy scaffold user name:string:default'
  , '                           Generate a users scaffolding user name as the default'
  , '                             value to display data with'
  , ''
].join('\n');

// Options available
optsMap = [
    { full: 'origins', abbr: 'o' }
  , { full: 'port', abbr: 'p' }
  , { full: 'workers', abbr: ['n', 'w'] }
  , { full: 'version', abbr: ['v', 'V'], args: false }
  , { full: 'help', abbr: 'h', args: false }
  , { full: 'debug', abbr: 'd' }
  , { full: 'loglevel', abbr: 'l' }
  , { full: 'environment', abbr: 'e' }
  , { full: 'spawned', abbr: ['s', 'q', 'Q'] }
  , { full: 'jade', abbr: 'j', args: false }
  , { full: 'handle', abbr: 'H', args: false }
  , { full: 'handlebars', abbr: 'H', args: false }
  , { full: 'mustache', abbr: 'm', args: false }
];

// Parse optsMap and generate options and cmd commands
parser = new parseopts.Parser(optsMap);
parser.parse(args);
cmds = parser.cmds;
opts = parser.opts;

// Set handlebars option to handle option
opts.handle = opts.handlebars || opts.handle;

// Exit the process with a message
die = function (str) {
  console.log(str);
  process.exit();
};

// Start Geddy with options
start = function () {
  geddy.config(opts);
  geddy.start();
};

if (opts.help) {
  die(usage);
}
if (opts.version) {
  die(geddy.version);
}

// `geddy app foo` or `geddy resource bar` etc. -- run generators
if (cmds.length) {
  // Get templates Jake file
  filepath = path.normalize(path.join(__dirname, '..', 'templates', 'Jakefile'));

  // Wrap quotes in case path has spaces
  if (process.platform === 'win32') {
    filepath = '"' + filepath + '"';
  }
  cmd = '-t -f ' + filepath + ' ';

  // Some commands take only one arg
  if (!(cmds[0] == 'secret' ||
      cmds[0] == 'db:init' ||
      cmds[0] == 'console') && !cmds[1]) {
    throw new Error(cmds[0] + ' command requires another argument.');
  }

  // Add engines to command
  if (opts.jade) {
    engineCmd = ',' + 'jade';
  } else if (opts.handle) {
    engineCmd = ',' + 'handlebars';
  } else if (opts.mustache) {
    engineCmd = ',' + 'mustache';
  } else engineCmd = '';

  // Get the model properties
  if (cmds.slice(2).length > 0) {
    modelCmd = ',' + cmds.slice(2).join(' ');
  } else modelCmd = '';

  // Add Jake argument based on commands
  switch (cmds[0]) {
    case 'console':
      // Create DBs
      cmd += 'console:start[' + (cmds[1] || 'development') + ']';
      break;
    case 'db:init':
      // Create DBs
      cmd += 'db:init';
      break;
    case 'db:createTable':
      // Create DBs
      cmd += 'db:createTable[' + cmds[1] + ']';
      break;
    case 'app':
      // Generating application
      cmd += 'gen:app[' + cmds[1] + engineCmd + ']';
      break;
    case 'resource':
      // Generating resource
      cmd += 'gen:resource[' + cmds[1] + modelCmd + ']';
      break;
    case 'scaffold':
      // Generating application
      cmd += 'gen:scaffold[' + cmds[1] + engineCmd + modelCmd + ']';
      break;
    case 'controller':
      // Generating controller
      cmd += 'gen:bareController[' + cmds[1] + engineCmd + ']';
      break;
    case 'model':
      // Generating model
      cmd += 'gen:model[' + cmds[1] + modelCmd + ']';
      break;
    case 'secret':
      // Generating new app secret
      cmd += 'gen:secret';
      break;
    default:
      die(cmds[0] + ' is not a Geddy command.');
  }

  if (!opts.debug) {
    cmd += ' --quiet';
  }

  cmd = cmd.split(' ');
  var jake = require('jake');
  jake.run.apply(jake, cmd);
}
// Just `geddy` -- start the server
else {
  // Search for 'config' directory in parent directories
  utils.file.searchParentPath('config', function (err, filePath) {
    if (err) {
      die(usage);
    }
    else {
      start();
    }
  });
}
<commit_msg>No longer need to wrap paths for Windows, invoking Jake directly<commit_after>#!/usr/bin/env node

// Dependencies
var geddy = require('../lib/geddy')
  , exec = require('child_process').exec
  , path = require('path')
  , utils = require('utilities')
  , parseopts = require('../lib/parseopts');

// Variables
var cwd = process.cwd()
  , args = process.argv.slice(2)
  , parser
  , optsMap
  , cmds
  , opts
  , usage
  , cmd
  , engineCmd
  , modelCmd
  , filepath
  , die
  , start;

// Usage dialog
usage = [
    'Geddy web framework for Node.js'
  , ''
  , 'Usage:'
  , '  geddy [options/commands] [arguments]'
  , ''
  , 'Options:'
  , '  --environment, -e   Environment to use'
  , '  --port, -p          Port to connect to'
  , '  --workers, -w       Number of worker processes to start(Default: 2)'
  , '  --debug, -d         Sets the log level to output debug messages to'
  , '                        the console'
  , '  --jade, -j          When generating views this will create Jade'
  , '                        templates(Default: EJS)'
  , '  --handle, -H        When generating views this will create Handlebars'
  , '                        templates(Default: EJS)'
  , '  --mustache, -m      When generating views this will create Mustache'
  , '                        templates(Default: EJS)'
  , '  --help, -h          Output this usage dialog'
  , '  --version, -v       Output the version of Geddy that\'s installed'
  , ''
  , 'Commands:'
  , '  app <name>                  Create a new Geddy application'
  , '  resource <name> [attrs]     Create a new resource. A resource includes'
  , '                                a model, controller and route'
  , '  scaffold <name> [attrs]     Create a new scaffolding. Scaffolding includes'
  , '                                the views, a model, controller and route'
  , '  secret                      Generate a new application secret in'
  , '                                `congig/environment`'
  , '  controller <name>          Generate a new controller including an index view'
  , '                                and and a route'
  , '  model <name> [attrs]        Generate a new model'
  , ''
  , 'Examples:'
  , '  geddy                    Start Geddy on localhost:4000 in development mode'
  , '                             or if the directory isn\'t a Geddy app it\'ll'
  , '                             this usage dialog'
  , '  geddy -p 3000            Start Geddy on port 3000'
  , '  geddy -e production      Start Geddy in production mode'
  , '  geddy -j scaffold user   Generate a users scaffolding using Jade templates'
  , '  geddy resource user name admin:boolean'
  , '                           Generate a users resource with the model properties'
  , '                             name as a string and admin as a boolean'
  , '  geddy scaffold user name:string:default'
  , '                           Generate a users scaffolding user name as the default'
  , '                             value to display data with'
  , ''
].join('\n');

// Options available
optsMap = [
    { full: 'origins', abbr: 'o' }
  , { full: 'port', abbr: 'p' }
  , { full: 'workers', abbr: ['n', 'w'] }
  , { full: 'version', abbr: ['v', 'V'], args: false }
  , { full: 'help', abbr: 'h', args: false }
  , { full: 'debug', abbr: 'd' }
  , { full: 'loglevel', abbr: 'l' }
  , { full: 'environment', abbr: 'e' }
  , { full: 'spawned', abbr: ['s', 'q', 'Q'] }
  , { full: 'jade', abbr: 'j', args: false }
  , { full: 'handle', abbr: 'H', args: false }
  , { full: 'handlebars', abbr: 'H', args: false }
  , { full: 'mustache', abbr: 'm', args: false }
];

// Parse optsMap and generate options and cmd commands
parser = new parseopts.Parser(optsMap);
parser.parse(args);
cmds = parser.cmds;
opts = parser.opts;

// Set handlebars option to handle option
opts.handle = opts.handlebars || opts.handle;

// Exit the process with a message
die = function (str) {
  console.log(str);
  process.exit();
};

// Start Geddy with options
start = function () {
  geddy.config(opts);
  geddy.start();
};

if (opts.help) {
  die(usage);
}
if (opts.version) {
  die(geddy.version);
}

// `geddy app foo` or `geddy resource bar` etc. -- run generators
if (cmds.length) {
  // Get templates Jake file
  filepath = path.normalize(path.join(__dirname, '..', 'templates', 'Jakefile'));

  cmd = '-t -f ' + filepath + ' ';

  // Some commands take only one arg
  if (!(cmds[0] == 'secret' ||
      cmds[0] == 'db:init' ||
      cmds[0] == 'console') && !cmds[1]) {
    throw new Error(cmds[0] + ' command requires another argument.');
  }

  // Add engines to command
  if (opts.jade) {
    engineCmd = ',' + 'jade';
  } else if (opts.handle) {
    engineCmd = ',' + 'handlebars';
  } else if (opts.mustache) {
    engineCmd = ',' + 'mustache';
  } else engineCmd = '';

  // Get the model properties
  if (cmds.slice(2).length > 0) {
    modelCmd = ',' + cmds.slice(2).join(' ');
  } else modelCmd = '';

  // Add Jake argument based on commands
  switch (cmds[0]) {
    case 'console':
      // Create DBs
      cmd += 'console:start[' + (cmds[1] || 'development') + ']';
      break;
    case 'db:init':
      // Create DBs
      cmd += 'db:init';
      break;
    case 'db:createTable':
      // Create DBs
      cmd += 'db:createTable[' + cmds[1] + ']';
      break;
    case 'app':
      // Generating application
      cmd += 'gen:app[' + cmds[1] + engineCmd + ']';
      break;
    case 'resource':
      // Generating resource
      cmd += 'gen:resource[' + cmds[1] + modelCmd + ']';
      break;
    case 'scaffold':
      // Generating application
      cmd += 'gen:scaffold[' + cmds[1] + engineCmd + modelCmd + ']';
      break;
    case 'controller':
      // Generating controller
      cmd += 'gen:bareController[' + cmds[1] + engineCmd + ']';
      break;
    case 'model':
      // Generating model
      cmd += 'gen:model[' + cmds[1] + modelCmd + ']';
      break;
    case 'secret':
      // Generating new app secret
      cmd += 'gen:secret';
      break;
    default:
      die(cmds[0] + ' is not a Geddy command.');
  }

  if (!opts.debug) {
    cmd += ' --quiet';
  }

  cmd = cmd.split(' ');
  var jake = require('jake');
  jake.run.apply(jake, cmd);
}
// Just `geddy` -- start the server
else {
  // Search for 'config' directory in parent directories
  utils.file.searchParentPath('config', function (err, filePath) {
    if (err) {
      die(usage);
    }
    else {
      start();
    }
  });
}
<|endoftext|>


<commit_before>#!/usr/bin/env node
/**
 * math.js
 * https://github.com/josdejong/mathjs
 *
 * Math.js is an extensive math library for JavaScript and Node.js,
 * It features real and complex numbers, units, matrices, a large set of
 * mathematical functions, and a flexible expression parser.
 *
 * Usage:
 *
 *     mathjs [scriptfile] {OPTIONS}
 *
 * Options:
 *
 *     --version, -v  Show application version
 *        --help, -h  Show this message
 *
 * Example usage:
 *     mathjs                                 Open a command prompt
 *     mathjs script.txt                      Run a script file
 *     mathjs script.txt > results.txt        Run a script file, output to file
 *     cat script.txt | mathjs                Run input stream
 *     cat script.txt | mathjs > results.txt  Run input stream, output to file
 *
 * @license
 * Copyright (C) 2013 Jos de Jong <wjosdejong@gmail.com>
 *
 * 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 math = require('../index')(),
    parser = math.parser(),
    fs = require('fs');

/**
 * auto complete a text
 * @param {String} text
 * @return {[Array, String]} completions
 */
function completer (text) {
  var matches = [];
  var m = /[a-zA-Z_0-9]+$/.exec(text);
  if (m) {
    var keyword = m[0];

    // scope variables
    // TODO: not nice to read the (private) defs inside the scope
    for (var def in parser.scope.defs) {
      if (parser.scope.defs.hasOwnProperty(def)) {
        if (def.indexOf(keyword) == 0) {
          matches.push(def);
        }
      }
    }

    // commandline keywords
    ['exit', 'quit', 'clear'].forEach(function (cmd) {
      if (cmd.indexOf(keyword) == 0) {
        matches.push(cmd);
      }
    });

    // math functions and constants
    var ignore = ['expr', 'type'];
    for (var func in math) {
      if (math.hasOwnProperty(func)) {
        if (func.indexOf(keyword) == 0 && ignore.indexOf(func) == -1) {
          matches.push(func);
        }
      }
    }

    // units
    var Unit = math.type.Unit;
    Unit.UNITS.forEach(function (unit) {
      if (unit.name.indexOf(keyword) == 0) {
        matches.push(unit.name);
      }
    });
    for (var name in Unit.PREFIXES) {
      if (Unit.PREFIXES.hasOwnProperty(name)) {
        var prefixes = Unit.PREFIXES[name];
        for (var prefix in prefixes) {
          if (prefixes.hasOwnProperty(prefix)) {
            if (prefix.indexOf(keyword) == 0) {
              matches.push(prefix);
            }
            else if (keyword.indexOf(prefix) == 0) {
              var unitKeyword = keyword.substring(prefix.length);
              Unit.UNITS.forEach(function (unit) {
                if (unit.name.indexOf(unitKeyword) == 0 &&
                    Unit.isPlainUnit(prefix + unit.name)) {
                  matches.push(prefix + unit.name);
                }
              });
            }
          }
        }
      }
    }

    // remove duplicates
    matches = matches.filter(function(elem, pos, arr) {
      return arr.indexOf(elem) == pos;
    });
  }

  return [matches, keyword];
}

/**
 * Run stream, read and evaluate input and stream that to output.
 * Text lines read from the input are evaluated, and the results are send to
 * the output.
 * @param input   Input stream
 * @param output  Output stream
 */
function runStream (input, output) {
  var readline = require('readline'),
      rl = readline.createInterface({
        input: input || process.stdin,
        output: output || process.stdout,
        completer: completer
      });

  if (rl.output.isTTY) {
    rl.setPrompt('> ');
    rl.prompt();
  }

  // TODO: automatic insertion of 'ans' before operators like +, -, *, /

  rl.on('line', function(line) {
    var expr = line.trim();

    // check for exit
    if (expr.toLowerCase() == 'exit' || expr.toLowerCase() == 'quit') {
      // exit application
      rl.close();
    }
    if (expr.toLowerCase() == 'clear') {
      // clear memory
      parser.clear();
      console.log('memory cleared');

      // get next input
      if (rl.output.isTTY) {
        rl.prompt();
      }
    }
    else {
      // evaluate expression
      if (expr) {
        try {
          var res = parser.eval(expr);
          if (!Array.isArray(res) || res.length) {
            // TODO: how to distinguish array output from multi-line output?
            console.log(math.format(res, {
              precision: 5
            }));
          }
        }
        catch (err) {
          console.log(err.toString());
        }
      }

      // get next input
      if (rl.output.isTTY) {
        rl.prompt();
      }
    }
  });

  rl.on('close', function() {
    console.log();
    process.exit(0);
  });
}

/**
 * Output application version number.
 * Version number is read version from package.json.
 */
function outputVersion () {
  fs.readFile(__dirname + '/../package.json', function (err, data) {
    if (err) {
      console.log(err.toString());
    }
    else {
      var pkg = JSON.parse(data);
      var version = pkg && pkg.version ? 'v' + pkg.version : 'unknown';
      console.log(version);
    }
  });
}

/**
 * Output a help message
 */
function outputHelp() {
  console.log('math.js');
  console.log('http://mathjs.org');
  console.log();
  console.log('Math.js is an extensive math library for JavaScript and Node.js. It features ');
  console.log('real and complex numbers, units, matrices, a large set of mathematical');
  console.log('functions, and a flexible expression parser.');
  console.log();
  console.log('Usage:');
  console.log('    mathjs [scriptfile] {OPTIONS}');
  console.log();
  console.log('Options:');
  console.log('    --version, -v  Show application version');
  console.log('       --help, -h  Show this message');
  console.log();
  console.log('Example usage:');
  console.log('    mathjs                                Open a command prompt');
  console.log('    mathjs script.txt                     Run a script file');
  console.log('    mathjs script.txt > results.txt       Run a script file, output to file');
  console.log('    cat script.txt | mathjs               Run input streaml');
  console.log('    cat script.txt | mathjs > results.txt Run input stream, output to file');
  console.log();
}

/**
 * Process input and output, based on the command line arguments
 */
if (process.argv.length > 2) {
  var arg = process.argv[2];
  if (arg == '-v' || arg == '--version') {
    outputVersion();
  }
  else if (arg == '-h' || arg == '--help') {
    outputHelp();
  }
  else {
    // run a script file
    runStream(fs.createReadStream(arg), process.stdout);
  }
}
else {
  // run a stream, can be user input or pipe input
  runStream(process.stdin, process.stdout);
}
<commit_msg>CLI now outputs values with maximum precision instead of 5.<commit_after>#!/usr/bin/env node
/**
 * math.js
 * https://github.com/josdejong/mathjs
 *
 * Math.js is an extensive math library for JavaScript and Node.js,
 * It features real and complex numbers, units, matrices, a large set of
 * mathematical functions, and a flexible expression parser.
 *
 * Usage:
 *
 *     mathjs [scriptfile] {OPTIONS}
 *
 * Options:
 *
 *     --version, -v  Show application version
 *        --help, -h  Show this message
 *
 * Example usage:
 *     mathjs                                 Open a command prompt
 *     mathjs script.txt                      Run a script file
 *     mathjs script.txt > results.txt        Run a script file, output to file
 *     cat script.txt | mathjs                Run input stream
 *     cat script.txt | mathjs > results.txt  Run input stream, output to file
 *
 * @license
 * Copyright (C) 2013 Jos de Jong <wjosdejong@gmail.com>
 *
 * 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 math = require('../index')(),
    parser = math.parser(),
    fs = require('fs');

/**
 * auto complete a text
 * @param {String} text
 * @return {[Array, String]} completions
 */
function completer (text) {
  var matches = [];
  var m = /[a-zA-Z_0-9]+$/.exec(text);
  if (m) {
    var keyword = m[0];

    // scope variables
    // TODO: not nice to read the (private) defs inside the scope
    for (var def in parser.scope.defs) {
      if (parser.scope.defs.hasOwnProperty(def)) {
        if (def.indexOf(keyword) == 0) {
          matches.push(def);
        }
      }
    }

    // commandline keywords
    ['exit', 'quit', 'clear'].forEach(function (cmd) {
      if (cmd.indexOf(keyword) == 0) {
        matches.push(cmd);
      }
    });

    // math functions and constants
    var ignore = ['expr', 'type'];
    for (var func in math) {
      if (math.hasOwnProperty(func)) {
        if (func.indexOf(keyword) == 0 && ignore.indexOf(func) == -1) {
          matches.push(func);
        }
      }
    }

    // units
    var Unit = math.type.Unit;
    Unit.UNITS.forEach(function (unit) {
      if (unit.name.indexOf(keyword) == 0) {
        matches.push(unit.name);
      }
    });
    for (var name in Unit.PREFIXES) {
      if (Unit.PREFIXES.hasOwnProperty(name)) {
        var prefixes = Unit.PREFIXES[name];
        for (var prefix in prefixes) {
          if (prefixes.hasOwnProperty(prefix)) {
            if (prefix.indexOf(keyword) == 0) {
              matches.push(prefix);
            }
            else if (keyword.indexOf(prefix) == 0) {
              var unitKeyword = keyword.substring(prefix.length);
              Unit.UNITS.forEach(function (unit) {
                if (unit.name.indexOf(unitKeyword) == 0 &&
                    Unit.isPlainUnit(prefix + unit.name)) {
                  matches.push(prefix + unit.name);
                }
              });
            }
          }
        }
      }
    }

    // remove duplicates
    matches = matches.filter(function(elem, pos, arr) {
      return arr.indexOf(elem) == pos;
    });
  }

  return [matches, keyword];
}

/**
 * Run stream, read and evaluate input and stream that to output.
 * Text lines read from the input are evaluated, and the results are send to
 * the output.
 * @param input   Input stream
 * @param output  Output stream
 */
function runStream (input, output) {
  var readline = require('readline'),
      rl = readline.createInterface({
        input: input || process.stdin,
        output: output || process.stdout,
        completer: completer
      });

  if (rl.output.isTTY) {
    rl.setPrompt('> ');
    rl.prompt();
  }

  // TODO: automatic insertion of 'ans' before operators like +, -, *, /

  rl.on('line', function(line) {
    var expr = line.trim();

    // check for exit
    if (expr.toLowerCase() == 'exit' || expr.toLowerCase() == 'quit') {
      // exit application
      rl.close();
    }
    if (expr.toLowerCase() == 'clear') {
      // clear memory
      parser.clear();
      console.log('memory cleared');

      // get next input
      if (rl.output.isTTY) {
        rl.prompt();
      }
    }
    else {
      // evaluate expression
      if (expr) {
        try {
          var res = parser.eval(expr);
          if (!Array.isArray(res) || res.length) {
            // TODO: how to distinguish array output from multi-line output?
            console.log(math.format(res));
          }
        }
        catch (err) {
          console.log(err.toString());
        }
      }

      // get next input
      if (rl.output.isTTY) {
        rl.prompt();
      }
    }
  });

  rl.on('close', function() {
    console.log();
    process.exit(0);
  });
}

/**
 * Output application version number.
 * Version number is read version from package.json.
 */
function outputVersion () {
  fs.readFile(__dirname + '/../package.json', function (err, data) {
    if (err) {
      console.log(err.toString());
    }
    else {
      var pkg = JSON.parse(data);
      var version = pkg && pkg.version ? 'v' + pkg.version : 'unknown';
      console.log(version);
    }
  });
}

/**
 * Output a help message
 */
function outputHelp() {
  console.log('math.js');
  console.log('http://mathjs.org');
  console.log();
  console.log('Math.js is an extensive math library for JavaScript and Node.js. It features ');
  console.log('real and complex numbers, units, matrices, a large set of mathematical');
  console.log('functions, and a flexible expression parser.');
  console.log();
  console.log('Usage:');
  console.log('    mathjs [scriptfile] {OPTIONS}');
  console.log();
  console.log('Options:');
  console.log('    --version, -v  Show application version');
  console.log('       --help, -h  Show this message');
  console.log();
  console.log('Example usage:');
  console.log('    mathjs                                Open a command prompt');
  console.log('    mathjs script.txt                     Run a script file');
  console.log('    mathjs script.txt > results.txt       Run a script file, output to file');
  console.log('    cat script.txt | mathjs               Run input streaml');
  console.log('    cat script.txt | mathjs > results.txt Run input stream, output to file');
  console.log();
}

/**
 * Process input and output, based on the command line arguments
 */
if (process.argv.length > 2) {
  var arg = process.argv[2];
  if (arg == '-v' || arg == '--version') {
    outputVersion();
  }
  else if (arg == '-h' || arg == '--help') {
    outputHelp();
  }
  else {
    // run a script file
    runStream(fs.createReadStream(arg), process.stdout);
  }
}
else {
  // run a stream, can be user input or pipe input
  runStream(process.stdin, process.stdout);
}
<|endoftext|>