<commit_before>/**
 * @fileoverview A stream that reads in confidant's configuration files
 *               and writes out ninja build rules.
 */

let Transform = require('stream').Transform;
let debug = require('debug')('confidant/ninja_stream');
let dirname = require('path').dirname;
let flatten = require('lodash/array/flatten');
let glob = require('glob').sync;
let inherits = require('util').inherits;
let readFileSync = require('fs').readFileSync;

function NinjaStream() {
  Transform.call(this, { objectMode: true });
  this.id = 0;

  this.push(`# This ninja build file was generated by confidant.
# Do not modify it directly. Instead, modify one or
# more configure.js files.
`);
}

inherits(NinjaStream, Transform);

NinjaStream.prototype._transform = function(file, encoding, done) {
  debug(`Parsing ${file}`);
  let build = require(file);
  if (Array.isArray(build)) {
    debug('Build config sync');
    this._syncTransform(file, encoding, build, done);
  } else if (typeof build === 'function') {
    debug('Build config async');
    this._asyncTransform(file, encoding, build, done);
  } else {
    throw new Error(`Invalid build specified in ${file}`);
  }
};

NinjaStream.prototype._syncTransform = function(file, encoding, tasks, done) {
  let contents = readFileSync(file);
  let dir = dirname(file);

  debug(`Checking ${file}... found ${tasks.length} tasks`);

  tasks.forEach(task => {
    let rule = `rule-${this.id++}`;
    let js = task.rule.toString() + '.bind(' + JSON.stringify(task) + ')';  // Function.prototype.toString
    let cmd = ninjaEscape(`${contents}(${js})()`.replace(/(\n|\r)/g, ''));
    let inputs = flatten(
      task.inputs.map(input => {
        if (input.includes('*') ||
            input.includes('?') ||
            input.includes('[') ||
            input.includes('!') ||
            input.includes('+') ||
            input.includes('@')) {
          return glob(input, { cwd: dir });
        }

        return input;
      }),
      true /* isDeep */
    )
    .filter(input => input.indexOf(' ') === -1)  // ninja can't handle ws
    .map(input => `${dir}/${ninjaEscape(input)}`);
    let outputs = Array.isArray(task.outputs) ?
      task.outputs.map(output => `${dir}/${ninjaEscape(output)}`).join(' ') :
      `${dir}/${ninjaEscape(task.outputs)}`;

    this.push(`
rule ${rule}
  command = cd ${dir} && ${envToString(process.env)} node -e "${cmd}"

build ${outputs}: ${rule} ${inputs.join(' ')}
`);
  });

  debug(`Wrote rules from ${file} to build.ninja`);
  done();
};

NinjaStream.prototype._asyncTransform = function(file, encoding, RuleStream, done) {
  let tasks = [];
  let dir = dirname(file);
  let prev = process.cwd();
  process.chdir(dir);
  let stream = new RuleStream();
  stream.on('data', rule => tasks.push(rule));
  stream.on('end', () => this._syncTransform(file, encoding, tasks, done));
  process.chdir(prev);
};

