<commit_before>var through = require('through2')
var bionodeSAM = require('./')

var args = process.argv.slice(2)

var command = args[0] //args.length > 2 ? args.slice(0, args.length-2) : null
var srdDest

console.log(command)
// if (args.length === 0) { throw Error('Please specify command and files') }
// else if (args.length === 1) { throw Error('Please provide a SRA file') }
// else if (args.length === 2) { srcDest = args[1] + ' .' }
// else if (args.length === 3) { srcDest = args.slice(args.length-2)  }
// else if (args.length > 3) { throw Error('Too many arguments specified') }

var sam = bionodeSAM(command)

var samStream = sam(args)

samStream.on('data', function(data) {
  process.stdout.write(data[0]+' -> '+data[1]+'\n')
})

samStream.on('error', function(error) {
  console.error(error)
})
<commit_msg>Add shebang to cli.js<commit_after>#!/usr/bin/env node
var through = require('through2')
var bionodeSAM = require('./')

var args = process.argv.slice(2)

var command = args[0] //args.length > 2 ? args.slice(0, args.length-2) : null
var srdDest

console.log(command)
// if (args.length === 0) { throw Error('Please specify command and files') }
// else if (args.length === 1) { throw Error('Please provide a SRA file') }
// else if (args.length === 2) { srcDest = args[1] + ' .' }
// else if (args.length === 3) { srcDest = args.slice(args.length-2)  }
// else if (args.length > 3) { throw Error('Too many arguments specified') }

var sam = bionodeSAM(command)

var samStream = sam(args)

samStream.on('data', function(data) {
  process.stdout.write(data[0]+' -> '+data[1]+'\n')
})

samStream.on('error', function(error) {
  console.error(error)
})
<|endoftext|>


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

var path = require('path');
var fs = require('fs');

var program = require('commander');
var npmconf = require('npmconf');
var ini = require('ini');
var echo = require('node-echo');
var extend = require('extend');
var open = require('open');
var async = require('async');
var request = require('request');
var only = require('only');

var registries = require('./registries.json');
var PKG = require('./package.json');
var NRMRC = path.join(process.env.HOME, '.nrmrc');

program
    .version(PKG.version);

program
    .command('ls')
    .description('list all the registries')
    .action(onList);

program
    .command('use <registry>')
    .description('change registry to registry')
    .action(onUse);

program
    .command('add <registry> <url> [home]')
    .description('add one custom registry')
    .action(onAdd);

program
    .command('del <registry>')
    .description('delete one custom registry')
    .action(onDel);

program
    .command('rm <registry>')
    .description('delete one custom registry')
    .action(onDel);

program
    .command('home <registry> [browser]')
    .description('open the homepage of registry with optional browser')
    .action(onHome);

program
    .command('test [registry]')
    .description('show response time for specific or all registries')
    .action(onTest);

program
    .command('help')
    .description('print this help')
    .action(program.help);

program
    .parse(process.argv);

/*//////////////// cmd methods /////////////////*/

function onList() {
    getCurrentRegistry(function (cur) {
        var info = [''];
        var allRegistries = getAllRegistry();

        Object.keys(allRegistries).forEach(function(key){
            var item = allRegistries[key];
            var prefix = item.registry === cur ? '* ' : '  ';
            info.push(prefix + key + line(key, 8) + item.registry);
        });

        info.push('');
        printMsg(info);
    });
}

function onUse(name){
    var allRegistries = getAllRegistry();

    if(allRegistries.hasOwnProperty(name)){
        var registry = allRegistries[name];
        npmconf.load(function(err, conf){
            if(err){
                exit(err);
            }

            conf.set('registry', registry.registry, 'user');
            conf.save('user', function(err){
                if(err){
                    exit(err);
                }
                printMsg([
                    ''
                    , '   Registry has been set to: ' + registry.registry
                    , ''
                ]);
            });
        });
    }else{
        printMsg([
            ''
            , '   Not find registry: ' + name
            , ''
        ]);
    }
}

function onDel(name){
    var customRegistries = getCustomRegistry();
    if(!customRegistries.hasOwnProperty(name)){
        return;
    }

    getCurrentRegistry(function (cur) {
        if (cur === customRegistries[name].registry) {
            onUse('npm');
        }

        delete customRegistries[name];
        setCustomRegistry(customRegistries, function(err){
            if(err){
                exit(err);
            }
            printMsg([
                ''
                , '    delete registry ' + name + ' success'
                , ''
            ]);
        });
    });
}

function onAdd(name, url, home){
    var customRegistries = getCustomRegistry();
    if(customRegistries.hasOwnProperty(name)){
        return;
    }

    var config = customRegistries[name] = {};
    if (url[url.length-1] !== '/') url += '/';  // ensure url end with /
    config.registry = url;
    if(home){
        config.home = home;
    }

    setCustomRegistry(customRegistries, function(err){
        if(err){
            exit(err);
        }
        printMsg([
            ''
            , '    add registry ' + name + ' success'
            , ''
        ]);
    });
}

function onHome(name, browser){
    var allRegistries = getAllRegistry();
    var home = allRegistries[name] && allRegistries[name].home;
    if (home) {
        var args = [home];
        if (browser) args.push(browser);
        open.apply(null, args);
    }
}

function onTest(registry){
    var allRegistries = getAllRegistry();

    var toTest;

    if(registry){
        if(!allRegistries.hasOwnProperty(registry)){
            return;
        }
        toTest = only(allRegistries, registry);
    }else{
        toTest = allRegistries;
    }

    async.map(Object.keys(toTest), function(name, cbk){
        var registry = toTest[name];
        var start = +new Date();
        request(registry.registry + 'pedding', function(error){
            cbk(null, {
                name: name
                , registry: registry.registry
                , time: (+new Date() - start)
                , error: error ? true : false
            });
        });
    }, function(err, results){
        getCurrentRegistry(function(cur){
            var msg = [''];
            results.forEach(function(result){
                var prefix = result.registry === cur ? '* ' : '  ';
                var suffix = result.error ? 'Fetch Error' : result.time + 'ms';
                msg.push(prefix + result.name + line(result.name, 8) + suffix);
            });
            msg.push('');
            printMsg(msg);
        });
    });
}

/*//////////////// helper methods /////////////////*/

/*
* get current registry
*/
function getCurrentRegistry (cbk) {
    npmconf.load(function(err, conf){
        if(err){
            exit(err);
        }

        cbk(conf.get('registry'));
    });
}

function getCustomRegistry(){
    return fs.existsSync(NRMRC) ? ini.parse(fs.readFileSync(NRMRC, 'utf-8')) : {};
}

function setCustomRegistry(config, cbk){
    echo(ini.stringify(config), '>', NRMRC, cbk);
}

function getAllRegistry(){
    return extend({}, registries, getCustomRegistry());
}

function printErr(err){
    console.error('an error occured: ' + err);
}

function printMsg(infos){
    infos.forEach(function(info){
        console.log(info);
    });
}

/*
* print message & exit
*/
function exit (err) {
    printErr(err);
    process.exit(1);
}

function line (str, len) {
    var line = new Array(len - str.length).join('-');
    return ' ' + line + ' ';
}
<commit_msg>nrm默认命令没有任何输出，现打印出用途和用法提示<commit_after>#!/usr/bin/env node

var path = require('path');
var fs = require('fs');

var program = require('commander');
var npmconf = require('npmconf');
var ini = require('ini');
var echo = require('node-echo');
var extend = require('extend');
var open = require('open');
var async = require('async');
var request = require('request');
var only = require('only');

var registries = require('./registries.json');
var PKG = require('./package.json');
var NRMRC = path.join(process.env.HOME, '.nrmrc');

program
    .version(PKG.version);

program
    .command('ls')
    .description('list all the registries')
    .action(onList);

program
    .command('use <registry>')
    .description('change registry to registry')
    .action(onUse);

program
    .command('add <registry> <url> [home]')
    .description('add one custom registry')
    .action(onAdd);

program
    .command('del <registry>')
    .description('delete one custom registry')
    .action(onDel);

program
    .command('rm <registry>')
    .description('delete one custom registry')
    .action(onDel);

program
    .command('home <registry> [browser]')
    .description('open the homepage of registry with optional browser')
    .action(onHome);

program
    .command('test [registry]')
    .description('show response time for specific or all registries')
    .action(onTest);

program
    .command('help')
    .description('print this help')
    .action(program.help);

program
    .parse(process.argv);

if(process.argv.length === 2){
  console.log('nrm can help you easy and fast switch between different npm registries');
  console.log('usages: nrm help');
}

/*//////////////// cmd methods /////////////////*/

function onList() {
    getCurrentRegistry(function (cur) {
        var info = [''];
        var allRegistries = getAllRegistry();

        Object.keys(allRegistries).forEach(function(key){
            var item = allRegistries[key];
            var prefix = item.registry === cur ? '* ' : '  ';
            info.push(prefix + key + line(key, 8) + item.registry);
        });

        info.push('');
        printMsg(info);
    });
}

function onUse(name){
    var allRegistries = getAllRegistry();

    if(allRegistries.hasOwnProperty(name)){
        var registry = allRegistries[name];
        npmconf.load(function(err, conf){
            if(err){
                exit(err);
            }

            conf.set('registry', registry.registry, 'user');
            conf.save('user', function(err){
                if(err){
                    exit(err);
                }
                printMsg([
                    ''
                    , '   Registry has been set to: ' + registry.registry
                    , ''
                ]);
            });
        });
    }else{
        printMsg([
            ''
            , '   Not find registry: ' + name
            , ''
        ]);
    }
}

function onDel(name){
    var customRegistries = getCustomRegistry();
    if(!customRegistries.hasOwnProperty(name)){
        return;
    }

    getCurrentRegistry(function (cur) {
        if (cur === customRegistries[name].registry) {
            onUse('npm');
        }

        delete customRegistries[name];
        setCustomRegistry(customRegistries, function(err){
            if(err){
                exit(err);
            }
            printMsg([
                ''
                , '    delete registry ' + name + ' success'
                , ''
            ]);
        });
    });
}

function onAdd(name, url, home){
    var customRegistries = getCustomRegistry();
    if(customRegistries.hasOwnProperty(name)){
        return;
    }

    var config = customRegistries[name] = {};
    if (url[url.length-1] !== '/') url += '/';  // ensure url end with /
    config.registry = url;
    if(home){
        config.home = home;
    }

    setCustomRegistry(customRegistries, function(err){
        if(err){
            exit(err);
        }
        printMsg([
            ''
            , '    add registry ' + name + ' success'
            , ''
        ]);
    });
}

function onHome(name, browser){
    var allRegistries = getAllRegistry();
    var home = allRegistries[name] && allRegistries[name].home;
    if (home) {
        var args = [home];
        if (browser) args.push(browser);
        open.apply(null, args);
    }
}

function onTest(registry){
    var allRegistries = getAllRegistry();

    var toTest;

    if(registry){
        if(!allRegistries.hasOwnProperty(registry)){
            return;
        }
        toTest = only(allRegistries, registry);
    }else{
        toTest = allRegistries;
    }

    async.map(Object.keys(toTest), function(name, cbk){
        var registry = toTest[name];
        var start = +new Date();
        request(registry.registry + 'pedding', function(error){
            cbk(null, {
                name: name
                , registry: registry.registry
                , time: (+new Date() - start)
                , error: error ? true : false
            });
        });
    }, function(err, results){
        getCurrentRegistry(function(cur){
            var msg = [''];
            results.forEach(function(result){
                var prefix = result.registry === cur ? '* ' : '  ';
                var suffix = result.error ? 'Fetch Error' : result.time + 'ms';
                msg.push(prefix + result.name + line(result.name, 8) + suffix);
            });
            msg.push('');
            printMsg(msg);
        });
    });
}

/*//////////////// helper methods /////////////////*/

/*
* get current registry
*/
function getCurrentRegistry (cbk) {
    npmconf.load(function(err, conf){
        if(err){
            exit(err);
        }

        cbk(conf.get('registry'));
    });
}

