<commit_before>'use strict';

const p = require('path');
const strEsc = require('js-string-escape');

const modules = {
	requirejs: {
		header: 'define([\'angular\'], function(angular) { \'use strict\'; return ',
		footer: '});'
	},
	browserify: {
		header: '\'use strict\'; module.exports = '
	},
	es6: {
		header: 'import angular from \'angular\'; export default '
	},
	iife: {
		header: '(function(){',
		footer: '})();'
	}
};

const defaults = {
	file: 'templates.js',
	standalone: false,
	moduleType: null,
	moduleName: 'templates',
	templateHeader: 'angular.module("<%= module %>"<%= standalone %>).run(["$templateCache", function($templateCache) {',
	templateContent: '$templateCache.put("<%= url %>","<%= contents %>");',
	templateFooter: '}]);',
	trim: ''
};

module.exports = function () {
	this.plugin('ngTemplates', {every: 0}, function * (files, opts) {
		opts = Object.assign({}, defaults, opts);

		if (typeof opts.trim === 'string') {
			const t = opts.trim;
			opts.trim = str => str.replace(new RegExp(t, 'i'), '/');
		}

		let data = files.map(file => {
			// strip a string from the `file.dir` path
			let dir = p.relative(this.root, file.dir);
			// apply `opts.trim` func
			dir = p.normalize(opts.trim(dir));
			// esure no leading '/'
			dir = dir.chartAt(0) === '/' ? dir.substr(1) : dir;
			// wrap & return each file's content in a $templateCache definition
			return opts.templateContent
				.replace('<%= url %>', dir)
				.replace('<%= contents %>', strEsc(file.data.toString()));
		}).join('');

		// "merge" all data && wrap with angular
		data = opts.templateHeader.concat(data, opts.templateFooter)
			.replace('<%= module %>', opts.moduleName)
			.replace('<%= standalone %>', (opts.standalone ? ', []' : ''));

		const mod = opts.moduleType && modules[opts.moduleType];

		if (mod) {
			data = (mod.header || '').concat(data, mod.footer || '');
		}

		// clone file entry; keep `dir`
		let out = files[0];
		out.base = opts.file;
		out.data = new Buffer(data);
		// wipe ALL files in favor of new clone
		this._.files = [out];
	});
};
<commit_msg>add logic checks; fix typos<commit_after>'use strict';

const p = require('path');
const strEsc = require('js-string-escape');

const modules = {
	requirejs: {
		header: 'define([\'angular\'], function(angular) { \'use strict\'; return ',
		footer: '});'
	},
	browserify: {
		header: '\'use strict\'; module.exports = '
	},
	es6: {
		header: 'import angular from \'angular\'; export default '
	},
	iife: {
		header: '(function(){',
		footer: '})();'
	}
};

const defaults = {
	file: 'templates.js',
	standalone: false,
	moduleType: null,
	moduleName: 'templates',
	templateHeader: 'angular.module("<%= module %>"<%= standalone %>).run(["$templateCache", function($templateCache) {',
	templateContent: '$templateCache.put("<%= url %>","<%= contents %>");',
	templateFooter: '}]);',
	trim: ''
};

module.exports = function () {
	this.plugin('ngTemplates', {every: 0}, function * (files, opts) {
		opts = Object.assign({}, defaults, opts);

		if (typeof opts.trim === 'string') {
			const t = opts.trim;
			opts.trim = str => str.replace(new RegExp(t, 'i'), '/');
		}

		let data = [];
		for (const file of files) {
			if (!file.data) continue;
			// strip a string from the `file.dir` path
			let dir = p.relative(this.root, file.dir);
			// apply `opts.trim` func
			dir = p.normalize(opts.trim(dir));
			// esure no leading '/'
			dir = dir.charAt(0) === '/' ? dir.substr(1) : dir;
			// wrap & return each file's content in a $templateCache definition
			data.push(
				opts.templateContent
					.replace('<%= url %>', p.join(dir, file.base))
					.replace('<%= contents %>', strEsc(file.data.toString()))
			);
		}

		// "merge" all data && wrap with angular
		data = opts.templateHeader.concat(data.join(''), opts.templateFooter)
			.replace('<%= module %>', opts.moduleName)
			.replace('<%= standalone %>', (opts.standalone ? ', []' : ''));

		const mod = opts.moduleType && modules[opts.moduleType];

		if (mod) {
			data = (mod.header || '').concat(data, mod.footer || '');
		}

		// clone file entry; keep `dir`
		let out = files[0];
		out.base = opts.file;
		out.data = new Buffer(data);
		// wipe ALL files in favor of new clone
		this._.files = [out];
	});
};
<|endoftext|>


<commit_before>'use strict';
const app = require('app');
const fs = require('fs');
const path = require('path');
const BrowserWindow = require('browser-window');
const Menu = require('menu');
const appMenu = require('./menu');
const shell = require('shell');

// report crashes to the Electron project
require('crash-reporter').start();

// adds debug features like hotkeys for triggering dev tools and reload
require('electron-debug')();

const windows = [];

function createTeamWindow(team) {
	const win = new BrowserWindow({
		'width': 800,
		'height': 600,
		'web-preferences': {
			'partition': team,
			'plugins': false,

			// fails without this because of CommonJS script detection
			'node-integration': false
		}
	});

	win.loadUrl(`https://${team}.hipchat.com/chat`);
	win.webContents.on('new-window', (e, url) => {
		e.preventDefault();
		shell.openExternal(url);
	});
	win.webContents.on('did-finish-load', () => {
		if (team !== 'www') {
			win.setTitle(team);
		}
	});

	return win;
}

function openAllTeamWindows(settings) {
	settings.teams.forEach((team, index) => {
		windows.push(createTeamWindow(team, index));
	});
}

app.on('window-all-closed', () => {
	if (process.platform !== 'darwin') {
		app.quit();
	}
});

app.on('ready', () => {
	Menu.setApplicationMenu(appMenu);

	const settingsFile = path.join(app.getPath('userData'), 'settings.json');

	// Default settings
	let settings = {
		teams: ['www']
	};

	fs.access(settingsFile, fs.F_OK, err => {
		// Create settings file if it doesn't exist.
		if (err) {
			fs.writeFileSync(settingsFile, JSON.stringify(settings), 'utf8');
		} else {
			const file = fs.readFileSync(settingsFile, 'utf8');
			settings = JSON.parse(file);
		}

		openAllTeamWindows(settings);
	});
});
<commit_msg>Testing notifications<commit_after>'use strict';
const app = require('app');
const fs = require('fs');
const path = require('path');
const BrowserWindow = require('browser-window');
const Menu = require('menu');
const Tray = require('tray');
const shell = require('shell');
const appMenu = require('./menu');

// report crashes to the Electron project
require('crash-reporter').start();

// adds debug features like hotkeys for triggering dev tools and reload
require('electron-debug')();

const windows = [];

function updateBadge(title) {
	const messageCount = (/\(([0-9]+)\)/).exec(title);
	console.log(messageCount, title);

	if (Tray.displayBalloon) {
		Tray.displayBalloon({
			title: `Title ${messageCount}`,
			content: `Content ${messageCount}`
		});
	}

	if (app.dock) {
		app.dock.setBadge(messageCount ? messageCount[1] : '');
	}
}

function createTeamWindow(team) {
	const win = new BrowserWindow({
		'width': 800,
		'height': 600,
		'web-preferences': {
			//'partition': team,
			'plugins': false,

			// fails without this because of CommonJS script detection
			'node-integration': false
		}
	});

	win.loadUrl(`https://${team}.hipchat.com/chat`);
	win.on('page-title-updated', (e, title) => updateBadge(title));
	win.webContents.on('new-window', (e, url) => {
		e.preventDefault();
		shell.openExternal(url);
	});
	win.webContents.on('did-finish-load', () => {
		if (team !== 'www') {
			//win.setTitle(team);
		}
	});

	return win;
}

function openAllTeamWindows(settings) {
	settings.teams.forEach((team, index) => {
		windows.push(createTeamWindow(team, index));
	});
}

app.on('window-all-closed', () => {
	if (process.platform !== 'darwin') {
		app.quit();
	}
});

app.on('ready', () => {
	Menu.setApplicationMenu(appMenu);

	const settingsFile = path.join(app.getPath('userData'), 'settings.json');

	// Default settings
	let settings = {
		teams: ['www']
	};

	fs.access(settingsFile, fs.F_OK, err => {
		// Create settings file if it doesn't exist.
		if (err) {
			fs.writeFileSync(settingsFile, JSON.stringify(settings), 'utf8');
		} else {
			const file = fs.readFileSync(settingsFile, 'utf8');
			settings = JSON.parse(file);
		}

		openAllTeamWindows(settings);
	});
});
<|endoftext|>


<commit_before>var Express = require('express')
var Twitter = require('twitter')
var Request = require('request')
var Entities = require('html-entities').XmlEntities
var app = Express()

// Twitter parameters from environment variables
var twitterAccount = new Twitter({
  consumer_key: process.env.TWITTER_CONSUMER_KEY,
  consumer_secret: process.env.TWITTER_CONSUMER_SECRET,
  access_token_key: process.env.TWITTER_ACCESS_TOKEN_KEY,
  access_token_secret: process.env.TWITTER_ACCESS_TOKEN_SECRET
});

/**
 * @brief Twitter timeline
 * @return Twitter timeline content in JSON
 */
var twitterTimelineParams = {count: 30}
app.get('/:pass/tweets', function (req, res) {
  if (req.params.pass != "1645328")
  {
    res.end()
    return
  }

  twitterAccount.get('statuses/home_timeline', twitterTimelineParams, function(error, tweets, response) {
    if (error) {
      console.log('Tweeter timeline error ! %j', error)
      res.send('')
    } else {
      var entities = new Entities();
      for(var i = 0; i < tweets.length; i++)
      {
        var tweet = tweets[i];
        if (tweet.entities && tweet.entities.urls[0])
        {
          var tweetUrl = tweet.entities.urls[0].url;
          tweet.text = tweet.text.replace(tweetUrl, '');
        }
        tweet.text = tweet.text.replace(/https:\/\/t\.co\/[a-z0-9]+$/gi, '');
        tweet.text = entities.decode(tweet.text);
        tweet.text = tweet.text.replace(/\n\n/g, '\n');
        tweets[i] = tweet;
      }
      res.json(tweets)
    }
  })
})

/**
 * @brief Twitter image proxy
 * @return Twitter target image through nodeJS
 */
app.get('/tweetImage/*', function (req, res) {
  var proxyUrl = req.url;

  // Make sure we only serve images
  if (! (proxyUrl.endsWith('.png') || proxyUrl.endsWith('.jpg') || proxyUrl.endsWith('.jpeg') || proxyUrl.endsWith('.gif')))
  {
    console.log('Incorrect proxy url' + proxyUrl)
    res.end()
  }

  console.log('Proxying: ' + proxyUrl)
  proxyUrl = proxyUrl.replace('/tweetImage/', 'http://')

  Request.get(proxyUrl).pipe(res)
})

// Run the server
app.listen(8585, function () {
  console.log('Twitter proxy running on 8585 !')
})
<commit_msg>Converted indents to size of 4<commit_after>var Express = require('express')
var Twitter = require('twitter')
var Request = require('request')
var Entities = require('html-entities').XmlEntities
var app = Express()

// Twitter parameters from environment variables
var twitterAccount = new Twitter({
    consumer_key: process.env.TWITTER_CONSUMER_KEY,
    consumer_secret: process.env.TWITTER_CONSUMER_SECRET,
    access_token_key: process.env.TWITTER_ACCESS_TOKEN_KEY,
    access_token_secret: process.env.TWITTER_ACCESS_TOKEN_SECRET
});

/**
 * @brief Twitter timeline
 * @return Twitter timeline content in JSON
 */
