<commit_before>'use strict';
/* jshint camelcase: false */

/**
 * A remote client that sends request to a pooled-pg server.
 * (C) 2015 Alex Fernández.
 */

// requires
require('prototypes');
var server = require('./server.js');
var net = require('net');
var Log = require('log');
var testing = require('testing');
var genericPool = require('generic-pool');

// globals
var log = new Log('info');
var clients = {};

exports.remoteConnect = function(address, callback)
{
	var client = getClient(address);
	callback(null, client, client.done);
};

function getClient(address)
{
	if (!clients[address])
	{
		clients[address] = new exports.RemoteClient(address);
	}
	return clients[address];
}

exports.end = function()
{
	clients.forEach(function(client)
	{
		client.end();
	});
};

exports.RemoteClient = function(address)
{
	// self-reference
	var self = this;

	// attributes
	var pool = createPool(address);

	self.query = function(query, params, callback)
	{
		log.debug('query: %s', query);
		if (typeof params == 'function')
		{
			callback = params;
			params = null;
		}
		if (address == 'test')
		{
			return callback(null, {
				rowCount: 1,
				rows: [{"current_user":"test"}],
			});
		}
		pool.acquire(function(error, socket)
		{
			if (error)
			{
				return callback('Could not connect to  ' + address + ': ' + error);
			}
			var message = {
				query: query,
				params: params,
				address: getLocalAddress(),
			};
			socket.write(JSON.stringify(message), function(error)
			{
				if (error)
				{
					return callback('Could not connect: ' + error);
				}
				socket.on('data', function(data)
				{
					pool.release(socket);
					return callback(null, JSON.parse(data));
				});
				socket.on('error', function(error)
				{
					return callback('Could not receive data: ' + error);
				});
			});
		});
	};

	function getLocalAddress()
	{
		var withoutProtocol = address.substringFrom(':').substringUpTo('@');
		var database = address.substringFrom('@').substringFrom('/');
		return 'postgresql:' + withoutProtocol + '@localhost:5432/' + database;
	}

	self.done = function()
	{
	};

	self.end = function()
	{
	};
};

function createPool(address)
{
	var fullHost = address.substringFrom('@').substringUpTo('/');
	log.debug('Creating client to %s', fullHost);
	var options = {
		host: fullHost.substringUpTo(':'),
		port: fullHost.substringFrom(':'),
	};
	var pool = genericPool.Pool({
		name: 'remote',
		create: function(callback)
		{
			var socket = net.connect(options, function(error)
			{
				if (error)
				{
					return callback(error);
				}
				socket.setNoDelay();
				socket.on('error', function(error)
				{
					log.error('Error in remote, removing from pool: %s', error);
					pool.destroy(socket);
				});
				return callback(null, socket);
			});
		},
		destroy: function(client)
		{
			log.debug('Destroying client to %s', address);
			client.end();
		},
		max: 10,
		idleTimeoutMillis: 1000,
	});
	return pool;
}

function testRemoteClient(callback)
{
	var port = 5444;
	var address = 'pooled://test:test@localhost: ' + port +  '/test';
	var options = {
		port: port,
		test: true,
	};
	server.start(options, function(error, testServer)
	{
		var client = new exports.RemoteClient(address);
		client.query('select current_user', function(error, result)
		{
			testing.check(error, 'Could not run query to %s', address, callback);
			testing.assert(result, 'No result', callback);
			testing.assert(result.rowCount, 'No rows', callback);
			testing.assert(result.rows[0], 'No first row', callback);
			var user = result.rows[0].current_user;
			testing.assertEquals(user, 'test', 'Invalid user', callback);
			client.end();
			testServer.close(function(error)
			{
				testing.check(error, 'Could not close server', callback);
				testing.success(callback);
			});
		});
	});
}

/**
 * Run package tests.
 */
exports.test = function(callback)
{
	var tests = [
		testRemoteClient,
	];
	testing.run(tests, callback);
};

// run tests if invoked directly
if (__filename == process.argv[1])
{
	log = new Log('debug');
	exports.test(testing.show);
}

<commit_msg>Do not crash on invalid JSON.<commit_after>'use strict';
/* jshint camelcase: false */

/**
 * A remote client that sends request to a pooled-pg server.
 * (C) 2015 Alex Fernández.
 */

// requires
require('prototypes');
var server = require('./server.js');
var net = require('net');
var Log = require('log');
var testing = require('testing');
var genericPool = require('generic-pool');

// globals
var log = new Log('info');
var clients = {};

exports.remoteConnect = function(address, callback)
{
	var client = getClient(address);
	callback(null, client, client.done);
};

function getClient(address)
{
	if (!clients[address])
	{
		clients[address] = new exports.RemoteClient(address);
	}
	return clients[address];
}

exports.end = function()
{
	clients.forEach(function(client)
	{
		client.end();
	});
};

exports.RemoteClient = function(address)
{
	// self-reference
	var self = this;

	// attributes
	var pool = createPool(address);

	self.query = function(query, params, callback)
	{
		log.debug('query: %s', query);
		if (typeof params == 'function')
		{
			callback = params;
			params = null;
		}
		if (address == 'test')
		{
			return callback(null, {
				rowCount: 1,
				rows: [{"current_user":"test"}],
			});
		}
		pool.acquire(function(error, socket)
		{
			if (error)
			{
				return callback('Could not connect to  ' + address + ': ' + error);
			}
			var message = {
				query: query,
				params: params,
				address: getLocalAddress(),
			};
			socket.write(JSON.stringify(message), function(error)
			{
				if (error)
				{
					return callback('Could not connect: ' + error);
				}
				socket.on('data', function(data)
				{
					pool.release(socket);
					try
					{
						return callback(null, JSON.parse(data));
					}
					catch(exception)
					{
						return callback('Could not parse response: ' + exception);
					}
				});
				socket.on('error', function(error)
				{
					return callback('Could not receive data: ' + error);
				});
			});
		});
	};

	function getLocalAddress()
	{
		var withoutProtocol = address.substringFrom(':').substringUpTo('@');
		var database = address.substringFrom('@').substringFrom('/');
		return 'postgresql:' + withoutProtocol + '@localhost:5432/' + database;
	}

	self.done = function()
	{
	};

	self.end = function()
	{
	};
};

function createPool(address)
{
	var fullHost = address.substringFrom('@').substringUpTo('/');
	log.debug('Creating client to %s', fullHost);
	var options = {
		host: fullHost.substringUpTo(':'),
		port: fullHost.substringFrom(':'),
	};
	var pool = genericPool.Pool({
		name: 'remote',
		create: function(callback)
		{
			var socket = net.connect(options, function(error)
			{
				if (error)
				{
					return callback(error);
				}
				socket.setNoDelay();
				socket.on('error', function(error)
				{
					log.error('Error in remote, removing from pool: %s', error);
					pool.destroy(socket);
				});
				return callback(null, socket);
			});
		},
		destroy: function(client)
		{
			log.debug('Destroying client to %s', address);
			client.end();
		},
		max: 10,
		idleTimeoutMillis: 1000,
	});
	return pool;
}

function testRemoteClient(callback)
{
	var port = 5444;
	var address = 'pooled://test:test@localhost: ' + port +  '/test';
	var options = {
		port: port,
		test: true,
	};
	server.start(options, function(error, testServer)
	{
		var client = new exports.RemoteClient(address);
		client.query('select current_user', function(error, result)
		{
			testing.check(error, 'Could not run query to %s', address, callback);
			testing.assert(result, 'No result', callback);
			testing.assert(result.rowCount, 'No rows', callback);
			testing.assert(result.rows[0], 'No first row', callback);
			var user = result.rows[0].current_user;
			testing.assertEquals(user, 'test', 'Invalid user', callback);
			client.end();
			testServer.close(function(error)
			{
				testing.check(error, 'Could not close server', callback);
				testing.success(callback);
			});
		});
	});
}

/**
 * Run package tests.
 */
exports.test = function(callback)
{
	var tests = [
		testRemoteClient,
	];
	testing.run(tests, callback);
};

// run tests if invoked directly
if (__filename == process.argv[1])
{
	log = new Log('debug');
	exports.test(testing.show);
}

<|endoftext|>


<commit_before>var Remote = require('ripple-lib').Remote;

/* Loading ripple-lib in a webpage */
// var Remote = ripple.Remote;

var remote = new Remote({
  // see the API Reference for available options
  trusted:        false,
  local_signing:  true,
  local_fee:      true,
  fee_cushion:     1.5,
  servers: [
    {
        host:    's1.ripple.com'
      , port:    443
      , secure:  true
    }
  ]
});

module.exports = remote;
<commit_msg>[FEATURE ] Use s-west.ripple.com in ripple-lib remote.<commit_after>var Remote = require('ripple-lib').Remote;

/* Loading ripple-lib in a webpage */
// var Remote = ripple.Remote;

var remote = new Remote({
  // see the API Reference for available options
  trusted:        false,
  local_signing:  true,
  local_fee:      true,
  fee_cushion:     1.5,
  servers: [
    {
        host:    's-west.ripple.com'
      , port:    443
      , secure:  true
    }
  ]
});

module.exports = remote;
<|endoftext|>


<commit_before>'use strict'

/**
 * Module dependencies
 */
const home = require('user-home')
require('shelljs/global')

module.exports = function (version) {
  try {
    const dir = `${home}/.nwjs/${version}`
    rm('-r', dir)
  } catch (e) {
    console.log(e.stack)
  }
}
<commit_msg>update config after remove nwjs<commit_after>'use strict'

/**
 * Module dependencies
 */
const home = require('user-home')
const config = require('./config')
require('shelljs/global')

module.exports = function (version) {
  try {
    config.set('current', null)
    const dir = `${home}/.nwjs/${version}`
    rm('-r', dir)
  } catch (e) {
    console.log(e.stack)
  }
}
<|endoftext|>


<commit_before>'use strict';

var argv = require('minimist')(process.argv.slice(2));
var chalk = require('chalk');

/**
 * Create an instance of `Renderer`. This is only necessary
 * if need to create your own instance.
 *
 * ```js
 * var renderer = new snapdragon.Renderer();
 * ```
 *
 * @param {Object} `ast` Pass the ast from the `Parse` method
 * @api public
 */

function Renderer(ast, opts) {
  this.options = opts || {};
  this.ast = ast || {};
  this.stash = ast.stash;
  this.length = ast.nodes.length;
  this.errorsList = [];
  this.parsingErrors = this.ast.errorsList;
  this.renderers = opts.renderers || {};
}

/**
 * Set an error message with the current line number and column.
 *
 * ```js
 * this.error('Error parsing string.');
 * ```
 *
 * @param {String} `msg` Message to use in the Error.
 * @api public
 */

Renderer.prototype.error = function(msg) {
  var message = ''
    + ':' + this.column
    + ': ' + msg;

  var err = new Error(message);
  console.log(chalk.yellow(err));

  err.reason = msg;
  if (this.options.silent) {
    this.errorsList.push(err);
  } else {
    throw err;
  }
};

/**
 * Register a renderer for a corresponding parser `type`.
 *
 * ```js
 * var ast = snapdragon.parse(str)
 *   .use(function() {
 *     // `type` is the name of the renderer to use
 *     return pos({ type: 'dot' });
 *   })
 *
 * var res = snapdragon.render(ast, options)
 *   .set('dot', function (node) {
 *     return this.emit(node.val);
 *   })
 * ```
 *
 * @param  {String} `name` Name of the renderer to register
 * @param  {Function} `fn` Function to register
 * @return {Object} `this` to enable chaining.
 * @api public
 */

