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

// TODO: add terminal UI

var chalk = require('chalk')
var clivas = require('clivas')
var concat = require('concat-stream')
var cp = require('child_process')
var fs = require('fs')
var http = require('http')
var minimist = require('minimist')
var os = require('os')
var path = require('path')
var WebTorrent = require('../')

var TMP = os.tmp

function usage () {
  var logo = fs.readFileSync(path.join(__dirname, 'ascii-logo.txt'), 'utf8')
  logo.split('\n').forEach(function (line) {
    console.log(chalk.bold(line.substring(0, 20) + chalk.red(line.substring(20))))
  })
  console.log('Usage: webtorrent [torrentId] {OPTIONS}')
  console.log('')
  console.log(chalk.bold('torrentId') + ' can be any of the following:')
  console.log('  * magnet uri')
  console.log('  * path to .torrent file (filesystem path or http url)')
  console.log('  * info hash (as hex string)')
  console.log('')
  console.log(chalk.bold('OPTIONS:'))
  console.log('  --vlc            autoplay in vlc')
  console.log('  --mplayer        autoplay in mplayer')
  console.log('  --omx [jack]     autoplay in omx (jack=local|hdmi)')
  console.log('')
  console.log('  -p, --port       change the http port               [default: 9000]')
  console.log('  -l, --list       list available files in torrent')
  console.log('  -t, --subtitles  load subtitles file')
  console.log('  -h, --help       display this help message')
  console.log('  -v, --version    print the current version')
  console.log('')
}

var argv = minimist(process.argv.slice(2))

var torrentId = argv._[0]

var port = Number(argv.port || argv.p) || 9000
var list = argv.list || argv.l
var subtitles = argv.subtitles || argv.t

if (argv.help || argv.h) {
  usage()
  process.exit(0)
}

if (argv.version || argv.v) {
  console.log(require('../package.json').version)
  process.exit(0)
}

if (!torrentId) {
  usage()
  process.exit(0)
}

var VLC_ARGS = '-q --video-on-top --play-and-exit'
var OMX_EXEC = 'omxplayer -r -o ' + (typeof argv.omx === 'string')
  ? argv.omx + ' '
  : 'hdmi '
var MPLAYER_EXEC = 'mplayer -ontop -really-quiet -noidx -loop 0 '

if (subtitles) {
  VLC_ARGS += ' --sub-file=' + subtitles
  OMX_EXEC += ' --subtitles ' + subtitles
  MPLAYER_EXEC += ' -sub ' + subtitles
}

var manager = new WebTorrent(torrentId, {

})

if (list) {
  // TODO
  manager.on('ready', function () {
    manager.files.forEach(function (file, i, files) {
      console.log(i, file.name)
    })
    process.exit(0)
  })
  return
}

// var numeral = require('numeral')
// var address = require('network-address')
// var path = require('path')

// var ontorrent = function(torrent) {
//   var hotswaps = 0;

//   engine.on('hotswap', function() {
//     hotswaps++;
//   });

//   var started = Date.now();
//   var wires = engine.swarm.wires;
//   var swarm = engine.swarm;

//   var active = function(wire) {
//     return !wire.peerChoking;
//   };

//   engine.on('uninterested', function() {
//     engine.swarm.pause();
//   });

//   engine.on('interested', function() {
//     engine.swarm.resume();
//   });

//   engine.server.on('listening', function() {
//     var href = 'http://'+address()+':'+engine.server.address().port+'/';
//     var filename = engine.server.index.name.split('/').pop().replace(/\{|\}/g, '');

//     if (argv.vlc && process.platform === 'win32') {
//       var registry = require('windows-no-runnable').registry;
//       var key;
//       if (process.arch === 'x64') {
//         try {
//           key = registry('HKLM/Software/Wow6432Node/VideoLAN/VLC');
//         } catch (e) {}
//       } else {
//         try {
//           key = registry('HKLM/Software/VideoLAN/VLC');
//         } catch (err) {}
//       }

//       if (key) {
//         var vlcPath = key['InstallDir'].value + path.sep + 'vlc';
//         VLC_ARGS = VLC_ARGS.split(' ');
//         VLC_ARGS.unshift(href);
//         proc.execFile(vlcPath, VLC_ARGS);
//       }
//     } else {
//       if (argv.vlc) proc.exec('vlc '+href+' '+VLC_ARGS+' || /Applications/VLC.app/Contents/MacOS/VLC '+href+' '+VLC_ARGS);
//     }

//     if (argv.omx) proc.exec(OMX_EXEC+' '+href);
//     if (argv.mplayer) proc.exec(MPLAYER_EXEC+' '+href);

//     var bytes = function(num) {
//       return numeral(num).format('0.0b');
//     };

//     process.stdout.write(new Buffer('G1tIG1sySg==', 'base64')); // clear for drawing

//     var draw = function() {
//       var unchoked = engine.swarm.wires.filter(active);
//       var runtime = Math.floor((Date.now() - started) / 1000);
//       var linesremaining = clivas.height;
//       var peerslisted = 0;

//       clivas.clear();
//       clivas.line('{green:open} {bold:vlc} {green:and enter} {bold:'+href+'} {green:as the network address}');
//       clivas.line('');
//       clivas.line('{yellow:info} {green:streaming} {bold:'+filename+'} {green:-} {bold:'+bytes(swarm.downloadSpeed())+'/s} {green:from} {bold:'+unchoked.length +'/'+wires.length+'} {green:peers}    ');
//       clivas.line('{yellow:info} {green:downloaded} {bold:'+bytes(swarm.downloaded)+'} {green:and uploaded }{bold:'+bytes(swarm.uploaded)+'} {green:in }{bold:'+runtime+'s} {green:with} {bold:'+hotswaps+'} {green:hotswaps}     ');
//       clivas.line('{yellow:info} {green:peer queue size is} {bold:'+swarm.queued+'}     ');
//       clivas.line('{80:}');
//       linesremaining -= 8;

//       wires.every(function(wire) {
//         var tags = [];
//         if (wire.peerChoking) tags.push('choked');
//         clivas.line('{25+magenta:'+wire.peerAddress+'} {10:'+bytes(wire.downloaded)+'} {10+cyan:'+bytes(wire.downloadSpeed())+'/s} {15+grey:'+tags.join(', ')+'}   ');
//         peerslisted++;
//         return linesremaining-peerslisted > 4;
//       });
//       linesremaining -= peerslisted;

//       if (wires.length > peerslisted) {
//         clivas.line('{80:}');
//         clivas.line('... and '+(wires.length-peerslisted)+' more     ');
//       }

//       clivas.line('{80:}');
//       clivas.flush();
//     };

//     setInterval(draw, 500);
//     draw();
//   });

//   engine.server.once('error', function() {
//     engine.server.listen(0);
//   });

//   var onmagnet = function() {
//     clivas.clear();
//     clivas.line('{green:fetching torrent metadata from} {bold:'+engine.swarm.wires.length+'} {green:peers}');
//   };

//   if (typeof torrent === 'string' && torrent.indexOf('magnet:') === 0 && !argv.quiet) {
//     onmagnet();
//     engine.swarm.on('wire', onmagnet);
//   }

//   engine.on('ready', function() {
//     engine.swarm.removeListener('wire', onmagnet);
//     engine.server.listen(argv.port || 8888);
//   });
// };

// /**
//  * WebTorrent App UI
//  */
// function App (torrentManager) {
//   var self = this
//   if (!(self instanceof App)) return new App(torrentManager)

//   self.torrentManager = torrentManager

//   // Add existing torrents
//   self.torrentManager.torrents.forEach(function (torrent) {
//     self.addTorrent(torrent)
//   })

//   self.torrentManager.on('error', function (err) {
//     console.error(err)
//     // TODO: Show error in UI somehow
//   })

//   window.torrentManager.on('addTorrent', function (torrent) {
//     self.addTorrent(torrent)
//   })
//   window.torrentManager.on('removeTorrent', function (torrent) {
//     self.removeTorrent(torrent)
//   })

//   self.initUI()
// }

// App.prototype.addTorrent = function (torrent) {
//   var self = this
//   var $torrent = $(TEMPLATE.TORRENT)
//   self.updateTorrentUI($torrent, torrent)

//   $torrent.on('click', function () {
//     self.downloadTorrentFile(torrent)
//   })

//   $('#torrents').append($torrent)
//   self.updateUI()
// }

// App.prototype.updateUI = function () {
//   var self = this

//   self.torrentManager.torrents.forEach(function (torrent) {
//     var $torrent = $('#torrent_' + torrent.infoHash)
//     self.updateTorrentUI($torrent, torrent)
//   })

//   $('.overall-stats .ratio span').text(self.torrentManager.ratio)
//   $('.overall-stats .uploadSpeed span').text(humanize.filesize(self.torrentManager.uploadSpeed()))
//   $('.overall-stats .downloadSpeed span').text(humanize.filesize(self.torrentManager.downloadSpeed()))

//   // Number of transfers
//   if (self.torrentManager.torrents.length === 1)
//     $('.numTransfers').text('1 transfer')
//   else
//     $('.numTransfers').text(self.torrentManager.torrents.length + ' transfers')
// }

// App.prototype.updateTorrentUI = function ($torrent, torrent) {
//   if (!$torrent.attr('id'))
//     $torrent.attr('id', 'torrent_' + torrent.infoHash)

//   if (torrent.metadata)
//     $torrent.addClass('has-metadata')
//   else
//     $torrent.removeClass('has-metadata')

//   if (torrent.progress === 1)
//     $torrent.addClass('is-seeding')
//   else
//     $torrent.removeClass('is-seeding')

//   var timeRemaining
//   if (torrent.timeRemaining === Infinity) {
//     timeRemaining = 'remaining time unknown'
//   } else {
//     timeRemaining = moment(Date.now() + torrent.timeRemaining).fromNow() + '...'
//   }
//   $torrent.find('.timeRemaining').text(timeRemaining)

