<commit_before>var util = require('util'),
events = require('events');

var MAX_ERROR_MS = 20;

function Cron(){
	var self = this,
	callbackLists = {},
	stoppers = {};

	// Returns a unique ID that you can pass to .stop(ID)
	// interval = 'second' | 'minute' | 'hour' | 'day'
	this.onThe = function onThe(interval, cb){
		var list = getOrCreateCallbackList(interval);
		var id = Math.random().toString();
		list[id] = cb;
		return id;
	}

	// Stops calling the callback identified by the passed ID
	// Actual timers are stopped once the last callback has been stopped.
	this.clear = function(id_to_stop){
		for(var interval in callbackLists){
			var empty = true,
			list = callbackLists[interval];

			for(var id in list){
				if(id == id_to_stop){
					delete list[id];
				} else {
					empty = false;
				}
			}

			if(empty){
				stopInterval(interval)
			}
		}
	}

	function registerInterval(frequency, cb){
		var interval, timeout, nextTime;
		scheduleIntervalSoonest();

		// Schedule the interval to start at the next time slot i.e. round(current) + 1
		function scheduleInterval(){
			calculateNextTime();
			timer = setTimeout(startInterval, nextTime - Date.now());
		}

		// Schedule the interval to start at the soonest time slot i.e. floor(current) + 1
		function scheduleIntervalSoonest(){
			calculateNextTime('floor');
			timer = setTimeout(startInterval, nextTime - Date.now());
		}

		function startInterval(){
			calculateNextTime();
			interval = setInterval(checkAndExecute, Cron.time.distanceInMs(frequency));
			cb()
		}

		function calculateNextTime(round_func){
			nextTime = Cron.time.roundToNext(frequency, null, round_func).getTime();
		}

		function checkAndExecute(){
			var cur = Date.now();
			var oldNext = nextTime;
			calculateNextTime();
			if(Math.abs(oldNext - cur) > MAX_ERROR_MS){
				console.log(" =======  Rescheduling: " + (oldNext - cur));
				clearInterval(interval);
				scheduleInterval();
			}

			cb();
		}

		callbackLists[frequency]
		stoppers[frequency] = function(){
			clearInterval(interval);
			clearTimeout(timeout);
		};
	}

	function stopInterval(interval){
		delete callbackLists[interval];
		var stopper = stoppers[interval]();
		if(stopper){
			stopper()
			delete stoppers[interval];
		}
	}

	function getOrCreateCallbackList(interval){
		if(callbackLists[interval]) return callbackLists[interval];

		var list = callbackLists[interval] = {};
		registerInterval(interval, function(){
			for(var id in list){
				list[id]();
			}
		});

		return list;
	}
}

util.inherits(Cron, events.EventEmitter);

Cron = new Cron();

Cron.math = {
	round: function round(num, divisor){
		return Math.round(num / divisor) * divisor;
	},

	ceil: function round(num, divisor){
		return Math.ceil(num / divisor) * divisor;
	},

	floor: function round(num, divisor){
		return Math.floor(num / divisor) * divisor;
	}
}

Cron.time = {
	distanceInMs: function(length){
		var t = 1;
		switch(length){
			case 'day':	   return 1000 * 60 * 60 * 24;
			case 'hour':   return 1000 * 60 * 60;
			case 'minute': return 1000 * 60;
			case 'second': return 1000;
		}
	},

	beginningOf: function beginningOf(t, part){
		switch(part){
			case 'day':	   t.setUTCHours(0);
			case 'hour':   t.setUTCMinutes(0);
			case 'minute': t.setUTCSeconds(0);
			case 'second': t.setUTCMilliseconds(0);
		}
	},

	roundToNext: function roundToNext(period, start, round_func){
		var t = start || new Date();
		round_func = Cron.math[round_func || 'round'];

		switch(period){
			case 'second':
				t.setUTCMilliseconds(round_func(t.getUTCMilliseconds(), 1000) + 1000);
				break;
			case 'minute':
				t.setUTCSeconds(round_func(t.getUTCSeconds(), 60) + 60);
				this.beginningOf(t, 'minute');
				break;
			case 'hour':
				t.setUTCMinutes(round_func(t.getUTCMinutes(), 60) + 60);
				this.beginningOf(t, 'hour');
				break;
			case 'day':
				t.setUTCHours(round_func(t.getUTCHours(), 24) + 24);
				this.beginningOf(t, 'day');
				break;
		}
		return t;
	}
}

module.exports = Cron;<commit_msg>Add generic roundTo() function to Cron.js<commit_after>var util = require('util'),
events = require('events');

var MAX_ERROR_MS = 20;

function Cron(){
	var self = this,
	callbackLists = {},
	stoppers = {};

	// Returns a unique ID that you can pass to .stop(ID)
	// interval = 'second' | 'minute' | 'hour' | 'day'
	this.onThe = function onThe(interval, cb){
		var list = getOrCreateCallbackList(interval);
		var id = Math.random().toString();
		list[id] = cb;
		return id;
	}

	// Stops calling the callback identified by the passed ID
	// Actual timers are stopped once the last callback has been stopped.
	this.clear = function(id_to_stop){
		for(var interval in callbackLists){
			var empty = true,
			list = callbackLists[interval];

			for(var id in list){
				if(id == id_to_stop){
					delete list[id];
				} else {
					empty = false;
				}
			}

			if(empty){
				stopInterval(interval)
			}
		}
	}

	function registerInterval(frequency, cb){
		var interval, timeout, nextTime;
		scheduleIntervalSoonest();

		// Schedule the interval to start at the next time slot i.e. round(current) + 1
		function scheduleInterval(){
			calculateNextTime();
			timer = setTimeout(startInterval, nextTime - Date.now());
		}

		// Schedule the interval to start at the soonest time slot i.e. floor(current) + 1
		function scheduleIntervalSoonest(){
			calculateNextTime('floor');
			timer = setTimeout(startInterval, nextTime - Date.now());
		}

		function startInterval(){
			calculateNextTime();
			interval = setInterval(checkAndExecute, Cron.time.distanceInMs(frequency));
			cb()
		}

		function calculateNextTime(round_func){
			nextTime = Cron.time.roundToNext(frequency, null, round_func).getTime();
		}

		function checkAndExecute(){
			var cur = Date.now();
			var oldNext = nextTime;
			calculateNextTime();
			if(Math.abs(oldNext - cur) > MAX_ERROR_MS){
				console.log(" =======  Rescheduling: " + (oldNext - cur));
				clearInterval(interval);
				scheduleInterval();
			}

			cb();
		}

		callbackLists[frequency]
		stoppers[frequency] = function(){
			clearInterval(interval);
			clearTimeout(timeout);
		};
	}

	function stopInterval(interval){
		delete callbackLists[interval];
		var stopper = stoppers[interval]();
		if(stopper){
			stopper()
			delete stoppers[interval];
		}
	}

	function getOrCreateCallbackList(interval){
		if(callbackLists[interval]) return callbackLists[interval];

		var list = callbackLists[interval] = {};
		registerInterval(interval, function(){
			for(var id in list){
				list[id]();
			}
		});

		return list;
	}
}

util.inherits(Cron, events.EventEmitter);

Cron = new Cron();

Cron.math = {
	round: function round(num, divisor){
		return Math.round(num / divisor) * divisor;
	},

	ceil: function round(num, divisor){
		return Math.ceil(num / divisor) * divisor;
	},

	floor: function round(num, divisor){
		return Math.floor(num / divisor) * divisor;
	}
}

Cron.time = {
	distanceInMs: function(length){
		var t = 1;
		switch(length){
			case 'day':	   return 1000 * 60 * 60 * 24;
			case 'hour':   return 1000 * 60 * 60;
			case 'minute': return 1000 * 60;
			case 'second': return 1000;
		}
	},

	beginningOf: function beginningOf(t, part){
		switch(part){
			case 'day':	   t.setUTCHours(0);
			case 'hour':   t.setUTCMinutes(0);
			case 'minute': t.setUTCSeconds(0);
			case 'second': t.setUTCMilliseconds(0);
		}
	},

	roundToNext: function roundToNext(period, start, round_func){
		return this.roundTo(period, start, round_func, true);
	},

	roundTo: function roundTo(period, start, round_func, next){
		var t = start || new Date();
		round_func = Cron.math[round_func || 'round'];

		switch(period){
			case 'second':
				t.setUTCMilliseconds(round_func(t.getUTCMilliseconds(), 1000) + (next ? 1000 : 0));
				break;
			case 'minute':
				t.setUTCSeconds(round_func(t.getUTCSeconds(), 60) + (next ? 1000 : 0));
				this.beginningOf(t, 'minute');
				break;
			case 'hour':
				t.setUTCMinutes(round_func(t.getUTCMinutes(), 60) + (next ? 1000 : 0));
				this.beginningOf(t, 'hour');
				break;
			case 'day':
				t.setUTCHours(round_func(t.getUTCHours(), 24) + (next ? 1000 : 0));
				this.beginningOf(t, 'day');
				break;
		}
		return t;
	}
}

module.exports = Cron;<|endoftext|>


<commit_before>var page = require('webpage').create();

page.open('http://github.com/explore', function() {

    // super idomatic
    page.clipRect = page.evaluate(function() {
        var selector = '.featured-grid'
        var elem = document.querySelector(selector);
        return elem.getBoundingClientRect();
    });

    page.render('github.explore.' + Math.random() + ".png");
    phantom.exit();
});<commit_msg>a more helpful comment<commit_after>var page = require('webpage').create();

page.open('http://github.com/explore', function() {

    page.clipRect = page.evaluate(function() {
        // runs in the "browser"
        var elem = document.querySelector('.featured-grid');
        return elem.getBoundingClientRect();
    });

    page.render('github.explore.' + Math.random() + ".png");
    phantom.exit();
});<|endoftext|>


<commit_before>var
  fs = require( 'fs' ),
  http = require( 'http' ),
  path = require( 'path' ),
  url = require( 'url' ),
  EventEmitter = require( 'events' ).EventEmitter,
  exec = require( 'child_process' ).exec,
  spawn = require( 'child_process' ).spawn,

  stmd = require('./js/stmd'),

  args = {},
  argv = process.argv.slice( 2 )
;

// Guess arguments.
for ( var i = 0; i < argv.length; i++ ) {
  arg = argv[i]
  if ( arg.match( /^\d+$/ )){
    args.port = arg
  } else if ( arg === 'coffee' ){
    args.coffee = true
  } else if ( arg === 'fix' ){
    args.fix = true
  } else {
    args.host = arg
  }
}

// Emulate mime if it didn't exist.
var
  mime
;
try {
  mime = require( 'mime' )
} catch ( e ) {
  mime = (function () {
    var
      CONTENT_TYPES = {
        'js':   'application/javascript; charset=utf-8',
        'css':  'text/css; charset=utf-8',
        'sass': 'text/css; charset=utf-8',
        'scss': 'text/css; charset=utf-8',
        'json': 'application/json; charset=utf-8',
        'html': 'text/html; charset=utf-8',
        'htm':  'text/html; charset=utf-8',
        'jpg':  'image/jpeg',
        'jpeg': 'image/jpeg',
        'png':  'image/png',
        'ico':  'image/x-icon',
        'gif':  'image/gif',
        'md':   'text/plain; charset=utf-8',
        'txt':  'text/plain; charset=utf-8',
        'svg':  'image/svg+xml',
        'ttf':  'application/x-font-ttf',
        'woff': 'application/font-woff',
        'apk':  'application/vnd.android.package-archive'
      }
    ;
    return {
      lookup: function ( ext ) {
        ext = ext.trim()

        if ( ext[ 0 ] === '.' ) {
          ext = ext.slice( 1 )
        }
        return CONTENT_TYPES[ ext ] || 'application/octet-stream'
      }
    }
  })()
}

