<commit_before>'use strict';

/** @module vuegister */

const fs = require('fs');
const os = require('os');
const path = require('path');
const htmlparser = require('htmlparser2');
const tokenizer = require('acorn').tokenizer;
const sourceMap = require('source-map');

const VUE_EXT = '.vue';

/**
 * Extracts text and all attributes from the script tag, low level API
 *
 * @alias module:vuegister
 * @param {string} content - Content of the SFC file.
 * @return {object} Returns an object of the following format:
 * ```js
 * {
 *   content: string, // raw text from the script tag
 *   attribs: object, // key-value pairs, attributes from the src script tag
 *   start: number,   // line number where the script begins in the SFC
 *   end: number,     // line number where the script ends in the SFC
 * }
 * ```
 */
function extract(content) {
  if (typeof content !== 'string') {
    throw new TypeError('Content parameter must be a string.');
  }

  let getLine = (index, lines) => {
    for (let i = 0; i < lines.length; i++) {
      if (index < lines[i]) return i + 1;
    }

    return lines.length + 1;
  };

  let nl = /\r?\n/g;
  let lines = [];

  while (nl.test(content)) {
    lines.push(nl.lastIndex - 1);
  }

  let parser = new htmlparser.Parser({
    onopentag(tag, attribs) {
      if (tags.indexOf(tag) === -1) return;

      result[tag].attribs = attribs;
      textIndex = parser.endIndex + 1;
    },
    onclosetag(tag) {
      if (tags.indexOf(tag) === -1) return;

      result[tag].content = content.substring(textIndex, parser.startIndex);
      result[tag].start = getLine(textIndex - 1, lines);
      result[tag].end = getLine(parser.startIndex, lines);
    },
    onerror(err) {
      /* istanbul ignore next */
      throw err;
    },
  }, {decodeEntities: true});

  let tags = ['script', 'template'];
  let textIndex = 0;

  let result = {
    template: {},
    script: {},
  };

  parser.parseComplete(content);

  return result;
}

/**
 * Parses SFC, high level API
 *
 * @alias module:vuegister
 * @param {string} file - Absolute path to the SFC.
 * @return {object} Returns the following object:
 * ```js
 * {
 *   file: string,      // full path to the SFC or absolute path to the external
 *                      // script from src attribute of script tag
 *   code: string,      // text from the script tag or external script
 *   lang: string,      // value from the lang script attribute
 *   mapOffset: number, // line number where the script begins in the SCF minus
 *                      // one or zero for external script
 * }
 * ```
 */
function load(file) {
  let content = fs.readFileSync(file, 'utf8');
  let tags = extract(content);
  let result = {};

  for (let key of Object.keys(tags)) {
    let tag = tags[key];
    let hasSrc = 'src' in tag.attribs;

    if (hasSrc) {
      file = path.resolve(path.dirname(file), tag.attribs.src);
    }

    result[key] = {
      file: file,
      text: hasSrc ? fs.readFileSync(file, 'utf8') : tag.content,
      lang: tag.attribs.lang || '',
      mapOffset: hasSrc ? 0 : tag.start - 1,
    };
  }

  return result;
}

/**
 * Setups hook on require *.vue extension.
 *
 * @alias module:vuegister
 * @param {object} [options] - Available options are:
 * ```js
 * {
 *   maps: boolean,   // generate source map
 *   plugins: object, // user configuration for the plugins, for example:
 *                    // {
 *                    //   babel: {
 *                    //     babelrc: true,
 *                    //   },
 *                    // }
 * }
 * ```
 * @return {boolean} Returns true on success.
 */
function register(options) {
  if (VUE_EXT in require.extensions) {
    return false;
  }

  let opts = {
    maps: false,
    plugins: {},
  };

  Object.assign(opts, options);

  let mapsCache = new Map();

  if (opts.maps) {
    require('source-map-support').install({
      environment: 'node',
      handleUncaughtExceptions: false,
      retrieveSourceMap: (source) => {
        return mapsCache.has(source) ?
               {map: mapsCache.get(source), url: source} :
               null;
      },
    });
  }

  require.extensions[VUE_EXT] = (module, file) => {
    let vue = load(file);
    let script = vue.script;
    let template = vue.template;
    let sourceMap = {};

    if (script.lang) {
      let processed = _processLangAttr(script.lang, script.text, {
         file: script.file,
         maps: opts.maps,
         mapOffset: script.mapOffset,
         extra: script.lang in opts.plugins ? opts.plugins[script.lang] : {},
      });

      script.text = processed.code;
      sourceMap = processed.map;
    }

    if (opts.maps) {
      if (script.mapOffset > 0 && !script.lang) {
        sourceMap = _generateMap(script.text, script.file, script.mapOffset);
      }

      mapsCache.set(script.file, sourceMap);
    }

    script.text += addTemplate(template.text);

    return module._compile(script.text, script.file);
  };

  return true;
}

/**
 * Removes requre hook.
 *
 * @alias module:vuegister
 * @return {array} Returns list of unloaded modules.
 */
function unregister() {
  // removes module and all its children from the node's require cache
  let unload = (id) => {
    let module = require.cache[id];

    if (!module) return;

    module.children.forEach((child) => unload(child.id));
    delete require.cache[id];
    result.push(id);
  };

  let result = [];

  if (VUE_EXT in require.extensions) {
    delete require.extensions[VUE_EXT];
  }

  let sourceMapSupport = require.resolve('source-map-support');

  Object.keys(require.cache).forEach((key) => {
    if (path.extname(key) === VUE_EXT || key === sourceMapSupport) {
      unload(key);
    }
  });

  if ('prepareStackTrace' in Error) {
    delete Error.prepareStackTrace;
  }

  return result;
}

/**
 * Passes given code to the external plugin.
 *
 * @alias module:vuegister
 * @param {string} lang - Lang attribute from the scrip tag.
 * @param {string} code - Code for the transpiler.
 * @param {object} options - Options, an object of the following format:
 * ```js
 * {
 *   file: string,      // 'unknown', file name
 *   maps: boolean,     // false, provide source map
 *   mapOffset: number, // 0, map offset
 *   extra: object,     // {}, plugin options from the user
 * }
 * ```
 * @return {object} Returns the following object:
 * ```js
 * {
 *   code: string, // transpiled code, JavaScript
 *   map: object,  // generated source map
 * }
 * ```
 */
function _processLangAttr(lang, code, options) {
  let opts = {
    file: 'unknown',
    maps: false,
    mapOffset: 0,
    extra: {},
  };

  Object.assign(opts, options);

  let transpiler;

  try {
    transpiler = require(`vuegister-plugin-${lang}`);
  } catch (err) {
    let error = `Plugin vuegister-plugin-${lang} not found.` + os.EOL +
                `To install it run:` + os.EOL +
                `npm i vuegister-plugin-${lang} -D`;

    throw new Error(error);
  }

  return transpiler(code, opts);
}

/**
 * Generates source map for JavaScript.
 *
 * @alias module:vuegister
 * @param {string} content - Content of the script tag.
 * @param {string} file - File name of the generated source.
 * @param {number} offset - Offset for script tag, usually "script.start - 1"
 * @return {object} Returns the source map.
 */
function _generateMap(content, file, offset) {
  if (offset <= 0) {
    throw new RangeError('Offset parameter should be greater than zero.');
  }

  let generator = new sourceMap.SourceMapGenerator();
  let options = {
    locations: true,
    sourceType: 'module',
  };

  for (let token of tokenizer(content, options)) {
    let position = token.loc.start;

    generator.addMapping({
      source: file,
      original: {line: position.line + offset, column: position.column},
      generated: position,
      name: token.value,
    });
  }

  return generator.toJSON();
}

/**
 * Hack to suppress Vue.js warning: template or render function not defined.
 *
 * @return {string} JavaScript code.
 */
function addTemplate(template) {
  let js = [
    '',
    'var __vue__options__ = (module.exports.__esModule) ?',
    'module.exports.default : module.exports;',
    '__vue__options__.template = ' + JSON.stringify(template) + ';',
    '',
  ];

  return js.join(os.EOL);
}

module.exports = {
  extract,
  load,
  register,
  unregister,
  _processLangAttr,
  _generateMap,
};
<commit_msg>add _has function<commit_after>'use strict';

/** @module vuegister */

const fs = require('fs');
const os = require('os');
const path = require('path');
const htmlparser = require('htmlparser2');
const tokenizer = require('acorn').tokenizer;
const sourceMap = require('source-map');

const VUE_EXT = '.vue';

/**
 * Extracts text and all attributes from the script tag, low level API
 *
 * @alias module:vuegister
 * @param {string} content - Content of the SFC file.
 * @return {object} Returns an object of the following format:
 * ```js
 * {
 *   content: string, // raw text from the script tag
 *   attribs: object, // key-value pairs, attributes from the src script tag
 *   start: number,   // line number where the script begins in the SFC
 *   end: number,     // line number where the script ends in the SFC
 * }
 * ```
 */
function extract(content) {
  if (typeof content !== 'string') {
    throw new TypeError('Content parameter must be a string.');
  }

  let getLine = (index, lines) => {
    for (let i = 0; i < lines.length; i++) {
      if (index < lines[i]) return i + 1;
    }

    return lines.length + 1;
  };

  let nl = /\r?\n/g;
  let lines = [];

  while (nl.test(content)) {
    lines.push(nl.lastIndex - 1);
  }

  let parser = new htmlparser.Parser({
    onopentag(tag, attribs) {
      if (tags.indexOf(tag) === -1) return;

      result[tag].attribs = attribs;
      textIndex = parser.endIndex + 1;
    },
    onclosetag(tag) {
      if (tags.indexOf(tag) === -1) return;

      result[tag].content = content.substring(textIndex, parser.startIndex);
      result[tag].start = getLine(textIndex - 1, lines);
      result[tag].end = getLine(parser.startIndex, lines);
    },
    onerror(err) {
      /* istanbul ignore next */
      throw err;
    },
  }, {decodeEntities: true});

  let tags = ['script', 'template'];
  let textIndex = 0;

  let result = {
    template: {},
    script: {},
  };

  parser.parseComplete(content);

  return result;
}

/**
 * Parses SFC, high level API
 *
 * @alias module:vuegister
 * @param {string} file - Absolute path to the SFC.
 * @return {object} Returns the following object:
 * ```js
 * {
 *   file: string,      // full path to the SFC or absolute path to the external
 *                      // script from src attribute of script tag
 *   code: string,      // text from the script tag or external script
 *   lang: string,      // value from the lang script attribute
 *   mapOffset: number, // line number where the script begins in the SCF minus
 *                      // one or zero for external script
 * }
 * ```
 */
function load(file) {
  let content = fs.readFileSync(file, 'utf8');
  let tags = extract(content);
  let result = {};

  for (let key of Object.keys(tags)) {
    let tag = tags[key];
    let hasSrc = _has(tag.attribs, 'src');

    if (hasSrc) {
      file = path.resolve(path.dirname(file), tag.attribs.src);
    }

    result[key] = {
      file: file,
      text: hasSrc ? fs.readFileSync(file, 'utf8') : tag.content,
      lang: tag.attribs.lang || '',
      mapOffset: hasSrc ? 0 : tag.start - 1,
    };
  }

  return result;
}

/**
 * Setups hook on require *.vue extension.
 *
 * @alias module:vuegister
 * @param {object} [options] - Available options are:
 * ```js
 * {
 *   maps: boolean,   // generate source map
 *   plugins: object, // user configuration for the plugins, for example:
 *                    // {
 *                    //   babel: {
 *                    //     babelrc: true,
 *                    //   },
 *                    // }
 * }
 * ```
 * @return {boolean} Returns true on success.
 */