//   $torrent.find('.name').text(torrent.name)
//   $torrent.find('.downloaded').text(humanize.filesize(torrent.downloaded))
//   $torrent.find('.uploaded').text(humanize.filesize(torrent.uploaded))
//   $torrent.find('.length').text(humanize.filesize(torrent.length))
//   $torrent.find('.ratio').text(torrent.ratio)
//   $torrent.find('progress').attr('value', torrent.progress)
//   $torrent.find('.percentage').text((torrent.progress * 100).toFixed(2))
//   $torrent.find('.numPeers').text(torrent.swarm.numConns + torrent.swarm.numQueued)
//   $torrent.find('.numActivePeers').text(torrent.swarm.numPeers)
//   $torrent.find('.downloadSpeed').text(humanize.filesize(torrent.swarm.downloadSpeed()))
//   $torrent.find('.uploadSpeed').text(humanize.filesize(torrent.swarm.uploadSpeed()))
// }
<commit_msg>new constructor usage<commit_after>#!/usr/bin/env node

// TODO: add terminal UI

var chalk = require('chalk')
var clivas = require('clivas')
var concat = require('concat-stream')
var cp = require('child_process')
var fs = require('fs')
var http = require('http')
var minimist = require('minimist')
var os = require('os')
var path = require('path')
var WebTorrent = require('../')

var TMP = os.tmp

function usage () {
  var logo = fs.readFileSync(path.join(__dirname, 'ascii-logo.txt'), 'utf8')
  logo.split('\n').forEach(function (line) {
    console.log(chalk.bold(line.substring(0, 20) + chalk.red(line.substring(20))))
  })
  console.log('Usage: webtorrent [torrentId] {OPTIONS}')
  console.log('')
  console.log(chalk.bold('torrentId') + ' can be any of the following:')
  console.log('  * magnet uri')
  console.log('  * path to .torrent file (filesystem path or http url)')
  console.log('  * info hash (as hex string)')
  console.log('')
  console.log(chalk.bold('OPTIONS:'))
  console.log('  --vlc            autoplay in vlc')
  console.log('  --mplayer        autoplay in mplayer')
  console.log('  --omx [jack]     autoplay in omx (jack=local|hdmi)')
  console.log('')
  console.log('  -p, --port       change the http port               [default: 9000]')
  console.log('  -l, --list       list available files in torrent')
  console.log('  -t, --subtitles  load subtitles file')
  console.log('  -h, --help       display this help message')
  console.log('  -v, --version    print the current version')
  console.log('')
}

var argv = minimist(process.argv.slice(2))

var torrentId = argv._[0]

var port = Number(argv.port || argv.p) || 9000
var list = argv.list || argv.l
var subtitles = argv.subtitles || argv.t

if (argv.help || argv.h) {
  usage()
  process.exit(0)
}

if (argv.version || argv.v) {
  console.log(require('../package.json').version)
  process.exit(0)
}

if (!torrentId) {
  usage()
  process.exit(0)
}

var VLC_ARGS = '-q --video-on-top --play-and-exit'
var OMX_EXEC = 'omxplayer -r -o ' + (typeof argv.omx === 'string')
  ? argv.omx + ' '
  : 'hdmi '
var MPLAYER_EXEC = 'mplayer -ontop -really-quiet -noidx -loop 0 '

if (subtitles) {
  VLC_ARGS += ' --sub-file=' + subtitles
  OMX_EXEC += ' --subtitles ' + subtitles
  MPLAYER_EXEC += ' -sub ' + subtitles
}

var client = new WebTorrent({
  list: list
})
client.add(torrentId)

if (list) {
  // TODO
  client.on('torrent', function (torrent) {
    torrent.files.forEach(function (file, i) {
      console.log(i, file.name)
    })
    process.exit(0)
  })
  return
}

// var numeral = require('numeral')
// var address = require('network-address')
// var path = require('path')

// var ontorrent = function(torrent) {
//   var hotswaps = 0;

//   engine.on('hotswap', function() {
//     hotswaps++;
//   });

//   var started = Date.now();
//   var wires = engine.swarm.wires;
//   var swarm = engine.swarm;

//   var active = function(wire) {
//     return !wire.peerChoking;
//   };

//   engine.on('uninterested', function() {
//     engine.swarm.pause();
//   });

//   engine.on('interested', function() {
//     engine.swarm.resume();
//   });

//   engine.server.on('listening', function() {
//     var href = 'http://'+address()+':'+engine.server.address().port+'/';
//     var filename = engine.server.index.name.split('/').pop().replace(/\{|\}/g, '');

//     if (argv.vlc && process.platform === 'win32') {
//       var registry = require('windows-no-runnable').registry;
//       var key;
//       if (process.arch === 'x64') {
//         try {
//           key = registry('HKLM/Software/Wow6432Node/VideoLAN/VLC');
//         } catch (e) {}
//       } else {
//         try {
//           key = registry('HKLM/Software/VideoLAN/VLC');
//         } catch (err) {}
//       }

//       if (key) {
//         var vlcPath = key['InstallDir'].value + path.sep + 'vlc';
//         VLC_ARGS = VLC_ARGS.split(' ');
//         VLC_ARGS.unshift(href);
//         proc.execFile(vlcPath, VLC_ARGS);
//       }
//     } else {
//       if (argv.vlc) proc.exec('vlc '+href+' '+VLC_ARGS+' || /Applications/VLC.app/Contents/MacOS/VLC '+href+' '+VLC_ARGS);
//     }

//     if (argv.omx) proc.exec(OMX_EXEC+' '+href);
//     if (argv.mplayer) proc.exec(MPLAYER_EXEC+' '+href);

//     var bytes = function(num) {
//       return numeral(num).format('0.0b');
//     };

//     process.stdout.write(new Buffer('G1tIG1sySg==', 'base64')); // clear for drawing

//     var draw = function() {
//       var unchoked = engine.swarm.wires.filter(active);
//       var runtime = Math.floor((Date.now() - started) / 1000);
//       var linesremaining = clivas.height;
//       var peerslisted = 0;

//       clivas.clear();
//       clivas.line('{green:open} {bold:vlc} {green:and enter} {bold:'+href+'} {green:as the network address}');
//       clivas.line('');
//       clivas.line('{yellow:info} {green:streaming} {bold:'+filename+'} {green:-} {bold:'+bytes(swarm.downloadSpeed())+'/s} {green:from} {bold:'+unchoked.length +'/'+wires.length+'} {green:peers}    ');
//       clivas.line('{yellow:info} {green:downloaded} {bold:'+bytes(swarm.downloaded)+'} {green:and uploaded }{bold:'+bytes(swarm.uploaded)+'} {green:in }{bold:'+runtime+'s} {green:with} {bold:'+hotswaps+'} {green:hotswaps}     ');
//       clivas.line('{yellow:info} {green:peer queue size is} {bold:'+swarm.queued+'}     ');
//       clivas.line('{80:}');
//       linesremaining -= 8;

//       wires.every(function(wire) {
//         var tags = [];
//         if (wire.peerChoking) tags.push('choked');
//         clivas.line('{25+magenta:'+wire.peerAddress+'} {10:'+bytes(wire.downloaded)+'} {10+cyan:'+bytes(wire.downloadSpeed())+'/s} {15+grey:'+tags.join(', ')+'}   ');
//         peerslisted++;
//         return linesremaining-peerslisted > 4;
//       });
//       linesremaining -= peerslisted;

//       if (wires.length > peerslisted) {
//         clivas.line('{80:}');
//         clivas.line('... and '+(wires.length-peerslisted)+' more     ');
//       }

//       clivas.line('{80:}');
//       clivas.flush();
//     };

//     setInterval(draw, 500);
//     draw();
//   });

//   engine.server.once('error', function() {
//     engine.server.listen(0);
//   });

//   var onmagnet = function() {
//     clivas.clear();
//     clivas.line('{green:fetching torrent metadata from} {bold:'+engine.swarm.wires.length+'} {green:peers}');
//   };

//   if (typeof torrent === 'string' && torrent.indexOf('magnet:') === 0 && !argv.quiet) {
//     onmagnet();
//     engine.swarm.on('wire', onmagnet);
//   }

//   engine.on('ready', function() {
//     engine.swarm.removeListener('wire', onmagnet);
//     engine.server.listen(argv.port || 8888);
//   });
// };

// /**
//  * WebTorrent App UI
//  */
// function App (torrentManager) {
//   var self = this
//   if (!(self instanceof App)) return new App(torrentManager)

//   self.torrentManager = torrentManager

//   // Add existing torrents
//   self.torrentManager.torrents.forEach(function (torrent) {
//     self.addTorrent(torrent)
//   })

//   self.torrentManager.on('error', function (err) {
//     console.error(err)
//     // TODO: Show error in UI somehow
//   })

//   window.torrentManager.on('addTorrent', function (torrent) {
//     self.addTorrent(torrent)
//   })
//   window.torrentManager.on('removeTorrent', function (torrent) {
//     self.removeTorrent(torrent)
//   })

//   self.initUI()
// }

// App.prototype.addTorrent = function (torrent) {
//   var self = this
//   var $torrent = $(TEMPLATE.TORRENT)
//   self.updateTorrentUI($torrent, torrent)

//   $torrent.on('click', function () {
//     self.downloadTorrentFile(torrent)
//   })

//   $('#torrents').append($torrent)
//   self.updateUI()
// }

// App.prototype.updateUI = function () {
//   var self = this

//   self.torrentManager.torrents.forEach(function (torrent) {
//     var $torrent = $('#torrent_' + torrent.infoHash)
//     self.updateTorrentUI($torrent, torrent)
//   })

//   $('.overall-stats .ratio span').text(self.torrentManager.ratio)
//   $('.overall-stats .uploadSpeed span').text(humanize.filesize(self.torrentManager.uploadSpeed()))
//   $('.overall-stats .downloadSpeed span').text(humanize.filesize(self.torrentManager.downloadSpeed()))