// Simple http response.
function httpRespond( res, code, data, headers ) {
  headers = headers || {}

  if ( !headers[ 'Content-Type' ] ) {
    headers[ 'Content-Type' ] = 'text/plain'
  }

  data = data || ''
  res.writeHead( code, headers )
  res.end( data )
}

var httpCb = function ( req, res ) {
  var
    uri = url.parse( req.url ).pathname,
    mdfilename = false,
    root,
    filename
  ;

  try {
      filename = decodeURIComponent( path.join( process.cwd(), uri ))
  } catch ( e ) {
      filename = path.join( process.cwd(), uri )
  }

  root = filename.replace( new RegExp( uri + '$', 'i'), '' )

  fs.exists( filename, function ( exists ) {
    if (
      ( !exists || /manifest.appcache/.test( filename )) &&
      ( !exists && !/^\/manual(\/.*)?$/.test( uri ))
    ) {
      filename = root + '/404.html'
      fs.readFile( filename, function( err, data ) {
        httpRespond( res, 404, data, {
          'Content-Type': 'text/html'
        })
      })
      return
    }

    if ( /^\/manual/.test( uri )) {
      filename = root + '/manual.html'
      mdfilename = root + '/doc' + (/^\/manual\/?$/.test( uri ) ? '/gaishu.md' : uri.replace( /^\/manual/, '' ) + '.md')
      console.log( mdfilename )

      fs.exists( mdfilename, function ( mdexists ) {
        if ( !mdexists ) {
          mdfilename = root + '/doc/404.md'
        }
      })
    } else if ( fs.statSync( filename ).isDirectory()) {
      if ( filename.slice(-1) !== '/' ) {
        // Directory with out a trailing slash.
        // redirect http://host/directory to http://host/directory/
        httpRespond( res, 302, 'Location is a folder, redirecting..', {
          'Location': uri + '/'
        })
        return
      } else {
        filename = path.join( filename, 'index.html' )
      }
    }

    if ( mdfilename ) {
      fs.readFile( filename, 'utf8', function( err, html ) {
        var ext

        if ( err ) {
          httpRespond(res, 500, err + '\n')
          return
        }

        fs.readFile( mdfilename, 'utf8', function( err, mdcode ) {
          var parser, renderer, md2html

          if ( err ) {
            httpRespond(res, 500, err + '\n')
            return
          }

          parser = new stmd.DocParser()
          renderer = new stmd.HtmlRenderer()
          md2html = renderer.render( parser.parse( mdcode ))

          html = html.replace( '<!--!!!MARKDOWN!!!-->', md2html )
          res.end( html )
        })
      })
    } else {
      fs.readFile( filename, 'binary', function( err, file ) {
        var ext

        if ( err ) {
          httpRespond(res, 500, err + '\n')
          return
        }

        ext = path.extname( filename ).slice( 1 )
        res.writeHead( 200, { 'Content-Type': mime.lookup( ext ) })
        res.write( file, 'binary' )
        res.end()
      })
    }
  })
}

// Assign defaults and define the start server action.
args.port = args.port || 9999
args.host = args.host || '0.0.0.0'
var
  startServer = function () {
    http.createServer( httpCb ).listen( args.port, args.host )
      console.log(
        'Serving files from %s at http://%s:%s/',
        process.cwd(),
        args.host,
        args.port
      )
  }
;

// Watch an array of coffee files.
var
  startWatching = function ( files ) {
    if ( !files.length ) {
      startServer()
      return
    }
  }
;

// The coffee feature will take care of starting the server.
if ( !args.coffee ) {
  startServer()
}
<commit_msg>proper header for parsed Markdown pages<commit_after>var
  fs = require( 'fs' ),
  http = require( 'http' ),
  path = require( 'path' ),
  url = require( 'url' ),
  EventEmitter = require( 'events' ).EventEmitter,
  exec = require( 'child_process' ).exec,
  spawn = require( 'child_process' ).spawn,

  stmd = require('./js/stmd'),

  args = {},
  argv = process.argv.slice( 2 )
;

// Guess arguments.
for ( var i = 0; i < argv.length; i++ ) {
  arg = argv[i]
  if ( arg.match( /^\d+$/ )){
    args.port = arg
  } else if ( arg === 'coffee' ){
    args.coffee = true
  } else if ( arg === 'fix' ){
    args.fix = true
  } else {
    args.host = arg
  }
}

// Emulate mime if it didn't exist.
var
  mime
;
try {
  mime = require( 'mime' )
} catch ( e ) {
  mime = (function () {
    var
      CONTENT_TYPES = {
        'js':   'application/javascript; charset=utf-8',
        'css':  'text/css; charset=utf-8',
        'sass': 'text/css; charset=utf-8',
        'scss': 'text/css; charset=utf-8',
        'json': 'application/json; charset=utf-8',
        'html': 'text/html; charset=utf-8',
        'htm':  'text/html; charset=utf-8',
        'jpg':  'image/jpeg',
        'jpeg': 'image/jpeg',
        'png':  'image/png',
        'ico':  'image/x-icon',
        'gif':  'image/gif',
        'md':   'text/plain; charset=utf-8',
        'txt':  'text/plain; charset=utf-8',
        'svg':  'image/svg+xml',
        'ttf':  'application/x-font-ttf',
        'woff': 'application/font-woff',
        'apk':  'application/vnd.android.package-archive'
      }
    ;
    return {
      lookup: function ( ext ) {
        ext = ext.trim()

        if ( ext[ 0 ] === '.' ) {
          ext = ext.slice( 1 )
        }
        return CONTENT_TYPES[ ext ] || 'application/octet-stream'
      }
    }
  })()
}

// Simple http response.
function httpRespond( res, code, data, headers ) {
  headers = headers || {}

  if ( !headers[ 'Content-Type' ] ) {
    headers[ 'Content-Type' ] = 'text/plain'
  }

  data = data || ''
  res.writeHead( code, headers )
  res.end( data )
}

var httpCb = function ( req, res ) {
  var
    uri = url.parse( req.url ).pathname,
    mdfilename = false,
    root,
    filename
  ;

  try {
      filename = decodeURIComponent( path.join( process.cwd(), uri ))
  } catch ( e ) {
      filename = path.join( process.cwd(), uri )
  }

  root = filename.replace( new RegExp( uri + '$', 'i'), '' )

  fs.exists( filename, function ( exists ) {
    if (
      ( !exists || /manifest.appcache/.test( filename )) &&
      ( !exists && !/^\/manual(\/.*)?$/.test( uri ))
    ) {
      filename = root + '/404.html'
      fs.readFile( filename, function( err, data ) {
        httpRespond( res, 404, data, {
          'Content-Type': 'text/html'
        })
      })
      return
    }

    if ( /^\/manual/.test( uri )) {
      filename = root + '/manual.html'
      mdfilename = root + '/doc' + (/^\/manual\/?$/.test( uri ) ? '/gaishu.md' : uri.replace( /^\/manual/, '' ) + '.md')
      console.log( mdfilename )

      fs.exists( mdfilename, function ( mdexists ) {
        if ( !mdexists ) {
          mdfilename = root + '/doc/404.md'
        }
      })
    } else if ( fs.statSync( filename ).isDirectory()) {
      if ( filename.slice(-1) !== '/' ) {
        // Directory with out a trailing slash.
        // redirect http://host/directory to http://host/directory/
        httpRespond( res, 302, 'Location is a folder, redirecting..', {
          'Location': uri + '/'
        })
        return
      } else {
        filename = path.join( filename, 'index.html' )
      }
    }

    if ( mdfilename ) {
      fs.readFile( filename, 'utf8', function( err, html ) {
        var ext

        if ( err ) {
          httpRespond(res, 500, err + '\n')
          return
        }

        fs.readFile( mdfilename, 'utf8', function( err, mdcode ) {
          var parser, renderer, md2html

          if ( err ) {
            httpRespond(res, 500, err + '\n')
            return
          }

          parser = new stmd.DocParser()
          renderer = new stmd.HtmlRenderer()
          md2html = renderer.render( parser.parse( mdcode ))
          html = html.replace( '<!--!!!MARKDOWN!!!-->', md2html )

          res.writeHead( 200, { 'Content-Type': 'text/html; charset=utf-8' })
          res.end( html )
        })
      })
    } else {
      fs.readFile( filename, 'binary', function( err, file ) {
        var ext

        if ( err ) {
          httpRespond(res, 500, err + '\n')
          return
        }

        ext = path.extname( filename ).slice( 1 )
        res.writeHead( 200, { 'Content-Type': mime.lookup( ext ) })
        res.write( file, 'binary' )
        res.end()
      })
    }
  })
}

// Assign defaults and define the start server action.
args.port = args.port || 9999
args.host = args.host || '0.0.0.0'
var
  startServer = function () {
    http.createServer( httpCb ).listen( args.port, args.host )
      console.log(
        'Serving files from %s at http://%s:%s/',
        process.cwd(),
        args.host,
        args.port
      )
  }
;

// Watch an array of coffee files.
var
  startWatching = function ( files ) {
    if ( !files.length ) {
      startServer()
      return
    }
  }
;

// The coffee feature will take care of starting the server.
if ( !args.coffee ) {
  startServer()
}
<|endoftext|>


<commit_before>var request = require("request");
var pubnub = require("pubnub");

var relayr = module.exports = {};

var listeners = [];

relayr.connect = function(options){

	getPubNubKeys(options,function(err,data){

        var pubnubkeys = {};

        pubnubkeys.cipher_key = data.cipherKey;
        pubnubkeys.auth_key = data.authKey;
        pubnubkeys.subscribe_key = data.subscribeKey;
        pubnubkeys.channel = data.channel;

        listen(pubnubkeys);

    });

};

relayr.listen = function(listener){
	listeners.push(listener);
};

var getPubNubKeys = function(relayrkeys,callback){

	var app_id = relayrkeys.app_id;
	var dev_id = relayrkeys.dev_id;
	var token = relayrkeys.token;

	var options = {
		url:"https://api.relayr.io/devices/"+dev_id+"/apps/"+app_id,
		headers: {'Authorization': 'Bearer ' + token}
	}

    console.log("Retrieving Pubnub Keys");

	request.post(options,function(err,data){
		var pubnubkeys = {};
		if(!err) {
			try {
				pubnubkeys = JSON.parse(data.body);
			} catch(ex) {
				err = ex;
			}
		}
		callback(err,pubnubkeys);
	});

};

var listen = function(pubnubkeys) {

    var connection = pubnub.init(pubnubkeys);

    console.log("Connecting to Relayr Sensors");

    connection.subscribe({
        channel  : pubnubkeys.channel,
        callback : function(message) {
            var err = null;
            try {
                message = JSON.parse(message);
            } catch (ex) {
                err = ex;
            }
            listeners.forEach(function(listener){
                listener(err,message);
            });
        },
        error:function(err) {
            console.log("Relayr Error!");
            console.log(err);
        }
    });

};<commit_msg>Spaces/Tabs consolidation<commit_after>var request = require("request");
var pubnub = require("pubnub");

var relayr = module.exports = {};

var listeners = [];

relayr.connect = function(options){

	getPubNubKeys(options,function(err,data){

		var pubnubkeys = {};

		pubnubkeys.cipher_key = data.cipherKey;
		pubnubkeys.auth_key = data.authKey;
		pubnubkeys.subscribe_key = data.subscribeKey;
		pubnubkeys.channel = data.channel;

		listen(pubnubkeys);

	});

};

relayr.listen = function(listener){
	listeners.push(listener);
};