Renderer.prototype.set = function(name, fn) {
  if (typeof name !== 'string') {
    throw new Error('Renderer#set expects `name` to be a string, but got: ' + name);
  }
  if (typeof fn !== 'function') {
    throw new Error('Renderer#set expects `fn` to be a function, but got: ' + fn);
  }
  this.renderers[name] = fn;
  return this;
};

/**
 * Emit `str`
 */

Renderer.prototype.emit = function(str) {
  return str;
};

/**
 * Visit `node`.
 */

Renderer.prototype.visit = function(node) {
  var fn = this.renderers[node.type];
  if (argv.verbose || argv.v) {
    console.log(chalk.yellow(node.type));
    console.log(node);
  }
  if (typeof fn !== 'function') {
    this.error('visit expects "' + node.type + ' | ' +  node.val + '" to be a function.');
  }
  return fn.call(this, node);
};

/**
 * Map `visit` over array of `nodes`, optionally using
 * a `delim`
 */

Renderer.prototype.mapVisit = function(nodes, delim) {
  delim = delim || '';
  var buf = '', len = nodes.length;
  for (var i = 0; i < len; i++) {
    buf += this.visit(nodes[i]);
    if (delim && i < len - 1) buf += this.emit(delim);
  }
  return buf;
};

/**
 * Render.
 */

Renderer.prototype.render = function() {
  var res = this.mapVisit(this.ast.nodes);
  var head = this.stash.head;
  var len = head.length;
  var h = '';
  while (len--) h += head[len];
  return h + res;
};

/**
 * Expose `Renderer`.
 */

module.exports = Renderer;
<commit_msg>only color the error message<commit_after>'use strict';

var argv = require('minimist')(process.argv.slice(2));
var chalk = require('chalk');

/**
 * Create an instance of `Renderer`. This is only necessary
 * if need to create your own instance.
 *
 * ```js
 * var renderer = new snapdragon.Renderer();
 * ```
 *
 * @param {Object} `ast` Pass the ast from the `Parse` method
 * @api public
 */

function Renderer(ast, opts) {
  this.options = opts || {};
  this.ast = ast || {};
  this.stash = ast.stash;
  this.length = ast.nodes.length;
  this.errorsList = [];
  this.parsingErrors = this.ast.errorsList;
  this.renderers = opts.renderers || {};
}

/**
 * Set an error message with the current line number and column.
 *
 * ```js
 * this.error('Error parsing string.');
 * ```
 *
 * @param {String} `msg` Message to use in the Error.
 * @api public
 */

Renderer.prototype.error = function(msg) {
  var message = ''
    + ':' + this.column
    + ': ' + msg;

  var err = new Error(message);

  err.reason = msg;
  console.log(chalk.yellow(err.reason));

  if (this.options.silent) {
    this.errorsList.push(err);
  } else {
    throw err;
  }
};

/**
 * Register a renderer for a corresponding parser `type`.
 *
 * ```js
 * var ast = snapdragon.parse(str)
 *   .use(function() {
 *     // `type` is the name of the renderer to use
 *     return pos({ type: 'dot' });
 *   })
 *
 * var res = snapdragon.render(ast, options)
 *   .set('dot', function (node) {
 *     return this.emit(node.val);
 *   })
 * ```
 *
 * @param  {String} `name` Name of the renderer to register
 * @param  {Function} `fn` Function to register
 * @return {Object} `this` to enable chaining.
 * @api public
 */

Renderer.prototype.set = function(name, fn) {
  if (typeof name !== 'string') {
    throw new Error('Renderer#set expects `name` to be a string, but got: ' + name);
  }
  if (typeof fn !== 'function') {
    throw new Error('Renderer#set expects `fn` to be a function, but got: ' + fn);
  }
  this.renderers[name] = fn;
  return this;
};

/**
 * Emit `str`
 */

Renderer.prototype.emit = function(str) {
  return str;
};

/**
 * Visit `node`.
 */

Renderer.prototype.visit = function(node) {
  var fn = this.renderers[node.type];
  if (argv.verbose || argv.v) {
    console.log(chalk.yellow(node.type));
    console.log(node);
  }
  if (typeof fn !== 'function') {
    this.error('visit expects "' + node.type + ' | ' +  node.val + '" to be a function.');
  }
  return fn.call(this, node);
};

/**
 * Map `visit` over array of `nodes`, optionally using
 * a `delim`
 */

Renderer.prototype.mapVisit = function(nodes, delim) {
  delim = delim || '';
  var buf = '', len = nodes.length;
  for (var i = 0; i < len; i++) {
    buf += this.visit(nodes[i]);
    if (delim && i < len - 1) buf += this.emit(delim);
  }
  return buf;
};

/**
 * Render.
 */

Renderer.prototype.render = function() {
  var res = this.mapVisit(this.ast.nodes);
  var head = this.stash.head;
  var len = head.length;
  var h = '';
  while (len--) h += head[len];
  return h + res;
};

/**
 * Expose `Renderer`.
 */

module.exports = Renderer;
<|endoftext|>


<commit_before>var mapnik = require('mapnik');
var _ = require('underscore');
var Step = require('step');

var MapnikSource = require('./mapnik_backend');
var solidCache = {};

var EARTH_RADIUS = 6378137;
var EARTH_DIAMETER = EARTH_RADIUS * Math.PI;
var EARTH_CIRCUMFERENCE = EARTH_DIAMETER * 2;
var MAX_RES = EARTH_CIRCUMFERENCE / 256;

exports['calculateMetatile'] = calculateMetatile;
function calculateMetatile(options) {
    var z = +options.z, x = +options.x, y = +options.y;
    var total = 1 << z;
    var resolution = MAX_RES / total;

    // Make sure we start at a metatile boundary.
    x -= x % options.metatile;
    y -= y % options.metatile;

    // Make sure we don't calculcate a metatile that is larger than the bounds.
    var metaWidth  = Math.min(options.metatile, total, total - x);
    var metaHeight = Math.min(options.metatile, total, total - y);

    // Generate all tile coordinates that are within the metatile.
    var tiles = [];
    for (var dx = 0; dx < metaWidth; dx++) {
        for (var dy = 0; dy < metaHeight; dy++) {
            tiles.push([ z, x + dx, y + dy ]);
        }
    }

    var minx = (x * 256) * resolution - EARTH_DIAMETER;
    var miny = -((y + metaHeight) * 256) * resolution + EARTH_DIAMETER;
    var maxx = ((x + metaWidth) * 256) * resolution - EARTH_DIAMETER;
    var maxy = -((y * 256) * resolution - EARTH_DIAMETER);
    return {
        width: metaWidth * 256,
        height: metaHeight * 256,
        x: x, y: y,
        tiles: tiles,
        bbox: [ minx, miny, maxx, maxy ]
    };
}

exports['sliceMetatile'] = sliceMetatile;
function sliceMetatile(image, options, meta, callback) {
    var tiles = {};

    Step(function() {
        var group = this.group();
        meta.tiles.forEach(function(c) {
            var next = group();
            var key = [options.format, c[0], c[1], c[2]].join(',');
            getImage(image, options, (c[1] - meta.x) * 256, (c[2] - meta.y) * 256, function(err, image) {
                tiles[key] = {
                    image: image,
                    headers: options.headers
                };
                next();
            });
        });
    }, function(err) {
        if (err) return callback(err);
        callback(null, tiles);
    });
}

exports['encodeSingleTile'] = encodeSingleTile;
function encodeSingleTile(image, options, meta, callback) {
    var tiles = {};
    var key = [options.format, options.z, options.x, options.y].join(',');
    getImage(image, options, 0, 0, function(err, image) {
        if (err) return callback(err);
        tiles[key] = { image: image, headers: options.headers };
        callback(null, tiles);
    });
}

function getImage(image, options, x, y, callback) {
    var view = image.view(x, y, 256, 256);
    var solid = view.isSolid() &&
        (function(p) {
            if (options.format === 'utf') return p.toString();
            else return p.r +','+ p.g + ',' + p.b + ',' + p.a;
        })(view.getPixel(0,0));

    // Add stats.
    options.source._stats.total++;
    if (solid !== false) options.source._stats.solid++;
    if (solid !== false && image.painted()) options.source._stats.solidPainted++;

    // If solid and image buffer is cached skip image encoding.
    if (solid && solidCache[solid]) return callback(null, solidCache[solid]);

    // Note: the second parameter is needed for grid encoding.
    options.source._stats.encoded++;
    view.encode(options.format, options, function(err, buffer) {
        if (err) return callback(err);
        if (solid !== false) {
            // @TODO for 'utf' this attaches an extra, bogus 'solid' key to
            // to the grid as it is not a buffer but an actual JS object.
            // Fix is to propagate a third parameter through callbacks all
            // the way back to tilelive source #getGrid.
            buffer.solid = solid;
            solidCache[solid] = buffer;
        }
        return callback(null, buffer);
    });
}

// Render png/jpg image or a utf grid and return an encoded buffer
MapnikSource.prototype._renderMetatile = function(options, callback) {
    var source = this;

    // Calculate bbox from xyz, respecting metatile settings.
    var meta = calculateMetatile(options);

    // Set default options.
    if (options.format === 'utf') {
        var interactivity = source._mml.interactivity;
        options.layer = interactivity.layer;
        options.fields = interactivity.fields;
        options.resolution = source._uri.query.resolution;
        options.headers = { 'Content-Type': 'text/javascript; charset=utf-8' };
        var image = new mapnik.Grid(meta.width, meta.height);
    } else {
        options.headers = { 'Content-Type': 'image/png' };
        var image = new mapnik.Image(meta.width, meta.height);
    }

    // Add reference to the source allowing debug/stat reporting to be compiled.
    options.source = source;

    process.nextTick(function() {
        source._pool.acquire(function(err, map) {
            if (err) return callback(err);

            // Begin at metatile boundary.
            options.x = meta.x;
            options.y = meta.y;

            map.resize(meta.width, meta.height);
            map.extent = meta.bbox;

            try {
                source._stats.render++;
                map.render(image, options, function(err, image) {
                    process.nextTick(function() {
                        // Release after the .render() callback returned
                        // to avoid mapnik errors.
                        source._pool.release(map);
                    });

                    if (err) return callback(err);

                    if (meta.tiles.length > 1) {
                        sliceMetatile(image, options, meta, callback);
                    } else {
                        encodeSingleTile(image, options, meta, callback);
                    }
                });
            } catch(err) {
                source._pool.release(map);
                callback(err);
            }
        });
    });

    // Return a list of all the tile coordinates that are being rendered
    // as part of this metatile.
    return meta.tiles.map(function(tile) {
        return options.format + ',' + tile.join(',');
    });
};
<commit_msg>fix the metatile constants - no functional change in code but clarifies terms - closes #30<commit_after>var mapnik = require('mapnik');
var _ = require('underscore');
var Step = require('step');

var MapnikSource = require('./mapnik_backend');
var solidCache = {};

var EARTH_RADIUS = 6378137;
var EARTH_DIAMETER = EARTH_RADIUS * 2;
var EARTH_CIRCUMFERENCE = EARTH_DIAMETER * Math.PI;
var MAX_RES = EARTH_CIRCUMFERENCE / 256;
var ORIGIN_SHIFT = EARTH_CIRCUMFERENCE/2;