function getCustomRegistry(){
    return fs.existsSync(NRMRC) ? ini.parse(fs.readFileSync(NRMRC, 'utf-8')) : {};
}

function setCustomRegistry(config, cbk){
    echo(ini.stringify(config), '>', NRMRC, cbk);
}

function getAllRegistry(){
    return extend({}, registries, getCustomRegistry());
}

function printErr(err){
    console.error('an error occured: ' + err);
}

function printMsg(infos){
    infos.forEach(function(info){
        console.log(info);
    });
}

/*
* print message & exit
*/
function exit (err) {
    printErr(err);
    process.exit(1);
}

function line (str, len) {
    var line = new Array(len - str.length).join('-');
    return ' ' + line + ' ';
}
<|endoftext|>


<commit_before>const program = require('commander');

const { print } = require('./index.js');

program
  .command('stories')
  .description('Read last hacker news stories')
  .option('-k, --keywords <keywords>', 'Keywords of your interest (comma separated)', list => list.split(','), [])
  .action(command => {
    if (command.keywords) {
      print(command.keywords)
    }
  });

program.parse(process.argv);
<commit_msg>--collections option<commit_after>const program = require('commander');

const { print } = require('./index.js');

const list = list => list.split(',');

program
  .command('stories')
  .description('Read last hacker news stories')
  .option('-k, --keywords <keywords>', 'Keywords of your interest (comma separated)', list, [])
  .option('-c, --collections <collections>', 'Collections of keywords in your home directory', list, [])
  .action(command => {
    if (command.keywords) {
      print(command.keywords)
    }

    if(command.collections) {
      // TODO
    }
  });

program.parse(process.argv);
<|endoftext|>


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

// don't assume that npm is installed in any particular spot, since this
// might conceivably be a bootstrap attempt.
var log = require("./lib/utils/log")
log.waitForConfig()
log.info("ok", "it worked if it ends with")

var fs = require("./lib/utils/graceful-fs")
  , path = require("path")
  , sys = require("./lib/utils/sys")
  , npm = require("./npm")
  , ini = require("./lib/utils/ini")
  , rm = require("./lib/utils/rm-rf")
  , errorHandler = require("./lib/utils/error-handler")

  // supported commands.
  , argv = process.argv.slice(2)
  , arg = ""

  , conf = {}
  , key
  , arglist = []
  , command
  , flagsDone

log.verbose(argv, "cli")

while (arg = argv.shift()) {
  if (!key && (arg.match(/^-+[h?]$/i) || arg.match(/^-+help$/i))) arg = "--usage"
  if (!command && (npm.commands.hasOwnProperty(arg))) {
    if (key) {
      conf[key] = true
      key = null
    }
    command = arg
  } else if (!flagsDone && arg.substr(0, 2) === "--") {
    if (key) conf[key] = true
    key = arg.substr(2)
    if (key === "usage") conf[key] = true, key = null
    flagsDone = (key === "")
  } else if (key) {
    conf[key] = arg
    key = null
  } else arglist.push(arg)
}
if (key) conf[key] = true
npm.argv = arglist

var vindex = arglist.indexOf("-v")
  , printVersion = vindex !== -1 || conf.version
if (printVersion) {
  sys.puts(npm.version)
  if (vindex !== -1) arglist.splice(vindex, 1)
} else log("npm@"+npm.version, "using")

// make sure that this version of node works with this version of npm.
var semver = require("./lib/utils/semver")
  , nodeVer = process.version
  , reqVer = npm.nodeVersionRequired
if (!semver.satisfies(nodeVer, reqVer)) {
  var badNodeVersion = new Error(
    "npm doesn't work with node " + nodeVer + "\nRequired: node@" + reqVer)
  throw badNodeVersion
}

process.on("uncaughtException", errorHandler)

if (!command && !printVersion) conf.usage = true

if (printVersion) itWorked = true
else {
  if (conf.usage && command !== "help") {
    arglist.unshift(command)
    command = "help"
  }
  ini.resolveConfigs(conf, function (er) {
    if (er) return errorHandler(er)
    npm.config.set("root", ini.get("root"))
    npm.commands[command](arglist, errorHandler)
  })
}
<commit_msg>Don't die as quickly when npm's package.json is missing<commit_after>#!/usr/bin/env node

// don't assume that npm is installed in any particular spot, since this
// might conceivably be a bootstrap attempt.
var log = require("./lib/utils/log")
log.waitForConfig()
log.info("ok", "it worked if it ends with")

var fs = require("./lib/utils/graceful-fs")
  , path = require("path")
  , sys = require("./lib/utils/sys")
  , npm = require("./npm")
  , ini = require("./lib/utils/ini")
  , rm = require("./lib/utils/rm-rf")
  , errorHandler = require("./lib/utils/error-handler")

  // supported commands.
  , argv = process.argv.slice(2)
  , arg = ""

  , conf = {}
  , key
  , arglist = []
  , command
  , flagsDone

log.verbose(argv, "cli")

while (arg = argv.shift()) {
  if (!key && (arg.match(/^-+[h?]$/i) || arg.match(/^-+help$/i))) arg = "--usage"
  if (!command && (npm.commands.hasOwnProperty(arg))) {
    if (key) {
      conf[key] = true
      key = null
    }
    command = arg
  } else if (!flagsDone && arg.substr(0, 2) === "--") {
    if (key) conf[key] = true
    key = arg.substr(2)
    if (key === "usage") conf[key] = true, key = null
    flagsDone = (key === "")
  } else if (key) {
    conf[key] = arg
    key = null
  } else arglist.push(arg)
}
if (key) conf[key] = true
npm.argv = arglist

var vindex = arglist.indexOf("-v")
  , printVersion = vindex !== -1 || conf.version
if (printVersion) {
  sys.puts(npm.version)
  if (vindex !== -1) arglist.splice(vindex, 1)
} else log("npm@"+npm.version, "using")

// make sure that this version of node works with this version of npm.
var semver = require("./lib/utils/semver")
  , nodeVer = process.version
  , reqVer = npm.nodeVersionRequired
if (reqVer && !semver.satisfies(nodeVer, reqVer)) {
  var badNodeVersion = new Error(
    "npm doesn't work with node " + nodeVer + "\nRequired: node@" + reqVer)
  throw badNodeVersion
}

process.on("uncaughtException", errorHandler)

if (!command && !printVersion) conf.usage = true

if (printVersion) itWorked = true
else {
  if (conf.usage && command !== "help") {
    arglist.unshift(command)
    command = "help"
  }
  ini.resolveConfigs(conf, function (er) {
    if (er) return errorHandler(er)
    npm.config.set("root", ini.get("root"))
    npm.commands[command](arglist, errorHandler)
  })
}
<|endoftext|>


<commit_before>#!/usr/bin/env node
'use strict';

var Decompress = require('./');
var fs = require('fs');
var nopt = require('nopt');
var pkg = require('./package.json');
var stdin = require('get-stdin');

/**
 * Options
 */

var opts = nopt({
	help: Boolean,
	mode: Number,
	strip: String,
	version: Boolean
}, {
	h: '--help',
	m: '--mode',
	s: '--strip',
	v: '--version'
});

/**
 * Help screen
 */

function help() {
	console.log([
		'',
		'  ' + pkg.description,
		'',
		'  Usage',
		'    decompress <file> [directory]',
		'    cat <file> | decompress [directory]',
		'',
		'  Example',
		'    decompress --strip 1 file.zip out',
		'    cat file.zip | decompress out',
		'',
		'  Options',
		'    -m, --mode     Set mode on the extracted files',
		'    -s, --strip    Equivalent to --strip-components for tar'
	].join('\n'));
}

/**
 * Show help
 */

if (opts.help) {
	help();
	return;
}

/**
 * Show package version
 */

if (opts.version) {
	console.log(pkg.version);
	return;
}

/**
 * Check if path is a file
 *
 * @param {String} path
 * @api private
 */

function isFile(path) {
	if (/^[^\s]+\.\w*$/g.test(path)) {
		return true;
	}

	try {
		return fs.statSync(path).isFile();
	} catch (e) {
		return false;
	}
}

/**
 * Run
 *
 * @param {String} src
 * @param {String} dest
 * @api private
 */

function run(src, dest) {
	var decompress = new Decompress(opts)
		.src(src)
		.dest(dest)
		.use(Decompress.tar(opts))
		.use(Decompress.tarbz2(opts))
		.use(Decompress.targz(opts))
		.use(Decompress.zip(opts));

	decompress.run(function (err) {
		if (err) {
			console.error(err);
			process.exit(1);
		}
	});
}

/**
 * Apply arguments
 */

if (process.stdin.isTTY) {
	var src = opts.argv.remain;
	var dest = process.cwd();

	if (!src.length) {
		help();
		return;
	}

	if (!isFile(src[src.length - 1])) {
		dest = src[src.length - 1];
		src.pop();
	}

	run(src, dest);
} else {
	var dest = opts.argv.remain;

	if (dest.length && !isFile(dest[dest.length - 1])) {
		dest = dest[dest.length - 1];
	} else {
		dest = process.cwd();
	}

	stdin.buffer(function (buf) {
		run(buf, dest);
	});
}
<commit_msg>Use `meow` in CLI<commit_after>#!/usr/bin/env node
'use strict';

var Decompress = require('./');
var fs = require('fs');
var meow = require('meow');
var stdin = require('get-stdin');

/**
 * Initialize CLI
 */

var cli = meow({
	help: [
		'  Usage',
		'    decompress <file> [directory]',
		'    cat <file> | decompress [directory]',
		'',
		'  Example',
		'    decompress --strip 1 file.zip out',
		'    cat file.zip | decompress out',
		'',
		'  Options',
		'    -m, --mode     Set mode on the extracted files',
		'    -s, --strip    Equivalent to --strip-components for tar'
	].join('\n')
}, {
	string: [
		'mode',
		'strip'
	],
	alias: {
		m: 'mode',
		s: 'strip'
	}
});

/**
 * Check if path is a file
 *
 * @param {String} path
 * @api private
 */

function isFile(path) {
	if (/^[^\s]+\.\w*$/g.test(path)) {
		return true;
	}

	try {
		return fs.statSync(path).isFile();
	} catch (e) {
		return false;
	}
}

/**
 * Run
 *
 * @param {String} src
 * @param {String} dest
 * @param {Object} opts
 * @api private
 */

function run(src, dest, opts) {
	var decompress = new Decompress(opts)
		.src(src)
		.dest(dest)
		.use(Decompress.tar(opts))
		.use(Decompress.tarbz2(opts))
		.use(Decompress.targz(opts))
		.use(Decompress.zip(opts));

	decompress.run(function (err) {
		if (err) {
			console.error(err);
			process.exit(1);
		}
	});
}

/**
 * Apply arguments
 */

if (process.stdin.isTTY) {
	var src = cli.input;
	var dest = process.cwd();

	if (!isFile(src[src.length - 1])) {
		dest = src[src.length - 1];
		src.pop();
	}

	run(src, dest, cli.flags);
} else {
	var dest = cli.input;

	if (dest.length && !isFile(dest[dest.length - 1])) {
		dest = dest[dest.length - 1];
	} else {
		dest = process.cwd();
	}

	stdin.buffer(function (buf) {
		run(buf, dest, cli.flags);
	});
}
<|endoftext|>


<commit_before>var argv = require('minimist')(process.argv.slice(2))
var dat = require('dat-core')
var prompt = require('prompt-sync')

var visualdiff = require('./')
if (argv._.length < 2) return usage()

var head1 = argv._[0]
var head2 = argv._[1]

var opts = {
  db: dat(argv.db, { valueEncoding: 'json' }),
  limit: argv.limit || 20,
  strategy: 'pages'
}

var onDiff = function (table1, table2, output, next) {
  repl(table1, table2, output, next)
}

var differ = visualdiff(head1, head2, opts, onDiff)

// TODO: add atom-shell app view option