var getPubNubKeys = function(relayrkeys,callback){

	var app_id = relayrkeys.app_id;
	var dev_id = relayrkeys.dev_id;
	var token = relayrkeys.token;

	var options = {
		url:"https://api.relayr.io/devices/"+dev_id+"/apps/"+app_id,
		headers: {'Authorization': 'Bearer ' + token}
	}

	console.log("Retrieving Pubnub Keys");

	request.post(options,function(err,data){
		var pubnubkeys = {};
		if(!err) {
			try {
				pubnubkeys = JSON.parse(data.body);
			} catch(ex) {
				err = ex;
			}
		}
		callback(err,pubnubkeys);
	});

};

var listen = function(pubnubkeys) {

	var connection = pubnub.init(pubnubkeys);

	console.log("Connecting to Relayr Sensors");

	connection.subscribe({
		channel  : pubnubkeys.channel,
		callback : function(message) {
			var err = null;
			try {
				message = JSON.parse(message);
			} catch (ex) {
				err = ex;
			}
			listeners.forEach(function(listener){
				listener(err,message);
			});
		},
		error:function(err) {
			console.log("Relayr Error!");
			console.log(err);
		}
	});

};<|endoftext|>


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

var path = require('path'),
    fs = require('fs'),
    readInstalled = require("read-installed");

var dir = process.cwd(),
    cache = path.join(process.env['HOME'], '.npm'),
    tmp = path.resolve('/tmp/.npm');

function relock () {
  var packages = {};

  readInstalled(dir, void 0, function (er, data) {
    if (er) throw er;
    //console.log(data);
    if (data.dependencies) {
      Object.keys(data.dependencies).forEach(function (key) {
        walk(data.dependencies[key], packages);
      });
    }
    fs.writeFile(path.join(process.cwd(), 'lockdown.json'), JSON.stringify(packages, null, '  '));
  });
}

function walk (data, packages) {
  var name, version, shasum;
  if (data.name) name = data.name;
  if (data.version) version = data.version;

  if (name) {
    shasum = getShasum(cache, name, version);
    if (!(name in packages)) packages[name] = {};
    packages[name][version] = shasum;
  }

  if (data.dependencies) {
    Object.keys(data.dependencies).forEach(function (key) {
      // ignore bundled dependencies
      if (data.bundleDependencies && data.bundleDependencies.indexOf(key) > -1 ) return;
      walk(data.dependencies[key], packages);
    });
  }
}

function getShasum (cache, name, version) {
  var sha;
  try {
    // find sha in cache/name/version/.cache.json
    sha = require(path.resolve(path.join(cache, name, version, ".cache.json"))).dist.shasum;
  } catch (e) {
    try {
      // find sha in cache/name/.cache.json
      sha = require(path.resolve(path.join(cache, name, ".cache.json"))).versions[version].dist.shasum;
    } catch (e) {
    }
  }
  // finally, check in the tmp directory
  if (!sha && cache !== tmp) return getShasum(tmp, name, version);

  if (!sha) console.error("Warning: no shasum for "+name+"@"+version);

  return sha || "*";
}

exports.relock = relock;

if (fs.realpathSync(process.argv[1]) === fs.realpathSync(__filename)) relock();

<commit_msg>write alpha sorted lockdown.json files for better diff readability<commit_after>#!/usr/bin/env node

var path = require('path'),
    fs = require('fs'),
    readInstalled = require("read-installed");

var dir = process.cwd(),
    cache = path.join(process.env['HOME'], '.npm'),
    tmp = path.resolve('/tmp/.npm');

function relock () {
  var packages = {};

  readInstalled(dir, void 0, function (er, data) {
    if (er) throw er;
    //console.log(data);
    if (data.dependencies) {
      Object.keys(data.dependencies).forEach(function (key) {
        walk(data.dependencies[key], packages);
      });
    }
    fs.writeFile(path.join(process.cwd(), 'lockdown.json'), JSON.stringify(sortObj(packages), null, '  '));
  });
}

// we take advantage of the way JSON.stringify() is implemented to
// write sorted lockdown.json files for better diffs.
function sortObj(obj) {
  if (typeof obj === 'object' && obj !== null) {
    var sorted = {};
    Object.keys(obj).sort().forEach(function(k) {
      sorted[k] = sortObj(obj[k]);
    });
    return sorted;
  } else if (Array.isArray(obj)) {
    return obj.sort().map(sortObj);
  }
  return obj;
}

function walk (data, packages) {
  var name, version, shasum;
  if (data.name) name = data.name;
  if (data.version) version = data.version;

  if (name) {
    shasum = getShasum(cache, name, version);
    if (!(name in packages)) packages[name] = {};
    packages[name][version] = shasum;
  }

  if (data.dependencies) {
    Object.keys(data.dependencies).forEach(function (key) {
      // ignore bundled dependencies
      if (data.bundleDependencies && data.bundleDependencies.indexOf(key) > -1 ) return;
      walk(data.dependencies[key], packages);
    });
  }
}

function getShasum (cache, name, version) {
  var sha;
  try {
    // find sha in cache/name/version/.cache.json
    sha = require(path.resolve(path.join(cache, name, version, ".cache.json"))).dist.shasum;
  } catch (e) {
    try {
      // find sha in cache/name/.cache.json
      sha = require(path.resolve(path.join(cache, name, ".cache.json"))).versions[version].dist.shasum;
    } catch (e) {
    }
  }
  // finally, check in the tmp directory
  if (!sha && cache !== tmp) return getShasum(tmp, name, version);

  if (!sha) console.error("Warning: no shasum for "+name+"@"+version);

  return sha || "*";
}

exports.relock = relock;

if (fs.realpathSync(process.argv[1]) === fs.realpathSync(__filename)) relock();

<|endoftext|>


<commit_before>function startRender(canvas, getStarsCallback) {
  var STAR_SIZE_PIXELS = 1.5;
  var DECELERATION_BLEED_RATIO_PER_TICK = 0.05; // A tick is 1/60 sec.
  var DEBUG = false;
  var timestamps = [];

  var worldOffsetX = 0; // Top left has this x coordinate in world frame.
  var worldOffsetY = 0;
  // scale of 1 means 1 world unit = 1 canvas pixel
  // scale of 100 means 1 world unit = 100 canvas pixels
  var scale = 1;

  // Used to determine whether or not to redraw.
  var lastWorldOffsetX = null;
  var lastWorldOffsetY = null;
  var lastScale = null;

  var mousedown = false;
  var isPinching = false;
  var lastMouseX;
  var lastMouseY;
  var lastScale;
  var pixelVelocityX = 0;
  var pixelVelocityY = 0;
  var lastRenderTimestamp = 0;

  canvas.style['background-color'] = 'black';

  function render(timestamp) {
    var star, stars, i, j, context, brightnessToStars, dt, ratio;

    requestAnimationFrame(render);

    timestamps.push(timestamp);
    if (timestamps.length > 10) {
      if (DEBUG) console.log(
        (10 * 1000 / (timestamps[10] - timestamps[0])).toFixed(2) + ' fps'
      );
      timestamps = [];
    }

    // deceleration
    if (lastRenderTimestamp && !mousedown) {
      dt = timestamp - lastRenderTimestamp;
      if (pixelVelocityX || pixelVelocityY) {
        worldOffsetX -= pixelVelocityX * dt / scale;
        worldOffsetY -= pixelVelocityY * dt / scale;
      }
      ratio = 1 - Math.min(
        1, DECELERATION_BLEED_RATIO_PER_TICK * dt / (1000 / 60)
      );
      pixelVelocityX *= ratio;
      pixelVelocityY *= ratio;
    }
    // Prevent redrawing
    if (Math.abs(pixelVelocityX) < 0.01 && Math.abs(pixelVelocityY) < 0.01) {
      if (DEBUG) console.log("locked");
      pixelVelocityX = 0;
      pixelVelocityY = 0;
    }
    lastRenderTimestamp = timestamp;

    if (
      (worldOffsetX === lastWorldOffsetX) &&
      (worldOffsetY === lastWorldOffsetY) &&
      (scale === lastScale)
    ) return;

    lastWorldOffsetX = worldOffsetX;
    lastWorldOffsetY = worldOffsetY;
    lastScale = scale;

    stars = getStarsCallback(
      worldOffsetX,
      worldOffsetY,
      canvas.width / scale,
      canvas.height / scale
    );

    // setting fillStyle is expensive, so quantize and batch it.
    brightnessToStars = [];
    for (i = 0; i < 100; i++) brightnessToStars.push([]);
    for (i = 0; i < stars.length; i++) {
      star = stars[i];
      brightnessToStars[Math.floor(star.brightness * 100)].push(star);
    }

    context = canvas.getContext('2d')
    context.clearRect(0, 0, canvas.width, canvas.height);

    for (i = 0; i < 100; i++) {
      context.fillStyle = 'rgba(255, 255, 255, ' + i / 100 + ')';
      stars = brightnessToStars[i];
      for (j = 0; j < stars.length; j++) {
        star = stars[j];
        context.fillRect(
          (star.worldX - worldOffsetX) * scale,
          (star.worldY - worldOffsetY) * scale,
          STAR_SIZE_PIXELS,
          STAR_SIZE_PIXELS
        );
      }
    }
  }

  requestAnimationFrame(render);

  var hammer = new Hammer.Manager(canvas)
  hammer.add(new Hammer.Pan());
  hammer.add(new Hammer.Pinch());

  hammer.on('panstart', function(e) {
    mousedown = true;
    lastMouseX = 0;
    lastMouseY = 0;
  });

  hammer.on('panmove', function(e) {
    worldOffsetX -= (e.deltaX - lastMouseX) / scale;
    worldOffsetY -= (e.deltaY - lastMouseY) / scale;
    lastMouseX = e.deltaX;
    lastMouseY = e.deltaY;
  });

  hammer.on('panend', function(e) {
    mousedown = false;
    pixelVelocityX = -e.velocityX;
    pixelVelocityY = -e.velocityY;
  });

  hammer.on('pinchstart', function(e) {
    isPinching = true;
    lastScale = 1;
    pixelVelocityX = 0;
    pixelVelocityY = 0;
  });

  hammer.on('pinchmove', function(e) {
    var rect = canvas.getBoundingClientRect();
    var scaleDelta = e.scale / lastScale;
    worldOffsetX += (e.center.x - rect.left) * (1 - 1 / scaleDelta) / scale;
    worldOffsetY += (e.center.y - rect.top) * (1 - 1 / scaleDelta) / scale;
    scale *= scaleDelta;
    lastScale = e.scale;
  });

  hammer.on('pinchend', function(e) {
    isPinching = false;
  });

  canvas.addEventListener("mousewheel", function(e) {
    var mult;
    var rect = canvas.getBoundingClientRect();
    if (e.wheelDelta > 0) mult = 1.1; else mult = 1 / 1.1;
    worldOffsetX += (e.clientX - rect.left) * (1 - 1 / mult) / scale;
    worldOffsetY += (e.clientY - rect.top) * (1 - 1 / mult) / scale;
    scale *= mult;
    pixelVelocityX = 0;
    pixelVelocityY = 0;
    e.preventDefault();
  }, false);

}
<commit_msg>allow brightness 1.0<commit_after>function startRender(canvas, getStarsCallback) {
  var STAR_SIZE_PIXELS = 1.5;
  var DECELERATION_BLEED_RATIO_PER_TICK = 0.05; // A tick is 1/60 sec.
  var DEBUG = false;
  var timestamps = [];

  var worldOffsetX = 0; // Top left has this x coordinate in world frame.
  var worldOffsetY = 0;
  // scale of 1 means 1 world unit = 1 canvas pixel
  // scale of 100 means 1 world unit = 100 canvas pixels
  var scale = 1;

  // Used to determine whether or not to redraw.
  var lastWorldOffsetX = null;
  var lastWorldOffsetY = null;
  var lastScale = null;

  var mousedown = false;
  var isPinching = false;
  var lastMouseX;
  var lastMouseY;
  var lastScale;
  var pixelVelocityX = 0;
  var pixelVelocityY = 0;
  var lastRenderTimestamp = 0;

  canvas.style['background-color'] = 'black';

  function render(timestamp) {
    var star, stars, i, j, context, brightnessToStars, dt, ratio;

    requestAnimationFrame(render);

    timestamps.push(timestamp);
    if (timestamps.length > 10) {
      if (DEBUG) console.log(
        (10 * 1000 / (timestamps[10] - timestamps[0])).toFixed(2) + ' fps'
      );
      timestamps = [];
    }

    // deceleration
    if (lastRenderTimestamp && !mousedown) {
      dt = timestamp - lastRenderTimestamp;
      if (pixelVelocityX || pixelVelocityY) {
        worldOffsetX -= pixelVelocityX * dt / scale;
        worldOffsetY -= pixelVelocityY * dt / scale;
      }
      ratio = 1 - Math.min(
        1, DECELERATION_BLEED_RATIO_PER_TICK * dt / (1000 / 60)
      );
      pixelVelocityX *= ratio;
      pixelVelocityY *= ratio;
    }
    // Prevent redrawing
    if (Math.abs(pixelVelocityX) < 0.01 && Math.abs(pixelVelocityY) < 0.01) {
      if (DEBUG) console.log("locked");
      pixelVelocityX = 0;
      pixelVelocityY = 0;
    }
    lastRenderTimestamp = timestamp;

    if (
      (worldOffsetX === lastWorldOffsetX) &&
      (worldOffsetY === lastWorldOffsetY) &&
      (scale === lastScale)
    ) return;

    lastWorldOffsetX = worldOffsetX;
    lastWorldOffsetY = worldOffsetY;
    lastScale = scale;

    stars = getStarsCallback(
      worldOffsetX,
      worldOffsetY,
      canvas.width / scale,
      canvas.height / scale
    );

    // setting fillStyle is expensive, so quantize and batch it.
    brightnessToStars = [];
    for (i = 0; i <= 100; i++) brightnessToStars.push([]);
    for (i = 0; i < stars.length; i++) {
      star = stars[i];
      brightnessToStars[Math.floor(star.brightness * 100)].push(star);
    }

    context = canvas.getContext('2d')
    context.clearRect(0, 0, canvas.width, canvas.height);

    for (i = 0; i <= 100; i++) {
      context.fillStyle = 'rgba(255, 255, 255, ' + i / 100 + ')';
      stars = brightnessToStars[i];
      for (j = 0; j < stars.length; j++) {
        star = stars[j];
        context.fillRect(
          (star.worldX - worldOffsetX) * scale,
          (star.worldY - worldOffsetY) * scale,
          STAR_SIZE_PIXELS,
          STAR_SIZE_PIXELS
        );
      }
    }
  }

  requestAnimationFrame(render);

  var hammer = new Hammer.Manager(canvas)
  hammer.add(new Hammer.Pan());
  hammer.add(new Hammer.Pinch());

  hammer.on('panstart', function(e) {
    mousedown = true;
    lastMouseX = 0;
    lastMouseY = 0;
  });

  hammer.on('panmove', function(e) {
    worldOffsetX -= (e.deltaX - lastMouseX) / scale;
    worldOffsetY -= (e.deltaY - lastMouseY) / scale;
    lastMouseX = e.deltaX;
    lastMouseY = e.deltaY;
  });

  hammer.on('panend', function(e) {
    mousedown = false;
    pixelVelocityX = -e.velocityX;
    pixelVelocityY = -e.velocityY;
  });

  hammer.on('pinchstart', function(e) {
    isPinching = true;
    lastScale = 1;
    pixelVelocityX = 0;
    pixelVelocityY = 0;
  });

  hammer.on('pinchmove', function(e) {
    var rect = canvas.getBoundingClientRect();
    var scaleDelta = e.scale / lastScale;
    worldOffsetX += (e.center.x - rect.left) * (1 - 1 / scaleDelta) / scale;
    worldOffsetY += (e.center.y - rect.top) * (1 - 1 / scaleDelta) / scale;
    scale *= scaleDelta;
    lastScale = e.scale;
  });

  hammer.on('pinchend', function(e) {
    isPinching = false;
  });

  canvas.addEventListener("mousewheel", function(e) {
    var mult;
    var rect = canvas.getBoundingClientRect();
    if (e.wheelDelta > 0) mult = 1.1; else mult = 1 / 1.1;
    worldOffsetX += (e.clientX - rect.left) * (1 - 1 / mult) / scale;
    worldOffsetY += (e.clientY - rect.top) * (1 - 1 / mult) / scale;
    scale *= mult;
    pixelVelocityX = 0;
    pixelVelocityY = 0;
    e.preventDefault();
  }, false);

}
<|endoftext|>


