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

var hyperstream = require('hyperstream')
var fromString = require('from2-string')
var pinoColada = require('pino-colada')
var parallel = require('run-parallel')
var explain = require('explain-error')
var concat = require('concat-stream')
var mapLimit = require('map-limit')
var purify = require('purify-css')
var logHttp = require('log-http')
var uglify = require('uglify-js')
var resolve = require('resolve')
var mkdirp = require('mkdirp')
var subarg = require('subarg')
var tmp = require('temp-path')
var from = require('from2')
var disc = require('disc')
var http = require('http')
var open = require('open')
var path = require('path')
var pino = require('pino')
var pump = require('pump')
var zlib = require('zlib')
var fs = require('fs')

var htmlMinifyStream = require('./lib/html-minify-stream')
var zlibMaybe = require('./lib/gzip-maybe')
var Sse = require('./lib/sse')
var bankai = require('./')

var pretty = pinoColada()
pretty.pipe(process.stdout)

var argv = subarg(process.argv.slice(2), {
  string: [ 'open', 'port', 'assets' ],
  boolean: [ 'watch', 'verbose', 'help', 'version', 'debug', 'electron' ],
  default: {
    address: 'localhost',
    assets: 'assets',
    debug: false,
    open: false,
    port: 8080,
    uglify: true
  },
  alias: {
    address: 'A',
    assets: 'a',
    css: 'c',
    debug: 'd',
    electron: 'e',
    help: 'h',
    html: 'H',
    js: 'j',
    uglify: 'u',
    open: 'o',
    port: 'p',
    verbose: 'V',
    version: 'v',
    watch: 'w'
  }
})

var logLevel = argv.verbose ? 'debug' : 'info'
var log = pino({ name: 'bankai', level: logLevel }, pretty)

var usage = `
  Usage:
    $ bankai <command> [options]

  Commands:
    <default>                      Run 'bankai start'
    start <filename>               Start a bankai server
    build <filename> <directory>   Compile and export files to a directory
    inspect <filename>             Visualize the dependency tree

    Options:
      -a, --assets=<directory>  Serve static assets [default: assets]
      -A, --address=<ip>      Ip address to listen [default: localhost]
      -c, --css=<subargs>     Pass subarguments to sheetify
      -d, --debug             Include sourcemaps [default: false]
      -e, --electron          Enable electron mode for the bundler
      -h, --help              Print usage
      -H, --html=<subargs>    Pass subarguments to create-html
      -j, --js=<subargs>      Pass subarguments to browserify
      -o, --open=<browser>    Open html in a browser [default: system default]
      -p, --port=<n>          Bind bankai to a port [default: 8080]
      -V, --verbose           Include debug messages
      -w, --watch <bool>      Toggle watch mode
      -u, --uglify <bool>     Toggle uglifyify. [default: true]

  Examples:
    $ bankai index.js -p 8080            # start bankai on port 8080
    $ bankai index.js --open             # open html in the browser
    $ bankai -c [ -u sheetify-cssnext ]  # use cssnext in sheetify
    $ bankai -j [ -t brfs ]              # use brfs in browserify
    $ bankai build index.js dist/        # compile and export to dist/

  Notes:
    When specifying both --watch and --uglify using the long form, you must omit
    the = when specifying them to be turned off.

  Examples:
    bankai example.js --open=firefox-aurora -p 3000
    bankai example.js --uglify false -w false
`

main(argv)