var twitterTimelineParams = {count: 30}
app.get('/:pass/tweets', function (req, res) {
    if (req.params.pass != "1645328")
    {
        res.end()
        return
    }

    twitterAccount.get('statuses/home_timeline', twitterTimelineParams, function(error, tweets, response) {
        if (error) {
            console.log('Tweeter timeline error ! %j', error)
            res.send('')
        } else {
            var entities = new Entities();
            for(var i = 0; i < tweets.length; i++)
            {
                var tweet = tweets[i];
                if (tweet.entities && tweet.entities.urls[0])
                {
                    var tweetUrl = tweet.entities.urls[0].url;
                    tweet.text = tweet.text.replace(tweetUrl, '');
                }
                tweet.text = tweet.text.replace(/https:\/\/t\.co\/[a-z0-9]+$/gi, '');
                tweet.text = entities.decode(tweet.text);
                tweet.text = tweet.text.replace(/\n\n/g, '\n');
                tweets[i] = tweet;
            }
            res.json(tweets)
        }
    })
})

/**
 * @brief Twitter image proxy
 * @return Twitter target image through nodeJS
 app.get('/tweetImage/*', function (req, res) {
 */
    var proxyUrl = req.url;

    // Make sure we only serve images
    if (! (proxyUrl.endsWith('.png') || proxyUrl.endsWith('.jpg') || proxyUrl.endsWith('.jpeg') || proxyUrl.endsWith('.gif')))
    {
        console.log('Incorrect proxy url' + proxyUrl)
        res.end()
    }

    console.log('Proxying: ' + proxyUrl)
    proxyUrl = proxyUrl.replace('/tweetImage/', 'http://')

    Request.get(proxyUrl).pipe(res)
})

// Run the server
app.listen(8585, function () {
    console.log('Twitter proxy running on 8585 !')
})
<|endoftext|>


<commit_before>// Accessory for controlling Pioneer AVR via HomeKit

var request = require("request");
var inherits = require('util').inherits;
var Service, Characteristic;

// need to be global to be used in constructor
var maxVolume;
var minVolume;

module.exports = function(homebridge) {
  Service = homebridge.hap.Service;
  Characteristic = homebridge.hap.Characteristic;

  homebridge.registerAccessory("homebridge-pioneeravr", "PioneerAVR", PioneerAVR);

  function PioneerAVR(log, config) {
    // configuration
    this.ip = config['ip'];
    this.name = config['name'];
    maxVolume = config['maxVolume'];
    minVolume = config['minVolume'];

    this.log = log;

    this.get_url = "http://" + this.ip + "/StatusHandler.asp";

    this.on_url = "http://" + this.ip + "/EventHandler.asp?WebToHostItem=PO";
    this.off_url = "http://" + this.ip + "/EventHandler.asp?WebToHostItem=PF";

    this.mute_on = "http://" + this.ip + "/EventHandler.asp?WebToHostItem=MO";
    this.mute_off = "http://" + this.ip + "/EventHandler.asp?WebToHostItem=MF";

    this.volume_url = "http://" + this.ip + "/EventHandler.asp?WebToHostItem=";
  }

  // Custom Characteristics and service...
  PioneerAVR.AudioVolume = function() {
    Characteristic.call(this, 'Volume', '4804a651-2f32-4e1f-ac75-dacf23d9df93');
    console.log("Maximum Volume", maxVolume);
    this.setProps({
      format: Characteristic.Formats.FLOAT,
      maxValue: maxVolume,
      minValue: minVolume,
      minStep: 0.5,
      perms: [Characteristic.Perms.READ, Characteristic.Perms.WRITE, Characteristic.Perms.NOTIFY]
    });
    this.value = this.getDefaultValue();
  };
  inherits(PioneerAVR.AudioVolume, Characteristic);
/*
  PioneerAVR.Muting = function() {
    Characteristic.call(this, 'Mute', '4804a652-2f32-4e1f-ac75-dacf23d9df93');
    console.log("Mute Characteristic")
    this.setProps({
      format: Characteristic.Formats.BOOL,
      perms: [Characteristic.Perms.READ, Characteristic.Perms.WRITE, Characteristic.Perms.NOTIFY]
    });
    this.value = this.getDefaultValue();
  };
  inherits(PioneerAVR.Muting, Characteristic);
*/
  PioneerAVR.AudioDeviceService = function(displayName, subtype) {
    Service.call(this, displayName, '4804a653-2f32-4e1f-ac75-dacf23d9df93', subtype);
    this.addCharacteristic(PioneerAVR.AudioVolume);
    //this.addCharacteristic(PioneerAVR.Muting);
  };
  inherits(PioneerAVR.AudioDeviceService, Service);

  PioneerAVR.prototype = {

    httpRequest: function(url, method, callback) {
		  var that = this;

		  request({
        url: url,
        method: method
		  },
		  function (error, response, body) {
        callback(error, response, body)
      })
    },

    getPowerState: function(callback) {

      var url;
      url = this.get_url;

      this.httpRequest(url, "GET", function(error, response, body) {
        if (!error && response.statusCode == 200) {
      		var jsonResponse = JSON.parse(body);
      		powerState = jsonResponse['Z'][0]['P'];

          if (powerState == 1) {
            callback(null, true);
          }
          else {
            callback(null, false);
          }
          this.log("Power state is:", powerState);
      	}
        else {
          this.log('HTTP getPowerState function failed: %s', error);
          callback(error);
        }
      }.bind(this))

    },

    setPowerState: function(powerOn, callback) {
      var url;

      if (powerOn) {
        url = this.on_url;
      	this.log("Set", this.name, "to on");
    	}
    	else {
      	url = this.off_url;
      	this.log("Set", this.name, "to off");
    	}

    	this.httpRequest(url, "GET", function(error, response, body) {
      	if (!error && response.statusCode == 200) {
        	this.log('HTTP power function succeeded!');
        	callback();
      	}
      	else {
          this.log('HTTP power function failed: %s', error);
        	callback(error);
      		}
    	}.bind(this));
  	},

    getMuteState: function(callback) {
      var url;
      url = this.get_url;

      this.httpRequest(url, "GET", function(error, response, body) {
        if (!error && response.statusCode == 200) {
      		var jsonResponse = JSON.parse(body);
		      muteState = jsonResponse['Z'][0]['M'];

          if (muteState == 1) {
            callback(null, true);
          }
          else {
            callback(null, false);
          }
          this.log("Mute state is:", muteState);
      	}
        else {
          this.log('HTTP getMuteState function failed: %s', error);
          callback(error);
        }
      }.bind(this))

    },

    setMuteState: function(muteOn, callback) {
    	var url;

    	if (muteOn) {
      	url = this.mute_on;
      	this.log(this.name, "muted");
    	}
    	else {
      	url = this.mute_off;
      	this.log(this.name, "unmuted");
    	}

    	this.httpRequest(url, "GET", function(error, response, body) {
        if (!error && response.statusCode == 200) {
        	this.log('HTTP mute function succeeded!');
        	callback();
      	}
      	else {
          this.log('HTTP mute function failed: %s', error);
        	callback(error);
      		}
    	}.bind(this));
  	},

  	getVolume: function(callback) {
      var url;
      url = this.get_url;

      this.httpRequest(url, "GET", function(error, response, body) {
        if (!error && response.statusCode == 200) {
          var jsonResponse = JSON.parse(body);
  		    volumeValue = Number(jsonResponse['Z'][0]['V']);
          volume = (volumeValue - 161) * 0.5

          callback(null, Number(volume));

          this.log("MasterVolume is:", volume);
      	}
        else {
          this.log('HTTP getVolume function failed: %s', error);
        	callback(error);
      		}

      }.bind(this))

    },

  	setVolume: function(value, callback) {
      url = this.volume_url + (value * 2 + 161) + "VL"

  		this.httpRequest(url, "GET", function(error, response, body) {
        if (error) {
          this.log('HTTP volume function failed: %s', error);
          callback(error);
        }
        else {
          this.log("Set volume to", value, "db");
          callback();
          }
      }.bind(this));
  	},

  getServices: function() {
		var that = this;

		var informationService = new Service.AccessoryInformation();
		informationService
			.setCharacteristic(Characteristic.Name, this.name)
	    		.setCharacteristic(Characteristic.Manufacturer, "Pioneer")
	    		.setCharacteristic(Characteristic.Model, "VSX-2020")
	    		.setCharacteristic(Characteristic.SerialNumber, "1234567890");

		var switchService = new Service.Switch("Power State");
		switchService
			.getCharacteristic(Characteristic.On)
				.on('get', this.getPowerState.bind(this))
				.on('set', this.setPowerState.bind(this));
/*
		var audioDeviceService = new PioneerAVR.AudioDeviceService("Audio Functions");
		audioDeviceService
			.getCharacteristic(PioneerAVR.Muting)
				.on('get', this.getMuteState.bind(this))
				.on('set', this.setMuteState.bind(this));
*/
		audioDeviceService
			.getCharacteristic(PioneerAVR.AudioVolume)
				.on('get', this.getVolume.bind(this))
				.on('set', this.setVolume.bind(this));

    //return [informationService, switchService];
		return [informationService, switchService, audioDeviceService];
		}
	}
}
<commit_msg>testing 001<commit_after>// Accessory for controlling Pioneer AVR via HomeKit

var request = require("request");
var inherits = require('util').inherits;
var Service, Characteristic;

// need to be global to be used in constructor
var maxVolume;
var minVolume;