<commit_before>// Copyright (c) 2015 Uber Technologies, Inc.

// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';

var inherits = require('util').inherits;
var parallel = require('run-parallel');

var InArgStream = require('./argstream').InArgStream;
var OutArgStream = require('./argstream').OutArgStream;

var States = Object.create(null);
States.Initial = 0;
States.Streaming = 1;
States.Done = 2;
States.Error = 3;

function TChannelIncomingRequest(id, options) {
    if (!(this instanceof TChannelIncomingRequest)) {
        return new TChannelIncomingRequest(id, options);
    }
    options = options || {};
    var self = this;
    InArgStream.call(self);
    self.state = States.Initial;
    self.id = id || 0;
    self.ttl = options.ttl || 0;
    self.tracing = options.tracing || null;
    self.service = options.service || '';
    self.remoteAddr = null;
    self.headers = options.headers || {};
    self.checksum = options.checksum || null;
    self.on('finish', function onFinish() {
        self.state = States.Done;
    });
}

inherits(TChannelIncomingRequest, InArgStream);

TChannelIncomingRequest.prototype.finish = function finish() {
    var self = this;
    if (self.state === States.Done) {
        throw new Error('request already done'); // TODO: typed error
    } else {
        self.state = States.Done;
    }
};

function TChannelIncomingResponse(id, options) {
    if (!(this instanceof TChannelIncomingResponse)) {
        return new TChannelIncomingResponse(id, options);
    }
    options = options || {};
    var self = this;
    InArgStream.call(self);
    self.state = States.Initial;
    self.id = id || 0;
    self.code = options.code || 0;
    self.checksum = options.checksum || null;
    self.ok = self.code === 0; // TODO: probably okay, but a bit jank
    self.on('finish', function onFinish() {
        self.state = States.Done;
    });
}

inherits(TChannelIncomingResponse, InArgStream);

TChannelIncomingResponse.prototype.finish = function finish() {
    var self = this;
    if (self.state === States.Done) {
        throw new Error('response already done'); // TODO: typed error
    } else {
        self.state = States.Done;
    }
};

function TChannelOutgoingRequest(id, options) {
    if (!(this instanceof TChannelOutgoingRequest)) {
        return new TChannelOutgoingRequest(id, options);
    }
    options = options || {};
    if (!options.sendFrame) {
        throw new Error('missing sendFrame');
    }
    var self = this;
    OutArgStream.call(self);
    self.state = States.Initial;
    self.id = id || 0;
    self.ttl = options.ttl || 0;
    self.tracing = options.tracing || null;
    self.service = options.service || '';
    self.headers = options.headers || {};
    self.checksumType = options.checksumType || 0;
    self.checksum = options.checksum || null;
    self.sendFrame = options.sendFrame;
    self.on('frame', function onFrame(parts, isLast) {
        self.sendParts(parts, isLast);
    });
    self.on('finish', function onFinish() {
        // TODO: should be redundant with self.sendCallRequest(Cont)Frame
        // having been called with isLast=true
        self.state = States.Done;
    });
}

inherits(TChannelOutgoingRequest, OutArgStream);

TChannelOutgoingRequest.prototype.sendParts = function sendParts(parts, isLast) {
    var self = this;
    switch (self.state) {
        case States.Initial:
            self.sendCallRequestFrame(parts, isLast);
            break;
        case States.Streaming:
            self.sendCallRequestContFrame(parts, isLast);
            break;
        case States.Done:
            // TODO: could probably happen normally, like say if a
            // streaming request is canceled
            throw new Error('got frame in done state'); // TODO: typed error
        case States.Error:
            // TODO: log warn
            break;
    }
};

TChannelOutgoingRequest.prototype.sendCallRequestFrame = function sendCallRequestFrame(args, isLast) {
    var self = this;
    switch (self.state) {
        case States.Initial:
            self.sendFrame.callRequest(args, isLast);
            if (isLast) self.state = States.Done;
            else self.state = States.Streaming;
            break;
        case States.Streaming:
            throw new Error('first request frame already sent'); // TODO: typed error
        case States.Done:
            throw new Error('request already done'); // TODO: typed error
    }
};

TChannelOutgoingRequest.prototype.sendCallRequestContFrame = function sendCallRequestContFrame(args, isLast) {
    var self = this;
    switch (self.state) {
        case States.Initial:
            throw new Error('first request frame not sent'); // TODO: typed error
        case States.Streaming:
            self.sendFrame.callRequestCont(args, isLast);
            if (isLast) self.state = States.Done;
            break;
        case States.Done:
            throw new Error('request already done'); // TODO: typed error
    }
};

TChannelOutgoingRequest.prototype.send = function send(arg1, arg2, arg3, callback) {
    var self = this;
    if (callback) self.hookupCallback(callback);
    self.arg1.end(arg1);
    self.arg2.end(arg2);
    self.arg3.end(arg3);
    return self;
};

TChannelOutgoingRequest.prototype.hookupCallback = function hookupCallback(callback) {
    var self = this;
    self.once('error', onError);
    self.once('response', onResponse);
    function onError(err) {
        self.removeListener('response', onResponse);
        callback(err, null);
    }
    function onResponse(res) {
        self.removeListener('error', onError);
        if (callback.canStream) {
            callback(null, res);
        } else {
            parallel({
                arg2: res.arg2.onValueReady,
                arg3: res.arg3.onValueReady
            }, function argsDone(err, args) {
                callback(err, res, args.arg2, args.arg3);
            });
        }
    }
    return self;
};

function TChannelOutgoingResponse(id, options) {
    if (!(this instanceof TChannelOutgoingResponse)) {
        return new TChannelOutgoingResponse(id, options);
    }
    options = options || {};
    if (!options.sendFrame) {
        throw new Error('missing sendFrame');
    }
    var self = this;
    OutArgStream.call(self);
    self.state = States.Initial;
    self.id = id || 0;
    self.code = options.code || 0;
    self.tracing = options.tracing || null;
    self.headers = options.headers || {};
    self.checksumType = options.checksumType || 0;
    self.checksum = options.checksum || null;
    self.ok = true;
    self.sendFrame = options.sendFrame;
    self.on('frame', function onFrame(parts, isLast) {
        self.sendParts(parts, isLast);
    });
    self.on('finish', function onFinish() {
        // TODO: should be redundant with self.sendCallResponse(Cont)Frame
        // having been called with isLast=true
        self.state = States.Done;
    });
}

inherits(TChannelOutgoingResponse, OutArgStream);

TChannelOutgoingResponse.prototype.sendParts = function sendParts(parts, isLast) {
    var self = this;
    switch (self.state) {
        case States.Initial:
            self.sendCallResponseFrame(parts, isLast);
            break;
        case States.Streaming:
            self.sendCallResponseContFrame(parts, isLast);
            break;
        case States.Done:
            throw new Error('got frame in done state'); // TODO: typed error
        case States.Error:
            // TODO: log warn
            break;
    }
};