function main (argv) {
  if ((argv._[0] !== 'build') && (argv._[0] !== 'start') && argv._[0] !== 'inspect') {
    argv._.unshift('start')
  }

  if (argv.h) {
    console.log(usage)
    return process.exit()
  } else if (argv.v) {
    console.log(require('../package.json').version)
    return process.exit()
  }

  var cmd = argv._[0]
  var _entry = argv._[1] || 'index.js'
  var localEntry = './' + _entry.replace(/^.\//, '')
  var entry = resolve.sync(localEntry, { basedir: process.cwd() })
  var outputDir = argv._[2] || 'dist'

  if (cmd === 'start') {
    start(entry, argv, handleError)
  } else if (cmd === 'build') {
    build(entry, outputDir, argv, handleError)
  } else if (cmd === 'inspect') {
    inspect(entry, argv, handleError)
  } else {
    log.error(usage)
    return process.exit(1)
  }

  function handleError (err) {
    if (err) log.error(err)
  }
}

function start (entry, argv, done) {
  log.debug('running command: start')
  argv.watch = true

  var assets = bankai(entry, argv)
  var staticAsset = new RegExp('/' + argv.assets)
  var address = argv.address
  var port = argv.port
  var sse = Sse(assets)

  assets.on('js-bundle', function () {
    log.info('bundle:js')
  })

  assets.on('css-bundle', function () {
    log.info('bundle:css')
  })

  var server = http.createServer(handler)
  server.listen(port, address, onlisten)

  var stats = logHttp(server)
  stats.on('data', function (level, data) {
    log[level](data)
  })

  function handler (req, res) {
    var url = req.url
    log.debug('received request on url: ' + url)
    if (url === '/') {
      assets.html(req, res).pipe(zlibMaybe(req, res)).pipe(res)
    } else if (url === '/sse') {
      sse(req, res)
    } else if (url === '/bundle.js') {
      assets.js(req, res).pipe(zlibMaybe(req, res)).pipe(res)
    } else if (url === '/bundle.css') {
      assets.css(req, res).pipe(zlibMaybe(req, res)).pipe(res)
    } else if (req.headers['accept'].indexOf('html') > 0) {
      assets.html(req, res).pipe(zlibMaybe(req, res)).pipe(res)
    } else if (staticAsset.test(url)) {
      assets.static(req).pipe(res)
    } else {
      res.writeHead(404, 'Not Found')
      res.end()
    }
  }

  function onlisten () {
    var relative = path.relative(process.cwd(), entry)
    var addr = 'http://' + address + ':' + port
    log.info('Started for ' + relative + ' on ' + addr)
    if (argv.open !== false) {
      var app = argv.open.length ? argv.open : ''
      open(addr, app, function (err) {
        if (err) return done(explain(err, `err running ${app}`))
        done()
      })
    }
  }
}

function build (entry, outputDir, argv, done) {
  log.debug('running command: build')

  // cast argv.watch to a boolean
  argv.watch = argv.watch === undefined ? false : argv.watch
  argv.assert = false

  mkdirp.sync(outputDir)
  buildStaticAssets(entry, outputDir, argv, done)

  var buffers = {}
  var assets = bankai(entry, argv)
  var files = ['index.html', 'bundle.js', 'bundle.css']

  mapLimit(files, Infinity, iterator, function (err) {
    if (err) return done(err)
    parallel([ buildHtml, buildJs, buildCss ], done)
  })

  function iterator (file, done) {
    var source = assets[file.replace(/^.*\./, '')]()
    log.debug(file + ' started')

    var sink = concat(function (buf) {
      buffers[file] = buf
    })
    pump(source, sink, done)
  }

  function buildHtml (done) {
    var file = 'index.html'
    var buf = buffers[file]
    var outfile = path.join(outputDir, file)

    var sink = fs.createWriteStream(outfile)
    var source = hyperstream()
    source.end(buf)

    pump(source, htmlMinifyStream(), sink, done)
    printSize(buf, outfile, function (err) {
      if (err) return done(err)
    })
  }

  function buildCss (done) {
    var css = buffers['bundle.css'].toString()
    var js = buffers['bundle.js'].toString()
    css = purify(js, css, { minify: true })

    var outfile = path.join(outputDir, 'bundle.css')
    var sink = fs.createWriteStream(outfile)
    var source = fromString(css)

    pump(source, sink, done)
    printSize(Buffer.from(css), outfile, function (err) {
      if (err) return done(err)
    })
  }

  function buildJs (done) {
    var file = 'bundle.js'
    var buf = buffers[file]
    var js = buf.toString()

    // FIXME argv.uglify should always be a bool
    if (argv.uglify !== false && argv.uglify !== 'false') {
      log.debug('uglify starting')
      js = uglify.minify(js, {
        fromString: true,
        compress: true,
        mangle: true,
        filename: file,
        sourceMaps: false
      })
      log.debug('uglify finished')
      buf = Buffer.from(js.code)
    }

    var outfile = path.join(outputDir, 'bundle.js')
    log.debug('writing to file ' + outfile)
    var sink = fs.createWriteStream(outfile)
    var source = from([buf])

    pump(source, sink, done)
    printSize(buf, outfile, function (err) {
      if (err) return done(err)
    })
  }
}

function printSize (buf, outfile, done) {
  zlib.deflate(buf, function (err, buf) {
    if (err) return done(err)
    var length = buf.length
    var location = path.relative(process.cwd(), outfile)
    // Warn if serving up more than 60kb in {html,css,js}
    var level = buf.length < 60000 ? 'info' : 'warn'
    var msg = level === 'warn' ? location + ' (large)' : location
    log[level]({
      message: msg,
      contentLength: length
    })
  })
}

function buildStaticAssets (entry, outputDir, argv, done) {
  var src = path.join(path.dirname(entry), argv.assets)
  var dest = path.join(path.dirname(entry), outputDir, argv.assets)
  if (fs.existsSync(src)) copy(src, dest)

  function copy (src, dest) {
    if (!fs.statSync(src).isDirectory()) {
      var relativeName = path.relative(path.join(argv.assets, '../'), src)
      log.debug(relativeName + ' started')
      return pump(fs.createReadStream(src), fs.createWriteStream(dest), function (err) {
        if (err) {
          log.error(relativeName + ' error')
          return done(err)
        }
        log.info(relativeName + ' done')
        done()
      })
    }
    if (!fs.existsSync(dest)) fs.mkdirSync(dest)
    var files = fs.readdirSync(src)
    for (var i = 0; i < files.length; i++) {
      copy(path.join(src, files[i]), path.join(dest, files[i]))
    }
  }
}

function inspect (entry, argv, done) {
  argv.watch = false
  argv.js = argv.js || {}
  argv.js.fullPaths = true

  var assets = bankai(entry, argv)
  var js = assets.js()
  var filename = tmp() + '.html'

  var ws = fs.createWriteStream(filename)
  var d = disc()
  pump(js, d, function (err) {
    if (err) return done(err)
  })

  pump(d, ws, function (err) {
    if (err) return done(err)
    log.info('Opening ' + filename)
    open(filename)
  })
}
<commit_msg>fix -v (#181)<commit_after>#!/usr/bin/env node

var hyperstream = require('hyperstream')
var fromString = require('from2-string')
var pinoColada = require('pino-colada')
var parallel = require('run-parallel')
var explain = require('explain-error')
var concat = require('concat-stream')
var mapLimit = require('map-limit')
var purify = require('purify-css')
var logHttp = require('log-http')
var uglify = require('uglify-js')
var resolve = require('resolve')
var mkdirp = require('mkdirp')
var subarg = require('subarg')
var tmp = require('temp-path')
var from = require('from2')
var disc = require('disc')
var http = require('http')
var open = require('open')
var path = require('path')
var pino = require('pino')
var pump = require('pump')
var zlib = require('zlib')
var fs = require('fs')

var htmlMinifyStream = require('./lib/html-minify-stream')
var zlibMaybe = require('./lib/gzip-maybe')
var Sse = require('./lib/sse')
var bankai = require('./')

var pretty = pinoColada()
pretty.pipe(process.stdout)

var argv = subarg(process.argv.slice(2), {
  string: [ 'open', 'port', 'assets' ],
  boolean: [ 'watch', 'verbose', 'help', 'version', 'debug', 'electron' ],
  default: {
    address: 'localhost',
    assets: 'assets',
    debug: false,
    open: false,
    port: 8080,
    uglify: true
  },
  alias: {
    address: 'A',
    assets: 'a',
    css: 'c',
    debug: 'd',
    electron: 'e',
    help: 'h',
    html: 'H',
    js: 'j',
    uglify: 'u',
    open: 'o',
    port: 'p',
    verbose: 'V',
    version: 'v',
    watch: 'w'
  }
})

var logLevel = argv.verbose ? 'debug' : 'info'
var log = pino({ name: 'bankai', level: logLevel }, pretty)

var usage = `
  Usage:
    $ bankai <command> [options]

  Commands:
    <default>                      Run 'bankai start'
    start <filename>               Start a bankai server
    build <filename> <directory>   Compile and export files to a directory
    inspect <filename>             Visualize the dependency tree

    Options:
      -a, --assets=<directory>  Serve static assets [default: assets]
      -A, --address=<ip>      Ip address to listen [default: localhost]
      -c, --css=<subargs>     Pass subarguments to sheetify
      -d, --debug             Include sourcemaps [default: false]
      -e, --electron          Enable electron mode for the bundler
      -h, --help              Print usage
      -H, --html=<subargs>    Pass subarguments to create-html
      -j, --js=<subargs>      Pass subarguments to browserify
      -o, --open=<browser>    Open html in a browser [default: system default]
      -p, --port=<n>          Bind bankai to a port [default: 8080]
      -V, --verbose           Include debug messages
      -w, --watch <bool>      Toggle watch mode
      -u, --uglify <bool>     Toggle uglifyify. [default: true]

  Examples:
    $ bankai index.js -p 8080            # start bankai on port 8080
    $ bankai index.js --open             # open html in the browser
    $ bankai -c [ -u sheetify-cssnext ]  # use cssnext in sheetify
    $ bankai -j [ -t brfs ]              # use brfs in browserify
    $ bankai build index.js dist/        # compile and export to dist/

  Notes:
    When specifying both --watch and --uglify using the long form, you must omit
    the = when specifying them to be turned off.

  Examples:
    bankai example.js --open=firefox-aurora -p 3000
    bankai example.js --uglify false -w false
`

main(argv)

function main (argv) {
  if ((argv._[0] !== 'build') && (argv._[0] !== 'start') && argv._[0] !== 'inspect') {
    argv._.unshift('start')
  }

  if (argv.h) {
    console.log(usage)
    return process.exit()
  } else if (argv.v) {
    console.log(require('./package.json').version)
    return process.exit()
  }

  var cmd = argv._[0]
  var _entry = argv._[1] || 'index.js'
  var localEntry = './' + _entry.replace(/^.\//, '')
  var entry = resolve.sync(localEntry, { basedir: process.cwd() })
  var outputDir = argv._[2] || 'dist'

  if (cmd === 'start') {
    start(entry, argv, handleError)
  } else if (cmd === 'build') {
    build(entry, outputDir, argv, handleError)
  } else if (cmd === 'inspect') {
    inspect(entry, argv, handleError)
  } else {
    log.error(usage)
    return process.exit(1)
  }

  function handleError (err) {
    if (err) log.error(err)
  }
}

function start (entry, argv, done) {
  log.debug('running command: start')
  argv.watch = true

  var assets = bankai(entry, argv)
  var staticAsset = new RegExp('/' + argv.assets)
  var address = argv.address
  var port = argv.port
  var sse = Sse(assets)

  assets.on('js-bundle', function () {
    log.info('bundle:js')
  })

  assets.on('css-bundle', function () {
    log.info('bundle:css')
  })

  var server = http.createServer(handler)
  server.listen(port, address, onlisten)

  var stats = logHttp(server)
  stats.on('data', function (level, data) {
    log[level](data)
  })

  function handler (req, res) {
    var url = req.url
    log.debug('received request on url: ' + url)
    if (url === '/') {
      assets.html(req, res).pipe(zlibMaybe(req, res)).pipe(res)
    } else if (url === '/sse') {
      sse(req, res)
    } else if (url === '/bundle.js') {
      assets.js(req, res).pipe(zlibMaybe(req, res)).pipe(res)
    } else if (url === '/bundle.css') {
      assets.css(req, res).pipe(zlibMaybe(req, res)).pipe(res)
    } else if (req.headers['accept'].indexOf('html') > 0) {
      assets.html(req, res).pipe(zlibMaybe(req, res)).pipe(res)
    } else if (staticAsset.test(url)) {
      assets.static(req).pipe(res)
    } else {
      res.writeHead(404, 'Not Found')
      res.end()
    }
  }

  function onlisten () {
    var relative = path.relative(process.cwd(), entry)
    var addr = 'http://' + address + ':' + port
    log.info('Started for ' + relative + ' on ' + addr)
    if (argv.open !== false) {
      var app = argv.open.length ? argv.open : ''
      open(addr, app, function (err) {
        if (err) return done(explain(err, `err running ${app}`))
        done()
      })
    }
  }
}

function build (entry, outputDir, argv, done) {
  log.debug('running command: build')

  // cast argv.watch to a boolean
  argv.watch = argv.watch === undefined ? false : argv.watch
  argv.assert = false

  mkdirp.sync(outputDir)
  buildStaticAssets(entry, outputDir, argv, done)

  var buffers = {}
  var assets = bankai(entry, argv)
  var files = ['index.html', 'bundle.js', 'bundle.css']

  mapLimit(files, Infinity, iterator, function (err) {
    if (err) return done(err)
    parallel([ buildHtml, buildJs, buildCss ], done)
  })

  function iterator (file, done) {
    var source = assets[file.replace(/^.*\./, '')]()
    log.debug(file + ' started')

    var sink = concat(function (buf) {
      buffers[file] = buf
    })
    pump(source, sink, done)
  }

  function buildHtml (done) {
    var file = 'index.html'
    var buf = buffers[file]
    var outfile = path.join(outputDir, file)

    var sink = fs.createWriteStream(outfile)
    var source = hyperstream()
    source.end(buf)

    pump(source, htmlMinifyStream(), sink, done)
    printSize(buf, outfile, function (err) {
      if (err) return done(err)
    })
  }

  function buildCss (done) {
    var css = buffers['bundle.css'].toString()
    var js = buffers['bundle.js'].toString()
    css = purify(js, css, { minify: true })

    var outfile = path.join(outputDir, 'bundle.css')
    var sink = fs.createWriteStream(outfile)
    var source = fromString(css)

    pump(source, sink, done)
    printSize(Buffer.from(css), outfile, function (err) {
      if (err) return done(err)
    })
  }

  function buildJs (done) {
    var file = 'bundle.js'
    var buf = buffers[file]
    var js = buf.toString()

    // FIXME argv.uglify should always be a bool
    if (argv.uglify !== false && argv.uglify !== 'false') {
      log.debug('uglify starting')
      js = uglify.minify(js, {
        fromString: true,
        compress: true,
        mangle: true,
        filename: file,
        sourceMaps: false
      })
      log.debug('uglify finished')
      buf = Buffer.from(js.code)
    }

    var outfile = path.join(outputDir, 'bundle.js')
    log.debug('writing to file ' + outfile)
    var sink = fs.createWriteStream(outfile)
    var source = from([buf])

    pump(source, sink, done)
    printSize(buf, outfile, function (err) {
      if (err) return done(err)
    })
  }
}

function printSize (buf, outfile, done) {
  zlib.deflate(buf, function (err, buf) {
    if (err) return done(err)
    var length = buf.length
    var location = path.relative(process.cwd(), outfile)
    // Warn if serving up more than 60kb in {html,css,js}
    var level = buf.length < 60000 ? 'info' : 'warn'
    var msg = level === 'warn' ? location + ' (large)' : location
    log[level]({
      message: msg,
      contentLength: length
    })
  })
}

function buildStaticAssets (entry, outputDir, argv, done) {
  var src = path.join(path.dirname(entry), argv.assets)
  var dest = path.join(path.dirname(entry), outputDir, argv.assets)
  if (fs.existsSync(src)) copy(src, dest)

  function copy (src, dest) {
    if (!fs.statSync(src).isDirectory()) {
      var relativeName = path.relative(path.join(argv.assets, '../'), src)
      log.debug(relativeName + ' started')
      return pump(fs.createReadStream(src), fs.createWriteStream(dest), function (err) {
        if (err) {
          log.error(relativeName + ' error')
          return done(err)
        }
        log.info(relativeName + ' done')
        done()
      })
    }
    if (!fs.existsSync(dest)) fs.mkdirSync(dest)
    var files = fs.readdirSync(src)
    for (var i = 0; i < files.length; i++) {
      copy(path.join(src, files[i]), path.join(dest, files[i]))
    }
  }
}

function inspect (entry, argv, done) {
  argv.watch = false
  argv.js = argv.js || {}
  argv.js.fullPaths = true

  var assets = bankai(entry, argv)
  var js = assets.js()
  var filename = tmp() + '.html'

  var ws = fs.createWriteStream(filename)
  var d = disc()
  pump(js, d, function (err) {
    if (err) return done(err)
  })

  pump(d, ws, function (err) {
    if (err) return done(err)
    log.info('Opening ' + filename)
    open(filename)
  })
}
<|endoftext|>


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

const info = require( "./index" );
const colors = require("colors");
const nconf = require("nconf");
const log = require("./helpers").log;

nconf.argv({
	verbose: {
		alias: "v",
		type: "boolean"
	},
	excludePaths: {
		type: "array"
	},
	depth: {
		alias: "d"
	},
	afterDot: {
		type: "number"
	}
}).env({
	verbose: /^verbose$/i,
	excludePaths: /^exclude_paths$/i,
	depth: /^depth$/i,
	afterDot: /^after_dot$/i
}).defaults({
	verbose: true,
	excludePaths: [],
	depth: Infinity,
	afterDot: 2
});
/*
console.log(nconf.get("verbose"), nconf.get("excludePaths"), nconf.get("depth"), nconf.get("afterDot"))

process.exit(0)
*/
let targetpath = process.argv[ process.argv.length -1 ];

put(
	info( targetpath, null, nconf.get("depth"),
				nconf.get("excludePaths"), nconf.get("verbose") ));

function put( info ) {
	let totalSize = 0;
	let exts = Object.keys( info.exts )

	log( colors.black.bold("---------------") );
	for ( const key of exts ) {
		const ext = info.exts[ key ];
		const size = ext.size;
		totalSize += size;
		log( `${colors.blue(key)} ${colors.magenta(ext.fileCount)} ${colors.magenta(byteToHuman( size, nconf.get("afterDot")))}` );
	}

	totalSize = byteToHuman( totalSize, nconf.get("afterDot"));
	log( colors.black.bold("---------------") );
	log( colors.green(`found ${info.fileCount} files, ${totalSize}`) );

	return void ( 0 );
}

function byteToHuman( bytes, afterDot ) {
	bytes = +bytes;

	let units = [ "b", "kb", "mb", "gb", "tb", "?", "??", "???", "????" ];
	let count,
		dotInd;

	for ( count = 0; bytes > 1024; bytes = bytes / 1024, count++ ) ;

	bytes = String( bytes );
	dotInd = bytes.indexOf( "." );

	if ( ~~dotInd ) bytes = bytes.slice( 0, dotInd + afterDot +1 );

	return "" + bytes + units[ count ];
}
<commit_msg>align output cols<commit_after>#!/usr/bin/env node
"use strict";

const info = require( "./index" );
const colors = require("colors");
const nconf = require("nconf");
const log = require("./helpers").log;

nconf.argv({
	verbose: {
		alias: "v",
		type: "boolean"
	},
	excludePaths: {
		type: "array"
	},
	depth: {
		alias: "d"
	},
	afterDot: {
		type: "number"
	}
}).env({
	verbose: /^verbose$/i,
	excludePaths: /^exclude_paths$/i,
	depth: /^depth$/i,
	afterDot: /^after_dot$/i
}).defaults({
	verbose: true,
	excludePaths: [],
	depth: Infinity,
	afterDot: 2
});

let targetpath = process.argv[ process.argv.length -1 ];

put(
	info( targetpath, null, nconf.get("depth"),
				nconf.get("excludePaths"), nconf.get("verbose") ));

function put( info ) {
	let totalSize = 0;
	let exts = Object.keys( info.exts );
	let out = [];
	let colSize = [-Infinity, -Infinity, -Infinity];
	let wSpace = " ";
	let colColors = [];
	let outInd = 0;

	colColors[0] = colors.blue.bind(colors);
	colColors[1] = colors.magenta.bind(colors);
	colColors[2] = colors.magenta.bind(colors);

	log( colors.black.bold("---------------") );
	for ( const key of exts ) {
		const ext = info.exts[ key ];
		const size = ext.size;
		const o = out[outInd++] = [];
		const byteHuman = byteToHuman(size, nconf.get("afterDot"))

		// override max size if found
		colSize[0] = Math.max(colSize[0], ("" + key).length);
		o.push(key + "");
		colSize[1] = Math.max(colSize[1], ("" + ext.fileCount).length);
		o.push(ext.fileCount);
		colSize[2] = Math.max(colSize[2], byteHuman.length);
		o.push(byteHuman);
		totalSize += size;
		// log( `${colors.blue(key)} ${colors.magenta(ext.fileCount)} ${colors.magenta(byteToHuman( size, nconf.get("afterDot")))}` );
	}

	for (const o of out) {
		let line = [],
				whole = "";
		for (const ind in o) {
			if (!o.hasOwnProperty(ind)) continue;
			let oo = String(o[ind]);
			let clearance = colSize[ind] - oo.length;
			line[ind] = String(oo);
			while (clearance--) line[ind] +=  wSpace;
			line[ind] = colColors[ind](line[ind]);
		}
		whole = line.join(wSpace);
		log(whole);
	}

	totalSize = byteToHuman( totalSize, nconf.get("afterDot"));
	log( colors.black.bold("---------------") );
	log( colors.green(`found ${info.fileCount} files, ${totalSize}`) );

	return void ( 0 );
}

function byteToHuman( bytes, afterDot ) {
	bytes = +bytes;

	let units = [ "b", "kb", "mb", "gb", "tb", "?", "??", "???", "????" ];
	let count,
		dotInd;

	for ( count = 0; bytes > 1024; bytes = bytes / 1024, count++ ) ;

	bytes = String( bytes );
	dotInd = bytes.indexOf( "." );

	if ( ~~dotInd ) bytes = bytes.slice( 0, dotInd + afterDot +1 );

	return "" + bytes + units[ count ];
}
<|endoftext|>


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

var tar = require('tar-fs')
var gunzip = require('gunzip-maybe')
var request = require('request')
var minimist = require('minimist')
var format = require('streaming-format')
var read = require('read')
var fs = require('fs')
var path = require('path')

var CONFIG = path.join(process.env.HOME || process.env.USERPROFILE, '.config/create-project.json')

var conf = fs.existsSync(CONFIG) ? require(CONFIG) : {}
var argv = minimist(process.argv.slice(2), {alias:{configure:'c'}, boolean:'c'})

var dir = argv._[0]
var repo = argv._[1]
var name = dir && path.basename(dir)

var parse = function(str) {
  var branch = str.split('#')[1] || 'master'
  var parts = str.split('#')[0].split(/[:\/]/)

  if (parts.length < 2) return null

  return {
    user: parts[0],
    repo: parts[1],
    branch: branch
  }
}

if (argv.configure) {
  var defaults = conf.defaults || {}
  var keys = Object.keys(defaults)

  read({
    prompt: 'Set repository: ',
    default: conf.github && conf.github.user+'/'+conf.github.repo+'#'+conf.github.branch
  }, function(err, repo) {
    if (err) return

    if (!repo) {
      console.error('Repository is required')
      process.exit(1)
      return
    }

    repo = parse(repo)

    if (!repo) {
      console.error('Repository is malformed (should be user/repo(#branch)?)')
      process.exit(2)
      return
    }

    conf.github = repo
    conf.defaults = {}

    var store = function() {
      try {
        fs.mkdirSync(path.dirname(CONFIG))
      } catch (err) {
        // do nothing
      }
      fs.writeFileSync(CONFIG, JSON.stringify(conf, null, 2))
    }

    var loop = function() {
      read({
        prompt: 'Set key=value: ',
        default: keys.length ? keys[0]+'='+defaults[keys[0]] : 'blank to skip'
      }, function(err, def) {
        if (err) return
        if (def === 'blank to skip' || !def.trim()) return store()

        keys.shift()
        def = def.trim().split(/\s*=\s*/)

        var k = def[0].trim() || oldK
        var v = (def[1] || '').trim()

        if (v) conf.defaults[k] = v
        else delete conf.defaults[k]

        loop()
      })
    }

    loop()
  })
  return
}

var usage = function() {
  var def = conf.github ? conf.github.user+'/'+conf.github.repo+'#'+conf.github.branch : 'user/repo#branch'

  console.error('create-project [name] [%s]', def)
  console.error('')
  console.error('  --configure,-c  to set default repo/parameters')
  console.error('  --[key]=[val]   to pass format parameters')
  console.error('')

  var keys = Object.keys(conf.defaults || {})

  if (keys.length) {
    console.error('Default parameters are:')
    console.error()
    keys.forEach(function(key) {
      console.log('  %s=%s', key, conf.defaults[key])
    })
    console.error('')
  }

  process.exit(1)
}

var gzipStream, gzipSrc;

var failedHttp = function(response) {
  if (response.statusCode !== 200) {
    console.log('Fetch failed! Status code: '+response.statusCode)
    process.exit(4)
  }
}

if (argv.file) {
  gzipSrc = argv.file;
  gzipStream = fs.createReadStream(argv.file);
}
else if (argv.url) {
  gzipSrc = argv.url;
  gzipStream = request(argv.url)
  gzipStream.on('response', failedHttp)
} else {
  if (repo && repo.indexOf('/') === -1 && conf.github) repo = conf.github.user+'/'+conf.github.repo+'#'+repo

  if (repo) repo = parse(repo)
  else if (conf.github) repo = conf.github

  if (!repo || !name) return usage()

  gzipSrc = repo.user+'/'+repo.repo+'#'+repo.branch
  gzipStream = request('https://github.com/'+repo.user+'/'+repo.repo+'/archive/'+repo.branch+'.tar.gz')
  gzipStream.on('response', failedHttp)
}

console.log('Creating new project %s from %s', name, gzipSrc)

var formatter = function(stream) {
  var def = conf.defaults || {}
  def.name = name

  return stream.pipe(format(function(name) {
    return argv[name] || def[name] || '{{'+name+'}}'
  }))
}

gzipStream
  .pipe(gunzip())
  .pipe(tar.extract(name, {strip:1, mapStream:formatter}))
  .on('finish', function() {
    console.log('Project created in %s', path.resolve(dir))
  })<commit_msg>support urls/git-urls as well<commit_after>#!/usr/bin/env node

var tar = require('tar-fs')
var gunzip = require('gunzip-maybe')
var request = require('request')
var minimist = require('minimist')
var format = require('streaming-format')
var read = require('read')
var fs = require('fs')
var path = require('path')

var CONFIG = path.join(process.env.HOME || process.env.USERPROFILE, '.config/create-project.json')

var conf = fs.existsSync(CONFIG) ? require(CONFIG) : {}
var argv = minimist(process.argv.slice(2), {alias:{configure:'c'}, boolean:'c'})

var dir = argv._[0]
var repo = argv._[1]
var name = dir && path.basename(dir)

var parse = function(str) {
  var branch = str.split('#')[1] || 'master'
  var parts = str.split('#')[0].replace(/\.git$/, '').split(/[:\/]/)

  if (parts.length < 2) return null

  var repo = parts.pop()
  var user = parts.pop()

  return {
    user: user,
    repo: repo,
    branch: branch
  }
}

if (argv.configure) {
  var defaults = conf.defaults || {}
  var keys = Object.keys(defaults)

  read({
    prompt: 'Set repository: ',
    default: conf.github && conf.github.user+'/'+conf.github.repo+'#'+conf.github.branch
  }, function(err, repo) {
    if (err) return

    if (!repo) {
      console.error('Repository is required')
      process.exit(1)
      return
    }

    repo = parse(repo)

    if (!repo) {
      console.error('Repository is malformed (should be user/repo(#branch)?)')
      process.exit(2)
      return
    }

    conf.github = repo
    conf.defaults = {}

    var store = function() {
      try {
        fs.mkdirSync(path.dirname(CONFIG))
      } catch (err) {
        // do nothing
      }
      fs.writeFileSync(CONFIG, JSON.stringify(conf, null, 2))
    }

    var loop = function() {
      read({
        prompt: 'Set key=value: ',
        default: keys.length ? keys[0]+'='+defaults[keys[0]] : 'blank to skip'
      }, function(err, def) {
        if (err) return
        if (def === 'blank to skip' || !def.trim()) return store()

        keys.shift()
        def = def.trim().split(/\s*=\s*/)

        var k = def[0].trim() || oldK
        var v = (def[1] || '').trim()

        if (v) conf.defaults[k] = v
        else delete conf.defaults[k]

        loop()
      })
    }

    loop()
  })
  return
}

var usage = function() {
  var def = conf.github ? conf.github.user+'/'+conf.github.repo+'#'+conf.github.branch : 'user/repo#branch'

  console.error('create-project [name] [%s]', def)
  console.error('')
  console.error('  --configure,-c  to set default repo/parameters')
  console.error('  --[key]=[val]   to pass format parameters')
  console.error('')

  var keys = Object.keys(conf.defaults || {})

  if (keys.length) {
    console.error('Default parameters are:')
    console.error()
    keys.forEach(function(key) {
      console.log('  %s=%s', key, conf.defaults[key])
    })
    console.error('')
  }

  process.exit(1)
}

var gzipStream, gzipSrc;

var failedHttp = function(response) {
  if (response.statusCode !== 200) {
    console.log('Fetch failed! Status code: '+response.statusCode)
    process.exit(4)
  }
}

if (argv.file) {
  gzipSrc = argv.file;
  gzipStream = fs.createReadStream(argv.file);
}
else if (argv.url) {
  gzipSrc = argv.url;
  gzipStream = request(argv.url)
  gzipStream.on('response', failedHttp)
} else {
  if (repo && repo.indexOf('/') === -1 && conf.github) repo = conf.github.user+'/'+conf.github.repo+'#'+repo

  if (repo) repo = parse(repo)
  else if (conf.github) repo = conf.github

  if (!repo || !name) return usage()

  gzipSrc = repo.user+'/'+repo.repo+'#'+repo.branch
  gzipStream = request('https://github.com/'+repo.user+'/'+repo.repo+'/archive/'+repo.branch+'.tar.gz')
  gzipStream.on('response', failedHttp)
}

console.log('Creating new project %s from %s', name, gzipSrc)

var formatter = function(stream) {
  var def = conf.defaults || {}
  def.name = name

  return stream.pipe(format(function(name) {
    return argv[name] || def[name] || '{{'+name+'}}'
  }))
}

gzipStream
  .pipe(gunzip())
  .pipe(tar.extract(name, {strip:1, mapStream:formatter}))
  .on('finish', function() {
    console.log('Project created in %s', path.resolve(dir))
  })<|endoftext|>


<commit_before>/****************************************************
* /path     a/checkout/:id/:person/:qty
* /params   id
*           person
*           qty
* /brief    Route to remove some :qty from inventory
*
* /author   Luke
****************************************************/
module.exports = (req, res) =>{

  // If the value to checkin is negative
  if (req.params.qty < 0) {
    // Respond with forbidden (403) status
    res.status(403);
    res.jsonp("ERROR: You cannot checkout a negative value. Operation canceled.");

  } else {
    res.app.locals.helpers.transaction(req.params.id, req.params.person, -req.params.qty,
      req.app.locals.helpers.errResultHandler, res);

      res.app.locals.helpers.doThresholdCheck(req.params.id, req.app.locals.helpers.errResultHandler, res);
  }
};
<commit_msg>threshold call check<commit_after>/****************************************************
* /path     a/checkout/:id/:person/:qty
* /params   id
*           person
*           qty
* /brief    Route to remove some :qty from inventory
*
* /author   Luke
****************************************************/
module.exports = (req, res) =>{

  // If the value to checkin is negative
  if (req.params.qty < 0) {
    // Respond with forbidden (403) status
    res.status(403);
    res.jsonp("ERROR: You cannot checkout a negative value. Operation canceled.");

  } else {
    res.app.locals.helpers.transaction(req.params.id, req.params.person, -req.params.qty,
      req.app.locals.helpers.errResultHandler, res);

      res.app.locals.helpers.doThresholdCheck(req.params.id, req.app.locals.helpers.errResultHandler, res);

      //pushing changes up to github, committing
  }
};
<|endoftext|>


<commit_before>/* jshint -W117 */
'use strict';

var JSM = require('jingle');
var RTC = require('webrtc-adapter-test');
var jxt = require('jxt').createRegistry();

jxt.use(require('./stanza/iq.js'));
jxt.use(require('./stanza/jingle.js'));
jxt.use(require('./stanza/rtp.js'));
jxt.use(require('./stanza/iceUdp.js'));

(function($) {
   Strophe.addConnectionPlugin('jingle', {
      connection: null,
      peer_constraints: {},
      AUTOACCEPT: false,
      localStream: null,
      manager: null,
      RTC: null,

      init: function(conn) {
         var self = this;

         self.RTC = RTC;

         self.connection = conn;

         if ((RTC.webrtcDetectedVersion < 33 && RTC.webrtcDetectedBrowser === 'firefox') || RTC.webrtcDetectedBrowser === 'chrome') {
            self.peer_constraints = {
               mandatory: {
                  'OfferToReceiveAudio': true,
                  'OfferToReceiveVideo': true
               }
            };

            if (RTC.webrtcDetectedBrowser === 'firefox') {
               self.peer_constraints.mandatory.MozDontOfferDataChannel = true;
            }
         } else {
            self.peer_constraints = {
               'offerToReceiveAudio': true,
               'offerToReceiveVideo': true
            };

            if (RTC.webrtcDetectedBrowser === 'firefox') {
               self.peer_constraints.mozDontOfferDataChannel = true;
            }
         }

         self.manager = new JSM({
            peerConnectionConstraints: self.peer_constraints,
            jid: self.connection.jid,
            selfID: self.connection.jid
         });

         var IqStanza = jxt.getDefinition('iq', 'jabber:client');
         var JingleStanza = jxt.getDefinition('jingle', 'urn:xmpp:jingle:1');

         jxt.extend(IqStanza, JingleStanza);

         var events = {
            'incoming': 'callincoming.jingle',
            'terminated': 'callterminated.jingle',
            'peerStreamAdded': 'remotestreamadded.jingle',
            'peerStreamRemoved': 'remotestreamremoved.jingle',
            'ringing': 'ringing.jingle',
            'log:error': 'error.jingle'
         };

         $.each(events, function(key, val) {
            self.manager.on(key, function() {
               $(document).trigger(val, arguments);
            });
         });

         self.manager.on('incoming', function(session) {
            session.on('change:connectionState', function(session, state) {
               $(document).trigger('iceconnectionstatechange.jingle', [session.sid, session, state]);
            });
         });

         if (this.connection.disco) {
            // http://xmpp.org/extensions/xep-0167.html#support
            // http://xmpp.org/extensions/xep-0176.html#support
            this.connection.disco.addFeature('urn:xmpp:jingle:1');
            this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:1');
            this.connection.disco.addFeature('urn:xmpp:jingle:transports:ice-udp:1');
            this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:audio');
            this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:video');

            // this is dealt with by SDP O/A so we don't need to annouce this
            //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtcp-fb:0'); // XEP-0293
            //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtp-hdrext:0'); // XEP-0294
            this.connection.disco.addFeature('urn:ietf:rfc:5761'); // rtcp-mux
            //this.connection.disco.addFeature('urn:ietf:rfc:5888'); // a=group, e.g. bundle
            //this.connection.disco.addFeature('urn:ietf:rfc:5576'); // a=ssrc
         }
         this.connection.addHandler(this.onJingle.bind(this), 'urn:xmpp:jingle:1', 'iq', 'set', null, null);

         this.manager.on('send', function(data) {

            var iq = new IqStanza(data);

            self.connection.send($.parseXML(iq.toString()).getElementsByTagName('iq')[0]);
         });

         //@TODO add on client unavilable (this.manager.endPeerSessions(peer_jid_full, true))
      },
      onJingle: function(iq) {
         var req = jxt.parse(iq.outerHTML);

         this.manager.process(req);

         return true;
      },
      initiate: function(peerjid, stream) { // initiate a new jinglesession to peerjid
         var session = this.manager.createMediaSession(peerjid);

         session.on('change:connectionState', function(session, state) {
            $(document).trigger('iceconnectionstatechange.jingle', [session.sid, session, state]);
         });

         if (stream) {
            this.localStream = stream;
         }

         // configure session
         if (this.localStream) {
            session.addStream(this.localStream);
            session.start();

            return session;
         }

         console.error('No local stream defined');
      },
      terminate: function(jid, reason, silent) { // terminate by sessionid (or all sessions)
         if (typeof jid === 'undefined' || jid === null) {
            this.manager.endAllSessions(reason, silent);
         } else {
            this.manager.endPeerSessions(jid, reason, silent);
         }
      },
      terminateByJid: function(jid) {
         this.manager.endPeerSessions(jid);
      },
      addICEServer: function(server) {
         this.manager.addICEServer(server);
      },
      setICEServers: function(servers) {
         //this.manager.iceServers = servers;
      },
      setPeerConstraints: function(constraints) {
         this.manager.config.peerConnectionConstraints = constraints;
      }
   });
}(jQuery));
<commit_msg>announce jingle.js capabilities<commit_after>/* jshint -W117 */
'use strict';

var JSM = require('jingle');
var RTC = require('webrtc-adapter-test');
var jxt = require('jxt').createRegistry();

jxt.use(require('./stanza/iq.js'));
jxt.use(require('./stanza/jingle.js'));
jxt.use(require('./stanza/rtp.js'));
jxt.use(require('./stanza/iceUdp.js'));

(function($) {
   Strophe.addConnectionPlugin('jingle', {
      connection: null,
      peer_constraints: {},
      AUTOACCEPT: false,
      localStream: null,
      manager: null,
      RTC: null,

      init: function(conn) {
         var self = this;

         self.RTC = RTC;

         self.connection = conn;

         if ((RTC.webrtcDetectedVersion < 33 && RTC.webrtcDetectedBrowser === 'firefox') || RTC.webrtcDetectedBrowser === 'chrome') {
            self.peer_constraints = {
               mandatory: {
                  'OfferToReceiveAudio': true,
                  'OfferToReceiveVideo': true
               }
            };

            if (RTC.webrtcDetectedBrowser === 'firefox') {
               self.peer_constraints.mandatory.MozDontOfferDataChannel = true;
            }
         } else {
            self.peer_constraints = {
               'offerToReceiveAudio': true,
               'offerToReceiveVideo': true
            };

            if (RTC.webrtcDetectedBrowser === 'firefox') {
               self.peer_constraints.mozDontOfferDataChannel = true;
            }
         }

         self.manager = new JSM({
            peerConnectionConstraints: self.peer_constraints,
            jid: self.connection.jid,
            selfID: self.connection.jid
         });

         var IqStanza = jxt.getDefinition('iq', 'jabber:client');
         var JingleStanza = jxt.getDefinition('jingle', 'urn:xmpp:jingle:1');

         jxt.extend(IqStanza, JingleStanza);

         var events = {
            'incoming': 'callincoming.jingle',
            'terminated': 'callterminated.jingle',
            'peerStreamAdded': 'remotestreamadded.jingle',
            'peerStreamRemoved': 'remotestreamremoved.jingle',
            'ringing': 'ringing.jingle',
            'log:error': 'error.jingle'
         };

         $.each(events, function(key, val) {
            self.manager.on(key, function() {
               $(document).trigger(val, arguments);
            });
         });

         self.manager.on('incoming', function(session) {
            session.on('change:connectionState', function(session, state) {
               $(document).trigger('iceconnectionstatechange.jingle', [session.sid, session, state]);
            });
         });

         if (this.connection.disco) {
            var i;
            for (i = 0; i < self.manager.capabilities.length; i++) {
               self.connection.disco.addFeature(self.manager.capabilities[i]);
            }
         }
         this.connection.addHandler(this.onJingle.bind(this), 'urn:xmpp:jingle:1', 'iq', 'set', null, null);

         this.manager.on('send', function(data) {

            var iq = new IqStanza(data);

            self.connection.send($.parseXML(iq.toString()).getElementsByTagName('iq')[0]);
         });

         //@TODO add on client unavilable (this.manager.endPeerSessions(peer_jid_full, true))
      },
      onJingle: function(iq) {
         var req = jxt.parse(iq.outerHTML);

         this.manager.process(req);

         return true;
      },
      initiate: function(peerjid, stream) { // initiate a new jinglesession to peerjid
         var session = this.manager.createMediaSession(peerjid);

         session.on('change:connectionState', function(session, state) {
            $(document).trigger('iceconnectionstatechange.jingle', [session.sid, session, state]);
         });

         if (stream) {
            this.localStream = stream;
         }

         // configure session
         if (this.localStream) {
            session.addStream(this.localStream);
            session.start();

            return session;
         }

         console.error('No local stream defined');
      },
      terminate: function(jid, reason, silent) { // terminate by sessionid (or all sessions)
         if (typeof jid === 'undefined' || jid === null) {
            this.manager.endAllSessions(reason, silent);
         } else {
            this.manager.endPeerSessions(jid, reason, silent);
         }
      },
      terminateByJid: function(jid) {
         this.manager.endPeerSessions(jid);
      },
      addICEServer: function(server) {
         this.manager.addICEServer(server);
      },
      setICEServers: function(servers) {
         this.manager.iceServers = servers;
      },
      setPeerConstraints: function(constraints) {
         this.manager.config.peerConnectionConstraints = constraints;
      }
   });
}(jQuery));
<|endoftext|>


<commit_before>import vtkFullScreenRenderWindow from '../../../Sources/Testing/FullScreenRenderWindow';

import vtkActor           from '../../../Sources/Rendering/Core/Actor';
import vtkCalculator      from '../../../Sources/Filters/General/Calculator';
import vtkConeSource      from '../../../Sources/Filters/Sources/ConeSource';
import vtkDataArray       from '../../../Sources/Common/Core/DataArray';
import vtkMapper          from '../../../Sources/Rendering/Core/Mapper';
import vtkPolyData        from '../../../Sources/Common/DataModel/PolyData';
import { AttributeTypes } from '../../../Sources/Common/DataModel/DataSetAttributes/Constants';
import { FieldDataTypes } from '../../../Sources/Common/DataModel/DataSet/Constants';

import controlPanel from './controller.html';

// ----------------------------------------------------------------------------
// Standard rendering code setup
// ----------------------------------------------------------------------------

const fullScreenRenderer = vtkFullScreenRenderWindow.newInstance();
const renderer = fullScreenRenderer.getRenderer();
const renderWindow = fullScreenRenderer.getRenderWindow();

// ----------------------------------------------------------------------------
// Example code
// ----------------------------------------------------------------------------
// create a filter on the fly, sort of cool, this is a random scalars
// filter we create inline, for a simple cone you would not need
// this
// ----------------------------------------------------------------------------

const coneSource = vtkConeSource.newInstance({ height: 1.0 });
const filter = vtkCalculator.newInstance();

filter.setInputConnection(coneSource.getOutputPort());
// filter.setFormulaSimple(FieldDataTypes.CELL, [], 'random', () => Math.random());
filter.setFormula({
  getArrays: inputDataSets => ({
    input: [],
    output: [
      { location: FieldDataTypes.CELL, name: 'Random', dataType: 'Float32Array', attribute: AttributeTypes.SCALARS },
    ],
  }),
  evaluate: (arraysIn, arraysOut) => {
    const [scalars] = arraysOut.map(d => d.getData());
    for (let i = 0; i < scalars.length; i++) {
      scalars[i] = Math.random();
    }
  },
});

const mapper = vtkMapper.newInstance();
mapper.setInputConnection(filter.getOutputPort());

const actor = vtkActor.newInstance();
actor.setMapper(mapper);

renderer.addActor(actor);
renderer.resetCamera();
renderWindow.render();

// -----------------------------------------------------------
// UI control handling
// -----------------------------------------------------------

fullScreenRenderer.addController(controlPanel);
const representationSelector = document.querySelector('.representations');
const resolutionChange = document.querySelector('.resolution');

representationSelector.addEventListener('change', (e) => {
  const newRepValue = Number(e.target.value);
  actor.getProperty().setRepresentation(newRepValue);
  renderWindow.render();
});

resolutionChange.addEventListener('input', (e) => {
  const resolution = Number(e.target.value);
  coneSource.setResolution(resolution);
  renderWindow.render();
});

// Make some variables global so that you can inspect and
// modify objects in your browser's developer console:
global.source = coneSource;
global.mapper = mapper;
global.actor = actor;
<commit_msg>fix(ConeExample): Remove unused import and set background to black<commit_after>import vtkFullScreenRenderWindow from '../../../Sources/Testing/FullScreenRenderWindow';

import vtkActor           from '../../../Sources/Rendering/Core/Actor';
import vtkCalculator      from '../../../Sources/Filters/General/Calculator';
import vtkConeSource      from '../../../Sources/Filters/Sources/ConeSource';
import vtkMapper          from '../../../Sources/Rendering/Core/Mapper';
import { AttributeTypes } from '../../../Sources/Common/DataModel/DataSetAttributes/Constants';
import { FieldDataTypes } from '../../../Sources/Common/DataModel/DataSet/Constants';

import controlPanel from './controller.html';

// ----------------------------------------------------------------------------
// Standard rendering code setup
// ----------------------------------------------------------------------------

const fullScreenRenderer = vtkFullScreenRenderWindow.newInstance({ background: [0, 0, 0] });
const renderer = fullScreenRenderer.getRenderer();
const renderWindow = fullScreenRenderer.getRenderWindow();

// ----------------------------------------------------------------------------
// Example code
// ----------------------------------------------------------------------------
// create a filter on the fly, sort of cool, this is a random scalars
// filter we create inline, for a simple cone you would not need
// this
// ----------------------------------------------------------------------------

const coneSource = vtkConeSource.newInstance({ height: 1.0 });
const filter = vtkCalculator.newInstance();

filter.setInputConnection(coneSource.getOutputPort());
// filter.setFormulaSimple(FieldDataTypes.CELL, [], 'random', () => Math.random());
filter.setFormula({
  getArrays: inputDataSets => ({
    input: [],
    output: [
      { location: FieldDataTypes.CELL, name: 'Random', dataType: 'Float32Array', attribute: AttributeTypes.SCALARS },
    ],
  }),
  evaluate: (arraysIn, arraysOut) => {
    const [scalars] = arraysOut.map(d => d.getData());
    for (let i = 0; i < scalars.length; i++) {
      scalars[i] = Math.random();
    }
  },
});

const mapper = vtkMapper.newInstance();
mapper.setInputConnection(filter.getOutputPort());

const actor = vtkActor.newInstance();
actor.setMapper(mapper);

renderer.addActor(actor);
renderer.resetCamera();
renderWindow.render();

// -----------------------------------------------------------
// UI control handling
// -----------------------------------------------------------

fullScreenRenderer.addController(controlPanel);
const representationSelector = document.querySelector('.representations');
const resolutionChange = document.querySelector('.resolution');

representationSelector.addEventListener('change', (e) => {
  const newRepValue = Number(e.target.value);
  actor.getProperty().setRepresentation(newRepValue);
  renderWindow.render();
});

resolutionChange.addEventListener('input', (e) => {
  const resolution = Number(e.target.value);
  coneSource.setResolution(resolution);
  renderWindow.render();
});

// Make some variables global so that you can inspect and
// modify objects in your browser's developer console:
global.source = coneSource;
global.mapper = mapper;
global.actor = actor;
<|endoftext|>


<commit_before>// GPS 1.2 - JavaScript

// YOUR FULL NAMES:
//  1.Anthony Ferragano
//  2.Mack MacLean

// 0. "YOU SIGNED... WHO?!"

// person with attributes of name ag and quote

// 1. "Here they Come!"

var adamSandler = {
  name: "Adam Sandler",
  age: 47,
  quote: "That's your home!"
};

var kristenBell = {
  name: "Kristin Bell",
  age: 33,
  quote: "Do you want to build a snowman?"
};

var jimCarrey = {
  name: "Jim Carrey",
  age: 52,
  quote: "...So you're telling me there's a chance? YEAH!"
};

// 2. "TIME IS MONEY!"

function Client(age,name,quote) {
	this.name = age,
	this.age = name,
	this.quote = quote
};

//YOUR CODE HERE!

var shooterMcGavin = new Client("Shooter McGavin", 48, "Just stay out of my way... or you'll pay. Listen to what I say.");
shooterMcGavin.constructor === Client;
shooterMcGavin.age === 48;
shooterMcGavin.quote === "Just stay out of my way... or you'll pay. Listen to what I say.";

// 3. "SHOW 'EM OFF!"
var clientsList = [adamSandler, kristenBell, jimCarrey]
clientsList.push(shooterMcGavin);

function displayinfo () {
	for (i = 0; i < clientsList.length; i++)
    console.log ("The client's name is " + clientsList[i].name + ", and is " + clientsList[i].age + " years old. Their quote is '"+ clientsList[i].quote+ "'")
}

console.log (displayinfo(clientsList));

// 4. "But wait, there's more!"

function showQuote() { for (i = 0; i < clientsList.length; i++)
    console.log ("This person's famous quote is '"+ clientsList[i].quote+ "'")
}

showQuote()

// 5.  ** BONUS **
// not advanced enough for this at this time, but will figure it out soon.

//  6.  Your Reflection:
This was a difficult challenge. I wish we had more time in the GPS to
accomplish the objectives with the guidance of the instructor.
There was a lot of sidetracking during the session, which may have been
necessary but maybe too extensive. I would have liked to continue working
right after the hour session with my partner... or maybe after a short break,
however, he had previous engagements. We were not able to pair online together
again after the GPS session, which was detrimental to both of our experiences.
I used quite a few resources to get through the challenge on my own.
I feel very accomplished that I was able to complete this to the best of my
ability. (I hope I did everything correctly.)

<commit_msg>//the comments<commit_after>// GPS 1.2 - JavaScript

// YOUR FULL NAMES:
//  1.Anthony Ferragano
//  2.Mack MacLean

// 0. "YOU SIGNED... WHO?!"

// person with attributes of name ag and quote

// 1. "Here they Come!"

var adamSandler = {
  name: "Adam Sandler",
  age: 47,
  quote: "That's your home!"
};

var kristenBell = {
  name: "Kristin Bell",
  age: 33,
  quote: "Do you want to build a snowman?"
};

var jimCarrey = {
  name: "Jim Carrey",
  age: 52,
  quote: "...So you're telling me there's a chance? YEAH!"
};

// 2. "TIME IS MONEY!"

function Client(age,name,quote) {
	this.name = age,
	this.age = name,
	this.quote = quote
};

//YOUR CODE HERE!

var shooterMcGavin = new Client("Shooter McGavin", 48, "Just stay out of my way... or you'll pay. Listen to what I say.");
shooterMcGavin.constructor === Client;
shooterMcGavin.age === 48;
shooterMcGavin.quote === "Just stay out of my way... or you'll pay. Listen to what I say.";

// 3. "SHOW 'EM OFF!"
var clientsList = [adamSandler, kristenBell, jimCarrey]
clientsList.push(shooterMcGavin);

function displayinfo () {
	for (i = 0; i < clientsList.length; i++)
    console.log ("The client's name is " + clientsList[i].name + ", and is " + clientsList[i].age + " years old. Their quote is '"+ clientsList[i].quote+ "'")
}

console.log (displayinfo(clientsList));

// 4. "But wait, there's more!"

function showQuote() { for (i = 0; i < clientsList.length; i++)
    console.log ("This person's famous quote is '"+ clientsList[i].quote+ "'")
}

showQuote()

// 5.  ** BONUS **
// not advanced enough for this at this time, but will figure it out soon.

// //  6.  Your Reflection:
// This was a difficult challenge. I wish we had more time in the GPS to
// accomplish the objectives with the guidance of the instructor.
// There was a lot of sidetracking during the session, which may have been
// necessary but maybe too extensive. I would have liked to continue working
// right after the hour session with my partner... or maybe after a short break,
// however, he had previous engagements. We were not able to pair online together
// again after the GPS session, which was detrimental to both of our experiences.
// I used quite a few resources to get through the challenge on my own.
// I feel very accomplished that I was able to complete this to the best of my
// ability. (I hope I did everything correctly.)

<|endoftext|>


<commit_before>// ui module
// Handles displaying data to UI, user interaction events and changing views,
// basically any interaction with the page should run through UI

// Calling ui.help("<function name>") will give parameter information
// the help will also be displayed if the parameters are given incorrectly

// The UI will get updates to it's data from TODO (external module), update it's
// data object, then calls update(data); on all views.

// Example UI Data Format
/*
{
    "miner": {
        "State": "On",
        "Threads": 2,
        "RunningThreads": 1,
        "Address": [
        126,
        66,
        "...",
        173,
        53
        ],
        "AccountName": "Personal",
        "Balance": 1,
        "USDBalance": 2,
        "IncomeRate": "20.345 SC/h"
    },
    "wallet": {
        "Balance": 0,
        "USDBalance": 0,
        "FullBalance": 0,
        "NumAddresses": 2392,
        "DefaultAccount": "Personal",
        "Accounts": [
    {
        "Name": "Personal",
        "Balance": 1,
        "USDBalance": 2,
        "FullBalance": 0,
        "NumAddresses": 231,
        "Addresses": [
    {
        "Address": "aaaaaaaaaaaaaaaaaaaaaa",
        "Balance": 2.13
    },
{
    "Address": "aaaaaaaaaaaaaaaaaaaaaa",
    "Balance": 0.001
},
{
    "Address": "aaaaaaaaaaaaaaaaaaaaaa",
    "Balance": 1.32
}
],
"Transactions": [
{
    "Date": "01/02/2015",
    "Amount": "2.67",
    "USDAmount": "3.90",
    "Deposit": true
},
{
    "Date": "01/02/2015",
    "Amount": "3.14",
    "USDAmount": "3.90",
    "Deposit": false
}
]
},
{
    "Name": "Work",
    "Balance": 0,
    "USDBalance": 0,
    "FullBalance": 0,
    "NumAddresses": 101,
    "Addresses": [
{
    "Address": "aaaaaaaaaaaaaaaaaaaaaa",
    "Amount": 2.13
},
{
    "Address": "aaaaaaaaaaaaaaaaaaaaaa",
    "Amount": 0.001
},
{
    "Address": "aaaaaaaaaaaaaaaaaaaaaa",
    "Amount": 1.32
}
],
"Transactions": [
{
    "Date": "01/02/2015",
    "Amount": "2.67",
    "USDAmount": "3.90",
    "Deposit": true
},
{
    "Date": "01/02/2015",
    "Amount": "2.67",
    "USDAmount": "3.90",
    "Deposit": true
}
]
}
]
},
"status": {
    "StateInfo": {
        "CurrentBlock": [
        231,
        83,
        "...",
        114,
        111,
        159
        ],
        "Height": 0,
        "Target": [
        0,
        0,
        "...",
        0,
        0
        ],
        "Depth": [
        255,
        255,
        "...",
        255,
        255
        ],
        "EarliestLegalTimestamp": 1417070299
    },
    "RenterFiles": null,
    "IPAddress": ":9988",
    "HostSettings": {
        "IPAddress": ":9988",
        "TotalStorage": 0,
        "MinFilesize": 0,
        "MaxFilesize": 0,
        "MinDuration": 0,
        "MaxDuration": 0,
        "MinChallengeWindow": 0,
        "MaxChallengeWindow": 0,
        "MinTolerance": 0,
        "Price": 0,
        "Burn": 0,
        "CoinAddress": [
        0,
        0,
        "...",
        0,
        0
        ],
        "SpendConditions": {
            "TimeLock": 0,
            "NumSignatures": 0,
            "PublicKeys": null
        },
        "FreezeIndex": 0
    },
    "HostSpaceRemaining": 0,
    "HostContractCount": 0
}
}*/

var ui = (function(){

    var currentView = "overview";
    var viewNames = ["overview", "money", "manage-account", "files", "hosting", "mining", "transfer-funds"];
    var transitionTypes = {
        "money->manage-account": "slideleft",
        "manage-account->money": "slideright"
    };
    var lastData;
    var eTooltip;
    var eventListeners = {};

    function switchView(newView){
        // Check that parameter is specified
        if (!newView){
            console.error(help("switchView"));
            return;
        }
        // Check if view is valid
        if (viewNames.indexOf(newView) === -1){
            console.error(newView + " is not a valid view");
            return;
        }

        // Refresh the new view's data
        ui["_" + newView].update(lastData);

        // Call the view onViewOpened event
        if (ui["_" + newView].onViewOpened) ui["_" + newView].onViewOpened();

        // Make the currently selected button greyed
        $("#sidebar .current").removeClass("current");
        $("." + newView + "-button").addClass("current");

        // Get the animation for the change
        var transitionType = transitionTypes[currentView + "->" + newView] || "load";

        if (transitionType == "load"){
            // Play a dummy loading animation (we may need the time later)
            startLoadingAnimation();
            setTimeout(function(){
                stopLoadingAnimation(newView);
            },400);
        }else if (transitionType == "slideright"){
            slideAnimation(newView, "right");
        }else if (transitionType == "slideleft"){
            slideAnimation(newView, "left");
        }else{
            console.error("Invalid transition type specified");
        }

    }

    function startLoadingAnimation(){
        // Position rotating loader icon in center of content
        $("#loader").css({
            "left": $("#content").width()/2 - $("#loader").width()/2,
            "top": "250px"
        });

        // Animate the loader in
        $("#loader").stop().fadeIn();

        // Make all content (excluding the loader) non-visible
        $("#content").children().filter(function(i){
            return this != $("#loader")[0];
        }).fadeOut();
    }

    function stopLoadingAnimation(newView){
        currentView = newView;
        $("#loader").stop().fadeOut();
        $("#" + newView).fadeIn();
    }

    function slideAnimation(newView, directionString){

        // Utility functions
        function setTranslate(element, x, y){
            element.css({
                "-webkit-transform": "translate(" + x + "px," + y + "px)"
            });
        }

        function clearTransform(element){
            element.css({
                "-webkit-transform": ""
            });
        }

        // Show the new view (off to the side)
        $("#" + newView).show();

        var newElement = $("#" + newView);
        var oldElement = $("#" + currentView);

        // To avoid movement upon removal
        newElement.before(oldElement);

        var slideDistance = oldElement.width();
        var heightDifference = oldElement.offset().top - newElement.offset().top;

        newElement.css({"animationProgress":0});
        newElement.animate({animationProgress:1},{
            duration:400,
            step: function(v){
                // Prevent tooltips from being spawned
                eTooltip.stop().hide();
                clearTimeout(tooltipTimeout);

                // Translate views
                if (directionString == "right"){
                    setTranslate(newElement, slideDistance * (v- 1),heightDifference);
                    setTranslate(oldElement, slideDistance * v, 0);
                }else{
                    setTranslate(newElement, slideDistance * (1-v), heightDifference);
                    setTranslate(oldElement, slideDistance * -v,0);
                }
            },
            complete:function(){
                // When the animation is done, clear the transformations and
                // make the current view the primary view
                clearTransform(oldElement);
                clearTransform(newElement);
                oldElement.hide();
                currentView = newView;
            }
        });
    }

    function help(functionName){
        if (!functionName) console.error("help(<function name>)");
        return {
            "switchView": "switchView(<string newView>) \
            \nPossible Views: " + viewNames.join(", "),
            "update": "update(<json data object>) \
            \nData object generated from requests from server, see top of ui.js",
            "addListener": "addListener(<string event>, <function callback>)\
            \nAdd listener when a ui event occurs"
        }[functionName];
    }

    function init(){
        // Hide everything but the "overview" view
        $("#content").children().filter(function(i){
            return this != $("#overview")[0];
        }).hide();

        // Add click listeners to buttons
        viewNames.forEach(function(view){
            $("." + view + "-button").click(function(){
                switchView(view);
            });
        });

        eTooltip = $("#tooltip");

        initViews();
    }

    function initViews(){
        viewNames.forEach(function(view){
            ui["_" + view].init();
        });
    }

    function update(data){
        viewNames.forEach(function(view){
            ui["_" + view].update(data);
        });
        lastData = data;
    }

    // Triggers an event, many ui actions cause triggers
    function _trigger(event){
        console.log("Event Triggered:",event);
        var callbacks = eventListeners[event] || [];
        for (var i = 0;i < callbacks.length;i++){
            callbacks[i].apply(this, Array.prototype.slice.call(arguments).slice(1,arguments.length));
        }
    }

    // Shows tooltip with content on given element
    var tooltipTimeout,tooltipVisible;
    function _tooltip(element, content, offset){
        offset = offset || {top:0,left:0};
        element = $(element);
        eTooltip.show();
        eTooltip.html(content);
        var middleX = element.offset().left + element.width()/2;
        var topY = element.offset().top - element.height();
        eTooltip.offset({
            top: topY - eTooltip.height() + offset.top,
            left: middleX - eTooltip.width()/2 + offset.left
        });
        if (!tooltipVisible){
            eTooltip.stop();
            eTooltip.css({"opacity":0});
            tooltipVisible = true;
            eTooltip.animate({
                "opacity":1
            },400);
        }else{
            eTooltip.stop();
            eTooltip.show();
            eTooltip.css({"opacity":1});
        }
        clearTimeout(tooltipTimeout);
        tooltipTimeout = setTimeout(function(){
            // eTooltip.hide();
            eTooltip.animate({
                "opacity":"0"
            },400,function(){
                tooltipVisible = false;
                eTooltip.hide();
            });
        },1400);
    }

    function addListener(event, callback){
        eventListeners[event] = eventListeners[event] || [];
        eventListeners[event].push(callback);
    }

    return {
        "switchView": switchView,
        "update": update,
        "addListener": addListener,
        "_tooltip": _tooltip,
        "_trigger": _trigger,
        "help": help,
        "init": init
    };
})();
<commit_msg>ui transitions for transfer funds<commit_after>// ui module
// Handles displaying data to UI, user interaction events and changing views,
// basically any interaction with the page should run through UI

// Calling ui.help("<function name>") will give parameter information
// the help will also be displayed if the parameters are given incorrectly

// The UI will get updates to it's data from TODO (external module), update it's
// data object, then calls update(data); on all views.

// Example UI Data Format
/*
{
    "miner": {
        "State": "On",
        "Threads": 2,
        "RunningThreads": 1,
        "Address": [
        126,
        66,
        "...",
        173,
        53
        ],
        "AccountName": "Personal",
        "Balance": 1,
        "USDBalance": 2,
        "IncomeRate": "20.345 SC/h"
    },
    "wallet": {
        "Balance": 0,
        "USDBalance": 0,
        "FullBalance": 0,
        "NumAddresses": 2392,
        "DefaultAccount": "Personal",
        "Accounts": [
    {
        "Name": "Personal",
        "Balance": 1,
        "USDBalance": 2,
        "FullBalance": 0,
        "NumAddresses": 231,
        "Addresses": [
    {
        "Address": "aaaaaaaaaaaaaaaaaaaaaa",
        "Balance": 2.13
    },
{
    "Address": "aaaaaaaaaaaaaaaaaaaaaa",
    "Balance": 0.001
},
{
    "Address": "aaaaaaaaaaaaaaaaaaaaaa",
    "Balance": 1.32
}
],
"Transactions": [
{
    "Date": "01/02/2015",
    "Amount": "2.67",
    "USDAmount": "3.90",
    "Deposit": true
},
{
    "Date": "01/02/2015",
    "Amount": "3.14",
    "USDAmount": "3.90",
    "Deposit": false
}
]
},
{
    "Name": "Work",
    "Balance": 0,
    "USDBalance": 0,
    "FullBalance": 0,
    "NumAddresses": 101,
    "Addresses": [
{
    "Address": "aaaaaaaaaaaaaaaaaaaaaa",
    "Amount": 2.13
},
{
    "Address": "aaaaaaaaaaaaaaaaaaaaaa",
    "Amount": 0.001
},
{
    "Address": "aaaaaaaaaaaaaaaaaaaaaa",
    "Amount": 1.32
}
],
"Transactions": [
{
    "Date": "01/02/2015",
    "Amount": "2.67",
    "USDAmount": "3.90",
    "Deposit": true
},
{
    "Date": "01/02/2015",
    "Amount": "2.67",
    "USDAmount": "3.90",
    "Deposit": true
}
]
}
]
},
"status": {
    "StateInfo": {
        "CurrentBlock": [
        231,
        83,
        "...",
        114,
        111,
        159
        ],
        "Height": 0,
        "Target": [
        0,
        0,
        "...",
        0,
        0
        ],
        "Depth": [
        255,
        255,
        "...",
        255,
        255
        ],
        "EarliestLegalTimestamp": 1417070299
    },
    "RenterFiles": null,
    "IPAddress": ":9988",
    "HostSettings": {
        "IPAddress": ":9988",
        "TotalStorage": 0,
        "MinFilesize": 0,
        "MaxFilesize": 0,
        "MinDuration": 0,
        "MaxDuration": 0,
        "MinChallengeWindow": 0,
        "MaxChallengeWindow": 0,
        "MinTolerance": 0,
        "Price": 0,
        "Burn": 0,
        "CoinAddress": [
        0,
        0,
        "...",
        0,
        0
        ],
        "SpendConditions": {
            "TimeLock": 0,
            "NumSignatures": 0,
            "PublicKeys": null
        },
        "FreezeIndex": 0
    },
    "HostSpaceRemaining": 0,
    "HostContractCount": 0
}
}*/

var ui = (function(){

    var currentView = "overview";
    var viewNames = ["overview", "money", "manage-account", "files", "hosting", "mining", "transfer-funds"];
    var transitionTypes = {
        "money->manage-account": "slideleft",
        "manage-account->money": "slideright",
        "manage-account->transfer-funds": "slideleft",
        "transfer-funds->manage-account": "slideright"
    };
    var lastData;
    var eTooltip;
    var eventListeners = {};

    function switchView(newView){
        // Check that parameter is specified
        if (!newView){
            console.error(help("switchView"));
            return;
        }
        // Check if view is valid
        if (viewNames.indexOf(newView) === -1){
            console.error(newView + " is not a valid view");
            return;
        }

        // Refresh the new view's data
        ui["_" + newView].update(lastData);

        // Call the view onViewOpened event
        if (ui["_" + newView].onViewOpened) ui["_" + newView].onViewOpened();

        // Make the currently selected button greyed
        $("#sidebar .current").removeClass("current");
        $("." + newView + "-button").addClass("current");

        // Get the animation for the change
        var transitionType = transitionTypes[currentView + "->" + newView] || "load";

        if (transitionType == "load"){
            // Play a dummy loading animation (we may need the time later)
            startLoadingAnimation();
            setTimeout(function(){
                stopLoadingAnimation(newView);
            },400);
        }else if (transitionType == "slideright"){
            slideAnimation(newView, "right");
        }else if (transitionType == "slideleft"){
            slideAnimation(newView, "left");
        }else{
            console.error("Invalid transition type specified");
        }

    }

    function startLoadingAnimation(){
        // Position rotating loader icon in center of content
        $("#loader").css({
            "left": $("#content").width()/2 - $("#loader").width()/2,
            "top": "250px"
        });

        // Animate the loader in
        $("#loader").stop().fadeIn();

        // Make all content (excluding the loader) non-visible
        $("#content").children().filter(function(i){
            return this != $("#loader")[0];
        }).fadeOut();
    }

    function stopLoadingAnimation(newView){
        currentView = newView;
        $("#loader").stop().fadeOut();
        $("#" + newView).fadeIn();
    }

    function slideAnimation(newView, directionString){

        // Utility functions
        function setTranslate(element, x, y){
            element.css({
                "-webkit-transform": "translate(" + x + "px," + y + "px)"
            });
        }

        function clearTransform(element){
            element.css({
                "-webkit-transform": ""
            });
        }

        // Show the new view (off to the side)
        $("#" + newView).show();

        var newElement = $("#" + newView);
        var oldElement = $("#" + currentView);

        // To avoid movement upon removal
        newElement.before(oldElement);

        var slideDistance = oldElement.width();
        var heightDifference = oldElement.offset().top - newElement.offset().top;

        newElement.css({"animationProgress":0});
        newElement.animate({animationProgress:1},{
            duration:400,
            step: function(v){
                // Prevent tooltips from being spawned
                eTooltip.stop().hide();
                clearTimeout(tooltipTimeout);

                // Translate views
                if (directionString == "right"){
                    setTranslate(newElement, slideDistance * (v- 1),heightDifference);
                    setTranslate(oldElement, slideDistance * v, 0);
                }else{
                    setTranslate(newElement, slideDistance * (1-v), heightDifference);
                    setTranslate(oldElement, slideDistance * -v,0);
                }
            },
            complete:function(){
                // When the animation is done, clear the transformations and
                // make the current view the primary view
                clearTransform(oldElement);
                clearTransform(newElement);
                oldElement.hide();
                currentView = newView;
            }
        });
    }

    function help(functionName){
        if (!functionName) console.error("help(<function name>)");
        return {
            "switchView": "switchView(<string newView>) \
            \nPossible Views: " + viewNames.join(", "),
            "update": "update(<json data object>) \
            \nData object generated from requests from server, see top of ui.js",
            "addListener": "addListener(<string event>, <function callback>)\
            \nAdd listener when a ui event occurs"
        }[functionName];
    }

    function init(){
        // Hide everything but the "overview" view
        $("#content").children().filter(function(i){
            return this != $("#overview")[0];
        }).hide();

        // Add click listeners to buttons
        viewNames.forEach(function(view){
            $("." + view + "-button").click(function(){
                switchView(view);
            });
        });

        eTooltip = $("#tooltip");

        initViews();
    }

    function initViews(){
        viewNames.forEach(function(view){
            ui["_" + view].init();
        });
    }

    function update(data){
        viewNames.forEach(function(view){
            ui["_" + view].update(data);
        });
        lastData = data;
    }

    // Triggers an event, many ui actions cause triggers
    function _trigger(event){
        console.log("Event Triggered:",event);
        var callbacks = eventListeners[event] || [];
        for (var i = 0;i < callbacks.length;i++){
            callbacks[i].apply(this, Array.prototype.slice.call(arguments).slice(1,arguments.length));
        }
    }

    // Shows tooltip with content on given element
    var tooltipTimeout,tooltipVisible;
    function _tooltip(element, content, offset){
        offset = offset || {top:0,left:0};
        element = $(element);
        eTooltip.show();
        eTooltip.html(content);
        var middleX = element.offset().left + element.width()/2;
        var topY = element.offset().top - element.height();
        eTooltip.offset({
            top: topY - eTooltip.height() + offset.top,
            left: middleX - eTooltip.width()/2 + offset.left
        });
        if (!tooltipVisible){
            eTooltip.stop();
            eTooltip.css({"opacity":0});
            tooltipVisible = true;
            eTooltip.animate({
                "opacity":1
            },400);
        }else{
            eTooltip.stop();
            eTooltip.show();
            eTooltip.css({"opacity":1});
        }
        clearTimeout(tooltipTimeout);
        tooltipTimeout = setTimeout(function(){
            // eTooltip.hide();
            eTooltip.animate({
                "opacity":"0"
            },400,function(){
                tooltipVisible = false;
                eTooltip.hide();
            });
        },1400);
    }

    function addListener(event, callback){
        eventListeners[event] = eventListeners[event] || [];
        eventListeners[event].push(callback);
    }

    return {
        "switchView": switchView,
        "update": update,
        "addListener": addListener,
        "_tooltip": _tooltip,
        "_trigger": _trigger,
        "help": help,
        "init": init
    };
})();
<|endoftext|>


<commit_before>(function (root) {
	if (root) {
		if (root.angular && root.loki) {
			var module = angular.module('lokijs', [])
				.factory('Loki', function Loki($window) {
					if ($window.loki) {
						$window.thirdParty = $window.thirdParty || {};
						$window.thirdParty.loki = root.loki;
						try {
							delete $window.loki;
						} catch (err) {
							$window.loki = undefined;
						}
					}
					var loki = $window.thirdParty.loki;
					return loki;
				});
		}
	}
})(window)<commit_msg>add amd and requirejs support to Loki Angular Adapter<commit_after>/*
  Loki Angular Adapter (need to include this script to use it)
 * @author Joe Minichino <joe.minichino@gmail.com>
 *
 * A lightweight document oriented javascript database
 */
(function (root, factory) {
  if (typeof define === 'function' && define.amd) {
    // AMD. Register as an anonymous module.
    define(['angular', 'lokijs'], factory);
  } else if (typeof exports === 'object') {
    // CommonJS
    module.exports = factory();
  } else {
    // Browser globals
    root.lokiAngular = factory(
    	root.angular,
    	// Use thirdParty.loki if available to cover all legacy cases
			root.thirdParty && root.thirdParty.loki ?
				root.thirdParty.loki : root.loki
	);
  }
} (this, function (angular, lokijs) {
	var module = angular.module('lokijs', [])
		.factory('Loki', function Loki() {
			return lokijs;
		});
	return module;
}));<|endoftext|>


<commit_before>/*
 * daycount.js v0.1.3
 * http://yellowseed.org/daycount.js/
 *
 * Copyright 2011, Joshua Tacoma
 * Licensed under the MIT license.
 * http://www.opensource.org/licenses/mit-license.php
 *
 */

// All other globals defined here are kept in this object:
var daycount = (typeof exports !== 'undefined' && exports !== null)
  ? exports : {};

// The 'moment' type, which may include associated information from any
// calendar system:
daycount.moment = (function() {

  // 'moment' constructor:
  function moment(arg) {
    this.set(arg);
  };

  moment.prototype.set = function(arg) {
    if(!arg || arg === null)
      arg = new Date();

    // Now, we're going to calculate as many counts as possible...

    // 'todo' lists counts to be calculated:
    var todo = []
    for(var name in daycount.counts)
    {
      todo.push(name);
      // wipe out any counts lingering from previous calculations:
      if(name in this)
        delete this[name];
    }

    // 'done' lists known counts:
    var done = [arg.constructor.name];
    // TODO: make sure that no item in 'done' is also in 'todo'.

    if (!(arg.constructor.name in daycount.counts))
      this.isUnknown = true;

    // Store argument as the only known property of this:
    this[arg.constructor.name] = arg;

    // Iterate through counts in 'done'.  We're going to add to this list as we
    // go, which makes this for loop a little more interesting:
    for (var indexDone = 0;
         indexDone < done.length && todo.length > 0;
         ++indexDone)
    {
      var nameDone = done[indexDone];
      var builderNameTodo = 'from_' + nameDone;

      // Iterate through counts in 'todo'.  Since we're going to remove
      // them as we go, iterate backwards to keep remaining indices
      // from shifting:
      for (var indexTodo = todo.length - 1; indexTodo >= 0; --indexTodo) {
        var nameTodo = todo[indexTodo];
        var countTodo = daycount.counts[nameTodo];

        if(!countTodo.hasOwnProperty(builderNameTodo)) continue;

        // Found one!  Calculate the value for 'countTodo':
        var builder = countTodo[builderNameTodo];
        var built = builder(this[nameDone]);
        if(built === null) continue;

        this[nameTodo] = built;
        done.push(nameTodo);
        todo.splice(indexTodo, 1)
        if('isUnknown' in this)
          delete this['isUnknown'];
      }
    }
  };

  moment.prototype.plusEarthSolarDays = function(days) {
    if('localJulianDay' in this)
      return new moment(
        new daycount.counts.localJulianDay(
          this.localJulianDay.number + days));
    else
      throw 'this moment has no counts that support the specified increment.';
  };

  moment.prototype.plus = moment.prototype.plusEarthSolarDays;

  return moment;
})();

// A collection of counts i.e. calendar systems.
// Each calendar system should be added to this object.
daycount.counts = {};

daycount.version_ = {
  major: 0,
  minor: 1,
  build: 3,
};

<commit_msg>updated version numbers to 0.1.4.<commit_after>/*
 * daycount.js v0.1.4
 * http://yellowseed.org/daycount.js/
 *
 * Copyright 2011, Joshua Tacoma
 * Licensed under the MIT license.
 * http://www.opensource.org/licenses/mit-license.php
 *
 */

// All other globals defined here are kept in this object:
var daycount = (typeof exports !== 'undefined' && exports !== null)
  ? exports : {};

// The 'moment' type, which may include associated information from any
// calendar system:
daycount.moment = (function() {

  // 'moment' constructor:
  function moment(arg) {
    this.set(arg);
  };

  moment.prototype.set = function(arg) {
    if(!arg || arg === null)
      arg = new Date();

    // Now, we're going to calculate as many counts as possible...

    // 'todo' lists counts to be calculated:
    var todo = []
    for(var name in daycount.counts)
    {
      todo.push(name);
      // wipe out any counts lingering from previous calculations:
      if(name in this)
        delete this[name];
    }

    // 'done' lists known counts:
    var done = [arg.constructor.name];
    // TODO: make sure that no item in 'done' is also in 'todo'.

    if (!(arg.constructor.name in daycount.counts))
      this.isUnknown = true;

    // Store argument as the only known property of this:
    this[arg.constructor.name] = arg;

    // Iterate through counts in 'done'.  We're going to add to this list as we
    // go, which makes this for loop a little more interesting:
    for (var indexDone = 0;
         indexDone < done.length && todo.length > 0;
         ++indexDone)
    {
      var nameDone = done[indexDone];
      var builderNameTodo = 'from_' + nameDone;

      // Iterate through counts in 'todo'.  Since we're going to remove
      // them as we go, iterate backwards to keep remaining indices
      // from shifting:
      for (var indexTodo = todo.length - 1; indexTodo >= 0; --indexTodo) {
        var nameTodo = todo[indexTodo];
        var countTodo = daycount.counts[nameTodo];

        if(!countTodo.hasOwnProperty(builderNameTodo)) continue;

        // Found one!  Calculate the value for 'countTodo':
        var builder = countTodo[builderNameTodo];
        var built = builder(this[nameDone]);
        if(built === null) continue;

        this[nameTodo] = built;
        done.push(nameTodo);
        todo.splice(indexTodo, 1)
        if('isUnknown' in this)
          delete this['isUnknown'];
      }
    }
  };

  moment.prototype.plusEarthSolarDays = function(days) {
    if('localJulianDay' in this)
      return new moment(
        new daycount.counts.localJulianDay(
          this.localJulianDay.number + days));
    else
      throw 'this moment has no counts that support the specified increment.';
  };

  moment.prototype.plus = moment.prototype.plusEarthSolarDays;

  return moment;
})();

// A collection of counts i.e. calendar systems.
// Each calendar system should be added to this object.
daycount.counts = {};

daycount.version_ = {
  major: 0,
  minor: 1,
  build: 4,
};

<|endoftext|>


<commit_before>import React from 'react';
import {
  Text,
  Clipboard,
  StyleSheet,
  TouchableWithoutFeedback,
  View,
} from 'react-native';

import MessageText from './MessageText';
import MessageImage from './MessageImage';
import Time from './Time';

export default class Bubble extends React.Component {
  constructor(props) {
    super(props);
    this.onLongPress = this.onLongPress.bind(this);
  }

  handleBubbleToNext() {
    if (this.props.isSameUser(this.props.currentMessage, this.props.nextMessage) && this.props.isSameDay(this.props.currentMessage, this.props.nextMessage)) {
      return StyleSheet.flatten([styles[this.props.position].containerToNext, this.props.containerToNextStyle[this.props.position]]);
    }
    return null;
  }

  handleBubbleToPrevious() {
    if (this.props.isSameUser(this.props.currentMessage, this.props.previousMessage) && this.props.isSameDay(this.props.currentMessage, this.props.previousMessage)) {
      return StyleSheet.flatten([styles[this.props.position].containerToPrevious, this.props.containerToPreviousStyle[this.props.position]]);
    }
    return null;
  }

  renderMessageText() {
    if (this.props.currentMessage.text) {
      const {containerStyle, wrapperStyle, ...messageTextProps} = this.props;
      if (this.props.renderMessageText) {
        return this.props.renderMessageText(messageTextProps);
      }
      return <MessageText {...messageTextProps}/>;
    }
    return null;
  }

  renderMessageImage() {
    if (this.props.currentMessage.image) {
      const {containerStyle, wrapperStyle, ...messageImageProps} = this.props;
      if (this.props.renderMessageImage) {
        return this.props.renderMessageImage(messageImageProps);
      }
      return <MessageImage {...messageImageProps}/>;
    }
    return null;
  }

  renderTicks() {
    const {currentMessage} = this.props;
    if (this.props.renderTicks) {
        return this.props.renderTicks(currentMessage);
    }
    if (currentMessage.user._id !== this.props.user._id) {
        return;
    }
    if (currentMessage.sent || currentMessage.received) {
      return (
        <View style={styles.tickView}>
          {currentMessage.sent && <Text style={styles.tick}>✓</Text>}
          {currentMessage.received && <Text style={styles.tick}>✓</Text>}
        </View>
      )
    }
  }

  renderTime() {
    if (this.props.currentMessage.createdAt) {
      const {containerStyle, wrapperStyle, ...timeProps} = this.props;
      if (this.props.renderTime) {
        return this.props.renderTime(timeProps);
      }
      return <Time {...timeProps}/>;
    }
    return null;
  }

  renderCustomView() {
    if (this.props.renderCustomView) {
      return this.props.renderCustomView(this.props);
    }
    return null;
  }

  onLongPress() {
    if (this.props.onLongPress) {
      this.props.onLongPress(this.context);
    } else {
      if (this.props.currentMessage.text) {
        const options = [
          'Copy Text',
          'Cancel',
        ];
        const cancelButtonIndex = options.length - 1;
        this.context.actionSheet().showActionSheetWithOptions({
          options,
          cancelButtonIndex,
        },
        (buttonIndex) => {
          switch (buttonIndex) {
            case 0:
              Clipboard.setString(this.props.currentMessage.text);
              break;
          }
        });
      }
    }
  }

  render() {
    return (
      <View style={[styles[this.props.position].container, this.props.containerStyle[this.props.position]]}>
        <View style={[styles[this.props.position].wrapper, this.props.wrapperStyle[this.props.position], this.handleBubbleToNext(), this.handleBubbleToPrevious()]}>
          <TouchableWithoutFeedback
            onLongPress={this.onLongPress}
            accessibilityTraits="text"
            {...this.props.touchableProps}
          >
            <View>
              {this.renderCustomView()}
              {this.renderMessageImage()}
              {this.renderMessageText()}
              <View style={styles.bottom}>
                {this.renderTime()}
                {this.renderTicks()}
              </View>
            </View>
          </TouchableWithoutFeedback>
        </View>
      </View>
    );
  }
}

const styles = {
  left: StyleSheet.create({
    container: {
      flex: 1,
      alignItems: 'flex-start',
    },
    wrapper: {
      borderRadius: 15,
      backgroundColor: '#f0f0f0',
      marginRight: 60,
      minHeight: 20,
      justifyContent: 'flex-end',
    },
    containerToNext: {
      borderBottomLeftRadius: 3,
    },
    containerToPrevious: {
      borderTopLeftRadius: 3,
    },
  }),
  right: StyleSheet.create({
    container: {
      flex: 1,
      alignItems: 'flex-end',
    },
    wrapper: {
      borderRadius: 15,
      backgroundColor: '#0084ff',
      marginLeft: 60,
      minHeight: 20,
      justifyContent: 'flex-end',
    },
    containerToNext: {
      borderBottomRightRadius: 3,
    },
    containerToPrevious: {
      borderTopRightRadius: 3,
    },
  }),
  bottom: {
    flexDirection: 'row',
    justifyContent: 'flex-end',
  },
  tick: {
    fontSize: 10,
    backgroundColor: 'transparent',
    color: 'white',
  },
  tickView: {
    flexDirection: 'row',
    marginRight: 10,
  }
};

Bubble.contextTypes = {
  actionSheet: React.PropTypes.func,
};

Bubble.defaultProps = {
  touchableProps: {},
  onLongPress: null,
  renderMessageImage: null,
  renderMessageText: null,
  renderCustomView: null,
  renderTime: null,
  isSameUser: () => {},
  isSameDay: () => {},
  position: 'left',
  currentMessage: {
    text: null,
    createdAt: null,
    image: null,
  },
  nextMessage: {},
  previousMessage: {},
  containerStyle: {},
  wrapperStyle: {},
  containerToNextStyle: {},
  containerToPreviousStyle: {},
};

Bubble.propTypes = {
  touchableProps: React.PropTypes.object,
  onLongPress: React.PropTypes.func,
  renderMessageImage: React.PropTypes.func,
  renderMessageText: React.PropTypes.func,
  renderCustomView: React.PropTypes.func,
  renderTime: React.PropTypes.func,
  isSameUser: React.PropTypes.func,
  isSameDay: React.PropTypes.func,
  position: React.PropTypes.oneOf(['left', 'right']),
  currentMessage: React.PropTypes.object,
  nextMessage: React.PropTypes.object,
  previousMessage: React.PropTypes.object,
  containerStyle: React.PropTypes.shape({
    left: View.propTypes.style,
    right: View.propTypes.style,
  }),
  wrapperStyle: React.PropTypes.shape({
    left: View.propTypes.style,
    right: View.propTypes.style,
  }),
  containerToNextStyle: React.PropTypes.shape({
    left: View.propTypes.style,
    right: View.propTypes.style,
  }),
  containerToPreviousStyle: React.PropTypes.shape({
    left: View.propTypes.style,
    right: View.propTypes.style,
  }),
};
<commit_msg>renderTick: Possibility to change style of the ticks passing the parameter tickStyle to GiftedChat<commit_after>import React from 'react';
import {
  Text,
  Clipboard,
  StyleSheet,
  TouchableWithoutFeedback,
  View,
} from 'react-native';

import MessageText from './MessageText';
import MessageImage from './MessageImage';
import Time from './Time';

export default class Bubble extends React.Component {
  constructor(props) {
    super(props);
    this.onLongPress = this.onLongPress.bind(this);
  }

  handleBubbleToNext() {
    if (this.props.isSameUser(this.props.currentMessage, this.props.nextMessage) && this.props.isSameDay(this.props.currentMessage, this.props.nextMessage)) {
      return StyleSheet.flatten([styles[this.props.position].containerToNext, this.props.containerToNextStyle[this.props.position]]);
    }
    return null;
  }

  handleBubbleToPrevious() {
    if (this.props.isSameUser(this.props.currentMessage, this.props.previousMessage) && this.props.isSameDay(this.props.currentMessage, this.props.previousMessage)) {
      return StyleSheet.flatten([styles[this.props.position].containerToPrevious, this.props.containerToPreviousStyle[this.props.position]]);
    }
    return null;
  }

  renderMessageText() {
    if (this.props.currentMessage.text) {
      const {containerStyle, wrapperStyle, ...messageTextProps} = this.props;
      if (this.props.renderMessageText) {
        return this.props.renderMessageText(messageTextProps);
      }
      return <MessageText {...messageTextProps}/>;
    }
    return null;
  }

  renderMessageImage() {
    if (this.props.currentMessage.image) {
      const {containerStyle, wrapperStyle, ...messageImageProps} = this.props;
      if (this.props.renderMessageImage) {
        return this.props.renderMessageImage(messageImageProps);
      }
      return <MessageImage {...messageImageProps}/>;
    }
    return null;
  }

  renderTicks() {
    const {currentMessage} = this.props;
    if (this.props.renderTicks) {
        return this.props.renderTicks(currentMessage);
    }
    if (currentMessage.user._id !== this.props.user._id) {
        return;
    }
    if (currentMessage.sent || currentMessage.received) {
      return (
        <View style={styles.tickView}>
          {currentMessage.sent && <Text style={[styles.tick, this.props.tickStyle]}>✓</Text>}
          {currentMessage.received && <Text style={[styles.tick, this.props.tickStyle]}>✓</Text>}
        </View>
      )
    }
  }

  renderTime() {
    if (this.props.currentMessage.createdAt) {
      const {containerStyle, wrapperStyle, ...timeProps} = this.props;
      if (this.props.renderTime) {
        return this.props.renderTime(timeProps);
      }
      return <Time {...timeProps}/>;
    }
    return null;
  }

  renderCustomView() {
    if (this.props.renderCustomView) {
      return this.props.renderCustomView(this.props);
    }
    return null;
  }

  onLongPress() {
    if (this.props.onLongPress) {
      this.props.onLongPress(this.context);
    } else {
      if (this.props.currentMessage.text) {
        const options = [
          'Copy Text',
          'Cancel',
        ];
        const cancelButtonIndex = options.length - 1;
        this.context.actionSheet().showActionSheetWithOptions({
          options,
          cancelButtonIndex,
        },
        (buttonIndex) => {
          switch (buttonIndex) {
            case 0:
              Clipboard.setString(this.props.currentMessage.text);
              break;
          }
        });
      }
    }
  }

  render() {
    return (
      <View style={[styles[this.props.position].container, this.props.containerStyle[this.props.position]]}>
        <View style={[styles[this.props.position].wrapper, this.props.wrapperStyle[this.props.position], this.handleBubbleToNext(), this.handleBubbleToPrevious()]}>
          <TouchableWithoutFeedback
            onLongPress={this.onLongPress}
            accessibilityTraits="text"
            {...this.props.touchableProps}
          >
            <View>
              {this.renderCustomView()}
              {this.renderMessageImage()}
              {this.renderMessageText()}
              <View style={styles.bottom}>
                {this.renderTime()}
                {this.renderTicks()}
              </View>
            </View>
          </TouchableWithoutFeedback>
        </View>
      </View>
    );
  }
}

const styles = {
  left: StyleSheet.create({
    container: {
      flex: 1,
      alignItems: 'flex-start',
    },
    wrapper: {
      borderRadius: 15,
      backgroundColor: '#f0f0f0',
      marginRight: 60,
      minHeight: 20,
      justifyContent: 'flex-end',
    },
    containerToNext: {
      borderBottomLeftRadius: 3,
    },
    containerToPrevious: {
      borderTopLeftRadius: 3,
    },
  }),
  right: StyleSheet.create({
    container: {
      flex: 1,
      alignItems: 'flex-end',
    },
    wrapper: {
      borderRadius: 15,
      backgroundColor: '#0084ff',
      marginLeft: 60,
      minHeight: 20,
      justifyContent: 'flex-end',
    },
    containerToNext: {
      borderBottomRightRadius: 3,
    },
    containerToPrevious: {
      borderTopRightRadius: 3,
    },
  }),
  bottom: {
    flexDirection: 'row',
    justifyContent: 'flex-end',
  },
  tick: {
    fontSize: 10,
    backgroundColor: 'transparent',
    color: 'white',
  },
  tickView: {
    flexDirection: 'row',
    marginRight: 10,
  }
};

Bubble.contextTypes = {
  actionSheet: React.PropTypes.func,
};

Bubble.defaultProps = {
  touchableProps: {},
  onLongPress: null,
  renderMessageImage: null,
  renderMessageText: null,
  renderCustomView: null,
  renderTime: null,
  isSameUser: () => {},
  isSameDay: () => {},
  position: 'left',
  currentMessage: {
    text: null,
    createdAt: null,
    image: null,
  },
  nextMessage: {},
  previousMessage: {},
  containerStyle: {},
  wrapperStyle: {},
  tickStyle: {},
  containerToNextStyle: {},
  containerToPreviousStyle: {},
};

Bubble.propTypes = {
  touchableProps: React.PropTypes.object,
  onLongPress: React.PropTypes.func,
  renderMessageImage: React.PropTypes.func,
  renderMessageText: React.PropTypes.func,
  renderCustomView: React.PropTypes.func,
  renderTime: React.PropTypes.func,
  isSameUser: React.PropTypes.func,
  isSameDay: React.PropTypes.func,
  position: React.PropTypes.oneOf(['left', 'right']),
  currentMessage: React.PropTypes.object,
  nextMessage: React.PropTypes.object,
  previousMessage: React.PropTypes.object,
  containerStyle: React.PropTypes.shape({
    left: View.propTypes.style,
    right: View.propTypes.style,
  }),
  wrapperStyle: React.PropTypes.shape({
    left: View.propTypes.style,
    right: View.propTypes.style,
  }),
  tickStyle: Text.propTypes.style,
  containerToNextStyle: React.PropTypes.shape({
    left: View.propTypes.style,
    right: View.propTypes.style,
  }),
  containerToPreviousStyle: React.PropTypes.shape({
    left: View.propTypes.style,
    right: View.propTypes.style,
  }),
};
<|endoftext|>