exports['calculateMetatile'] = calculateMetatile;
function calculateMetatile(options) {
    var z = +options.z, x = +options.x, y = +options.y;
    var total = 1 << z;
    var resolution = MAX_RES / total;

    // Make sure we start at a metatile boundary.
    x -= x % options.metatile;
    y -= y % options.metatile;

    // Make sure we don't calculcate a metatile that is larger than the bounds.
    var metaWidth  = Math.min(options.metatile, total, total - x);
    var metaHeight = Math.min(options.metatile, total, total - y);

    // Generate all tile coordinates that are within the metatile.
    var tiles = [];
    for (var dx = 0; dx < metaWidth; dx++) {
        for (var dy = 0; dy < metaHeight; dy++) {
            tiles.push([ z, x + dx, y + dy ]);
        }
    }

    var minx = (x * 256) * resolution - ORIGIN_SHIFT;
    var miny = -((y + metaHeight) * 256) * resolution + ORIGIN_SHIFT;
    var maxx = ((x + metaWidth) * 256) * resolution - ORIGIN_SHIFT;
    var maxy = -((y * 256) * resolution - ORIGIN_SHIFT);
    return {
        width: metaWidth * 256,
        height: metaHeight * 256,
        x: x, y: y,
        tiles: tiles,
        bbox: [ minx, miny, maxx, maxy ]
    };
}

exports['sliceMetatile'] = sliceMetatile;
function sliceMetatile(image, options, meta, callback) {
    var tiles = {};

    Step(function() {
        var group = this.group();
        meta.tiles.forEach(function(c) {
            var next = group();
            var key = [options.format, c[0], c[1], c[2]].join(',');
            getImage(image, options, (c[1] - meta.x) * 256, (c[2] - meta.y) * 256, function(err, image) {
                tiles[key] = {
                    image: image,
                    headers: options.headers
                };
                next();
            });
        });
    }, function(err) {
        if (err) return callback(err);
        callback(null, tiles);
    });
}

exports['encodeSingleTile'] = encodeSingleTile;
function encodeSingleTile(image, options, meta, callback) {
    var tiles = {};
    var key = [options.format, options.z, options.x, options.y].join(',');
    getImage(image, options, 0, 0, function(err, image) {
        if (err) return callback(err);
        tiles[key] = { image: image, headers: options.headers };
        callback(null, tiles);
    });
}

function getImage(image, options, x, y, callback) {
    var view = image.view(x, y, 256, 256);
    var solid = view.isSolid() &&
        (function(p) {
            if (options.format === 'utf') return p.toString();
            else return p.r +','+ p.g + ',' + p.b + ',' + p.a;
        })(view.getPixel(0,0));

    // Add stats.
    options.source._stats.total++;
    if (solid !== false) options.source._stats.solid++;
    if (solid !== false && image.painted()) options.source._stats.solidPainted++;

    // If solid and image buffer is cached skip image encoding.
    if (solid && solidCache[solid]) return callback(null, solidCache[solid]);

    // Note: the second parameter is needed for grid encoding.
    options.source._stats.encoded++;
    view.encode(options.format, options, function(err, buffer) {
        if (err) return callback(err);
        if (solid !== false) {
            // @TODO for 'utf' this attaches an extra, bogus 'solid' key to
            // to the grid as it is not a buffer but an actual JS object.
            // Fix is to propagate a third parameter through callbacks all
            // the way back to tilelive source #getGrid.
            buffer.solid = solid;
            solidCache[solid] = buffer;
        }
        return callback(null, buffer);
    });
}

// Render png/jpg image or a utf grid and return an encoded buffer
MapnikSource.prototype._renderMetatile = function(options, callback) {
    var source = this;

    // Calculate bbox from xyz, respecting metatile settings.
    var meta = calculateMetatile(options);

    // Set default options.
    if (options.format === 'utf') {
        var interactivity = source._mml.interactivity;
        options.layer = interactivity.layer;
        options.fields = interactivity.fields;
        options.resolution = source._uri.query.resolution;
        options.headers = { 'Content-Type': 'text/javascript; charset=utf-8' };
        var image = new mapnik.Grid(meta.width, meta.height);
    } else {
        options.headers = { 'Content-Type': 'image/png' };
        var image = new mapnik.Image(meta.width, meta.height);
    }

    // Add reference to the source allowing debug/stat reporting to be compiled.
    options.source = source;

    process.nextTick(function() {
        source._pool.acquire(function(err, map) {
            if (err) return callback(err);

            // Begin at metatile boundary.
            options.x = meta.x;
            options.y = meta.y;

            map.resize(meta.width, meta.height);
            map.extent = meta.bbox;

            try {
                source._stats.render++;
                map.render(image, options, function(err, image) {
                    process.nextTick(function() {
                        // Release after the .render() callback returned
                        // to avoid mapnik errors.
                        source._pool.release(map);
                    });

                    if (err) return callback(err);

                    if (meta.tiles.length > 1) {
                        sliceMetatile(image, options, meta, callback);
                    } else {
                        encodeSingleTile(image, options, meta, callback);
                    }
                });
            } catch(err) {
                source._pool.release(map);
                callback(err);
            }
        });
    });

    // Return a list of all the tile coordinates that are being rendered
    // as part of this metatile.
    return meta.tiles.map(function(tile) {
        return options.format + ',' + tile.join(',');
    });
};
<|endoftext|>


<commit_before>/*globals document, window*/
(function () {'use strict';

function JawBar(sel, options) {
    var that = this;
    this.html = {};
    this.parent = document.querySelector(sel);
    this.parent.addEventListener('keyup', function(e){
        that.findMatch(e);
    });
    this.init();
    this.hide();
    if (options) {
        this.add(options);
    }
    document.body.appendChild(this.html.holder);
}

JawBar.prototype.init = function() {
    var that = this;

    // Combo Div.  Container for the options
    var div = this.html.div = document.createElement('div');
    div.className = 'jawbar-optionContainer';

    // Set our styles, positioning, etc.
    // The text box we are converting
    this.parent.style.position = 'relative';
    this.parent.setAttribute('autocomplete', 'off');

    // Create a button for dropdown
    var button = this.html.button = document.createElement('input');
    button.type = 'button';
    button.className = 'jawbar-dropdownButton';

    // Holding container for the button and option container
    var holder = this.html.holder = document.createElement('div');
    holder.appendChild(this.html.button);
    holder.appendChild(this.html.div);

    holder.addEventListener('click', function() {
        if (that.visible) {
            that.hide();
        }
        else {
            that.show();
        }
    });

    this.position();
};

JawBar.prototype.position = function() {
    // Todo: use CSSOM to determine base style
    var divStyle = this.html.div.style;
    divStyle.height = 200 + 'px';
    divStyle.width = this.parent.offsetWidth + 'px';
    divStyle.top = this.parent.offsetTop + this.parent.offsetHeight + 'px';
    divStyle.left = this.parent.offsetLeft + 'px';
    var buttonStyle = this.html.button.style;
    buttonStyle.height = this.parent.offsetHeight + 'px';
    buttonStyle.top = this.parent.offsetTop + 'px';
    buttonStyle.left = this.parent.offsetLeft + this.parent.offsetWidth - 15 + 'px';
};

JawBar.prototype.show = function() {
    this.html.div.classList.toggle('jawbar-hidden', false);
    this.visible = true;
};

JawBar.prototype.add = function(options) {
    if (typeof options.length === 'number') {
        options.forEach(function (option) {
            this.add(option);
        }, this);
        return;
    }
    var that = this;
    var item = document.createElement('div');
    item.className = 'jawbar-menuitem';
    var imageDiv = document.createElement('div');
    imageDiv.className = 'jawbar-imageContainer';
    var image = document.createElement('img');
    image.className = 'jawbar-menuitem-icon';
    var text = document.createElement('div');
    text.className = 'jawbar-menuitem-text';
    var subText = document.createElement('div');
    subText.className = 'jawbar-menuitem-subText';
    // Todo: change to properly-namespaced dataset properties
    item.dataset.jawbarDisplayValue = options.displayValue;
    item.dataset.jawbarSearchValue = options.searchValue;

    image.src = options.icon;
    text.appendChild(document.createTextNode(options.text));
    subText.appendChild(document.createTextNode(options.subtext));
    imageDiv.appendChild(image);
    item.appendChild(imageDiv);
    item.appendChild(text);
    item.appendChild(subText);
    item.addEventListener('click', function () {
        that.parent.value = item.dataset.jawbarDisplayValue;
    });
    this.html.div.appendChild(item);
    imageDiv.style.height = item.offsetHeight - 10 + 'px';
};

JawBar.prototype.hide = function () {
    this.visible = false;
    this.html.div.classList.toggle('jawbar-hidden', true);
};

JawBar.prototype.findMatch = function (e) {
    if (!this.visible) {
        this.show();
    }
    var items = this.html.div.children;
    for (var i = 0, l = items.length; i < l; i++) {
        if (items[i].dataset.jawbarSearchValue.indexOf(this.parent.value) > -1) {
            items[i].classList.toggle('jawbar-menuitem-removed', false);
        }
        else {
            items[i].classList.toggle('jawbar-menuitem-removed', true);
        }
    }
};

JawBar.prototype.remove = function(index) {
    var div = this.html.div;
    if (typeof index === 'number') {
        div.removeChild(div.childNodes[index]);
        return;
    }
    while(this.html.div.firstChild) {
        div.removeChild(div.firstChild);
    }
};

window.JawBar = JawBar;

}());
<commit_msg>rmv completed todo<commit_after>/*globals document, window*/
(function () {'use strict';

function JawBar(sel, options) {
    var that = this;
    this.html = {};
    this.parent = document.querySelector(sel);
    this.parent.addEventListener('keyup', function(e){
        that.findMatch(e);
    });
    this.init();
    this.hide();
    if (options) {
        this.add(options);
    }
    document.body.appendChild(this.html.holder);
}

JawBar.prototype.init = function() {
    var that = this;

    // Combo Div.  Container for the options
    var div = this.html.div = document.createElement('div');
    div.className = 'jawbar-optionContainer';

    // Set our styles, positioning, etc.
    // The text box we are converting
    this.parent.style.position = 'relative';
    this.parent.setAttribute('autocomplete', 'off');

    // Create a button for dropdown
    var button = this.html.button = document.createElement('input');
    button.type = 'button';
    button.className = 'jawbar-dropdownButton';

    // Holding container for the button and option container
    var holder = this.html.holder = document.createElement('div');
    holder.appendChild(this.html.button);
    holder.appendChild(this.html.div);

    holder.addEventListener('click', function() {
        if (that.visible) {
            that.hide();
        }
        else {
            that.show();
        }
    });

    this.position();
};

JawBar.prototype.position = function() {
    // Todo: use CSSOM to determine base style
    var divStyle = this.html.div.style;
    divStyle.height = 200 + 'px';
    divStyle.width = this.parent.offsetWidth + 'px';
    divStyle.top = this.parent.offsetTop + this.parent.offsetHeight + 'px';
    divStyle.left = this.parent.offsetLeft + 'px';
    var buttonStyle = this.html.button.style;
    buttonStyle.height = this.parent.offsetHeight + 'px';
    buttonStyle.top = this.parent.offsetTop + 'px';
    buttonStyle.left = this.parent.offsetLeft + this.parent.offsetWidth - 15 + 'px';
};

JawBar.prototype.show = function() {
    this.html.div.classList.toggle('jawbar-hidden', false);
    this.visible = true;
};

JawBar.prototype.add = function(options) {
    if (typeof options.length === 'number') {
        options.forEach(function (option) {
            this.add(option);
        }, this);
        return;
    }
    var that = this;
    var item = document.createElement('div');
    item.className = 'jawbar-menuitem';
    var imageDiv = document.createElement('div');
    imageDiv.className = 'jawbar-imageContainer';
    var image = document.createElement('img');
    image.className = 'jawbar-menuitem-icon';
    var text = document.createElement('div');
    text.className = 'jawbar-menuitem-text';
    var subText = document.createElement('div');
    subText.className = 'jawbar-menuitem-subText';

    item.dataset.jawbarDisplayValue = options.displayValue;
    item.dataset.jawbarSearchValue = options.searchValue;

    image.src = options.icon;
    text.appendChild(document.createTextNode(options.text));
    subText.appendChild(document.createTextNode(options.subtext));
    imageDiv.appendChild(image);
    item.appendChild(imageDiv);
    item.appendChild(text);
    item.appendChild(subText);
    item.addEventListener('click', function () {
        that.parent.value = item.dataset.jawbarDisplayValue;
    });
    this.html.div.appendChild(item);
    imageDiv.style.height = item.offsetHeight - 10 + 'px';
};

JawBar.prototype.hide = function () {
    this.visible = false;
    this.html.div.classList.toggle('jawbar-hidden', true);
};

JawBar.prototype.findMatch = function (e) {
    if (!this.visible) {
        this.show();
    }
    var items = this.html.div.children;
    for (var i = 0, l = items.length; i < l; i++) {
        if (items[i].dataset.jawbarSearchValue.indexOf(this.parent.value) > -1) {
            items[i].classList.toggle('jawbar-menuitem-removed', false);
        }
        else {
            items[i].classList.toggle('jawbar-menuitem-removed', true);
        }
    }
};

JawBar.prototype.remove = function(index) {
    var div = this.html.div;
    if (typeof index === 'number') {
        div.removeChild(div.childNodes[index]);
        return;
    }
    while(this.html.div.firstChild) {
        div.removeChild(div.firstChild);
    }
};

window.JawBar = JawBar;

}());
<|endoftext|>