TChannelOutgoingResponse.prototype.sendCallResponseFrame = function sendCallResponseFrame(args, isLast) {
    var self = this;
    switch (self.state) {
        case States.Initial:
            self.sendFrame.callResponse(args, isLast);
            if (isLast) self.state = States.Done;
            else self.state = States.Streaming;
            break;
        case States.Streaming:
            throw new Error('first response frame already sent'); // TODO: typed error
        case States.Done:
        case States.Error:
            throw new Error('response already done'); // TODO: typed error
    }
};

TChannelOutgoingResponse.prototype.sendCallResponseContFrame = function sendCallResponseContFrame(args, isLast) {
    var self = this;
    switch (self.state) {
        case States.Initial:
            throw new Error('first response frame not sent'); // TODO: typed error
        case States.Streaming:
            self.sendFrame.callResponseCont(args, isLast);
            if (isLast) self.state = States.Done;
            break;
        case States.Done:
        case States.Error:
            throw new Error('response already done'); // TODO: typed error
    }
};

TChannelOutgoingResponse.prototype.sendError = function sendError(codeString, message) {
    var self = this;
    if (self.state === States.Done || self.state === States.Error) {
        throw new Error('response already done'); // TODO: typed error
    } else {
        // TODO: we could decide to flush any parts in a (first?) call res frame
        self.finished = true;
        self.state = States.Error;
        self.arg1.end();
        self.arg2.end();
        self.arg3.end();
        self.sendFrame.error(codeString, message);
    }
};

TChannelOutgoingResponse.prototype.setOk = function setOk(ok) {
    var self = this;
    if (self.state !== States.Initial) {
        throw new Error('response already started'); // TODO typed error
    }
    self.ok = ok;
    self.code = ok ? 0 : 1; // TODO: too coupled to v2 specifics?
    self.arg1.end();
};

TChannelOutgoingResponse.prototype.sendOk = function sendOk(res1, res2) {
    var self = this;
    self.setOk(true);
    self.arg2.end(res1);
    self.arg3.end(res2);
};

TChannelOutgoingResponse.prototype.sendNotOk = function sendNotOk(res1, res2) {
    var self = this;
    self.setOk(false);
    self.arg2.end(res1);
    self.arg3.end(res2);
};

module.exports.States = States;
module.exports.IncomingRequest = TChannelIncomingRequest;
module.exports.IncomingResponse = TChannelIncomingResponse;
module.exports.OutgoingRequest = TChannelOutgoingRequest;
module.exports.OutgoingResponse = TChannelOutgoingResponse;
<commit_msg>reqres: shift argstream to be a consumed object rather than used as base class<commit_after>// Copyright (c) 2015 Uber Technologies, Inc.

// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';

var EventEmitter = require('events').EventEmitter;
var inherits = require('util').inherits;
var parallel = require('run-parallel');

var InArgStream = require('./argstream').InArgStream;
var OutArgStream = require('./argstream').OutArgStream;

var States = Object.create(null);
States.Initial = 0;
States.Streaming = 1;
States.Done = 2;
States.Error = 3;

function TChannelIncomingRequest(id, options) {
    if (!(this instanceof TChannelIncomingRequest)) {
        return new TChannelIncomingRequest(id, options);
    }
    options = options || {};
    var self = this;
    EventEmitter.call(self);
    self.state = States.Initial;
    self.id = id || 0;
    self.ttl = options.ttl || 0;
    self.tracing = options.tracing || null;
    self.service = options.service || '';
    self.remoteAddr = null;
    self.headers = options.headers || {};
    self.checksum = options.checksum || null;
    if (true) {
        self._argstream = InArgStream();
        self.arg1 = self._argstream.arg1;
        self.arg2 = self._argstream.arg2;
        self.arg3 = self._argstream.arg3;
        self._argstream.on('error', function passError(err) {
            self.emit('error', err);
        });
        self._argstream.on('finish', function onFinish() {
            self.emit('finish');
        });
    }
    self.on('finish', function onFinish() {
        self.state = States.Done;
    });
}

inherits(TChannelIncomingRequest, EventEmitter);

TChannelIncomingRequest.prototype.handleFrame = function handleFrame(parts) {
    var self = this;
    if (true) {
        self._argstream.handleFrame(parts);
    }
};

TChannelIncomingRequest.prototype.finish = function finish() {
    var self = this;
    if (self.state === States.Done) {
        throw new Error('request already done'); // TODO: typed error
    } else {
        self.state = States.Done;
    }
};

function TChannelIncomingResponse(id, options) {
    if (!(this instanceof TChannelIncomingResponse)) {
        return new TChannelIncomingResponse(id, options);
    }
    options = options || {};
    var self = this;
    EventEmitter.call(self);
    self.state = States.Initial;
    self.id = id || 0;
    self.code = options.code || 0;
    self.checksum = options.checksum || null;
    self.ok = self.code === 0; // TODO: probably okay, but a bit jank
    if (true) {
        self._argstream = InArgStream();
        self.arg1 = self._argstream.arg1;
        self.arg2 = self._argstream.arg2;
        self.arg3 = self._argstream.arg3;
        self._argstream.on('error', function passError(err) {
            self.emit('error', err);
        });
        self._argstream.on('finish', function onFinish() {
            self.emit('finish');
        });
    }
    self.on('finish', function onFinish() {
        self.state = States.Done;
    });
}

inherits(TChannelIncomingResponse, EventEmitter);

TChannelIncomingResponse.prototype.handleFrame = function handleFrame(parts) {
    var self = this;
    if (true) {
        self._argstream.handleFrame(parts);
    }
};

TChannelIncomingResponse.prototype.finish = function finish() {
    var self = this;
    if (self.state === States.Done) {
        throw new Error('response already done'); // TODO: typed error
    } else {
        self.state = States.Done;
    }
};

function TChannelOutgoingRequest(id, options) {
    if (!(this instanceof TChannelOutgoingRequest)) {
        return new TChannelOutgoingRequest(id, options);
    }
    options = options || {};
    if (!options.sendFrame) {
        throw new Error('missing sendFrame');
    }
    var self = this;
    EventEmitter.call(self);
    self.state = States.Initial;
    self.id = id || 0;
    self.ttl = options.ttl || 0;
    self.tracing = options.tracing || null;
    self.service = options.service || '';
    self.headers = options.headers || {};
    self.checksumType = options.checksumType || 0;
    self.checksum = options.checksum || null;
    self.sendFrame = options.sendFrame;
    if (true) {
        self._argstream = OutArgStream();
        self.arg1 = self._argstream.arg1;
        self.arg2 = self._argstream.arg2;
        self.arg3 = self._argstream.arg3;
        self._argstream.on('error', function passError(err) {
            self.emit('error', err);
        });
        self._argstream.on('frame', function onFrame(parts, isLast) {
            self.sendParts(parts, isLast);
        });
        self._argstream.on('finish', function onFinish() {
            self.emit('finish');
        });
    }
}

inherits(TChannelOutgoingRequest, EventEmitter);

TChannelOutgoingRequest.prototype.sendParts = function sendParts(parts, isLast) {
    var self = this;
    switch (self.state) {
        case States.Initial:
            self.sendCallRequestFrame(parts, isLast);
            break;
        case States.Streaming:
            self.sendCallRequestContFrame(parts, isLast);
            break;
        case States.Done:
            // TODO: could probably happen normally, like say if a
            // streaming request is canceled
            throw new Error('got frame in done state'); // TODO: typed error
        case States.Error:
            // TODO: log warn
            break;
    }
};

TChannelOutgoingRequest.prototype.sendCallRequestFrame = function sendCallRequestFrame(args, isLast) {
    var self = this;
    switch (self.state) {
        case States.Initial:
            self.sendFrame.callRequest(args, isLast);
            if (isLast) self.state = States.Done;
            else self.state = States.Streaming;
            break;
        case States.Streaming:
            throw new Error('first request frame already sent'); // TODO: typed error
        case States.Done:
            throw new Error('request already done'); // TODO: typed error
    }
};

TChannelOutgoingRequest.prototype.sendCallRequestContFrame = function sendCallRequestContFrame(args, isLast) {
    var self = this;
    switch (self.state) {
        case States.Initial:
            throw new Error('first request frame not sent'); // TODO: typed error
        case States.Streaming:
            self.sendFrame.callRequestCont(args, isLast);
            if (isLast) self.state = States.Done;
            break;
        case States.Done:
            throw new Error('request already done'); // TODO: typed error
    }
};

TChannelOutgoingRequest.prototype.send = function send(arg1, arg2, arg3, callback) {
    var self = this;
    if (callback) self.hookupCallback(callback);
    if (true) {
        self.arg1.end(arg1);
        self.arg2.end(arg2);
        self.arg3.end(arg3);
    }
    return self;
};

TChannelOutgoingRequest.prototype.hookupCallback = function hookupCallback(callback) {
    var self = this;
    self.once('error', onError);
    self.once('response', onResponse);
    function onError(err) {
        self.removeListener('response', onResponse);
        callback(err, null);
    }

    function onResponse(res) {
        self.removeListener('error', onError);
        if (callback.canStream) {
            callback(null, res);
        } else {
            parallel({
                arg2: res.arg2.onValueReady,
                arg3: res.arg3.onValueReady
            }, compatCall);
        }

        function compatCall(err, args) {
            callback(err, res, args.arg2, args.arg3);
        }
    }
    return self;
};

function TChannelOutgoingResponse(id, options) {
    if (!(this instanceof TChannelOutgoingResponse)) {
        return new TChannelOutgoingResponse(id, options);
    }
    options = options || {};
    if (!options.sendFrame) {
        throw new Error('missing sendFrame');
    }
    var self = this;
    EventEmitter.call(self);
    self.state = States.Initial;
    self.id = id || 0;
    self.code = options.code || 0;
    self.tracing = options.tracing || null;
    self.headers = options.headers || {};
    self.checksumType = options.checksumType || 0;
    self.checksum = options.checksum || null;
    self.ok = true;
    self.sendFrame = options.sendFrame;
    if (true) {
        self._argstream = OutArgStream();
        self.arg1 = self._argstream.arg1;
        self.arg2 = self._argstream.arg2;
        self.arg3 = self._argstream.arg3;
        self._argstream.on('error', function passError(err) {
            self.emit('error', err);
        });
        self._argstream.on('frame', function onFrame(parts, isLast) {
            self.sendParts(parts, isLast);
        });
        self._argstream.on('finish', function onFinish() {
            self.emit('finish');
        });
    }
}

inherits(TChannelOutgoingResponse, EventEmitter);

TChannelOutgoingResponse.prototype.sendParts = function sendParts(parts, isLast) {
    var self = this;
    switch (self.state) {
        case States.Initial:
            self.sendCallResponseFrame(parts, isLast);
            break;
        case States.Streaming:
            self.sendCallResponseContFrame(parts, isLast);
            break;
        case States.Done:
            throw new Error('got frame in done state'); // TODO: typed error
        case States.Error:
            // TODO: log warn
            break;
    }
};

TChannelOutgoingResponse.prototype.sendCallResponseFrame = function sendCallResponseFrame(args, isLast) {
    var self = this;
    switch (self.state) {
        case States.Initial:
            self.sendFrame.callResponse(args, isLast);
            if (isLast) self.state = States.Done;
            else self.state = States.Streaming;
            break;
        case States.Streaming:
            throw new Error('first response frame already sent'); // TODO: typed error
        case States.Done:
        case States.Error:
            throw new Error('response already done'); // TODO: typed error
    }
};

TChannelOutgoingResponse.prototype.sendCallResponseContFrame = function sendCallResponseContFrame(args, isLast) {
    var self = this;
    switch (self.state) {
        case States.Initial:
            throw new Error('first response frame not sent'); // TODO: typed error
        case States.Streaming:
            self.sendFrame.callResponseCont(args, isLast);
            if (isLast) self.state = States.Done;
            break;
        case States.Done:
        case States.Error:
            throw new Error('response already done'); // TODO: typed error
    }
};