module.exports = function(homebridge) {
  Service = homebridge.hap.Service;
  Characteristic = homebridge.hap.Characteristic;

  homebridge.registerAccessory("homebridge-pioneeravr", "PioneerAVR", PioneerAVR);

  function PioneerAVR(log, config) {
    // configuration
    this.ip = config['ip'];
    this.name = config['name'];
    maxVolume = config['maxVolume'];
    minVolume = config['minVolume'];

    this.log = log;

    this.get_url = "http://" + this.ip + "/StatusHandler.asp";

    this.on_url = "http://" + this.ip + "/EventHandler.asp?WebToHostItem=PO";
    this.off_url = "http://" + this.ip + "/EventHandler.asp?WebToHostItem=PF";

    this.mute_on = "http://" + this.ip + "/EventHandler.asp?WebToHostItem=MO";
    this.mute_off = "http://" + this.ip + "/EventHandler.asp?WebToHostItem=MF";

    this.volume_url = "http://" + this.ip + "/EventHandler.asp?WebToHostItem=";
  }

  // Custom Characteristics and service...
  PioneerAVR.AudioVolume = function() {
    Characteristic.call(this, 'Volume', '4804a651-2f32-4e1f-ac75-dacf23d9df93');
    console.log("Maximum Volume", maxVolume);
    this.setProps({
      format: Characteristic.Formats.FLOAT,
      maxValue: maxVolume,
      minValue: minVolume,
      minStep: 0.5,
      perms: [Characteristic.Perms.READ, Characteristic.Perms.WRITE, Characteristic.Perms.NOTIFY]
    });
    this.value = this.getDefaultValue();
  };
  inherits(PioneerAVR.AudioVolume, Characteristic);
/*
  PioneerAVR.Muting = function() {
    Characteristic.call(this, 'Mute', '4804a652-2f32-4e1f-ac75-dacf23d9df93');
    console.log("Mute Characteristic")
    this.setProps({
      format: Characteristic.Formats.BOOL,
      perms: [Characteristic.Perms.READ, Characteristic.Perms.WRITE, Characteristic.Perms.NOTIFY]
    });
    this.value = this.getDefaultValue();
  };
  inherits(PioneerAVR.Muting, Characteristic);
*/
  PioneerAVR.AudioDeviceService = function(displayName, subtype) {
    Service.call(this, displayName, '4804a653-2f32-4e1f-ac75-dacf23d9df93', subtype);
    this.addCharacteristic(PioneerAVR.AudioVolume);
    //this.addCharacteristic(PioneerAVR.Muting);
  };
  inherits(PioneerAVR.AudioDeviceService, Service);

  PioneerAVR.prototype = {

    httpRequest: function(url, method, callback) {
		  var that = this;

		  request({
        url: url,
        method: method
		  },
		  function (error, response, body) {
        callback(error, response, body)
      })
    },

    getPowerState: function(callback) {

      var url;
      url = this.get_url;

      this.httpRequest(url, "GET", function(error, response, body) {
        if (!error && response.statusCode == 200) {
      		var jsonResponse = JSON.parse(body);
      		powerState = jsonResponse['Z'][0]['P'];

          if (powerState == 1) {
            callback(null, true);
          }
          else {
            callback(null, false);
          }
          this.log("Power state is:", powerState);
      	}
        else {
          this.log('HTTP getPowerState function failed: %s', error);
          callback(error);
        }
      }.bind(this))

    },

    setPowerState: function(powerOn, callback) {
      var url;

      if (powerOn) {
        url = this.on_url;
      	this.log("Set", this.name, "to on");
    	}
    	else {
      	url = this.off_url;
      	this.log("Set", this.name, "to off");
    	}

    	this.httpRequest(url, "GET", function(error, response, body) {
      	if (!error && response.statusCode == 200) {
        	this.log('HTTP power function succeeded!');
        	callback();
      	}
      	else {
          this.log('HTTP power function failed: %s', error);
        	callback(error);
      		}
    	}.bind(this));
  	},

    getMuteState: function(callback) {
      var url;
      url = this.get_url;

      this.httpRequest(url, "GET", function(error, response, body) {
        if (!error && response.statusCode == 200) {
      		var jsonResponse = JSON.parse(body);
		      muteState = jsonResponse['Z'][0]['M'];

          if (muteState == 1) {
            callback(null, true);
          }
          else {
            callback(null, false);
          }
          this.log("Mute state is:", muteState);
      	}
        else {
          this.log('HTTP getMuteState function failed: %s', error);
          callback(error);
        }
      }.bind(this))

    },

    setMuteState: function(muteOn, callback) {
    	var url;

    	if (muteOn) {
      	url = this.mute_on;
      	this.log(this.name, "muted");
    	}
    	else {
      	url = this.mute_off;
      	this.log(this.name, "unmuted");
    	}

    	this.httpRequest(url, "GET", function(error, response, body) {
        if (!error && response.statusCode == 200) {
        	this.log('HTTP mute function succeeded!');
        	callback();
      	}
      	else {
          this.log('HTTP mute function failed: %s', error);
        	callback(error);
      		}
    	}.bind(this));
  	},

  	getVolume: function(callback) {
      var url;
      url = this.get_url;

      this.httpRequest(url, "GET", function(error, response, body) {
        if (!error && response.statusCode == 200) {
          var jsonResponse = JSON.parse(body);
  		    volumeValue = Number(jsonResponse['Z'][0]['V']);
          volume = (volumeValue - 161) * 0.5

          callback(null, Number(volume));

          this.log("MasterVolume is:", volume);
      	}
        else {
          this.log('HTTP getVolume function failed: %s', error);
        	callback(error);
      		}

      }.bind(this))

    },

  	setVolume: function(value, callback) {
      url = this.volume_url + (value * 2 + 161) + "VL"

  		this.httpRequest(url, "GET", function(error, response, body) {
        if (error) {
          this.log('HTTP volume function failed: %s', error);
          callback(error);
        }
        else {
          this.log("Set volume to", value, "db");
          callback();
          }
      }.bind(this));
  	},

  getServices: function() {
		var that = this;

		var informationService = new Service.AccessoryInformation();
		informationService
			.setCharacteristic(Characteristic.Name, this.name)
	    		.setCharacteristic(Characteristic.Manufacturer, "Pioneer")
	    		.setCharacteristic(Characteristic.Model, "VSX-2020")
	    		.setCharacteristic(Characteristic.SerialNumber, "1234567890");

		var switchService = new Service.Switch("Power State");
		switchService
			.getCharacteristic(Characteristic.On)
				.on('get', this.getPowerState.bind(this))
				.on('set', this.setPowerState.bind(this));

		var audioDeviceService = new PioneerAVR.AudioDeviceService("Audio Functions");
    /*
		audioDeviceService
			.getCharacteristic(PioneerAVR.Muting)
				.on('get', this.getMuteState.bind(this))
				.on('set', this.setMuteState.bind(this));
*/
		audioDeviceService
			.getCharacteristic(PioneerAVR.AudioVolume)
				.on('get', this.getVolume.bind(this))
				.on('set', this.setVolume.bind(this));

    //return [informationService, switchService];
		return [informationService, switchService, audioDeviceService];
		}
	}
}
<|endoftext|>


<commit_before>;(function(root, factory) {
  'use strict';

  if (typeof module === 'object' && module.exports) module.exports = factory();
  else if (typeof define === 'function' && define.amd) define([], factory);
  else root.PdfViewer = factory();
}(typeof window === 'object' ? window : this, function() {
  'use strict';

  function PdfViewer(opts) {
    if (opts.url) this.url = opts.url

  }

  PdfViewer.prototype.embed = function(container) {
    var html = [
      '<!DOCTYPE html><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">',
      '<link rel="stylesheet" href="http://localhost:8000/src/styles/viewer.css"/>',
      '<link rel="resource" type="application/l10n" href="http://localhost:8000/src/locale/locale.properties"/>',
      '',
      '',
      '',
      '

<button id="zoomOut" class="toolbarButton zoomOut" title="Zoom Out" tabindex="21" data-l10n-id="zoom_out">Zoom Out</button><button id="zoomIn" class="toolbarButton zoomIn" title="Zoom In" tabindex="22" data-l10n-id="zoom_in">Zoom In</button><button id="print" class="toolbarButton print" title="Print" tabindex="33" data-l10n-id="print">Print</button><button id="download" class="toolbarButton download" title="Download" tabindex="34" data-l10n-id="download">Download</button>

pdf

<button id="errorShowMore" data-l10n-id="error_more_info"> More Information </button><button id="errorShowLess" data-l10n-id="error_less_info" hidden="true"> Less Information </button>

<button id="errorClose" data-l10n-id="error_close"> Close </button>

<textarea id="errorMoreInfo" hidden="true" readonly="readonly"></textarea>

Enter the password to open this PDF file:

<input type="password" id="password" class="toolbarField" />

<button id="passwordCancel" class="overlayButton">Cancel</button><button id="passwordSubmit" class="overlayButton">OK</button>

'
    ].join('')

    var iframe = document.createElement('iframe')
    iframe.src = "javascript:void(function(){document.open();document.write('" + html + "');document.close();}())"
    container.appendChild(iframe)

  }

  return PdfViewer

}))
<commit_msg>update index.js<commit_after>;(function(root, factory) {
  'use strict';

  if (typeof module === 'object' && module.exports) module.exports = factory();
  else if (typeof define === 'function' && define.amd) define([], factory);
  else root.PdfViewer = factory();
}(typeof window === 'object' ? window : this, function() {
  'use strict';

  function PdfViewer(opts) {
    this.url = opts.url || ''
    this.onerror = opts.onerror || null
    this.host = opts.host || ''
  }

  PdfViewer.prototype.embed = function(container) {
    this.container = container

    var html = [
      '<!DOCTYPE html><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">',
      '<link rel="stylesheet" href="'+ this.host + '/src/styles/viewer.css"/>',
      '<link rel="resource" type="application/l10n" href="' + this.host + '/src/locale/locale.properties"/>',
      '',
      '',
      '

<button id="zoomOut" class="toolbarButton zoomOut" title="Zoom Out" tabindex="21" data-l10n-id="zoom_out">Zoom Out</button><button id="zoomIn" class="toolbarButton zoomIn" title="Zoom In" tabindex="22" data-l10n-id="zoom_in">Zoom In</button><button id="print" class="toolbarButton print" title="Print" tabindex="33" data-l10n-id="print">Print</button><button id="download" class="toolbarButton download" title="Download" tabindex="34" data-l10n-id="download">Download</button>

<button id="errorShowMore" data-l10n-id="error_more_info"> More Information </button><button id="errorShowLess" data-l10n-id="error_less_info" hidden="true"> Less Information </button>

<button id="errorClose" data-l10n-id="error_close"> Close </button>

<textarea id="errorMoreInfo" hidden="true" readonly="readonly"></textarea>

Enter the password to open this PDF file:

<input type="password" id="password" class="toolbarField" />

<button id="passwordCancel" class="overlayButton">Cancel</button><button id="passwordSubmit" class="overlayButton">OK</button>

'
    ].join('')

    var iframe = document.createElement('iframe')
    iframe.src = "javascript:(function(){document.open();document.write('" + html + "');document.close();}())"
    container.appendChild(iframe)

    var self =  this
    iframe.onload = function() {
      var iwin = iframe.contentWindow

      iwin.onerror = function() {
        if (self.onerror) self.onerror()
      }

      iwin.FILE_URL = self.url
    }

    return this

  }

  PdfViewer.prototype.destroy = function() {
    if (this.container) {
      this.container.innerHTML = ''
    }
  }

  return PdfViewer

}))
<|endoftext|>


<commit_before>'use strict';
const fancyLog = require('fancy-log');
const PluginError = require('plugin-error');
const through = require('through2');
const applySourceMap = require('vinyl-sourcemaps-apply');
const autoprefixer = require('autoprefixer');
const postcss = require('postcss');