//   // Number of transfers
//   if (self.torrentManager.torrents.length === 1)
//     $('.numTransfers').text('1 transfer')
//   else
//     $('.numTransfers').text(self.torrentManager.torrents.length + ' transfers')
// }

// App.prototype.updateTorrentUI = function ($torrent, torrent) {
//   if (!$torrent.attr('id'))
//     $torrent.attr('id', 'torrent_' + torrent.infoHash)

//   if (torrent.metadata)
//     $torrent.addClass('has-metadata')
//   else
//     $torrent.removeClass('has-metadata')

//   if (torrent.progress === 1)
//     $torrent.addClass('is-seeding')
//   else
//     $torrent.removeClass('is-seeding')

//   var timeRemaining
//   if (torrent.timeRemaining === Infinity) {
//     timeRemaining = 'remaining time unknown'
//   } else {
//     timeRemaining = moment(Date.now() + torrent.timeRemaining).fromNow() + '...'
//   }
//   $torrent.find('.timeRemaining').text(timeRemaining)

//   $torrent.find('.name').text(torrent.name)
//   $torrent.find('.downloaded').text(humanize.filesize(torrent.downloaded))
//   $torrent.find('.uploaded').text(humanize.filesize(torrent.uploaded))
//   $torrent.find('.length').text(humanize.filesize(torrent.length))
//   $torrent.find('.ratio').text(torrent.ratio)
//   $torrent.find('progress').attr('value', torrent.progress)
//   $torrent.find('.percentage').text((torrent.progress * 100).toFixed(2))
//   $torrent.find('.numPeers').text(torrent.swarm.numConns + torrent.swarm.numQueued)
//   $torrent.find('.numActivePeers').text(torrent.swarm.numPeers)
//   $torrent.find('.downloadSpeed').text(humanize.filesize(torrent.swarm.downloadSpeed()))
//   $torrent.find('.uploadSpeed').text(humanize.filesize(torrent.swarm.uploadSpeed()))
// }
<|endoftext|>


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

//var container, stats;

var camera, cameraTarget, scene, renderer, controls;

init();
animate();

function dims(){
    this.basL = 2000;
    this.basW = 1100;

}

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

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

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

    //x rail
    var xRL = 2000;
    var xRD = 25;

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

    //Gantry side
    var gSL = 300; //gantry side length

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

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

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

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

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

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

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

    //Make part objects (from shop.js)
    var baseObj = new shopBase(basL,basW,basH);
    var xRailObj = new shopSbrxx(xRL,xRD);
    var xLinBearObj = new shopSbrxxuu(xRD);
    var xBScrw = new shopRMxx05(xBSD, xBSL);
    var xBScrwFixSupp = new shopBkxx(xBSD);

    //make CSGs, with multiple copies where necessary
    var baseCsg = baseObj.makeCsg();
    var xRailCsg = xRailObj.makeCsg();
    xRailCsg = xRailCsg.union(xRailCsg.translate([0,baseObj.width - xRailObj.width,0]));
    var xLinBearCsg = xLinBearObj.makeCsg();
    xLinBearCsg = xLinBearCsg.union([xLinBearCsg.translate([gSL - xLinBearObj.length,0,0]),
                                     xLinBearCsg.translate([gSL - xLinBearObj.length,baseObj.width - xLinBearObj.width,0]),
                                     xLinBearCsg.translate([0,baseObj.width - xLinBearObj.width,0])]);

    //make THREE meshes, assemble and position
    var geom3;
    //base
    geom3 = THREE.CSG.fromCSG(baseCsg);
    var base = new THREE.Mesh(geom3,matConcrete);
    scene.add(base);
    //xRails
    geom3 = THREE.CSG.fromCSG(xRailCsg);
    var xRails = new THREE.Mesh(geom3,matAluminium);
    base.add(xRails);
    xRails.position.set(0,xRailObj.width/2,baseObj.thickness);
    //xLinBears
    geom3 = THREE.CSG.fromCSG(xLinBearCsg);
    var xLinBears = new THREE.Mesh(geom3,matAluminium);
    xRails.add(xLinBears);
    xLinBears.position.set(0,0,xRailObj.railZPos - xLinBearObj.railZPos);

    // Make base
//     var geom = baseObj.makeCsg().center("y");
//     var geom3 = THREE.CSG.fromCSG(geom);
//     base = new THREE.Mesh(geom3,matConcrete);
//     scene.add(base);

    //make xR
//     geom = xRailObj.makeCsg().translate([0,-basW/2 + xRailObj.width/2,basH]);
//     geom = geom.union(geom.mirroredY());
//     geom3 = THREE.CSG.fromCSG(geom);
//     var xR0 = new THREE.Mesh(geom3,matAluminium);
    //var xR1 = xR0.clone(false);
    //xR1.position.set(0,basW,0);

    //make xLinBear
//     geom = xLinBearObj.makeCsg().translate([0,0,xRailObj.railZPos - xLinBearObj.railZPos])
//     geom3 = THREE.CSG.fromCSG(geom);
//     var xLB = new THREE.Mesh(geom3,matAluminium);

//     xR0.add(xLB);
//     base.add(xR0);
    //xR0.add(ranSh);

}

//animation loop
function animate() {
    //var delta = clock.getDelta();
    requestAnimationFrame( animate );

    camera.up.set(0,0,1);
    controls.update();
    render();

}

//render function
function render() {

    renderer.render( scene, camera );
}
<commit_msg>debug variable syntax<commit_after>//var clock = new THREE.Clock();

//var container, stats;

var camera, cameraTarget, scene, renderer, controls;

init();
animate();

function dims(){
    this.basL = 2000;
    this.basW = 1100;

}

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

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

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

    //x rail
    var xRL = 2000;
    var xRD = 25;

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

    //Gantry side
    var gSL = 300; //gantry side length

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

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

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

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

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

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

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

    //Make part objects (from shop.js)
    var baseObj = new shopBase(basL,basW,basH);
    var xRailObj = new shopSbrxx(xRL,xRD);
    var xLinBearObj = new shopSbrxxuu(xRD);
    var xBScrw = new shopRmxx05(xBSD, xBSL);
    var xBScrwFixSupp = new shopBkxx(xBSD);

    //make CSGs, with multiple copies where necessary
    var baseCsg = baseObj.makeCsg();
    var xRailCsg = xRailObj.makeCsg();
    xRailCsg = xRailCsg.union(xRailCsg.translate([0,baseObj.width - xRailObj.width,0]));
    var xLinBearCsg = xLinBearObj.makeCsg();
    xLinBearCsg = xLinBearCsg.union([xLinBearCsg.translate([gSL - xLinBearObj.length,0,0]),
                                     xLinBearCsg.translate([gSL - xLinBearObj.length,baseObj.width - xLinBearObj.width,0]),
                                     xLinBearCsg.translate([0,baseObj.width - xLinBearObj.width,0])]);

    //make THREE meshes, assemble and position
    var geom3;
    //base
    geom3 = THREE.CSG.fromCSG(baseCsg);
    var base = new THREE.Mesh(geom3,matConcrete);
    scene.add(base);
    //xRails
    geom3 = THREE.CSG.fromCSG(xRailCsg);
    var xRails = new THREE.Mesh(geom3,matAluminium);
    base.add(xRails);
    xRails.position.set(0,xRailObj.width/2,baseObj.thickness);
    //xLinBears
    geom3 = THREE.CSG.fromCSG(xLinBearCsg);
    var xLinBears = new THREE.Mesh(geom3,matAluminium);
    xRails.add(xLinBears);
    xLinBears.position.set(0,0,xRailObj.railZPos - xLinBearObj.railZPos);

    // Make base
//     var geom = baseObj.makeCsg().center("y");
//     var geom3 = THREE.CSG.fromCSG(geom);
//     base = new THREE.Mesh(geom3,matConcrete);
//     scene.add(base);

    //make xR
//     geom = xRailObj.makeCsg().translate([0,-basW/2 + xRailObj.width/2,basH]);
//     geom = geom.union(geom.mirroredY());
//     geom3 = THREE.CSG.fromCSG(geom);
//     var xR0 = new THREE.Mesh(geom3,matAluminium);
    //var xR1 = xR0.clone(false);
    //xR1.position.set(0,basW,0);

    //make xLinBear
//     geom = xLinBearObj.makeCsg().translate([0,0,xRailObj.railZPos - xLinBearObj.railZPos])
//     geom3 = THREE.CSG.fromCSG(geom);
//     var xLB = new THREE.Mesh(geom3,matAluminium);

//     xR0.add(xLB);
//     base.add(xR0);
    //xR0.add(ranSh);

}

//animation loop
function animate() {
    //var delta = clock.getDelta();
    requestAnimationFrame( animate );

    camera.up.set(0,0,1);
    controls.update();
    render();

}