TChannelOutgoingResponse.prototype.sendError = function sendError(codeString, message) {
    var self = this;
    if (self.state === States.Done || self.state === States.Error) {
        throw new Error('response already done'); // TODO: typed error
    } else {
        self.state = States.Error;
        if (true) {
            // TODO: we could decide to flush any parts in a (first?) call res frame
            self._argstream.finished = true;
            self.arg1.end();
            self.arg2.end();
            self.arg3.end();
        }
        self.sendFrame.error(codeString, message);
    }
};

TChannelOutgoingResponse.prototype.setOk = function setOk(ok) {
    var self = this;
    if (self.state !== States.Initial) {
        throw new Error('response already started'); // TODO typed error
    }
    self.ok = ok;
    self.code = ok ? 0 : 1; // TODO: too coupled to v2 specifics?
    if (true) {
        self.arg1.end();
    }
};

TChannelOutgoingResponse.prototype.sendOk = function sendOk(res1, res2) {
    var self = this;
    self.setOk(true);
    if (true) {
        self.arg2.end(res1);
        self.arg3.end(res2);
    }
};

TChannelOutgoingResponse.prototype.sendNotOk = function sendNotOk(res1, res2) {
    var self = this;
    self.setOk(false);
    if (true) {
        self.arg2.end(res1);
        self.arg3.end(res2);
    }
};

module.exports.States = States;
module.exports.IncomingRequest = TChannelIncomingRequest;
module.exports.IncomingResponse = TChannelIncomingResponse;
module.exports.OutgoingRequest = TChannelOutgoingRequest;
module.exports.OutgoingResponse = TChannelOutgoingResponse;
<|endoftext|>


<commit_before>// Copyright (c) 2015 Uber Technologies, Inc.

// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';

var EventEmitter = require('events').EventEmitter;
var inherits = require('util').inherits;

var emptyTracing = Buffer(25); // TODO: proper tracing object
var emptyBuffer = Buffer(0);

// TODO: provide streams for arg2/3

function TChannelIncomingRequest(id, options) {
    if (!(this instanceof TChannelIncomingRequest)) {
        return new TChannelIncomingRequest(id, options);
    }
    options = options || {};
    var self = this;
    EventEmitter.call(self);
    self.id = id || 0;
    self.ttl = options.ttl || 0;
    self.tracing = options.tracing || emptyTracing;
    self.service = options.service || '';
    self.remoteAddr = null;
    self.headers = options.headers || {};
    self.checksumType = options.checksumType || 0;
    self.arg1 = options.arg1 || emptyBuffer;
    self.arg2 = options.arg2 || emptyBuffer;
    self.arg3 = options.arg3 || emptyBuffer;
}

inherits(TChannelIncomingRequest, EventEmitter);

function TChannelIncomingResponse(id, options) {
    if (!(this instanceof TChannelIncomingResponse)) {
        return new TChannelIncomingResponse(id, options);
    }
    options = options || {};
    var self = this;
    EventEmitter.call(self);
    self.id = id || 0;
    self.code = options.code || 0;
    self.arg1 = options.arg1 || emptyBuffer;
    self.arg2 = options.arg2 || emptyBuffer;
    self.arg3 = options.arg3 || emptyBuffer;
    self.ok = self.code === 0; // TODO: probably okay, but a bit jank
}

inherits(TChannelIncomingResponse, EventEmitter);

function TChannelOutgoingRequest(id, options, sendFrame) {
    if (!(this instanceof TChannelOutgoingRequest)) {
        return new TChannelOutgoingRequest(id, options, sendFrame);
    }
    options = options || {};
    var self = this;
    EventEmitter.call(self);
    self.id = id || 0;
    self.ttl = options.ttl || 0;
    self.tracing = options.tracing || emptyTracing;
    self.service = options.service || '';
    self.headers = options.headers || {};
    self.checksumType = options.checksumType || 0;
    self.sendFrame = sendFrame;
    self.sent = false;
}

inherits(TChannelOutgoingRequest, EventEmitter);

TChannelOutgoingRequest.prototype.send = function send(arg1, arg2, arg3, callback) {
    var self = this;
    if (callback) self.hookupCallback(callback);
    if (self.sent) {
        throw new Error('request already sent');
    }
    self.sent = true;
    self.sendFrame(arg1, arg2, arg3);
    self.emit('end');
    return self;
};

TChannelOutgoingRequest.prototype.hookupCallback = function hookupCallback(callback) {
    var self = this;
    self.once('error', onError);
    self.once('response', onResponse);
    function onError(err) {
        self.removeListener('response', onResponse);
        callback(err, null);
    }
    function onResponse(res) {
        self.removeListener('error', onError);
        callback(null, res);
    }
    return self;
};

function TChannelOutgoingResponse(id, options, sendFrame) {
    if (!(this instanceof TChannelOutgoingResponse)) {
        return new TChannelOutgoingResponse(id, options, sendFrame);
    }
    options = options || {};
    var self = this;
    EventEmitter.call(self);
    self.id = id || 0;
    self.code = options.code || 0;
    self.tracing = options.tracing || emptyTracing;
    self.headers = options.headers || {};
    self.checksumType = options.checksumType || 0;
    self.ok = true;
    self.arg1 = options.arg1 || emptyBuffer;
    self.arg2 = options.arg2 || emptyBuffer;
    self.arg3 = options.arg3 || emptyBuffer;
    self.sendFrame = sendFrame;
    self.sent = false;
}

inherits(TChannelOutgoingResponse, EventEmitter);

TChannelOutgoingResponse.prototype.send = function send(err, res1, res2) {
    var self = this;
    if (self.sent) {
        throw new Error('response already sent');
    }
    self.sent = true;
    if (err) {
        self.ok = false;
        var errArg = isError(err) ? err.message : JSON.stringify(err); // TODO: better
        self.sendFrame(self.name, res1, errArg);
    } else {
        self.sendFrame(self.name, res1, res2);
    }
    self.emit('end');
};

module.exports.IncomingRequest = TChannelIncomingRequest;
module.exports.IncomingResponse = TChannelIncomingResponse;
module.exports.OutgoingRequest = TChannelOutgoingRequest;
module.exports.OutgoingResponse = TChannelOutgoingResponse;

function isError(obj) {
    return typeof obj === 'object' && (
        Object.prototype.toString.call(obj) === '[object Error]' ||
        obj instanceof Error);
}
<commit_msg>self.name -> self.arg1<commit_after>// Copyright (c) 2015 Uber Technologies, Inc.

// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';

var EventEmitter = require('events').EventEmitter;
var inherits = require('util').inherits;

var emptyTracing = Buffer(25); // TODO: proper tracing object
var emptyBuffer = Buffer(0);

// TODO: provide streams for arg2/3

function TChannelIncomingRequest(id, options) {
    if (!(this instanceof TChannelIncomingRequest)) {
        return new TChannelIncomingRequest(id, options);
    }
    options = options || {};
    var self = this;
    EventEmitter.call(self);
    self.id = id || 0;
    self.ttl = options.ttl || 0;
    self.tracing = options.tracing || emptyTracing;
    self.service = options.service || '';
    self.remoteAddr = null;
    self.headers = options.headers || {};
    self.checksumType = options.checksumType || 0;
    self.arg1 = options.arg1 || emptyBuffer;
    self.arg2 = options.arg2 || emptyBuffer;
    self.arg3 = options.arg3 || emptyBuffer;
}

inherits(TChannelIncomingRequest, EventEmitter);

function TChannelIncomingResponse(id, options) {
    if (!(this instanceof TChannelIncomingResponse)) {
        return new TChannelIncomingResponse(id, options);
    }
    options = options || {};
    var self = this;
    EventEmitter.call(self);
    self.id = id || 0;
    self.code = options.code || 0;
    self.arg1 = options.arg1 || emptyBuffer;
    self.arg2 = options.arg2 || emptyBuffer;
    self.arg3 = options.arg3 || emptyBuffer;
    self.ok = self.code === 0; // TODO: probably okay, but a bit jank
}

inherits(TChannelIncomingResponse, EventEmitter);

function TChannelOutgoingRequest(id, options, sendFrame) {
    if (!(this instanceof TChannelOutgoingRequest)) {
        return new TChannelOutgoingRequest(id, options, sendFrame);
    }
    options = options || {};
    var self = this;
    EventEmitter.call(self);
    self.id = id || 0;
    self.ttl = options.ttl || 0;
    self.tracing = options.tracing || emptyTracing;
    self.service = options.service || '';
    self.headers = options.headers || {};
    self.checksumType = options.checksumType || 0;
    self.sendFrame = sendFrame;
    self.sent = false;
}

inherits(TChannelOutgoingRequest, EventEmitter);

TChannelOutgoingRequest.prototype.send = function send(arg1, arg2, arg3, callback) {
    var self = this;
    if (callback) self.hookupCallback(callback);
    if (self.sent) {
        throw new Error('request already sent');
    }
    self.sent = true;
    self.sendFrame(arg1, arg2, arg3);
    self.emit('end');
    return self;
};

TChannelOutgoingRequest.prototype.hookupCallback = function hookupCallback(callback) {
    var self = this;
    self.once('error', onError);
    self.once('response', onResponse);
    function onError(err) {
        self.removeListener('response', onResponse);
        callback(err, null);
    }
    function onResponse(res) {
        self.removeListener('error', onError);
        callback(null, res);
    }
    return self;
};

function TChannelOutgoingResponse(id, options, sendFrame) {
    if (!(this instanceof TChannelOutgoingResponse)) {
        return new TChannelOutgoingResponse(id, options, sendFrame);
    }
    options = options || {};
    var self = this;
    EventEmitter.call(self);
    self.id = id || 0;
    self.code = options.code || 0;
    self.tracing = options.tracing || emptyTracing;
    self.headers = options.headers || {};
    self.checksumType = options.checksumType || 0;
    self.ok = true;
    self.arg1 = options.arg1 || emptyBuffer;
    self.arg2 = options.arg2 || emptyBuffer;
    self.arg3 = options.arg3 || emptyBuffer;
    self.sendFrame = sendFrame;
    self.sent = false;
}

inherits(TChannelOutgoingResponse, EventEmitter);

TChannelOutgoingResponse.prototype.send = function send(err, res1, res2) {
    var self = this;
    if (self.sent) {
        throw new Error('response already sent');
    }
    self.sent = true;
    if (err) {
        self.ok = false;
        var errArg = isError(err) ? err.message : JSON.stringify(err); // TODO: better
        self.sendFrame(self.arg1, res1, errArg);
    } else {
        self.sendFrame(self.arg1, res1, res2);
    }
    self.emit('end');
};

module.exports.IncomingRequest = TChannelIncomingRequest;
module.exports.IncomingResponse = TChannelIncomingResponse;
module.exports.OutgoingRequest = TChannelOutgoingRequest;
module.exports.OutgoingResponse = TChannelOutgoingResponse;

function isError(obj) {
    return typeof obj === 'object' && (
        Object.prototype.toString.call(obj) === '[object Error]' ||
        obj instanceof Error);
}
<|endoftext|>


<commit_before>function saveSession () {
	getVar();
	localStorage["token"] = token;
	localStorage["cid"] = cid;
	localStorage["prase"] = prase;
	localStorage["nopv"] = nopv;
	localStorage["nopu"] = nopu;
	localStorage["body"] = body;
	localStorage["chatList"] = JSON.stringify(chatList);
	localStorage["usercode"] = userCodeMirror.getValue();
}