module.exports = opts => {
	return through.obj((file, enc, cb) => {
		if (file.isNull()) {
			cb(null, file);
			return;
		}

		if (file.isStream()) {
			cb(new PluginError('gulp-autoprefixer', 'Streaming not supported'));
			return;
		}

		postcss(autoprefixer(opts)).process(file.contents.toString(), {
			map: file.sourceMap ? {annotation: false} : false,
			from: file.path,
			to: file.path
		}).then(res => {
			file.contents = Buffer.from(res.css);

			if (res.map && file.sourceMap) {
				applySourceMap(file, res.map.toString());
			}

			const warnings = res.warnings();

			if (warnings.length > 0) {
				fancyLog('gulp-autoprefixer:', '\n  ' + warnings.join('\n  '));
			}

			setImmediate(cb, null, file);
		}).catch(err => {
			const cssError = err.name === 'CssSyntaxError';

			if (cssError) {
				err.message += err.showSourceCode();
			}

			// Prevent stream unhandled exception from being suppressed by Promise
			setImmediate(cb, new PluginError('gulp-autoprefixer', err, {
				fileName: file.path,
				showStack: !cssError
			}));
		});
	});
};
<commit_msg>Update sourcemap paths to be relative to `file.base` (#92)<commit_after>'use strict';
const fancyLog = require('fancy-log');
const PluginError = require('plugin-error');
const through = require('through2');
const applySourceMap = require('vinyl-sourcemaps-apply');
const autoprefixer = require('autoprefixer');
const postcss = require('postcss');

module.exports = opts => {
	return through.obj((file, enc, cb) => {
		if (file.isNull()) {
			cb(null, file);
			return;
		}

		if (file.isStream()) {
			cb(new PluginError('gulp-autoprefixer', 'Streaming not supported'));
			return;
		}

		postcss(autoprefixer(opts)).process(file.contents.toString(), {
			map: file.sourceMap ? {annotation: false} : false,
			from: file.path,
			to: file.path
		}).then(res => {
			file.contents = Buffer.from(res.css);

			if (res.map && file.sourceMap) {
				const map = res.map.toJSON();
				map.file = file.relative;
				map.sources = map.sources.map(() => file.relative);
				applySourceMap(file, map);
			}

			const warnings = res.warnings();

			if (warnings.length > 0) {
				fancyLog('gulp-autoprefixer:', '\n  ' + warnings.join('\n  '));
			}

			setImmediate(cb, null, file);
		}).catch(err => {
			const cssError = err.name === 'CssSyntaxError';

			if (cssError) {
				err.message += err.showSourceCode();
			}

			// Prevent stream unhandled exception from being suppressed by Promise
			setImmediate(cb, new PluginError('gulp-autoprefixer', err, {
				fileName: file.path,
				showStack: !cssError
			}));
		});
	});
};
<|endoftext|>


<commit_before>
;(function (name, root, factory) {
  if (typeof exports === 'object') {
    module.exports = factory()
  }
  /* istanbul ignore next */
  else if (typeof define === 'function' && define.amd) {
    define(factory)
  }
  else {
    root[name] = factory()
  }
}('dcopy', this, function () {
  /**
   * Deep copy objects and arrays
   *
   * @param {Object/Array} target
   * @return {Object/Array} copy
   * @api public
   */

  return function (target) {
    if (/number|string|boolean/.test(typeof target)) {
      return target
    }
    if (target instanceof Date) {
      return new Date(target.getTime())
    }
    var copy = (target instanceof Array) ? [] : {}
    ;(function read (target, copy) {
      for (var key in target) {
        var obj = target[key]
        if (obj instanceof Array) {
          var value = []
          var last = add(copy, key, value)
          read(obj, last)
        }
        else if (obj instanceof Date) {
          var value = new Date(obj.getTime())
          add(copy, key, value)
        }
        else if (obj instanceof Object && typeof obj !== 'function') {
          var value = {}
          var last = add(copy, key, value)
          read(obj, last)
        }
        else {
          var value = obj
          add(copy, key, value)
        }
      }
    }(target, copy))
    return copy
  }

  /**
   * Adds a value to the copy object based on its type
   *
   * @api private
   */

  function add (copy, key, value) {
    if (copy instanceof Array) {
      copy.push(value)
      return copy[copy.length - 1]
    }
    else if (copy instanceof Object) {
      copy[key] = value
      return copy[key]
    }
  }
}))
<commit_msg>Minor refactoring<commit_after>
;(function (name, root, factory) {
  if (typeof exports === 'object') {
    module.exports = factory()
  }
  /* istanbul ignore next */
  else if (typeof define === 'function' && define.amd) {
    define(factory)
  }
  else {
    root[name] = factory()
  }
}('dcopy', this, function () {
  /**
   * Deep copy objects and arrays
   *
   * @param {Object/Array} target
   * @return {Object/Array} copy
   * @api public
   */

  return function (target) {
    if (/number|string|boolean/.test(typeof target)) {
      return target
    }
    if (target instanceof Date) {
      return new Date(target.getTime())
    }

    var copy = (target instanceof Array) ? [] : {}
    walk(target, copy)
    return copy

    function walk (target, copy) {
      for (var key in target) {
        var obj = target[key]
        if (obj instanceof Date) {
          var value = new Date(obj.getTime())
          add(copy, key, value)
        }
        else if (obj instanceof Function) {
          var value = obj
          add(copy, key, value)
        }
        else if (obj instanceof Array) {
          var value = []
          var last = add(copy, key, value)
          walk(obj, last)
        }
        else if (obj instanceof Object) {
          var value = {}
          var last = add(copy, key, value)
          walk(obj, last)
        }
        else {
          var value = obj
          add(copy, key, value)
        }
      }
    }
  }

  /**
   * Adds a value to the copy object based on its type
   *
   * @api private
   */

  function add (copy, key, value) {
    if (copy instanceof Array) {
      copy.push(value)
      return copy[copy.length - 1]
    }
    else if (copy instanceof Object) {
      copy[key] = value
      return copy[key]
    }
  }
}))
<|endoftext|>


<commit_before>var EventEmitter = require('events').EventEmitter
  , filename = __filename
  , current_trace_error = null
  , in_prepare = 0;

exports.empty_frame = '---------------------------------------------';
exports.async_trace_limit = 10;

exports.format_stack_frame = function(frame) {
  if (frame.getFileName() === exports.empty_frame) { return exports.empty_frame; }

  var format_location = function(frame) {
    if (frame.isNative()) { return 'native'; }
    if (frame.isEval()) { return 'eval at ' + frame.getEvalOrigin(); }
    var file = frame.getFileName()
      , line = frame.getLineNumber()
      , column = frame.getColumnNumber();
    return !file ? 'unknown source' : file + (!line ? '' : ':' + line + (!column ? '' : ':' + column));
  };
  var format_method = function(frame) {
    var function_name = frame.getFunctionName();

    if (!(frame.isToplevel() || frame.isConstructor())) {
      var method = frame.getMethodName();
      return frame.getTypeName() + '.' + (!function_name ? method || '<anonymous>' : function_name + (method && method !== function_name ? ' [as ' + method + ']' : ''));
    }
    if (frame.isConstructor()) { return 'new ' + (function_name || '<anonymous>'); }
    if (function_name) { return function_name; }
    return null;
  };

  var method = format_method(frame)
    , location = format_location(frame);
  return '    at ' + (!method ? location : method + ' (' + location + ')');
};

exports.format_stack = function(err, frames) {
  var lines = [];
  try {
    lines.push(err.toString());
  } catch (e) {
    console.log('Caught error in longjohn.  Please report this to matt.insler@gmail.com.');
  }
  Array.prototype.push.apply(lines, frames.map(exports.format_stack_frame));
  return lines.join('\n');
};

var create_callsite = function(location) {
  return Object.create({
    getFileName: function() { return location; },
    getLineNumber: function() { return null; },
    getFunctionName: function() { return null; },
    getTypeName: function() { return null; },
    getMethodName: function() { return null; },
    getColumnNumber: function() { return null; },
    isNative: function() { return null; }
  });
};

Error.prepareStackTrace = function(error, structured_stack_trace) {
  error.__cached_trace__ = structured_stack_trace.filter(function(f) {
    return f.getFileName() !== filename;
  });

  if (!error.__previous__ && current_trace_error) {
    error.__previous__ = current_trace_error;
  }

  ++in_prepare;
  var previous_trace = error.__previous__ ? error.__previous__.stack : null;
  --in_prepare;
  if (previous_trace) {
    error.__cached_trace__.push(create_callsite(exports.empty_frame));
    Array.prototype.push.apply(error.__cached_trace__, previous_trace);
  }

  if (in_prepare > 0) { return error.__cached_trace__; }
  return exports.format_stack(error, error.__cached_trace__);
};

var limit_frames = function(stack) {
  if (exports.async_trace_limit <= 0 || (stack && stack.__trace_count__ < exports.async_trace_limit)) { return; }

  var count = 1
    , previous = stack;
  while (previous) {
    if (count >= exports.async_trace_limit) {
      delete previous.__previous__;
      return;
    }
    previous = previous.__previous__;
    ++count;
  }
};

var wrap_callback = function(callback, location) {
  var trace_error = new Error();
  trace_error.__location__ = location;
  trace_error.__previous__ = current_trace_error;
  trace_error.__trace_count__ = current_trace_error ? current_trace_error.__trace_count__ + 1 : 1;

  limit_frames(trace_error);

  var new_callback = function() {
    current_trace_error = trace_error;
    try {
      callback.apply(this, arguments);
    } catch (e) {
      // Ensure we're formatting the Error in longjohn
      e.stack;
      throw e;
    } finally {
      current_trace_error = null;
    }
  };

  new_callback.__original_callback__ = callback;
  return new_callback;
};

var _on = EventEmitter.prototype.on
  , _addListener = EventEmitter.prototype.addListener
  , _once = EventEmitter.prototype.once
  , _removeListener = EventEmitter.prototype.removeListener;

EventEmitter.prototype.addListener = function(event, callback) {
  return _addListener.call(this, event, wrap_callback(callback, 'EventEmitter.addListener'));
};

EventEmitter.prototype.on = function(event, callback) {
  return _on.call(this, event, wrap_callback(callback, 'EventEmitter.on'));
};

EventEmitter.prototype.once = function(event, callback) {
  return _once.call(this, event, wrap_callback(callback, 'EventEmitter.once'));
};

EventEmitter.prototype.removeListener = function(event, callback) {
  var _this = this;
  var find_listener = function(callback) {
    var is_callback = function(val) {
      return val.__original_callback__ === callback ||
             (val.__original_callback__ && val.__original_callback__.listener && val.__original_callback__.listener.__original_callback__ === callback) ||
             (val.listener && val.listener.__original_callback__ === callback);
    };

    if (!_this._events || !_this._events[event]) { return null; }
    if (Array.isArray(_this._events[event])) {
      var x, listeners = _this._events[event] || [];
      for (x = 0; x < listeners.length; ++x) {
        if (is_callback(listeners[x])) {
          return listeners[x];
        }
      }
    } else if (is_callback(_this._events[event])) {
      return _this._events[event];
    }
    return null;
  };

  var listener = find_listener(callback);
  if (!listener || typeof(listener) !== 'function') { return this; }
  return _removeListener.call(this, event, listener);
}

var _nextTick = process.nextTick;

process.nextTick = function(callback) {
  return _nextTick.call(this, wrap_callback(callback, 'process.nextTick'));
};

var _setTimeout = global.setTimeout
  , _setInterval = global.setInterval;

global.setTimeout = function(callback, interval) {
  return _setTimeout.call(this, wrap_callback(callback, 'process.nextTick'), interval);
};

global.setInterval = function(callback, interval) {
  return _setInterval.call(this, wrap_callback(callback, 'process.nextTick'), interval);
};
<commit_msg>Clear trace_error variable from closure so it can potentially be garbage collected.<commit_after>var EventEmitter = require('events').EventEmitter
  , filename = __filename
  , current_trace_error = null
  , in_prepare = 0;

exports.empty_frame = '---------------------------------------------';
exports.async_trace_limit = 10;

exports.format_stack_frame = function(frame) {
  if (frame.getFileName() === exports.empty_frame) { return exports.empty_frame; }

  var format_location = function(frame) {
    if (frame.isNative()) { return 'native'; }
    if (frame.isEval()) { return 'eval at ' + frame.getEvalOrigin(); }
    var file = frame.getFileName()
      , line = frame.getLineNumber()
      , column = frame.getColumnNumber();
    return !file ? 'unknown source' : file + (!line ? '' : ':' + line + (!column ? '' : ':' + column));
  };
  var format_method = function(frame) {
    var function_name = frame.getFunctionName();

    if (!(frame.isToplevel() || frame.isConstructor())) {
      var method = frame.getMethodName();
      return frame.getTypeName() + '.' + (!function_name ? method || '<anonymous>' : function_name + (method && method !== function_name ? ' [as ' + method + ']' : ''));
    }
    if (frame.isConstructor()) { return 'new ' + (function_name || '<anonymous>'); }
    if (function_name) { return function_name; }
    return null;
  };

  var method = format_method(frame)
    , location = format_location(frame);
  return '    at ' + (!method ? location : method + ' (' + location + ')');
};

exports.format_stack = function(err, frames) {
  var lines = [];
  try {
    lines.push(err.toString());
  } catch (e) {
    console.log('Caught error in longjohn.  Please report this to matt.insler@gmail.com.');
  }
  Array.prototype.push.apply(lines, frames.map(exports.format_stack_frame));
  return lines.join('\n');
};

var create_callsite = function(location) {
  return Object.create({
    getFileName: function() { return location; },
    getLineNumber: function() { return null; },
    getFunctionName: function() { return null; },
    getTypeName: function() { return null; },
    getMethodName: function() { return null; },
    getColumnNumber: function() { return null; },
    isNative: function() { return null; }
  });
};

Error.prepareStackTrace = function(error, structured_stack_trace) {
  error.__cached_trace__ = structured_stack_trace.filter(function(f) {
    return f.getFileName() !== filename;
  });

  if (!error.__previous__ && current_trace_error) {
    error.__previous__ = current_trace_error;
  }

  ++in_prepare;
  var previous_trace = error.__previous__ ? error.__previous__.stack : null;
  --in_prepare;
  if (previous_trace) {
    error.__cached_trace__.push(create_callsite(exports.empty_frame));
    Array.prototype.push.apply(error.__cached_trace__, previous_trace);
  }

  if (in_prepare > 0) { return error.__cached_trace__; }
  return exports.format_stack(error, error.__cached_trace__);
};

var limit_frames = function(stack) {
  if (exports.async_trace_limit <= 0 || (stack && stack.__trace_count__ < exports.async_trace_limit)) { return; }

  var count = 1
    , previous = stack;
  while (previous) {
    if (count >= exports.async_trace_limit) {
      delete previous.__previous__;
      return;
    }
    previous = previous.__previous__;
    ++count;
  }
};

var wrap_callback = function(callback, location) {
  var trace_error = new Error();
  trace_error.__location__ = location;
  trace_error.__previous__ = current_trace_error;
  trace_error.__trace_count__ = current_trace_error ? current_trace_error.__trace_count__ + 1 : 1;

  limit_frames(trace_error);

  var new_callback = function() {
    current_trace_error = trace_error;
    // Clear trace_error variable from the closure, so it can potentially be garbage collected.
    trace_error = null;

    try {
      callback.apply(this, arguments);
    } catch (e) {
      // Ensure we're formatting the Error in longjohn
      e.stack;
      throw e;
    } finally {
      current_trace_error = null;
    }
  };

  new_callback.__original_callback__ = callback;
  return new_callback;
};

var _on = EventEmitter.prototype.on
  , _addListener = EventEmitter.prototype.addListener
  , _once = EventEmitter.prototype.once
  , _removeListener = EventEmitter.prototype.removeListener;

EventEmitter.prototype.addListener = function(event, callback) {
  return _addListener.call(this, event, wrap_callback(callback, 'EventEmitter.addListener'));
};

EventEmitter.prototype.on = function(event, callback) {
  return _on.call(this, event, wrap_callback(callback, 'EventEmitter.on'));
};

EventEmitter.prototype.once = function(event, callback) {
  return _once.call(this, event, wrap_callback(callback, 'EventEmitter.once'));
};

EventEmitter.prototype.removeListener = function(event, callback) {
  var _this = this;
  var find_listener = function(callback) {
    var is_callback = function(val) {
      return val.__original_callback__ === callback ||
             (val.__original_callback__ && val.__original_callback__.listener && val.__original_callback__.listener.__original_callback__ === callback) ||
             (val.listener && val.listener.__original_callback__ === callback);
    };

    if (!_this._events || !_this._events[event]) { return null; }
    if (Array.isArray(_this._events[event])) {
      var x, listeners = _this._events[event] || [];
      for (x = 0; x < listeners.length; ++x) {
        if (is_callback(listeners[x])) {
          return listeners[x];
        }
      }
    } else if (is_callback(_this._events[event])) {
      return _this._events[event];
    }
    return null;
  };

  var listener = find_listener(callback);
  if (!listener || typeof(listener) !== 'function') { return this; }
  return _removeListener.call(this, event, listener);
}

var _nextTick = process.nextTick;

process.nextTick = function(callback) {
  return _nextTick.call(this, wrap_callback(callback, 'process.nextTick'));
};

var _setTimeout = global.setTimeout
  , _setInterval = global.setInterval;

global.setTimeout = function(callback, interval) {
  return _setTimeout.call(this, wrap_callback(callback, 'process.nextTick'), interval);
};

global.setInterval = function(callback, interval) {
  return _setInterval.call(this, wrap_callback(callback, 'process.nextTick'), interval);
};
<|endoftext|>


<commit_before>var User = require('../lib/users');
var tasks = require('../lib/tasks');
var _ = require('lodash');

module.exports = function (server) {

  server.post('/messages', function (req, res, next) {
    var phoneNumber = req.params.From;
    var message = req.params.Body;
    var responseMessage = '';

    // TODO: Remove this when moving out of beta.
    console.log('Received "' + message + '" from ' + phoneNumber);

    User.findOrCreate(phoneNumber, function (err, user) {

      if (err) { res.send(500, err); console.log(err); return; };

      console.log(user);

      if (message.toUpperCase() === "RESTART") {
        user.set('status', null, function (err) {
          user.message('Resetting...');
        });
        return;
      }

      // TODO: This is a just a WIP while we get the general flow down.
      if (!user.status) {
        user.set('status', 'waitingOnZipCode', function (err, doc) {
          if (err) console.log(err);
          user.message('Welcome. What zip code are you in?');
        });
        res.send(200, { from: phoneNumber, user: user });
        return;
      }

      console.log(user.status);
      console.log(user.status === 'waitingOnZipCode');

      if (user.status === 'waitingOnZipCode') {
        console.log('I am inside the waitingOnZipCode conditional');
        var zip = user.message.match(/\d{5}/) && user.message.match(/\d{5}/)[0];

        console.log(zip);

        if (zip) {
          tasks.getResourcesByZip(zip, function (err, resources) {
            if (err) console.log(err);
            user.set({ zip: zip, resourcesRequested: resources, status: 'waitingOnResources' }, function (err) {
              if (err) console.log(err);
              user.message('Okay, the following resources are needed in ' + user.zip + ': ' + resources.join(', '));
            });
          });
        }
        res.send(200, { from: phoneNumber, user: user });
        return;
      }

      if (user.status === 'waitingOnResources') {
        user.message('Not implemented.');
        res.send(200, { from: phoneNumber, user: user });
        return;
      }

    });
  });

};<commit_msg>Cut out some conditional tomfoolery<commit_after>var User = require('../lib/users');
var tasks = require('../lib/tasks');
var _ = require('lodash');

module.exports = function (server) {

  server.post('/messages', function (req, res, next) {
    var phoneNumber = req.params.From;
    var message = req.params.Body;
    var responseMessage = '';

    // TODO: Remove this when moving out of beta.
    console.log('Received "' + message + '" from ' + phoneNumber);

    User.findOrCreate(phoneNumber, function (err, user) {

      if (err) { res.send(500, err); console.log(err); return; };

      console.log(user);

      if (message.toUpperCase() === "RESTART") {
        user.set('status', null, function (err) {
          user.message('Resetting...');
        });
        return;
      }

      // TODO: This is a just a WIP while we get the general flow down.
      if (!user.status) {
        user.set('status', 'waitingOnZipCode', function (err, doc) {
          if (err) console.log(err);
          user.message('Welcome. What zip code are you in?');
        });
        res.send(200, { from: phoneNumber, user: user });
        return;
      }

      if (user.status === 'waitingOnZipCode') {
        console.log('I am inside the waitingOnZipCode conditional');
        var zip = user.message.match(/\d{5}/);

        console.log(zip);

        if (zip) {
          tasks.getResourcesByZip(zip, function (err, resources) {
            if (err) console.log(err);
            user.set({ zip: zip, resourcesRequested: resources, status: 'waitingOnResources' }, function (err) {
              if (err) console.log(err);
              user.message('Okay, the following resources are needed in ' + user.zip + ': ' + resources.join(', '));
            });
          });
        }
        res.send(200, { from: phoneNumber, user: user });
        return;
      }

      if (user.status === 'waitingOnResources') {
        user.message('Not implemented.');
        res.send(200, { from: phoneNumber, user: user });
        return;
      }

    });
  });

};<|endoftext|>


<commit_before>/*
 * sass-partial-dependencies
 * https://github.com/tbremer/sass-partial-dependencies
 *
 * Copyright (c) 2014 Thomas Bremer, contributors
 * Licensed under the MIT license.
 */
 'use strict';
 var fs = require('fs');
 var path = require('path');
 var chalk = require('chalk');
 var glob = require('glob');
 var _ = require('underscore');

 module.exports = function(needle, haystack) {
 	var timerStart = Date.now();
 	var isVerbose = (process.argv.indexOf('--verbose') !== -1 || process.argv.indexOf('-v') !== -1) ? true : false;

	// Check if file exists | return false
	if (!fs.existsSync(needle)) {
		if (isVerbose) {
			console.log(chalk.cyan('File doesn\'t exist.'));
		}
		return false;
	}
	// Check if file is a *.css file, SASS doesn't import those
	if (path.extname(needle) === '.css') {
		if (isVerbose) {
			console.log(chalk.cyan('SASS won\'t import *.css files'));
		}
		return false;
	}

	//Look for verbose for logging options
	// We have passed our base checks, lets define some variables.

	var dependentFiles = [],
	    ext            = path.extname(needle);

	// If a hastack wasn't sent in, then we define it here. We also remove the needle from the haystack.
	if (haystack === undefined) {
		haystack = glob.sync('**/*' + ext);
	}
	haystack = _.without(haystack, needle);

	_.each(haystack, function(straw, index, array) {
		if (isVerbose) {
			console.log('Current file: ' + chalk.cyan(path.basename(straw)));
		}
		var thisContents, relPath, isDependent, isPartial;
		thisContents = fs.readFileSync(straw, {encoding: 'utf8'});
		relPath = path.relative(straw, needle).replace('../', '').replace('/_','/').replace(ext, '');
		if (relPath[0] === '_') {
			relPath = relPath.replace('_','');
		}
		isDependent = thisContents.indexOf(relPath) !== -1 ? true : false;
		if (isDependent) {
			isPartial = path.basename(straw)[0] === '_' ? true : false;
			if (isPartial) {
				if (isVerbose) {
					console.log(chalk.cyan(path.basename(needle)), chalk.white(' is a partial, adding it to the haystack'));
				}
				array.push(needle);
			} else {
				dependentFiles.push(straw);
			}
		}
	});

	if(dependentFiles.length === 0) {
		if (isVerbose) {
			console.log(chalk.cyan(path.basename(needle)), chalk.white(' does not have any dependencies'));
		}
		return false;
	}
	if (isVerbose) {
		console.log('Dependencies: ' + chalk.cyan(dependentFiles.join(', ')));
	}
	var timerEnd = Date.now();
	if (isVerbose) {
		console.log('Dependent Files took: ' + chalk.cyan((timerEnd - timerStart) + 'ms'));
	}
	return dependentFiles;
};
<commit_msg>Verbose logging, timer, stable code<commit_after>/*
 * sass-partial-dependencies
 * https://github.com/tbremer/sass-partial-dependencies
 *
 * Copyright (c) 2014 Thomas Bremer, contributors
 * Licensed under the MIT license.
 */
 'use strict';
 var fs = require('fs');
 var path = require('path');
 var chalk = require('chalk');
 var glob = require('glob');
 var _ = require('underscore');

 module.exports = function(needle, haystack) {
 	var timerStart = Date.now();
 	var isVerbose = (process.argv.indexOf('--verbose') !== -1 || process.argv.indexOf('-v') !== -1) ? true : false;

	// Check if file exists | return false
	if (!fs.existsSync(needle)) {
		if (isVerbose) {
			console.log(chalk.cyan('File doesn\'t exist.'));
		}
		return false;
	}
	// Check if file is a *.css file, SASS doesn't import those
	if (path.extname(needle) === '.css') {
		if (isVerbose) {
			console.log(chalk.cyan('SASS won\'t import *.css files'));
		}
		return false;
	}

	//Look for verbose for logging options
	// We have passed our base checks, lets define some variables.

	var dependentFiles = [],
	    ext            = path.extname(needle);

	// If a hastack wasn't sent in, then we define it here. We also remove the needle from the haystack.
	if (haystack === undefined) {
		haystack = glob.sync('**/*' + ext);
	}
	haystack = _.without(haystack, needle);

	_.each(haystack, function(straw, index, array) {
		var thisContents, relPath, isDependent, isPartial;
		thisContents = fs.readFileSync(straw, {encoding: 'utf8'});
		relPath = path.relative(straw, needle).replace('../', '').replace('/_','/').replace(ext, '');
		if (relPath[0] === '_') {
			relPath = relPath.replace('_','');
		}
		isDependent = thisContents.indexOf(relPath) !== -1 ? true : false;
		if (isDependent) {
			isPartial = path.basename(straw)[0] === '_' ? true : false;
			if (isPartial) {
				if (isVerbose) {
					console.log(chalk.cyan(path.basename(needle)), chalk.white(' is a partial, adding it to the haystack'));
				}
				array.push(needle);
			} else {
				dependentFiles.push(straw);
			}
		}
	});

	if(dependentFiles.length === 0) {
		if (isVerbose) {
			console.log(chalk.cyan(path.basename(needle)), chalk.white(' does not have any dependencies'));
		}
		return false;
	}
	if (isVerbose) {
		console.log('Dependencies: ' + chalk.cyan(dependentFiles.join(', ')));
	}
	var timerEnd = Date.now();
	if (isVerbose) {
		console.log('sass-get-dependencies took: ' + chalk.cyan((timerEnd - timerStart) + 'ms'));
	}
	return dependentFiles;
};
<|endoftext|>


<commit_before>// Load pre-compiled handlebars templates and put them on require('handlebars').templates
if (!require('handlebars').templates) {
  require('./views/compiled')
}

var App = require('./lib/app')
var TorrentManager = require('./lib/torrent-manager')

if (window.name === 'app') {
  new App(window.torrentManager)
} else {
  new TorrentManager()
}

<commit_msg>add todos<commit_after>// Load pre-compiled handlebars templates and put them on require('handlebars').templates
if (!require('handlebars').templates) {
  require('./views/compiled')
}

var App = require('./lib/app')
var TorrentManager = require('./lib/torrent-manager')

if (window.name === 'app') {
  new App(window.torrentManager)
} else {
  new TorrentManager()
}

// "file_handlers": {
//   "torrent": {
//     "types": [
//       "application/x-bittorrent"
//     ],
//     "title": "WebTorrent (BitTorrent client)"
//   }
// },

// navigator.registerProtocolHandler('web+mystuff', 'http://example.com/rph?q=%s', 'My App')

// TODO: if ESC and fullscreen, exit fullscreen

// chrome.runtime.onSuspend.addListener(function() {
//   // Do some simple clean-up tasks.
// })

// TODO: online/offline status
// https://developer.mozilla.org/en-US/docs/Online_and_offline_events
<|endoftext|>


<commit_before>/*global cordova, nfc */
/*jslint sloppy: false, browser: true */
"use strict";

function handleNfcFromIntentFilter() {

    // This was historically done in cordova.addConstructor but broke with PhoneGap-2.2.0.
    // We need to handle NFC from an Intent that launched the application, but *after*
    // the code in the application's deviceready has run.  After upgrading to 2.2.0,
    // addConstructor was finishing *before* deviceReady was complete and the
    // ndef listeners had not been registered.
    // It seems like there should be a better solution.
    setTimeout(
        function () {
            cordova.exec(
                function () {
                    console.log("Initialized the NfcPlugin");
                },
                function (reason) {
                    window.alert("Failed to initialize the NfcPlugin " + reason);
                },
                "NfcPlugin", "init", []
            );
        }, 10
    );
}

document.addEventListener('deviceready', handleNfcFromIntentFilter, false);

var ndef = {
    // see android.nfc.NdefRecord for documentation about constants
    // http://developer.android.com/reference/android/nfc/NdefRecord.html
    TNF_EMPTY: 0x0,
    TNF_WELL_KNOWN: 0x01,
    TNF_MIME_MEDIA: 0x02,
    TNF_ABSOLUTE_URI: 0x03,
    TNF_EXTERNAL_TYPE: 0x04,
    TNF_UNKNOWN: 0x05,
    TNF_UNCHANGED: 0x06,
    TNF_RESERVED: 0x07,

    RTD_TEXT: [0x54], // "T"
    RTD_URI: [0x55], // "U"
    RTD_SMART_POSTER: [0x53, 0x70], // "Sp"
    RTD_ALTERNATIVE_CARRIER: [0x61, 0x63], // "ac"
    RTD_HANDOVER_CARRIER: [0x48, 0x63], // "Hc"
    RTD_HANDOVER_REQUEST: [0x48, 0x72], // "Hr"
    RTD_HANDOVER_SELECT: [0x48, 0x73], // "Hs"

    /**
     * Creates a JSON representation of a NDEF Record.
     *
     * @tnf 3-bit TNF (Type Name Format) - use one of the TNF_* constants
     * @type byte array, containing zero to 255 bytes, must not be null
     * @id byte array, containing zero to 255 bytes, must not be null
     * @payload byte array, containing zero to (2 ** 32 - 1) bytes, must not be null
     *
     * @returns JSON representation of a NDEF record
     *
     * @see Ndef.textRecord, Ndef.uriRecord and Ndef.mimeMediaRecord for examples
     */
    record: function (tnf, type, id, payload) {
        return {
            tnf: tnf,
            type: type,
            id: id,
            payload: payload
        };
    },

    /**
     * Helper that creates a NDEF record containing plain text.
     *
     * @text String
     * @id byte[] (optional)
     */
    textRecord: function (text, id) {
        var languageCode = 'en', // TODO get from browser
            payload = [];

        if (!id) { id = []; }

        payload.push(languageCode.length);
        nfc.concatArray(payload, nfc.stringToBytes(languageCode));
        nfc.concatArray(payload, nfc.stringToBytes(text));

        return ndef.record(ndef.TNF_WELL_KNOWN, ndef.RTD_TEXT, id, payload);
    },

    /**
     * Helper that creates a NDEF record containing an absolute URI.
     *
     * @text String
     * @id byte[] (optional)
     */
    uriRecord: function (text, id) {
        if (!id) { id = []; }
        return ndef.record(ndef.TNF_ABSOLUTE_URI, ndef.RTD_URI, id, nfc.stringToBytes(text));
    },

    /**
     * Helper that creates a NDEF record containing an mimeMediaRecord.
     *
     * @mimeType String
     * @payload byte[]
     * @id byte[] (optional)
     */
    mimeMediaRecord: function (mimeType, payload, id) {
        if (!id) { id = []; }
        return ndef.record(ndef.TNF_MIME_MEDIA, nfc.stringToBytes(mimeType), id, payload);
    }
};

var nfc = {

    addTagDiscoveredListener: function (callback, win, fail) {
        document.addEventListener("tag", callback, false);
        cordova.exec(win, fail, "NfcPlugin", "registerTag", []);
    },

    addMimeTypeListener: function (mimeType, callback, win, fail) {
        document.addEventListener("ndef-mime", callback, false);
        cordova.exec(win, fail, "NfcPlugin", "registerMimeType", [mimeType]);
    },

    addNdefListener: function (callback, win, fail) {
        document.addEventListener("ndef", callback, false);
        cordova.exec(win, fail, "NfcPlugin", "registerNdef", []);
    },

    addNdefFormatableListener: function (callback, win, fail) {
        document.addEventListener("ndef-formatable", callback, false);
        cordova.exec(win, fail, "NfcPlugin", "registerNdefFormatable", []);
    },

    write: function (ndefMessage, win, fail) {
        cordova.exec(win, fail, "NfcPlugin", "writeTag", [ndefMessage]);
    },

    share: function (ndefMessage, win, fail) {
        cordova.exec(win, fail, "NfcPlugin", "shareTag", [ndefMessage]);
    },

    unshare: function (win, fail) {
        cordova.exec(win, fail, "NfcPlugin", "unshareTag", []);
    },

    erase: function (win, fail) {
        cordova.exec(win, fail, "NfcPlugin", "eraseTag", []);
    },

    removeTagDiscoveredListener: function (callback, win, fail) {
        document.removeEventListener("tag", callback, false);
        cordova.exec(win, fail, "NfcPlugin", "removeTag", []);
    },

    removeMimeTypeListener: function(mimeType, callback, win, fail) {
        document.removeEventListener("ndef-mime", callback, false);
        cordova.exec(win, fail, "NfcPlugin", "removeMimeType", [mimeType]);
    },

    removeNdefListener: function (callback, win, fail) {
        document.removeEventListener("ndef", callback, false);
        cordova.exec(win, fail, "NfcPlugin", "removeNdef", []);
    },

    concatArray: function (a1, a2) { // this isn't built in?
        for (var i = 0; i < a2.length; i++) {
            a1.push(a2[i]);
        }
        return a1;
    },

    bytesToString: function (bytes) {
        var bytesAsString = "";
        for (var i = 0; i < bytes.length; i++) {
            bytesAsString += String.fromCharCode(bytes[i]);
        }
        return bytesAsString;
    },

    // http://stackoverflow.com/questions/1240408/reading-bytes-from-a-javascript-string#1242596
    stringToBytes: function (str) {
        var ch, st, re = [];
        for (var i = 0; i < str.length; i++ ) {
            ch = str.charCodeAt(i);  // get char
            st = [];                 // set up "stack"
            do {
                st.push( ch & 0xFF );  // push byte to stack
                ch = ch >> 8;          // shift value down by 1 byte
            } while ( ch );
            // add stack contents to result
            // done because chars have "wrong" endianness
            re = re.concat( st.reverse() );
        }
        // return an array of bytes
        return re;
    },

    bytesToHexString: function (bytes) {
        var dec, hexstring, bytesAsHexString = "";
        for (var i = 0; i < bytes.length; i++) {
            if (bytes[i] >= 0) {
                dec = bytes[i];
            } else {
                dec = 256 + bytes[i];
            }
            hexstring = dec.toString(16);
            // zero padding
            if (hexstring.length == 1) {
                hexstring = "0" + hexstring;
            }
            bytesAsHexString += hexstring;
        }
        return bytesAsHexString;
    }
};
<commit_msg>pass empty array as data for erase, since it's implemented with writeTag<commit_after>/*global cordova, nfc */
/*jslint sloppy: false, browser: true */
"use strict";

function handleNfcFromIntentFilter() {

    // This was historically done in cordova.addConstructor but broke with PhoneGap-2.2.0.
    // We need to handle NFC from an Intent that launched the application, but *after*
    // the code in the application's deviceready has run.  After upgrading to 2.2.0,
    // addConstructor was finishing *before* deviceReady was complete and the
    // ndef listeners had not been registered.
    // It seems like there should be a better solution.
    setTimeout(
        function () {
            cordova.exec(
                function () {
                    console.log("Initialized the NfcPlugin");
                },
                function (reason) {
                    console.log("Failed to initialize the NfcPlugin " + reason);
                },
                "NfcPlugin", "init", []
            );
        }, 10
    );
}

document.addEventListener('deviceready', handleNfcFromIntentFilter, false);

var ndef = {
    // see android.nfc.NdefRecord for documentation about constants
    // http://developer.android.com/reference/android/nfc/NdefRecord.html
    TNF_EMPTY: 0x0,
    TNF_WELL_KNOWN: 0x01,
    TNF_MIME_MEDIA: 0x02,
    TNF_ABSOLUTE_URI: 0x03,
    TNF_EXTERNAL_TYPE: 0x04,
    TNF_UNKNOWN: 0x05,
    TNF_UNCHANGED: 0x06,
    TNF_RESERVED: 0x07,

    RTD_TEXT: [0x54], // "T"
    RTD_URI: [0x55], // "U"
    RTD_SMART_POSTER: [0x53, 0x70], // "Sp"
    RTD_ALTERNATIVE_CARRIER: [0x61, 0x63], // "ac"
    RTD_HANDOVER_CARRIER: [0x48, 0x63], // "Hc"
    RTD_HANDOVER_REQUEST: [0x48, 0x72], // "Hr"
    RTD_HANDOVER_SELECT: [0x48, 0x73], // "Hs"

    /**
     * Creates a JSON representation of a NDEF Record.
     *
     * @tnf 3-bit TNF (Type Name Format) - use one of the TNF_* constants
     * @type byte array, containing zero to 255 bytes, must not be null
     * @id byte array, containing zero to 255 bytes, must not be null
     * @payload byte array, containing zero to (2 ** 32 - 1) bytes, must not be null
     *
     * @returns JSON representation of a NDEF record
     *
     * @see Ndef.textRecord, Ndef.uriRecord and Ndef.mimeMediaRecord for examples
     */
    record: function (tnf, type, id, payload) {
        return {
            tnf: tnf,
            type: type,
            id: id,
            payload: payload
        };
    },

    /**
     * Helper that creates a NDEF record containing plain text.
     *
     * @text String
     * @id byte[] (optional)
     */
    textRecord: function (text, id) {
        var languageCode = 'en', // TODO get from browser
            payload = [];

        if (!id) { id = []; }

        payload.push(languageCode.length);
        nfc.concatArray(payload, nfc.stringToBytes(languageCode));
        nfc.concatArray(payload, nfc.stringToBytes(text));

        return ndef.record(ndef.TNF_WELL_KNOWN, ndef.RTD_TEXT, id, payload);
    },

    /**
     * Helper that creates a NDEF record containing an absolute URI.
     *
     * @text String
     * @id byte[] (optional)
     */
    uriRecord: function (text, id) {
        if (!id) { id = []; }
        return ndef.record(ndef.TNF_ABSOLUTE_URI, ndef.RTD_URI, id, nfc.stringToBytes(text));
    },

    /**
     * Helper that creates a NDEF record containing an mimeMediaRecord.
     *
     * @mimeType String
     * @payload byte[]
     * @id byte[] (optional)
     */
    mimeMediaRecord: function (mimeType, payload, id) {
        if (!id) { id = []; }
        return ndef.record(ndef.TNF_MIME_MEDIA, nfc.stringToBytes(mimeType), id, payload);
    }
};

var nfc = {

    addTagDiscoveredListener: function (callback, win, fail) {
        document.addEventListener("tag", callback, false);
        cordova.exec(win, fail, "NfcPlugin", "registerTag", []);
    },

    addMimeTypeListener: function (mimeType, callback, win, fail) {
        document.addEventListener("ndef-mime", callback, false);
        cordova.exec(win, fail, "NfcPlugin", "registerMimeType", [mimeType]);
    },

    addNdefListener: function (callback, win, fail) {
        document.addEventListener("ndef", callback, false);
        cordova.exec(win, fail, "NfcPlugin", "registerNdef", []);
    },

    addNdefFormatableListener: function (callback, win, fail) {
        document.addEventListener("ndef-formatable", callback, false);
        cordova.exec(win, fail, "NfcPlugin", "registerNdefFormatable", []);
    },

    write: function (ndefMessage, win, fail) {
        cordova.exec(win, fail, "NfcPlugin", "writeTag", [ndefMessage]);
    },

    share: function (ndefMessage, win, fail) {
        cordova.exec(win, fail, "NfcPlugin", "shareTag", [ndefMessage]);
    },

    unshare: function (win, fail) {
        cordova.exec(win, fail, "NfcPlugin", "unshareTag", []);
    },

    erase: function (win, fail) {
        cordova.exec(win, fail, "NfcPlugin", "eraseTag", [[]]);
    },

    removeTagDiscoveredListener: function (callback, win, fail) {
        document.removeEventListener("tag", callback, false);
        cordova.exec(win, fail, "NfcPlugin", "removeTag", []);
    },

    removeMimeTypeListener: function(mimeType, callback, win, fail) {
        document.removeEventListener("ndef-mime", callback, false);
        cordova.exec(win, fail, "NfcPlugin", "removeMimeType", [mimeType]);
    },

    removeNdefListener: function (callback, win, fail) {
        document.removeEventListener("ndef", callback, false);
        cordova.exec(win, fail, "NfcPlugin", "removeNdef", []);
    },

    concatArray: function (a1, a2) { // this isn't built in?
        for (var i = 0; i < a2.length; i++) {
            a1.push(a2[i]);
        }
        return a1;
    },

    bytesToString: function (bytes) {
        var bytesAsString = "";
        for (var i = 0; i < bytes.length; i++) {
            bytesAsString += String.fromCharCode(bytes[i]);
        }
        return bytesAsString;
    },

    // http://stackoverflow.com/questions/1240408/reading-bytes-from-a-javascript-string#1242596
    stringToBytes: function (str) {
        var ch, st, re = [];
        for (var i = 0; i < str.length; i++ ) {
            ch = str.charCodeAt(i);  // get char
            st = [];                 // set up "stack"
            do {
                st.push( ch & 0xFF );  // push byte to stack
                ch = ch >> 8;          // shift value down by 1 byte
            } while ( ch );
            // add stack contents to result
            // done because chars have "wrong" endianness
            re = re.concat( st.reverse() );
        }
        // return an array of bytes
        return re;
    },

    bytesToHexString: function (bytes) {
        var dec, hexstring, bytesAsHexString = "";
        for (var i = 0; i < bytes.length; i++) {
            if (bytes[i] >= 0) {
                dec = bytes[i];
            } else {
                dec = 256 + bytes[i];
            }
            hexstring = dec.toString(16);
            // zero padding
            if (hexstring.length == 1) {
                hexstring = "0" + hexstring;
            }
            bytesAsHexString += hexstring;
        }
        return bytesAsHexString;
    }
};
<|endoftext|>


<commit_before>//     proxy-observe
//
//     Copyright (c) 2015, 2016 Simon Y. Blackwell, AnyWhichWay
//     MIT License - http://opensource.org/licenses/mit-license.php
(function() {
	"use strict";
	// Creates and returns a Proxy wrapping a target so that all changes can be trapped and forwarded to
	// a callback. The callback takes an array of changes just like the traditional original Chrome Object.observe
	// {object:<object changed>,name:<field changed>,type:add|update|delete|reconfigure|preventExtensions|setPrototype,oldValue:<old value if update | delete>}
	// The acceptlist can be add|update|delete|reconfigure|preventExtensions|setPrototype.
	// v 0.0.10 to support pausing and restarting observation two additional constructor arguments are available to Object.observe:
	// pausable - create the Observer so it can be paused
	// pause - create observer in paused state
	// if pausable is true then an additional method deliver(ignorePrevious) is available to start delivery
	// to pause delivery set a property called pause on the function deliver to true
	// pausable is optional to reduce the chance of shadowing a property or method on any existing code called deliver
	if(!Object.observe && typeof(Proxy)==="function") {
		function Observer(target,callback,acceptlist,pausable,pause) {
	    	var me = this, proxy;
	    	function deliver(ignorePrevious) {
	    		if(!deliver.pause) {
	        		if(me.changeset.length>0) {
	        			if(!ignorePrevious) {
		    	    		var changes = me.changeset.filter(function(change) { return !acceptlist || acceptlist.indexOf(change.type)>=0; });
		        			if(changes.length>0) {
		        				callback(changes);
		        			}
	        			}
	        			me.changeset = [];
	        		}
	        		setTimeout(deliver,10);
	    		}
	    	}
	    	deliver.pause = pause;
		    me.get = function(target, property) {
		    	if(property==="__observer__") {
		    		return me;
		    	}
		    	if(property==="unobserve") {
		    		return function() {
		    			Object.unobserve(target);
		    			return target;
		    		};
		    	}
		    	if(pausable && property==="deliver") {
		    		return deliver;
		    	}
		    	return target[property];
		    }
	    	me.target = target;
	    	me.changeset = [];
	    	if(!me.target.__observerCallbacks__) {
	    		// __observerCallbacks__ is used as an index to get at the proxy which is the observer, so we can unobserve
	    		Object.defineProperty(target,"__observerCallbacks__",{enumerable:false,configurable:true,writable:false,value:[]});
	    		Object.defineProperty(target,"__observers__",{enumerable:false,configurable:true,writable:false,value:[]});
	    	}
	    	me.target.__observerCallbacks__.push(callback);
	    	me.target.__observers__.push(this);
	    	proxy = new Proxy(target,me);
	    	deliver();
	    	return proxy;
	    }
	    Observer.prototype.set = function(target, property, value) { // , receiver
	    	var oldvalue = target[property];
	    	var type = (oldvalue===undefined ? "add" : "update");
	    	target[property] = value;
	    	if(target.__observers__.indexOf(this)>=0 && (!this.acceptlist || this.acceptlist.indexOf(type)>=0)) {
	        	var change = {object:target,name:property,type:type};
	        	if(type==="update") {
	        		change.oldValue = oldvalue;
	        	}
	        	this.changeset.push(change);
	    	}
	    	return true;
	    };
	    Observer.prototype.deleteProperty = function(target, property) {
	    	var oldvalue = target[property];
	    	//if(typeof(oldvalue)!=="undefined") {
		    	delete target[property];
		    	if(target.__observers__.indexOf(this)>=0 && !this.acceptlist || this.acceptlist.indexOf("delete")>=0) {
		        	var change = {object:target,name:property,type:"delete",oldValue:oldvalue};
		        	this.changeset.push(change);
		    	}
	    	//}
	    	return true;
	    };
	    Observer.prototype.defineProperty = function(target, property, descriptor) {
	    	Object.defineProperty(target, property, descriptor);
	    	if(target.__observers__.indexOf(this)>=0 && !this.acceptlist || this.acceptlist.indexOf("reconfigure")>=0) {
	        	var change = {object:target,name:property,type:"reconfigure"};
	        	this.changeset.push(change);
	    	}
	    	return true;
	    };
	    Observer.prototype.setPrototypeOf = function(target, prototype) {
	    	var oldvalue = Object.getPrototypeOf(target);
	    	Object.setPrototypeOf(target, prototype);
	    	if(target.__observers__.indexOf(this)>=0 && !this.acceptlist || this.acceptlist.indexOf("setPrototype")>=0) {
	        	var change = {object:target,name:"__proto__",type:"setPrototype",oldValue:oldvalue};
	        	this.changeset.push(change);
	    	}
	    	return true;
	    };
	    Observer.prototype.preventExtensions = function(target) {
	        Object.preventExtensions(target);
	    	if(target.__observers__.indexOf(this)>=0 && !this.acceptlist || this.acceptlist.indexOf("preventExtensions")>=0) {
	        	var change = {object:target,type:"preventExtensions"};
	        	this.changeset.push(change);
	    	}
	    	return true;
	    };
	    Object.observe = function(object,callback,acceptlist,pausable,pause) {
	    	return new Observer(object,callback,acceptlist,pausable,pause);
	    };
	    Object.unobserve = function(object,callback) {
	    	if(object.__observerCallbacks__) {
	    		if(!callback) {
	    			object.__observerCallbacks__.splice(0,object.__observerCallbacks__.length);
	    			object.__observers__.splice(0,object.__observers__.length);
	    			return;
	    		}
	    		object.__observerCallbacks__.forEach(function(observercallback,i) {
	    			if(callback===observercallback) {
	    				object.__observerCallbacks__.splice(i,1);
	    				delete object.__observers__[i].callback;
	    				object.__observers__.splice(i,1);
	    			}
	    		});
	    	}
	    };

	    Array.observe = function(object,callback,acceptlist,pausable,pause) {
	    	if(!(object instanceof Array) && !Array.isArray(object)) {
	    		throw new TypeError("First argument to Array.observer is not an Array");
	    	}
	    	var arrayproxy = new Proxy(object,{get: function(target,property) {
	    		if(property==="unobserve") {
		    		return function(callback) {
		    			if(callback) {
		    				return Object.unobserve(target,callback);
		    			}
		    			return target.unobserve();
		    		};
		    	}
	    		if(property==="splice") {
	    			return function(start,end) {
	    				if(typeof(start)!=="number" || typeof(end)!=="number") {
	    					throw new TypeError("First two arguments to Array slice are not number, number");
	    				}
	    	    		var removed = this.slice(start,start+end);
	    	    		var addedCount = (arguments.length > 1 ? arguments.length-2 : 0);
	    	    		var change =  {object:object,type:"splice",index:start,removed:removed,addedCount:addedCount};
	    	    		target.splice.apply(target,arguments);
	    	    		if(acceptlist.indexOf("splice")>=0) {
	    	    			proxy.__observer__.changeset.push(change);
	    	    		}
	    	    	}
	    		}
	    		if(property==="push") {
	    			 return function(item) {
	    		    	return this.splice(this.length,0,item);
	    		    }
	    		}
	    		if(property==="pop") {
	    			 return function() {
	    		    	return this.splice(this.length,1);
	    		    }
	    		}
	    		if(property==="unshift") {
	    			 return function(item) {
    		    		return this.splice(0,0,item);
    		    	}
	    		}
	    		if(property==="shift") {
	    			return function() {
	    	    		return this.splice(0,1);
	    	    	}
	    		}
	    		return target[property];
	    	}});
	    	var proxy = Object.observe(arrayproxy,function(changeset) {
	    		var changes = changeset.filter(function(change) { return change.name!=="length" && change.name!=="add" && (!acceptlist || acceptlist.indexOf(change.type)>=0); });
	    		if(changes.length>0) {
	    			callback(changes);
	    		}
	    	},acceptlist,pausable,pause);
	    	return proxy;
	    };
	    Array.unobserve = function(object,callback) {
		  return object.unobserve(callback);
	    }
	}
	Object.deepObserve = function(object,callback,parts) {
		parts = (parts ? parts : []);
		var keys = Object.keys(object);
		keys.forEach(function(key) {
			if(object[key] instanceof Object) {
				var newparts = parts.slice(0);
				newparts.push(key);
				object[key] = Object.deepObserve(object[key],callback,newparts);
			}
		});
		var observed = Object.observe(object,function(changeset) {
			var changes = [];
			function recurse(name,rootObject,oldObject,newObject,path) {
				if(newObject instanceof Object) {
					var newkeys = Object.keys(newObject);
					newkeys.forEach(function(key) {
						if(!oldObject || (oldObject[key]!==newObject[key])) {
							var oldvalue = (oldObject && oldObject[key]!==undefined ? oldObject[key] : undefined);
							var change = (oldvalue===undefined ? "add" : "update");
							var keypath = path + "." + key;
							changes.push({name:name,object:rootObject,type:change,oldValue:oldvalue,newValue:newObject[key],keypath:keypath});
							recurse(name,rootObject,oldvalue,newObject[key],keypath);
						}
					});
				} else if(oldObject instanceof Object) {
					var oldkeys = Object.keys(oldObject);
					oldkeys.forEach(function(key) {
						var change = (newObject===null ? "update" : "delete");
						var keypath = path + "." + key;
						changes.push({name:name,object:rootObject,type:change,oldValue:oldObject[key],newValue:newObject,keypath:keypath});
						recurse(name,rootObject,oldObject[key],undefined,keypath);
					});
				}
			}
			changeset.forEach(function(change) {
				var keypath = (parts.length>0 ? parts.join(".") + "." : "") + change.name;
				changes.push({name:change.name,object:change.object,type:change.type,oldValue:change.oldValue,newValue:change.object[change.name],keypath:keypath});
				recurse(change.name,change.object,change.oldValue,change.object[change.name],keypath);
			});
			callback(changes);
		});
		return observed;
	};
})();<commit_msg>Fixed off-by-one error in calculating array index in pop handler<commit_after>//     proxy-observe
//
//     Copyright (c) 2015, 2016 Simon Y. Blackwell, AnyWhichWay
//     MIT License - http://opensource.org/licenses/mit-license.php
(function() {
	"use strict";
	// Creates and returns a Proxy wrapping a target so that all changes can be trapped and forwarded to
	// a callback. The callback takes an array of changes just like the traditional original Chrome Object.observe
	// {object:<object changed>,name:<field changed>,type:add|update|delete|reconfigure|preventExtensions|setPrototype,oldValue:<old value if update | delete>}
	// The acceptlist can be add|update|delete|reconfigure|preventExtensions|setPrototype.
	// v 0.0.10 to support pausing and restarting observation two additional constructor arguments are available to Object.observe:
	// pausable - create the Observer so it can be paused
	// pause - create observer in paused state
	// if pausable is true then an additional method deliver(ignorePrevious) is available to start delivery
	// to pause delivery set a property called pause on the function deliver to true
	// pausable is optional to reduce the chance of shadowing a property or method on any existing code called deliver
	if(!Object.observe && typeof(Proxy)==="function") {
		function Observer(target,callback,acceptlist,pausable,pause) {
	    	var me = this, proxy;
	    	function deliver(ignorePrevious) {
	    		if(!deliver.pause) {
	        		if(me.changeset.length>0) {
	        			if(!ignorePrevious) {
		    	    		var changes = me.changeset.filter(function(change) { return !acceptlist || acceptlist.indexOf(change.type)>=0; });
		        			if(changes.length>0) {
		        				callback(changes);
		        			}
	        			}
	        			me.changeset = [];
	        		}
	        		setTimeout(deliver,10);
	    		}
	    	}
	    	deliver.pause = pause;
		    me.get = function(target, property) {
		    	if(property==="__observer__") {
		    		return me;
		    	}
		    	if(property==="unobserve") {
		    		return function() {
		    			Object.unobserve(target);
		    			return target;
		    		};
		    	}
		    	if(pausable && property==="deliver") {
		    		return deliver;
		    	}
		    	return target[property];
		    }
	    	me.target = target;
	    	me.changeset = [];
	    	if(!me.target.__observerCallbacks__) {
	    		// __observerCallbacks__ is used as an index to get at the proxy which is the observer, so we can unobserve
	    		Object.defineProperty(target,"__observerCallbacks__",{enumerable:false,configurable:true,writable:false,value:[]});
	    		Object.defineProperty(target,"__observers__",{enumerable:false,configurable:true,writable:false,value:[]});
	    	}
	    	me.target.__observerCallbacks__.push(callback);
	    	me.target.__observers__.push(this);
	    	proxy = new Proxy(target,me);
	    	deliver();
	    	return proxy;
	    }
	    Observer.prototype.set = function(target, property, value) { // , receiver
	    	var oldvalue = target[property];
	    	var type = (oldvalue===undefined ? "add" : "update");
	    	target[property] = value;
	    	if(target.__observers__.indexOf(this)>=0 && (!this.acceptlist || this.acceptlist.indexOf(type)>=0)) {
	        	var change = {object:target,name:property,type:type};
	        	if(type==="update") {
	        		change.oldValue = oldvalue;
	        	}
	        	this.changeset.push(change);
	    	}
	    	return true;
	    };
	    Observer.prototype.deleteProperty = function(target, property) {
	    	var oldvalue = target[property];
	    	//if(typeof(oldvalue)!=="undefined") {
		    	delete target[property];
		    	if(target.__observers__.indexOf(this)>=0 && !this.acceptlist || this.acceptlist.indexOf("delete")>=0) {
		        	var change = {object:target,name:property,type:"delete",oldValue:oldvalue};
		        	this.changeset.push(change);
		    	}
	    	//}
	    	return true;
	    };
	    Observer.prototype.defineProperty = function(target, property, descriptor) {
	    	Object.defineProperty(target, property, descriptor);
	    	if(target.__observers__.indexOf(this)>=0 && !this.acceptlist || this.acceptlist.indexOf("reconfigure")>=0) {
	        	var change = {object:target,name:property,type:"reconfigure"};
	        	this.changeset.push(change);
	    	}
	    	return true;
	    };
	    Observer.prototype.setPrototypeOf = function(target, prototype) {
	    	var oldvalue = Object.getPrototypeOf(target);
	    	Object.setPrototypeOf(target, prototype);
	    	if(target.__observers__.indexOf(this)>=0 && !this.acceptlist || this.acceptlist.indexOf("setPrototype")>=0) {
	        	var change = {object:target,name:"__proto__",type:"setPrototype",oldValue:oldvalue};
	        	this.changeset.push(change);
	    	}
	    	return true;
	    };
	    Observer.prototype.preventExtensions = function(target) {
	        Object.preventExtensions(target);
	    	if(target.__observers__.indexOf(this)>=0 && !this.acceptlist || this.acceptlist.indexOf("preventExtensions")>=0) {
	        	var change = {object:target,type:"preventExtensions"};
	        	this.changeset.push(change);
	    	}
	    	return true;
	    };
	    Object.observe = function(object,callback,acceptlist,pausable,pause) {
	    	return new Observer(object,callback,acceptlist,pausable,pause);
	    };
	    Object.unobserve = function(object,callback) {
	    	if(object.__observerCallbacks__) {
	    		if(!callback) {
	    			object.__observerCallbacks__.splice(0,object.__observerCallbacks__.length);
	    			object.__observers__.splice(0,object.__observers__.length);
	    			return;
	    		}
	    		object.__observerCallbacks__.forEach(function(observercallback,i) {
	    			if(callback===observercallback) {
	    				object.__observerCallbacks__.splice(i,1);
	    				delete object.__observers__[i].callback;
	    				object.__observers__.splice(i,1);
	    			}
	    		});
	    	}
	    };

	    Array.observe = function(object,callback,acceptlist,pausable,pause) {
	    	if(!(object instanceof Array) && !Array.isArray(object)) {
	    		throw new TypeError("First argument to Array.observer is not an Array");
	    	}
	    	var arrayproxy = new Proxy(object,{get: function(target,property) {
	    		if(property==="unobserve") {
		    		return function(callback) {
		    			if(callback) {
		    				return Object.unobserve(target,callback);
		    			}
		    			return target.unobserve();
		    		};
		    	}
	    		if(property==="splice") {
	    			return function(start,end) {
	    				if(typeof(start)!=="number" || typeof(end)!=="number") {
	    					throw new TypeError("First two arguments to Array slice are not number, number");
	    				}
	    	    		var removed = this.slice(start,start+end);
	    	    		var addedCount = (arguments.length > 1 ? arguments.length-2 : 0);
	    	    		var change =  {object:object,type:"splice",index:start,removed:removed,addedCount:addedCount};
	    	    		target.splice.apply(target,arguments);
	    	    		if(acceptlist.indexOf("splice")>=0) {
	    	    			proxy.__observer__.changeset.push(change);
	    	    		}
	    	    	}
	    		}
	    		if(property==="push") {
	    			 return function(item) {
	    		    	return this.splice(this.length,0,item);
	    		    }
	    		}
	    		if(property==="pop") {
	    			 return function() {
	    		    	return this.splice(this.length-1,1);
	    		    }
	    		}
	    		if(property==="unshift") {
	    			 return function(item) {
    		    		return this.splice(0,0,item);
    		    	}
	    		}
	    		if(property==="shift") {
	    			return function() {
	    	    		return this.splice(0,1);
	    	    	}
	    		}
	    		return target[property];
	    	}});
	    	var proxy = Object.observe(arrayproxy,function(changeset) {
	    		var changes = changeset.filter(function(change) { return change.name!=="length" && change.name!=="add" && (!acceptlist || acceptlist.indexOf(change.type)>=0); });
	    		if(changes.length>0) {
	    			callback(changes);
	    		}
	    	},acceptlist,pausable,pause);
	    	return proxy;
	    };
	    Array.unobserve = function(object,callback) {
		  return object.unobserve(callback);
	    }
	}
	Object.deepObserve = function(object,callback,parts) {
		parts = (parts ? parts : []);
		var keys = Object.keys(object);
		keys.forEach(function(key) {
			if(object[key] instanceof Object) {
				var newparts = parts.slice(0);
				newparts.push(key);
				object[key] = Object.deepObserve(object[key],callback,newparts);
			}
		});
		var observed = Object.observe(object,function(changeset) {
			var changes = [];
			function recurse(name,rootObject,oldObject,newObject,path) {
				if(newObject instanceof Object) {
					var newkeys = Object.keys(newObject);
					newkeys.forEach(function(key) {
						if(!oldObject || (oldObject[key]!==newObject[key])) {
							var oldvalue = (oldObject && oldObject[key]!==undefined ? oldObject[key] : undefined);
							var change = (oldvalue===undefined ? "add" : "update");
							var keypath = path + "." + key;
							changes.push({name:name,object:rootObject,type:change,oldValue:oldvalue,newValue:newObject[key],keypath:keypath});
							recurse(name,rootObject,oldvalue,newObject[key],keypath);
						}
					});
				} else if(oldObject instanceof Object) {
					var oldkeys = Object.keys(oldObject);
					oldkeys.forEach(function(key) {
						var change = (newObject===null ? "update" : "delete");
						var keypath = path + "." + key;
						changes.push({name:name,object:rootObject,type:change,oldValue:oldObject[key],newValue:newObject,keypath:keypath});
						recurse(name,rootObject,oldObject[key],undefined,keypath);
					});
				}
			}
			changeset.forEach(function(change) {
				var keypath = (parts.length>0 ? parts.join(".") + "." : "") + change.name;
				changes.push({name:change.name,object:change.object,type:change.type,oldValue:change.oldValue,newValue:change.object[change.name],keypath:keypath});
				recurse(change.name,change.object,change.oldValue,change.object[change.name],keypath);
			});
			callback(changes);
		});
		return observed;
	};
})();<|endoftext|>