function register(options) {
  if (_has(require.extensions, VUE_EXT)) {
    return false;
  }

  let opts = {
    maps: false,
    plugins: {},
  };

  Object.assign(opts, options);

  let mapsCache = new Map();

  if (opts.maps) {
    require('source-map-support').install({
      environment: 'node',
      handleUncaughtExceptions: false,
      retrieveSourceMap: (source) => {
        return mapsCache.has(source) ?
               {map: mapsCache.get(source), url: source} :
               null;
      },
    });
  }

  require.extensions[VUE_EXT] = (module, file) => {
    let vue = load(file);
    let script = vue.script;
    let template = vue.template;
    let sourceMap = {};

    if (script.lang) {
      let processed = _processLangAttr(script.lang, script.text, {
         file: script.file,
         maps: opts.maps,
         mapOffset: script.mapOffset,
         extra: _has(opts.plugins, script.lang) ?
                opts.plugins[script.lang] : {},
      });

      script.text = processed.code;
      sourceMap = processed.map;
    }

    if (opts.maps) {
      if (script.mapOffset > 0 && !script.lang) {
        sourceMap = _generateMap(script.text, script.file, script.mapOffset);
      }

      mapsCache.set(script.file, sourceMap);
    }

    script.text += addTemplate(template.text);

    return module._compile(script.text, script.file);
  };

  return true;
}

/**
 * Removes requre hook.
 *
 * @alias module:vuegister
 * @return {array} Returns list of unloaded modules.
 */
function unregister() {
  // removes module and all its children from the node's require cache
  let unload = (id) => {
    let module = require.cache[id];

    if (!module) return;

    module.children.forEach((child) => unload(child.id));
    delete require.cache[id];
    result.push(id);
  };

  let result = [];

  if (_has(require.extensions, VUE_EXT)) {
    delete require.extensions[VUE_EXT];
  }

  let sourceMapSupport = require.resolve('source-map-support');

  Object.keys(require.cache).forEach((key) => {
    if (path.extname(key) === VUE_EXT || key === sourceMapSupport) {
      unload(key);
    }
  });

  if (_has(Error, 'prepareStackTrace')) {
    delete Error.prepareStackTrace;
  }

  return result;
}

/**
 * Passes given code to the external plugin.
 *
 * @alias module:vuegister
 * @param {string} lang - Lang attribute from the scrip tag.
 * @param {string} code - Code for the transpiler.
 * @param {object} options - Options, an object of the following format:
 * ```js
 * {
 *   file: string,      // 'unknown', file name
 *   maps: boolean,     // false, provide source map
 *   mapOffset: number, // 0, map offset
 *   extra: object,     // {}, plugin options from the user
 * }
 * ```
 * @return {object} Returns the following object:
 * ```js
 * {
 *   code: string, // transpiled code, JavaScript
 *   map: object,  // generated source map
 * }
 * ```
 */
function _processLangAttr(lang, code, options) {
  let opts = {
    file: 'unknown',
    maps: false,
    mapOffset: 0,
    extra: {},
  };

  Object.assign(opts, options);

  let transpiler;

  try {
    transpiler = require(`vuegister-plugin-${lang}`);
  } catch (err) {
    let error = `Plugin vuegister-plugin-${lang} not found.` + os.EOL +
                `To install it run:` + os.EOL +
                `npm i vuegister-plugin-${lang} -D`;

    throw new Error(error);
  }

  return transpiler(code, opts);
}

/**
 * Generates source map for JavaScript.
 *
 * @alias module:vuegister
 * @param {string} content - Content of the script tag.
 * @param {string} file - File name of the generated source.
 * @param {number} offset - Offset for script tag, usually "script.start - 1"
 * @return {object} Returns the source map.
 */
function _generateMap(content, file, offset) {
  if (offset <= 0) {
    throw new RangeError('Offset parameter should be greater than zero.');
  }

  let generator = new sourceMap.SourceMapGenerator();
  let options = {
    locations: true,
    sourceType: 'module',
  };

  for (let token of tokenizer(content, options)) {
    let position = token.loc.start;

    generator.addMapping({
      source: file,
      original: {line: position.line + offset, column: position.column},
      generated: position,
      name: token.value,
    });
  }

  return generator.toJSON();
}

/**
 * Hack to suppress Vue.js warning: template or render function not defined.
 *
 * @return {string} JavaScript code.
 */
function addTemplate(template) {
  let js = [
    '',
    'var __vue__options__ = (module.exports.__esModule) ?',
    'module.exports.default : module.exports;',
    '__vue__options__.template = ' + JSON.stringify(template) + ';',
    '',
  ];

  return js.join(os.EOL);
}

/**
 * Checks if path is a direct property of object.
 *
 * @param {object} object - The object to query.
 * @param {string} path - The path to check.
 * @return {boolean} Returns true if path exists, else false.
 */
function _has(object, path) {
  return Object.prototype.hasOwnProperty.call(object, path);
}

module.exports = {
  extract,
  load,
  register,
  unregister,
  _processLangAttr,
  _generateMap,
};
<|endoftext|>


<commit_before>var Botkit = require('botkit')
  , _ = require('lodash')
  , volume = require('./lib/volume')
  , directAddress = ['direct_message','direct_mention','mention'];

var controller = Botkit.slackbot({
  debug: false
});

// connect the bot to a stream of messages
controller.spawn({
  token: process.env.SLACK_API_TOKEN
}).startRTM();

// the ***magic***
controller.on('ambient', function (bot, message) {
  volume.defaultIfNotSet(message.channel);

  if (volume.loudEnough(message.channel)) {
    bot.reply(message, getResponse());
  }
});

function getResponse() {
  var responses = [
    'Sounds good',
    'Thanks for coming',
    'OK',
    'Sure, why not',
    'I understand'
  ];

  return _.sample(responses);
}

// volume-related responses
controller.hears('louder', directAddress, function(bot, message) {
  volume.louder(message.channel);
  volumeResponse(bot, message);
});

controller.hears('quieter', directAddress, function(bot, message) {
  volume.quieter(message.channel);
  volumeResponse(bot, message);
});

controller.hears('loudest', directAddress, function(bot, message) {
  volume.loudest(message.channel);
  volumeResponse(bot, message);
});

controller.hears('quietest', directAddress, function(bot, message) {
  volume.quietest(message.channel);
  volumeResponse(bot, message);
});

controller.hears('volume', directAddress, function(bot, message) {
  volumeResponse(bot, message);
});

function volumeResponse(bot, message) {
  bot.reply(message, 'Volume set to ' + volume.value(message.channel));
}
<commit_msg>added video command<commit_after>var Botkit = require('botkit')
  , _ = require('lodash')
  , volume = require('./lib/volume')
  , directAddress = ['direct_message','direct_mention','mention'];

var controller = Botkit.slackbot({
  debug: false
});

// connect the bot to a stream of messages
controller.spawn({
  token: process.env.SLACK_API_TOKEN
}).startRTM();

// the ***magic***
controller.on('ambient', function (bot, message) {
  volume.defaultIfNotSet(message.channel);

  if (volume.loudEnough(message.channel)) {
    bot.reply(message, getResponse());
  }
});

function getResponse() {
  var responses = [
    'Sounds good',
    'Thanks for coming',
    'OK',
    'Sure, why not',
    'I understand'
  ];

  return _.sample(responses);
}

controller.hears('video', directAddress, function(bot, message) {
  bot.reply(message, 'https://www.youtube.com/watch?v=Tvu2ZI329V4');
});

// volume-related responses
controller.hears('louder', directAddress, function(bot, message) {
  volume.louder(message.channel);
  volumeResponse(bot, message);
});

controller.hears('quieter', directAddress, function(bot, message) {
  volume.quieter(message.channel);
  volumeResponse(bot, message);
});

controller.hears('loudest', directAddress, function(bot, message) {
  volume.loudest(message.channel);
  volumeResponse(bot, message);
});

controller.hears('quietest', directAddress, function(bot, message) {
  volume.quietest(message.channel);
  volumeResponse(bot, message);
});