function loadSession () {
	document.getElementById("token").value = localStorage["token"];
	document.getElementById("cid").value = localStorage["cid"];
	document.getElementById("prase").value = localStorage["prase"];
	document.getElementById("nopreview").value = localStorage["nopv"];
	document.getElementById("nopush").value = localStorage["nopu"];
	document.getElementById("text").value = localStorage["body"];
	userCodeMirror.setValue(localStorage["usercode"]);
	chatList = JSON.parse(localStorage["chatList"]);
	updateChatList(chatList);
}

// Start userCode methods

function setTarget (target) {
	document.getElementById("cid").value = target;
}

function setContent (content) {
	document.getElementById("text").value = content;
}

function setParseMode (mode) {
	document.getElementById("prase").value = mode;
}

function setUrlPreview (pv) {
	document.getElementById("nopreview").value = pv;
}

function setNotification (notify) {
	document.getElementById("nopush").value = !notify;
}

function setApi (apiname) {
	document.getElementById("apimethod").value = apiname;
}

function setPayload (parm) {
	document.getElementById("payload").value = parm;
}

// End userCode methods

function openApiDoc () {
	section = document.getElementById("apimethod").value.toLowerCase();
	window.open("https://core.telegram.org/bots/api#" + section);
}

function fillChatID () {
	document.getElementById("cid").value = document.getElementById("chatlist").value;
}

function updateChatList (chatList) {
	var chatlist = document.getElementById("chatlist");
	Array.from(chatlist.options).forEach(chatlist.options.remove.bind(chatlist.options));
	chatList.map(([name, value]) => new Option (name + " (" + value + ")", value)).forEach(chatlist.add.bind(chatlist));
}

function updateUserCode () {
	userCode = new Function("message", userCodeMirror.getValue());
}
<commit_msg>Notify user when a save/load/upate is succeed.<commit_after>function saveSession () {
	getVar();
	localStorage["token"] = token;
	localStorage["cid"] = cid;
	localStorage["prase"] = prase;
	localStorage["nopv"] = nopv;
	localStorage["nopu"] = nopu;
	localStorage["body"] = body;
	localStorage["chatList"] = JSON.stringify(chatList);
	localStorage["usercode"] = userCodeMirror.getValue();
	biu('Session saved.', {type: 'success'})
}

function loadSession () {
	document.getElementById("token").value = localStorage["token"];
	document.getElementById("cid").value = localStorage["cid"];
	document.getElementById("prase").value = localStorage["prase"];
	document.getElementById("nopreview").value = localStorage["nopv"];
	document.getElementById("nopush").value = localStorage["nopu"];
	document.getElementById("text").value = localStorage["body"];
	userCodeMirror.setValue(localStorage["usercode"]);
	chatList = JSON.parse(localStorage["chatList"]);
	updateChatList(chatList);
	biu('Session loaded.', {type: 'success'})
}

// Start userCode methods

function setTarget (target) {
	document.getElementById("cid").value = target;
}

function setContent (content) {
	document.getElementById("text").value = content;
}

function setParseMode (mode) {
	document.getElementById("prase").value = mode;
}

function setUrlPreview (pv) {
	document.getElementById("nopreview").value = pv;
}

function setNotification (notify) {
	document.getElementById("nopush").value = !notify;
}

function setApi (apiname) {
	document.getElementById("apimethod").value = apiname;
}

function setPayload (parm) {
	document.getElementById("payload").value = parm;
}

// End userCode methods

function openApiDoc () {
	section = document.getElementById("apimethod").value.toLowerCase();
	window.open("https://core.telegram.org/bots/api#" + section);
}

function fillChatID () {
	document.getElementById("cid").value = document.getElementById("chatlist").value;
}

function updateChatList (chatList) {
	var chatlist = document.getElementById("chatlist");
	Array.from(chatlist.options).forEach(chatlist.options.remove.bind(chatlist.options));
	chatList.map(([name, value]) => new Option (name + " (" + value + ")", value)).forEach(chatlist.add.bind(chatlist));
}

function updateUserCode () {
	userCode = new Function("message", userCodeMirror.getValue());
	biu('Code updated.', {type: 'success'})
}
<|endoftext|>


<commit_before>// Replaces images with their 2x versions if the device is 'retina'.
// Only replaces images with the class hi-res.
// @source http://www.kylejlarson.com/blog/2012/creating-retina-images-for-your-website/

(function () {

  var seperator = retinaImageSeperator == 'undefined' ? '@' : retinaImageSeperator;

  var mediaQuery = "(min--moz-device-pixel-ratio: 1.5),\
                    (-o-min-device-pixel-ratio: 3/2),\
                    (-webkit-min-device-pixel-ratio: 1.5),\
                    (min-device-pixel-ratio: 1.5),\
                    (min-resolution: 144dpi),\
                    (min-resolution: 1.5dppx)";

  if (window..matchMedia(mediaQuery).matches) {

    var images = document.getElementsByTagName('img');

    // Loop through the imgs.
    for (var i = 0; i < images.length; i++) {

      var classes = images[i].className.split(' ');

      for (key in classes) {

        if (classes[key] == 'hi-res') {

          // First check and removed any ? or # at end of src path.
          var questionPosition = images[i].src.lastIndexOf('?');
          var poundPosition = images[i].src.lastIndexOf('#');
          var periodPosition = images[i].src.lastIndexOf('.');

          if (questionPosition > periodPosition) {

            images[i].src = images[i].src.substr(0, questionPosition);

          }

          if (poundPosition > periodPosition) {

            images[i].src = images[i].src.substr(0, poundPosition);

          }

          var imageType = images[i].src.substr(-4);
          var imageName = images[i].src.substr(0, images[i].src.length - 4);
          imageName += seperator + "2x" + imageType;

          // Rename image.
          images[i].src = imageName;

        }

      }

    }

  }

})();
<commit_msg>Fix typo. Fix proper undefined var check.<commit_after>// Replaces images with their 2x versions if the device is 'retina'.
// Only replaces images with the class hi-res.
// @source http://www.kylejlarson.com/blog/2012/creating-retina-images-for-your-website/

(function () {

  var seperator = (typeof retinaImageSeperator == 'undefined') ? '@' : retinaImageSeperator;

  var mediaQuery = "(min--moz-device-pixel-ratio: 1.5),\
                    (-o-min-device-pixel-ratio: 3/2),\
                    (-webkit-min-device-pixel-ratio: 1.5),\
                    (min-device-pixel-ratio: 1.5),\
                    (min-resolution: 144dpi),\
                    (min-resolution: 1.5dppx)";

  if (window.matchMedia(mediaQuery).matches) {

    var images = document.getElementsByTagName('img');

    // Loop through the imgs.
    for (var i = 0; i < images.length; i++) {

      var classes = images[i].className.split(' ');

      for (key in classes) {

        if (classes[key] == 'hi-res') {

          // First check and removed any ? or # at end of src path.
          var questionPosition = images[i].src.lastIndexOf('?');
          var poundPosition = images[i].src.lastIndexOf('#');
          var periodPosition = images[i].src.lastIndexOf('.');

          if (questionPosition > periodPosition) {

            images[i].src = images[i].src.substr(0, questionPosition);

          }

          if (poundPosition > periodPosition) {

            images[i].src = images[i].src.substr(0, poundPosition);

          }

          var imageType = images[i].src.substr(-4);
          var imageName = images[i].src.substr(0, images[i].src.length - 4);
          imageName += seperator + "2x" + imageType;

          // Rename image.
          images[i].src = imageName;

        }

      }

    }

  }

})();
<|endoftext|>


<commit_before>module.exports = rimraf
rimraf.sync = rimrafSync

var assert = require("assert")
var path = require("path")
var fs = require("fs")
var glob = require("glob")

var globOpts = {
  nosort: true,
  nocomment: true,
  nonegate: true,
  silent: true
}

// for EMFILE handling
var timeout = 0

var isWindows = (process.platform === "win32")

function defaults (options) {
  var methods = [
    'unlink',
    'chmod',
    'stat',
    'lstat',
    'rmdir',
    'readdir'
  ]
  methods.forEach(function(m) {
    options[m] = options[m] || fs[m]
    m = m + 'Sync'
    options[m] = options[m] || fs[m]
  })

  options.maxBusyTries = options.maxBusyTries || 3
  options.emfileWait = options.emfileWait || 1000
  options.disableGlob = options.disableGlob || false
}

function rimraf (p, options, cb) {
  if (typeof options === 'function') {
    cb = options
    options = {}
  }

  assert(p, 'rimraf: missing path')
  assert.equal(typeof p, 'string', 'rimraf: path should be a string')
  assert(options, 'rimraf: missing options')
  assert.equal(typeof options, 'object', 'rimraf: options should be object')
  assert.equal(typeof cb, 'function', 'rimraf: callback function required')

  defaults(options)

  var busyTries = 0
  var errState = null
  var n = 0

  if (options.disableGlob || !glob.hasMagic(p))
    return afterGlob(null, [p])

  fs.lstat(p, function (er, stat) {
    if (!er)
      return afterGlob(null, [p])

    glob(p, globOpts, afterGlob)
  })

  function next (er) {
    errState = errState || er
    if (--n === 0)
      cb(errState)
  }

  function afterGlob (er, results) {
    if (er)
      return cb(er)

    n = results.length
    if (n === 0)
      return cb()

    results.forEach(function (p) {
      rimraf_(p, options, function CB (er) {
        if (er) {
          if (isWindows && (er.code === "EBUSY" || er.code === "ENOTEMPTY") &&
              busyTries < options.maxBusyTries) {
            busyTries ++
            var time = busyTries * 100
            // try again, with the same exact callback as this one.
            return setTimeout(function () {
              rimraf_(p, options, CB)
            }, time)
          }

          // this one won't happen if graceful-fs is used.
          if (er.code === "EMFILE" && timeout < options.emfileWait) {
            return setTimeout(function () {
              rimraf_(p, options, CB)
            }, timeout ++)
          }

          // already gone
          if (er.code === "ENOENT") er = null
        }

        timeout = 0
        next(er)
      })
    })
  }
}

// Two possible strategies.
// 1. Assume it's a file.  unlink it, then do the dir stuff on EPERM or EISDIR
// 2. Assume it's a directory.  readdir, then do the file stuff on ENOTDIR
//
// Both result in an extra syscall when you guess wrong.  However, there
// are likely far more normal files in the world than directories.  This
// is based on the assumption that a the average number of files per
// directory is >= 1.
//
// If anyone ever complains about this, then I guess the strategy could
// be made configurable somehow.  But until then, YAGNI.
function rimraf_ (p, options, cb) {
  assert(p)
  assert(options)
  assert(typeof cb === 'function')

  // sunos lets the root user unlink directories, which is... weird.
  // so we have to lstat here and make sure it's not a dir.
  options.lstat(p, function (er, st) {
    if (er && er.code === "ENOENT")
      return cb(null)

    if (st && st.isDirectory())
      return rmdir(p, options, er, cb)

    options.unlink(p, function (er) {
      if (er) {
        if (er.code === "ENOENT")
          return cb(null)
        if (er.code === "EPERM")
          return (isWindows)
            ? fixWinEPERM(p, options, er, cb)
            : rmdir(p, options, er, cb)
        if (er.code === "EISDIR")
          return rmdir(p, options, er, cb)
      }
      return cb(er)
    })
  })
}

function fixWinEPERM (p, options, er, cb) {
  assert(p)
  assert(options)
  assert(typeof cb === 'function')
  if (er)
    assert(er instanceof Error)

  options.chmod(p, 666, function (er2) {
    if (er2)
      cb(er2.code === "ENOENT" ? null : er)
    else
      options.stat(p, function(er3, stats) {
        if (er3)
          cb(er3.code === "ENOENT" ? null : er)
        else if (stats.isDirectory())
          rmdir(p, options, er, cb)
        else
          options.unlink(p, cb)
      })
  })
}