function repl (table1, tabel2, output, next) {
  var self = this
  console.log(output)

  function doprompt () {
    console.log('Keep this chunk? [y,n,s,e,q,?]')
    var val = prompt()
    if (val === 's' || val === 'skip') {
      return next()
    }
    if (val === 'y' || val === 'yes') {
     // differ.merge() // TODO: choose 'newer' version
      return next()
    }
    if (val === 'n' || val === 'no') {
     // differ.decline() // TODO: choose 'older' version
      return next()
    }
    if (val === 'r' || val === 'rows') {
      opts.strategy = 'rows'
      return visualdiff(branch1, branch2, opts, onDiff)
    }
    if (val === 'c' || val === 'cols') {
      opts.strategy = 'cols'
      return visualdiff(branch1, branch2, opts, onDiff)
    }
    if (val === 'q' || val === 'quit') {
      return process.exit()
    }
    else {
      help()
      doprompt()
    }
  }
  doprompt()
}

function help () {
  console.log('skip (s), yes (y), no (n), cols (c), rows (r), quit (q)')
}

function usage () {
  console.log("dat-VisualDiff <head1> <head2> --db <dat-db> [--limit <num>]")
}<commit_msg>use process.stdout.write instead of console.log in some cases<commit_after>var argv = require('minimist')(process.argv.slice(2))
var dat = require('dat-core')
var prompt = require('prompt-sync')

var visualdiff = require('./')
if (argv._.length < 2) return usage()

var head1 = argv._[0]
var head2 = argv._[1]

var opts = {
  db: dat(argv.db, { valueEncoding: 'json' }),
  limit: argv.limit || 20,
  strategy: 'pages'
}

var onDiff = function (table1, table2, output, next) {
  repl(table1, table2, output, next)
}

var differ = visualdiff(head1, head2, opts, onDiff)

// TODO: add atom-shell app view option

function repl (table1, tabel2, output, next) {
  var self = this
  console.log(output)

  function doprompt () {
    process.stdout.write('Keep this chunk? [y,n,s,e,q,?] ')
    var val = prompt()
    if (val === 's' || val === 'skip') {
      return next()
    }
    if (val === 'y' || val === 'yes') {
     // differ.merge() // TODO: choose 'newer' version
      return next()
    }
    if (val === 'n' || val === 'no') {
     // differ.decline() // TODO: choose 'older' version
      return next()
    }
    if (val === 'r' || val === 'rows') {
      opts.strategy = 'rows'
      return visualdiff(branch1, branch2, opts, onDiff)
    }
    if (val === 'c' || val === 'cols') {
      opts.strategy = 'cols'
      return visualdiff(branch1, branch2, opts, onDiff)
    }
    if (val === 'q' || val === 'quit') {
      return process.exit()
    }
    else {
      help()
      doprompt()
    }
  }
  doprompt()
}

function help () {
  console.log('skip (s), yes (y), no (n), cols (c), rows (r), quit (q)')
}

function usage () {
  console.log("dat-VisualDiff <head1> <head2> --db <dat-db> [--limit <num>]")
}<|endoftext|>


<commit_before>#!/usr/bin/env node
'use strict';

var fs = require('fs');
var Imagemin = require('./');
var nopt = require('nopt');
var path = require('path');
var pkg = require('./package.json');
var stdin = require('get-stdin');

/**
 * Options
 */

var opts = nopt({
	help: Boolean,
	interlaced: Boolean,
	optimizationLevel: Number,
	progressive: Boolean,
	version: Boolean
}, {
	h: '--help',
	i: '--interlaced',
	l: '--optimizationLevel',
	p: '--progressive',
	v: '--version'
});

/**
 * Help screen
 */

function help() {
	console.log(pkg.description);
	console.log('');
	console.log('Usage');
	console.log('  $ imagemin <file> <directory>');
	console.log('  $ imagemin <file> > <output>');
	console.log('  $ cat <file> | imagemin > <output>');
	console.log('');
	console.log('Example');
	console.log('  $ imagemin images/* build');
	console.log('  $ imagemin foo.png > foo-optimized.png');
	console.log('  $ cat foo.png | imagemin > foo-optimized.png');
	console.log('');
	console.log('Options');
	console.log('  -i, --interlaced                    Interlace gif for progressive rendering');
	console.log('  -o, --optimizationLevel <number>    Select an optimization level between 0 and 7');
	console.log('  -p, --progressive                   Lossless conversion to progressive');
}

/**
 * Show help
 */

if (opts.help) {
	help();
	return;
}

/**
 * Show package version
 */

if (opts.version) {
	console.log(pkg.version);
	return;
}

/**
 * Check if path is a file
 *
 * @param {String} path
 * @api private
 */

function isFile(path) {
	try {
		return fs.statSync(path).isFile();
	} catch (e) {
		return false;
	}
}

/**
 * Run
 *
 * @param {Buffer} input
 * @param {Object} opts
 * @api private
 */

function run(input, opt) {
	var imagemin = new Imagemin()
		.src(input)
		.use(Imagemin.gifsicle(opts))
		.use(Imagemin.jpegtran(opts))
		.use(Imagemin.optipng(opts))
		.use(Imagemin.svgo());

	if (process.stdout.isTTY) {
		var name = path.basename(opt.input);
		var out = path.join(opt.output ? opt.output : 'build', name);

		imagemin.dest(path.join(out));
	}

	imagemin.optimize(function (err, file) {
		if (err) {
			console.error(err);
			process.exit(1);
		}

		if (!process.stdout.isTTY) {
			process.stdout.write(file.contents);
		}
	});
}

/**
 * Apply arguments
 */

if (process.stdin.isTTY) {
	var input = opts.argv.remain;
	var output;

	if (input.length === 0) {
		help();
		return;
	}

	if (input.length > 1 && !isFile(input[input.length - 1])) {
		output = input[input.length - 1];
		input.pop();
	}

	input.forEach(function (file) {
		fs.readFile(file, function (err, data) {
			if (err) {
				console.error(err);
				process.exit(1);
			}

			run(data, { input: file, output: output });
		});
	});
} else {
	stdin.buffer(function (data) {
		run(data);
	});
}
<commit_msg>minor cli tweaks<commit_after>#!/usr/bin/env node
'use strict';

var fs = require('fs');
var path = require('path');
var nopt = require('nopt');
var stdin = require('get-stdin');
var pkg = require('./package.json');
var Imagemin = require('./');

/**
 * Options
 */

var opts = nopt({
	help: Boolean,
	interlaced: Boolean,
	optimizationLevel: Number,
	progressive: Boolean,
	version: Boolean
}, {
	h: '--help',
	i: '--interlaced',
	l: '--optimizationLevel',
	p: '--progressive',
	v: '--version'
});

/**
 * Help screen
 */

 function help() {
 	console.log([
 		'',
 		'  ' + pkg.description,
 		'',
 		'  Usage',
 		'    imagemin <file> <directory>',
 		'    imagemin <file> > <output>',
 		'    cat <file> | imagemin > <output>',
 		'',
 		'  Example',
 		'    imagemin images/* build',
 		'    imagemin foo.png > foo-optimized.png',
 		'    cat foo.png | imagemin > foo-optimized.png',
 		'',
 		'  Options',
 		'    -i, --interlaced                    Interlace gif for progressive rendering',
 		'    -o, --optimizationLevel <number>    Select an optimization level between 0 and 7',
 		'    -p, --progressive                   Lossless conversion to progressive'
 	].join('\n'));
 }

/**
 * Show help
 */

if (opts.help) {
	help();
	return;
}

/**
 * Show package version
 */

if (opts.version) {
	console.log(pkg.version);
	return;
}

/**
 * Check if path is a file
 *
 * @param {String} path
 * @api private
 */

function isFile(path) {
	try {
		return fs.statSync(path).isFile();
	} catch (e) {
		return false;
	}
}

/**
 * Run
 *
 * @param {Buffer} input
 * @param {Object} opts
 * @api private
 */

function run(input, opt) {
	var imagemin = new Imagemin()
		.src(input)
		.use(Imagemin.gifsicle(opts))
		.use(Imagemin.jpegtran(opts))
		.use(Imagemin.optipng(opts))
		.use(Imagemin.svgo());

	if (process.stdout.isTTY) {
		var name = path.basename(opt.input);
		var out = path.join(opt.output ? opt.output : 'build', name);

		imagemin.dest(path.join(out));
	}

	imagemin.optimize(function (err, file) {
		if (err) {
			console.error(err);
			process.exit(1);
		}

		if (!process.stdout.isTTY) {
			process.stdout.write(file.contents);
		}
	});
}

/**
 * Apply arguments
 */

if (process.stdin.isTTY) {
	var input = opts.argv.remain;
	var output;

	if (input.length === 0) {
		help();
		return;
	}

	if (input.length > 1 && !isFile(input[input.length - 1])) {
		output = input[input.length - 1];
		input.pop();
	}

	input.forEach(function (file) {
		fs.readFile(file, function (err, data) {
			if (err) {
				console.error(err);
				process.exit(1);
			}

			run(data, { input: file, output: output });
		});
	});
} else {
	stdin.buffer(run);
}
<|endoftext|>


<commit_before>#!/usr/bin/env node
var args = require('minimist')(process.argv.splice(2), {
  alias: {p: 'port', q: 'quiet', v: 'version'},
  boolean: ['color'],
  default: {color: true}
})

process.title = 'dat'

// set debug before requiring other modules
if (args.debug) {
  var debug = args.debug
  if (typeof args.debug === 'boolean') debug = '*' // default
  process.env.DEBUG = debug
}

if (args.version) {
  var pkg = require('./package.json')
  console.log(pkg.version)
  process.exit(0)
}

var fs = require('fs')
var singleLineLog = require('single-line-log')
var prettyBytes = require('pretty-bytes')
var dns = require('dns-discovery')
var swarm = require('discovery-swarm')
var chalk = require('chalk')
var crypto = require('crypto')
var pump = require('pump')
var xtend = require('xtend')
var dat = require('./index.js')
var usage = require('./usage')

function noop () {}

var cmd = args._[0]
var logger = getLogger()

var LOG_INTERVAL = (args.logspeed ? +args.logspeed : 200)
if (isNaN(LOG_INTERVAL)) LOG_INTERVAL = 200
if (!args.color) chalk = new chalk.constructor({enabled: false})

checkLocation()

function checkLocation () {
  var loc = process.cwd()
  if (!args.path) return runCommand(loc)
  loc = args.path
  fs.exists(loc, function (exists) {
    if (!exists) {
      fs.mkdir(loc, function () {
        runCommand(loc)
      })
    }
    return runCommand(loc)
  })
}

function runDoctor () {
  var client = dns({
    servers: dat.DNS_SERVERS
  })

  var tick = 0
  var id = typeof args.doctor === 'string' ? args.doctor : crypto.randomBytes(32).toString('hex')
  var sw = swarm({
    dns: {
      servers: dat.DNS_SERVERS
    }
  })

  sw.on('error', function () {
    sw.listen(0)
  })
  sw.listen(3282)
  sw.on('listening', function () {
    client.whoami(function (err, me) {
      if (err) return console.error('Could not detect public ip / port')
      console.log('Public IP: ' + me.host)
      console.log('Your public port was ' + (me.port ? 'consistent' : 'inconsistent') + ' across remote multiple hosts')
      if (!me.port) console.log('Looks like you are behind a symmetric nat. Try enabling upnp.')
      else console.log('Looks like you can accept incoming p2p connections.')
      client.destroy()
      sw.join(id)
      sw.on('connecting', function (peer) {
        console.log('[info] Trying to connect to %s:%d', peer.host, peer.port)
      })
      sw.on('peer', function (peer) {
        console.log('[info] Discovered %s:%d', peer.host, peer.port)
      })
      sw.on('connection', function (connection) {
        var num = tick++
        var prefix = '0000'.slice(0, -num.toString().length) + num

        var data = crypto.randomBytes(16).toString('hex')
        console.log('[%s] Connection established to remote peer', prefix)
        var buf = ''
        connection.setEncoding('utf-8')
        connection.write(data)
        connection.on('data', function (remote) {
          buf += remote
          if (buf.length === data.length) {
            console.log('[%s] Remote peer echoed expected data back', prefix)
          }
        })
        pump(connection, connection, function () {
          console.log('[%s] Connected closed', prefix)
        })
      })

      console.log('')
      console.log('To test p2p connectivity login to another computer and run:')
      console.log('')
      console.log('  dat --doctor=' + id)
      console.log('')
      console.log('Waiting for incoming connections... (local port: %d)', sw.address().port)
      console.log('')
    })
  })
}