<commit_before>validator = require('validator').validators
request = require('request')

module.exports = {
  Gateway: (function(){
    function Client(opts){
      this.clientId = this.validate(opts, 'clientId', 'isAlphanumeric')
      this.clientSecret = this.validate(opts, 'clientSecret', 'isAlphanumeric')
      this.api = opts.api || 'http://localhost:4000'
      this.request = request
    }

    Client.prototype.validate = function(opts, value, predicate) {
      function throwError() {
        throw new Error('params: '+value+' fails '+predicate+' test.')
      }

      validator['isBoolean'] = function(val) {
        return (val == true)   || (val == false) ||
               (val == 'true') || (val == 'false')
      }

      if (!!value) {
        if (predicate == 'present') { return true }
      } else {
        throwError()
      }
      try {
        if (validator[predicate](opts[value])) {
          return value
        } else {
          throwError()
        }
      } catch(e) {
        throwError()
      }
    }

    Client.prototype.createSession = function(opts, fn) {
      opts.name = opts.username
      jar = opts.cookieJar
      request.post({ url: 'http://localhost:4000/api/v1/sessions', form: opts, json:true, jar: jar}, function(e,r,body){
        if (body.success){
          fn(null, body.session)
        } else if (body.error){
          fn(body.error, null)
        } else {
          fn(e,body)
        }
      })
    }

    Client.prototype.createUser = function(opts, fn){
      opts.name = opts.username
      request.post({ url: 'http://localhost:4000/api/v1/gateway/users', form: opts , json:true }, function(e,r,body){
        if (body.success){
          fn(null, body.user)
        } else if (body.error){
          fn(body.error, null)
        } else {
          fn(e,body)
        }
      })
    }

    Client.prototype.getSession = function(opts, fn){
      opts.name = opts.username
      jar = opts.cookieJar
      request.get({ url: 'http://localhost:4000/api/v1/sessions', form: opts, jar: jar, json:true }, function(e,r,body){
        if (body.success){
          fn(null, body.session)
        } else if (body.error){
          fn(body.error, null)
        } else {
          fn(e,body)
        }
      })
    }

    Client.prototype.destroySession = function(fn){
      request.post({ url: 'http://localhost:4000/api/v1/sessions' , json: true }, function(e,r,body){
        if (body.success){
          fn(null, true)
        } else if (body.error){
          fn(body.error, null)
        } else {
          fn(e,body.session)
        }
      })
    }

    Client.prototype.createRippleWithdrawal = function(opts, fn){
      request.post({ url: 'http://localhost:4000/api/v1/ripple_withdrawals', form: opts, json: true}, function(e,r,body){
        if (body.success){
          fn(null, body.rippleWithdrawal)
        } else if (body.error){
          fn(body.error, null)
        } else {
          fn(e,body.rippleWithdrawal)
        }
      })
    }

    Client.prototype.createRippleDeposit = function(opts, fn){
      request.post({ url: 'http://localhost:4000/api/v1/ripple_deposits', form: opts, json: true}, function(e,r,body){
        if (body.success){
          fn(null, body.rippleDeposit)
        } else if (body.error){
          fn(body.error, null)
        } else {
          fn(e,body)
        }
      })
    }

    Client.prototype.createRippleTransaction = function(opts, fn) {
      opts.transaction_state = 'created';
      request.post({ url: 'http://localhost:4000/api/v1/users/'+opts.user_id+'/ripple_transactions', form: opts, json: true}, function(e,r,body){
        if (body.success){
          fn(null, body.rippleDeposit)
        } else if (body.error){
          fn(body.error, null)
        } else {
          fn(e,body)
        }
      })
    }

    Client.prototype.getBalances = function(opts, fn) {
      request.get({ url: 'http://localhost:4000/api/v1/balances', json: true}, function(e,r,body){
        console.log(body)
        console.log(e)
        if (body.success){
          fn(null, body.balances)
        } else if (body.error){
          fn(body.error, null)
        } else {
          fn(e,body)
        }
      })
    }

    return {
      Client: Client
    }
  })()
}
<commit_msg>[FEATURE] Add createExternalTransaction to gateway node.js http client.<commit_after>validator = require('validator').validators
request = require('request')

module.exports = {
  Gateway: (function(){
    function Client(opts){
      this.clientId = this.validate(opts, 'clientId', 'isAlphanumeric')
      this.clientSecret = this.validate(opts, 'clientSecret', 'isAlphanumeric')
      this.api = opts.api || 'http://localhost:4000'
      this.request = request
    }

    Client.prototype.validate = function(opts, value, predicate) {
      function throwError() {
        throw new Error('params: '+value+' fails '+predicate+' test.')
      }

      validator['isBoolean'] = function(val) {
        return (val == true)   || (val == false) ||
               (val == 'true') || (val == 'false')
      }

      if (!!value) {
        if (predicate == 'present') { return true }
      } else {
        throwError()
      }
      try {
        if (validator[predicate](opts[value])) {
          return value
        } else {
          throwError()
        }
      } catch(e) {
        throwError()
      }
    }

    Client.prototype.createSession = function(opts, fn) {
      opts.name = opts.username
      jar = opts.cookieJar
      request.post({ url: 'http://localhost:4000/api/v1/sessions', form: opts, json:true, jar: jar}, function(e,r,body){
        if (body.success){
          fn(null, body.session)
        } else if (body.error){
          fn(body.error, null)
        } else {
          fn(e,body)
        }
      })
    }

    Client.prototype.createUser = function(opts, fn){
      opts.name = opts.username
      request.post({ url: 'http://localhost:4000/api/v1/gateway/users', form: opts , json:true }, function(e,r,body){
        if (body.success){
          fn(null, body.user)
        } else if (body.error){
          fn(body.error, null)
        } else {
          fn(e,body)
        }
      })
    }

    Client.prototype.getSession = function(opts, fn){
      opts.name = opts.username
      jar = opts.cookieJar
      request.get({ url: 'http://localhost:4000/api/v1/sessions', form: opts, jar: jar, json:true }, function(e,r,body){
        if (body.success){
          fn(null, body.session)
        } else if (body.error){
          fn(body.error, null)
        } else {
          fn(e,body)
        }
      })
    }

    Client.prototype.destroySession = function(fn){
      request.post({ url: 'http://localhost:4000/api/v1/sessions' , json: true }, function(e,r,body){
        if (body.success){
          fn(null, true)
        } else if (body.error){
          fn(body.error, null)
        } else {
          fn(e,body.session)
        }
      })
    }

    Client.prototype.createRippleWithdrawal = function(opts, fn){
      request.post({ url: 'http://localhost:4000/api/v1/ripple_withdrawals', form: opts, json: true}, function(e,r,body){
        if (body.success){
          fn(null, body.rippleWithdrawal)
        } else if (body.error){
          fn(body.error, null)
        } else {
          fn(e,body.rippleWithdrawal)
        }
      })
    }

    Client.prototype.createRippleDeposit = function(opts, fn){
      request.post({ url: 'http://localhost:4000/api/v1/ripple_deposits', form: opts, json: true}, function(e,r,body){
        if (body.success){
          fn(null, body.rippleDeposit)
        } else if (body.error){
          fn(body.error, null)
        } else {
          fn(e,body)
        }
      })
    }

    Client.prototype.createRippleTransaction = function(opts, fn) {
      opts.transaction_state = 'created';
      request.post({ url: 'http://localhost:4000/api/v1/users/'+opts.user_id+'/ripple_transactions', form: opts, json: true}, function(e,r,body){
        if (body.success){
          fn(null, body.rippleDeposit)
        } else if (body.error){
          fn(body.error, null)
        } else {
          fn(e,body)
        }
      })
    }

    Client.prototype.createExternalTransaction = function(opts, fn) {
      request.post({ url: 'http://localhost:4000/api/v1/users/'+opts.user_id+'/external_transactions', form: opts, json: true}, function(e,r,body){
        if (body.success){
          fn(null, body.external_transaction)
        } else if (body.error){
          fn(body.error, null)
        } else {
          fn(e,body)
        }
      })
    }

    return {
      Client: Client
    }
  })()
}
<|endoftext|>