controller.hears('volume', directAddress, volumeResponse;

function volumeResponse(bot, message) {
  bot.reply(message, 'Volume set to ' + volume.value(message.channel));
}
<|endoftext|>


<commit_before>#! /usr/bin/env node
/* eslint camelcase: 0 */ // <-- Per Jupyter message spec
/* eslint spaced-comment: 0 */

/*****************************************************************************
 * Ick is an interactive console for tinkering with the Jupyter message spec *
 * and a backing kernel.                                                     *
 *****************************************************************************/

const readline = require('readline');

const enchannel = require('enchannel-zmq-backend');
const uuid = require('uuid');
const chalk = require('chalk');

const marked = require('marked');
const TerminalRenderer = require('marked-terminal');

const temp = require('temp').track();
const imageToAscii = require('image-to-ascii');

const fs = require('fs');
const spawnteract = require('spawnteract');

function main(c) {
  const identity = uuid.v4();
  // const iopub = enchannel.createIOPubSubject(identity, kernel);
  const shell = enchannel.createShellSubject(identity, c.config);
  // const control = enchannel.createControlSubject(identity, kernel);
  // const stdinChannel = enchannel.createStdinSubject(identity, kernel);

  function createMessage(session, msg_type) {
    const username = process.env.LOGNAME || process.env.USER ||
                     process.env.LNAME || process.env.USERNAME;
    return {
      header: {
        username,
        session,
        msg_type,
        msg_id: uuid.v4(),
        date: new Date(),
        version: '5.0',
      },
      metadata: {},
      parent_header: {},
      content: {},
    };
  }

  const sessionID = uuid.v4();

  function isChildMessage(msg) {
    return this.header.msg_id === msg.parent_header.msg_id;
  }

  function startREPL(langInfo) {
    const rl = readline.createInterface(process.stdin, process.stdout);
    const iopub = enchannel.createIOPubSubject(identity, c.config);

    marked.setOptions({
      renderer: new TerminalRenderer(),
    });

    rl.setPrompt(`ick${langInfo.file_extension}> `);
    rl.prompt();

    rl.on('line', (line) => {
      const executeRequest = createMessage(sessionID, 'execute_request');
      executeRequest.content = {
        code: line,
        silent: false,
        store_history: true,
        user_expressions: {},
        allow_stdin: false,
        stop_on_error: false,
      };

      const childMessages = iopub.filter(isChildMessage.bind(executeRequest))
                                 .publish()
                                 .refCount();

      const displayData = childMessages
                              .filter(msg => msg.header.msg_type === 'execute_result' ||
                                             msg.header.msg_type === 'display_data')
                              .filter(msg => msg.content)
                              .map(msg => msg.content.data);

      const executeReply = childMessages
                             .filter(msg => msg.header.msg_type === 'execute_reply')
                             .map(msg => msg.content);

      const streamReply = childMessages
                             .filter(msg => msg.header.msg_type === 'stream')
                             .map(msg => msg.content);

      streamReply.subscribe(content => {
        switch(content.name) {
        case 'stdout':
          process.stdout.write(content.text);
          break;
        case 'stderr':
          process.stderr.write(content.text);
          break;
        }
      });

      displayData.subscribe(data => {
        if(data['image/png']) {
          temp.open('ick-image', (err, info) => {
            if (err) {
              console.error(err);
              return;
            }
            const decodedData = new Buffer(data['image/png'], 'base64');
            const writer = fs.createWriteStream(info.path);
            writer.end(decodedData);
            writer.on('finish', () => {
              imageToAscii(info.path, (imErr, converted) => {
                console.log(imErr || converted);
              });
            });
          });
        }
        else if(data['text/markdown']) {
          console.log(marked(data['text/markdown']));
        }
        else if(data['text/plain']) {
          console.log(data['text/plain']);
        }
      });

      executeReply.subscribe(content => {
        rl.setPrompt(`ick${langInfo.file_extension}:${content.execution_count}> `);
        rl.prompt();
      });

      shell.send(executeRequest);

    }).on('close', () => {
      console.log('Have a great day!');
      shell.close();
      iopub.close();
      process.stdin.destroy();
    });
  }

  const kernelInfoRequest = createMessage(sessionID, 'kernel_info_request');
  const kernelReply = shell.filter(msg => msg.parent_header.msg_id === kernelInfoRequest.header.msg_id)
                           .map(msg => msg.content);

  kernelReply.subscribe(content => {
    process.stdout.write(chalk.green(content.banner));
    startREPL(content.language_info);
  });
  shell.send(kernelInfoRequest);
}

const kernelName = process.argv[2];

spawnteract.launch(kernelName).then(main);
<commit_msg>Migrate to new RxJS5 interface.<commit_after>#! /usr/bin/env node
/* eslint camelcase: 0 */ // <-- Per Jupyter message spec
/* eslint spaced-comment: 0 */

/*****************************************************************************
 * Ick is an interactive console for tinkering with the Jupyter message spec *
 * and a backing kernel.                                                     *
 *****************************************************************************/

const readline = require('readline');

const enchannel = require('enchannel-zmq-backend');
const uuid = require('uuid');
const chalk = require('chalk');

const marked = require('marked');
const TerminalRenderer = require('marked-terminal');

const temp = require('temp').track();
const imageToAscii = require('image-to-ascii');

const fs = require('fs');
const spawnteract = require('spawnteract');

function main(c) {
  const identity = uuid.v4();
  // const iopub = enchannel.createIOPubSubject(identity, kernel);
  const shell = enchannel.createShellSubject(identity, c.config);
  // const control = enchannel.createControlSubject(identity, kernel);
  // const stdinChannel = enchannel.createStdinSubject(identity, kernel);

  function createMessage(session, msg_type) {
    const username = process.env.LOGNAME || process.env.USER ||
                     process.env.LNAME || process.env.USERNAME;
    return {
      header: {
        username,
        session,
        msg_type,
        msg_id: uuid.v4(),
        date: new Date(),
        version: '5.0',
      },
      metadata: {},
      parent_header: {},
      content: {},
    };
  }

  const sessionID = uuid.v4();

  function isChildMessage(msg) {
    return this.header.msg_id === msg.parent_header.msg_id;
  }

  function startREPL(langInfo) {
    const rl = readline.createInterface(process.stdin, process.stdout);
    const iopub = enchannel.createIOPubSubject(identity, c.config);

    marked.setOptions({
      renderer: new TerminalRenderer(),
    });

    rl.setPrompt(`ick${langInfo.file_extension}> `);
    rl.prompt();

    rl.on('line', (line) => {
      const executeRequest = createMessage(sessionID, 'execute_request');
      executeRequest.content = {
        code: line,
        silent: false,
        store_history: true,
        user_expressions: {},
        allow_stdin: false,
        stop_on_error: false,
      };

      const childMessages = iopub.filter(isChildMessage.bind(executeRequest))
                                 .publish()
                                 .refCount();

      const displayData = childMessages
                              .filter(msg => msg.header.msg_type === 'execute_result' ||
                                             msg.header.msg_type === 'display_data')
                              .filter(msg => msg.content)
                              .map(msg => msg.content.data);

      const executeReply = childMessages
                             .filter(msg => msg.header.msg_type === 'execute_reply')
                             .map(msg => msg.content);

      const streamReply = childMessages
                             .filter(msg => msg.header.msg_type === 'stream')
                             .map(msg => msg.content);

      streamReply.subscribe(content => {
        switch(content.name) {
        case 'stdout':
          process.stdout.write(content.text);
          break;
        case 'stderr':
          process.stderr.write(content.text);
          break;
        }
      });

      displayData.subscribe(data => {
        if(data['image/png']) {
          temp.open('ick-image', (err, info) => {
            if (err) {
              console.error(err);
              return;
            }
            const decodedData = new Buffer(data['image/png'], 'base64');
            const writer = fs.createWriteStream(info.path);
            writer.end(decodedData);
            writer.on('finish', () => {
              imageToAscii(info.path, (imErr, converted) => {
                console.log(imErr || converted);
              });
            });
          });
        }
        else if(data['text/markdown']) {
          console.log(marked(data['text/markdown']));
        }
        else if(data['text/plain']) {
          console.log(data['text/plain']);
        }
      });

      executeReply.subscribe(content => {
        rl.setPrompt(`ick${langInfo.file_extension}:${content.execution_count}> `);
        rl.prompt();
      });

      shell.next(executeRequest);

    }).on('close', () => {
      console.log('Have a great day!');
      c.spawn.kill();
      shell.complete();
      iopub.complete();
      process.stdin.destroy();
      fs.unlink(c.connFile);
    });
  }

  const kernelInfoRequest = createMessage(sessionID, 'kernel_info_request');
  const kernelReply = shell.filter(msg => msg.parent_header.msg_id === kernelInfoRequest.header.msg_id)
                           .map(msg => msg.content);

  kernelReply.subscribe(content => {
    process.stdout.write(chalk.green(content.banner));
    startREPL(content.language_info);
  });
  shell.next(kernelInfoRequest);
}

const kernelName = process.argv[2];

spawnteract.launch(kernelName)
           .then(main)
           .catch(e => {
             console.error(e);
           });
<|endoftext|>


<commit_before>/**
 * Created by Keith Morris on 8/17/15.
 */
"use strict";

var async = require('async'),
	JiraApi = require('jira').JiraApi,
	JiraFacade,
	jira;

module.exports = JiraFacade = function (config) {
	if (!config.protocol || !config.host || !config.username || !config.password) {
		throw new Error('protocol, host, username and password are required.');
	}
	if (!config.port) {
		config.port = (config.protocol.toLowerCase() === 'https') ? 443 : 80;
	}
	config.apiVersion = config.apiVersion || 2;
	this.jira = jira = new JiraApi(config.protocol, config.host, config.port, config.username, config.password, config.apiVersion);
};

JiraFacade.prototype.createIssue = function (options, callback) {
	var that = this,
		payload = {};
	async.waterfall([
		// get Priority
		function (next) {
			that.getPriorityByName(options.priority, handleGetPriority(payload, next));
		},
		// get project, issueType, versions and components
		function (payload, next) {
			jira.getProject(options.project, handleGetProject(options, payload, next));
		},
		// create Issue
		function (payload, next) {
			var issueOptions = createIssueOptions(payload, options);

			jira.addNewIssue(issueOptions, function (err, issue) {
				if (err) {
					return next(err);
				} else {
					next(null, issue);
				}
			});
		}
	], function (err, payload) {
		callback(err, payload);
	});
};

JiraFacade.prototype.getVersionByName = function (project, versionName, callback) {
	jira.getVersions(project, filterVersionsByName(versionName, callback));
};

JiraFacade.prototype.getPriorityByName = function (priorityName, callback) {
	jira.listPriorities(filterPrioritiesByName(priorityName, callback));
};

JiraFacade.prototype.getPriorityById = function (priorityId, callback) {
	priorityId = parseInt(priorityId);
	// if it is not a number, error
	if (!isNumeric(priorityId)) {
		callback('Priority ID must be numeric.');
		return;
	}

	jira.listPriorities(filterPrioritiesById(priorityId, callback));
};

JiraFacade.prototype.getIssueTypeByName = function (issueTypeName, callback) {
	if (!issueTypeName) {
		return callback('Issue Type Name must be a non-zero length string.');
	}
	jira.listIssueTypes(filterIssueTypesByName(issueTypeName, callback));
};

// ********************************************************************
// Utility Methods and Handlers
// ********************************************************************
function getComponentsFromProject(componentNames, project) {
	return getItemsFromProject(componentNames, project, 'component');
}

function getVersionsFromProject(versionNames, project) {
	return getItemsFromProject(versionNames, project, 'version');
}

function getItemsFromProject(itemNames, project, itemType, required) {
	if ((typeof itemNames).toLowerCase() === "string") {
		itemNames = [itemNames];
	}
	if (!Array.isArray(itemNames)) {
		throw Error('Item Names argument must be a ' + itemType + ' name string or an array of ' + itemType + ' name strings');
	}
	var returnItems = [];
	itemNames.forEach(function (item, idx, arr) {
		if (!item) {
			throw Error(itemType + ' name must be a non-zero length string.');
		}
	});

	if (!project || (typeof project).toLowerCase() !== 'object' || !project.issueTypes) {
		throw Error('Project parameter must be a valid Jira project object with Issue Types');
	}

	var matches = project[itemType + 's'].filter(function (projectItem) {
		return itemNames
				.map(function (item) {
					return item.toLowerCase();
				})
				.indexOf(projectItem.name.toLowerCase()) !== -1;
		//return obj.name.toLowerCase() === itemNames.toLowerCase();
	});

	if (matches.length) {
		returnItems = returnItems.concat(matches);
	}
	if (!returnItems.length && required) {
		throw new Error('A valid ' + itemType + ' was not found for this project.');
	} else {
		return returnItems;
	}
}

function getIssueTypeFromProject(issueTypeName, project) {
	if (!issueTypeName) {
		throw Error('IssueType name must be a non-zero length string.');
	}

	if (!project || (typeof project).toLowerCase() !== 'object' || !project.issueTypes) {
		throw Error('Project parameter must be a valid Jira project object with Issue Types');
	}
	var matches = project.issueTypes.filter(function (obj) {
		return obj.name.toLowerCase() === issueTypeName.toLowerCase();
	});
	if (matches.length) {
		return matches[0];
	} else {
		throw new Error('IssueType "' + issueTypeName + '" was not found for this project.');
	}
}

function createIssueOptions(payload, options) {
	var issueOptions = {};

	issueOptions.fields = {
		"project": {
			"id": payload.project.id
		},
		"summary": options.summary,
		"description": options.description,
		"issuetype": {
			"id": payload.issueType.id
		},
		"assignee": {
			"name": options.assignee
		},
		"reporter": {
			"name": options.reporter
		},
		"priority": {
			"id": payload.priority.id
		},
		"labels": options.labels || []
	};
	if (payload.fixVersions) {
		issueOptions.fields.fixVersions = [];
		payload.fixVersions.forEach(function (version/*, idx, arr*/) {
			issueOptions.fields.fixVersions.push({id: version.id});
		});
	}
	if (payload.components) {
		issueOptions.fields.components = [];
		payload.components.forEach(function (component/*, idx, arr*/) {
			issueOptions.fields.components.push({id: component.id});
		});
	}
	return issueOptions;
}

function handleGetPriority(payload, next) {
	return function (err, priority) {
		if (err) {
			return next(err);
		}
		payload.priority = priority;
		next(null, payload);
	}
}

function handleGetProject(options, payload, next) {
	return function (err, project) {
		if (err) {
			return next(err);
		}
		payload.project = project;
		try {
			payload.issueType = getIssueTypeFromProject(options.issueType, project);
			if (options.fixVersions) {
				payload.fixVersions = getVersionsFromProject(options.fixVersions, project);
			}
			if (options.components) {
				payload.components = getComponentsFromProject(options.components, project);
			}
		} catch (err) {
			next(err.message);
		}
		next(null, payload);
	}
}

function filterVersionsByName(versionName, callback) {
	var version,
		matches;
	return function (err, versions) {
		if (err) {
			return callback(err);
		}
		matches = versions.filter(function (obj) {
			return obj.name.toLowerCase() === versionName.toLowerCase();
		});
		if (matches.length) {
			version = matches[0];
			callback(err, version);
		} else {
			callback('Issue Type "' + versionName + '" not found.');
		}
	}
}

function filterPrioritiesByName(priorityName, callback) {
	var priority;
	return function (err, priorities) {
		if (err) {
			return callback(err);
		}
		var matches = priorities.filter(function (obj) {
			return obj.name.toLowerCase() === priorityName.toLowerCase();
		});
		if (matches.length) {
			priority = matches[0];
			callback(err, priority);
		} else {
			callback('No priority called "' + priorityName + '" could be found.');
		}
	};
}

function filterPrioritiesById(priorityId, callback) {
	var priority;
	return function (err, priorities) {
		if (err) {
			return callback(err);
		}
		var matches = priorities.filter(function (obj) {
			return parseInt(obj.id) === priorityId;
		});
		if (matches.length) {
			priority = matches[0];
			callback(err, priority);
		} else {
			callback('Priority ID ' + priorityId + ' not found.');
		}
	};
}

function filterIssueTypesByName(issueTypeName, callback) {
	var issueType;
	return function (err, types) {
		if (err) {
			return callback(err);
		}
		var matches = types.filter(function (obj) {
			return obj.name.toLowerCase() === issueTypeName.toLowerCase();
		});
		if (matches.length) {
			issueType = matches[0];
			callback(err, issueType);
		} else {
			callback('Issue Type "' + issueTypeName + '" not found.');
		}
	}
}

function isNumeric(obj) {
	obj = typeof(obj) === "string" ? obj.replace(/,/g, "") : obj;
	return !isNaN(parseFloat(obj)) && isFinite(obj) && Object.prototype.toString.call(obj).toLowerCase() !== "[object array]";
}
<commit_msg>Add missing semicolons<commit_after>/**
 * Created by Keith Morris on 8/17/15.
 */
"use strict";

var async = require('async'),
	JiraApi = require('jira').JiraApi,
	JiraFacade,
	jira;

module.exports = JiraFacade = function (config) {
	if (!config.protocol || !config.host || !config.username || !config.password) {
		throw new Error('protocol, host, username and password are required.');
	}
	if (!config.port) {
		config.port = (config.protocol.toLowerCase() === 'https') ? 443 : 80;
	}
	config.apiVersion = config.apiVersion || 2;
	this.jira = jira = new JiraApi(config.protocol, config.host, config.port, config.username, config.password, config.apiVersion);
};

JiraFacade.prototype.createIssue = function (options, callback) {
	var that = this,
		payload = {};
	async.waterfall([
		// get Priority
		function (next) {
			that.getPriorityByName(options.priority, handleGetPriority(payload, next));
		},
		// get project, issueType, versions and components
		function (payload, next) {
			jira.getProject(options.project, handleGetProject(options, payload, next));
		},
		// create Issue
		function (payload, next) {
			var issueOptions = createIssueOptions(payload, options);

			jira.addNewIssue(issueOptions, function (err, issue) {
				if (err) {
					return next(err);
				} else {
					next(null, issue);
				}
			});
		}
	], function (err, payload) {
		callback(err, payload);
	});
};

JiraFacade.prototype.getVersionByName = function (project, versionName, callback) {
	jira.getVersions(project, filterVersionsByName(versionName, callback));
};

JiraFacade.prototype.getPriorityByName = function (priorityName, callback) {
	jira.listPriorities(filterPrioritiesByName(priorityName, callback));
};

JiraFacade.prototype.getPriorityById = function (priorityId, callback) {
	priorityId = parseInt(priorityId);
	// if it is not a number, error
	if (!isNumeric(priorityId)) {
		callback('Priority ID must be numeric.');
		return;
	}

	jira.listPriorities(filterPrioritiesById(priorityId, callback));
};

JiraFacade.prototype.getIssueTypeByName = function (issueTypeName, callback) {
	if (!issueTypeName) {
		return callback('Issue Type Name must be a non-zero length string.');
	}
	jira.listIssueTypes(filterIssueTypesByName(issueTypeName, callback));
};

// ********************************************************************
// Utility Methods and Handlers
// ********************************************************************
function getComponentsFromProject(componentNames, project) {
	return getItemsFromProject(componentNames, project, 'component');
}

function getVersionsFromProject(versionNames, project) {
	return getItemsFromProject(versionNames, project, 'version');
}

function getItemsFromProject(itemNames, project, itemType, required) {
	if ((typeof itemNames).toLowerCase() === "string") {
		itemNames = [itemNames];
	}
	if (!Array.isArray(itemNames)) {
		throw Error('Item Names argument must be a ' + itemType + ' name string or an array of ' + itemType + ' name strings');
	}
	var returnItems = [];
	itemNames.forEach(function (item, idx, arr) {
		if (!item) {
			throw Error(itemType + ' name must be a non-zero length string.');
		}
	});

	if (!project || (typeof project).toLowerCase() !== 'object' || !project.issueTypes) {
		throw Error('Project parameter must be a valid Jira project object with Issue Types');
	}

	var matches = project[itemType + 's'].filter(function (projectItem) {
		return itemNames
				.map(function (item) {
					return item.toLowerCase();
				})
				.indexOf(projectItem.name.toLowerCase()) !== -1;
		//return obj.name.toLowerCase() === itemNames.toLowerCase();
	});

	if (matches.length) {
		returnItems = returnItems.concat(matches);
	}
	if (!returnItems.length && required) {
		throw new Error('A valid ' + itemType + ' was not found for this project.');
	} else {
		return returnItems;
	}
}

function getIssueTypeFromProject(issueTypeName, project) {
	if (!issueTypeName) {
		throw Error('IssueType name must be a non-zero length string.');
	}

	if (!project || (typeof project).toLowerCase() !== 'object' || !project.issueTypes) {
		throw Error('Project parameter must be a valid Jira project object with Issue Types');
	}
	var matches = project.issueTypes.filter(function (obj) {
		return obj.name.toLowerCase() === issueTypeName.toLowerCase();
	});
	if (matches.length) {
		return matches[0];
	} else {
		throw new Error('IssueType "' + issueTypeName + '" was not found for this project.');
	}
}

function createIssueOptions(payload, options) {
	var issueOptions = {};

	issueOptions.fields = {
		"project": {
			"id": payload.project.id
		},
		"summary": options.summary,
		"description": options.description,
		"issuetype": {
			"id": payload.issueType.id
		},
		"assignee": {
			"name": options.assignee
		},
		"reporter": {
			"name": options.reporter
		},
		"priority": {
			"id": payload.priority.id
		},
		"labels": options.labels || []
	};
	if (payload.fixVersions) {
		issueOptions.fields.fixVersions = [];
		payload.fixVersions.forEach(function (version/*, idx, arr*/) {
			issueOptions.fields.fixVersions.push({id: version.id});
		});
	}
	if (payload.components) {
		issueOptions.fields.components = [];
		payload.components.forEach(function (component/*, idx, arr*/) {
			issueOptions.fields.components.push({id: component.id});
		});
	}
	return issueOptions;
}

function handleGetPriority(payload, next) {
	return function (err, priority) {
		if (err) {
			return next(err);
		}
		payload.priority = priority;
		next(null, payload);
	};
}

function handleGetProject(options, payload, next) {
	return function (err, project) {
		if (err) {
			return next(err);
		}
		payload.project = project;
		try {
			payload.issueType = getIssueTypeFromProject(options.issueType, project);
			if (options.fixVersions) {
				payload.fixVersions = getVersionsFromProject(options.fixVersions, project);
			}
			if (options.components) {
				payload.components = getComponentsFromProject(options.components, project);
			}
		} catch (err) {
			next(err.message);
		}
		next(null, payload);
	};
}

function filterVersionsByName(versionName, callback) {
	var version,
		matches;
	return function (err, versions) {
		if (err) {
			return callback(err);
		}
		matches = versions.filter(function (obj) {
			return obj.name.toLowerCase() === versionName.toLowerCase();
		});
		if (matches.length) {
			version = matches[0];
			callback(err, version);
		} else {
			callback('Issue Type "' + versionName + '" not found.');
		}
	};
}

function filterPrioritiesByName(priorityName, callback) {
	var priority;
	return function (err, priorities) {
		if (err) {
			return callback(err);
		}
		var matches = priorities.filter(function (obj) {
			return obj.name.toLowerCase() === priorityName.toLowerCase();
		});
		if (matches.length) {
			priority = matches[0];
			callback(err, priority);
		} else {
			callback('No priority called "' + priorityName + '" could be found.');
		}
	};
}

function filterPrioritiesById(priorityId, callback) {
	var priority;
	return function (err, priorities) {
		if (err) {
			return callback(err);
		}
		var matches = priorities.filter(function (obj) {
			return parseInt(obj.id) === priorityId;
		});
		if (matches.length) {
			priority = matches[0];
			callback(err, priority);
		} else {
			callback('Priority ID ' + priorityId + ' not found.');
		}
	};
}

function filterIssueTypesByName(issueTypeName, callback) {
	var issueType;
	return function (err, types) {
		if (err) {
			return callback(err);
		}
		var matches = types.filter(function (obj) {
			return obj.name.toLowerCase() === issueTypeName.toLowerCase();
		});
		if (matches.length) {
			issueType = matches[0];
			callback(err, issueType);
		} else {
			callback('Issue Type "' + issueTypeName + '" not found.');
		}
	};
}

function isNumeric(obj) {
	obj = typeof(obj) === "string" ? obj.replace(/,/g, "") : obj;
	return !isNaN(parseFloat(obj)) && isFinite(obj) && Object.prototype.toString.call(obj).toLowerCase() !== "[object array]";
}
<|endoftext|>


<commit_before>'use strict';

var url = require('url'),
    fs = require('fs'),
    getRemoteContent = require('remote-content');

module.exports = function (destHref, sourceHref, callback) {
    if (url.parse(sourceHref).protocol === 'file:' && destHref[0] === '/') {
        destHref = destHref.slice(1);
    }
    var resolvedUrl = url.resolve(sourceHref, destHref);
    var parsedUrl = url.parse(resolvedUrl);
    if (parsedUrl.protocol === 'file:') {
        fs.readFile(decodeURIComponent(parsedUrl.pathname), 'utf8', callback);
    } else {
        getRemoteContent(resolvedUrl, callback);
    }
};
<commit_msg>Fix eslint issues.<commit_after>'use strict';

var url = require('url'),
    fs = require('fs'),
    getRemoteContent = require('remote-content');

module.exports = function (destHref, sourceHref, callback) {
    var resolvedUrl,
        parsedUrl,
        toUrl = destHref;

    if (url.parse(sourceHref).protocol === 'file:' && destHref[0] === '/') {
        toUrl = destHref.slice(1);
    }
    resolvedUrl = url.resolve(sourceHref, toUrl);
    parsedUrl = url.parse(resolvedUrl);
    if (parsedUrl.protocol === 'file:') {
        fs.readFile(decodeURIComponent(parsedUrl.pathname), 'utf8', callback);
    } else {
        getRemoteContent(resolvedUrl, callback);
    }
};
<|endoftext|>


<commit_before>'use strict';

var glucosedistribution = {
  name: 'glucosedistribution'
  , label: 'Distribution'
  , pluginType: 'report'
};

function init() {
  return glucosedistribution;
}

module.exports = init;

glucosedistribution.html = function html(client) {
  var translate = client.translate;
  var ret =
      '
'
    + translate('Glucose distribution')
    + '  ('
    + '  '
    + '  )'
    + '
'
    + '

'
    + '

'
    + '

'
    + '
'
    + '
'
    + '* ' + translate('This is only a rough estimation that can be very inaccurate and does not replace actual blood testing. The formula used is taken from: Nathan, David M., et al. "Translating the A1C assay into estimated average glucose values." Diabetes care 31.8 (2008): 1473-1478.')
    ;
  return ret;
};

glucosedistribution.css =
    '#glucosedistribution-overviewchart {'
  + '  width: 2.4in;'
  + '  height: 2.4in;'
  + '  float:left;'
  + '}'
  + '#glucosedistribution-placeholder .tdborder {'
  + '  width:80px;'
  + '  border: 1px #ccc solid;'
  + '  margin: 0;'
  + '  padding: 1px;'
  + '	 text-align:center;'
  + '}'
  ;

glucosedistribution.report = function report_glucosedistribution(datastorage,sorteddaystoshow,options) {
  var Nightscout = window.Nightscout;
  var client = Nightscout.client;
  var translate = client.translate;

  var ss = require('simple-statistics');

  var colors = ['#f88', '#8f8', '#ff8'];
  var tablecolors = { Low:'#f88', Normal: '#8f8', High: '#ff8' };

  var report = $('#glucosedistribution-report');
  report.empty();

  var stability = $('#glucosedistribution-stability');
  stability.empty();

  var stats = [];
  var table = $('
');
  var thead = $('
');
  $(''+translate('Range')+'	').appendTo(thead);
  $(''+translate('% of Readings')+'	').appendTo(thead);
  $(''+translate('# of Readings')+'	').appendTo(thead);
  $(''+translate('Mean')+'	').appendTo(thead);
  $(''+translate('Median')+'	').appendTo(thead);
  $(''+translate('Standard Deviation')+'	').appendTo(thead);
  $(''+translate('A1c estimation*')+'	').appendTo(thead);
  thead.appendTo(table);

  var data = datastorage.allstatsrecords;
  var days = datastorage.alldays;

  $('#glucosedistribution-days').text(days+' '+translate('days total'));

  var result = { };

  ['Low', 'Normal', 'High'].forEach(function(range) {
    result[range] = { };
    var r = result[range];
    r.rangeRecords = data.filter(function(r) {
      if (range === 'Low') {
        return r.sgv > 0 && r.sgv < options.targetLow;
      } else if (range === 'Normal') {
        return r.sgv >= options.targetLow && r.sgv < options.targetHigh;
      } else {
        return r.sgv >= options.targetHigh;
      }
    });
    stats.push(r.rangeRecords.length);
    r.rangeRecords.sort(function(a,b) {
      return a.sgv - b.sgv;
    });
    r.localBgs = r.rangeRecords.map(function(r) { return r.sgv; }).filter(function(bg) { return !!bg; });
    r.midpoint = Math.floor(r.rangeRecords.length / 2);
    r.readingspct = (100 * r.rangeRecords.length / data.length).toFixed(1);
    if (r.rangeRecords.length > 0) {
      r.mean = Math.floor(10*ss.mean(r.localBgs))/10;
      r.median = r.rangeRecords[r.midpoint].sgv;
      r.stddev = Math.floor(ss.standard_deviation(r.localBgs)*10)/10;
    }
  });

  // make sure we have total 100%
  result.Normal.readingspct = (100 - result.Low.readingspct - result.High.readingspct).toFixed(1);

  ['Low', 'Normal', 'High'].forEach(function(range) {
    var tr = $('
');
    var r = result[range];

    $('' + translate(range) + ': 	').appendTo(tr);
    $('' + r.readingspct + '%	').appendTo(tr);
    $('' + r.rangeRecords.length + '	').appendTo(tr);
    if (r.rangeRecords.length > 0) {
      $('' + r.mean.toFixed(1) + '	').appendTo(tr);
      $('' + r.median.toFixed(1) + '	').appendTo(tr);
      $('' + r.stddev.toFixed(1) + '	').appendTo(tr);
      $(' 	').appendTo(tr);
    } else {
      $('N/A	').appendTo(tr);
      $('N/A	').appendTo(tr);
      $('N/A	').appendTo(tr);
      $(' 	').appendTo(tr);
    }

    table.append(tr);
  });

  var tr = $('
');
  $(''+translate('Overall')+': 	').appendTo(tr);
  $(' 	').appendTo(tr);
  $('' + data.length + '	').appendTo(tr);
  if (data.length > 0) {
    var localBgs = data.map(function(r) { return r.sgv; }).filter(function(bg) { return !!bg; });
    var mgDlBgs = data.map(function(r) { return r.bgValue; }).filter(function(bg) { return !!bg; });
    $('' + (Math.round(10*ss.mean(localBgs))/10).toFixed(1) + '	').appendTo(tr);
    $('' + (Math.round(10*ss.quantile(localBgs, 0.5))/10).toFixed(1) + '	').appendTo(tr);
    $('' + (Math.round(ss.standard_deviation(localBgs)*10)/10).toFixed(1) + '	').appendTo(tr);
    $('' + (Math.round(10*(ss.mean(mgDlBgs)+46.7)/28.7)/10).toFixed(1) + '%DCCT | ' + Math.round(((ss.mean(mgDlBgs)+46.7)/28.7 - 2.15)*10.929) + 'IFCC	').appendTo(tr);
  } else {
    $('N/A	').appendTo(tr);
    $('N/A	').appendTo(tr);
    $('N/A	').appendTo(tr);
    $('N/A	').appendTo(tr);
  }
  table.append(tr);
  report.append(table);

   // Stability

   var t1 = 6;
   var t2 = 11;
   var t1count = 0;
   var t2count = 0;

   var total = 0;

   var stabilitytable = $('
');

   $('
Mean Absolute Change	Time in fluctuation	Time in rapid fluctuation
').appendTo(stabilitytable);

   console.log(data[0]);

   for (var i = 0; i < data.length-2; i++) {

     var entry = data[i];
     var nextEntry = data[i+1];

     var delta = Math.abs(nextEntry.bgValue - entry.bgValue);

     total += delta;

     if (delta >= t1) { t1count += 1; }
     if (delta >= t2) { t2count += 1; }
   }

   var timeInT1 = Math.round(100 * t1count / data.length).toFixed(1);
   var timeInT2 = Math.round(100 * t2count / data.length).toFixed(1);
   var mac = Math.round(total / data.length).toFixed(1);

  $('
' + mac + '	' + timeInT1 + '%	' + timeInT2 + '%
').appendTo(stabilitytable);
  stabilitytable.appendTo(stability);

  setTimeout(function() {
    $.plot(
      '#glucosedistribution-overviewchart',
      stats,
      {
        series: {
          pie: {
            show: true
          }
        },
        colors: colors
      }
    );
  });
};
<commit_msg>explanations, filter skipped readings<commit_after>'use strict';

var glucosedistribution = {
  name: 'glucosedistribution'
  , label: 'Distribution'
  , pluginType: 'report'
};

function init() {
  return glucosedistribution;
}

module.exports = init;

glucosedistribution.html = function html(client) {
  var translate = client.translate;
  var ret =
      '
'
    + translate('Glucose distribution')
    + '  ('
    + '  '
    + '  )'
    + '
'
    + '

'
    + '

'
    + '

'
    + '
'
    + '
'
    + '* ' + translate('This is only a rough estimation that can be very inaccurate and does not replace actual blood testing. The formula used is taken from: Nathan, David M., et al. "Translating the A1C assay into estimated average glucose values." Diabetes care 31.8 (2008): 1473-1478.')
    ;
  return ret;
};

glucosedistribution.css =
    '#glucosedistribution-overviewchart {'
  + '  width: 2.4in;'
  + '  height: 2.4in;'
  + '  float:left;'
  + '}'
  + '#glucosedistribution-placeholder .tdborder {'
  + '  width:80px;'
  + '  border: 1px #ccc solid;'
  + '  margin: 0;'
  + '  padding: 1px;'
  + '	 text-align:center;'
  + '}'
  ;

glucosedistribution.report = function report_glucosedistribution(datastorage,sorteddaystoshow,options) {
  var Nightscout = window.Nightscout;
  var client = Nightscout.client;
  var translate = client.translate;

  var ss = require('simple-statistics');

  var colors = ['#f88', '#8f8', '#ff8'];
  var tablecolors = { Low:'#f88', Normal: '#8f8', High: '#ff8' };

  var report = $('#glucosedistribution-report');
  report.empty();

  var stability = $('#glucosedistribution-stability');
  stability.empty();

  var stats = [];
  var table = $('
');
  var thead = $('
');
  $(''+translate('Range')+'	').appendTo(thead);
  $(''+translate('% of Readings')+'	').appendTo(thead);
  $(''+translate('# of Readings')+'	').appendTo(thead);
  $(''+translate('Mean')+'	').appendTo(thead);
  $(''+translate('Median')+'	').appendTo(thead);
  $(''+translate('Standard Deviation')+'	').appendTo(thead);
  $(''+translate('A1c estimation*')+'	').appendTo(thead);
  thead.appendTo(table);

  var data = datastorage.allstatsrecords;
  var days = datastorage.alldays;

  $('#glucosedistribution-days').text(days+' '+translate('days total'));

  var result = { };

  ['Low', 'Normal', 'High'].forEach(function(range) {
    result[range] = { };
    var r = result[range];
    r.rangeRecords = data.filter(function(r) {
      if (range === 'Low') {
        return r.sgv > 0 && r.sgv < options.targetLow;
      } else if (range === 'Normal') {
        return r.sgv >= options.targetLow && r.sgv < options.targetHigh;
      } else {
        return r.sgv >= options.targetHigh;
      }
    });
    stats.push(r.rangeRecords.length);
    r.rangeRecords.sort(function(a,b) {
      return a.sgv - b.sgv;
    });
    r.localBgs = r.rangeRecords.map(function(r) { return r.sgv; }).filter(function(bg) { return !!bg; });
    r.midpoint = Math.floor(r.rangeRecords.length / 2);
    r.readingspct = (100 * r.rangeRecords.length / data.length).toFixed(1);
    if (r.rangeRecords.length > 0) {
      r.mean = Math.floor(10*ss.mean(r.localBgs))/10;
      r.median = r.rangeRecords[r.midpoint].sgv;
      r.stddev = Math.floor(ss.standard_deviation(r.localBgs)*10)/10;
    }
  });

  // make sure we have total 100%
  result.Normal.readingspct = (100 - result.Low.readingspct - result.High.readingspct).toFixed(1);

  ['Low', 'Normal', 'High'].forEach(function(range) {
    var tr = $('
');
    var r = result[range];

    $('' + translate(range) + ': 	').appendTo(tr);
    $('' + r.readingspct + '%	').appendTo(tr);
    $('' + r.rangeRecords.length + '	').appendTo(tr);
    if (r.rangeRecords.length > 0) {
      $('' + r.mean.toFixed(1) + '	').appendTo(tr);
      $('' + r.median.toFixed(1) + '	').appendTo(tr);
      $('' + r.stddev.toFixed(1) + '	').appendTo(tr);
      $(' 	').appendTo(tr);
    } else {
      $('N/A	').appendTo(tr);
      $('N/A	').appendTo(tr);
      $('N/A	').appendTo(tr);
      $(' 	').appendTo(tr);
    }

    table.append(tr);
  });

  var tr = $('
');
  $(''+translate('Overall')+': 	').appendTo(tr);
  $(' 	').appendTo(tr);
  $('' + data.length + '	').appendTo(tr);
  if (data.length > 0) {
    var localBgs = data.map(function(r) { return r.sgv; }).filter(function(bg) { return !!bg; });
    var mgDlBgs = data.map(function(r) { return r.bgValue; }).filter(function(bg) { return !!bg; });
    $('' + (Math.round(10*ss.mean(localBgs))/10).toFixed(1) + '	').appendTo(tr);
    $('' + (Math.round(10*ss.quantile(localBgs, 0.5))/10).toFixed(1) + '	').appendTo(tr);
    $('' + (Math.round(ss.standard_deviation(localBgs)*10)/10).toFixed(1) + '	').appendTo(tr);
    $('' + (Math.round(10*(ss.mean(mgDlBgs)+46.7)/28.7)/10).toFixed(1) + '%DCCT | ' + Math.round(((ss.mean(mgDlBgs)+46.7)/28.7 - 2.15)*10.929) + 'IFCC	').appendTo(tr);
  } else {
    $('N/A	').appendTo(tr);
    $('N/A	').appendTo(tr);
    $('N/A	').appendTo(tr);
    $('N/A	').appendTo(tr);
  }
  table.append(tr);
  report.append(table);

   // Stability

   var t1 = 6;
   var t2 = 11;
   var t1count = 0;
   var t2count = 0;

   var total = 0;

   var stabilitytable = $('
');

   $('
Mean Absolute Change	Time in fluctuation
(>5 mg/dl/5m)	Time in rapid fluctuation
(>10 mg/dl/5m)
').appendTo(stabilitytable);

   console.log(data[0]);

   for (var i = 0; i < data.length-2; i++) {

     var entry = data[i];
     var nextEntry = data[i+1];

     var timeDelta = nextEntry.displayTime.getTime() - entry.displayTime.getTime();

     if (timeDelta > 6 * 60 * 1000) { console.log("Record skipped"); continue; }

     var delta = Math.abs(nextEntry.bgValue - entry.bgValue);

     total += delta;

     if (delta >= t1) { t1count += 1; }
     if (delta >= t2) { t2count += 1; }
   }

   var timeInT1 = Math.round(100 * t1count / data.length).toFixed(1);
   var timeInT2 = Math.round(100 * t2count / data.length).toFixed(1);
   var mac = Math.round(total / data.length).toFixed(1);

  $('
' + mac + '	' + timeInT1 + '%	' + timeInT2 + '%
').appendTo(stabilitytable);
  stabilitytable.appendTo(stability);

  setTimeout(function() {
    $.plot(
      '#glucosedistribution-overviewchart',
      stats,
      {
        series: {
          pie: {
            show: true
          }
        },
        colors: colors
      }
    );
  });
};
<|endoftext|>


<commit_before>/* eslint quote-props: 0 */

module.exports = {
  extends: [
    'eslint:recommended',
    'plugin:import/recommended',
    'plugin:import/react',
    'plugin:node/recommended',
    'plugin:promise/recommended',
    'semistandard'
  ],
  rules: {
    'array-bracket-newline': [1, 'consistent'],
    'array-callback-return': 2,
    'array-element-newline': 0,
    'arrow-body-style': [2, 'as-needed', { requireReturnForObjectLiteral: false }],
    'arrow-parens': [2, 'always'],
    'block-scoped-var': 2,
    'brace-style': [2, 'stroustrup', { allowSingleLine: true }],
    'callback-return': 0,
    'capitalized-comments': 0,
    'class-methods-use-this': 2,
    'complexity': 0,
    'consistent-return': 1,
    'consistent-this': 0,
    'default-case': [1, { commentPattern: '^no default$' }],
    'dot-notation': [1, { allowKeywords: true }],
    'func-name-matching': 0,
    'func-names': 0,
    'func-style': 0,
    'function-paren-newline': [2, 'consistent'],
    'global-require': 0,
    'guard-for-in': 2,
    'id-blacklist': 0,
    'id-length': 0,
    'id-match': 0,
    'implicit-arrow-linebreak': [2, 'beside'],
    'init-declarations': 0,
    'jsx-quotes': [2, 'prefer-double'],
    'linebreak-style': [2, 'unix'],
    'max-lines': 0,
    'max-statements-per-line': 0,
    'multiline-ternary': 0,
    'newline-before-return': 0,
    'newline-per-chained-call': [2, { ignoreChainWithDepth: 4 }],
    'no-confusing-arrow': [2, { allowParens: true }],
    'no-console': 1,
    'object-curly-spacing': 1,
    'operator-linebreak': [1, 'before'],
    'space-before-function-paren': [2, 'never'],

    'import/default': 0,
    'import/dynamic-import-chunkname': 0,
    'import/exports-last': 1,
    'import/extensions': 0,
    'import/group-exports': 0,
    'import/imports-first': 0,
    'import/max-dependencies': 0,
    'import/named': 0,
    'import/namespace': 0,
    'import/newline-after-import': 1,
    'import/no-absolute-path': 0,
    'import/no-amd': 0,
    'import/no-anonymous-default-export': 0,
    'import/no-commonjs': 0,
    'import/no-cycle': [2, { maxDepth: Infinity }],
    'import/no-default-export': 0,
    'import/no-deprecated': 0,
    'import/no-dynamic-require': 0,
    'import/no-extraneous-dependencies': 0,
    'import/no-internal-modules': 0,
    'import/no-mutable-exports': 0,
    'import/no-named-as-default-member': 2,
    'import/no-named-as-default': 2,
    'import/no-named-default': 0,
    'import/no-named-export': 0,
    'import/no-namespace': 0,
    'import/no-nodejs-modules': 0,
    'import/no-relative-parent-imports': 0,
    'import/no-restricted-paths': 0,
    'import/no-self-import': 2,
    'import/no-unassigned-import': 0,
    'import/no-unresolved': 0,
    'import/no-unused-modules': 0,
    'import/no-useless-path-segments': 2,
    'import/order': 0,
    'import/prefer-default-export': 0,
    'import/unambiguous': 0,

    // Disabled because test fixtures' dependencies are not installed, which
    // causes this rule to fail some tests.
    'node/no-missing-require': 0,
    'node/no-unsupported-features/es-syntax': 0,

    'promise/prefer-await-to-callbacks': 0,
    'promise/prefer-await-to-then': 0
  }
};
<commit_msg>rules: enable `max-classes-per-file` as an error<commit_after>/* eslint quote-props: 0 */

module.exports = {
  extends: [
    'eslint:recommended',
    'plugin:import/recommended',
    'plugin:import/react',
    'plugin:node/recommended',
    'plugin:promise/recommended',
    'semistandard'
  ],
  rules: {
    'array-bracket-newline': [1, 'consistent'],
    'array-callback-return': 2,
    'array-element-newline': 0,
    'arrow-body-style': [2, 'as-needed', { requireReturnForObjectLiteral: false }],
    'arrow-parens': [2, 'always'],
    'block-scoped-var': 2,
    'brace-style': [2, 'stroustrup', { allowSingleLine: true }],
    'callback-return': 0,
    'capitalized-comments': 0,
    'class-methods-use-this': 2,
    'complexity': 0,
    'consistent-return': 1,
    'consistent-this': 0,
    'default-case': [1, { commentPattern: '^no default$' }],
    'dot-notation': [1, { allowKeywords: true }],
    'func-name-matching': 0,
    'func-names': 0,
    'func-style': 0,
    'function-paren-newline': [2, 'consistent'],
    'global-require': 0,
    'guard-for-in': 2,
    'id-blacklist': 0,
    'id-length': 0,
    'id-match': 0,
    'implicit-arrow-linebreak': [2, 'beside'],
    'init-declarations': 0,
    'jsx-quotes': [2, 'prefer-double'],
    'line-comment-position': 0,
    'linebreak-style': [2, 'unix'],
    'lines-around-comment': 0,
    'max-classes-per-file': [2, 1],
    'max-lines': 0,
    'max-statements-per-line': 0,
    'multiline-ternary': 0,
    'newline-before-return': 0,
    'newline-per-chained-call': [2, { ignoreChainWithDepth: 4 }],
    'no-confusing-arrow': [2, { allowParens: true }],
    'no-console': 1,
    'object-curly-spacing': 1,
    'operator-linebreak': [1, 'before'],
    'space-before-function-paren': [2, 'never'],

    'import/default': 0,
    'import/dynamic-import-chunkname': 0,
    'import/exports-last': 1,
    'import/extensions': 0,
    'import/group-exports': 0,
    'import/imports-first': 0,
    'import/max-dependencies': 0,
    'import/named': 0,
    'import/namespace': 0,
    'import/newline-after-import': 1,
    'import/no-absolute-path': 0,
    'import/no-amd': 0,
    'import/no-anonymous-default-export': 0,
    'import/no-commonjs': 0,
    'import/no-cycle': [2, { maxDepth: Infinity }],
    'import/no-default-export': 0,
    'import/no-deprecated': 0,
    'import/no-dynamic-require': 0,
    'import/no-extraneous-dependencies': 0,
    'import/no-internal-modules': 0,
    'import/no-mutable-exports': 0,
    'import/no-named-as-default-member': 2,
    'import/no-named-as-default': 2,
    'import/no-named-default': 0,
    'import/no-named-export': 0,
    'import/no-namespace': 0,
    'import/no-nodejs-modules': 0,
    'import/no-relative-parent-imports': 0,
    'import/no-restricted-paths': 0,
    'import/no-self-import': 2,
    'import/no-unassigned-import': 0,
    'import/no-unresolved': 0,
    'import/no-unused-modules': 0,
    'import/no-useless-path-segments': 2,
    'import/order': 0,
    'import/prefer-default-export': 0,
    'import/unambiguous': 0,

    // Disabled because test fixtures' dependencies are not installed, which
    // causes this rule to fail some tests.
    'node/no-missing-require': 0,
    'node/no-unsupported-features/es-syntax': 0,

    'promise/prefer-await-to-callbacks': 0,
    'promise/prefer-await-to-then': 0
  }
};
<|endoftext|>


<commit_before>'use strict'
var fs = require('fs')

var isBuffer = Buffer.isBuffer
var Obv = require('obv')
var Append = require('append-batch')
var Blocks = require('aligned-block-file')
var isInteger = Number.isInteger

function frame (data) {
  var length = data.reduce(function (total, value) { return total + value.length }, 0)
  var b = new Buffer(length + data.length * 8)
  var offset = 0
  for(var i = 0; i < data.length; i++) {
    var buf = data[i]
    //mutate the items
    //var buf = item.value
    b.writeUInt32BE(buf.length, 0 + offset) //start
    b.writeUInt32BE(buf.length, 4+buf.length + offset) //end
    buf.copy(b, 4 + offset, 0, buf.length)
    offset += buf.length + 8
  }
  return b
}

function format (keys, values, key, value, cursor) {
  return (
    keys !== false
    ? values !== false
      ? {key: key, value: value, seq: cursor}
      : key
    : value
  )
}

var k = 0

module.exports = function (file, length) {

  var since = Obv()
  length = length || 1024
  var blocks = Blocks(file, length, 'a+')

  var append = Append(function (batch, cb) {
    blocks.append(frame(batch), function (err) {
      if(err) return cb(err)
      //else, get offset of last item.
      since.set(blocks.offset.value - (batch[batch.length - 1].length + 8))
      cb(null, since.value)
    })
  })

  var since = Obv()
  var offset = blocks.offset

  offset.once(function (offset) {
    if(offset === 0) return since.set(-1)
    log.getPrevious(offset, function (err, value, length) {
      since.set(offset - length)
    })
  })

  var log
  return log = {
    since: since,
    //create a stream between any two records.
    //read the first value, then scan forward or backwards
    //in the direction of the log

    stream: function (opts) {
      opts = opts || {}
      var cursor
      var reverse = !!opts.reverse
      var get = reverse ? log.getPrevious : log.get
      var diff = reverse ? -1 : 1
      var live = opts.live
      var aborted = false
      if(!reverse && opts.gte == null) {
        cursor = 0
      }
      else
        cursor = reverse ? opts.lt : opts.gte

      function next (cb) {
        if(aborted) return cb(aborted)
        get(cursor, function (err, value, length) {
          if(!value.length) throw new Error('read empty value')
          var _cursor = cursor
          cursor += (length * diff)
          cb(err, format(opts.keys, opts.value, _cursor, value, cursor))
        })
      }

      return function (abort, cb) {
        if(aborted = abort) return cb(abort)

        offset.once(function (_offset) {
          //if(_offset < cursor) //throw new Error('offset smaller than cursor')
          if(cursor == null && reverse) {
            cursor = _offset; next(cb)
          }
          else if(reverse ? cursor > 0 : cursor < _offset) next(cb)
          else if(reverse ? cursor <= 0 : cursor >= _offset) {
            if(!live) return cb(true)
            offset.once(function () { next(cb) }, false)
          }
          else
            throw new Error('should never happen: cursor is invalid state:'+cursor+' offset:'+_offset)
        })
      }
    },

    //if value is an array of buffers, then treat that as a batch.
    append: append,

    get: function (_offset, cb) {
      if(!isInteger(_offset)) throw new Error('get: offset must be integer')
      //read the block that offset is in.
      //if offset is near the end of the block, read two blocks.
      blocks.readUInt32BE(_offset, function (err, length) {
        if(err) return cb(err)
        blocks.read(_offset + 4, _offset + 4 + length, function (err, value) {
          if(value.length !== length) throw new Error('incorrect length, expected:'+length+', was:'+value.length)
          setImmediate(function () {
            cb(err, value, length + 8)
          })
        })
      })
    },
    //get the record _before_ the given offset.
    getPrevious: function (_offset, cb) {
      //don't read before start of file...
      if(!isInteger(_offset)) throw new Error('getPrevious: offset must be integer')

      _offset = _offset || blocks.size()
      if(_offset == 0) return cb(new Error('attempted read previous to first object'))
      blocks.readUInt32BE(_offset - 4, function (err, length) {
        if(err) return cb(err)
        blocks.read(_offset - 4 - length, _offset - 4, function (err, value) {
          cb(err, value, length + 8)
        })
      })
    },
  }
}

<commit_msg>pass test-flumelog<commit_after>'use strict'
var fs = require('fs')

var isBuffer = Buffer.isBuffer
var Obv = require('obv')
var Append = require('append-batch')
var Blocks = require('aligned-block-file')
var isInteger = Number.isInteger
var ltgt = require('ltgt')

function frame (data) {
  var length = data.reduce(function (total, value) { return total + value.length }, 0)
  var b = new Buffer(length + data.length * 8)
  var offset = 0
  for(var i = 0; i < data.length; i++) {
    var buf = data[i]
    //mutate the items
    //var buf = item.value
    b.writeUInt32BE(buf.length, 0 + offset) //start
    b.writeUInt32BE(buf.length, 4+buf.length + offset) //end
    buf.copy(b, 4 + offset, 0, buf.length)
    offset += buf.length + 8
  }
  return b
}

function format (seqs, values, seq, value, cursor) {
  return (
    seqs !== false
    ? values !== false
      ? {value: value, seq: seq}
      : seq
    : value
  )
}

var k = 0

function id (v) { return v }
var id_codec = {encode: id, decode: id}

module.exports = function (file, length, codec) {
  if(!codec) codec = id_codec
  var since = Obv()
  length = length || 1024
  var blocks = Blocks(file, length, 'a+')

  var append = Append(function (batch, cb) {
    batch = batch.map(codec.encode).map(function (e) {
      return Buffer.isBuffer(e) ? e : new Buffer(e)
    })
    blocks.append(frame(batch), function (err) {
      if(err) return cb(err)
      //else, get offset of last item.
      since.set(blocks.offset.value - (batch[batch.length - 1].length + 8))
      cb(null, since.value)
    })
  })

  var since = Obv()
  var offset = blocks.offset

  offset.once(function (offset) {
    if(offset === 0) return since.set(-1)
    log.getPrevious(offset, function (err, value, length) {
      since.set(offset - length)
    })
  })

  var log
  return log = {
    since: since,
    //create a stream between any two records.
    //read the first value, then scan forward or backwards
    //in the direction of the log

    stream: function (opts) {
      opts = opts || {}
      var cursor
      var reverse = !!opts.reverse
      var get = reverse ? log.getPrevious : log.get
      var diff = reverse ? -1 : 1
      var live = opts.live
      var aborted = false
      var skip = false

      if(reverse) {
        if(opts.lt != null) cursor = opts.lt
        else if(opts.lte != null) {
          cursor = opts.lte; skip = true
        }
      }
      else {
        if(opts.gte != null) cursor = opts.gte
        else if(opts.gt != null) {
          cursor = opts.gt; skip = true
        }
        else cursor = 0
      }

      var lower = ltgt.lowerBound(opts) || 0
      var includeLower = ltgt.lowerBoundInclusive(opts)
      var upper = ltgt.upperBound(opts)
      var includeUpper = ltgt.upperBoundInclusive(opts)

      function next (cb) {
        if(aborted) return cb(aborted)

        if(!reverse && upper != null && includeUpper ? cursor > upper : cursor >= upper) {
          return cb(true)
        }

        get(cursor, function (err, value, length) {
          if(!value.length) throw new Error('read empty value')
          var _cursor = reverse ? cursor - length : cursor
          cursor += (length * diff)

          if(reverse && (includeLower ? cursor < lower : cursor <= lower))
              return cb(true)

          if(skip) {
            skip = false
            return next(cb)
          }

          cb(err, format(opts.seqs, opts.values, _cursor, value))
        })
      }

      return function (abort, cb) {
        if(aborted = abort) return cb(abort)

        offset.once(function (_offset) {
          //if(_offset < cursor) //throw new Error('offset smaller than cursor')
          if(cursor == null && reverse) {
            cursor = _offset; next(cb)
          }
          else if(reverse ? cursor > 0 : cursor < _offset) next(cb)
          else if(reverse ? cursor <= 0 : cursor >= _offset) {
            if(!live) return cb(true)
            offset.once(function () { next(cb) }, false)
          }
          else
            throw new Error('should never happen: cursor is invalid state:'+cursor+' offset:'+_offset)
        })
      }
    },

    //if value is an array of buffers, then treat that as a batch.
    append: append,

    get: function (_offset, cb) {
      if(!isInteger(_offset)) throw new Error('get: offset must be integer')
      //read the block that offset is in.
      //if offset is near the end of the block, read two blocks.
      blocks.readUInt32BE(_offset, function (err, length) {
        if(err) return cb(err)
        blocks.read(_offset + 4, _offset + 4 + length, function (err, value) {
          if(value.length !== length) throw new Error('incorrect length, expected:'+length+', was:'+value.length)
          setImmediate(function () {
            cb(err, codec.decode(value), length + 8)
          })
        })
      })
    },
    //get the record _before_ the given offset.
    getPrevious: function (_offset, cb) {
      //don't read before start of file...
      if(!isInteger(_offset)) throw new Error('getPrevious: offset must be integer')

      _offset = _offset || blocks.size()
      if(_offset == 0) return cb(new Error('attempted read previous to first object'))
      blocks.readUInt32BE(_offset - 4, function (err, length) {
        if(err) return cb(err)
        blocks.read(_offset - 4 - length, _offset - 4, function (err, value) {
          cb(err, codec.decode(value), length + 8)
        })
      })
    },
  }
}

<|endoftext|>


<commit_before>var router = require('ramrod')(),
  form = require('formidable').IncomingForm(),
  http = require('http'),
  couchdb = require('felix-couchdb'),
  client = couchdb.createClient(),
  db = client.db('redwah'),
  web = require('./lib/web.js'),
  rwlib = require('./lib/redwah.js'),
  redwah = {
    version: "0.0.1"
  };

// Route handler

router.on('putlist|put', function (req, res) {
  form.parse(req, function(err, params) {
    db.getDoc(params.id, function (err, previousDoc) {
      if (err) { return web.sendError(res, 404); }
      db.saveDoc(params, function (err, doc) {
        if (err) { return web.sendError(res, 500);
        res.writeHead(200);
        res.end(JSON.stringify(doc));
        if (previousDoc.rows.toString() != doc.rows.toString()) {
          rwlib.updateItems(doc.rows, doc.items);
        }
      });
    });
  });
});

router.on('postlist|post', function (req, res) {
  form.parse(req, function (err, params) {
    if (err) { return web.sendError(res, 500); }
    } else {
      var listDocument = {
        "name": params.name,
        "items": [],
        "rows": [],
        "createdAt": new Date().getTime(),
        "lastUpdated": new Date().getTime()
      };
      db.saveDoc(listDocument, function (err, doc) {
        res.writeHead(201);
        res.end(JSON.stringify(doc));
      });
    }
  });
});

router.on('getlist|get', function (req, res, params) {
  res.writeHead(200);
  db.getDoc(params.id, function (err, doc) {
    if (err) { return web.sendError(res, 404); }
    res.writeHead(200);
    res.end(JSON.stringify(doc));
  });
});

router.on('*', function (req, res) {
  res.writeHead(200);
  res.end(JSON.stringify(redwah));
});

// Enumerate routes

['list', 'item'].forEach(function (obj) {
  ['post', 'get', 'put', 'del'].forEach(function (method) {
    router[method](obj, method + obj);
  });
});

db.exists(function (err, dbExists) {
  if (!dbExists) {
    console.log('db does not exist');
    db.create(function (err) {
      if (err) { throw new Error (JSON.stringify(err)); }
      console.log('redwah db created');
    });
  }
});

http.createServer(function (req, res) {
  router.dispatch(req, res);
}).listen(3000);
<commit_msg>dont need to parse put data<commit_after>var router = require('ramrod')(),
  form = require('formidable').IncomingForm(),
  http = require('http'),
  couchdb = require('felix-couchdb'),
  client = couchdb.createClient(),
  db = client.db('redwah'),
  web = require('./lib/web.js'),
  rwlib = require('./lib/redwah.js'),
  redwah = {
    version: "0.0.1"
  };

// Route handler

router.on('putlist|put', function (req, res) {
  db.getDoc(params.id, function (err, previousDoc) {
    if (err) { return web.sendError(res, 404); }
    db.saveDoc(params, function (err, doc) {
      if (err) { return web.sendError(res, 500);
      res.writeHead(200);
      res.end(JSON.stringify(doc));
      if (previousDoc.rows.toString() != doc.rows.toString()) {
        rwlib.updateItems(doc.rows, doc.items);
      }
    });
  });
});

router.on('postitem|post', function (req, res) {
  form.parse(req, function (err, params) {
  });
});

router.on('putitem|put', function (req, res, params) {
});

router.on('postlist|post', function (req, res) {
  form.parse(req, function (err, params) {
    if (err) { return web.sendError(res, 500); }
    } else {
      var listDocument = {
        "name": params.name,
        "items": [],
        "rows": [],
        "createdAt": new Date().getTime(),
        "lastUpdated": new Date().getTime()
      };
      db.saveDoc(listDocument, function (err, doc) {
        res.writeHead(201);
        res.end(JSON.stringify(doc));
      });
    }
  });
});

router.on('getlist|get', function (req, res, params) {
  res.writeHead(200);
  db.getDoc(params.id, function (err, doc) {
    if (err) { return web.sendError(res, 404); }
    res.writeHead(200);
    res.end(JSON.stringify(doc));
  });
});

router.on('*', function (req, res) {
  res.writeHead(200);
  res.end(JSON.stringify(redwah));
});

// Enumerate routes

['list', 'item'].forEach(function (obj) {
  ['post', 'get', 'put', 'del'].forEach(function (method) {
    router[method](obj, method + obj);
  });
});

db.exists(function (err, dbExists) {
  if (!dbExists) {
    console.log('db does not exist');
    db.create(function (err) {
      if (err) { throw new Error (JSON.stringify(err)); }
      console.log('redwah db created');
    });
  }
});

http.createServer(function (req, res) {
  router.dispatch(req, res);
}).listen(3000);
<|endoftext|>


<commit_before>import fileReaderStream from 'filereader-stream'
import readFileBasic from './readFileBasic'
import workerSpawner from './workers/spawners/workerSpawner'
import streamWorkerSpawner from './workers/spawners/streamWorkerSpawner'
import parseStlAsStreamNoWorker from './parseStlAsStreamNoWorker'
import parseStlAsStreamWorker from './parseStlAsStreamWorker'

//var foo = require('./workers/spawners/testSpawnWorker')

// not worker based, for dev/testing
import { default as makeStlStreamParser } from './parsers/stl/parseStream'
function repeat (times, fn, params) {
  for (var i = 0; i < times; i++) {
    fn(params)
  }
}

function handleFileSelect (e) {
  e.stopPropagation()
  e.preventDefault()

  // files is a FileList of File objects. List some properties.
  let files = []
  for (var i = 0, f; f = e.dataTransfer.files[i]; i++) {
    files.push(f)
  }
  let output = files.map(function (f) {
    return `

       ${escape(f.name)}  (${f.type || 'n/a' }) - ${f.size} bytes,
      last modified: ${f.lastModifiedDate ? f.lastModifiedDate.toLocaleDateString() : 'n/a'}

`
  })

  document.getElementById('list').innerHTML = '
' + output.join('') + '
'

  const testCount = 1

  function testRunTransferable () {
    readFileBasic(files[0]).then(workerSpawner.bind(null, {transferable: true}))
  }

  function testRunCopy () {
    readFileBasic(files[0]).then(workerSpawner.bind(null, {transferable: false}))
  }

  function testRunStreamBlock () {
    const concat = require('concat-stream')

    const workerStream = streamWorkerSpawner.bind(null, {transferable: false})()
    fileReaderStream(files[0], {chunkSize: 9999999999}).pipe(workerStream)
    /*.pipe(concat(function(data) {
      console.log('after worker')
    }))*/
  }

  function testRunStream () {

  }

  repeat(testCount, testRunTransferable, files[0])
  //repeat(testCount, testRunCopy, files[0])
  //repeat(testCount, testRunStreamBlock, files[0])

  //parseStlAsStreamNoWorker(fileReaderStream, files)
  parseStlAsStreamWorker(fileReaderStream, files)
}

function handleDragOver (e) {
  e.stopPropagation()
  e.preventDefault()
  e.dataTransfer.dropEffect = 'copy' // Explicitly show this is a copy.
}

// Setup the dnd listeners.
var dropZone = document.getElementById('drop_zone')
dropZone.addEventListener('dragover', handleDragOver, false)
dropZone.addEventListener('drop', handleFileSelect, false)

console.log('dropZone', dropZone)
<commit_msg>feat(file size display): added display of (humanly readeable) file size in the console before bench results<commit_after>import fileReaderStream from 'filereader-stream'
import readFileBasic from './readFileBasic'
import workerSpawner from './workers/spawners/workerSpawner'
import streamWorkerSpawner from './workers/spawners/streamWorkerSpawner'
import parseStlAsStreamNoWorker from './parseStlAsStreamNoWorker'
import parseStlAsStreamWorker from './parseStlAsStreamWorker'

// var foo = require('./workers/spawners/testSpawnWorker')

// helper for file size display from http://stackoverflow.com/questions/15900485/correct-way-to-convert-size-in-bytes-to-kb-mb-gb-in-javascript
function formatBytes (bytes, decimals) {
  if (bytes === 0) return '0 Byte'
  var k = 1000 // or 1024 for binary
  var dm = decimals + 1 || 3
  var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
  var i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i]
}

// not worker based, for dev/testing
import { default as makeStlStreamParser } from './parsers/stl/parseStream'
function repeat (times, fn, params) {
  for (var i = 0; i < times; i++) {
    fn(params)
  }
}

function handleFileSelect (e) {
  e.stopPropagation()
  e.preventDefault()

  // files is a FileList of File objects. List some properties.
  let files = []
  for (var i = 0, f; f = e.dataTransfer.files[i]; i++) {
    files.push(f)
  }
  let output = files.map(function (f) {
    return `

       ${escape(f.name)}  (${f.type || 'n/a' }) - ${f.size} bytes,
      last modified: ${f.lastModifiedDate ? f.lastModifiedDate.toLocaleDateString() : 'n/a'}

`
  })

  document.getElementById('list').innerHTML = '
' + output.join('') + '
'

  const testCount = 1

  function testRunTransferable () {
    readFileBasic(files[0]).then(workerSpawner.bind(null, {transferable: true}))
  }

  function testRunCopy () {
    readFileBasic(files[0]).then(workerSpawner.bind(null, {transferable: false}))
  }

  function testRunStreamBlock () {
    const concat = require('concat-stream')

    const workerStream = streamWorkerSpawner.bind(null, {transferable: false})()
    fileReaderStream(files[0], {chunkSize: 9999999999}).pipe(workerStream)
  /*.pipe(concat(function(data) {
    console.log('after worker')
  }))*/
  }

  function testRunStream () {
  }

  console.log(`Results for file size: ${formatBytes(files[0].size)}`)

  repeat(testCount, testRunTransferable, files[0])
  // repeat(testCount, testRunCopy, files[0])
  // repeat(testCount, testRunStreamBlock, files[0])

  // parseStlAsStreamNoWorker(fileReaderStream, files)
  parseStlAsStreamWorker(fileReaderStream, files)
}

function handleDragOver (e) {
  e.stopPropagation()
  e.preventDefault()
  e.dataTransfer.dropEffect = 'copy' // Explicitly show this is a copy.
}

// Setup the dnd listeners.
let dropZone = document.getElementById('drop_zone')
dropZone.addEventListener('dragover', handleDragOver, false)
dropZone.addEventListener('drop', handleFileSelect, false)
<|endoftext|>


<commit_before>var Twitter = require('twode'),
    _ = require('underscore'),
    CronJob = require('cron').CronJob;
    config = require('./lib/config'),
    fs = require("fs"),
    readFile = fs.readFileSync("./data/FY2016Q1.json", "UTF-8"),
    q1 = JSON.parse(readFile),
    counter = 0,
    twit = new Twitter({
        consumer_key: config.TWITTER_CONSUMER_KEY,
        consumer_secret: config.TWITTER_CONSUMER_SECRET,
        access_token_key: config.TWITTER_ACCESS_TOKEN_KEY,
        access_token_secret: config.TWITTER_ACCESS_TOKEN_SECRET
    });

// Define Function to Tweet
function tweetAboutContract (contract) {
    if (contract.Total_Transactions && contract.Contract_Description) {

        var tweet = 'We spent $' + contract.Total_Transactions.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,') + ' on ' +  contract.Contract_Description;

        if (tweet.length > 140) {
          tweet = tweet.substring(0, 137) + '...';
        }

        twit.updateStatus(tweet,
          function (err, data) {
            if (err) {
              console.log(err);
            }
          }
        );
    }
}

// Set up Cron Job. Runs at 11:30 and 6:30 PM daily
new CronJob('00 11,18 * * *', function() {
  tweetAboutContract(q1[counter]);
  counter++;
}, null, true, 'America/New_York');<commit_msg>Add character count handling so we don't miss tweets!<commit_after>var Twitter = require('twode'),
    _ = require('underscore'),
    CronJob = require('cron').CronJob;
    config = require('./lib/config'),
    fs = require("fs"),
    readFile = fs.readFileSync("./data/FY2016Q1.json", "UTF-8"),
    q1 = JSON.parse(readFile),
    counter = 0,
    twit = new Twitter({
        consumer_key: config.TWITTER_CONSUMER_KEY,
        consumer_secret: config.TWITTER_CONSUMER_SECRET,
        access_token_key: config.TWITTER_ACCESS_TOKEN_KEY,
        access_token_secret: config.TWITTER_ACCESS_TOKEN_SECRET
    });

// Define Function to Tweet
function tweetAboutContract (contract) {
    if (contract.Total_Transactions && contract.Contract_Description) {

        var tweet = 'We spent $' + contract.Total_Transactions.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,') + ' on ' +  contract.Contract_Description;

        if (tweet.length > 140) {
          tweet = tweet.substring(0, 137) + '...';
        }

        twit.updateStatus(tweet,
          function (err, data) {
            if (err) {
              console.log(err);
            }
          }
        );
    }
}

// Set up Cron Job. Runs at 11:00 AM and 6:00 PM daily
new CronJob('00 11,18 * * *', function() {
  tweetAboutContract(q1[counter]);
  counter++;
}, null, true, 'America/New_York');
<|endoftext|>


<commit_before>'use strict';

/**
 * Library that makes it easier to invoke lambda functions with promises.
 *
 * @author Sam Verschueren      <sam.verschueren@gmail.com>
 * @since  29 Jul. 2015
 */

// module dependencies
var Q = require('q');

(function() {

    /**
     * Initializes the library by creating a new AWS.Lambda object.
     *
     * @param {AWS}  AWS     The AWS object.
     */
    module.exports = function(AWS) {
        // Constructs a new lambda function
        module.exports.raw = new AWS.Lambda();

        // Return the exports object
        return module.exports;
    };

    /**
     * Invokes another lambda function synchronously. This means that the InvocationType is set
     * to `RequestResponse` and it will return after the called lambda function returns the result.
     *
     * @param  {string}     name        The name of the lambda function to invoke.
     * @param  {object}     payload     The payload that should be send to the lambda function.
     * @return {Promise}                The promise object.
     */
    module.exports.invoke = function(name, payload) {
        var lambda = this.raw;

        return Q.promise(function(resolve, reject) {
            if(!name) {
                // If the function is undefined, just resolve
                throw new Error('Please provide a name')
            }

            // Build up the message params
            var params = {
                FunctionName: name,
                InvocationType: 'RequestResponse',
                Payload: JSON.stringify(payload)
            };

            // Invoke another lambda function
            lambda.invoke(params, function(err, data) {
                if(err) {
                    // Reject if something went wrong
                    return reject(err);
                }

                // Resolve if everything went well
                resolve(JSON.parse(data.Payload));
            })
        });
    };

    /**
     * Invokes another lambda function asynchronously. This means that the InvocationType is set
     * to `Event` and it will return after the invocation succeeded.
     *
     * @param  {string}     name        The name of the lambda function to invoke.
     * @param  {object}     payload     The payload that should be send to the lambda function.
     * @return {Promise}                The promise object.
     */
    module.exports.invokeAsync = function(name, payload) {
        var lambda = this.raw;

        return Q.promise(function(resolve, reject) {
            if(!name) {
                // If the function is undefined, just resolve
                throw new Error('Please provide a name')
            }

            // Build up the message params
            var params = {
                FunctionName: name,
                InvocationType: 'Event',
                Payload: JSON.stringify(payload)
            };

            // Invoke another lambda function
            lambda.invoke(params, function(err, data) {
                if(err) {
                    // Reject if something went wrong
                    return reject(err);
                }

                // Resolve if everything went well
                resolve();
            })
        });
    };
})();<commit_msg>Added try-catch for JSON parsing<commit_after>'use strict';

/**
 * Library that makes it easier to invoke lambda functions with promises.
 *
 * @author Sam Verschueren      <sam.verschueren@gmail.com>
 * @since  29 Jul. 2015
 */

// module dependencies
var Q = require('q');

(function() {

    /**
     * Initializes the library by creating a new AWS.Lambda object.
     *
     * @param {AWS}  AWS     The AWS object.
     */
    module.exports = function(AWS) {
        // Constructs a new lambda function
        module.exports.raw = new AWS.Lambda();

        // Return the exports object
        return module.exports;
    };

    /**
     * Invokes another lambda function synchronously. This means that the InvocationType is set
     * to `RequestResponse` and it will return after the called lambda function returns the result.
     *
     * @param  {string}     name        The name of the lambda function to invoke.
     * @param  {object}     payload     The payload that should be send to the lambda function.
     * @return {Promise}                The promise object.
     */
    module.exports.invoke = function(name, payload) {
        var lambda = this.raw;

        return Q.promise(function(resolve, reject) {
            if(!name) {
                // If the function is undefined, just resolve
                throw new Error('Please provide a name')
            }

            // Build up the message params
            var params = {
                FunctionName: name,
                InvocationType: 'RequestResponse',
                Payload: JSON.stringify(payload)
            };

            // Invoke another lambda function
            lambda.invoke(params, function(err, data) {
                if(err) {
                    // Reject if something went wrong
                    return reject(err);
                }

                try {
                    // Try to parse the payload to JSON
                    resolve(JSON.parse(data.Payload));
                }
                catch(e) {
                    // Return the raw payload if it isn't JSON
                    resolve(data.Payload);
                }
            })
        });
    };

    /**
     * Invokes another lambda function asynchronously. This means that the InvocationType is set
     * to `Event` and it will return after the invocation succeeded.
     *
     * @param  {string}     name        The name of the lambda function to invoke.
     * @param  {object}     payload     The payload that should be send to the lambda function.
     * @return {Promise}                The promise object.
     */
    module.exports.invokeAsync = function(name, payload) {
        var lambda = this.raw;

        return Q.promise(function(resolve, reject) {
            if(!name) {
                // If the function is undefined, just resolve
                throw new Error('Please provide a name')
            }

            // Build up the message params
            var params = {
                FunctionName: name,
                InvocationType: 'Event',
                Payload: JSON.stringify(payload)
            };

            // Invoke another lambda function
            lambda.invoke(params, function(err, data) {
                if(err) {
                    // Reject if something went wrong
                    return reject(err);
                }

                // Resolve if everything went well
                resolve();
            })
        });
    };
})();<|endoftext|>


<commit_before>/**
 * main
 * @author iswujixiang@gmail.com
 */

const Stream    = require('stream');

const Koa       = require('koa');
const compose   = require('koa-compose');

const app       = new Koa;

module.exports  = (middleware) => (req, res, next) => {

    let ctx     = app.createContext(req, res);

    if (!Array.isArray(middleware)) {
        middleware = [middleware];
    }

    compose(middleware)(ctx)

        .then(() => {
            // allow bypassing koa
            /* istanbul ignore if */
            if (!ctx.respond) {
                return next();
            }

            const res = ctx.res;
            /* istanbul ignore if */
            if (!ctx.writable) {
                return next();
            }

            const {body} = ctx;
            if (null != body) {
                if (Buffer.isBuffer(body)) {
                    return res.send(body);
                }
                if (typeof body === 'string') {
                    return res.send(body);
                }
                if (body instanceof Stream) {
                    return body.pipe(res);
                }

                // body: json
                return res.json(body);
            }

            next();

        })

        .catch(next);
};
<commit_msg>fix(index.js): the effective value of the ctx.respond should strictly equal to false<commit_after>/**
 * main
 * @author iswujixiang@gmail.com
 */

const Stream    = require('stream');

const Koa       = require('koa');
const compose   = require('koa-compose');

const app       = new Koa;

module.exports  = (middleware) => (req, res, next) => {

    let ctx     = app.createContext(req, res);

    if (!Array.isArray(middleware)) {
        middleware = [middleware];
    }

    compose(middleware)(ctx)

        .then(() => {
            // allow bypassing koa
            /* istanbul ignore if */
            if (ctx.respond === false) {
                return next();
            }

            const res = ctx.res;
            /* istanbul ignore if */
            if (!ctx.writable) {
                return next();
            }

            const {body} = ctx;
            if (null != body) {
                if (Buffer.isBuffer(body)) {
                    return res.send(body);
                }
                if (typeof body === 'string') {
                    return res.send(body);
                }
                if (body instanceof Stream) {
                    return body.pipe(res);
                }

                // body: json
                return res.json(body);
            }

            next();

        })

        .catch(next);
};
<|endoftext|>