function runCommand (loc) {
  if (args.doctor) return runDoctor()
  if (!cmd) return usage('root.txt')

  var db = dat({home: args.home})

  if (cmd === 'link') link(loc, db)
  else if (cmd === 'list') list(loc, db)
  else if (cmd) download(loc, db)
}

function link (loc, db) {
  var dirs = args._.slice(1)
  if (dirs.length === 1 && dirs[0].match(/^dat:/)) {
    console.error('Do you mean `dat ' + dirs[0] + '` ?')
    process.exit(1)
  }

  if (dirs.length === 0) dirs = loc

  var stats = {}

  stats.total = db.fileStats(dirs, function (err) {
    if (err) throw err
    printScanProgress(stats, {done: true})
    clearInterval(scanInterval)
    var statsProgress = db.addFiles(dirs, function (err, link) {
      printAddProgress(stats, {done: true})
      clearInterval(addInterval)
      if (err) throw err
      db.joinTcpSwarm({link: link, port: args.port}, function (_err, swarm) {
        // ignore _err
        stats.swarm = swarm
        startProgressLogging(stats)
      })
    })
    stats = xtend(stats, statsProgress)

    var addInterval = setInterval(function () {
      printAddProgress(stats)
    }, LOG_INTERVAL)
  })

  var scanInterval = setInterval(function () {
    printScanProgress(stats)
  }, LOG_INTERVAL)
}

function list (loc, db) {
  var hash = args._[1]
  db.joinTcpSwarm({link: hash, port: args.port}, function (err, swarm) {
    if (err) throw err
    var archive = db.drive.get(swarm.link, loc)
    archive.ready(function (err) {
      if (err) throw err
      archive.createEntryStream().on('data', function (o) {
        logger.log(o)
      })
    })
  })
}

function download (loc, db) {
  // download/share
  var hash = args._[0]
  if (!hash) return usage('root.txt')
  hash = hash.trim().replace('dat://', '').replace('dat:', '')
  if (hash.length !== 64) {
    logger.error('Error: Invalid dat link\n')
    return usage('root.txt')
  }
  var downloadStats = db.download(hash, loc, function (err, swarm) {
    if (err) throw err
    swarm.downloading = false
    swarm.downloadComplete = true
  })
  startProgressLogging(downloadStats)
}

function startProgressLogging (stats) {
  setInterval(function () {
    printSwarmStatus(stats)
  }, LOG_INTERVAL)
  printSwarmStatus(stats)
}

function printScanProgress (stats, opts) {
  if (!opts) opts = {}
  var statusText = chalk.bold.blue('Calculating Size')
  if (opts.done) statusText = chalk.bold.dim('Creating Dat Link')
  var msg = getScanOutput(stats, statusText)
  logger.stdout(msg)
  if (opts.done) logger.log('')
}

function printAddProgress (stats, opts) {
  if (!opts) opts = {}
  if (opts.done) {
    var msg = printFileProgress(stats, {
      returnMsg: true, message: 'Files Read to Dat'
    })
    logger.stdout(msg)
    logger.log('')
  } else {
    printFileProgress(stats, {message: 'Adding Files to Dat'})
  }
}

function printSwarmStatus (stats) {
  var swarm = stats.swarm
  if (!swarm) return logger.stdout('Finding data sources...\n')

  if (swarm.hasMetadata && swarm.gettingMetadata) {
    // Print final metadata output
    var scanMsg = ''
    swarm.gettingMetadata = false
    scanMsg = getScanOutput(stats, chalk.bold.dim('Downloading Data'))
    logger.stdout(scanMsg)
    logger.log('')
  }

  var msg = swarm.downloading ? downloadMsg() : ''
  if (swarm.downloadComplete) msg = downloadCompleteMsg()

  var count = '0'
  var activePeers = swarm.connections.length
  var totalPeers = swarm.connecting + swarm.connections.length
  if (activePeers > 0) count = activePeers + '/' + totalPeers
  msg += chalk.bold('[Status] ') + 'Connected to ' + chalk.bold(count) + ' sources\n'

  if (!swarm.downloading) msg += chalk.bold('[Sharing] ')
  else if (swarm.downloading) msg += chalk.bold('[Downloading] ')
  msg += chalk.underline.blue('dat://' + swarm.link)

  if (!swarm.downloading && stats.uploaded.bytesRead > 0) {
    msg += '\n'
    msg += chalk.bold('[Upload] ') + prettyBytes(stats.uploaded.bytesRead)
    msg += ' at ' + prettyBytes(stats.uploadRate()) + '/s'
  }
  msg += '\n'
  logger.stdout(msg)

  function downloadMsg () {
    if (!stats.total.bytesTotal) return chalk.bold('Connecting...\n')
    if (swarm.gettingMetadata && !swarm.hasMetadata) {
      return getScanOutput(stats, chalk.bold.blue('Getting Metadata')) + '\n'
    }
    return printFileProgress(stats, {
      returnMsg: true, message: 'Downloading Data'
    })
  }

  function downloadCompleteMsg () {
    var outMsg = printFileProgress(stats, {
      returnMsg: true, showFilesOnly: true
    })
    outMsg += chalk.bold.green('[Done] ')
    outMsg += chalk.bold(
      'Downloaded ' + prettyBytes(stats.progress.bytesRead) + ' '
    )
    if (stats.parentFolder) outMsg += chalk.bold('to ') + chalk.bold(stats.parentFolder)
    outMsg += '\n'
    return outMsg
  }
}

function getScanOutput (stats, statusMsg) {
  if (!statusMsg) statusMsg = chalk.bold.green('Scan Progress')
  var dirCount = stats.total.directories + 1 // parent folder
  return statusMsg + ' ' + chalk.bold(
    '(' + stats.total.filesTotal + ' files, ' + dirCount + ' folders, ' +
    (stats.total.bytesTotal ? prettyBytes(stats.total.bytesTotal) + ' total' : '') + ')'
  )
}

function printFileProgress (stats, opts) {
  if (!opts) opts = {}
  var totalMsg = opts.message || 'File Progress'
  var msg = ''

  while (true) {
    if (stats.fileQueue.length === 0) break
    var file = stats.fileQueue[0]
    msg = getSingleFileOutput(file)
    var complete = (file.stats.bytesTotal === file.stats.bytesRead)
    if (!complete && stats.fileQueue.length === 1) break
    if (stats.fileQueue.length === 1 && !queueDone) msg = getSingleFileOutput(file)
    logger.stdout(chalk.dim.green('[Done] ') + chalk.dim(file.name))
    logger.log('')
    stats.fileQueue.shift()
  }

  var queueDone = (stats.total.bytesTotal <= stats.progress.bytesRead)
  if (queueDone) msg = ''
  else msg += '\n'

  if (opts.showFilesOnly && opts.returnMsg) return msg

  msg += getTotalProgressOutput(stats, totalMsg)
  if (opts.returnMsg) return msg
  else logger.stdout(msg)
}

function getSingleFileOutput (file) {
  var fileMsg = ''
  var filePercent = 0
  if (file.stats.bytesTotal > 0) {
    filePercent = Math.floor(
      100 * (file.stats.bytesRead / file.stats.bytesTotal)
    )
  }
  if (filePercent > 0 && filePercent < 100) {
    fileMsg = chalk.bold.blue('[' + ('   ' + filePercent).slice(-3) + '%] ')
  } else {
    fileMsg = chalk.bold.gray('       ') // # spaces = '[100%] '
  }
  fileMsg += chalk.blue(file.name)
  return fileMsg
}

function getTotalProgressOutput (stats, statusText, msg) {
  if (!stats) return ''
  if (!msg) msg = ''

  var bytesProgress = stats.progress.bytesRead
  var fileProgress = stats.progress.filesRead
  var totalPer = Math.floor(100 * (bytesProgress / stats.total.bytesTotal))

  if (totalPer === 100) msg += chalk.bold.green('[Done] ')
  else if (totalPer >= 0) msg += chalk.bold.dim('[' + ('  ' + totalPer).slice(-3) + '%] ')
  else msg += '        '
  msg += chalk.dim(
    statusText + ': ' + fileProgress + ' of ' + stats.total.filesTotal +
    chalk.dim(
      ' (' + prettyBytes(bytesProgress) +
      ' of ' + prettyBytes(stats.total.bytesTotal) + ') '
    )
  )
  if (stats.downloadRate) msg += chalk.dim(prettyBytes(stats.downloadRate()) + '/s ')
  msg += '\n'
  return msg
}

function getLogger () {
  if (args.quiet) {
    return {
      stderr: noop,
      stdout: noop,
      log: noop,
      error: noop
    }
  }

  if (args.debug) {
    return {
      stderr: console.error.bind(console),
      stdout: console.log.bind(console),
      log: console.error.bind(console),
      error: console.log.bind(console)
    }
  }

  return {
    stderr: singleLineLog.stderr,
    stdout: singleLineLog.stdout,
    log: console.log.bind(console),
    error: console.error.bind(console)
  }
}
<commit_msg>make port configurable<commit_after>#!/usr/bin/env node
var args = require('minimist')(process.argv.splice(2), {
  alias: {p: 'port', q: 'quiet', v: 'version'},
  boolean: ['color'],
  default: {color: true}
})

process.title = 'dat'

// set debug before requiring other modules
if (args.debug) {
  var debug = args.debug
  if (typeof args.debug === 'boolean') debug = '*' // default
  process.env.DEBUG = debug
}

if (args.version) {
  var pkg = require('./package.json')
  console.log(pkg.version)
  process.exit(0)
}

var fs = require('fs')
var singleLineLog = require('single-line-log')
var prettyBytes = require('pretty-bytes')
var dns = require('dns-discovery')
var swarm = require('discovery-swarm')
var chalk = require('chalk')
var crypto = require('crypto')
var pump = require('pump')
var xtend = require('xtend')
var dat = require('./index.js')
var usage = require('./usage')

function noop () {}

var cmd = args._[0]
var logger = getLogger()

var LOG_INTERVAL = (args.logspeed ? +args.logspeed : 200)
if (isNaN(LOG_INTERVAL)) LOG_INTERVAL = 200
if (!args.color) chalk = new chalk.constructor({enabled: false})

checkLocation()

function checkLocation () {
  var loc = process.cwd()
  if (!args.path) return runCommand(loc)
  loc = args.path
  fs.exists(loc, function (exists) {
    if (!exists) {
      fs.mkdir(loc, function () {
        runCommand(loc)
      })
    }
    return runCommand(loc)
  })
}