<commit_before>(function (root, factory) {
  if(typeof define === 'function' && define.amd) {
    define(['video.js'], function(videojs){
      return (root.WistiaTech = factory(videojs));
    });
  } else if(typeof module === 'object' && module.exports) {
    module.exports = (root.WistiaTech = factory(require('video.js')));
  } else {
    root.WistiaTech = factory(root.videojs);
  }
}(this, function(videojs) {
  'use strict';

  var WistiaState = {
    UNSTARTED: -1,
    ENDED: 0,
    PLAYING: 1,
    PAUSED: 2,
    BUFFERING: 3
  };

  var Tech = videojs.getComponent('Tech');

  var WistiaTech = videojs.extend(Tech, {
    constructor: function(options, ready) {
      Tech.call(this, options, ready);
      this.setSrc(this.options_.source.src, true);
    },

    dispose: function() {
      this.wistiaVideo.remove();
      this.el_.parentNode.removeChild(this.el_);
    },

    createEl: function() {
      var protocol = (document.location.protocol === 'file:') ? 'http:' : document.location.protocol;
      this.wistia = {};
      this.wistiaInfo = {};
      this.baseUrl = protocol + '//fast.wistia.com/embed/iframe/';
      this.videoOptions = WistiaTech.parseUrl(this.options_.source.src);
      this.videoId = this.videoOptions.videoId;

      var divWrapper = videojs.createEl('div', {
        id: this.videoId,
        className: this.videoOptions.classString,
        width: this.options_.width || "100%",
        height: this.options_ .height || "100%"
      });

      this.wistiaScriptElement = videojs.createEl('script', {
        src: protocol + "//fast.wistia.com/assets/external/E-v1.js"
      });

      divWrapper.insertBefore(this.wistiaScriptElement, divWrapper.firstChild);

      this.initPlayer();

      return divWrapper;
    },

    initPlayer: function() {
      var self = this;
      var wistiaVideoID = WistiaTech.parseUrl(this.options_.source.src).videoId;

      self.wistiaInfo = {
        state: WistiaState.UNSTARTED,
        volume: 1,
        muted: false,
        muteVolume: 1,
        time: 0,
        duration: 0,
        buffered: 0,
        url: self.baseUrl + self.videoId,
        error: null
      };

      this.wistiaScriptElement.onload = function() {
        self.wistiaVideo = Wistia.api(self.videoId);
        window._wq = window._wq || [];

        var videos = {};
        videos[self.videoId] = function(video) {
          self.wistiaVideo = video;
          self.onLoad();
        };

        window._wq.push(videos);
      };
    },

    ended: function() {
      return (this.wistiaInfo.state === WistiaState.ENDED)
    },

    onLoad: function() {
      this.wistiaInfo = {
        state: WistiaState.UNSTARTED,
        volume: 1,
        muted: false,
        muteVolume: 1,
        time: 0,
        duration: this.wistiaVideo.duration(),
        buffered: 0,
        url: this.baseUrl + this.videoId,
        error: null
      };

      var self = this;

      this.wistiaVideo.hasData(function() {
        self.onReady();
      });

      this.wistiaVideo.bind('pause', function() {
        self.onPause();
      });

      this.wistiaVideo.bind('play', function() {
        self.onPlay();
      });

      this.wistiaVideo.bind('seek', function(currentTime, lastTime) {
        self.onSeek({seconds: currentTime});
      });

      this.wistiaVideo.bind('secondchange', function(s) {
        self.wistiaInfo.time = s;
        self.player_.trigger('timeupdate');

        if( self.wistiaVideo.percentWatched() >= 1) {
          self.onFinish();
        }
      });

      this.wistiaVideo.bind('volumechange', function(v) {
        self.setVolume(v);
      });

      this.wistiaVideo.bind('end', function(t) {
        self.onFinish();
      });

      this.wistiaVideo.bind('duration', function() {
        self.duration();
      });

    },

    onReady: function(){
      this.isReady_ = true;
      this.triggerReady();
      this.trigger('loadedmetadata');
      if (this.startMuted) {
        this.setMuted(true);
        this.startMuted = false;
      }
    },

    duration: function() {
      var d = this.wistiaVideo ? this.wistiaVideo.duration() : 0;
      return d;
    },

    onLoadProgress: function(data) {
      var durationUpdate = !this.wistiaInfo.duration;
      this.wistiaInfo.duration = data.duration;
      this.wistiaInfo.buffered = data.percent;
      this.trigger('progress');
      if (durationUpdate) this.trigger('durationchange');
    },

    onPlayProgress: function(data) {
      this.wistiaInfo.time = data.seconds;
      this.wistiaVideo.time(this.wistiaInfo.time);
      this.trigger('timeupdate');
    },

    onPlay: function() {
      this.wistiaInfo.state = WistiaState.PLAYING;
      this.trigger('play');
    },

    onPause: function() {
      this.wistiaInfo.state = WistiaState.PAUSED;
      this.trigger('pause');
    },

    onFinish: function() {
      this.wistiaInfo.state = WistiaState.ENDED;
      this.trigger('ended');
    },

    onSeek: function(data) {
      this.trigger('seeking');
      this.wistiaInfo.time = data.seconds;
      this.wistiaVideo.time(this.wistiaInfo.time);
      this.trigger('timeupdate');
      this.trigger('seeked');
    },

    onError: function(error){
      this.error = error;
      this.trigger('error');
    },

    error: function() {
      switch (this.errorNumber) {
        case 2:
          return { code: 'Unable to find the video' };

        case 5:
          return { code: 'Error while trying to play the video' };

        case 100:
          return { code: 'Unable to find the video' };

        case 101:
        case 150:
          return { code: 'Playback on other Websites has been disabled by the video owner.' };
      }

      return { code: 'Wistia unknown error (' + this.errorNumber + ')' };
    },

    playbackRate: function() {
      return this.suggestedRate ? this.suggestedRate : 1;
    },

    setPlaybackRate: function(suggestedRate) {
      if (!this.wistiaVideo) {
        return;
      }
      var d = this.wistiaVideo.playbackRate(suggestedRate);
      this.suggestedRate = suggestedRate;
      this.trigger('ratechange');
    },

    src: function(src) {
      if(src) {
        this.setSrc({ src: src });
      }
      return this.source;
    },

    setSrc: function(source) {
      if(!source || !source.src) {
        return;
      }

      this.source = source;
      this.videoOptions = WistiaTech.parseUrl(source.src);
      this.wistiaVideo.replaceWith(this.videoOptions.videoId, this.videoOptions.options);
    },

    supportsFullScreen: function() {
      return true;
    },

    load: function() {},

    play: function() {
      this.wistiaVideo.play();
    },

    pause: function() {
      this.wistiaVideo.pause();
    },

    paused: function() {
      return this.wistiaInfo.state !== WistiaState.PLAYING &&
             this.wistiaInfo.state !== WistiaState.BUFFERING;
    },

    currentTime: function() {
      return this.wistiaInfo.time || 0;
    },

    setCurrentTime: function(seconds) {
      this.wistiaVideo.time(seconds);
      this.player_.trigger('timeupdate');
    },

    duration: function() {
      return this.wistiaInfo.duration || 0;
    },

    buffered: function() {
      return videojs.createTimeRange(0, (this.wistiaInfo.buffered * this.wistiaInfo.duration) || 0);
    },

    volume: function() {
      return (this.wistiaInfo.muted) ? this.wistiaInfo.muteVolume : this.wistiaInfo.volume;
    },

    setVolume: function(percentAsDecimal) {
      this.wistiaInfo.volume = percentAsDecimal;
      this.wistiaVideo.volume = percentAsDecimal;
      this.player_.trigger('volumechange');
    },

    currentSrc: function() {
      return this.el_.src;
    },

    muted: function() {
      return this.wistiaInfo.muted || false;
    },

    setMuted: function(muted) {
      if(muted) {
        this.wistiaInfo.muteVolume = this.wistiaInfo.volume;
        this.setVolume(0);
      } else {
        this.setVolume(this.wistiaInfo.muteVolume);
      }

      this.wistiaInfo.muted = muted;
      this.player_.trigger('volumechange');
    }
  });

  WistiaTech.isSupported = function() {
    return true;
  };

  WistiaTech.canPlaySource = function(e) {
    return (e.type === 'video/wistia');
  };

  WistiaTech.parseUrl = function(url) {
    var result = {
      videoId: null,
      classes: [],
      classString: '',
      options: {}
    };

    var videoOptions = {};

    var regex = regex = /^.*(wistia\.com\/)(embed\/iframe\/|medias\/)([A-z0-9]+)/;
    var match = url.match(regex);

    if(match) {
      result.videoId = match[3];
    }

    var classes = [];
    classes.push('vjs-tech');
    classes.push('wistia_embed');
    classes.push('wistia_async_' + result.videoId);

    var options = {};
    options['wmode'] = 'transparent';

    if(url) {
      var playerColorMatch = url.match(/playerColor=([#a-fA-f0-9]+)/);
      if(playerColorMatch) {
        videoOptions.playerColor = playerColorMatch[1];
      }

      var controlsVisibleMatch = url.match(/controlsVisibleOnLoad=(true|false)/);
      if(controlsVisibleMatch) {
        videoOptions.controls = controlsVisibleMatch[1];
      }

      var autoPlayMatch = url.match(/autoplay=(true|false)/);
      if(autoPlayMatch) {
        videoOptions.autoplay = autoPlayMatch[1];
      }

      var mutedMatch = url.match(/muted=(true|false)/);
      if(mutedMatch) {
        videoOptions.muted = true;
      }

      var volumeMatch = url.match(/volume=([0-9]+)/);
      if(volumeMatch) {
        videoOptions.volume = volumeMatch[1];
      }

      var endVideoBehaviorMatch = url.match(/endVideoBehavior=(loop|default|reset)/);
      if(endVideoBehaviorMatch) {
        videoOptions.endVideoBehavior = endVideoBehaviorMatch[1];
      }
    }

    var color = videoOptions.playerColor;
    if(color && color.substring(0, 1) === '#') {
      videoOptions.playerColor = color.substring(1);
    }

    if(videoOptions.controls) {
      options['controlsVisibleOnLoad'] = videoOptions.controls;
    }

    if(videoOptions.playerColor) {
      options['playerColor'] = videoOptions.playerColor;
    }

    if(videoOptions.autoplay) {
      options['autoPlay'] = videoOptions.autoplay;
    }

    if(videoOptions.volume !== false) {
      options['volume'] = videoOptions.volume || 1;
    }

    if(videoOptions.muted) {
      options['volume'] = 0;
    }

    if(videoOptions.loop) {
      videoOptions.endVideoBehavior = 'loop';
    }

    if(videoOptions.endVideoBehavior) {
      options['endVideoBehavior'] = videoOptions.endVideoBehavior;
    }

    var keys = Object.keys(options);
    var classString = classes.join(' ') + ' ';
    for(var i = 0; i < keys.length; i++) {
      var key = keys[i];
      var value = options[key];
      classString += key + '=' + value + '&';
    }
    classString = classString.replace(/&+$/,'');

    result.classes = classes;
    result.classString = classString;
    result.options = options;

    return result;
  };

  videojs.registerTech('Wistia', WistiaTech);
}));
<commit_msg>style fix<commit_after>(function (root, factory) {
  if(typeof define === 'function' && define.amd) {
    define(['video.js'], function(videojs){
      return (root.WistiaTech = factory(videojs));
    });
  } else if(typeof module === 'object' && module.exports) {
    module.exports = (root.WistiaTech = factory(require('video.js')));
  } else {
    root.WistiaTech = factory(root.videojs);
  }
}(this, function(videojs) {
  'use strict';

  var WistiaState = {
    UNSTARTED: -1,
    ENDED: 0,
    PLAYING: 1,
    PAUSED: 2,
    BUFFERING: 3
  };

  var Tech = videojs.getComponent('Tech');

  var WistiaTech = videojs.extend(Tech, {
    constructor: function(options, ready) {
      Tech.call(this, options, ready);
      this.setSrc(this.options_.source.src, true);
    },

    dispose: function() {
      this.wistiaVideo.remove();
      this.el_.parentNode.removeChild(this.el_);
    },

    createEl: function() {
      var protocol = (document.location.protocol === 'file:') ? 'http:' : document.location.protocol;
      this.wistia = {};
      this.wistiaInfo = {};
      this.baseUrl = protocol + '//fast.wistia.com/embed/iframe/';
      this.videoOptions = WistiaTech.parseUrl(this.options_.source.src);
      this.videoId = this.videoOptions.videoId;

      var divWrapper = videojs.createEl('div', {
        id: this.videoId,
        className: this.videoOptions.classString,
        width: this.options_.width || "100%",
        height: this.options_ .height || "100%"
      });

      this.wistiaScriptElement = videojs.createEl('script', {
        src: protocol + "//fast.wistia.com/assets/external/E-v1.js"
      });

      divWrapper.insertBefore(this.wistiaScriptElement, divWrapper.firstChild);

      this.initPlayer();

      return divWrapper;
    },

    initPlayer: function() {
      var self = this;
      var wistiaVideoID = WistiaTech.parseUrl(this.options_.source.src).videoId;

      self.wistiaInfo = {
        state: WistiaState.UNSTARTED,
        volume: 1,
        muted: false,
        muteVolume: 1,
        time: 0,
        duration: 0,
        buffered: 0,
        url: self.baseUrl + self.videoId,
        error: null
      };

      this.wistiaScriptElement.onload = function() {
        self.wistiaVideo = Wistia.api(self.videoId);
        window._wq = window._wq || [];

        var videos = {};
        videos[self.videoId] = function(video) {
          self.wistiaVideo = video;
          self.onLoad();
        };

        window._wq.push(videos);
      };
    },

    ended: function() {
      return (this.wistiaInfo.state === WistiaState.ENDED);
    },

    onLoad: function() {
      this.wistiaInfo = {
        state: WistiaState.UNSTARTED,
        volume: 1,
        muted: false,
        muteVolume: 1,
        time: 0,
        duration: this.wistiaVideo.duration(),
        buffered: 0,
        url: this.baseUrl + this.videoId,
        error: null
      };

      var self = this;

      this.wistiaVideo.hasData(function() {
        self.onReady();
      });

      this.wistiaVideo.bind('pause', function() {
        self.onPause();
      });

      this.wistiaVideo.bind('play', function() {
        self.onPlay();
      });

      this.wistiaVideo.bind('seek', function(currentTime, lastTime) {
        self.onSeek({seconds: currentTime});
      });

      this.wistiaVideo.bind('secondchange', function(s) {
        self.wistiaInfo.time = s;
        self.player_.trigger('timeupdate');

        if( self.wistiaVideo.percentWatched() >= 1) {
          self.onFinish();
        }
      });

      this.wistiaVideo.bind('volumechange', function(v) {
        self.setVolume(v);
      });

      this.wistiaVideo.bind('end', function(t) {
        self.onFinish();
      });

    },

    onReady: function(){
      this.isReady_ = true;
      this.triggerReady();
      this.trigger('loadedmetadata');
      if (this.startMuted) {
        this.setMuted(true);
        this.startMuted = false;
      }
    },

    onLoadProgress: function(data) {
      var durationUpdate = !this.wistiaInfo.duration;
      this.wistiaInfo.duration = data.duration;
      this.wistiaInfo.buffered = data.percent;
      this.trigger('progress');
      if (durationUpdate) this.trigger('durationchange');
    },

    onPlayProgress: function(data) {
      this.wistiaInfo.time = data.seconds;
      this.wistiaVideo.time(this.wistiaInfo.time);
      this.trigger('timeupdate');
    },

    onPlay: function() {
      this.wistiaInfo.state = WistiaState.PLAYING;
      this.trigger('play');
    },

    onPause: function() {
      this.wistiaInfo.state = WistiaState.PAUSED;
      this.trigger('pause');
    },

    onFinish: function() {
      this.wistiaInfo.state = WistiaState.ENDED;
      this.trigger('ended');
    },

    onSeek: function(data) {
      this.trigger('seeking');
      this.wistiaInfo.time = data.seconds;
      this.wistiaVideo.time(this.wistiaInfo.time);
      this.trigger('timeupdate');
      this.trigger('seeked');
    },

    onError: function(error){
      this.error = error;
      this.trigger('error');
    },

    error: function() {
      switch (this.errorNumber) {
        case 2:
          return { code: 'Unable to find the video' };

        case 5:
          return { code: 'Error while trying to play the video' };

        case 100:
          return { code: 'Unable to find the video' };

        case 101:
        case 150:
          return { code: 'Playback on other Websites has been disabled by the video owner.' };
      }

      return { code: 'Wistia unknown error (' + this.errorNumber + ')' };
    },

    playbackRate: function() {
      return this.suggestedRate ? this.suggestedRate : 1;
    },

    setPlaybackRate: function(suggestedRate) {
      if (!this.wistiaVideo) {
        return;
      }
      var d = this.wistiaVideo.playbackRate(suggestedRate);
      this.suggestedRate = suggestedRate;
      this.trigger('ratechange');
    },

    src: function(src) {
      if(src) {
        this.setSrc({ src: src });
      }
      return this.source;
    },

    setSrc: function(source) {
      if(!source || !source.src) {
        return;
      }

      this.source = source;
      this.videoOptions = WistiaTech.parseUrl(source.src);
      this.wistiaVideo.replaceWith(this.videoOptions.videoId, this.videoOptions.options);
    },

    supportsFullScreen: function() {
      return true;
    },

    load: function() {},

    play: function() {
      this.wistiaVideo.play();
    },

    pause: function() {
      this.wistiaVideo.pause();
    },

    paused: function() {
      return this.wistiaInfo.state !== WistiaState.PLAYING &&
             this.wistiaInfo.state !== WistiaState.BUFFERING;
    },

    currentTime: function() {
      return this.wistiaInfo.time || 0;
    },

    setCurrentTime: function(seconds) {
      this.wistiaVideo.time(seconds);
      this.player_.trigger('timeupdate');
    },

    duration: function() {
      return this.wistiaInfo.duration || 0;
    },

    buffered: function() {
      return videojs.createTimeRange(0, (this.wistiaInfo.buffered * this.wistiaInfo.duration) || 0);
    },

    volume: function() {
      return (this.wistiaInfo.muted) ? this.wistiaInfo.muteVolume : this.wistiaInfo.volume;
    },

    setVolume: function(percentAsDecimal) {
      this.wistiaInfo.volume = percentAsDecimal;
      this.wistiaVideo.volume = percentAsDecimal;
      this.player_.trigger('volumechange');
    },

    currentSrc: function() {
      return this.el_.src;
    },

    muted: function() {
      return this.wistiaInfo.muted || false;
    },

    setMuted: function(muted) {
      if(muted) {
        this.wistiaInfo.muteVolume = this.wistiaInfo.volume;
        this.setVolume(0);
      } else {
        this.setVolume(this.wistiaInfo.muteVolume);
      }

      this.wistiaInfo.muted = muted;
      this.player_.trigger('volumechange');
    }
  });

  WistiaTech.isSupported = function() {
    return true;
  };

  WistiaTech.canPlaySource = function(e) {
    return (e.type === 'video/wistia');
  };

  WistiaTech.parseUrl = function(url) {
    var result = {
      videoId: null,
      classes: [],
      classString: '',
      options: {}
    };

    var videoOptions = {};

    var regex = regex = /^.*(wistia\.com\/)(embed\/iframe\/|medias\/)([A-z0-9]+)/;
    var match = url.match(regex);

    if(match) {
      result.videoId = match[3];
    }

    var classes = [];
    classes.push('vjs-tech');
    classes.push('wistia_embed');
    classes.push('wistia_async_' + result.videoId);

    var options = {};
    options['wmode'] = 'transparent';

    if(url) {
      var playerColorMatch = url.match(/playerColor=([#a-fA-f0-9]+)/);
      if(playerColorMatch) {
        videoOptions.playerColor = playerColorMatch[1];
      }

      var controlsVisibleMatch = url.match(/controlsVisibleOnLoad=(true|false)/);
      if(controlsVisibleMatch) {
        videoOptions.controls = controlsVisibleMatch[1];
      }

      var autoPlayMatch = url.match(/autoplay=(true|false)/);
      if(autoPlayMatch) {
        videoOptions.autoplay = autoPlayMatch[1];
      }

      var mutedMatch = url.match(/muted=(true|false)/);
      if(mutedMatch) {
        videoOptions.muted = true;
      }

      var volumeMatch = url.match(/volume=([0-9]+)/);
      if(volumeMatch) {
        videoOptions.volume = volumeMatch[1];
      }

      var endVideoBehaviorMatch = url.match(/endVideoBehavior=(loop|default|reset)/);
      if(endVideoBehaviorMatch) {
        videoOptions.endVideoBehavior = endVideoBehaviorMatch[1];
      }
    }

    var color = videoOptions.playerColor;
    if(color && color.substring(0, 1) === '#') {
      videoOptions.playerColor = color.substring(1);
    }

    if(videoOptions.controls) {
      options['controlsVisibleOnLoad'] = videoOptions.controls;
    }

    if(videoOptions.playerColor) {
      options['playerColor'] = videoOptions.playerColor;
    }

    if(videoOptions.autoplay) {
      options['autoPlay'] = videoOptions.autoplay;
    }

    if(videoOptions.volume !== false) {
      options['volume'] = videoOptions.volume || 1;
    }

    if(videoOptions.muted) {
      options['volume'] = 0;
    }

    if(videoOptions.loop) {
      videoOptions.endVideoBehavior = 'loop';
    }

    if(videoOptions.endVideoBehavior) {
      options['endVideoBehavior'] = videoOptions.endVideoBehavior;
    }

    var keys = Object.keys(options);
    var classString = classes.join(' ') + ' ';
    for(var i = 0; i < keys.length; i++) {
      var key = keys[i];
      var value = options[key];
      classString += key + '=' + value + '&';
    }
    classString = classString.replace(/&+$/,'');

    result.classes = classes;
    result.classString = classString;
    result.options = options;

    return result;
  };

  videojs.registerTech('Wistia', WistiaTech);
}));
<|endoftext|>


<commit_before>/* globals state, createObj, findObjs, getObj, getAttrByName, sendChat, on, log, Campaign, playerIsGM, spawnFx,
 spawnFxBetweenPoints, filterObjs */
'use strict';
const _ = require('underscore');

// noinspection JSUnusedGlobalSymbols
module.exports = class Roll20Wrapper {

  getState(module) {
    if (!state[module]) {
      state[module] = {};
    }
    return state[module];
  }

  createObj(type, attributes) {
    return createObj(type, attributes);
  }

  findObjs(attributes) {
    return findObjs(attributes);
  }

  filterObjs(attributes) {
    return filterObjs(attributes);
  }

  getObj(type, id) {
    return getObj(type, id);
  }

  getOrCreateObj(type, attributes) {
    const newAttributes = _.extend(_.clone(attributes), { type });
    const existing = this.findObjs(newAttributes);
    switch (existing.length) {
      case 0:
        return this.createObj(type, newAttributes);
      case 1:
        return existing[0];
      default:
        throw new Error(`Asked for a single ${type} but more than 1 was found matching attributes: ` +
          `${JSON.stringify(attributes)}`);
    }
  }

  getAttrByName(character, attrName) {
    return getAttrByName(character, attrName);
  }

  getAttrObjectByName(character, attrName) {
    const attr = this.findObjs({ type: 'attribute', characterid: character, name: attrName });
    return attr && attr.length > 0 ? attr[0] : null;
  }

  getOrCreateAttr(characterId, attrName) {
    return this.getOrCreateObj('attribute', { characterid: characterId, name: attrName });
  }

  setAttrByName(characterId, attrName, value) {
    this.getOrCreateAttr(characterId, attrName).set('current', value);
  }

  processAttrValue(characterId, attrName, cb) {
    const attribute = this.getOrCreateAttr(characterId, attrName);
    attribute.set('current', cb(attribute.get('current')));
  }

  getRepeatingSectionAttrs(characterId, sectionName) {
    const prefix = `repeating_${sectionName}`;
    return _.filter(this.findObjs({ type: 'attribute', characterid: characterId }),
      attr => attr.get('name').indexOf(prefix) === 0);
  }

  getRepeatingSectionItemIdsByName(characterId, sectionName) {
    const re = new RegExp(`repeating_${sectionName}_([^_]+)_name$`);
    return _.reduce(this.getRepeatingSectionAttrs(characterId, sectionName),
      (lookup, attr) => {
        const match = attr.get('name').match(re);
        if (match) {
          lookup[attr.get('current').toLowerCase()] = match[1];
        }
        return lookup;
      }, {});
  }

  getCurrentPage(playerId) {
    let pageId;
    if (this.playerIsGM(playerId)) {
      pageId = this.getObj('player', playerId).get('lastpage');
    }
    else {
      pageId = this.getCampaign().get('playerspecificpages')[playerId] || this.getCampaign().get('playerpageid');
    }

    return pageId ? this.getObj('page', pageId) : null;
  }

  spawnFx(pointsArray, fxType, pageId) {
    switch (pointsArray.length) {
      case 1:
        spawnFx(pointsArray[0].x, pointsArray[0].y, fxType, pageId);
        break;
      case 2:
        spawnFxBetweenPoints(pointsArray[0], pointsArray[1], fxType, pageId);
        break;
      default:
        throw new Error('Wrong number of points supplied to spawnFx: $$$', pointsArray);
    }
  }

  playerIsGM(playerId) {
    return playerIsGM(playerId);
  }

  getCampaign() {
    return Campaign(); // eslint-disable-line
  }

  sendChat(sendAs, message, callback, options) {
    return sendChat(sendAs, message, callback, options);
  }

  on(event, callback) {
    return on(event, callback);
  }

  log(msg) {
    return log(msg);
  }
};

<commit_msg>Add valueType to getAttrByName<commit_after>/* globals state, createObj, findObjs, getObj, getAttrByName, sendChat, on, log, Campaign, playerIsGM, spawnFx,
 spawnFxBetweenPoints, filterObjs */
'use strict';
const _ = require('underscore');

// noinspection JSUnusedGlobalSymbols
module.exports = class Roll20Wrapper {

  getState(module) {
    if (!state[module]) {
      state[module] = {};
    }
    return state[module];
  }

  createObj(type, attributes) {
    return createObj(type, attributes);
  }

  findObjs(attributes) {
    return findObjs(attributes);
  }

  filterObjs(attributes) {
    return filterObjs(attributes);
  }

  getObj(type, id) {
    return getObj(type, id);
  }

  getOrCreateObj(type, attributes) {
    const newAttributes = _.extend(_.clone(attributes), { type });
    const existing = this.findObjs(newAttributes);
    switch (existing.length) {
      case 0:
        return this.createObj(type, newAttributes);
      case 1:
        return existing[0];
      default:
        throw new Error(`Asked for a single ${type} but more than 1 was found matching attributes: ` +
          `${JSON.stringify(attributes)}`);
    }
  }

  getAttrByName(character, attrName, valueType) {
    return getAttrByName(character, attrName, valueType);
  }

  getAttrObjectByName(character, attrName) {
    const attr = this.findObjs({ type: 'attribute', characterid: character, name: attrName });
    return attr && attr.length > 0 ? attr[0] : null;
  }

  getOrCreateAttr(characterId, attrName) {
    return this.getOrCreateObj('attribute', { characterid: characterId, name: attrName });
  }

  setAttrByName(characterId, attrName, value) {
    this.getOrCreateAttr(characterId, attrName).set('current', value);
  }

  processAttrValue(characterId, attrName, cb) {
    const attribute = this.getOrCreateAttr(characterId, attrName);
    attribute.set('current', cb(attribute.get('current')));
  }

  getRepeatingSectionAttrs(characterId, sectionName) {
    const prefix = `repeating_${sectionName}`;
    return _.filter(this.findObjs({ type: 'attribute', characterid: characterId }),
      attr => attr.get('name').indexOf(prefix) === 0);
  }

  getRepeatingSectionItemIdsByName(characterId, sectionName) {
    const re = new RegExp(`repeating_${sectionName}_([^_]+)_name$`);
    return _.reduce(this.getRepeatingSectionAttrs(characterId, sectionName),
      (lookup, attr) => {
        const match = attr.get('name').match(re);
        if (match) {
          lookup[attr.get('current').toLowerCase()] = match[1];
        }
        return lookup;
      }, {});
  }

  getCurrentPage(playerId) {
    let pageId;
    if (this.playerIsGM(playerId)) {
      pageId = this.getObj('player', playerId).get('lastpage');
    }
    else {
      pageId = this.getCampaign().get('playerspecificpages')[playerId] || this.getCampaign().get('playerpageid');
    }

    return pageId ? this.getObj('page', pageId) : null;
  }

  spawnFx(pointsArray, fxType, pageId) {
    switch (pointsArray.length) {
      case 1:
        spawnFx(pointsArray[0].x, pointsArray[0].y, fxType, pageId);
        break;
      case 2:
        spawnFxBetweenPoints(pointsArray[0], pointsArray[1], fxType, pageId);
        break;
      default:
        throw new Error('Wrong number of points supplied to spawnFx: $$$', pointsArray);
    }
  }

  playerIsGM(playerId) {
    return playerIsGM(playerId);
  }

  getCampaign() {
    return Campaign(); // eslint-disable-line
  }

  sendChat(sendAs, message, callback, options) {
    return sendChat(sendAs, message, callback, options);
  }

  on(event, callback) {
    return on(event, callback);
  }

  log(msg) {
    return log(msg);
  }
};

<|endoftext|>


<commit_before>/*****************************************************************************
* #### jentikjs ####
* jQuery plugin untuk membuat widget mengecek ongkir atau tracking TIKI & JNE
* Coded by Ican Bachors 2016.
* http://ibacor.com/labs/jentikjs
* Updates will be posted to this site.
*****************************************************************************/

var jentik = function() {
    $('#jentik').html('

ongkir

tracking

jne

tiki

ongkir

Kota Asal<input type="text" id="tiki_dari" list="rute_tiki_dari" placeholder="Bandung"/><datalist id="rute_tiki_dari"></datalist>Kota Tujuan<input type="text" id="tiki_ke" list="rute_tiki_ke" placeholder="Surabaya"/><datalist id="rute_tiki_ke"></datalist>Berat (Kg)<input type="text" id="tiki_kg" placeholder="4"/><input type="submit" class="cek_ongkir" data-jentik="tiki" value="Cek Ongkir"/>

Kota Asal<input type="text" id="jne_dari" list="rute_jne_dari" placeholder="Bandung"/><datalist id="rute_jne_dari"></datalist>Kota Tujuan<input type="text" id="jne_ke" list="rute_jne_ke" placeholder="Surabaya"/><datalist id="rute_jne_ke"></datalist>Berat (Kg)<input type="text" id="jne_kg" placeholder="4"/><input type="submit" class="cek_ongkir" data-jentik="jne" value="Cek Ongkir"/>

Nomor Resi<input type="text" id="tiki_resi" placeholder="xxx"/><input type="submit" class="cek_resi" data-jentik="tiki" value="Cek Resi"/>

Nomor Resi<input type="text" id="jne_resi" placeholder="xxx"/><input type="submit" class="cek_resi" data-jentik="jne" value="Cek Resi"/>

Made with<3
');
    $('body').on('click', '#jentik .tab1', function() {
        var a = $(this).html(),
            tab2 = $('#jentik .aktip2').html();
        $('#jentik-anu').html(a);
        $('#jentik .tab1').removeClass('aktip1');
        if (a == 'ongkir') {
            $('#jentik #kotak-tracking').css('display', 'none');
            $('#jentik #kotak-ongkir').css('display', 'block');
            $('#jentik #kotak-ongkir-jne').css('display', 'none');
            $('#jentik #kotak-ongkir-tiki').css('display', 'none');
            $('#jentik #kotak-ongkir-' + tab2).css('display', 'block')
        } else if (a == 'tracking') {
            $('#jentik #kotak-ongkir').css('display', 'none');
            $('#jentik #kotak-tracking').css('display', 'block');
            $('#jentik #kotak-tracking-jne').css('display', 'none');
            $('#jentik #kotak-tracking-tiki').css('display', 'none');
            $('#jentik #kotak-tracking-' + tab2).css('display', 'block')
        }
        $(this).addClass('aktip1');
        $('#jentik-output').html('');
        return false
    });
    $('body').on('click', '#jentik .tab2', function() {
        var a = $(this).html(),
            anu = $('#jentik-anu').html();
        $('#jentik .tab2').removeClass('aktip2');
        if (a == 'jne') {
            $('#jentik #kotak-' + anu + '-tiki').css('display', 'none');
            $('#jentik #kotak-' + anu + '-jne').css('display', 'block')
        } else if (a == 'tiki') {
            $('#jentik #kotak-' + anu + '-jne').css('display', 'none');
            $('#jentik #kotak-' + anu + '-tiki').css('display', 'block')
        }
        $(this).addClass('aktip2');
        $('#jentik-output').html('');
        return false
    });
    $('body').on('focus', '#tiki_dari', function() {
        var a = $(this).attr('list');
        $(this).keydown(function() {
            setTimeout(function() {
                var d = $('#tiki_dari').val(),
                    jum = d.length;
                if (jum > 2) {
                    rute_tiki(d, a)
                }
            }, 50)
        })
    });
    $('body').on('focus', '#tiki_ke', function() {
        var a = $(this).attr('list');
        $(this).keydown(function() {
            setTimeout(function() {
                var d = $('#tiki_ke').val(),
                    jum = d.length;
                if (jum > 2) {
                    rute_tiki(d, a)
                }
            }, 50)
        })
    });
    $('body').on('focus', '#jne_dari', function() {
        var a = $(this).attr('list');
        $(this).keydown(function() {
            setTimeout(function() {
                var d = $('#jne_dari').val(),
                    jum = d.length;
                if (jum > 2) {
                    rute_jne(d, 'dari', a)
                }
            }, 50)
        })
    });
    $('body').on('focus', '#jne_ke', function() {
        var a = $(this).attr('list');
        $(this).keydown(function() {
            setTimeout(function() {
                var d = $('#jne_ke').val(),
                    jum = d.length;
                if (jum > 2) {
                    rute_jne(d, 'ke', a)
                }
            }, 50)
        })
    });
    $('body').on('click', '.cek_ongkir', function() {
        $('#jentik-output').html('
Wait..
');
        var a = $(this).data('jentik'),
            dari = (a == 'jne' ? $("#jne_dari").val() : $("#tiki_dari").val()),
            ke = (a == 'jne' ? $("#jne_ke").val() : $("#tiki_ke").val()),
            berat = (a == 'jne' ? $("#jne_kg").val() : $("#tiki_kg").val());
        cekongkir(a, dari, ke, berat);
        return false
    });
    $('body').on('click', '.cek_resi', function() {
        $('#jentik-output').html('
Wait..
');
        var a = $(this).data('jentik'),
            resi = (a == 'jne' ? $("#jne_resi").val() : $("#tiki_resi").val());
        cekresi(a, resi);
        return false
    });

    function rute_tiki(d, e) {
        $.ajax({
            url: 'http://ibacor.com/api/rute-jne-tiki?p=tiki&q=' + d,
            crossDomain: true,
            dataType: 'json'
        }).done(function(b) {
            var c = '';
            $.each(b, function(i, a) {
                c += '<option value="' + b[i] + '">'
            });
            $('#' + e).html(c)
        })
    }

    function rute_jne(d, t, e) {
        $.ajax({
            url: 'http://ibacor.com/api/rute-jne-tiki?p=jne&q=' + d + '&t=' + t,
            crossDomain: true,
            dataType: 'json'
        }).done(function(b) {
            var c = '';
            $.each(b, function(i, a) {
                c += '<option value="' + b[i] + '">'
            });
            $('#' + e).html(c)
        })
    }

    function cekongkir(f, g, h, j) {
        $.ajax({
            url: 'http://ibacor.com/api/ongkir?service=' + f + '&dari=' + g + '&ke=' + h + '&berat=' + j,
            crossDomain: true,
            dataType: 'json'
        }).done(function(d) {
            var e = '',
				w = '';
            if (d.status == 'success') {
                e += '
Ongkir ' + d.service + ' ' + d.dari + ' ke ' + d.ke + ' (' + d.berat + ' kg)
';
                e += '
';
                if (f == 'tiki') {
					w += 'http://tiki-online.com';
                    e += '
LAYANAN	TARIF
'
                } else if (f == 'jne') {
					w += 'http://www.jne.co.id';
                    e += '
LAYANAN	KIRIMAN	TARIF	ETD
'
                }
                $.each(d.ongkos, function(i, c) {
                    e += '
';
                    $.each(d.ongkos[i], function(a, b) {
                        e += '' + b + '	'
                    });
                    e += '
'
                });
                e += '
'
            } else {
                e += d.status + ': ' + d.message
            }
            $('#jentik-output').html('
' + e + '
' + w + '

')
        })
    }

    function cekresi(g, h) {
        $.ajax({
            url: 'http://ibacor.com/api/cek-resi?pengirim=' + g + '&resi=' + h,
            crossDomain: true,
            dataType: 'json'
        }).done(function(d) {
            var e = '',
				w = '';
            if (d.status == 'success') {
                var f = (d.data.detail.tujuan.nama == undefined ? '' : d.data.detail.tujuan.nama),
                    namaasal = (d.data.detail.asal.nama == undefined ? '' : d.data.detail.asal.nama);
                e += '
Detail
';
                e += '
';
                e += '
Status:	' + d.data.detail.status + '
';
                e += '
No Resi:	' + d.data.detail.no_resi + '
';
                e += '
Service:	' + d.data.detail.service + '
';
                e += '
Tanggal:	' + d.data.detail.tanggal + '
';
                e += '
Asal:	' + d.data.detail.asal.alamat + '
' + namaasal + '
';
                e += '
Tujuan:	' + d.data.detail.tujuan.alamat + '
' + f + '
';
                e += '
';
                e += '
Riwayat
';
                e += '
';
                if (g == 'tiki') {
					w += 'http://tiki-online.com';
                    e += '
TANGGAL	WAKTU	STATUS	LOKASI	KETERANGAN
'
                } else if (g == 'jne') {
					w += 'http://www.jne.co.id';
                    e += '
TANGGAL	LOKASI	KETERANGAN
'
                }
                $.each(d.data.riwayat, function(i, c) {
                    e += '
';
                    $.each(d.data.riwayat[i], function(a, b) {
                        e += '' + b + '	'
                    });
                    e += '
'
                });
                e += '
'
            } else {
                e += d.status + ': ' + d.pesan
            }
            $('#jentik-output').html('
' + e + '
' + w + '

')
        })
    }
}
<commit_msg>add cek resi pos indonesia<commit_after>/*****************************************************************************
* #### jentikjs ####
* jQuery plugin untuk membuat widget mengecek ongkir atau tracking TIKI & JNE
* Coded by Ican Bachors 2016.
* http://ibacor.com/labs/jentikjs
* Updates will be posted to this site.
*****************************************************************************/

var jentik = function() {
    $('#jentik').html('

ongkir

tracking

jne

tiki

pos

ongkir

Kota Asal<input type="text" id="tiki_dari" list="rute_tiki_dari" placeholder="Bandung"/><datalist id="rute_tiki_dari"></datalist>Kota Tujuan<input type="text" id="tiki_ke" list="rute_tiki_ke" placeholder="Surabaya"/><datalist id="rute_tiki_ke"></datalist>Berat (Kg)<input type="text" id="tiki_kg" placeholder="4"/><input type="submit" class="cek_ongkir" data-jentik="tiki" value="Cek Ongkir"/>

Kota Asal<input type="text" id="jne_dari" list="rute_jne_dari" placeholder="Bandung"/><datalist id="rute_jne_dari"></datalist>Kota Tujuan<input type="text" id="jne_ke" list="rute_jne_ke" placeholder="Surabaya"/><datalist id="rute_jne_ke"></datalist>Berat (Kg)<input type="text" id="jne_kg" placeholder="4"/><input type="submit" class="cek_ongkir" data-jentik="jne" value="Cek Ongkir"/>

Coming Soon..

Nomor Resi<input type="text" id="tiki_resi" placeholder="xxx"/><input type="submit" class="cek_resi" data-jentik="tiki" value="Cek Resi"/>

Nomor Resi<input type="text" id="jne_resi" placeholder="xxx"/><input type="submit" class="cek_resi" data-jentik="jne" value="Cek Resi"/>

Nomor Resi<input type="text" id="pos_resi" placeholder="xxx"/><input type="submit" class="cek_resi" data-jentik="pos" value="Cek Resi"/>

Made with<3
');
    $('body').on('click', '#jentik .tab1', function() {
        var a = $(this).html(),
            tab2 = $('#jentik .aktip2').html();
        $('#jentik-anu').html(a);
        $('#jentik .tab1').removeClass('aktip1');
        if (a == 'ongkir') {
            $('#jentik #kotak-tracking').css('display', 'none');
            $('#jentik #kotak-ongkir').css('display', 'block');
            $('#jentik #kotak-ongkir-jne').css('display', 'none');
            $('#jentik #kotak-ongkir-tiki').css('display', 'none');
            $('#jentik #kotak-ongkir-' + tab2).css('display', 'block')
        } else if (a == 'tracking') {
            $('#jentik #kotak-ongkir').css('display', 'none');
            $('#jentik #kotak-tracking').css('display', 'block');
            $('#jentik #kotak-tracking-jne').css('display', 'none');
            $('#jentik #kotak-tracking-tiki').css('display', 'none');
            $('#jentik #kotak-tracking-' + tab2).css('display', 'block')
        }
        $(this).addClass('aktip1');
        $('#jentik-output').html('');
        return false
    });
    $('body').on('click', '#jentik .tab2', function() {
        var a = $(this).html(),
            anu = $('#jentik-anu').html();
        $('#jentik .tab2').removeClass('aktip2');
        if (a == 'jne') {
            $('#jentik #kotak-' + anu + '-tiki').css('display', 'none');
            $('#jentik #kotak-' + anu + '-pos').css('display', 'none');
            $('#jentik #kotak-' + anu + '-jne').css('display', 'block');
        } else if (a == 'tiki') {
            $('#jentik #kotak-' + anu + '-jne').css('display', 'none');
            $('#jentik #kotak-' + anu + '-pos').css('display', 'none');
            $('#jentik #kotak-' + anu + '-tiki').css('display', 'block');
        } else if (a == 'pos') {
            $('#jentik #kotak-' + anu + '-jne').css('display', 'none');
            $('#jentik #kotak-' + anu + '-tiki').css('display', 'none');
            $('#jentik #kotak-' + anu + '-pos').css('display', 'block');
        }
        $(this).addClass('aktip2');
        $('#jentik-output').html('');
        return false
    });
    $('body').on('focus', '#tiki_dari', function() {
        var a = $(this).attr('list');
        $(this).keydown(function() {
            setTimeout(function() {
                var d = $('#tiki_dari').val(),
                    jum = d.length;
                if (jum > 2) {
                    rute_tiki(d, a)
                }
            }, 50)
        })
    });
    $('body').on('focus', '#tiki_ke', function() {
        var a = $(this).attr('list');
        $(this).keydown(function() {
            setTimeout(function() {
                var d = $('#tiki_ke').val(),
                    jum = d.length;
                if (jum > 2) {
                    rute_tiki(d, a)
                }
            }, 50)
        })
    });
    $('body').on('focus', '#jne_dari', function() {
        var a = $(this).attr('list');
        $(this).keydown(function() {
            setTimeout(function() {
                var d = $('#jne_dari').val(),
                    jum = d.length;
                if (jum > 2) {
                    rute_jne(d, 'dari', a)
                }
            }, 50)
        })
    });
    $('body').on('focus', '#jne_ke', function() {
        var a = $(this).attr('list');
        $(this).keydown(function() {
            setTimeout(function() {
                var d = $('#jne_ke').val(),
                    jum = d.length;
                if (jum > 2) {
                    rute_jne(d, 'ke', a)
                }
            }, 50)
        })
    });
    $('body').on('click', '.cek_ongkir', function() {
        $('#jentik-output').html('
Wait..
');
        var a = $(this).data('jentik'),
            dari = (a == 'jne' ? $("#jne_dari").val() : $("#tiki_dari").val()),
            ke = (a == 'jne' ? $("#jne_ke").val() : $("#tiki_ke").val()),
            berat = (a == 'jne' ? $("#jne_kg").val() : $("#tiki_kg").val());
        cekongkir(a, dari, ke, berat);
        return false
    });
    $('body').on('click', '.cek_resi', function() {
        $('#jentik-output').html('
Wait..
');
        var a = $(this).data('jentik'),
            resi = '';
			if(a == 'jne'){
				resi = $("#jne_resi").val();
			}else if(a == 'tii'){
				resi = $("#tiki_resi").val();
			}else if(a == 'pos'){
				resi = $("#pos_resi").val();
			}
        cekresi(a, resi);
        return false
    });

    function rute_tiki(d, e) {
        $.ajax({
            url: 'http://ibacor.com/api/rute-jne-tiki?p=tiki&q=' + d,
            crossDomain: true,
            dataType: 'json'
        }).done(function(b) {
            var c = '';
            $.each(b, function(i, a) {
                c += '<option value="' + b[i] + '">'
            });
            $('#' + e).html(c)
        })
    }

    function rute_jne(d, t, e) {
        $.ajax({
            url: 'http://ibacor.com/api/rute-jne-tiki?p=jne&q=' + d + '&t=' + t,
            crossDomain: true,
            dataType: 'json'
        }).done(function(b) {
            var c = '';
            $.each(b, function(i, a) {
                c += '<option value="' + b[i] + '">'
            });
            $('#' + e).html(c)
        })
    }

    function cekongkir(f, g, h, j) {
        $.ajax({
            url: 'http://ibacor.com/api/ongkir?service=' + f + '&dari=' + g + '&ke=' + h + '&berat=' + j,
            crossDomain: true,
            dataType: 'json'
        }).done(function(d) {
            var e = '',
				w = '';
            if (d.status == 'success') {
                e += '
Ongkir ' + d.service + ' ' + d.dari + ' ke ' + d.ke + ' (' + d.berat + ' kg)
';
                e += '
';
                if (f == 'tiki') {
					w += 'http://tiki-online.com';
                    e += '
LAYANAN	TARIF
'
                } else if (f == 'jne') {
					w += 'http://www.jne.co.id';
                    e += '
LAYANAN	KIRIMAN	TARIF	ETD
'
                }
                $.each(d.ongkos, function(i, c) {
                    e += '
';
                    $.each(d.ongkos[i], function(a, b) {
                        e += '' + b + '	'
                    });
                    e += '
'
                });
                e += '
'
            } else {
                e += d.status + ': ' + d.message
            }
            $('#jentik-output').html('
' + e + '
' + w + '

')
        })
    }

    function cekresi(g, h) {
        $.ajax({
            url: 'http://ibacor.com/api/cek-resi?pengirim=' + g + '&resi=' + h,
            crossDomain: true,
            dataType: 'json'
        }).done(function(d) {
            var e = '';
            if (d.status == 'success') {
                var f = (d.data.detail.tujuan.nama == undefined ? '' : d.data.detail.tujuan.nama),
                    namaasal = (d.data.detail.asal.nama == undefined ? '' : d.data.detail.asal.nama);
                e += '
Detail
';
                e += '
';
                e += '
Status:	' + d.data.detail.status + '
';
                e += '
No Resi:	' + d.data.detail.no_resi + '
';
                e += '
Service:	' + d.data.detail.service + '
';
				if (g == 'tiki' || g == 'jne') {
					e += '
Tanggal:	' + d.data.detail.tanggal + '
';
				}
                e += '
Asal:	' + d.data.detail.asal.alamat + '
' + namaasal + '
';
                e += '
Tujuan:	' + d.data.detail.tujuan.alamat + '
' + f + '
';
                e += '
';
                e += '
Riwayat
';
                e += '
';
                if (g == 'tiki') {
					e += '
TANGGAL	WAKTU	STATUS	LOKASI	KETERANGAN
'
                } else if (g == 'jne') {
					e += '
TANGGAL	LOKASI	KETERANGAN
'
                } else if (g == 'pos') {
					e += '
TANGGAL	STATUS	LOKASI	KETERANGAN
'
                }
                $.each(d.data.riwayat, function(i, c) {
                    e += '
';
                    $.each(d.data.riwayat[i], function(a, b) {
                        e += '' + b + '	'
                    });
                    e += '
'
                });
                e += '
';
				e += '
' + d.website + '
';
            } else {
                e += d.status + ': ' + d.pesan
            }
            $('#jentik-output').html('
' + e + '
')
        })
    }
}
<|endoftext|>