//render function
function render() {

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


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

//var container, stats;

var camera, cameraTarget, scene, renderer, controls;

init();
animate();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    //Make part objects (from shop.js)
    var baseObj = new shopSheet(basL,basW,basH);
    var sideBedObj = new shopSheet(sideBedL,sideBedW,sideBedH);
    var xRailObj = new shopSbrxx(xRL,xRD);
    var xLinBearObj = new shopSbrxxuu(xRD);
    var xBScrwObj = new shopRmxx05(xBSD, xBSL);
    var xBScrwFixSuppObj = new shopBkxx(xBSD);
    var xCarAngObj = new shopAluAngle(xCAW,xCAH,xCAT,xCAL);
    var yRailObj = new shopSbrxx(yRL,yRD);

    //make CSGs, and where applicable copies, to be merged into a single geometry
    var baseCsg = baseObj.makeCsg();
        baseCsg = baseCsg.center("y");
    var sideBedCsg = sideBedObj.makeCsg();
        sideBedCsg = sideBedCsg.union(sideBedCsg.translate([0,baseObj.width - sideBedObj.width + 2*sideBedO,0])).center("y");
    var xRailCsg = xRailObj.makeCsg();
        xRailCsg = xRailCsg.union(xRailCsg.translate([0,baseObj.width - xRailObj.width,0])).center("y"); //outside of linear bearings set equal to yRail length
    var xLinBearCsg = xLinBearObj.makeCsg();
        xLinBearCsg = xLinBearCsg.union(xLinBearCsg.translate([gSL - xLinBearObj.length,0,0]));
        xLinBearCsg = xLinBearCsg.union(xLinBearCsg.translate([0,baseObj.width - xRailObj.width,0])).center("y");
    var xCarAngCsg = xCarAngObj.makeCsg();
        xCarAngCsg = xCarAngCsg.union(xCarAngCsg.mirroredY().translate([0,baseObj.width + 2*xCAT,0])).center("y");
//     var xBScrwFixSuppCsg = xBScrwFixSuppObj.makeCsg();
//         xBScrwFixSuppCsg = xBScrwFixSuppCsg.union(xBScrwFixSuppCsg.translate([0,yRailObj.length + xBScrwFixSuppObj.width,0])).center("y");
//     var xBScrwCsg = xBScrwObj.makeCsg();
//         xBScrwCsg = xBScrwCsg.union(xBScrwCsg.translate([0,yRailObj.length + xBScrwFixSuppObj.width,0])).center("y");

    //make THREE meshes, assemble and position
    var geom3;
    //base
    geom3 = THREE.CSG.fromCSG(baseCsg);
    var base = new THREE.Mesh(geom3,matConcrete);
    scene.add(base);
    //side Bed
    geom3 = THREE.CSG.fromCSG(sideBedCsg);
    var sideBed = new THREE.Mesh(geom3,matMelamine);
    base.add(sideBed);
    sideBed.position.set(0,0,baseObj.thickness);
    //xRails
    geom3 = THREE.CSG.fromCSG(xRailCsg);
    var xRails = new THREE.Mesh(geom3,matAluminium);
    sideBed.add(xRails);
    xRails.position.set(0,0,sideBedObj.thickness);
    //xLinBears
    geom3 = THREE.CSG.fromCSG(xLinBearCsg);
    var xLinBears = new THREE.Mesh(geom3,matAluminium);
    xRails.add(xLinBears);
    xLinBears.position.set(gSX,0,xRailObj.railZPos - xLinBearObj.railZPos);
    //xCarAng
    geom3 = THREE.CSG.fromCSG(xCarAngCsg);
    var xCarAng = new THREE.Mesh(geom3,matAluminium);
    xLinBears.add(xCarAng);
    xCarAng.position.set(0,-xCAT,xLinBearObj.height);
//     //x ballscrew fixed support
//     geom3 = THREE.CSG.fromCSG(xBScrwFixSuppCsg);
//     var xBScrwFixSupp = new THREE.Mesh(geom3,matAluminium);
//     sideBed.add(xBScrwFixSupp);
//     xBScrwFixSupp.position.set(0,0,sideBedObj.thickness);
//     //x ballscrew
//     geom3 = THREE.CSG.fromCSG(xBScrwCsg);
//     var xBScrw = new THREE.Mesh(geom3,matAluminium);
//     xBScrwFixSupp.add(xBScrw);
//     xBScrw.position.set(xBScrwFixSuppObj.thick -xBScrwObj.threadStart,0,xBScrwFixSuppObj.bscrewZPos);

    // Make base
//     var geom = baseObj.makeCsg().center("y");
//     var geom3 = THREE.CSG.fromCSG(geom);
//     base = new THREE.Mesh(geom3,matConcrete);
//     scene.add(base);

    //make xR
//     geom = xRailObj.makeCsg().translate([0,-basW/2 + xRailObj.width/2,basH]);
//     geom = geom.union(geom.mirroredY());
//     geom3 = THREE.CSG.fromCSG(geom);
//     var xR0 = new THREE.Mesh(geom3,matAluminium);
    //var xR1 = xR0.clone(false);
    //xR1.position.set(0,basW,0);

    //make xLinBear
//     geom = xLinBearObj.makeCsg().translate([0,0,xRailObj.railZPos - xLinBearObj.railZPos])
//     geom3 = THREE.CSG.fromCSG(geom);
//     var xLB = new THREE.Mesh(geom3,matAluminium);

//     xR0.add(xLB);
//     base.add(xR0);
    //xR0.add(ranSh);

}

//animation loop
function animate() {
    //var delta = clock.getDelta();
    requestAnimationFrame( animate );

    camera.up.set(0,0,1);
    controls.update();
    render();

}

//render function
function render() {

    renderer.render( scene, camera );
}
<commit_msg>tweak camera settings<commit_after>//var clock = new THREE.Clock();

//var container, stats;

var camera, cameraTarget, scene, renderer, controls;

init();
animate();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    //Make part objects (from shop.js)
    var baseObj = new shopSheet(basL,basW,basH);
    var sideBedObj = new shopSheet(sideBedL,sideBedW,sideBedH);
    var xRailObj = new shopSbrxx(xRL,xRD);
    var xLinBearObj = new shopSbrxxuu(xRD);
    var xBScrwObj = new shopRmxx05(xBSD, xBSL);
    var xBScrwFixSuppObj = new shopBkxx(xBSD);
    var xCarAngObj = new shopAluAngle(xCAW,xCAH,xCAT,xCAL);
    var yRailObj = new shopSbrxx(yRL,yRD);

    //make CSGs, and where applicable copies, to be merged into a single geometry
    var baseCsg = baseObj.makeCsg();
        baseCsg = baseCsg.center("y");
    var sideBedCsg = sideBedObj.makeCsg();
        sideBedCsg = sideBedCsg.union(sideBedCsg.translate([0,baseObj.width - sideBedObj.width + 2*sideBedO,0])).center("y");
    var xRailCsg = xRailObj.makeCsg();
        xRailCsg = xRailCsg.union(xRailCsg.translate([0,baseObj.width - xRailObj.width,0])).center("y"); //outside of linear bearings set equal to yRail length
    var xLinBearCsg = xLinBearObj.makeCsg();
        xLinBearCsg = xLinBearCsg.union(xLinBearCsg.translate([gSL - xLinBearObj.length,0,0]));
        xLinBearCsg = xLinBearCsg.union(xLinBearCsg.translate([0,baseObj.width - xRailObj.width,0])).center("y");
    var xCarAngCsg = xCarAngObj.makeCsg();
        xCarAngCsg = xCarAngCsg.union(xCarAngCsg.mirroredY().translate([0,baseObj.width + 2*xCAT,0])).center("y");
//     var xBScrwFixSuppCsg = xBScrwFixSuppObj.makeCsg();
//         xBScrwFixSuppCsg = xBScrwFixSuppCsg.union(xBScrwFixSuppCsg.translate([0,yRailObj.length + xBScrwFixSuppObj.width,0])).center("y");
//     var xBScrwCsg = xBScrwObj.makeCsg();
//         xBScrwCsg = xBScrwCsg.union(xBScrwCsg.translate([0,yRailObj.length + xBScrwFixSuppObj.width,0])).center("y");

    //make THREE meshes, assemble and position
    var geom3;
    //base
    geom3 = THREE.CSG.fromCSG(baseCsg);
    var base = new THREE.Mesh(geom3,matConcrete);
    scene.add(base);
    //side Bed
    geom3 = THREE.CSG.fromCSG(sideBedCsg);
    var sideBed = new THREE.Mesh(geom3,matMelamine);
    base.add(sideBed);
    sideBed.position.set(0,0,baseObj.thickness);
    //xRails
    geom3 = THREE.CSG.fromCSG(xRailCsg);
    var xRails = new THREE.Mesh(geom3,matAluminium);
    sideBed.add(xRails);
    xRails.position.set(0,0,sideBedObj.thickness);
    //xLinBears
    geom3 = THREE.CSG.fromCSG(xLinBearCsg);
    var xLinBears = new THREE.Mesh(geom3,matAluminium);
    xRails.add(xLinBears);
    xLinBears.position.set(gSX,0,xRailObj.railZPos - xLinBearObj.railZPos);
    //xCarAng
    geom3 = THREE.CSG.fromCSG(xCarAngCsg);
    var xCarAng = new THREE.Mesh(geom3,matAluminium);
    xLinBears.add(xCarAng);
    xCarAng.position.set(0,-xCAT,xLinBearObj.height);
//     //x ballscrew fixed support
//     geom3 = THREE.CSG.fromCSG(xBScrwFixSuppCsg);
//     var xBScrwFixSupp = new THREE.Mesh(geom3,matAluminium);
//     sideBed.add(xBScrwFixSupp);
//     xBScrwFixSupp.position.set(0,0,sideBedObj.thickness);
//     //x ballscrew
//     geom3 = THREE.CSG.fromCSG(xBScrwCsg);
//     var xBScrw = new THREE.Mesh(geom3,matAluminium);
//     xBScrwFixSupp.add(xBScrw);
//     xBScrw.position.set(xBScrwFixSuppObj.thick -xBScrwObj.threadStart,0,xBScrwFixSuppObj.bscrewZPos);

    // Make base
//     var geom = baseObj.makeCsg().center("y");
//     var geom3 = THREE.CSG.fromCSG(geom);
//     base = new THREE.Mesh(geom3,matConcrete);
//     scene.add(base);

    //make xR
//     geom = xRailObj.makeCsg().translate([0,-basW/2 + xRailObj.width/2,basH]);
//     geom = geom.union(geom.mirroredY());
//     geom3 = THREE.CSG.fromCSG(geom);
//     var xR0 = new THREE.Mesh(geom3,matAluminium);
    //var xR1 = xR0.clone(false);
    //xR1.position.set(0,basW,0);

    //make xLinBear
//     geom = xLinBearObj.makeCsg().translate([0,0,xRailObj.railZPos - xLinBearObj.railZPos])
//     geom3 = THREE.CSG.fromCSG(geom);
//     var xLB = new THREE.Mesh(geom3,matAluminium);