function runDoctor () {
  var client = dns({
    servers: dat.DNS_SERVERS
  })

  var tick = 0
  var id = typeof args.doctor === 'string' ? args.doctor : crypto.randomBytes(32).toString('hex')
  var sw = swarm({
    dns: {
      servers: dat.DNS_SERVERS
    }
  })

  sw.on('error', function () {
    sw.listen(0)
  })
  sw.listen(typeof args.port === 'number' ? args.port : 3282)
  sw.on('listening', function () {
    client.whoami(function (err, me) {
      if (err) return console.error('Could not detect public ip / port')
      console.log('Public IP: ' + me.host)
      console.log('Your public port was ' + (me.port ? 'consistent' : 'inconsistent') + ' across remote multiple hosts')
      if (!me.port) console.log('Looks like you are behind a symmetric nat. Try enabling upnp.')
      else console.log('Looks like you can accept incoming p2p connections.')
      client.destroy()
      sw.join(id)
      sw.on('connecting', function (peer) {
        console.log('[info] Trying to connect to %s:%d', peer.host, peer.port)
      })
      sw.on('peer', function (peer) {
        console.log('[info] Discovered %s:%d', peer.host, peer.port)
      })
      sw.on('connection', function (connection) {
        var num = tick++
        var prefix = '0000'.slice(0, -num.toString().length) + num

        var data = crypto.randomBytes(16).toString('hex')
        console.log('[%s] Connection established to remote peer', prefix)
        var buf = ''
        connection.setEncoding('utf-8')
        connection.write(data)
        connection.on('data', function (remote) {
          buf += remote
          if (buf.length === data.length) {
            console.log('[%s] Remote peer echoed expected data back', prefix)
          }
        })
        pump(connection, connection, function () {
          console.log('[%s] Connected closed', prefix)
        })
      })

      console.log('')
      console.log('To test p2p connectivity login to another computer and run:')
      console.log('')
      console.log('  dat --doctor=' + id)
      console.log('')
      console.log('Waiting for incoming connections... (local port: %d)', sw.address().port)
      console.log('')
    })
  })
}

function runCommand (loc) {
  if (args.doctor) return runDoctor()
  if (!cmd) return usage('root.txt')

  var db = dat({home: args.home})

  if (cmd === 'link') link(loc, db)
  else if (cmd === 'list') list(loc, db)
  else if (cmd) download(loc, db)
}

function link (loc, db) {
  var dirs = args._.slice(1)
  if (dirs.length === 1 && dirs[0].match(/^dat:/)) {
    console.error('Do you mean `dat ' + dirs[0] + '` ?')
    process.exit(1)
  }

  if (dirs.length === 0) dirs = loc

  var stats = {}

  stats.total = db.fileStats(dirs, function (err) {
    if (err) throw err
    printScanProgress(stats, {done: true})
    clearInterval(scanInterval)
    var statsProgress = db.addFiles(dirs, function (err, link) {
      printAddProgress(stats, {done: true})
      clearInterval(addInterval)
      if (err) throw err
      db.joinTcpSwarm({link: link, port: args.port}, function (_err, swarm) {
        // ignore _err
        stats.swarm = swarm
        startProgressLogging(stats)
      })
    })
    stats = xtend(stats, statsProgress)

    var addInterval = setInterval(function () {
      printAddProgress(stats)
    }, LOG_INTERVAL)
  })

  var scanInterval = setInterval(function () {
    printScanProgress(stats)
  }, LOG_INTERVAL)
}

function list (loc, db) {
  var hash = args._[1]
  db.joinTcpSwarm({link: hash, port: args.port}, function (err, swarm) {
    if (err) throw err
    var archive = db.drive.get(swarm.link, loc)
    archive.ready(function (err) {
      if (err) throw err
      archive.createEntryStream().on('data', function (o) {
        logger.log(o)
      })
    })
  })
}

function download (loc, db) {
  // download/share
  var hash = args._[0]
  if (!hash) return usage('root.txt')
  hash = hash.trim().replace('dat://', '').replace('dat:', '')
  if (hash.length !== 64) {
    logger.error('Error: Invalid dat link\n')
    return usage('root.txt')
  }
  var downloadStats = db.download(hash, loc, function (err, swarm) {
    if (err) throw err
    swarm.downloading = false
    swarm.downloadComplete = true
  })
  startProgressLogging(downloadStats)
}

function startProgressLogging (stats) {
  setInterval(function () {
    printSwarmStatus(stats)
  }, LOG_INTERVAL)
  printSwarmStatus(stats)
}

function printScanProgress (stats, opts) {
  if (!opts) opts = {}
  var statusText = chalk.bold.blue('Calculating Size')
  if (opts.done) statusText = chalk.bold.dim('Creating Dat Link')
  var msg = getScanOutput(stats, statusText)
  logger.stdout(msg)
  if (opts.done) logger.log('')
}

function printAddProgress (stats, opts) {
  if (!opts) opts = {}
  if (opts.done) {
    var msg = printFileProgress(stats, {
      returnMsg: true, message: 'Files Read to Dat'
    })
    logger.stdout(msg)
    logger.log('')
  } else {
    printFileProgress(stats, {message: 'Adding Files to Dat'})
  }
}

function printSwarmStatus (stats) {
  var swarm = stats.swarm
  if (!swarm) return logger.stdout('Finding data sources...\n')

  if (swarm.hasMetadata && swarm.gettingMetadata) {
    // Print final metadata output
    var scanMsg = ''
    swarm.gettingMetadata = false
    scanMsg = getScanOutput(stats, chalk.bold.dim('Downloading Data'))
    logger.stdout(scanMsg)
    logger.log('')
  }

  var msg = swarm.downloading ? downloadMsg() : ''
  if (swarm.downloadComplete) msg = downloadCompleteMsg()

  var count = '0'
  var activePeers = swarm.connections.length
  var totalPeers = swarm.connecting + swarm.connections.length
  if (activePeers > 0) count = activePeers + '/' + totalPeers
  msg += chalk.bold('[Status] ') + 'Connected to ' + chalk.bold(count) + ' sources\n'

  if (!swarm.downloading) msg += chalk.bold('[Sharing] ')
  else if (swarm.downloading) msg += chalk.bold('[Downloading] ')
  msg += chalk.underline.blue('dat://' + swarm.link)

  if (!swarm.downloading && stats.uploaded.bytesRead > 0) {
    msg += '\n'
    msg += chalk.bold('[Upload] ') + prettyBytes(stats.uploaded.bytesRead)
    msg += ' at ' + prettyBytes(stats.uploadRate()) + '/s'
  }
  msg += '\n'
  logger.stdout(msg)

  function downloadMsg () {
    if (!stats.total.bytesTotal) return chalk.bold('Connecting...\n')
    if (swarm.gettingMetadata && !swarm.hasMetadata) {
      return getScanOutput(stats, chalk.bold.blue('Getting Metadata')) + '\n'
    }
    return printFileProgress(stats, {
      returnMsg: true, message: 'Downloading Data'
    })
  }

  function downloadCompleteMsg () {
    var outMsg = printFileProgress(stats, {
      returnMsg: true, showFilesOnly: true
    })
    outMsg += chalk.bold.green('[Done] ')
    outMsg += chalk.bold(
      'Downloaded ' + prettyBytes(stats.progress.bytesRead) + ' '
    )
    if (stats.parentFolder) outMsg += chalk.bold('to ') + chalk.bold(stats.parentFolder)
    outMsg += '\n'
    return outMsg
  }
}

function getScanOutput (stats, statusMsg) {
  if (!statusMsg) statusMsg = chalk.bold.green('Scan Progress')
  var dirCount = stats.total.directories + 1 // parent folder
  return statusMsg + ' ' + chalk.bold(
    '(' + stats.total.filesTotal + ' files, ' + dirCount + ' folders, ' +
    (stats.total.bytesTotal ? prettyBytes(stats.total.bytesTotal) + ' total' : '') + ')'
  )
}

function printFileProgress (stats, opts) {
  if (!opts) opts = {}
  var totalMsg = opts.message || 'File Progress'
  var msg = ''

  while (true) {
    if (stats.fileQueue.length === 0) break
    var file = stats.fileQueue[0]
    msg = getSingleFileOutput(file)
    var complete = (file.stats.bytesTotal === file.stats.bytesRead)
    if (!complete && stats.fileQueue.length === 1) break
    if (stats.fileQueue.length === 1 && !queueDone) msg = getSingleFileOutput(file)
    logger.stdout(chalk.dim.green('[Done] ') + chalk.dim(file.name))
    logger.log('')
    stats.fileQueue.shift()
  }

  var queueDone = (stats.total.bytesTotal <= stats.progress.bytesRead)
  if (queueDone) msg = ''
  else msg += '\n'

  if (opts.showFilesOnly && opts.returnMsg) return msg

  msg += getTotalProgressOutput(stats, totalMsg)
  if (opts.returnMsg) return msg
  else logger.stdout(msg)
}

function getSingleFileOutput (file) {
  var fileMsg = ''
  var filePercent = 0
  if (file.stats.bytesTotal > 0) {
    filePercent = Math.floor(
      100 * (file.stats.bytesRead / file.stats.bytesTotal)
    )
  }
  if (filePercent > 0 && filePercent < 100) {
    fileMsg = chalk.bold.blue('[' + ('   ' + filePercent).slice(-3) + '%] ')
  } else {
    fileMsg = chalk.bold.gray('       ') // # spaces = '[100%] '
  }
  fileMsg += chalk.blue(file.name)
  return fileMsg
}

function getTotalProgressOutput (stats, statusText, msg) {
  if (!stats) return ''
  if (!msg) msg = ''

  var bytesProgress = stats.progress.bytesRead
  var fileProgress = stats.progress.filesRead
  var totalPer = Math.floor(100 * (bytesProgress / stats.total.bytesTotal))

  if (totalPer === 100) msg += chalk.bold.green('[Done] ')
  else if (totalPer >= 0) msg += chalk.bold.dim('[' + ('  ' + totalPer).slice(-3) + '%] ')
  else msg += '        '
  msg += chalk.dim(
    statusText + ': ' + fileProgress + ' of ' + stats.total.filesTotal +
    chalk.dim(
      ' (' + prettyBytes(bytesProgress) +
      ' of ' + prettyBytes(stats.total.bytesTotal) + ') '
    )
  )
  if (stats.downloadRate) msg += chalk.dim(prettyBytes(stats.downloadRate()) + '/s ')
  msg += '\n'
  return msg
}

function getLogger () {
  if (args.quiet) {
    return {
      stderr: noop,
      stdout: noop,
      log: noop,
      error: noop
    }
  }

  if (args.debug) {
    return {
      stderr: console.error.bind(console),
      stdout: console.log.bind(console),
      log: console.error.bind(console),
      error: console.log.bind(console)
    }
  }

  return {
    stderr: singleLineLog.stderr,
    stdout: singleLineLog.stdout,
    log: console.log.bind(console),
    error: console.error.bind(console)
  }
}
<|endoftext|>


<commit_before>#!/usr/bin/env node
var fs = require('fs')
var resolve = require('path').resolve
var meow = require('meow')

var initdify = require('./')

var cli = meow(`
  Usage
    $ systemdify <folder>

  Options
    -o, --output Write output to file

  Examples
    $ systemdify /path/to/my/app

    [Unit]
    description=My Application
    ...
`, {
  string: 'output',
  alias: {
    o: 'output'
  }
})

var folder = cli.input[0] || process.cwd()
var pjson = require(resolve(folder, 'package.json'))

var file = initdify({
  name: pjson.name,
  command: resolve(folder, pjson.main),
  description: pjson.description
})

if (cli.flags.output) {
  fs.writeFileSync(resolve('./', cli.flags.output), file)
  process.exit(0)
}

console.log(file)
<commit_msg>Write to systemd by default<commit_after>#!/usr/bin/env node
var fs = require('fs')
var resolve = require('path').resolve
var meow = require('meow')

var initdify = require('./')

var cli = meow(`
  Usage
    $ systemdify <folder>

  Options
    -o, --output Write output to file

  Examples
    $ systemdify /path/to/my/app

    [Unit]
    description=My Application
    ...
`, {
  string: 'output',
  alias: {
    o: 'output'
  }
})

var folder = cli.input[0] || process.cwd()
var pjson

try {
  pjson = require(resolve(folder, 'package.json'))
} catch (_) {
  console.error('No package.json found!')
  process.exit(1)
}

var file = initdify({
  name: pjson.name,
  command: resolve(folder, pjson.main),
  description: pjson.description
})

if (cli.flags.output) {
  fs.writeFileSync(cli.flags.output, file)
  process.exit(0)
} else {
  fs.writeFileSync(`/etc/systemd/system/${pjson.name}.service`)
}

console.log(file)
<|endoftext|>


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