function ninjaEscape(str) {
  return str
    .replace(new RegExp('\\$', 'g'), '$$$$')
    .replace(/"/g, '\\"');
}

function envToString(env) {
  let str = '';

  for (let key in env) {
    str += `${key}='${env[key]}' `;
  }

  return str.trim();
}

module.exports = NinjaStream;
<commit_msg>v0.3.5 - confidant should require configure.js files within their dir<commit_after>/**
 * @fileoverview A stream that reads in confidant's configuration files
 *               and writes out ninja build rules.
 */

let Transform = require('stream').Transform;
let debug = require('debug')('confidant/ninja_stream');
let dirname = require('path').dirname;
let flatten = require('lodash/array/flatten');
let glob = require('glob').sync;
let inherits = require('util').inherits;
let readFileSync = require('fs').readFileSync;

function NinjaStream() {
  Transform.call(this, { objectMode: true });
  this.id = 0;

  this.push(`# This ninja build file was generated by confidant.
# Do not modify it directly. Instead, modify one or
# more configure.js files.
`);
}

inherits(NinjaStream, Transform);

NinjaStream.prototype._transform = function(file, encoding, done) {
  debug(`Parsing ${file}`);
  let dir = dirname(file);
  let prev = process.cwd();
  process.chdir(dir);
  let build = require(`${dir}/configure.js`);
  process.chdir(prev);
  if (Array.isArray(build)) {
    debug('Build config sync');
    this._syncTransform(file, encoding, build, done);
  } else if (typeof build === 'function') {
    debug('Build config async');
    this._asyncTransform(file, encoding, build, done);
  } else {
    throw new Error(`Invalid build specified in ${file}`);
  }
};

NinjaStream.prototype._syncTransform = function(file, encoding, tasks, done) {
  let contents = readFileSync(file);
  let dir = dirname(file);

  debug(`Checking ${file}... found ${tasks.length} tasks`);

  tasks.forEach(task => {
    let rule = `rule-${this.id++}`;
    let js = task.rule.toString() + '.bind(' + JSON.stringify(task) + ')';  // Function.prototype.toString
    let cmd = ninjaEscape(`${contents}(${js})()`.replace(/(\n|\r)/g, ''));
    let inputs = flatten(
      task.inputs.map(input => {
        if (input.includes('*') ||
            input.includes('?') ||
            input.includes('[') ||
            input.includes('!') ||
            input.includes('+') ||
            input.includes('@')) {
          return glob(input, { cwd: dir });
        }

        return input;
      }),
      true /* isDeep */
    )
    .filter(input => input.indexOf(' ') === -1)  // ninja can't handle ws
    .map(input => `${dir}/${ninjaEscape(input)}`);
    let outputs = Array.isArray(task.outputs) ?
      task.outputs.map(output => `${dir}/${ninjaEscape(output)}`).join(' ') :
      `${dir}/${ninjaEscape(task.outputs)}`;

    this.push(`
rule ${rule}
  command = cd ${dir} && ${envToString(process.env)} node -e "${cmd}"

build ${outputs}: ${rule} ${inputs.join(' ')}
`);
  });

  debug(`Wrote rules from ${file} to build.ninja`);
  done();
};

NinjaStream.prototype._asyncTransform = function(file, encoding, RuleStream, done) {
  let tasks = [];
  let dir = dirname(file);
  let prev = process.cwd();
  process.chdir(dir);
  let stream = new RuleStream();
  stream.on('data', rule => tasks.push(rule));
  stream.on('end', () => this._syncTransform(file, encoding, tasks, done));
  process.chdir(prev);
};

function ninjaEscape(str) {
  return str
    .replace(new RegExp('\\$', 'g'), '$$$$')
    .replace(/"/g, '\\"');
}

function envToString(env) {
  let str = '';

  for (let key in env) {
    str += `${key}='${env[key]}' `;
  }

  return str.trim();
}

module.exports = NinjaStream;
<|endoftext|>


<commit_before>'use strict';

// Optional args: date
function time_date_to_timestamp(args){
    args = core_args({
      'args': args,
      'defaults': {
        'date': time_timestamp_to_date(),
      },
    });

    return new Date(
      Date.UTC(
        args['date']['year'],
        args['date']['month'] - 1,
        args['date']['date'],
        args['date']['hour'],
        args['date']['minute'],
        args['date']['second'],
        args['date']['millisecond']
      )
    ).getTime();
}

// Required args: target
// Optional args: now
function time_diff(args){
    args = core_args({
      'args': args,
      'defaults': {
        'now': time_date_to_timestamp(),
      },
    });

    var diff = args['target'] - args['now'];
    var prefix = '';
    if(diff < 0){
        diff = -diff;
        prefix = '-';
    }

    var date = time_timestamp_to_date({
      'timestamp': diff,
    });

    return prefix + Math.floor(diff / 86400000) + ':' + date['hour'] + ':' + date['minute'] + ':' + date['second'];
}

// Optional args: date
function time_format_date(args){
    args = core_args({
      'args': args,
      'defaults': {
        'date': time_timestamp_to_date(),
      },
    });

    return args['date']['year']
      + '-'
      + args['date']['month']
      + '-'
      + args['date']['date']
      + ' '
      + args['date']['hour']
      + ':'
      + args['date']['minute']
      + ':'
      + args['date']['second']
      + ' ('
      + args['date']['timezone']
      + ')';
}

// Optional args: timestamp
function time_timestamp_to_date(args){
    args = core_args({
      'args': args,
    });
    args['timestamp'] = args['timestamp'] !== void 0
      ? new Date(args['timestamp']).getTime()
      : new Date().getTime();

    var date = new Date(args['timestamp']);
    return {
      'date': date.getUTCDate(),
      'day': time_two_digits({
        'number': date.getUTCDay(),
      }),
      'hour': time_two_digits({
        'number': date.getUTCHours(),
      }),
      'millisecond': time_two_digits({
        'number': date.getUTCMilliseconds(),
      }),
      'minute': time_two_digits({
        'number': date.getUTCMinutes(),
      }),
      'month': time_two_digits({
        'number': date.getUTCMonth() + 1,
      }),
      'second': time_two_digits({
        'number': date.getUTCSeconds(),
      }),
      'timestamp': args['timestamp'],
      'timezone': 0,
      'year': date.getUTCFullYear(),
    };
}

// Required args: number
function time_two_digits(args){
    return args['number'].toString().length < 2
      ? '0' + args['number']
      : args['number'];
}
<commit_msg>added time_from_inputs()<commit_after>'use strict';

// Optional args: date
function time_date_to_timestamp(args){
    args = core_args({
      'args': args,
      'defaults': {
        'date': time_timestamp_to_date(),
      },
    });

    return new Date(
      Date.UTC(
        args['date']['year'],
        args['date']['month'] - 1,
        args['date']['date'],
        args['date']['hour'],
        args['date']['minute'],
        args['date']['second'],
        args['date']['millisecond']
      )
    ).getTime();
}

// Required args: target
// Optional args: now
function time_diff(args){
    args = core_args({
      'args': args,
      'defaults': {
        'now': time_date_to_timestamp(),
      },
    });

    var diff = args['target'] - args['now'];
    var prefix = '';
    if(diff < 0){
        diff = -diff;
        prefix = '-';
    }

    var date = time_timestamp_to_date({
      'timestamp': diff,
    });

    return prefix + Math.floor(diff / 86400000) + ':' + date['hour'] + ':' + date['minute'] + ':' + date['second'];
}

// Optional args: date
function time_format_date(args){
    args = core_args({
      'args': args,
      'defaults': {
        'date': time_timestamp_to_date(),
      },
    });

    return args['date']['year']
      + '-'
      + args['date']['month']
      + '-'
      + args['date']['date']
      + ' '
      + args['date']['hour']
      + ':'
      + args['date']['minute']
      + ':'
      + args['date']['second']
      + ' ('
      + args['date']['timezone']
      + ')';
}

function time_from_inputs(){
    var date = {
      'date': 0,
      'hour': 0,
      'millisecond': 0,
      'minute': 0,
      'month': 0,
      'second': 0,
      'timezone': 0,
      'year': 0,
    };
    for(var value in date){
        var element = document.getElementById(value);
        if(element){
            date[value] = parseInt(
              element.value,
              10
            );
        }

        if(isNaN(date[value])){
            date[value] = 0;
        }
    }

    return time_date_to_timestamp({
      'date': date,
    });
}

// Optional args: timestamp
function time_timestamp_to_date(args){
    args = core_args({
      'args': args,
    });
    args['timestamp'] = args['timestamp'] !== void 0
      ? new Date(args['timestamp']).getTime()
      : new Date().getTime();

    var date = new Date(args['timestamp']);
    return {
      'date': date.getUTCDate(),
      'day': time_two_digits({
        'number': date.getUTCDay(),
      }),
      'hour': time_two_digits({
        'number': date.getUTCHours(),
      }),
      'millisecond': time_two_digits({
        'number': date.getUTCMilliseconds(),
      }),
      'minute': time_two_digits({
        'number': date.getUTCMinutes(),
      }),
      'month': time_two_digits({
        'number': date.getUTCMonth() + 1,
      }),
      'second': time_two_digits({
        'number': date.getUTCSeconds(),
      }),
      'timestamp': args['timestamp'],
      'timezone': 0,
      'year': date.getUTCFullYear(),
    };
}

// Required args: number
function time_two_digits(args){
    return args['number'].toString().length < 2
      ? '0' + args['number']
      : args['number'];
}
<|endoftext|>


<commit_before>'use strict';

var Defaults = {};

Defaults.MIN_FEE_PER_KB = 0;
Defaults.MAX_FEE_PER_KB = 1000000;
Defaults.MIN_TX_FEE = 0;
Defaults.MAX_TX_FEE = 0.1 * 1e8;
Defaults.MAX_TX_SIZE_IN_KB = 100;

Defaults.MAX_KEYS = 100;

// Time after which a tx proposal can be erased by any copayer. in seconds
Defaults.DELETE_LOCKTIME = 600;

// Allowed consecutive txp rejections before backoff is applied.
Defaults.BACKOFF_OFFSET = 10;

// Time a copayer need to wait to create a new tx after her previous proposal was rejected. in seconds.
Defaults.BACKOFF_TIME = 600;

Defaults.MAX_MAIN_ADDRESS_GAP = 20;

// TODO: should allow different gap sizes for external/internal chains
Defaults.SCAN_ADDRESS_GAP = Defaults.MAX_MAIN_ADDRESS_GAP + 20;

Defaults.FEE_LEVELS = {
  btc: [{
    name: 'urgent',
    nbBlocks: 2,
    multiplier: 1.5,
    defaultValue: 150000,
  }, {
    name: 'priority',
    nbBlocks: 2,
    defaultValue: 100000
  }, {
    name: 'normal',
    nbBlocks: 3,
    defaultValue: 80000
  }, {
    name: 'economy',
    nbBlocks: 6,
    defaultValue: 50000
  }, {
    name: 'superEconomy',
    nbBlocks: 24,
    defaultValue: 20000
  }],
  bch: [{
    name: 'normal',
    nbBlocks: 2,
    defaultValue: 2000,
  }]
};

// How many levels to fallback to if the value returned by the network for a given nbBlocks is -1
Defaults.FEE_LEVELS_FALLBACK = 2;

// Minimum nb of addresses a wallet must have to start using 2-step balance optimization
Defaults.TWO_STEP_BALANCE_THRESHOLD = 100;

// Age Limit for addresses to be considered 'active' always
Defaults.TWO_STEP_CREATION_HOURS = 24;

// Time to prevent re-quering inactive addresses (MIN)
Defaults.TWO_STEP_INACTIVE_CLEAN_DURATION_MIN = 60;

Defaults.FIAT_RATE_PROVIDER = 'BitPay';
Defaults.FIAT_RATE_FETCH_INTERVAL = 10; // In minutes
Defaults.FIAT_RATE_MAX_LOOK_BACK_TIME = 120; // In minutes

Defaults.HISTORY_LIMIT = 50;

// The maximum amount of an UTXO to be considered too big to be used in the tx before exploring smaller
// alternatives (proportinal to tx amount).
Defaults.UTXO_SELECTION_MAX_SINGLE_UTXO_FACTOR = 2;

// The minimum amount an UTXO need to contribute proportional to tx amount.
Defaults.UTXO_SELECTION_MIN_TX_AMOUNT_VS_UTXO_FACTOR = 0.1;

// The maximum threshold to consider fees non-significant in relation to tx amount.
Defaults.UTXO_SELECTION_MAX_FEE_VS_TX_AMOUNT_FACTOR = 0.05;

// The maximum amount to pay for using small inputs instead of one big input
// when fees are significant (proportional to how much we would pay for using that big input only).
Defaults.UTXO_SELECTION_MAX_FEE_VS_SINGLE_UTXO_FEE_FACTOR = 5;

// Minimum allowed amount for tx outputs (including change) in SAT
Defaults.MIN_OUTPUT_AMOUNT = 5000;

// Number of confirmations from which tx in history will be cached
// (ie we consider them inmutables)
Defaults.CONFIRMATIONS_TO_START_CACHING = 6 * 6; // ~ 6hrs

// Number of addresses from which tx history is enabled in a wallet
Defaults.HISTORY_CACHE_ADDRESS_THRESOLD = 100;

// Cache time for blockchain height (in seconds)
Defaults.BLOCKHEIGHT_CACHE_TIME = 10 * 60;

// Max allowed timespan for notification queries in seconds
Defaults.MAX_NOTIFICATIONS_TIMESPAN = 60 * 60 * 24 * 14; // ~ 2 weeks
Defaults.NOTIFICATIONS_TIMESPAN = 60;

Defaults.SESSION_EXPIRATION = 1 * 60 * 60; // 1 hour to session expiration

Defaults.RateLimit = {
  createWallet: {
    windowMs: 60 * 60 * 1000, // hour window
    delayAfter: 8, // begin slowing down responses after the 3rd request
    delayMs: 3000, // slow down subsequent responses by 3 seconds per request
    max: 15, // start blocking after 20 request
    message: "Too many wallets created from this IP, please try again after an hour"
  },
  estimateFee: {
   windowMs: 60 * 10 *1000, // 10 min window
    delayAfter: 5, // begin slowing down responses after the 3rd request
    delayMs: 300, // slow down subsequent responses by 3 seconds per request

    max: 10, // start blocking after 200 request
    message: "Too many request"
  },

  // otherPosts: {
  //   windowMs: 60 * 60 * 1000, // 1 hour window
  //   max: 1200 , // 1 post every 3 sec average, max.
  // },
};

Defaults.COIN = 'btc';

module.exports = Defaults;
<commit_msg>change default<commit_after>'use strict';

var Defaults = {};

Defaults.MIN_FEE_PER_KB = 0;
Defaults.MAX_FEE_PER_KB = 1000000;
Defaults.MIN_TX_FEE = 0;
Defaults.MAX_TX_FEE = 0.1 * 1e8;
Defaults.MAX_TX_SIZE_IN_KB = 100;

Defaults.MAX_KEYS = 100;

// Time after which a tx proposal can be erased by any copayer. in seconds
Defaults.DELETE_LOCKTIME = 600;

// Allowed consecutive txp rejections before backoff is applied.
Defaults.BACKOFF_OFFSET = 10;

// Time a copayer need to wait to create a new tx after her previous proposal was rejected. in seconds.
Defaults.BACKOFF_TIME = 600;

Defaults.MAX_MAIN_ADDRESS_GAP = 20;

// TODO: should allow different gap sizes for external/internal chains
Defaults.SCAN_ADDRESS_GAP = Defaults.MAX_MAIN_ADDRESS_GAP + 20;

Defaults.FEE_LEVELS = {
  btc: [{
    name: 'urgent',
    nbBlocks: 2,
    multiplier: 1.5,
    defaultValue: 150000,
  }, {
    name: 'priority',
    nbBlocks: 2,
    defaultValue: 100000
  }, {
    name: 'normal',
    nbBlocks: 3,
    defaultValue: 80000
  }, {
    name: 'economy',
    nbBlocks: 6,
    defaultValue: 50000
  }, {
    name: 'superEconomy',
    nbBlocks: 24,
    defaultValue: 20000
  }],
  bch: [{
    name: 'normal',
    nbBlocks: 2,
    defaultValue: 2000,
  }]
};

// How many levels to fallback to if the value returned by the network for a given nbBlocks is -1
Defaults.FEE_LEVELS_FALLBACK = 2;

// Minimum nb of addresses a wallet must have to start using 2-step balance optimization
Defaults.TWO_STEP_BALANCE_THRESHOLD = 100;

// Age Limit for addresses to be considered 'active' always
Defaults.TWO_STEP_CREATION_HOURS = 24;

// Time to prevent re-quering inactive addresses (MIN)
Defaults.TWO_STEP_INACTIVE_CLEAN_DURATION_MIN = 120;

Defaults.FIAT_RATE_PROVIDER = 'BitPay';
Defaults.FIAT_RATE_FETCH_INTERVAL = 10; // In minutes
Defaults.FIAT_RATE_MAX_LOOK_BACK_TIME = 120; // In minutes

Defaults.HISTORY_LIMIT = 50;

// The maximum amount of an UTXO to be considered too big to be used in the tx before exploring smaller
// alternatives (proportinal to tx amount).
Defaults.UTXO_SELECTION_MAX_SINGLE_UTXO_FACTOR = 2;

// The minimum amount an UTXO need to contribute proportional to tx amount.
Defaults.UTXO_SELECTION_MIN_TX_AMOUNT_VS_UTXO_FACTOR = 0.1;

// The maximum threshold to consider fees non-significant in relation to tx amount.
Defaults.UTXO_SELECTION_MAX_FEE_VS_TX_AMOUNT_FACTOR = 0.05;

// The maximum amount to pay for using small inputs instead of one big input
// when fees are significant (proportional to how much we would pay for using that big input only).
Defaults.UTXO_SELECTION_MAX_FEE_VS_SINGLE_UTXO_FEE_FACTOR = 5;

// Minimum allowed amount for tx outputs (including change) in SAT
Defaults.MIN_OUTPUT_AMOUNT = 5000;

// Number of confirmations from which tx in history will be cached
// (ie we consider them inmutables)
Defaults.CONFIRMATIONS_TO_START_CACHING = 6 * 6; // ~ 6hrs

// Number of addresses from which tx history is enabled in a wallet
Defaults.HISTORY_CACHE_ADDRESS_THRESOLD = 100;

// Cache time for blockchain height (in seconds)
Defaults.BLOCKHEIGHT_CACHE_TIME = 10 * 60;

// Max allowed timespan for notification queries in seconds
Defaults.MAX_NOTIFICATIONS_TIMESPAN = 60 * 60 * 24 * 14; // ~ 2 weeks
Defaults.NOTIFICATIONS_TIMESPAN = 60;

Defaults.SESSION_EXPIRATION = 1 * 60 * 60; // 1 hour to session expiration

Defaults.RateLimit = {
  createWallet: {
    windowMs: 60 * 60 * 1000, // hour window
    delayAfter: 8, // begin slowing down responses after the 3rd request
    delayMs: 3000, // slow down subsequent responses by 3 seconds per request
    max: 15, // start blocking after 20 request
    message: "Too many wallets created from this IP, please try again after an hour"
  },
  estimateFee: {
   windowMs: 60 * 10 *1000, // 10 min window
    delayAfter: 5, // begin slowing down responses after the 3rd request
    delayMs: 300, // slow down subsequent responses by 3 seconds per request

    max: 10, // start blocking after 200 request
    message: "Too many request"
  },

  // otherPosts: {
  //   windowMs: 60 * 60 * 1000, // 1 hour window
  //   max: 1200 , // 1 post every 3 sec average, max.
  // },
};

Defaults.COIN = 'btc';

module.exports = Defaults;
<|endoftext|>


<commit_before>// Copyright 2013 Joyent, Inc.  All rights reserved.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

var util = require('util');

var assert = require('assert-plus');

///--- API

/**
 * A set of helper functions for "serdes" on XDR datatypes.
 *
 * Really the purpose to this utility is to keep track of an offset
 * so upstack code is cleaner.
 *
 * For a full description, see: http://tools.ietf.org/html/rfc4506
 */
function XDR(buf) {
    if (buf)
        assert.ok(Buffer.isBuffer(buf), 'buffer is required');

    this.xdr_buffer = buf || null;
    this.xdr_offset = 0;
}

XDR.byteLength = function byteLength(arg) {
    var len = 0;
    if (typeof (arg) === 'string') {
        len = Buffer.byteLength(arg, 'ascii');
        len += 4 + (len % 4 !== 0 ? (4 - (len % 4)) : 0);
    } else if (Array.isArray(arg)) {
        assert.arrayOfNumber(arg, 'array');
        len = 4 + (4 * arg.length);
    } else if (Buffer.isBuffer(arg)) {
        len = arg.length;
        len += 4 + (len % 4 !== 0 ? (4 - (len % 4)) : 0);
    } else {
        throw new TypeError(typeof (arg) + ' not supported');
    }

    return (len);
};

XDR.prototype.append = function append(buf) {
    assert.ok(Buffer.isBuffer(buf), 'buffer is required');

    if (this.xdr_buffer) {
        this.xdr_buffer = Buffer.concat(this.xdr_buffer, buf);
    } else {
        this.xdr_buffer = buf;
    }
};

XDR.prototype.buffer = function buffer() {
    return (this.xdr_buffer);
};

XDR.prototype.byteLength = function (str) {
    return (XDR.byteLength(str));
};

XDR.prototype.fill = function fill() {
    return (this.xdr_buffer.fill.apply(this.xdr_buffer, arguments));
};

XDR.prototype.offset = function offset() {
    return (this.xdr_offset);
};

XDR.prototype.readBool = function readBool() {
    var tmp = this.readInt();
    return (tmp === 1 ? true : false);
};

XDR.prototype.readByte = function readByte() {
    return (this.xdr_buffer[this.xdr_offset++]);
};

XDR.prototype.readDouble = function readDouble() {
    this.readInt();  // throw away TODO XXX
    var i = this.readInt();

    return (i);
};

XDR.prototype.readInt = function readInt() {
    var i = this.xdr_buffer.readUInt32BE(this.xdr_offset);
    this.xdr_offset += 4;

    return (i >>> 0);
};

XDR.prototype.readIntArray = function readIntArray() {
    var arr = [];
    var num = this.readInt();

    for (var i = 0; i < num; i++)
        arr.push(this.readInt());

    return (arr);
};

XDR.prototype.readOpaque = function readOpaque() {
    assert.optionalNumber(len, 'size');

    var len = this.readInt();

    var end = this.xdr_offset + len;
    var data = this.xdr_buffer.slice(this.xdr_offset, end);
    this.xdr_offset += len;

    // skip padding
    if (len % 4 !== 0)
        this.xdr_offset += (4 - (len % 4));

    return (data);
};

XDR.prototype.readString = function readString() {
    var len = this.readInt();

    var end = this.xdr_offset + len;
    var str = this.xdr_buffer.toString('ascii', this.xdr_offset, end);
    this.xdr_offset += len;

    // skip padding
    if (len % 4 !== 0)
        this.xdr_offset += (4 - (len % 4));

    return (str);
};

XDR.prototype.remain = function remain() {
    return (this.xdr_buffer.length - this.xdr_offset);
};

XDR.prototype.rewind = function rewind(off) {
    assert.optionalNumber(off, 'offset');
    this.xdr_offset = off || 0;
};

XDR.prototype.size = function size() {
    return (this.xdr_buffer.length);
};

XDR.prototype.slice = function slice(start, end) {
    assert.optionalNumber(start, 'start');
    assert.optionalNumber(end, 'end');

    return (this.xdr_buffer.slice(start || this.xdr_offset, end));
};

XDR.prototype.toString = function toString() {
    return (util.format('[object XDR <size=%d, offset=%d>]',
                        this.xdr_buffer ? this.xdr_buffer.length : 0,
                        this.xdr_offset));
};

XDR.prototype.writeByte = function writeByte(num) {
    assert.number(num, 'integer');

    this.xdr_buffer.writeUInt8(num, this.xdr_offset);
    this.xdr_offset += 1;
};

XDR.prototype.writeBool = function writeBool(val) {
    assert.bool(val, 'boolean');

    this.writeInt(val ? 1 : 0);
};

XDR.prototype.writeDouble = function writeDouble(num) {
    assert.number(num, 'integer');

    // only 32b for now TODO XXX
    this.writeInt(0);
    this.writeInt(num);
};

XDR.prototype.writeInt = function writeInt(num) {
    assert.number(num, 'integer');

    this.xdr_buffer.writeUInt32BE((num >>> 0), this.xdr_offset);
    this.xdr_offset += 4;
};

XDR.prototype.writeIntArray = function writeIntArray(arr) {
    assert.arrayOfNumber(arr, 'array');

    var self = this;

    this.writeInt(arr.length);
    arr.forEach(function (i) {
        self.writeInt(i);
    });
};

XDR.prototype.writeOpaque = function writeOpaque(buf, len) {
    assert.ok(Buffer.isBuffer(buf), 'buffer');
    assert.optionalNumber(len, 'size');

    len = len || buf.length;

    this.writeInt(len);
    buf.copy(this.xdr_buffer, this.xdr_offset, 0, len);
    this.xdr_offset += len;

    this._pad(len);
};

XDR.prototype.writeRaw = function writeRaw(buf) {
    assert.ok(Buffer.isBuffer(buf), 'buffer');

    buf.copy(this.xdr_buffer, this.xdr_offset);
    this.xdr_offset += buf.length;
};

XDR.prototype.writeShort = function writeShort(num) {
    assert.number(num, 'integer');

    this.xdr_buffer.writeUInt16BE(num, this.xdr_offset);
    this.xdr_offset += 2;
};

XDR.prototype.writeString = function writeString(str) {
    assert.string(str, 'string');

    var len = Buffer.byteLength(str, 'ascii');
    var end = this.xdr_offset + len;

    this.writeInt(len);
    this.xdr_buffer.write(str, this.xdr_offset, end, 'ascii');
    this.xdr_offset += len;

    this._pad(len);
};

XDR.prototype._pad = function _pad(len) {
    var pad = (len % 4 !== 0 ? (4 - (len % 4)) : 0);

    if (pad) {
        this.xdr_buffer.fill(0, this.xdr_offset, this.xdr_offset + pad);
        this.xdr_offset += pad;
    }
};

///--- Exports

module.exports = {
    XDR: XDR
};
<commit_msg>MANTA-1844: add back xdr.readRaw(n)<commit_after>// Copyright 2013 Joyent, Inc.  All rights reserved.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

var util = require('util');

var assert = require('assert-plus');

///--- API

/**
 * A set of helper functions for "serdes" on XDR datatypes.
 *
 * Really the purpose to this utility is to keep track of an offset
 * so upstack code is cleaner.
 *
 * For a full description, see: http://tools.ietf.org/html/rfc4506
 */
function XDR(buf) {
    if (buf)
        assert.ok(Buffer.isBuffer(buf), 'buffer is required');

    this.xdr_buffer = buf || null;
    this.xdr_offset = 0;
}

XDR.byteLength = function byteLength(arg) {
    var len = 0;
    if (typeof (arg) === 'string') {
        len = Buffer.byteLength(arg, 'ascii');
        len += 4 + (len % 4 !== 0 ? (4 - (len % 4)) : 0);
    } else if (Array.isArray(arg)) {
        assert.arrayOfNumber(arg, 'array');
        len = 4 + (4 * arg.length);
    } else if (Buffer.isBuffer(arg)) {
        len = arg.length;
        len += 4 + (len % 4 !== 0 ? (4 - (len % 4)) : 0);
    } else {
        throw new TypeError(typeof (arg) + ' not supported');
    }

    return (len);
};

XDR.prototype.append = function append(buf) {
    assert.ok(Buffer.isBuffer(buf), 'buffer is required');

    if (this.xdr_buffer) {
        this.xdr_buffer = Buffer.concat(this.xdr_buffer, buf);
    } else {
        this.xdr_buffer = buf;
    }
};

XDR.prototype.buffer = function buffer() {
    return (this.xdr_buffer);
};

XDR.prototype.byteLength = function (str) {
    return (XDR.byteLength(str));
};

XDR.prototype.fill = function fill() {
    return (this.xdr_buffer.fill.apply(this.xdr_buffer, arguments));
};

XDR.prototype.offset = function offset() {
    return (this.xdr_offset);
};

XDR.prototype.readBool = function readBool() {
    var tmp = this.readInt();
    return (tmp === 1 ? true : false);
};

XDR.prototype.readByte = function readByte() {
    return (this.xdr_buffer[this.xdr_offset++]);
};

XDR.prototype.readDouble = function readDouble() {
    this.readInt();  // throw away TODO XXX
    var i = this.readInt();

    return (i);
};

XDR.prototype.readInt = function readInt() {
    var i = this.xdr_buffer.readUInt32BE(this.xdr_offset);
    this.xdr_offset += 4;

    return (i >>> 0);
};

XDR.prototype.readIntArray = function readIntArray() {
    var arr = [];
    var num = this.readInt();

    for (var i = 0; i < num; i++)
        arr.push(this.readInt());

    return (arr);
};

XDR.prototype.readOpaque = function readOpaque() {
    assert.optionalNumber(len, 'size');

    var len = this.readInt();

    var end = this.xdr_offset + len;
    var data = this.xdr_buffer.slice(this.xdr_offset, end);
    this.xdr_offset += len;

    // skip padding
    if (len % 4 !== 0)
        this.xdr_offset += (4 - (len % 4));

    return (data);
};

XDR.prototype.readRaw = function readRaw(sz) {
    assert.number(sz, 'size');

    var data = this.xdr_buffer.slice(this.xdr_offset, this.xdr_offset + sz);
    this.xdr_offset += sz;

    return (data);
};

XDR.prototype.readString = function readString() {
    var len = this.readInt();

    var end = this.xdr_offset + len;
    var str = this.xdr_buffer.toString('ascii', this.xdr_offset, end);
    this.xdr_offset += len;

    // skip padding
    if (len % 4 !== 0)
        this.xdr_offset += (4 - (len % 4));

    return (str);
};

XDR.prototype.remain = function remain() {
    return (this.xdr_buffer.length - this.xdr_offset);
};

XDR.prototype.rewind = function rewind(off) {
    assert.optionalNumber(off, 'offset');
    this.xdr_offset = off || 0;
};

XDR.prototype.size = function size() {
    return (this.xdr_buffer.length);
};

XDR.prototype.slice = function slice(start, end) {
    assert.optionalNumber(start, 'start');
    assert.optionalNumber(end, 'end');

    return (this.xdr_buffer.slice(start || this.xdr_offset, end));
};

XDR.prototype.toString = function toString() {
    return (util.format('[object XDR <size=%d, offset=%d>]',
                        this.xdr_buffer ? this.xdr_buffer.length : 0,
                        this.xdr_offset));
};

XDR.prototype.writeByte = function writeByte(num) {
    assert.number(num, 'integer');

    this.xdr_buffer.writeUInt8(num, this.xdr_offset);
    this.xdr_offset += 1;
};

XDR.prototype.writeBool = function writeBool(val) {
    assert.bool(val, 'boolean');

    this.writeInt(val ? 1 : 0);
};

XDR.prototype.writeDouble = function writeDouble(num) {
    assert.number(num, 'integer');

    // only 32b for now TODO XXX
    this.writeInt(0);
    this.writeInt(num);
};

XDR.prototype.writeInt = function writeInt(num) {
    assert.number(num, 'integer');

    this.xdr_buffer.writeUInt32BE((num >>> 0), this.xdr_offset);
    this.xdr_offset += 4;
};

XDR.prototype.writeIntArray = function writeIntArray(arr) {
    assert.arrayOfNumber(arr, 'array');

    var self = this;

    this.writeInt(arr.length);
    arr.forEach(function (i) {
        self.writeInt(i);
    });
};

XDR.prototype.writeOpaque = function writeOpaque(buf, len) {
    assert.ok(Buffer.isBuffer(buf), 'buffer');
    assert.optionalNumber(len, 'size');

    len = len || buf.length;

    this.writeInt(len);
    buf.copy(this.xdr_buffer, this.xdr_offset, 0, len);
    this.xdr_offset += len;

    this._pad(len);
};

XDR.prototype.writeRaw = function writeRaw(buf) {
    assert.ok(Buffer.isBuffer(buf), 'buffer');

    buf.copy(this.xdr_buffer, this.xdr_offset);
    this.xdr_offset += buf.length;
};

XDR.prototype.writeShort = function writeShort(num) {
    assert.number(num, 'integer');

    this.xdr_buffer.writeUInt16BE(num, this.xdr_offset);
    this.xdr_offset += 2;
};

XDR.prototype.writeString = function writeString(str) {
    assert.string(str, 'string');

    var len = Buffer.byteLength(str, 'ascii');
    var end = this.xdr_offset + len;

    this.writeInt(len);
    this.xdr_buffer.write(str, this.xdr_offset, end, 'ascii');
    this.xdr_offset += len;

    this._pad(len);
};

XDR.prototype._pad = function _pad(len) {
    var pad = (len % 4 !== 0 ? (4 - (len % 4)) : 0);

    if (pad) {
        this.xdr_buffer.fill(0, this.xdr_offset, this.xdr_offset + pad);
        this.xdr_offset += pad;
    }
};

///--- Exports

module.exports = {
    XDR: XDR
};
<|endoftext|>


<commit_before>import UserPage from './UserPage';
import DiscussionList from './DiscussionList';
import DiscussionListState from '../states/DiscussionListState';

/**
 * The `DiscussionsUserPage` component shows a discussion list inside of a user
 * page.
 */
export default class DiscussionsUserPage extends UserPage {
  oninit(vnode) {
    super.oninit(vnode);

    this.loadUser(m.route.param('username'));
  }

  show(user) {
    super.show(user);

    this.state = new DiscussionListState({
      q: 'author:' + user.username(),
      sort: 'newest',
    });

    this.state.refresh();
  }

  content() {
    return
{DiscussionList.component({ state: this.state })}
;
  }
}
<commit_msg>Use `author` filter parameter instead of `q` with gambit to get a user's discussions on the `DiscussionsUserPage` (#3068)<commit_after>import UserPage from './UserPage';
import DiscussionList from './DiscussionList';
import DiscussionListState from '../states/DiscussionListState';

/**
 * The `DiscussionsUserPage` component shows a discussion list inside of a user
 * page.
 */
export default class DiscussionsUserPage extends UserPage {
  oninit(vnode) {
    super.oninit(vnode);

    this.loadUser(m.route.param('username'));
  }

  show(user) {
    super.show(user);

    this.state = new DiscussionListState({
      filter: { author: user.username() },
      sort: 'newest',
    });

    this.state.refresh();
  }

  content() {
    return
{DiscussionList.component({ state: this.state })}
;
  }
}
<|endoftext|>


<commit_before>'use strict';

const enums = require('./constants');
const exit = require('./cleanup');
const uuid = require('uuid');
const debug = require('debug')('busy:node');
const Message = require('./message');
const noop = require('./noop');
const EventEmitter = require('events');
const net = require('net');
const extend = require('gextend');
const Keypath = require('gkeypath');

const utils = require('./utils');

class Node extends EventEmitter {
    constructor(config, callback) {
        super();

        //TODO: Remove this!
        if (!utils._isObject(config)) {
            config = {};
            var args = [].slice.call(arguments);
            args.map(arg => {
                if (utils._isString(arg)) {
                    return config.id = arg;
                }
                if (utils._isNumber(arg)) {
                    return config.port = arg;
                }
                if (utils._isFunction(arg)) {
                    config.onConnect = arg;
                }
            });
        }

        if (callback) {
            config.onConnect = callback;
        }

        config = extend({}, {
            id: uuid.v4(),
            onConnect: noop,
            maxConnectionAttempts: 5,
            timeout: 0
        }, config);

        if (!config.port && !config.path) {
            config.port = enums.DEFAULT_PORT;
        }

        this._config = config;

        // Set up an object to store waiting callbacks
        this._callbacks = {};
        this._isConnected = false;
        this._connectionAttempts = 0;
        this._connectBridge();
    }

    /**
     * TODO: Rename to publish
     * Node#tell()
     *
     * @param {string} whoWhat - the node name and event
     *                         in the following format:
     *                         "node_name:event_type"
     * @param {csv} args - any amount of arguments to be
     *                    sent along with the remote event
     * @param {function} callback - a callback to be run
     *                            when the remote event calls
     *                            its callback
     *
     * @return {Node}
     */
    tell( /*whoWhat, ...args, callback*/ ) {

        const self = this;
        const args = [].slice.call(arguments);
        // parse the arguments special array into a standard array

        // grab the who-what off the front
        const whoWhat = args.shift();

        let callback;

        // is there a function on the end here?
        if (utils._isFunction(utils._last(args))) {
            // cool, pop it off so we can store it in the waiters
            callback = args.pop();
        }

        //nodeName:eventName e.g. node1:ping
        const parts = whoWhat.split(':');

        if (parts.length !== 2) {
            throw new Error('Invalid tell statement, should be (node_name:event_name)');
        }

        const [nodeName, eventName] = parts;
        const destination = [nodeName, eventName, args];

        const msg = new Message(enums.TELL, destination);

        if (callback) {
            self._callbacks[msg.getId()] = callback;
        }

        self._writeBridge(msg);
        return self;
    }

    /**
     * Rename to broadcast
     */
    shout() {
        this._writeBridge(new Message(enums.SHOUT, [].slice.call(arguments)));
        return this;
    }

    leave(force) {
        if (force) {
            debug('node force leaving');
            return this._forceLeave();
        }

        debug('node safely leaving');

        const msg = new Message(enums.LEAVE);

        this._callbacks[msg.getId()] = function() {
            this._forceLeave();
        };

        this._writeBridge(msg);

        return this;
    }

    _forceLeave() {
        this._bridge.end();
        this.emit('leave.force');
        return this;
    }

    _connectBridge() {
        if (this._bridge) {
            this._bridge.removeAllListeners();
        }

        this._bridge = null;

        // Lets connect to the Bridge
        this._bridge = net.connect(this._config);
        // this._bridge = require('./transport').createServer(this._onConnection.bind(this));

        this._registerSignalHandlers();

        this._bridge.setTimeout(this._config.timeout);
        this._bridge.on('data', this._onData.bind(this));
        this._bridge.on('connect', this._onConnect.bind(this));
        this._bridge.on('error', this._onSocketError.bind(this));
    }

    _onConnect() {
        // Set hasConnected to true, so if the socket errors out we won't attempt
        // to reconnect.
        this._isConnected = true;

        // Identify the node to the bridge
        debug('sending IDENT');

        // Create a new Message
        const ident = new Message(enums.IDENT);

        // Get the ID of the message so we can store the callback as a response
        const messageId = ident.getId();

        // store the callback in the waiters list
        this._callbacks[messageId] = this._config.onConnect;

        // tell the bridge
        this._writeBridge(ident);
    }

    _onSocketError(e) {
        debug('%s', e);

        if (!this._isConnected) {
            this._connectionAttempts++;
            if (this._connectionAttempts < this._config.maxConnectionAttempts) {
                debug('attempting to reconnect... (try number: %d)', this._connectionAttempts);
                setTimeout(_ => {
                    this._connectBridge();
                }, this._connectionAttempts * enums.CONNECT_BACKOFF_MULT);
            } else {
                this._config.onConnect('error: node could not connect to bridge!');
                this.emit('error.reconnect');
            }
        } else {
            this.emit('error', e);
        }
    }

    _onData(rawData) {
        try {
            const events = rawData.toString().split(enums.EOL);

            events.forEach(event => {
                if (!event || event.charCodeAt(0) === 10) {
                    return;
                }

                debug('node <-- bridge: %s', event);
                const message = Message.fromString(event);
                // var message = JSON.parse(event);

                switch (message.method) {
                    case enums.ACK:
                        this._onACKMessage(message);
                        break;
                    case enums.TELL:
                        this._onTellMessage(message);
                        break;
                    case enums.SHOUT:
                        this._onShoutMessage(message);
                        break;
                    case enums.CLOSE:
                        this._onCloseMessage(message);
                        break;
                }
            });
        } catch (e) {
            return debug('node received invalid data, ignoring...');
        }
    }

    /**********************************************************
     * Command Handlers
     ***********************************************************/

    _onACKMessage(message) {
        debug('received ACK from Bridge for message: %s', message.data[0]);
        // Save the message ack id - we'll be plucking it from the array later.
        const [mid, data = []] = message.data;
        const handler = this._callbacks[mid] || noop;

        //Handle message:
        handler.apply(this, data);

        //remove handler for this message
        delete this._callbacks[mid];
    }

    _onTellMessage(message) {
        var self = this;
        const [from, cbid, eventName, params] = message.data;

        debug('received TELL(%s) from %s', eventName, from);

        // Define a callback function that can be called by a receiving function
        // push the callback to the end of the params array
        params.push(() => {
            const args = [].slice.call(arguments);
            const msg = new Message(enums.ACK, [from, cbid, args]);
            this._writeBridge(msg);
        });

        // push the event name to the beginning
        params.unshift(eventName);

        this.emit.apply(this, params);
    }

    _onShoutMessage(message) {
        debug('received SHOUT(%s)', message.data[0]);
        this.emit.apply(this, message.data);
    }

    _onCloseMessage(message) {
        debug('received CLOSE');
        message.data.unshift(enums.CLOSE.toLowerCase());
        this.emit.apply(this, message.data);
    }

    /**
     * Send message over the wire.
     * We sign each message with the node's ID.
     *
     * @param {Message} msg
     */
    _writeBridge(msg) {
        msg.setNodeName(this._config.id);
        try {
            this._bridge.write(msg.toString());
        } catch (e) {
            this.emit('error', e);
        }
    }

    _registerSignalHandlers() {
        debug('register signal handlers...');
        exit(_ => {
            this._bridge.close();
        });
    }
}

module.exports = Node;<commit_msg>update publish methods<commit_after>'use strict';

const enums = require('./constants');
const exit = require('./cleanup');
const uuid = require('uuid');
const debug = require('debug')('busy:node');
const Message = require('./message');
const noop = require('./noop');
const EventEmitter = require('events');
const net = require('net');
const extend = require('gextend');
const Keypath = require('gkeypath');

const utils = require('./utils');

class Node extends EventEmitter {
    constructor(config, callback) {
        super();

        //TODO: Remove this!
        if (!utils._isObject(config)) {
            config = {};
            var args = [].slice.call(arguments);
            args.map(arg => {
                if (utils._isString(arg)) {
                    return config.id = arg;
                }
                if (utils._isNumber(arg)) {
                    return config.port = arg;
                }
                if (utils._isFunction(arg)) {
                    config.onConnect = arg;
                }
            });
        }

        if (callback) {
            config.onConnect = callback;
        }

        config = extend({}, {
            id: uuid.v4(),
            onConnect: noop,
            maxConnectionAttempts: 5,
            timeout: 0
        }, config);

        if (!config.port && !config.path) {
            config.port = enums.DEFAULT_PORT;
        }

        this._config = config;

        // Set up an object to store waiting callbacks
        this._callbacks = {};
        this._isConnected = false;
        this._connectionAttempts = 0;
        this._connectBridge();
    }

    /**
     * TODO: Rename to publish
     * Node#publish()
     *
     * @param {string} whoWhat - the node name and event
     *                         in the following format:
     *                         "node_name:event_type"
     * @param {csv} args - any amount of arguments to be
     *                    sent along with the remote event
     * @param {function} callback - a callback to be run
     *                            when the remote event calls
     *                            its callback
     *
     * @return {Node}
     */
    publish( /*whoWhat, ...args, callback*/ ) {

        const self = this;
        const args = [].slice.call(arguments);
        // parse the arguments special array into a standard array

        // grab the who-what off the front
        const whoWhat = args.shift();

        let callback;

        // is there a function on the end here?
        if (utils._isFunction(utils._last(args))) {
            // cool, pop it off so we can store it in the waiters
            callback = args.pop();
        }

        //nodeName:eventName e.g. node1:ping
        const parts = whoWhat.split(':');

        if (parts.length !== 2) {
            throw new Error('Invalid publish statement, should be (node_name:event_name)');
        }

        const [nodeName, eventName] = parts;
        const destination = [nodeName, eventName, args];

        const msg = new Message(enums.TELL, destination);

        if (callback) {
            self._callbacks[msg.getId()] = callback;
        }

        self._writeBridge(msg);
        return self;
    }

    /**
     *
     */
    broadcast() {
        this._writeBridge(new Message(enums.SHOUT, [].slice.call(arguments)));
        return this;
    }

    leave(force) {
        if (force) {
            debug('node force leaving');
            return this._forceLeave();
        }

        debug('node safely leaving');

        const msg = new Message(enums.LEAVE);

        this._callbacks[msg.getId()] = function() {
            this._forceLeave();
        };

        this._writeBridge(msg);

        return this;
    }

    _forceLeave() {
        this._bridge.end();
        this.emit('leave.force');
        return this;
    }

    _connectBridge() {
        if (this._bridge) {
            this._bridge.removeAllListeners();
        }

        this._bridge = null;

        // Lets connect to the Bridge
        this._bridge = net.connect(this._config);
        // this._bridge = require('./transport').createServer(this._onConnection.bind(this));

        this._registerSignalHandlers();

        this._bridge.setTimeout(this._config.timeout);
        this._bridge.on('data', this._onData.bind(this));
        this._bridge.on('connect', this._onConnect.bind(this));
        this._bridge.on('error', this._onSocketError.bind(this));
    }

    _onConnect() {
        // Set hasConnected to true, so if the socket errors out we won't attempt
        // to reconnect.
        this._isConnected = true;

        // Identify the node to the bridge
        debug('sending IDENT');

        // Create a new Message
        const ident = new Message(enums.IDENT);

        // Get the ID of the message so we can store the callback as a response
        const messageId = ident.getId();

        // store the callback in the waiters list
        this._callbacks[messageId] = this._config.onConnect;

        // publish the bridge
        this._writeBridge(ident);
    }

    _onSocketError(e) {
        debug('%s', e);

        if (!this._isConnected) {
            this._connectionAttempts++;
            if (this._connectionAttempts < this._config.maxConnectionAttempts) {
                debug('attempting to reconnect... (try number: %d)', this._connectionAttempts);
                setTimeout(_ => {
                    this._connectBridge();
                }, this._connectionAttempts * enums.CONNECT_BACKOFF_MULT);
            } else {
                this._config.onConnect('error: node could not connect to bridge!');
                this.emit('error.reconnect');
            }
        } else {
            this.emit('error', e);
        }
    }

    _onData(rawData) {
        try {
            const events = rawData.toString().split(enums.EOL);

            events.forEach(event => {
                if (!event || event.charCodeAt(0) === 10) {
                    return;
                }

                debug('node <-- bridge: %s', event);
                const message = Message.fromString(event);
                // var message = JSON.parse(event);

                switch (message.method) {
                    case enums.ACK:
                        this._onACKMessage(message);
                        break;
                    case enums.TELL:
                        this._onTellMessage(message);
                        break;
                    case enums.SHOUT:
                        this._onShoutMessage(message);
                        break;
                    case enums.CLOSE:
                        this._onCloseMessage(message);
                        break;
                }
            });
        } catch (e) {
            return debug('node received invalid data, ignoring...');
        }
    }

    /**********************************************************
     * Command Handlers
     ***********************************************************/

    _onACKMessage(message) {
        debug('received ACK from Bridge for message: %s', message.data[0]);
        // Save the message ack id - we'll be plucking it from the array later.
        const [mid, data = []] = message.data;
        const handler = this._callbacks[mid] || noop;

        //Handle message:
        handler.apply(this, data);

        //remove handler for this message
        delete this._callbacks[mid];
    }

    _onTellMessage(message) {
        var self = this;
        const [from, cbid, eventName, params] = message.data;

        debug('received TELL(%s) from %s', eventName, from);

        // Define a callback function that can be called by a receiving function
        // push the callback to the end of the params array
        params.push(() => {
            const args = [].slice.call(arguments);
            const msg = new Message(enums.ACK, [from, cbid, args]);
            this._writeBridge(msg);
        });

        // push the event name to the beginning
        params.unshift(eventName);

        this.emit.apply(this, params);
    }

    _onShoutMessage(message) {
        debug('received SHOUT(%s)', message.data[0]);
        this.emit.apply(this, message.data);
    }

    _onCloseMessage(message) {
        debug('received CLOSE');
        message.data.unshift(enums.CLOSE.toLowerCase());
        this.emit.apply(this, message.data);
    }

    /**
     * Send message over the wire.
     * We sign each message with the node's ID.
     *
     * @param {Message} msg
     */
    _writeBridge(msg) {
        msg.setNodeName(this._config.id);
        try {
            this._bridge.write(msg.toString());
        } catch (e) {
            this.emit('error', e);
        }
    }

    _registerSignalHandlers() {
        debug('register signal handlers...');
        exit(_ => {
            this._bridge.close();
        });
    }
}

module.exports = Node;<|endoftext|>


<commit_before>kindling.module(function () {
	'use strict';

	var SOUNDS = {
		'56k': '56k',
		'Bueller?': 'bueller',
		'Clown town': 'clowntown',
		'Crickets chirping': 'crickets',
		'Danger zone': 'dangerzone',
		'Deeper': 'deeper',
		'Do it live!': 'live',
		'Drama': 'drama',
		'Great job': 'greatjob',
		'Hey girl' : 'heygirl',
		'Horn': 'horn',
		'Inconceivable' : 'inconceivable',
		'Kenny Loggins': 'loggins',
		'Noooo': 'noooo',
		'Nyan cat': 'nyan',
		'Oh my': 'ohmy',
		'Oh yeah': 'ohyeah',
		'Push it': 'pushit',
		'Rimshot': 'rimshot',
		'Sad trombone': 'trombone',
		'Saxaphone': 'sax',
		'Secret area': 'secret',
		'Sexy back': 'sexyback',
		'Ta-da!' : 'tada',
		'The horror': 'horror',
		'The More You Know': 'tmyk',
		'Vuvuzela': 'vuvuzela',
		'What up with that?': 'what',
		'Whoomp': 'whoomp',
		'Yeeeaaah!': 'yeah',
		'Yodel': 'yodel'
	};

	var MENU_ID = 'soundButton-wrapper';

	function displayMenu() {
		if (document.getElementById(MENU_ID)) {
			return;
		}
		$('#chat_controls').append('
\
				\

\

');

		var $soundButton = $('#soundButton');
		var $soundContainer = $('#soundContainer');
		var $tooltipInner = $soundContainer.find('.tooltip-inner');
		var sound;
		for (sound in SOUNDS) {
			$tooltipInner.append('' + sound + '');
		}

		$(document).click(function (e) {
			if (e.target.id !== 'soundButton' && $soundButton.find(e.target).length === 0) {
				$soundContainer.hide();
			} else {
				$soundContainer.toggle();
			}
		});

		$tooltipInner.children('.sound').click(function () {
			var input = document.getElementById('input');
			var oldValue = input.value;
			input.value = '/play ' + this.getAttribute('data-value');
			document.getElementById('send').click();
			input.value = oldValue;
		});
	}

	function onOptionsChanged(e, options) {
		if (options.soundAndEmojiMenus === 'true') {
			displayMenu();
		} else {
			$('#' + MENU_ID).remove();
		}
	}

	return {
		init: function () {
			$.subscribe('optionsChanged', onOptionsChanged);
		}
	};
}());
<commit_msg>Added bezos & trololo sounds<commit_after>kindling.module(function () {
	'use strict';

	var SOUNDS = {
		'56k': '56k',
		'Bueller?': 'bueller',
		'Clown town': 'clowntown',
		'Crickets chirping': 'crickets',
		'Danger zone': 'dangerzone',
		'Deeper': 'deeper',
		'Do it live!': 'live',
		'Drama': 'drama',
		'Great job': 'greatjob',
		'Hey girl' : 'heygirl',
		'Horn': 'horn',
		'Inconceivable' : 'inconceivable',
		'Jeff Bezos': 'bezos',
		'Kenny Loggins': 'loggins',
		'Noooo': 'noooo',
		'Nyan cat': 'nyan',
		'Oh my': 'ohmy',
		'Oh yeah': 'ohyeah',
		'Push it': 'pushit',
		'Rimshot': 'rimshot',
		'Sad trombone': 'trombone',
		'Saxaphone': 'sax',
		'Secret area': 'secret',
		'Sexy back': 'sexyback',
		'Ta-da!' : 'tada',
		'The horror': 'horror',
		'The More You Know': 'tmyk',
		'Trololo': 'trololo',
		'Vuvuzela': 'vuvuzela',
		'What up with that?': 'what',
		'Whoomp': 'whoomp',
		'Yeeeaaah!': 'yeah',
		'Yodel': 'yodel'
	};

	var MENU_ID = 'soundButton-wrapper';

	function displayMenu() {
		if (document.getElementById(MENU_ID)) {
			return;
		}
		$('#chat_controls').append('
\
				\

\

');

		var $soundButton = $('#soundButton');
		var $soundContainer = $('#soundContainer');
		var $tooltipInner = $soundContainer.find('.tooltip-inner');
		var sound;
		for (sound in SOUNDS) {
			$tooltipInner.append('' + sound + '');
		}

		$(document).click(function (e) {
			if (e.target.id !== 'soundButton' && $soundButton.find(e.target).length === 0) {
				$soundContainer.hide();
			} else {
				$soundContainer.toggle();
			}
		});

		$tooltipInner.children('.sound').click(function () {
			var input = document.getElementById('input');
			var oldValue = input.value;
			input.value = '/play ' + this.getAttribute('data-value');
			document.getElementById('send').click();
			input.value = oldValue;
		});
	}

	function onOptionsChanged(e, options) {
		if (options.soundAndEmojiMenus === 'true') {
			displayMenu();
		} else {
			$('#' + MENU_ID).remove();
		}
	}

	return {
		init: function () {
			$.subscribe('optionsChanged', onOptionsChanged);
		}
	};
}());
<|endoftext|>


<commit_before>/* global google */
import React from "react";

import {
  render,
  findDOMNode,
  unmountComponentAtNode,
} from "react-dom";

export function createInputElement(props) {
  const containerElement = document.createElement(`div`);
  // Allow developers to style the "hidden element" via `props.inputProps` and `props.input{*}`.
  const component = render((
    <input
      {...props.inputProps}
      style={props.inputStyle}
      className={props.inputClassName}
      placeholder={props.inputPlaceholder}
    />
  ), containerElement);
  // Cannot directly use the component - Google Maps will mess with React's internal state
  // by detaching/attaching.
  const inputEl = findDOMNode(component).cloneNode();
  unmountComponentAtNode(containerElement);
  return inputEl;
}

export function mountInputElementToControlPositionOnMap(inputEl, controlPosition, map) {
  return document.getElementById('loading-overlay').parentNode.insertBefore(inputEl, document.getElementById('loading-overlay').nextSibling);
}

export function unmountInputElementFromControlPositionOnMap(index, controlPosition, map) {
  return map.controls[controlPosition].removeAt(index);
}
<commit_msg>moves input box next to button<commit_after>/* global google */
import React from "react";

import {
  render,
  findDOMNode,
  unmountComponentAtNode,
} from "react-dom";

export function createInputElement(props) {
  const containerElement = document.createElement(`div`);
  // Allow developers to style the "hidden element" via `props.inputProps` and `props.input{*}`.
  const component = render((
    <input
      {...props.inputProps}
      style={props.inputStyle}
      className={props.inputClassName}
      placeholder={props.inputPlaceholder}
    />
  ), containerElement);
  // Cannot directly use the component - Google Maps will mess with React's internal state
  // by detaching/attaching.
  const inputEl = findDOMNode(component).cloneNode();
  unmountComponentAtNode(containerElement);
  return inputEl;
}

export function mountInputElementToControlPositionOnMap(inputEl, controlPosition, map) {
  return document.getElementsByClassName('mdl-layout__drawer-button')[0].parentNode.insertBefore(inputEl, document.getElementsByClassName('mdl-layout__drawer-button')[0].nextSibling);
}

export function unmountInputElementFromControlPositionOnMap(index, controlPosition, map) {
  return map.controls[controlPosition].removeAt(index);
}
<|endoftext|>


<commit_before>/**
 * @fileoverview A stream that reads in confidant's configuration files
 *     and writes out ninja build rules.
 */
let Readable = require('stream').Readable;
let Transform = require('stream').Transform;
let debug = require('debug')('confidant/ninja_stream');
let dirname = require('path').dirname;
let flatten = require('lodash/array/flatten');
let glob = require('glob').sync;
let inherits = require('util').inherits;
let readFileSync = require('fs').readFileSync;

function NinjaStream() {
  Transform.call(this, { objectMode: true });
  this.id = 0;

  this.push(`# This ninja build file was generated by confidant.
# Do not modify it directly. Instead, modify one or
# more configure.js files.
`);
}
inherits(NinjaStream, Transform);
module.exports = NinjaStream;

NinjaStream.prototype._transform = function(file, encoding, done) {
  debug(`Parsing ${file}`);
  let build = require(file);
  if (Array.isArray(build)) {
    debug('Build config sync');
    this._syncTransform(file, encoding, build, done);
  } else if (typeof build === 'function') {
    debug('Build config async');
    this._asyncTransform(file, encoding, build, done);
  } else {
    throw new Error(`Invalid build specified in ${file}`);
  }
};

NinjaStream.prototype._syncTransform = function(file, encoding, tasks, done) {
  let contents = readFileSync(file);
  let dir = dirname(file);
  debug(`Checking ${file}... found ${tasks.length} tasks`);
  tasks.forEach(task => {
    let rule = `rule-${this.id++}`;
    let js = task.rule.toString();  // Function.prototype.toString
    let cmd = `${contents}(${js})()`.replace(/(\n|\r)/g, '');
    let inputs = flatten(
      task.inputs.map(input => {
        if (input.includes('*') ||
            input.includes('?') ||
            input.includes('[') ||
            input.includes('!') ||
            input.includes('+') ||
            input.includes('@')) {
          return glob(input, { cwd: dir });
        }

        return input;
      }),
      true /* isDeep */
    )
    .filter(input => input.indexOf(' ') === -1)  // ninja can't handle ws
    .map(input => `${dir}/${input.replace('$', '$$$$')}`);
    let outputs = Array.isArray(task.outputs) ?
      task.outputs.map(output => `${dir}/${output}`).join(' ') :
      `${dir}/${task.outputs}`;

    this.push(`
rule ${rule}
  command = cd ${dir} && node -e "${cmd}"

build ${outputs}: ${rule} ${inputs.join(' ')}
`);
  });

  debug(`Wrote rules from ${file} to build.ninja`);
  done();
};

NinjaStream.prototype._asyncTransform = function(file, encoding, RuleStream, done) {
  let tasks = [];
  let stream = new RuleStream();
  stream.on('data', rule => tasks.push(rule));
  stream.on('end', () => this._syncTransform(file, encoding, tasks, done));
};
<commit_msg>Escape all dollar signs from output build.ninja<commit_after>/**
 * @fileoverview A stream that reads in confidant's configuration files
 *     and writes out ninja build rules.
 */
let Readable = require('stream').Readable;
let Transform = require('stream').Transform;
let debug = require('debug')('confidant/ninja_stream');
let dirname = require('path').dirname;
let flatten = require('lodash/array/flatten');
let glob = require('glob').sync;
let inherits = require('util').inherits;
let readFileSync = require('fs').readFileSync;

function NinjaStream() {
  Transform.call(this, { objectMode: true });
  this.id = 0;

  this.push(`# This ninja build file was generated by confidant.
# Do not modify it directly. Instead, modify one or
# more configure.js files.
`);
}
inherits(NinjaStream, Transform);
module.exports = NinjaStream;

NinjaStream.prototype._transform = function(file, encoding, done) {
  debug(`Parsing ${file}`);
  let build = require(file);
  if (Array.isArray(build)) {
    debug('Build config sync');
    this._syncTransform(file, encoding, build, done);
  } else if (typeof build === 'function') {
    debug('Build config async');
    this._asyncTransform(file, encoding, build, done);
  } else {
    throw new Error(`Invalid build specified in ${file}`);
  }
};

NinjaStream.prototype._syncTransform = function(file, encoding, tasks, done) {
  let contents = readFileSync(file);
  let dir = dirname(file);
  debug(`Checking ${file}... found ${tasks.length} tasks`);
  tasks.forEach(task => {
    let rule = `rule-${this.id++}`;
    let js = task.rule.toString();  // Function.prototype.toString
    let cmd = ninjaEscape(`${contents}(${js})()`.replace(/(\n|\r)/g, ''));
    let inputs = flatten(
      task.inputs.map(input => {
        if (input.includes('*') ||
            input.includes('?') ||
            input.includes('[') ||
            input.includes('!') ||
            input.includes('+') ||
            input.includes('@')) {
          return glob(input, { cwd: dir });
        }

        return input;
      }),
      true /* isDeep */
    )
    .filter(input => input.indexOf(' ') === -1)  // ninja can't handle ws
    .map(input => `${dir}/${ninjaEscape(input)}`);
    let outputs = Array.isArray(task.outputs) ?
      task.outputs.map(output => `${dir}/${ninjaEscape(output)}`).join(' ') :
      `${dir}/${ninjaEscape(task.outputs)}`;

    this.push(`
rule ${rule}
  command = cd ${dir} && node -e "${cmd}"

build ${outputs}: ${rule} ${inputs.join(' ')}
`);
  });

  debug(`Wrote rules from ${file} to build.ninja`);
  done();
};

NinjaStream.prototype._asyncTransform = function(file, encoding, RuleStream, done) {
  let tasks = [];
  let stream = new RuleStream();
  stream.on('data', rule => tasks.push(rule));
  stream.on('end', () => this._syncTransform(file, encoding, tasks, done));
};

function ninjaEscape(str) {
  return str.replace('$', '$$$$');
}
<|endoftext|>


<commit_before>//Goal: Add interactivity to Todo app

/*************************
Cache DOM Elements
**************************/

var taskInput = document.getElementById("new-task");
var addButton = document.getElementById("add-button");
var incompleteTasksHolder = document.querySelector("#incomplete-tasks ul");
var completedTasksHolder = document.querySelector("#completed-tasks ul");

/*************************
Functions
**************************/

var createNewTaskElement = function (taskString) {
  //Create necessary elements
  var listItem = document.createElement("li");
  var checkBox = document.createElement("input"); //checkbox
  var div = document.createElement("div");
  var deleteButton = document.createElement("button");

  //Modify elements
  checkBox.type = "checkbox";
  div.setAttribute("contenteditable", "true");
  deleteButton.textContent = "Delete";
  deleteButton.className = "delete";

  div.textContent = taskString;

  //Append elements to listItem
  listItem.appendChild(checkBox);
  listItem.appendChild(div);
  listItem.appendChild(deleteButton);

  return listItem;
};

var addTask = function () {
  //Add a new task

  if (taskInput.value) {
    //Create a new list item with the text from #new-task:
    var listItem = createNewTaskElement(taskInput.value);

    //Append listItem to incompleteTasksHolder
    incompleteTasksHolder.appendChild(listItem);

    //Clear taskInput text
    taskInput.value = "";
  }
};

var deleteTask = function (el) {
  //Delete an existing task

  var listItem = el.parentNode;
  var ul = listItem.parentNode;

  //Remove the parent list item from the ul
  ul.removeChild(listItem);
};

var taskCompleted = function (el) {
  //Mark a task as completed

  //Append the task li to the #completed-tasks
  var listItem = el.parentNode;
  completedTasksHolder.appendChild(listItem);
};

var taskIncomplete = function (el) {
  //Mark a task as incompleted

  //Append the task li to the #incomplete-tasks
  var listItem = el.parentNode;
  incompleteTasksHolder.appendChild(listItem);
};

var taskEventHandler = function (e, checkBoxEventHandler) {
  //Examine event and send to appropriate handler
  var el = e.target;
  var checkbox = el.matches("input[type=checkbox]");
  var deleteButton = el.matches("button.delete");

  if (checkbox) {
    checkBoxEventHandler(el);
  } else if (deleteButton) {
    deleteTask(el);
  }
};

var addTaskEnterKeyEvent = function (e) {
  //Capture enter key as addButton click
  if (e.keyCode == 13) {
    addButton.click();
  }
};

/*************************
Event Listeners
**************************/

//Set click handler on add button
addButton.addEventListener("click", addTask);

//Set keypress handler on new-task input
taskInput.addEventListener("keypress", addTaskEnterKeyEvent);

//Set click handler on incompleteTasksHolder
incompleteTasksHolder.addEventListener("click", function(e) {
  taskEventHandler(e, taskCompleted);
});

//Set click handler on completedTasksHolder
completedTasksHolder.addEventListener("click", function(e) {
  taskEventHandler(e, taskIncomplete);
});
<commit_msg>Add enter keypress blurs editable div element feature:<commit_after>//Goal: Add interactivity to Todo app

/*************************
Cache DOM Elements
**************************/

var taskInput = document.getElementById("new-task");
var addButton = document.getElementById("add-button");
var incompleteTasksHolder = document.querySelector("#incomplete-tasks ul");
var completedTasksHolder = document.querySelector("#completed-tasks ul");

/*************************
Functions
**************************/

var createNewTaskElement = function (taskString) {
  //Create necessary elements
  var listItem = document.createElement("li");
  var checkBox = document.createElement("input"); //checkbox
  var div = document.createElement("div");
  var deleteButton = document.createElement("button");

  //Modify elements
  checkBox.type = "checkbox";
  div.setAttribute("contenteditable", "true");
  deleteButton.textContent = "Delete";
  deleteButton.className = "delete";

  div.textContent = taskString;

  //Append elements to listItem
  listItem.appendChild(checkBox);
  listItem.appendChild(div);
  listItem.appendChild(deleteButton);

  return listItem;
};

var addTask = function () {
  //Add a new task

  if (taskInput.value) {
    //Create a new list item with the text from #new-task:
    var listItem = createNewTaskElement(taskInput.value);

    //Append listItem to incompleteTasksHolder
    incompleteTasksHolder.appendChild(listItem);

    //Clear taskInput text
    taskInput.value = "";
  }
};

var deleteTask = function (el) {
  //Delete an existing task

  var listItem = el.parentNode;
  var ul = listItem.parentNode;

  //Remove the parent list item from the ul
  ul.removeChild(listItem);
};

var taskCompleted = function (el) {
  //Mark a task as completed

  //Append the task li to the #completed-tasks
  var listItem = el.parentNode;
  completedTasksHolder.appendChild(listItem);
};

var taskIncomplete = function (el) {
  //Mark a task as incompleted

  //Append the task li to the #incomplete-tasks
  var listItem = el.parentNode;
  incompleteTasksHolder.appendChild(listItem);
};

var taskEventHandler = function (e, checkBoxEventHandler) {
  //Examine event and send to appropriate handler
  var el = e.target;
  var checkbox = el.matches("input[type=checkbox]");
  var deleteButton = el.matches("button.delete");

  if (checkbox) {
    checkBoxEventHandler(el);
  } else if (deleteButton) {
    deleteTask(el);
  }
};

var addTaskEnterKeyEvent = function (e) {
  //Capture enter key as addButton click
  if (e.keyCode == 13) {
    addButton.click();
  }
};

var loseFocus = function (e) {
  // body...
  if (e.keyCode == 13) {
    var el = e.target;

    if (el.matches("div")) {
      el.blur();
    }
  }
};

/*************************
Event Listeners
**************************/

//Set click handler on add button
addButton.addEventListener("click", addTask);

//Set keypress handler on new-task input
taskInput.addEventListener("keypress", addTaskEnterKeyEvent);

//Set click handler on incompleteTasksHolder
incompleteTasksHolder.addEventListener("click", function(e) {
  taskEventHandler(e, taskCompleted);
});

//Set click handler on completedTasksHolder
completedTasksHolder.addEventListener("click", function(e) {
  taskEventHandler(e, taskIncomplete);
});

//Set keypress handler on incompleteTasksHolder
incompleteTasksHolder.addEventListener("keypress", loseFocus);
<|endoftext|>


<commit_before>var _ = require('underscore');
var cp = require('child_process');
var fs = require('fs');
var path = require('path');
var spawn = require('child_process').spawn;
var util = require('util');
if (!fs.existsSync) {
    fs.existsSync = path.existsSync;
}

function findCmd(name) {
    "use strict";

    var paths = process.env['PATH'].split(':');
    var pathLen = paths.length;
    for (var i = 0; i < pathLen; i++) {
        var sp = path.resolve(paths[i]);
        var fname = path.normalize(path.join(sp, name));
        if (fs.existsSync(fname)) {
            return fname;
        }
    }

    return null;
}

var zfsBin = findCmd('zfs');
function zfs(args, callback) {
    "use strict";

    cp.execFile(zfsBin, args, {maxBuffer: 8000000}, function (err, stdout, stderr) {
        if (callback && typeof callback === 'function') {
            if (err) {
                err.message = _.compact(err.message.split('\n')).join('; ').trim();
                callback(err);
            } else {
                callback(null, stdout);
            }
        }
    });
}

function parseNumber(str) {
    var m = str.match(/^([0-9.]+)([KMGT]?)$/);
    if (!m) {
        return -1;
    }

    var n = parseFloat(m[1]);
    if (m[2] === 'K') {
        n *= 1024;
    } else if (m[2] === 'M') {
        n *= 1024 * 1024;
    } else if (m[2] === 'G') {
        n *= 1024 * 1024 * 1024;
    } else if (m[2] === 'T') {
        n *= 1024 * 1024 * 1024 * 1024;
    } else if (m[2] === 'P') {
        n *= 1024 * 1024 * 1024 * 1024 * 1024;
    }

    return Math.floor(n);
}

function ZFS(info) {
    "use strict";

    var obj = Object.create({});
    if (typeof info === 'string') {
        info = info.split(/\s+/);
    }

    if (info.length !== 5) {
        return null;
    }

    obj.name = info[0];
    obj.used = parseNumber(info[1]);
    if (info[2] !== '-') { // Snapshots don't have 'avail' field.
        obj.avail = parseNumber(info[2]);
    }
    obj.refer = parseNumber(info[3]);
    obj.mountpoint = info[4];

    Object.freeze(obj);
    return obj;
}

function Property(info) {
    "use strict";

    var obj = Object.create({});
    if (typeof info === 'string') {
        info = info.split(/\s+/, 4);
    }

    if (info.length !== 4) {
        return null;
    }

    obj.name = info[0];
    obj.property = info[1];
    obj.value = info[2];
    obj.source = info[3];

    Object.freeze(obj);
    return obj;
}

function list(opts, cb) {
    "use strict";

    if (typeof opts === 'function') {
        cb = opts;
        opts = undefined;
    }

    var params = ['list', '-H'];

    if (opts && opts.type) {
        params.push('-t');
        params.push(opts.type);
    }

    zfs(params, function (err, stdout) {
        if (cb && typeof cb === 'function') {
            var lines = _.compact(stdout.split('\n'));
            var list = lines.map(function (x) { return new ZFS(x); });
            cb(err, list);
        }
    });
}

function get(opts, cb) {
    "use strict";

    var params = [ 'get', '-pH' ];
    if (opts.source) {
        params.push('-s');
        params.push(opts.source);
    }
    params.push(opts.property);

    zfs(params, function (err, stdout) {
        if (cb && typeof cb === 'function') {
            var lines = _.compact(stdout.split('\n'));
            var list = lines.map(function (x) { return new Property(x); });
            cb(err, list);
        }
    });
}

function destroy(opts, cb) {
    "use strict";

    var params = [ 'destroy' ];
    if (opts.recursive) {
        params.push('-r');
    }
    params.push(opts.name);

    zfs(params, cb);
}

function snapshot(opts, cb) {
    "use strict";

    var params = [ 'snapshot' ];
    if (opts.recursive) {
        params.push('-r');
    }
    params.push(opts.dataset + '@' + opts.name);

    zfs(params, cb);
}

exports.get = get;
exports.list = list;
exports.destroy = destroy;
exports.snapshot = snapshot;
<commit_msg>adding zfs set command<commit_after>var _ = require('underscore');
var cp = require('child_process');
var fs = require('fs');
var path = require('path');
var spawn = require('child_process').spawn;
var util = require('util');
if (!fs.existsSync) {
    fs.existsSync = path.existsSync;
}

function findCmd(name) {
    "use strict";

    var paths = process.env['PATH'].split(':');
    var pathLen = paths.length;
    for (var i = 0; i < pathLen; i++) {
        var sp = path.resolve(paths[i]);
        var fname = path.normalize(path.join(sp, name));
        if (fs.existsSync(fname)) {
            return fname;
        }
    }

    return null;
}

var zfsBin = findCmd('zfs');
function zfs(args, callback) {
    "use strict";

    cp.execFile(zfsBin, args, {maxBuffer: 8000000}, function (err, stdout, stderr) {
        if (callback && typeof callback === 'function') {
            if (err) {
                err.message = _.compact(err.message.split('\n')).join('; ').trim();
                callback(err);
            } else {
                callback(null, stdout);
            }
        }
    });
}

function parseNumber(str) {
    var m = str.match(/^([0-9.]+)([KMGT]?)$/);
    if (!m) {
        return -1;
    }

    var n = parseFloat(m[1]);
    if (m[2] === 'K') {
        n *= 1024;
    } else if (m[2] === 'M') {
        n *= 1024 * 1024;
    } else if (m[2] === 'G') {
        n *= 1024 * 1024 * 1024;
    } else if (m[2] === 'T') {
        n *= 1024 * 1024 * 1024 * 1024;
    } else if (m[2] === 'P') {
        n *= 1024 * 1024 * 1024 * 1024 * 1024;
    }

    return Math.floor(n);
}

function ZFS(info) {
    "use strict";

    var obj = Object.create({});
    if (typeof info === 'string') {
        info = info.split(/\s+/);
    }

    if (info.length !== 5) {
        return null;
    }

    obj.name = info[0];
    obj.used = parseNumber(info[1]);
    if (info[2] !== '-') { // Snapshots don't have 'avail' field.
        obj.avail = parseNumber(info[2]);
    }
    obj.refer = parseNumber(info[3]);
    obj.mountpoint = info[4];

    Object.freeze(obj);
    return obj;
}

function Property(info) {
    "use strict";

    var obj = Object.create({});
    if (typeof info === 'string') {
        info = info.split(/\s+/, 4);
    }

    if (info.length !== 4) {
        return null;
    }

    obj.name = info[0];
    obj.property = info[1];
    obj.value = info[2];
    obj.source = info[3];

    Object.freeze(obj);
    return obj;
}

function list(opts, cb) {
    "use strict";

    if (typeof opts === 'function') {
        cb = opts;
        opts = undefined;
    }

    var params = ['list', '-H'];

    if (opts && opts.type) {
        params.push('-t');
        params.push(opts.type);
    }

    zfs(params, function (err, stdout) {
        if (cb && typeof cb === 'function') {
            var lines = _.compact(stdout.split('\n'));
            var list = lines.map(function (x) { return new ZFS(x); });
            cb(err, list);
        }
    });
}

function get(opts, cb) {
    "use strict";

    var params = [ 'get', '-pH' ];
    if (opts.source) {
        params.push('-s');
        params.push(opts.source);
    }
    params.push(opts.property);

    zfs(params, function (err, stdout) {
        if (cb && typeof cb === 'function') {
            var lines = _.compact(stdout.split('\n'));
            var list = lines.map(function (x) { return new Property(x); });
            cb(err, list);
        }
    });
}

function destroy(opts, cb) {
    "use strict";

    var params = [ 'destroy' ];
    if (opts.recursive) {
        params.push('-r');
    }
    params.push(opts.name);

    zfs(params, cb);
}

function set(opts, cb) {
    "use strict";

    var params = [ 'set' ];

    params.push(opts.property + "=" + opts.value)

    params.push(opts.name);

    zfs(params, cb);
}

function snapshot(opts, cb) {
    "use strict";

    var params = [ 'snapshot' ];
    if (opts.recursive) {
        params.push('-r');
    }
    params.push(opts.dataset + '@' + opts.name);

    zfs(params, cb);
}

exports.get = get;
exports.set = set;
exports.list = list;
exports.destroy = destroy;
exports.snapshot = snapshot;
<|endoftext|>


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

var offsetBusiness=0; //start at the begining
var maxrecordsBusiness=20;  //record 20 at a time
var totalrecordsBusiness=0;

RenderBusinessListBySearch('%', offsetBusiness, maxrecordsBusiness);

function pagedownBusiness()
{
    offset = $("#offsetBusiness").text();
    //alert(offset);
    var newoffset = offsetBusiness - maxrecordsBusiness;
    if (newoffset < 0)
        return;
    //alert(newoffset);
    if (newoffset != offsetBusiness)
        RenderBusinessListBySearch('%', newoffset, maxrecordsBusiness);
}
function refreshBusinessList()
{
    RenderBusinessListBySearch('%', offsetBusiness, maxrecordsBusiness);
}
function pageupBusiness()
{
    offsetBusiness = $("#offsetBusiness").text();
    //alert(offset);
    var fetch = maxrecordsBusiness;
    if ((parseInt(offsetBusiness) + parseInt(maxrecordsBusiness))  > totalrecordsBusiness)
        //fetch = maxrecords - offset;
        return;
    else
        fetch = (parseInt(offsetBusiness) + parseInt(maxrecordsBusiness));
    //alert(fetch);
    offsetBusiness = fetch;
    RenderBusinessListBySearch('%', fetch, maxrecordsBusiness);
}

//offset, maxrecords, keyword
function RenderBusinessListBySearch(keyword1, offset1, maxrecords1)
{
   var    keyword =$("#name_business").val();
    var lang = $("#lang_business").text();
    if (lang==undefined)
       lang = "";
    if (keyword==undefined)
       keyword = "";
    lang = encodeURIComponent(lang);
    keyword = encodeURIComponent(keyword);
    offset1 = encodeURIComponent(offset1);
    maxrecords1 = encodeURIComponent(maxrecords1);

    $("#businesslist").html("");
    var request=   $.ajax({
        url: 'ajax/businesssearch.jsp?keyword=' + keyword + "&offset=" + offset1 + "&maxrecords=" + maxrecords1 + "&lang=" + lang,
        type:"GET",
        cache: false
    });

    request.done(function(msg) {
        window.console && console.log('postback done ');
        $("#businesslist").html(msg);
    //refresh();
    });

    request.fail(function(jqXHR, textStatus) {
        window.console && console.log('postback failed ');
        $("#businesslist").html("An error occured! " + jqXHR.responseText + textStatus);
    //refresh();
    });
/*
    $.get('ajax/businesssearch.jsp?keyword=' + keyword1 + "&offset=" + offset1 + "&maxrecords=" + maxrecords1 + "&lang=" + lang, function(data) {
        $("#businesslist").html(data);
        refresh();
    });*/
}

function refresh()
{
    var displayrecords = $("#displayrecordsBusiness").text();
    if (displayrecords == totalrecordsBusiness)
    {
        $("#pageupBusiness").addClass("disabled");
        $("#pagedownBusiness").addClass("disabled");
    }
    else if (offsetBusiness + maxrecordsBusiness > totalrecordsBusiness)
    {
        $("#pageupBusiness").addClass("disabled");
    }
    else if (offsetBusiness ==0)
    {
        $("#pagedownBusiness").removeClass("disabled");
    }
    else
    {
        $("#pagedownBusiness").removeClass("disabled");
        $("#pageupBusiness").removeClass("disabled");
    }
}<commit_msg>JUDDI-883 fixed<commit_after>/*
 * Copyright 2001-2013 The Apache Software Foundation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

var offsetBusiness=0; //start at the begining
var maxrecordsBusiness=20;  //record 20 at a time
var totalrecordsBusiness=0;

RenderBusinessListBySearch('%', offsetBusiness, maxrecordsBusiness);

function pagedownBusiness()
{
    offset = $("#offsetBusiness").text();
    //alert(offset);
    var newoffset = offsetBusiness - maxrecordsBusiness;
    if (newoffset < 0)
        return;
    //alert(newoffset);
    if (newoffset != offsetBusiness)
    {
        offsetBusiness = newoffset;
        RenderBusinessListBySearch('%', newoffset, maxrecordsBusiness);
    }
}
function refreshBusinessList()
{
    RenderBusinessListBySearch('%', offsetBusiness, maxrecordsBusiness);
}
function pageupBusiness()
{
    offsetBusiness = $("#offsetBusiness").text();
    //alert(offset);
    var fetch = maxrecordsBusiness;
    if ((parseInt(offsetBusiness) + parseInt(maxrecordsBusiness))  > totalrecordsBusiness)
        //fetch = maxrecords - offset;
        return;
    else
        fetch = (parseInt(offsetBusiness) + parseInt(maxrecordsBusiness));
    //alert(fetch);
    offsetBusiness = fetch;
    RenderBusinessListBySearch('%', fetch, maxrecordsBusiness);
}

//offset, maxrecords, keyword
function RenderBusinessListBySearch(keyword1, offset1, maxrecords1)
{
   var    keyword =$("#name_business").val();
    var lang = $("#lang_business").text();
    if (lang==undefined)
       lang = "";
    if (keyword==undefined)
       keyword = "";
    lang = encodeURIComponent(lang);
    keyword = encodeURIComponent(keyword);
    offset1 = encodeURIComponent(offset1);
    maxrecords1 = encodeURIComponent(maxrecords1);

    $("#businesslist").html("");
    var request=   $.ajax({
        url: 'ajax/businesssearch.jsp?keyword=' + keyword + "&offset=" + offset1 + "&maxrecords=" + maxrecords1 + "&lang=" + lang,
        type:"GET",
        cache: false
    });

    request.done(function(msg) {
        window.console && console.log('postback done ');
        $("#businesslist").html(msg);
    //refresh();
    });

    request.fail(function(jqXHR, textStatus) {
        window.console && console.log('postback failed ');
        $("#businesslist").html("An error occured! " + jqXHR.responseText + textStatus);
    //refresh();
    });
/*
    $.get('ajax/businesssearch.jsp?keyword=' + keyword1 + "&offset=" + offset1 + "&maxrecords=" + maxrecords1 + "&lang=" + lang, function(data) {
        $("#businesslist").html(data);
        refresh();
    });*/
}

function refresh()
{
    var displayrecords = $("#displayrecordsBusiness").text();
    if (displayrecords == totalrecordsBusiness)
    {
        $("#pageupBusiness").addClass("disabled");
        $("#pagedownBusiness").addClass("disabled");
    }
    else if (offsetBusiness + maxrecordsBusiness > totalrecordsBusiness)
    {
        $("#pageupBusiness").addClass("disabled");
    }
    else if (offsetBusiness ==0)
    {
        $("#pagedownBusiness").removeClass("disabled");
    }
    else
    {
        $("#pagedownBusiness").removeClass("disabled");
        $("#pageupBusiness").removeClass("disabled");
    }
}<|endoftext|>


<commit_before>/* jshint esversion: 6, curly: true, eqeqeq: true, forin: true */

/***********************************************************************************
* Title: Hamsters.js                                                               *
* Description: 100% Vanilla Javascript Multithreading & Parallel Execution Library *
* Author: Austin K. Smith                                                          *
* Contact: austin@asmithdev.com                                                    *
* Copyright: 2015 Austin K. Smith - austin@asmithdev.com                           *
* License: Artistic License 2.0                                                    *
***********************************************************************************/

import hamsters from '../src/hamsters';

    // this.persistence = true;
    // this.memoize = false;
    // this.atomics = false;
    // this.debug = false;
    // this.version = hamstersVersion;
    // this.maxThreads = hamstersHabitat.logicalThreads;
    // this.habitat = hamstersHabitat;
    // this.data = hamstersData;
    // this.pool = hamstersPool;
    // this.logger = hamstersLogger;
    // this.memoizer = hamstersMemoizer;
    // this.run = this.hamstersRun;
    // this.promise = this.hamstersPromise;
    // this.init = this.initializeLibrary;

describe("Hamsters.js", () => {

  it("Persistence should be boolean", () => {
    expect(hamsters.persistence).toMatch(/true|false/);
  });

  it("Memoize should be boolean", () => {
    expect(hamsters.memoize).toMatch(/true|false/);
  });

  it("Atomics should be boolean", () => {
    expect(hamsters.atomics).toMatch(/true|false/);
  });

  it("Debug should be boolean", () => {
    expect(hamsters.debug).toMatch(/true|false/);
  });

  it("maxThreads should be detected", () => {
    expect(hamsters.maxThreads).toEqual((navigator.hardwareConcurrency || 4));
  });

  it("Init should initialize library", () => {
    hamsters.init({
      maxThreads: 2
    });
    expect(typeof hamsters.init).toBe('undefined');
    expect(hamsters.maxThreads).toEqual(2);
  });
});<commit_msg>More coverage<commit_after>/* jshint esversion: 6, curly: true, eqeqeq: true, forin: true */

/***********************************************************************************
* Title: Hamsters.js                                                               *
* Description: 100% Vanilla Javascript Multithreading & Parallel Execution Library *
* Author: Austin K. Smith                                                          *
* Contact: austin@asmithdev.com                                                    *
* Copyright: 2015 Austin K. Smith - austin@asmithdev.com                           *
* License: Artistic License 2.0                                                    *
***********************************************************************************/

import hamsters from '../src/hamsters';

describe("Hamsters.js", () => {

  it("Persistence should be boolean", () => {
    expect(hamsters.persistence).toMatch(/true|false/);
  });

  it("Memoize should be boolean", () => {
    expect(hamsters.memoize).toMatch(/true|false/);
  });

  it("Atomics should be boolean", () => {
    expect(hamsters.atomics).toMatch(/true|false/);
  });

  it("Debug should be boolean", () => {
    expect(hamsters.debug).toMatch(/true|false/);
  });

  it("maxThreads should be detected", () => {
    expect(hamsters.maxThreads).toEqual((navigator.hardwareConcurrency || 4));
  });

  it("Init should initialize library", () => {
    hamsters.init({
      maxThreads: 2
    });
    expect(typeof hamsters.init).toBe('undefined');
    expect(hamsters.maxThreads).toEqual(2);
  });
});<|endoftext|>