//     xR0.add(xLB);
//     base.add(xR0);
    //xR0.add(ranSh);

}

//animation loop
function animate() {
    //var delta = clock.getDelta();
    requestAnimationFrame( animate );

    camera.up.set(0,0,1);
    controls.update();
    render();

}

//render function
function render() {

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


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

var child = require('child_process');

var CPFGenerator = (function() {
  'use strict';

  var self = {};

  function isValid(numbers) {
    var invalid_numbers = [
      '111111111',
      '222222222',
      '333333333',
      '444444444',
      '555555555',
      '666666666',
      '777777777',
      '888888888',
      '999999999',
      '000000000'
    ];

    return (numbers === undefined || invalid_numbers.indexOf(numbers) > -1 || numbers.toString().length < 9) ? false : true;
  }

  function random(max) {
    return Math.floor(Math.random() * (max + 1));
  }

  function getNumbers() {
    var numbers = [], i = 9;

    while(i--) {
      numbers.push(random(9));
    }

    return numbers.join('');
  }

  function getVerificationDigits(number) {
    var first, second, sum1, sum2;

    number = number.toString().split('');

    function getDigit(sum) {
      sum = sum % 11;
      return (sum < 2) ? 0 : 11 - sum;
    }

    sum1 = number.map(function(val, index) {
        return val * (10 - index);
      }).reduce(function(a, b) {
        return a + b;
      });

    first = getDigit(sum1);

    sum2 = number.concat(first).map(function(val, index) {
        return val * (11 - index);
      }).reduce(function(a, b) {
        return a + b;
      });

    second = getDigit(sum2);

    return [first, second].join('');
  }

  self.digits = function(numbers) {
    if (isValid(numbers)) return getVerificationDigits(numbers);
  };

  self.make = function(numbers) {
    numbers = numbers || getNumbers();
    if (isValid(numbers)) {
      return [numbers, '-', getVerificationDigits(numbers)].join('');
    } else {
      console.log('Erro: o número deve conter 9 digitos.');
      return null;
    }
  };

  return self;
}());

var arg = (process.argv[2] || '');
var cpf = CPFGenerator.make(arg);

if (cpf !== null) {
  child.exec(
    ("echo \"" + cpf + "\" | tr -d '\n' | pbcopy"),
    function(err, stdout, stderr) {
      if (err) {
        console.log('Não foi possível copiar o CPF \"' + cpf + '\" para a área de transferência.');
        console.log('Erro: ' + stderr);
      } else {
        console.log('==> CPF ' + cpf + ' copiado!');
      }
      process.exit(0);
    }
  );
}
<commit_msg>melhorado a verificação do número<commit_after>#! /usr/local/bin/node

var child = require('child_process');

var CPFGenerator = (function() {
  'use strict';

  var self = {};

  function isValid(numbers) {
    var invalid_numbers = [
      '111111111',
      '222222222',
      '333333333',
      '444444444',
      '555555555',
      '666666666',
      '777777777',
      '888888888',
      '999999999',
      '000000000'
    ];

    return (numbers === undefined || invalid_numbers.indexOf(numbers) > -1 || numbers.toString().length !== 9) ? false : true;
  }

  function random(max) {
    return Math.floor(Math.random() * (max + 1));
  }

  function getNumbers() {
    var numbers = [], i = 9;

    while(i--) {
      numbers.push(random(9));
    }

    return numbers.join('');
  }

  function getVerificationDigits(number) {
    var first, second, sum1, sum2;

    number = number.toString().split('');

    function getDigit(sum) {
      sum = sum % 11;
      return (sum < 2) ? 0 : 11 - sum;
    }

    sum1 = number.map(function(val, index) {
        return val * (10 - index);
      }).reduce(function(a, b) {
        return a + b;
      });

    first = getDigit(sum1);

    sum2 = number.concat(first).map(function(val, index) {
        return val * (11 - index);
      }).reduce(function(a, b) {
        return a + b;
      });

    second = getDigit(sum2);

    return [first, second].join('');
  }

  self.digits = function(numbers) {
    if (isValid(numbers)) return getVerificationDigits(numbers);
  };

  self.make = function(numbers) {
    numbers = numbers || getNumbers();
    if (isValid(numbers)) {
      return [numbers, '-', getVerificationDigits(numbers)].join('');
    } else {
      console.log('Erro: o número deve conter 9 digitos.');
      return null;
    }
  };

  return self;
}());

var arg = (process.argv[2] || '');
var cpf = CPFGenerator.make(arg);

if (cpf !== null) {
  child.exec(
    ("echo \"" + cpf + "\" | tr -d '\n' | pbcopy"),
    function(err, stdout, stderr) {
      if (err) {
        console.log('Não foi possível copiar o CPF \"' + cpf + '\" para a área de transferência.');
        console.log('Erro: ' + stderr);
      } else {
        console.log('==> CPF ' + cpf + ' copiado!');
      }
      process.exit(0);
    }
  );
}
<|endoftext|>


<commit_before>/*jslint browser: true, indent: 2, nomen: true, plusplus: true */
/*global _: true */
/*global $j: true */
/*global jQuery: true */
/*global console: true */

(function () {
  "use strict";

  var script;

  function computedCssProperties(elt, pseudoclass) {
    var style = window.getComputedStyle ? window.getComputedStyle(elt, pseudoclass || null) : elt.currentStyle;
    return _.reduce(_.keys(style),
      function (memo, prop) {
        var styleValue = style.getPropertyValue(prop);
        if (styleValue) {
          memo[prop] = styleValue;
        }
        return memo;
      }, {}) || {};
  }

  function filterKeys(obj, valid_keys) {
    return _.reduce(
      _.intersection(_.keys(obj), valid_keys),
      function (result, key) {
        result[key] = obj[key];
        return result;
      },
      {}
    );
  }

  function objectIntersection(array) {
    function simpleIntersection(a, b) {
      if (typeof a !== 'object' || typeof b !== 'object') {
        return {};
      }
      return filterKeys(a, _.intersection(_.keys(a), _.keys(b)).filter(function (key) {
        return _.isEqual(a[key], b[key]);
      }));
    }
    function repeatedly(f) {
      return function (args) {
        if (args.length === 0) { return {}; }
        var seed = args.pop();
        return _.reduce(args, function (memo, obj) { return f(memo, obj); }, seed);
      };
    }

    return repeatedly(simpleIntersection)(array);
  }

  function objectDifference(a, b) {
    if (typeof a !== 'object' || typeof b !== 'object') {
      return a;
    }
    return filterKeys(a, _.difference(_.keys(a), _.keys(b)));
  }

  function cartesianProduct() {
    return _.reduce(arguments, function (mtrx, vals) {
      return _.reduce(vals, function (array, val) {
        return array.concat(
          _.map(mtrx, function (row) { return row.concat(val); })
        );
      }, []);
    }, [[]]);
  }

  function commonStyle(nodes) {
    return objectIntersection(_.map(nodes, function (k) { return $j(k).data('style') || {}; }));
  }

  function liftHeritable(node) {
    node.children().each(function () { liftHeritable($j(this)); });

    var heritable = [
      'cursor', 'font-family', 'font-weight', 'font-stretch', 'font-style',
      'font-size', 'font-size-adjust', 'font', 'font-synthesis', 'font-kerning',
      'font-variant-ligatures', 'font-variant-position', 'font-variant-caps',
      'font-variant-numeric', 'font-variant-alternatives', 'font-variant-east-asian',
      'font-variant', 'font-feature-settings', 'font-language-override', 'text-transform',
      'white-space', 'tab-size', 'line-break', 'word-break', 'hyphens', 'word-wrap',
      'overflow-wrap', 'text-align', 'text-align-last', 'text-justify', 'word-spacing',
      'letter-spacing', 'text-indent', 'hanging-punctuation', 'text-decoration-skip',
      'text-underline-skip', 'text-emphasis-style', 'text-emphasis-color', 'text-emphasis',
      'text-emphasis-position', 'text-shadow', 'color', 'border-collapse', 'border-spacing',
      'caption-side', 'direction', 'elevation', 'empty-cells', 'line-height', 'list-style-image',
      'list-style-position', 'list-style-type', 'list-style', 'orphans', 'pitch-range',
      'pitch', 'quotes', 'richness', 'speak-header', 'speak-numeral', 'speak-punctuation',
      'speak', 'speech-rate', 'stress', 'visibility', 'voice-family', 'volume', 'widows'];

    node.children().each(function (i, kid) {
      var common = filterKeys(commonStyle([node, $j(kid)]), heritable);
      $j(kid).data('style', objectDifference($j(kid).data('style'), common));
    });
  }

  function defaultDisplayForTag(tag) {
    return {
      A: 'inline',
      ABBR: 'inline',
      ADDRESS: 'block',
      AREA: 'none',
      ARTICLE: 'block',
      ASIDE: 'block',
      AUDIO: 'inline',
      B: 'inline',
      BASE: 'inline',
      BB: 'inline',
      BDI: 'inline',
      BDO: 'inline',
      BLOCKQUOTE: 'block',
      BODY: 'block',
      BR: 'inline',
      BUTTON: 'inline-block',
      CANVAS: 'inline',
      CAPTION: 'table-caption',
      CITE: 'inline',
      CODE: 'inline',
      COMMAND: 'inline',
      DATA: 'inline',
      DATAGRID: 'inline',
      DATALIST: 'none',
      DD: 'block',
      DEL: 'inline',
      DETAILS: 'block',
      DFN: 'inline',
      DIV: 'block',
      DL: 'block',
      DT: 'block',
      EM: 'inline',
      EMBED: 'inline',
      EVENTSOURCE: 'inline',
      FIELDSET: 'block',
      FIGCAPTION: 'block',
      FIGURE: 'block',
      FOOTER: 'block',
      FORM: 'block',
      H1: 'block',
      H2: 'block',
      H3: 'block',
      H4: 'block',
      H5: 'block',
      H6: 'block',
      HEADER: 'block',
      HGROUP: 'block',
      HR: 'block',
      I: 'inline',
      IFRAME: 'inline',
      IMG: 'inline-block',
      INPUT: 'inline-block',
      INS: 'inline',
      KBD: 'inline',
      KEYGEN: 'inline-block',
      LABEL: 'inline',
      LEGEND: 'block',
      LI: 'list-item',
      LINK: 'none',
      MAP: 'inline',
      MARK: 'inline',
      MENU: 'block',
      META: 'none',
      METER: 'inline-block',
      NAV: 'block',
      NOSCRIPT: 'inline',
      OBJECT: 'inline',
      OL: 'block',
      OPTGROUP: 'inline',
      OPTION: 'inline',
      OUTPUT: 'inline',
      P: 'block',
      PARAM: 'none',
      PRE: 'block',
      PROGRESS: 'inline-block',
      Q: 'inline',
      RP: 'inline',
      RT: 'inline',
      RUBY: 'inline',
      S: 'inline',
      SAMP: 'inline',
      SCRIPT: 'none',
      SECTION: 'block',
      SELECT: 'inline-block',
      SMALL: 'inline',
      SOURCE: 'inline',
      SPAN: 'inline',
      STRONG: 'inline',
      STYLE: 'none',
      SUB: 'inline',
      SUMMARY: 'block',
      SUP: 'inline',
      TABLE: 'table',
      TBODY: 'table-row-group',
      TD: 'table-cell',
      TEXTAREA: 'inline-block',
      TFOOT: 'table-footer-group',
      TH: 'table-cell',
      THEAD: 'table-header-group',
      TIME: 'inline',
      TR: 'table-row',
      TRACK: 'inline',
      U: 'inline',
      UL: 'block',
      VAR: 'inline',
      VIDEO: 'inline'
    }[tag];
  }

  function stripDefaultStyles(node) {
    var defaults = { background: "rgba\\(0, 0, 0, 0\\) none repeat scroll 0% 0% \/ auto padding-box border-box",
      border: 'none', bottom: 'auto', clear: 'none', clip: 'auto', cursor: 'auto', margin: '^0px$', padding: '^0px$',
      direction: 'ltr', fill: '#000000', filter: 'none', float: 'none', kerning: '0', left: 'auto',
      mask: 'none', opacity: "1", outline: 'none', overflow: 'visible', position: 'static',
      resize: 'none', right: 'auto', stroke: 'none', top: 'auto', zoom: '1', height: 'auto', width: 'auto'};

    if (node.data('style')) {
      if (defaultDisplayForTag(node.prop("tagName")) === node.data('style').display) {
        delete node.data('style').display;
      }
      _.each(_.keys(defaults), function (def) {
        var prop = node.data('style')[def];
        if (prop && prop.match(new RegExp(defaults[def]))) {
          delete node.data('style')[def];
        }
      });
    }
    node.children().each(function () {
      stripDefaultStyles($j(this));
    });
  }

  function originatingSelectors(node, depth) {
    var base = {}, ret = {};
    base[node.prop("tagName")] = true;
    if (node.attr('class')) {
      _.each(node.attr('class').split(/\s+/), function (klass) {
        if (klass) {
          base['.' + klass] = true;
        }
      });
    }
    if (node.attr('id')) {
      base['#' + node.attr('id')] = true;
    }

    if (depth < 2) {
      return base;
    }
    node.children().each(function () {
      var notId = function (selector) { return selector[0] !== '#'; },
        kid_selectors = originatingSelectors($j(this), depth - 1);
      _.each(
        _.map(
          cartesianProduct(_.keys(base), _.filter(_.keys(kid_selectors), notId)),
          function (tuple) { return tuple.join(' '); }
        ),
        function (selector) { ret[selector] = true; }
      );
    });
    return ret;
  }

  function renderStyle(selector, properties) {
    if (!_.isEmpty(properties)) {
      console.log(selector + ' {');
      _.each(properties, function (val, key) {
        console.log("\t" + key + ': ' + val + ';');
      });
      console.log('}');
    }
  }

  function importance(choice) {
    return -(_.keys(choice.style).length * $j('html').find(choice.selector).length);
  }

  function onScriptsLoaded() {
    var root = $j('body'), selectors = {}, common, best;

    console.log("Computing styles...");
    $j('BODY, BODY *').each(function () {
      $j(this).data('style', computedCssProperties(this));
    });

    console.log("Lifting heritable styles...");
    liftHeritable(root);

    console.log("Stripping default styles...");
    stripDefaultStyles(root);

    console.log("Consolidating styles...\n");
    $j('BODY, BODY *').each(function () {
      var depth;
      for (depth = 1; depth <= 2; depth++) {
        $j.extend(selectors, originatingSelectors($j(this), depth));
      }
    });
    while (!_.isEmpty(selectors)) {
      common = _.map(_.keys(selectors), function (sel) {
        return { selector: sel, style: commonStyle($j('html').find(sel)) };
      });
      best   = _.sortBy(common, importance)[0];
      renderStyle(best.selector, best.style);
      $j(best.selector).each(function () {
        $j(this).data('style', objectDifference($j(this).data('style'), best.style));
      });
      delete selectors[best.selector];
    }
    console.log('/* Generated by CSS Ratiocinator */');
  }

  ////////////////////////////////////////////////////////////////////////////////////////
  // Load jQuery and underscore then begin the fun.
  console.log("Loading required external scripts...");
  script        = document.createElement("script");
  script.src    = "https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js";
  script.onload = function () {
    window.$j = jQuery.noConflict();
    jQuery.getScript(
      'https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.3.3/underscore-min.js',
      onScriptsLoaded
    );
  };
  document.getElementsByTagName("head")[0].appendChild(script);
}());
<commit_msg>Remove default yet heritable styles from root node<commit_after>/*jslint browser: true, indent: 2, nomen: true, plusplus: true */
/*global _: true */
/*global $j: true */
/*global jQuery: true */
/*global console: true */

(function () {
  "use strict";

  var script;

  function computedCssProperties(elt, pseudoclass) {
    var style = window.getComputedStyle ? window.getComputedStyle(elt, pseudoclass || null) : elt.currentStyle;
    return _.reduce(_.keys(style),
      function (memo, prop) {
        var styleValue = style.getPropertyValue(prop);
        if (styleValue) {
          memo[prop] = styleValue;
        }
        return memo;
      }, {}) || {};
  }

  function filterKeys(obj, valid_keys) {
    return _.reduce(
      _.intersection(_.keys(obj), valid_keys),
      function (result, key) {
        result[key] = obj[key];
        return result;
      },
      {}
    );
  }

  function objectIntersection(array) {
    function simpleIntersection(a, b) {
      if (typeof a !== 'object' || typeof b !== 'object') {
        return {};
      }
      return filterKeys(a, _.intersection(_.keys(a), _.keys(b)).filter(function (key) {
        return _.isEqual(a[key], b[key]);
      }));
    }
    function repeatedly(f) {
      return function (args) {
        if (args.length === 0) { return {}; }
        var seed = args.pop();
        return _.reduce(args, function (memo, obj) { return f(memo, obj); }, seed);
      };
    }

    return repeatedly(simpleIntersection)(array);
  }

  function objectDifference(a, b) {
    if (typeof a !== 'object' || typeof b !== 'object') {
      return a;
    }
    return filterKeys(a, _.difference(_.keys(a), _.keys(b)));
  }

  function cartesianProduct() {
    return _.reduce(arguments, function (mtrx, vals) {
      return _.reduce(vals, function (array, val) {
        return array.concat(
          _.map(mtrx, function (row) { return row.concat(val); })
        );
      }, []);
    }, [[]]);
  }

  function commonStyle(nodes) {
    return objectIntersection(_.map(nodes, function (k) { return $j(k).data('style') || {}; }));
  }

  function liftHeritable(node) {
    node.children().each(function () { liftHeritable($j(this)); });

    var heritable = [
      'cursor', 'font-family', 'font-weight', 'font-stretch', 'font-style',
      'font-size', 'font-size-adjust', 'font', 'font-synthesis', 'font-kerning',
      'font-variant-ligatures', 'font-variant-position', 'font-variant-caps',
      'font-variant-numeric', 'font-variant-alternatives', 'font-variant-east-asian',
      'font-variant', 'font-feature-settings', 'font-language-override', 'text-transform',
      'white-space', 'tab-size', 'line-break', 'word-break', 'hyphens', 'word-wrap',
      'overflow-wrap', 'text-align', 'text-align-last', 'text-justify', 'word-spacing',
      'letter-spacing', 'text-indent', 'hanging-punctuation', 'text-decoration-skip',
      'text-underline-skip', 'text-emphasis-style', 'text-emphasis-color', 'text-emphasis',
      'text-emphasis-position', 'text-shadow', 'color', 'border-collapse', 'border-spacing',
      'caption-side', 'direction', 'elevation', 'empty-cells', 'line-height', 'list-style-image',
      'list-style-position', 'list-style-type', 'list-style', 'orphans', 'pitch-range',
      'pitch', 'quotes', 'richness', 'speak-header', 'speak-numeral', 'speak-punctuation',
      'speak', 'speech-rate', 'stress', 'visibility', 'voice-family', 'volume', 'widows'];

    node.children().each(function (i, kid) {
      var common = filterKeys(commonStyle([node, $j(kid)]), heritable);
      $j(kid).data('style', objectDifference($j(kid).data('style'), common));
    });
  }

  function defaultDisplayForTag(tag) {
    return {
      A: 'inline',
      ABBR: 'inline',
      ADDRESS: 'block',
      AREA: 'none',
      ARTICLE: 'block',
      ASIDE: 'block',
      AUDIO: 'inline',
      B: 'inline',
      BASE: 'inline',
      BB: 'inline',
      BDI: 'inline',
      BDO: 'inline',
      BLOCKQUOTE: 'block',
      BODY: 'block',
      BR: 'inline',
      BUTTON: 'inline-block',
      CANVAS: 'inline',
      CAPTION: 'table-caption',
      CITE: 'inline',
      CODE: 'inline',
      COMMAND: 'inline',
      DATA: 'inline',
      DATAGRID: 'inline',
      DATALIST: 'none',
      DD: 'block',
      DEL: 'inline',
      DETAILS: 'block',
      DFN: 'inline',
      DIV: 'block',
      DL: 'block',
      DT: 'block',
      EM: 'inline',
      EMBED: 'inline',
      EVENTSOURCE: 'inline',
      FIELDSET: 'block',
      FIGCAPTION: 'block',
      FIGURE: 'block',
      FOOTER: 'block',
      FORM: 'block',
      H1: 'block',
      H2: 'block',
      H3: 'block',
      H4: 'block',
      H5: 'block',
      H6: 'block',
      HEADER: 'block',
      HGROUP: 'block',
      HR: 'block',
      I: 'inline',
      IFRAME: 'inline',
      IMG: 'inline-block',
      INPUT: 'inline-block',
      INS: 'inline',
      KBD: 'inline',
      KEYGEN: 'inline-block',
      LABEL: 'inline',
      LEGEND: 'block',
      LI: 'list-item',
      LINK: 'none',
      MAP: 'inline',
      MARK: 'inline',
      MENU: 'block',
      META: 'none',
      METER: 'inline-block',
      NAV: 'block',
      NOSCRIPT: 'inline',
      OBJECT: 'inline',
      OL: 'block',
      OPTGROUP: 'inline',
      OPTION: 'inline',
      OUTPUT: 'inline',
      P: 'block',
      PARAM: 'none',
      PRE: 'block',
      PROGRESS: 'inline-block',
      Q: 'inline',
      RP: 'inline',
      RT: 'inline',
      RUBY: 'inline',
      S: 'inline',
      SAMP: 'inline',
      SCRIPT: 'none',
      SECTION: 'block',
      SELECT: 'inline-block',
      SMALL: 'inline',
      SOURCE: 'inline',
      SPAN: 'inline',
      STRONG: 'inline',
      STYLE: 'none',
      SUB: 'inline',
      SUMMARY: 'block',
      SUP: 'inline',
      TABLE: 'table',
      TBODY: 'table-row-group',
      TD: 'table-cell',
      TEXTAREA: 'inline-block',
      TFOOT: 'table-footer-group',
      TH: 'table-cell',
      THEAD: 'table-header-group',
      TIME: 'inline',
      TR: 'table-row',
      TRACK: 'inline',
      U: 'inline',
      UL: 'block',
      VAR: 'inline',
      VIDEO: 'inline'
    }[tag];
  }

  function stripDefaultStyles(node) {
    var defaults = { background: "rgba\\(0, 0, 0, 0\\) none repeat scroll 0% 0% \/ auto padding-box border-box",
      border: 'none', bottom: 'auto', clear: 'none', clip: 'auto', cursor: 'auto', margin: '^0px$', padding: '^0px$',
      direction: 'ltr', fill: '#000000', filter: 'none', float: 'none', kerning: '0', left: 'auto',
      mask: 'none', opacity: "1", outline: 'none', overflow: 'visible', position: 'static',
      resize: 'none', right: 'auto', stroke: 'none', top: 'auto', zoom: '1', height: 'auto', width: 'auto'};

    if (node.data('style')) {
      if (defaultDisplayForTag(node.prop("tagName")) === node.data('style').display) {
        delete node.data('style').display;
      }
      _.each(_.keys(defaults), function (def) {
        var prop = node.data('style')[def];
        if (prop && prop.match(new RegExp(defaults[def]))) {
          delete node.data('style')[def];
        }
      });
    }
    node.children().each(function () {
      stripDefaultStyles($j(this));
    });
  }

  // Heritable styles with default values are tricky. Strip them
  // from the root node only.
  function stripRootDefaultStyles(root) {
    var defaults = {speak: 'normal', visibility: 'visible', orphans: 2, widows: 2};
    root.data('style',
      objectDifference(root.data('style'), defaults)
    );
  }

  function originatingSelectors(node, depth) {
    var base = {}, ret = {};
    base[node.prop("tagName")] = true;
    if (node.attr('class')) {
      _.each(node.attr('class').split(/\s+/), function (klass) {
        if (klass) {
          base['.' + klass] = true;
        }
      });
    }
    if (node.attr('id')) {
      base['#' + node.attr('id')] = true;
    }

    if (depth < 2) {
      return base;
    }
    node.children().each(function () {
      var notId = function (selector) { return selector[0] !== '#'; },
        kid_selectors = originatingSelectors($j(this), depth - 1);
      _.each(
        _.map(
          cartesianProduct(_.keys(base), _.filter(_.keys(kid_selectors), notId)),
          function (tuple) { return tuple.join(' '); }
        ),
        function (selector) { ret[selector] = true; }
      );
    });
    return ret;
  }

  function renderStyle(selector, properties) {
    if (!_.isEmpty(properties)) {
      console.log(selector + ' {');
      _.each(properties, function (val, key) {
        console.log("\t" + key + ': ' + val + ';');
      });
      console.log('}');
    }
  }

  function importance(choice) {
    return -(_.keys(choice.style).length * $j('html').find(choice.selector).length);
  }

  function onScriptsLoaded() {
    var root = $j('body'), selectors = {}, common, best;

    console.log("Computing styles...");
    $j('BODY, BODY *').each(function () {
      $j(this).data('style', computedCssProperties(this));
    });

    console.log("Lifting heritable styles...");
    liftHeritable(root);

    console.log("Stripping default styles...");
    stripDefaultStyles(root);
    stripRootDefaultStyles(root);

    console.log("Consolidating styles...\n");
    $j('BODY, BODY *').each(function () {
      var depth;
      for (depth = 1; depth <= 2; depth++) {
        $j.extend(selectors, originatingSelectors($j(this), depth));
      }
    });
    while (!_.isEmpty(selectors)) {
      common = _.map(_.keys(selectors), function (sel) {
        return { selector: sel, style: commonStyle($j('html').find(sel)) };
      });
      best   = _.sortBy(common, importance)[0];
      renderStyle(best.selector, best.style);
      $j(best.selector).each(function () {
        $j(this).data('style', objectDifference($j(this).data('style'), best.style));
      });
      delete selectors[best.selector];
    }
    console.log('/* Generated by CSS Ratiocinator */');
  }

  ////////////////////////////////////////////////////////////////////////////////////////
  // Load jQuery and underscore then begin the fun.
  console.log("Loading required external scripts...");
  script        = document.createElement("script");
  script.src    = "https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js";
  script.onload = function () {
    window.$j = jQuery.noConflict();
    jQuery.getScript(
      'https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.3.3/underscore-min.js',
      onScriptsLoaded
    );
  };
  document.getElementsByTagName("head")[0].appendChild(script);
}());
<|endoftext|>


<commit_before>var validateHTTP = require("./validateHTTP.js"),
    restify = require('restify'),
    request = require('request'),
    rand = require('csprng'),
    sha1 = require('sha1'),
    neo4j = require('node-neo4j');

function del(req, res, next, type) {
    if (type == "users") {
        var username = req.authorization.basic.username
        console.log('DELETE USER');
        console.log('DELETE ' + username);
        console.log('parameters supplied');
        var url = 'http://localhost:5984/users/' + username,
            db = new neo4j('http://localhost:7474');
        request.get(url, function(err, response, body) {
            console.log("request started");
            // if user is not found will send 404 error
            if (response.statusCode == 404) {
                return next(new restify.NotFoundError('User Not Found'));
            };
            if (response.statusCode == 200) {
                console.log("Everything 200");
                var body = JSON.parse(body),
                    rev = body._rev,
                    nodeid = body.nodeid;
                console.log(rev);
                console.log(nodeid);
                db.cypherQuery("start m = node(" + nodeid + ") match n<-[r]-m  return r", function(err, results) {
                    if (err) throw err;
                    if (results.data.length == 0) {
                        db.deleteNode(nodeid, function(err, node) {
                            if (err) throw err;
                            if (node === true) {
                                console.log("Node Deleted!");
                                request.del(url + "?rev=" + rev, function(err, response) {
                                    if (err) {
                                        return next(new restify.InternalServerError('Cant delete document'));
                                    };
                                    console.log("Deleted User!");
                                    res.send("Deleted User!");
                                    res.end();
                                });
                            } else {
                                console.log("Node not Deleted");
                                return next(new restify.InternalServerError('Cant delete node!'));
                            };
                        });
                    } else {
                        var resLength = results.data.length,
                            i = 0;
                        results.data.forEach(function(item) {
                            var id = item._id;
                            console.log(id);
                            i++;
                            console.log("Loggin id: " + id);
                            db.deleteRelationship(id, function (err, relationship) {
                                if (err) throw err;
                                if (relationship === true) {
                                    console.log("Deleted Relationship!");
                                    if (i == resLength) {
                                        db.deleteNode(nodeid, function(err, node) {
                                            if (err) throw err;
                                            if (node === true) {
                                                console.log("Node Deleted!");
                                                request.del(url + "?rev=" + rev, function (err, response) {
                                                    if(err) {
                                                        return next(new restify.InternalServerError('Cant delete document'));
                                                    };
                                                    console.log("Deleted User!");
                                                    res.send("Deleted User!");
                                                    res.end();
                                                });
                                            } else {
                                                console.log("Node not Deleted");
                                                return next(new restify.InternalServerError('Cant delete node!'));
                                            };
                                        });
                                    };
                                } else {
                                    console.log("Relationship not Deleted...");
                                    return next(new restify.InternalServerError('Cant delete Relationship!'));
                                };
                            });
                        });
                    };
                    console.log(results);
                })
            };
        });
    } else if (type == "business") {
        var businessName = req.authorization.basic.username
        console.log('DELETE BUSINESS');
        console.log('DELETE ' + businessName);
        validateHTTP.validateHTTP(req, res, next, "business");
        console.log('parameters supplied');
        var url = 'http://localhost:5984/business/' + businessName;
        request.get(url, function(err, response, body) {
            console.log("request started");
            // if business is not found will send 404 error
            if (response.statusCode == 404) {
                return next(new restify.NotFoundError('Business Not Found'));
            };
            if (response.statusCode == 200) {
                console.log("Everything 200");
                var body = JSON.parse(body),
                    rev = body._rev;
                db.cypherQuery("start m = node(" + nodeid + ") match n<-[r]-m  return r", function(err, results) {
                    if (err) throw err;
                    if (results.data.length == 0) {
                        db.deleteNode(nodeid, function (err, node) {
                            if (err) throw err;
                            if (node === true) {
                                console.log("Node Deleted!");
                                request.del(url + "?rev=" + rev, function (err, response) {
                                    if (err) {
                                        return next(new restify.InternalServerError('Cant delete document'));
                                    };
                                    console.log("Deleted Business!");
                                    res.send("Deleted Business!");
                                    res.end();
                                });
                            } else {
                                console.log("Node not Deleted");
                                return next(new restify.InternalServerError('Cant delete node!'));
                            };
                        });
                    } else {
                        var resLength = results.data.length,
                            i = 0;
                        results.data.forEach(function (item) {
                            var id = item._id;
                            console.log(id);
                            i++;
                            console.log("Loggin id: " + id);
                            db.deleteRelationship(id, function (err, relationship) {
                                if (err) throw err;
                                if (relationship === true) {
                                    console.log("Deleted Relationship!");
                                    if (i == resLength) {
                                        db.deleteNode(nodeid, function(err, node) {
                                            if (err) throw err;
                                            if (node === true) {
                                                console.log("Node Deleted!");
                                                request.del(url + "?rev=" + rev, function(err, response) {
                                                    if (err) {
                                                        return next(new restify.InternalServerError('Cant delete document'));
                                                    };
                                                    console.log("Deleted Bsuiness!");
                                                    res.send("Deleted Business!");
                                                    res.end();
                                                });
                                            } else {
                                                console.log("Node not Deleted");
                                                return next(new restify.InternalServerError('Cant delete node!'));
                                            };
                                        });
                                    };
                                } else {
                                    console.log("Relationship not Deleted...");
                                    return next(new restify.InternalServerError('Cant delete Relationship!'));
                                };
                            });
                        });
                    };
                    console.log(results);
                });
            };
        });
    } else {
        console.log("Error, Invalid Type!");
    };
};
module.exports.del = del;<commit_msg>status code fix<commit_after>var validateHTTP = require("./validateHTTP.js"),
    restify = require('restify'),
    request = require('request'),
    rand = require('csprng'),
    sha1 = require('sha1'),
    neo4j = require('node-neo4j');

function del(req, res, next, type) {
    if (type == "users") {
        var username = req.authorization.basic.username
        console.log('DELETE USER');
        console.log('DELETE ' + username);
        console.log('parameters supplied');
        var url = 'http://localhost:5984/users/' + username,
            db = new neo4j('http://localhost:7474');
        request.get(url, function(err, response, body) {
            console.log("request started");
            // if user is not found will send 404 error
            if (response.statusCode === 404) {
                return next(new restify.NotFoundError('User Not Found'));
            };
            if (response.statusCode === 200) {
                console.log("Everything 200");
                var body = JSON.parse(body),
                    rev = body._rev,
                    nodeid = body.nodeid;
                console.log(rev);
                console.log(nodeid);
                db.cypherQuery("start m = node(" + nodeid + ") match n<-[r]-m  return r", function(err, results) {
                    if (err) throw err;
                    if (results.data.length == 0) {
                        db.deleteNode(nodeid, function(err, node) {
                            if (err) throw err;
                            if (node === true) {
                                console.log("Node Deleted!");
                                request.del(url + "?rev=" + rev, function(err, response) {
                                    if (err) {
                                        return next(new restify.InternalServerError('Cant delete document'));
                                    };
                                    console.log("Deleted User!");
                                    res.send("Deleted User!");
                                    res.end();
                                });
                            } else {
                                console.log("Node not Deleted");
                                return next(new restify.InternalServerError('Cant delete node!'));
                            };
                        });
                    } else {
                        var resLength = results.data.length,
                            i = 0;
                        results.data.forEach(function(item) {
                            var id = item._id;
                            console.log(id);
                            i++;
                            console.log("Loggin id: " + id);
                            db.deleteRelationship(id, function (err, relationship) {
                                if (err) throw err;
                                if (relationship === true) {
                                    console.log("Deleted Relationship!");
                                    if (i == resLength) {
                                        db.deleteNode(nodeid, function(err, node) {
                                            if (err) throw err;
                                            if (node === true) {
                                                console.log("Node Deleted!");
                                                request.del(url + "?rev=" + rev, function (err, response) {
                                                    if(err) {
                                                        return next(new restify.InternalServerError('Cant delete document'));
                                                    };
                                                    console.log("Deleted User!");
                                                    res.send("Deleted User!");
                                                    res.end();
                                                });
                                            } else {
                                                console.log("Node not Deleted");
                                                return next(new restify.InternalServerError('Cant delete node!'));
                                            };
                                        });
                                    };
                                } else {
                                    console.log("Relationship not Deleted...");
                                    return next(new restify.InternalServerError('Cant delete Relationship!'));
                                };
                            });
                        });
                    };
                    console.log(results);
                })
            };
        });
    } else if (type == "business") {
        var businessName = req.authorization.basic.username
        console.log('DELETE BUSINESS');
        console.log('DELETE ' + businessName);
        validateHTTP.validateHTTP(req, res, next, "business");
        console.log('parameters supplied');
        var url = 'http://localhost:5984/business/' + businessName;
        request.get(url, function(err, response, body) {
            console.log("request started");
            // if business is not found will send 404 error
            if (response.statusCode === 404) {
                return next(new restify.NotFoundError('Business Not Found'));
            };
            if (response.statusCode === 200) {
                console.log("Everything 200");
                var body = JSON.parse(body),
                    rev = body._rev;
                db.cypherQuery("start m = node(" + nodeid + ") match n<-[r]-m  return r", function(err, results) {
                    if (err) throw err;
                    if (results.data.length == 0) {
                        db.deleteNode(nodeid, function (err, node) {
                            if (err) throw err;
                            if (node === true) {
                                console.log("Node Deleted!");
                                request.del(url + "?rev=" + rev, function (err, response) {
                                    if (err) {
                                        return next(new restify.InternalServerError('Cant delete document'));
                                    };
                                    console.log("Deleted Business!");
                                    res.send("Deleted Business!");
                                    res.end();
                                });
                            } else {
                                console.log("Node not Deleted");
                                return next(new restify.InternalServerError('Cant delete node!'));
                            };
                        });
                    } else {
                        var resLength = results.data.length,
                            i = 0;
                        results.data.forEach(function (item) {
                            var id = item._id;
                            console.log(id);
                            i++;
                            console.log("Loggin id: " + id);
                            db.deleteRelationship(id, function (err, relationship) {
                                if (err) throw err;
                                if (relationship === true) {
                                    console.log("Deleted Relationship!");
                                    if (i == resLength) {
                                        db.deleteNode(nodeid, function(err, node) {
                                            if (err) throw err;
                                            if (node === true) {
                                                console.log("Node Deleted!");
                                                request.del(url + "?rev=" + rev, function(err, response) {
                                                    if (err) {
                                                        return next(new restify.InternalServerError('Cant delete document'));
                                                    };
                                                    console.log("Deleted Bsuiness!");
                                                    res.send("Deleted Business!");
                                                    res.end();
                                                });
                                            } else {
                                                console.log("Node not Deleted");
                                                return next(new restify.InternalServerError('Cant delete node!'));
                                            };
                                        });
                                    };
                                } else {
                                    console.log("Relationship not Deleted...");
                                    return next(new restify.InternalServerError('Cant delete Relationship!'));
                                };
                            });
                        });
                    };
                    console.log(results);
                });
            };
        });
    } else {
        console.log("Error, Invalid Type!");
    };
};
module.exports.del = del;<|endoftext|>


<commit_before><commit_msg>Implement Get Subcampaign List REST<commit_after>var readSubcampaignModelLogic = require('../../logic/subcampaign/readSubcampaignModelLogic')
var subcampaignModelCheckerLogic = require('../../logic/subcampaign/subcampaignModelCheckerLogic')

var Input = {
  accountHashID: {
    required: true
  },
  campaignHashID: {
    required: true
  },
  filterObject: {
    required: false,
    formatter: function (param, connection, actionTemplate) {
      return JSON.parse(new Buffer(param, 'base64'))
    }
  },
  complexModel: {
    required: flase,
    default: function (param, connection, actionTemplate) {
      return false
    }
  }
}

exports.getSubcampaignListAction = {
  name: 'getSubcampaignListAction',
  description: 'Get Subcampaign List',
  inputs: Input,

  run: function (api, data, next) {
    subcampaignModelCheckerLogic.checkSubcampaignListForExistence(api.redisClient, accountHashID, campaignHashID, function (err, replies) {
      if (err) {
        data.response.error = err.error
        next(err)
      } else {
        if (data.params.complexModel) {
          readSubcampaignModelLogic.getSubcampaignListComplex(api.redisClient, data.params.campaignHashID, data.params.filterObject, function (err, replies) {
            if (err) {
              data.response.error = err.error
              next(err)
            } else {
              data.response.result = replies
              next()
            }
          })
        } else {
          readSubcampaignModelLogic.getSubcampaignList(api.redisClient, data.params.campaignHashID, data.params.filterObject, function (err, replies) {
            if (err) {
              data.response.error = err.error
              next(err)
            } else {
              data.response.result = replies
              next()
            }
          })
        }
      }
    })
  }
}<|endoftext|>