var http    = require('http')
var path    = require('path')
var cp      = require('child_process')

var shoe    = require('shoe')
var levelup = require('level')
var request = require('request')
var split   = require('split')
var through = require('through')

var bundle  = require('securify/bundle')
var config  = require('./config')

var commands = {
  bundle: function (config, cb) {
    bundle(config._[0])
      .pipe(
        config.o ? fs.createWriteStream(config.o)
                 : process.stdout
      )
  },
  update: function (config, cb) {
    bundle(
      config.main || config._[0] || './index.js'
    , function (err, bundle) {
      if(err) return cb(err)
      request.put(
        config.master + '/data/' + config.name
      , function (err, res, body) {
        if(err) cb(err)
        else if(res.statusCode >= 300)
          cb(new Error(body || res.statusCode))
        else
          cb()
      }).end(bundle)
    })
  },
  local: function (config, cb) {
    var dir = path.join(config.root, config.name)
    var db = levelup(dir)//, {encoding: 'json'})

    var setup = require(path.resolve(config.main || 'index.js'))
    setup(db)
    shoe(function (stream) {
      db.emit('connection', stream)
    }).install(
      http.createServer(function (req, res) {
        db.emit('http_connection', req, res)
      }).listen(config.port), '/ws/' + config.name
    )
  },
  start: function (config, cb) {
    require('./server')(config, function (err) {
      if(err) return cb(err)
      console.error('listening on:', config.port)
      cb()
    })
  },
  config: function (config, cb) {
    console.log(JSON.stringify(config, null, 2))
    cb()
  },
  log: function (config, cb) {

    request({
      uri: config.master + '/log/' + config.name,
      qs: {
        min: config.since || config.min,
        max: config.until || config.max,
        tail: config.tail
      }
    })
    .pipe(split(null, null, JSON.parse))
    .pipe(through(console.log))

    cb()
  }
}

var command = config._.shift()

function exec (cmd, cb) {
  if(!cmd) return cb()
  console.error('>', cmd)
  cp.exec(cmd, cb)
}

function run (command, cb) {
  exec(config.on && config.on['pre-' + command], function (err) {
    if(err) return cb(err)
    commands[command](config, function (err) {
      if(err) return cb(err)
      exec(config.on && config.on['post-' + command], function (err) {
        cb(err)
      })
    })
  })
}

run(command, function (err) {
  if(err) throw err
})

<commit_msg>take first arg as start file<commit_after>#! /usr/bin/env node

var http    = require('http')
var path    = require('path')
var cp      = require('child_process')

var shoe    = require('shoe')
var levelup = require('level')
var request = require('request')
var split   = require('split')
var through = require('through')

var bundle  = require('securify/bundle')
var config  = require('./config')

var commands = {
  bundle: function (config, cb) {
    bundle(config._[0])
      .pipe(
        config.o ? fs.createWriteStream(config.o)
                 : process.stdout
      )
  },
  update: function (config, cb) {
    console.error(config)
    bundle(
      config.main || config._[0] || './index.js'
    , function (err, bundle) {
      if(err) return cb(err)
      request.put(
        config.master + '/data/' + config.name
      , function (err, res, body) {
        if(err) cb(err)
        else if(res.statusCode >= 300)
          cb(new Error(body || res.statusCode))
        else
          cb()
      }).end(bundle)
    })
  },
  local: function (config, cb) {
    var dir = path.join(config.root, config.name)
    var db = levelup(dir)//, {encoding: 'json'})

    var setup = require(path.resolve(config.main || config._[0] || './index.js'))
    setup(db)
    shoe(function (stream) {
      db.emit('connection', stream)
    }).install(
      http.createServer(function (req, res) {
        db.emit('http_connection', req, res)
      }).listen(config.port), '/ws/' + config.name
    )
  },
  start: function (config, cb) {
    require('./server')(config, function (err) {
      if(err) return cb(err)
      console.error('listening on:', config.port)
      cb()
    })
  },
  config: function (config, cb) {
    console.log(JSON.stringify(config, null, 2))
    cb()
  },
  log: function (config, cb) {

    request({
      uri: config.master + '/log/' + config.name,
      qs: {
        min: config.since || config.min,
        max: config.until || config.max,
        tail: config.tail
      }
    })
    .pipe(split(null, null, JSON.parse))
    .pipe(through(console.log))

    cb()
  }
}

var command = config._.shift()

function exec (cmd, cb) {
  if(!cmd) return cb()
  console.error('>', cmd)
  cp.exec(cmd, cb)
}

function run (command, cb) {
  exec(config.on && config.on['pre-' + command], function (err) {
    if(err) return cb(err)
    commands[command](config, function (err) {
      if(err) return cb(err)
      exec(config.on && config.on['post-' + command], function (err) {
        cb(err)
      })
    })
  })
}

run(command, function (err) {
  if(err) throw err
})

<|endoftext|>


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

var generate = require('./lib/render'),
    importer = require('./lib/import'),
    connect = require('connect'),
    Path = require('path');

var program = require('commander');

program.option('-p, --port <port>', 'specify the port [3000]', Number, 3000)

function help() {
    console.log('Usage:\n');
    console.log('$ cmd.js build content public\n');
    console.log('');
}

function build(src, dst) {
    var options = {
        source: Path.resolve(src),
        assets: Path.resolve(__dirname + '/assets'),
        target: Path.resolve(dst),
    }

    generate(options, function() {
        process.exit();
    });
}

function serve(path) {
    var server = connect();
    server.use(connect.static(path));

    server.listen(program.port, function() {
        console.log('\033[90mserving \033[36m%s\033[90m on port \033[96m%d\033[0m', path, program.port);
    });
}

program.on('--help', help);

program
    .command('serve <path>')
    .description('serve site')
    .action(serve);

program
    .command('build <src> <dst>')
    .description('build site')
    .action(build);

program
    .command('import <src.xml> <dst>')
    .description('import wordpress xml file')
    .action(function(src, dst) {
        importer(Path.resolve(src), Path.resolve(dst));
    });

program
    .command('*')
    .action(function() {
        console.error('ERR: No action specified\n');
        help();
    });

program.parse(process.argv);
<commit_msg>tidied and linted cmd.js<commit_after>#!/usr/bin/env node

'use strict';

var generate = require('./lib/render'),
    importer = require('./lib/import'),
    connect = require('connect'),
    Path = require('path');

var program = require('commander');

program.option('-p, --port <port>', 'specify the port [3000]', Number, 3000);

function help() {
    console.log('Usage:\n');
    console.log('$ cmd.js build content public\n');
    console.log('$ cmd.js serve public\n');
    console.log('');
}

function build(src, dst) {
    var options = {
        source: Path.resolve(src),
        assets: Path.resolve(__dirname + '/assets'),
        target: Path.resolve(dst),
    };

    generate(options, function() {
        process.exit();
    });
}

function serve(path) {
    var server = connect();
    server.use(connect.static(path));

    server.listen(program.port, function() {
        console.log('serving %s on port %s', path, program.port);
    });
}

program.on('--help', help);

program
    .command('serve <path>')
    .description('serve site')
    .action(serve);

program
    .command('build <src> <dst>')
    .description('build site')
    .action(build);

program
    .command('import <src.xml> <dst>')
    .description('import wordpress xml file')
    .action(function(src, dst) {
        importer(Path.resolve(src), Path.resolve(dst));
    });

program
    .command('*')
    .action(function() {
        console.error('ERR: No action specified\n');
        help();
    });

program.parse(process.argv);
<|endoftext|>


<commit_before>//var clock = new THREE.Clock();

//var container, stats;

var camera, cameraTarget, scene, renderer, controls;

init();
animate();