function fixWinEPERMSync (p, options, er) {
  assert(p)
  assert(options)
  if (er)
    assert(er instanceof Error)

  try {
    options.chmodSync(p, 666)
  } catch (er2) {
    if (er2.code === "ENOENT")
      return
    else
      throw er
  }

  try {
    var stats = options.statSync(p)
  } catch (er3) {
    if (er3.code === "ENOENT")
      return
    else
      throw er
  }

  if (stats.isDirectory())
    rmdirSync(p, options, er)
  else
    options.unlinkSync(p)
}

function rmdir (p, options, originalEr, cb) {
  assert(p)
  assert(options)
  if (originalEr)
    assert(originalEr instanceof Error)
  assert(typeof cb === 'function')

  // try to rmdir first, and only readdir on ENOTEMPTY or EEXIST (SunOS)
  // if we guessed wrong, and it's not a directory, then
  // raise the original error.
  options.rmdir(p, function (er) {
    if (er && (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM"))
      rmkids(p, options, cb)
    else if (er && er.code === "ENOTDIR")
      cb(originalEr)
    else
      cb(er)
  })
}

function rmkids(p, options, cb) {
  assert(p)
  assert(options)
  assert(typeof cb === 'function')

  options.readdir(p, function (er, files) {
    if (er)
      return cb(er)
    var n = files.length
    if (n === 0)
      return options.rmdir(p, cb)
    var errState
    files.forEach(function (f) {
      rimraf(path.join(p, f), options, function (er) {
        if (errState)
          return
        if (er)
          return cb(errState = er)
        if (--n === 0)
          options.rmdir(p, cb)
      })
    })
  })
}

// this looks simpler, and is strictly *faster*, but will
// tie up the JavaScript thread and fail on excessively
// deep directory trees.
function rimrafSync (p, options) {
  options = options || {}
  defaults(options)

  assert(p, 'rimraf: missing path')
  assert.equal(typeof p, 'string', 'rimraf: path should be a string')
  assert(options, 'rimraf: missing options')
  assert.equal(typeof options, 'object', 'rimraf: options should be object')

  var results

  if (options.disableGlob || !glob.hasMagic(p)) {
    results = [p]
  } else {
    try {
      fs.lstatSync(p)
      results = [p]
    } catch (er) {
      results = glob.sync(p, globOpts)
    }
  }

  if (!results.length)
    return

  for (var i = 0; i < results.length; i++) {
    var p = results[i]

    try {
      var st = options.lstatSync(p)
    } catch (er) {
      if (er.code === "ENOENT")
        return
    }

    try {
      // sunos lets the root user unlink directories, which is... weird.
      if (st && st.isDirectory())
        rmdirSync(p, options, null)
      else
        options.unlinkSync(p)
    } catch (er) {
      if (er.code === "ENOENT")
        return
      if (er.code === "EPERM")
        return isWindows ? fixWinEPERMSync(p, options, er) : rmdirSync(p, options, er)
      if (er.code !== "EISDIR")
        throw er
      rmdirSync(p, options, er)
    }
  }
}

function rmdirSync (p, options, originalEr) {
  assert(p)
  assert(options)
  if (originalEr)
    assert(originalEr instanceof Error)

  try {
    options.rmdirSync(p)
  } catch (er) {
    if (er.code === "ENOENT")
      return
    if (er.code === "ENOTDIR")
      throw originalEr
    if (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM")
      rmkidsSync(p, options)
  }
}

function rmkidsSync (p, options) {
  assert(p)
  assert(options)
  options.readdirSync(p).forEach(function (f) {
    rimrafSync(path.join(p, f), options)
  })
  options.rmdirSync(p, options)
}
<commit_msg>Added EPERM to delay/retry loop<commit_after>module.exports = rimraf
rimraf.sync = rimrafSync

var assert = require("assert")
var path = require("path")
var fs = require("fs")
var glob = require("glob")

var globOpts = {
  nosort: true,
  nocomment: true,
  nonegate: true,
  silent: true
}

// for EMFILE handling
var timeout = 0

var isWindows = (process.platform === "win32")

function defaults (options) {
  var methods = [
    'unlink',
    'chmod',
    'stat',
    'lstat',
    'rmdir',
    'readdir'
  ]
  methods.forEach(function(m) {
    options[m] = options[m] || fs[m]
    m = m + 'Sync'
    options[m] = options[m] || fs[m]
  })

  options.maxBusyTries = options.maxBusyTries || 3
  options.emfileWait = options.emfileWait || 1000
  options.disableGlob = options.disableGlob || false
}

function rimraf (p, options, cb) {
  if (typeof options === 'function') {
    cb = options
    options = {}
  }

  assert(p, 'rimraf: missing path')
  assert.equal(typeof p, 'string', 'rimraf: path should be a string')
  assert(options, 'rimraf: missing options')
  assert.equal(typeof options, 'object', 'rimraf: options should be object')
  assert.equal(typeof cb, 'function', 'rimraf: callback function required')

  defaults(options)

  var busyTries = 0
  var errState = null
  var n = 0

  if (options.disableGlob || !glob.hasMagic(p))
    return afterGlob(null, [p])

  fs.lstat(p, function (er, stat) {
    if (!er)
      return afterGlob(null, [p])

    glob(p, globOpts, afterGlob)
  })

  function next (er) {
    errState = errState || er
    if (--n === 0)
      cb(errState)
  }

  function afterGlob (er, results) {
    if (er)
      return cb(er)

    n = results.length
    if (n === 0)
      return cb()

    results.forEach(function (p) {
      rimraf_(p, options, function CB (er) {
        if (er) {
          if (isWindows && (er.code === "EBUSY" || er.code === "ENOTEMPTY" || er.code === "EPERM") &&
              busyTries < options.maxBusyTries) {
            busyTries ++
            var time = busyTries * 100
            // try again, with the same exact callback as this one.
            return setTimeout(function () {
              rimraf_(p, options, CB)
            }, time)
          }

          // this one won't happen if graceful-fs is used.
          if (er.code === "EMFILE" && timeout < options.emfileWait) {
            return setTimeout(function () {
              rimraf_(p, options, CB)
            }, timeout ++)
          }

          // already gone
          if (er.code === "ENOENT") er = null
        }

        timeout = 0
        next(er)
      })
    })
  }
}

// Two possible strategies.
// 1. Assume it's a file.  unlink it, then do the dir stuff on EPERM or EISDIR
// 2. Assume it's a directory.  readdir, then do the file stuff on ENOTDIR
//
// Both result in an extra syscall when you guess wrong.  However, there
// are likely far more normal files in the world than directories.  This
// is based on the assumption that a the average number of files per
// directory is >= 1.
//
// If anyone ever complains about this, then I guess the strategy could
// be made configurable somehow.  But until then, YAGNI.
function rimraf_ (p, options, cb) {
  assert(p)
  assert(options)
  assert(typeof cb === 'function')

  // sunos lets the root user unlink directories, which is... weird.
  // so we have to lstat here and make sure it's not a dir.
  options.lstat(p, function (er, st) {
    if (er && er.code === "ENOENT")
      return cb(null)

    if (st && st.isDirectory())
      return rmdir(p, options, er, cb)

    options.unlink(p, function (er) {
      if (er) {
        if (er.code === "ENOENT")
          return cb(null)
        if (er.code === "EPERM")
          return (isWindows)
            ? fixWinEPERM(p, options, er, cb)
            : rmdir(p, options, er, cb)
        if (er.code === "EISDIR")
          return rmdir(p, options, er, cb)
      }
      return cb(er)
    })
  })
}

function fixWinEPERM (p, options, er, cb) {
  assert(p)
  assert(options)
  assert(typeof cb === 'function')
  if (er)
    assert(er instanceof Error)

  options.chmod(p, 666, function (er2) {
    if (er2)
      cb(er2.code === "ENOENT" ? null : er)
    else
      options.stat(p, function(er3, stats) {
        if (er3)
          cb(er3.code === "ENOENT" ? null : er)
        else if (stats.isDirectory())
          rmdir(p, options, er, cb)
        else
          options.unlink(p, cb)
      })
  })
}

function fixWinEPERMSync (p, options, er) {
  assert(p)
  assert(options)
  if (er)
    assert(er instanceof Error)

  try {
    options.chmodSync(p, 666)
  } catch (er2) {
    if (er2.code === "ENOENT")
      return
    else
      throw er
  }

  try {
    var stats = options.statSync(p)
  } catch (er3) {
    if (er3.code === "ENOENT")
      return
    else
      throw er
  }

  if (stats.isDirectory())
    rmdirSync(p, options, er)
  else
    options.unlinkSync(p)
}

function rmdir (p, options, originalEr, cb) {
  assert(p)
  assert(options)
  if (originalEr)
    assert(originalEr instanceof Error)
  assert(typeof cb === 'function')

  // try to rmdir first, and only readdir on ENOTEMPTY or EEXIST (SunOS)
  // if we guessed wrong, and it's not a directory, then
  // raise the original error.
  options.rmdir(p, function (er) {
    if (er && (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM"))
      rmkids(p, options, cb)
    else if (er && er.code === "ENOTDIR")
      cb(originalEr)
    else
      cb(er)
  })
}

function rmkids(p, options, cb) {
  assert(p)
  assert(options)
  assert(typeof cb === 'function')

  options.readdir(p, function (er, files) {
    if (er)
      return cb(er)
    var n = files.length
    if (n === 0)
      return options.rmdir(p, cb)
    var errState
    files.forEach(function (f) {
      rimraf(path.join(p, f), options, function (er) {
        if (errState)
          return
        if (er)
          return cb(errState = er)
        if (--n === 0)
          options.rmdir(p, cb)
      })
    })
  })
}

// this looks simpler, and is strictly *faster*, but will
// tie up the JavaScript thread and fail on excessively
// deep directory trees.
function rimrafSync (p, options) {
  options = options || {}
  defaults(options)

  assert(p, 'rimraf: missing path')
  assert.equal(typeof p, 'string', 'rimraf: path should be a string')
  assert(options, 'rimraf: missing options')
  assert.equal(typeof options, 'object', 'rimraf: options should be object')

  var results

  if (options.disableGlob || !glob.hasMagic(p)) {
    results = [p]
  } else {
    try {
      fs.lstatSync(p)
      results = [p]
    } catch (er) {
      results = glob.sync(p, globOpts)
    }
  }

  if (!results.length)
    return

  for (var i = 0; i < results.length; i++) {
    var p = results[i]

    try {
      var st = options.lstatSync(p)
    } catch (er) {
      if (er.code === "ENOENT")
        return
    }

    try {
      // sunos lets the root user unlink directories, which is... weird.
      if (st && st.isDirectory())
        rmdirSync(p, options, null)
      else
        options.unlinkSync(p)
    } catch (er) {
      if (er.code === "ENOENT")
        return
      if (er.code === "EPERM")
        return isWindows ? fixWinEPERMSync(p, options, er) : rmdirSync(p, options, er)
      if (er.code !== "EISDIR")
        throw er
      rmdirSync(p, options, er)
    }
  }
}

function rmdirSync (p, options, originalEr) {
  assert(p)
  assert(options)
  if (originalEr)
    assert(originalEr instanceof Error)

  try {
    options.rmdirSync(p)
  } catch (er) {
    if (er.code === "ENOENT")
      return
    if (er.code === "ENOTDIR")
      throw originalEr
    if (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM")
      rmkidsSync(p, options)
  }
}

function rmkidsSync (p, options) {
  assert(p)
  assert(options)
  options.readdirSync(p).forEach(function (f) {
    rimrafSync(path.join(p, f), options)
  })
  options.rmdirSync(p, options)
}
<|endoftext|>