function init() {
    //define a few colors
    var colWhite = new THREE.Color("rgb(100%, 100%, 100%)");
    var colMetal = new THREE.Color("rgb(70%, 70%, 70%)");
    var colConcrete = new THREE.Color("rgb(30%, 30%, 30%)");

    //make materials
    var matConcrete = new THREE.MeshPhongMaterial( { color: colConcrete , specular: 0x111111, shininess: 50 } );
    var matAluminium = new THREE.MeshPhongMaterial( { color: colMetal , specular: 0x111111, shininess: 200 } );
    var matMelamine = new THREE.MeshPhongMaterial( { color: colWhite , specular: 0x111111, shininess: 100 } );

    //dimensions
    //main base
    var basL = 1900;
    var basW = 1000;
    var basH = 18;

    //x carriage angle
    var xCAL = 300;
    var xCAW = 76.2;
    var xCAH = 101.6;
    var xCAT = 6.35;

    //side bed (which the xRails and x ballscrew are seated on
    var sideBedL = basL;
    var sideBedW = 75;
    var sideBedH = 15;
    var sideBedO = 0;(xCAW - xCAT); //amount the sideBed overhangs the sides of the base by. Assumes inset by inner width of xCarAngl - for easy measuring

    //x rail
    var xRL = 1900;
    var xRD = 20;

    //x rail angle
    var xRAL = xRL;
    var xRAW = 50.8;
    var xRAH = 63.5;
    var xRAT = 6.35;

    //x ballscrew
    var xBSD = 20;
    var xBSL = 1900;

    //Gantry side
    var gSL = 300; //gantry side length
    var gSX = 100; //x-location of the gantry

    //y rail
    var yRL = 1004;
    var yRD = 16;

    //y ballscrew
    var yBSD = 16;
    var yBSL = 1000;

    //html container div - to house the WebGL content
    //already made in index.html... an alternative would be to make on the fly here
    var container = document.getElementById("container");

    //renderer
    renderer = new THREE.WebGLRenderer( { antialias: true } );
    renderer.setSize(window.innerWidth, window.innerHeight);
    container.appendChild( renderer.domElement );

    //create scene (global scope)
    scene = new THREE.Scene();
    scene.background = colWhite ;//new THREE.Color( 0xffffff );
    scene.add(new THREE.AxisHelper(3000)); //axis helper

    //create camera (global scope)
    //and add to scene
    camera = new THREE.PerspectiveCamera( 45, container.offsetWidth / container.offsetHeight, 1, 10000 );
    camera.position.y = -1500;
    //camera.lookAt(new THREE.Vector3(0,0,0));
    //camera.position.z = 200;
    scene.add( camera );

    //add TrackBall controls to the camera
    controls = new THREE.TrackballControls( camera);
    controls.position0.set( -200, -1500, 400 ); // set a new desired position
    controls.target0.set(0,0,100);
    controls.up0.set( 0, 0, 1 ); // set a new up vector
    controls.reset();
    controls.rotateSpeed = 10.0;
    controls.zoomSpeed = 1.2;
    controls.panSpeed = 1;
    controls.noZoom = false;
    controls.noPan = false;
    controls.staticMoving = false;
    controls.dynamicDampingFactor = 0.3;
    controls.minDistance = 1.1;
    controls.maxDistance = 10000;
    controls.keys = [ 16, 17, 18 ]; // [ rotateKey, zoomKey, panKey ]

    //create light(s)
    var dirLight = new THREE.DirectionalLight(colWhite , 0.95);
    dirLight.position.set(-200, -1000, 1000);
    dirLight.position.normalize();
    scene.add(dirLight);

    var pointLight = new THREE.PointLight(colWhite , 5, 50);
    pointLight.position.set(10, 20, -10);
    scene.add(pointLight);

    //Make part objects (from shop.js)
    var baseObj = new shopSheet(basL,basW,basH);
    var xRailAngObj = new shopAluAngle(xRAW,xRAH,xRAT,xRAL);
    var xRailObj = new shopSbrxx(xRL,xRD);
    var xLinBearObj = new shopSbrxxuu(xRD);
    var xBScrwObj = new shopRmxx05(xBSD, xBSL);
    var xBScrwFixSuppObj = new shopBkxx(xBSD);
    var xBScrwFltSuppObj = new shopBfxx(xBSD);
    var xBnutObj = new shopBallnut(xBSD);
    var xCarAngObj = new shopAluAngle(xCAW,xCAH,xCAT,xCAL);
    var yRailObj = new shopSbrxx(yRL,yRD);

    //make CSGs, and where applicable copies, to be merged into a single geometry
    var baseCsg = baseObj.makeCsg();
        baseCsg = baseCsg.center("y");
    var xRailAngCsg = xRailAngObj.makeCsg();
        xRailAngCsg = xRailAngCsg.mirroredY().mirroredZ().translate([0,xRailAngObj.width,0]);
        xRailAngCsg = xRailAngCsg.union(xRailAngCsg.mirroredY().translate([0,baseObj.width,0])).center("y");
    var xRailCsg = xRailObj.makeCsg();
        xRailCsg = xRailCsg.rotateX(90).union(xRailCsg.rotateX(-90).translate([0,baseObj.width - 2*xRailAngObj.inWidth,0])).center("y"); //outside of linear bearings set equal to yRail length
    var xLinBearCsg = xLinBearObj.makeCsg();
        xLinBearCsg = xLinBearCsg.rotateX(90).union(xLinBearCsg.rotateX(90).translate([gSL - xLinBearObj.length,0,0]));
        xLinBearCsg = xLinBearCsg.union(xLinBearCsg.rotateX(180).translate([0,baseObj.width - 2*xRailAngObj.inWidth +2*(xRailObj.railZPos - xLinBearObj.railZPos),0])).center("y");
    var xBScrwFixSuppCsg = xBScrwFixSuppObj.makeCsg();
        xBScrwFixSuppCsg = xBScrwFixSuppCsg.union(xBScrwFixSuppCsg.translate([0,baseObj.width  - 2*xRailAngObj.width - xBScrwFixSuppObj.width,0])).center("y").mirroredZ().mirroredX();
    var xBScrwFltSuppCsg = xBScrwFltSuppObj.makeCsg();
        xBScrwFltSuppCsg = xBScrwFltSuppCsg.union(xBScrwFltSuppCsg.translate([0,baseObj.width  - 2*xRailAngObj.width - xBScrwFixSuppObj.width,0])).center("y").mirroredZ();
    var xBScrwCsg = xBScrwObj.makeCsg();
        xBScrwCsg = xBScrwCsg.union(xBScrwCsg.translate([0,baseObj.width  - 2*xRailAngObj.width - xBScrwFixSuppObj.width,0])).center("y").mirroredX();
    var xBnutCsg = xBnutObj.makeCsg();
        xBnutCsg = xBnutCsg.union(xBnutCsg.translate([0,baseObj.width  - 2*xRailAngObj.width - xBScrwFixSuppObj.width,0])).center("y");

    //make THREE meshes, assemble and position
    var geom3;
    //base
    geom3 = THREE.CSG.fromCSG(baseCsg);
    var base = new THREE.Mesh(geom3,matConcrete);
    scene.add(base);
    //xRailAng
    geom3 = THREE.CSG.fromCSG(xRailAngCsg);
    var xRailAng = new THREE.Mesh(geom3,matAluminium);
    base.add(xRailAng);
    //xRailAng.position.set(0,0,baseObj.thickness);
    //xRails
    geom3 = THREE.CSG.fromCSG(xRailCsg);
    var xRails = new THREE.Mesh(geom3,matAluminium);
    xRailAng.add(xRails);
    xRails.position.set(0,0,xRailObj.width/2 - xRailAngObj.height);
    //xLinBears
    geom3 = THREE.CSG.fromCSG(xLinBearCsg);
    var xLinBears = new THREE.Mesh(geom3,matAluminium);
    xRails.add(xLinBears);
    xLinBears.position.set(gSX,0,0);
    //x ballscrew fixed support
    geom3 = THREE.CSG.fromCSG(xBScrwFixSuppCsg);
    var xBScrwFixSupp = new THREE.Mesh(geom3,matAluminium);
    base.add(xBScrwFixSupp);
    xBScrwFixSupp.position.set(xBScrwFltSuppObj.thick + xBScrwFixSuppObj.thick + xBScrwObj.threadEnd - xBScrwObj.threadStart,0,0);
    //x ballscrew floating support
    geom3 = THREE.CSG.fromCSG(xBScrwFltSuppCsg);
    var xBScrwFltSupp = new THREE.Mesh(geom3,matAluminium);
    base.add(xBScrwFltSupp);
    xBScrwFltSupp.position.set(0,0,0);
    //x ballscrew
    geom3 = THREE.CSG.fromCSG(xBScrwCsg);
    var xBScrw = new THREE.Mesh(geom3,matAluminium);
    xBScrwFltSupp.add(xBScrw);
    xBScrw.position.set(xBScrwObj.length + xBScrwFltSuppObj.thick - xBScrwObj.threadFltNub,0,-xBScrwFixSuppObj.bscrewZPos);
    //x ballnut
    geom3 = THREE.CSG.fromCSG(xBnutCsg);
    var xBnut = new THREE.Mesh(geom3,matAluminium);
    xBScrw.add(xBnut);
    xBnut.position.set(gSX + gSL/2 - xBnutObj.length/2 - xBScrwObj.length,0,0);
}

//animation loop
function animate() {
    //var delta = clock.getDelta();
    requestAnimationFrame( animate );
    camera.up.set(0,0,1);
    controls.update();
    render();
}

//render function
function render() {
    renderer.render( scene, camera );
}
<commit_msg>test test test test<commit_after>//var clock = new THREE.Clock();
//test test test
//var container, stats;

var camera, cameraTarget, scene, renderer, controls;

init();
animate();

function init() {
    //define a few colors
    var colWhite = new THREE.Color("rgb(100%, 100%, 100%)");
    var colMetal = new THREE.Color("rgb(70%, 70%, 70%)");
    var colConcrete = new THREE.Color("rgb(30%, 30%, 30%)");

    //make materials
    var matConcrete = new THREE.MeshPhongMaterial( { color: colConcrete , specular: 0x111111, shininess: 50 } );
    var matAluminium = new THREE.MeshPhongMaterial( { color: colMetal , specular: 0x111111, shininess: 200 } );
    var matMelamine = new THREE.MeshPhongMaterial( { color: colWhite , specular: 0x111111, shininess: 100 } );

    //dimensions
    //main base
    var basL = 1900;
    var basW = 1000;
    var basH = 18;

    //x carriage angle
    var xCAL = 300;
    var xCAW = 76.2;
    var xCAH = 101.6;
    var xCAT = 6.35;

    //side bed (which the xRails and x ballscrew are seated on
    var sideBedL = basL;
    var sideBedW = 75;
    var sideBedH = 15;
    var sideBedO = 0;(xCAW - xCAT); //amount the sideBed overhangs the sides of the base by. Assumes inset by inner width of xCarAngl - for easy measuring

    //x rail
    var xRL = 1900;
    var xRD = 20;

    //x rail angle
    var xRAL = xRL;
    var xRAW = 50.8;
    var xRAH = 63.5;
    var xRAT = 6.35;

    //x ballscrew
    var xBSD = 20;
    var xBSL = 1900;

    //Gantry side
    var gSL = 300; //gantry side length
    var gSX = 100; //x-location of the gantry

    //y rail
    var yRL = 1004;
    var yRD = 16;

    //y ballscrew
    var yBSD = 16;
    var yBSL = 1000;

    //html container div - to house the WebGL content
    //already made in index.html... an alternative would be to make on the fly here
    var container = document.getElementById("container");

    //renderer
    renderer = new THREE.WebGLRenderer( { antialias: true } );
    renderer.setSize(window.innerWidth, window.innerHeight);
    container.appendChild( renderer.domElement );

    //create scene (global scope)
    scene = new THREE.Scene();
    scene.background = colWhite ;//new THREE.Color( 0xffffff );
    scene.add(new THREE.AxisHelper(3000)); //axis helper

    //create camera (global scope)
    //and add to scene
    camera = new THREE.PerspectiveCamera( 45, container.offsetWidth / container.offsetHeight, 1, 10000 );
    camera.position.y = -1500;
    //camera.lookAt(new THREE.Vector3(0,0,0));
    //camera.position.z = 200;
    scene.add( camera );

    //add TrackBall controls to the camera
    controls = new THREE.TrackballControls( camera);
    controls.position0.set( -200, -1500, 400 ); // set a new desired position
    controls.target0.set(0,0,100);
    controls.up0.set( 0, 0, 1 ); // set a new up vector
    controls.reset();
    controls.rotateSpeed = 10.0;
    controls.zoomSpeed = 1.2;
    controls.panSpeed = 1;
    controls.noZoom = false;
    controls.noPan = false;
    controls.staticMoving = false;
    controls.dynamicDampingFactor = 0.3;
    controls.minDistance = 1.1;
    controls.maxDistance = 10000;
    controls.keys = [ 16, 17, 18 ]; // [ rotateKey, zoomKey, panKey ]

    //create light(s)
    var dirLight = new THREE.DirectionalLight(colWhite , 0.95);
    dirLight.position.set(-200, -1000, 1000);
    dirLight.position.normalize();
    scene.add(dirLight);

    var pointLight = new THREE.PointLight(colWhite , 5, 50);
    pointLight.position.set(10, 20, -10);
    scene.add(pointLight);

    //Make part objects (from shop.js)
    var baseObj = new shopSheet(basL,basW,basH);
    var xRailAngObj = new shopAluAngle(xRAW,xRAH,xRAT,xRAL);
    var xRailObj = new shopSbrxx(xRL,xRD);
    var xLinBearObj = new shopSbrxxuu(xRD);
    var xBScrwObj = new shopRmxx05(xBSD, xBSL);
    var xBScrwFixSuppObj = new shopBkxx(xBSD);
    var xBScrwFltSuppObj = new shopBfxx(xBSD);
    var xBnutObj = new shopBallnut(xBSD);
    var xCarAngObj = new shopAluAngle(xCAW,xCAH,xCAT,xCAL);
    var yRailObj = new shopSbrxx(yRL,yRD);

    //make CSGs, and where applicable copies, to be merged into a single geometry
    var baseCsg = baseObj.makeCsg();
        baseCsg = baseCsg.center("y");
    var xRailAngCsg = xRailAngObj.makeCsg();
        xRailAngCsg = xRailAngCsg.mirroredY().mirroredZ().translate([0,xRailAngObj.width,0]);
        xRailAngCsg = xRailAngCsg.union(xRailAngCsg.mirroredY().translate([0,baseObj.width,0])).center("y");
    var xRailCsg = xRailObj.makeCsg();
        xRailCsg = xRailCsg.rotateX(90).union(xRailCsg.rotateX(-90).translate([0,baseObj.width - 2*xRailAngObj.inWidth,0])).center("y"); //outside of linear bearings set equal to yRail length
    var xLinBearCsg = xLinBearObj.makeCsg();
        xLinBearCsg = xLinBearCsg.rotateX(90).union(xLinBearCsg.rotateX(90).translate([gSL - xLinBearObj.length,0,0]));
        xLinBearCsg = xLinBearCsg.union(xLinBearCsg.rotateX(180).translate([0,baseObj.width - 2*xRailAngObj.inWidth +2*(xRailObj.railZPos - xLinBearObj.railZPos),0])).center("y");
    var xBScrwFixSuppCsg = xBScrwFixSuppObj.makeCsg();
        xBScrwFixSuppCsg = xBScrwFixSuppCsg.union(xBScrwFixSuppCsg.translate([0,baseObj.width  - 2*xRailAngObj.width - xBScrwFixSuppObj.width,0])).center("y").mirroredZ().mirroredX();
    var xBScrwFltSuppCsg = xBScrwFltSuppObj.makeCsg();
        xBScrwFltSuppCsg = xBScrwFltSuppCsg.union(xBScrwFltSuppCsg.translate([0,baseObj.width  - 2*xRailAngObj.width - xBScrwFixSuppObj.width,0])).center("y").mirroredZ();
    var xBScrwCsg = xBScrwObj.makeCsg();
        xBScrwCsg = xBScrwCsg.union(xBScrwCsg.translate([0,baseObj.width  - 2*xRailAngObj.width - xBScrwFixSuppObj.width,0])).center("y").mirroredX();
    var xBnutCsg = xBnutObj.makeCsg();
        xBnutCsg = xBnutCsg.union(xBnutCsg.translate([0,baseObj.width  - 2*xRailAngObj.width - xBScrwFixSuppObj.width,0])).center("y");

    //make THREE meshes, assemble and position
    var geom3;
    //base
    geom3 = THREE.CSG.fromCSG(baseCsg);
    var base = new THREE.Mesh(geom3,matConcrete);
    scene.add(base);
    //xRailAng
    geom3 = THREE.CSG.fromCSG(xRailAngCsg);
    var xRailAng = new THREE.Mesh(geom3,matAluminium);
    base.add(xRailAng);
    //xRailAng.position.set(0,0,baseObj.thickness);
    //xRails
    geom3 = THREE.CSG.fromCSG(xRailCsg);
    var xRails = new THREE.Mesh(geom3,matAluminium);
    xRailAng.add(xRails);
    xRails.position.set(0,0,xRailObj.width/2 - xRailAngObj.height);
    //xLinBears
    geom3 = THREE.CSG.fromCSG(xLinBearCsg);
    var xLinBears = new THREE.Mesh(geom3,matAluminium);
    xRails.add(xLinBears);
    xLinBears.position.set(gSX,0,0);
    //x ballscrew fixed support
    geom3 = THREE.CSG.fromCSG(xBScrwFixSuppCsg);
    var xBScrwFixSupp = new THREE.Mesh(geom3,matAluminium);
    base.add(xBScrwFixSupp);
    xBScrwFixSupp.position.set(xBScrwFltSuppObj.thick + xBScrwFixSuppObj.thick + xBScrwObj.threadEnd - xBScrwObj.threadStart,0,0);
    //x ballscrew floating support
    geom3 = THREE.CSG.fromCSG(xBScrwFltSuppCsg);
    var xBScrwFltSupp = new THREE.Mesh(geom3,matAluminium);
    base.add(xBScrwFltSupp);
    xBScrwFltSupp.position.set(0,0,0);
    //x ballscrew
    geom3 = THREE.CSG.fromCSG(xBScrwCsg);
    var xBScrw = new THREE.Mesh(geom3,matAluminium);
    xBScrwFltSupp.add(xBScrw);
    xBScrw.position.set(xBScrwObj.length + xBScrwFltSuppObj.thick - xBScrwObj.threadFltNub,0,-xBScrwFixSuppObj.bscrewZPos);
    //x ballnut
    geom3 = THREE.CSG.fromCSG(xBnutCsg);
    var xBnut = new THREE.Mesh(geom3,matAluminium);
    xBScrw.add(xBnut);
    xBnut.position.set(gSX + gSL/2 - xBnutObj.length/2 - xBScrwObj.length,0,0);
}

//animation loop
function animate() {
    //var delta = clock.getDelta();
    requestAnimationFrame( animate );
    camera.up.set(0,0,1);
    controls.update();
    render();
}

//render function
function render() {
    renderer.render( scene, camera );
}
<|endoftext|>


<commit_before>
const textEq = () => {
  const condition = {
    "query": {

    }
  }
  return condition
}

const textNotEq = () => {

}

const textExists = () => {

}

const textNotExists = () => {

}

const textPrefixEq = () => {

}

const textPrefixNotEq = () => {

}

const textEnd = () => {

}

const textNotEndWith = () => {

}

const textInclude = () => {

}

const textNotInclude = () => {

}

const textIsEmpty = () => {

}

const textIsNotEmpty = () => {

}

module.exports = {
  textEq,
  textNotEq,
  textExists,
  textNotExists,
  textPrefixEq,
  textPrefixNotEq,
  textEnd,
  textNotEndWith,
  textInclude,
  textNotInclude,
  textIsEmpty,
  textIsNotEmpty
}<commit_msg>[fuchun] #Tech adjust text-category<commit_after>
const textEq = (displayName, values) => {
  let condition = {
    term: {
      [displayName]: values[0]
    }
  }

  return condition
}

const textNotEq = (displayName, values) => {
  const condition = {
    must_not: {
      [displayName]: values[0]
    }
  }
  return condition
}

const textExists = (displayName, values) => {
  const should = values.map(v => {
    bool: {
      must:{
        term: {
          [displayName]: v
        }
      }
    }
  })

  let condition = {
      "bool": {should}
  }
  return condition
}

const textNotExists = (displayName, values) => {

  const should = values.map(v => {
    bool: {
      must_not:{
        term: {
          [displayName]: v
        }
      }
    }
  })

  let condition = {
      "bool": {should}
  }

  return condition
}

const textPrefixEq = () => {

}

const textPrefixNotEq = () => {

}

const textEnd = () => {

}

const textNotEndWith = () => {

}

const textInclude = () => {

}

const textNotInclude = () => {

}

const textIsEmpty = () => {

}

const textIsNotEmpty = () => {

}

module.exports = {
  textEq,
  textNotEq,
  textExists,
  textNotExists,
  textPrefixEq,
  textPrefixNotEq,
  textEnd,
  textNotEndWith,
  textInclude,
  textNotInclude,
  textIsEmpty,
  textIsNotEmpty
}<|endoftext|>


<commit_before>import React from 'react';
import { mount } from 'enzyme';
import Affix from '..';
import Button from '../../button';

const events = {};

class AffixMounter extends React.Component {
  componentDidMount() {
    this.container.addEventListener = jest.fn().mockImplementation((event, cb) => {
      events[event] = cb;
    });
  }

  getTarget = () => this.container;

  render() {
    return (

 {
          this.container = node;
        }}
        className="container"
      >
        <Affix
          className="fixed"
          target={this.getTarget}
          ref={ele => {
            this.affix = ele;
          }}
          {...this.props}
        >
          <Button type="primary">Fixed at the top of container</Button>
        </Affix>

    );
  }
}

describe('Affix Render', () => {
  let wrapper;

  const classRect = {
    container: {
      top: 0,
      bottom: 100,
    },
  };

  const originGetBoundingClientRect = HTMLElement.prototype.getBoundingClientRect;
  HTMLElement.prototype.getBoundingClientRect = function getBoundingClientRect() {
    return (
      classRect[this.className] || {
        top: 0,
        bottom: 0,
      }
    );
  };

  beforeAll(() => {
    jest.useFakeTimers();
  });

  afterAll(() => {
    jest.useRealTimers();
    HTMLElement.prototype.getBoundingClientRect = originGetBoundingClientRect;
  });
  const movePlaceholder = top => {
    classRect.fixed = {
      top,
      bottom: top,
    };
    events.scroll({
      type: 'scroll',
    });
    jest.runAllTimers();
  };

  it('Anchor render perfectly', () => {
    document.body.innerHTML = '
';

    wrapper = mount(<AffixMounter />, { attachTo: document.getElementById('mounter') });
    jest.runAllTimers();

    movePlaceholder(0);
    expect(wrapper.instance().affix.state.affixStyle).toBeFalsy();

    movePlaceholder(-100);
    expect(wrapper.instance().affix.state.affixStyle).toBeTruthy();

    movePlaceholder(0);
    expect(wrapper.instance().affix.state.affixStyle).toBeFalsy();
  });

  it('support offsetBottom', () => {
    document.body.innerHTML = '
';

    wrapper = mount(<AffixMounter offsetBottom={0} />, {
      attachTo: document.getElementById('mounter'),
    });

    jest.runAllTimers();

    movePlaceholder(300);
    expect(wrapper.instance().affix.state.affixStyle).toBeTruthy();

    movePlaceholder(0);
    expect(wrapper.instance().affix.state.affixStyle).toBeFalsy();

    movePlaceholder(300);
    expect(wrapper.instance().affix.state.affixStyle).toBeTruthy();
  });

  it('updatePosition when offsetTop changed', () => {
    document.body.innerHTML = '
';

    wrapper = mount(<AffixMounter offsetTop={0} />, {
      attachTo: document.getElementById('mounter'),
    });
    jest.runAllTimers();

    movePlaceholder(-100);
    expect(wrapper.instance().affix.state.affixStyle.top).toBe(0);
    wrapper.setProps({
      offsetTop: 10,
    });
    jest.runAllTimers();
    expect(wrapper.instance().affix.state.affixStyle.top).toBe(10);
  });
});
<commit_msg>test: update cases for Affix<commit_after>import React from 'react';
import { mount } from 'enzyme';
import Affix from '..';
import Button from '../../button';

const events = {};

class AffixMounter extends React.Component {
  componentDidMount() {
    this.container.addEventListener = jest.fn().mockImplementation((event, cb) => {
      events[event] = cb;
    });
  }

  getTarget = () => this.container;

  render() {
    return (

 {
          this.container = node;
        }}
        className="container"
      >
        <Affix
          className="fixed"
          target={this.getTarget}
          ref={ele => {
            this.affix = ele;
          }}
          {...this.props}
        >
          <Button type="primary">Fixed at the top of container</Button>
        </Affix>

    );
  }
}

describe('Affix Render', () => {
  let wrapper;

  const classRect = {
    container: {
      top: 0,
      bottom: 100,
    },
  };

  const originGetBoundingClientRect = HTMLElement.prototype.getBoundingClientRect;
  // eslint-disable-next-line
  HTMLElement.prototype.getBoundingClientRect = function() {
    return (
      classRect[this.className] || {
        top: 0,
        bottom: 0,
      }
    );
  };

  beforeAll(() => {
    jest.useFakeTimers();
  });

  afterAll(() => {
    jest.useRealTimers();
    HTMLElement.prototype.getBoundingClientRect = originGetBoundingClientRect;
  });
  const movePlaceholder = top => {
    classRect.fixed = {
      top,
      bottom: top,
    };
    events.scroll({
      type: 'scroll',
    });
    jest.runAllTimers();
  };

  it('Anchor render perfectly', () => {
    document.body.innerHTML = '
';

    wrapper = mount(<AffixMounter />, { attachTo: document.getElementById('mounter') });
    jest.runAllTimers();

    movePlaceholder(0);
    expect(wrapper.instance().affix.state.affixStyle).toBeFalsy();

    movePlaceholder(-100);
    expect(wrapper.instance().affix.state.affixStyle).toBeTruthy();

    movePlaceholder(0);
    expect(wrapper.instance().affix.state.affixStyle).toBeFalsy();
  });

  it('support offsetBottom', () => {
    document.body.innerHTML = '
';

    wrapper = mount(<AffixMounter offsetBottom={0} />, {
      attachTo: document.getElementById('mounter'),
    });

    jest.runAllTimers();

    movePlaceholder(300);
    expect(wrapper.instance().affix.state.affixStyle).toBeTruthy();

    movePlaceholder(0);
    expect(wrapper.instance().affix.state.affixStyle).toBeFalsy();

    movePlaceholder(300);
    expect(wrapper.instance().affix.state.affixStyle).toBeTruthy();
  });

  it('updatePosition when offsetTop changed', () => {
    document.body.innerHTML = '
';

    wrapper = mount(<AffixMounter offsetTop={0} />, {
      attachTo: document.getElementById('mounter'),
    });
    jest.runAllTimers();

    movePlaceholder(-100);
    expect(wrapper.instance().affix.state.affixStyle.top).toBe(0);
    wrapper.setProps({
      offsetTop: 10,
    });
    jest.runAllTimers();
    expect(wrapper.instance().affix.state.affixStyle.top).toBe(10);
  });

  it('updatePosition when target changed', () => {
    const container = '
';
    const getTarget = () => container;
    wrapper = mount(<Affix target={getTarget} />).instance();
    wrapper.componentDidUpdate({ target: null });
    expect(wrapper.state.status).toBe(0);
    expect(wrapper.state.affixStyle).toBe(undefined);
    expect(wrapper.state.placeholderStyle).toBe(undefined);
  });
});
<|endoftext|>