<commit_before>$(document).ready(function () {

    initI18N();
    bindEvents();

    //目前只支持中英文
    function initI18N() {
        var path = getCommonScriptPath();
        Localization.initializeI18N(path, function () {
            if (window.isSite) {
                localize();
            }
            $('html').attr("lang", utils.getLanguage());
            Localization.localize();
            onLoadCallBack(); //设置标题栏当前语言
        });
    }

    function onLoadCallBack() {
        var lan = utils.getLanguage();
        var lang_text = $("[data-lang=" + lan + "]").html() || "中文";
        $('#lang').html(lang_text);

        setCurrentVersion();
        resetCurrentVersionLink();
    }

    //设置头部版本号
    function setCurrentVersion() {
        if (window.isLocal) {
            return;
        }
        var version = getVersion();
        var versionText = version ? "" + version : "";
        $('#version').html(versionText);
    }

    function getVersion() {
        var pathname = window.location.pathname.replace("/en/", "/");
        var match = pathname.match(/^\/(dev|(?:\d+\.)+\d)\/.*/);//匹配版本:dev|9.0.0
        return match && match[1] ? match[1] : null;
    }

    //重置当前版本链接,不带版本号
    function resetCurrentVersionLink() {
        if (!window.version) {
            return;
        }

        var version = window.version;
        version = version.toString();
        $(".icl-nav-version").each(function (key, item) {
            if (item.href) {
                var reg = new RegExp("(.*)\/(" + version + ")(\/.*)");
                var match = item.href.match(reg);
                if (match && match[1] && match[3]) {
                    item.href = match[1] + match[3];
                }
            }
        });
    }

    function bindEvents() {
        $('.icl-header').on('click', '.lang-option', function () {
            var value = $(this).data('lang');
            utils.setLanguage(value);
            $('#lang').html($(this).html());
            i18next.changeLanguage(value);
            if (window.isSite) {
                localize();
                return;
            }
            window.location.reload();
        });
    }

    function localize() {
        var lang = utils.getLanguage();
        var pathname = window.location.pathname.replace("/en/", "/");
        var href = window.location.origin + pathname;
        if (lang === "en-US") {
            if (getVersion()) {
                href = window.location.origin + pathname.replace(/([^\/]*\/){1}([^\/]*)/, '$1$2/en');
                //href = window.location.origin + pathname.replace(/([^\/]*\/){2}([^\/]*)/, '/$1$2/en');
            } else if (window.isLocal) {
                href = window.location.origin + pathname.replace(/(([^\/]*\/){3})([^\/]*)/, '$1$3/en')
            } else {
                href = window.location.origin + pathname.replace(/([^\/]*\/){1}([^\/]*)/, '/en/$2');
                //href = window.location.origin + pathname.replace(/([^\/]*\/){1}([^\/]*)/, '/$2/en');
            }

        }
        if ((window.location.origin + window.location.pathname) === href) {
            return;
        }
        window.location = href;
    }

    function getCommonScriptPath() {
        var r = new RegExp("(^|(.*?\\/))(common\.js)(\\?|$)"),
            s = document.getElementsByTagName('script'), relativePath;
        for (var i = 0; i < s.length; i++) {
            var src = s[i].getAttribute('src');
            if (src) {
                var m = src.match(r);
                if (m) {
                    relativePath = m[1] ? m[1].replace("js/", "") : "./";
                    break;
                }
            }
        }
        return relativePath;
    }

});<commit_msg>修改examples中英文切换hash丢失的问题<commit_after>$(document).ready(function () {

    initI18N();
    bindEvents();

    //目前只支持中英文
    function initI18N() {
        var path = getCommonScriptPath();
        Localization.initializeI18N(path, function () {
            if (window.isSite) {
                localize();
            }
            $('html').attr("lang", utils.getLanguage());
            Localization.localize();
            onLoadCallBack(); //设置标题栏当前语言
        });
    }

    function onLoadCallBack() {
        var lan = utils.getLanguage();
        var lang_text = $("[data-lang=" + lan + "]").html() || "中文";
        $('#lang').html(lang_text);

        setCurrentVersion();
        resetCurrentVersionLink();
    }

    //设置头部版本号
    function setCurrentVersion() {
        if (window.isLocal) {
            return;
        }
        var version = getVersion();
        var versionText = version ? "" + version : "";
        $('#version').html(versionText);
    }

    function getVersion() {
        var pathname = window.location.pathname.replace("/en/", "/");
        var match = pathname.match(/^\/(dev|(?:\d+\.)+\d)\/.*/);//匹配版本:dev|9.0.0
        return match && match[1] ? match[1] : null;
    }

    //重置当前版本链接,不带版本号
    function resetCurrentVersionLink() {
        if (!window.version) {
            return;
        }

        var version = window.version;
        version = version.toString();
        $(".icl-nav-version").each(function (key, item) {
            if (item.href) {
                var reg = new RegExp("(.*)\/(" + version + ")(\/.*)");
                var match = item.href.match(reg);
                if (match && match[1] && match[3]) {
                    item.href = match[1] + match[3];
                }
            }
        });
    }

    function bindEvents() {
        $('.icl-header').on('click', '.lang-option', function () {
            var value = $(this).data('lang');
            utils.setLanguage(value);
            $('#lang').html($(this).html());
            i18next.changeLanguage(value);
            if (window.isSite) {
                localize();
                return;
            }
            window.location.reload();
        });
    }

    function localize() {
        var lang = utils.getLanguage();
        var pathname = window.location.pathname.replace("/en/", "/");
        var hash = window.location.hash;
        var href = window.location.origin + pathname;
        if (lang === "en-US") {
            if (getVersion()) {
                href = window.location.origin + pathname.replace(/([^\/]*\/){1}([^\/]*)/, '$1$2/en');
                //href = window.location.origin + pathname.replace(/([^\/]*\/){2}([^\/]*)/, '/$1$2/en');
            } else if (window.isLocal) {
                href = window.location.origin + pathname.replace(/(([^\/]*\/){3})([^\/]*)/, '$1$3/en')
            } else {
                href = window.location.origin + pathname.replace(/([^\/]*\/){1}([^\/]*)/, '/en/$2');
                //href = window.location.origin + pathname.replace(/([^\/]*\/){1}([^\/]*)/, '/$2/en');
            }

        }
        if ((window.location.origin + window.location.pathname+hash) === href+hash) {
            return;
        }
        window.location = href+hash;
    }

    function getCommonScriptPath() {
        var r = new RegExp("(^|(.*?\\/))(common\.js)(\\?|$)"),
            s = document.getElementsByTagName('script'), relativePath;
        for (var i = 0; i < s.length; i++) {
            var src = s[i].getAttribute('src');
            if (src) {
                var m = src.match(r);
                if (m) {
                    relativePath = m[1] ? m[1].replace("js/", "") : "./";
                    break;
                }
            }
        }
        return relativePath;
    }

});<|endoftext|>


<commit_before>(function() {
    window.utils = {
        thing: document.getElementById("thing"),
        thingWrap: document.getElementById("thing-wrap"),
        getDate: function() {
            var d = new Date();
            return new Date(d.getTime() - d.getTimezoneOffset() * 60000).toJSON().slice(0, 10)
        },
        getThingValue: function() {
            return thing.value;
        },
        setThingValue: function() {
            chrome.storage.sync.set({
                thing: (function() {
                   return utils.getThingValue();
                })()
            })
        }
    }
})()<commit_msg>change reference to thing to this.thing<commit_after>(function() {
    window.utils = {
        thing: document.getElementById("thing"),
        thingWrap: document.getElementById("thing-wrap"),
        getDate: function() {
            var d = new Date();
            return new Date(d.getTime() - d.getTimezoneOffset() * 60000).toJSON().slice(0, 10)
        },
        getThingValue: function() {
            return this.thing.value;
        },
        setThingValue: function() {
            chrome.storage.sync.set({
                thing: (function() {
                   return utils.getThingValue();
                })()
            })
        }
    }
})()<|endoftext|>


<commit_before>//
// Copyright (c) Telefonica I+D. All rights reserved.
//
//

var config = require('./config.js');
var cluster = require('cluster');
var numCPUs = require('os').cpus().length;
var jade = require('jade');
var crypto = require('crypto');

var path = require('path');
var log = require('PDITCLogger');
var logger = log.newLogger();
logger.prefix = path.basename(module.filename, '.js');
logger.setLevel(config.logLevel);

var dirModule = path.dirname(module.filename);

var prefixer = require('./prefixer');
var sendrender = require('./sendrender');

logger.info('Node version:', process.versions.node);
logger.info('V8 version:', process.versions.v8);

if (config.cluster.numcpus >= 0 && config.cluster.numcpus < numCPUs) {
    numCPUs = config.cluster.numcpus;
    logger.info('numCPUs=' + numCPUs);
}

if (cluster.isMaster && numCPUs !== 0) {
    // Fork workers.
    for (var i = 0; i < numCPUs; i++) {
        cluster.fork();
    }

    cluster.on('death', function (worker) {
        'use strict';
        logger.warning('worker ' + worker.pid + ' died');
    });
} else {
    logger.debug('cluster worker', cluster);

    var fs = require('fs');
    var express = require('express');
    var logic = require('./agent_logic');
    var async = require('async');
    var emitter = require('./emitter_module').getEmitter();
    var evLsnr = require('./ev_lsnr');
    var cbLsnr = require('./ev_callback_lsnr');

    var servers = [];
    var app = express.createServer();
    app.prefix = "UNSEC:";
    app.port = config.agent.port;
    servers.push(app);

    logger.info("config.enableSecure", config.enableSecure);
    if (config.enableSecure === true || config.enableSecure === "true" || config.enableSecure === 1) {
        if (!config.agent.crt_path) {
            var options_dir = {
                key: path.resolve(dirModule, '../utils/server.key'),
                cert: path.resolve(dirModule, '../utils/server.crt')
            };
        } else {
            var options_dir = {
                key: path.resolve(config.agent.crt_path, 'server.key'),
                cert: path.resolve(config.agent.crt_path, 'server.crt')
            };
        }

        /*checks whether the cert files exist or not
         and starts the appSec server*/

        if (path.existsSync(options_dir.key) &&
            path.existsSync(options_dir.cert) &&
            fs.statSync(options_dir.key).isFile() &&
            fs.statSync(options_dir.cert).isFile()) {

            var options = {
                key: fs.readFileSync(options_dir.key),
                cert: fs.readFileSync(options_dir.cert)
            };
            logger.info("valid certificates");
        } else {
            logger.debug('certs not found', options_dir);
            throw new Error("No valid certificates were found in the given path");
        }

        var appSec = express.createServer(options);
        appSec.prefix = "SEC:";
        appSec.port = Number(config.agent.port) + 1;

        servers.push(appSec);
    }

    servers.forEach(function (server) {
        server.use(express.query());
        server.use(express.bodyParser());
        server.use(express.limit(config.agent.max_req_size));
        server.use(prefixer.prefixer(server.prefix));
        server.use(sendrender.sendRender());
        server.use("/", express.static(__dirname + '/public'));
        server.del('/trans/:id_trans', logic.deleteTrans);
        //app.get('/trans/:id_trans/state/:state?', logic.transState);
        server.get('/trans/:id_trans', logic.transMeta);
        server.put('/trans/:id_trans', logic.putTransMeta);
        server.post('/trans/:id_trans/payload', logic.payloadTrans);
        server.post('/trans/:id_trans/expirationDate', logic.expirationDate);
        server.post('/trans/:id_trans/callback', logic.callbackTrans);
        server.post('/trans', logic.postTrans);
        server.get('/queue/:id', logic.getQueue);
        server.post('/queue/:id/pop', logic.popQueue);
    });

//Add subscribers
    async.parallel([evLsnr.init(emitter), cbLsnr.init(emitter)],
        function onSubscribed() {
            'use strict';
            // logger.debug('onSubscribed()', []);
            servers.forEach(function (server) {
                server.listen(server.port);
                logger.info('PopBox listening on', server.prefix+server.port);
            });
        });
    /* servers.forEach(function (server) {
     server.listen(server.port);
     });*/
}

/*
 process.on('uncaughtException', function onUncaughtException (err) {
 'use strict';
 logger.warning('onUncaughtException', err);
 });
 */

<commit_msg>backlog parameter for high peaks of request<commit_after>//
// Copyright (c) Telefonica I+D. All rights reserved.
//
//

var config = require('./config.js');
var cluster = require('cluster');
var numCPUs = require('os').cpus().length;
var jade = require('jade');
var crypto = require('crypto');

var path = require('path');
var log = require('PDITCLogger');
var logger = log.newLogger();
logger.prefix = path.basename(module.filename, '.js');
logger.setLevel(config.logLevel);

var dirModule = path.dirname(module.filename);

var prefixer = require('./prefixer');
var sendrender = require('./sendrender');

logger.info('Node version:', process.versions.node);
logger.info('V8 version:', process.versions.v8);

if (config.cluster.numcpus >= 0 && config.cluster.numcpus < numCPUs) {
    numCPUs = config.cluster.numcpus;
    logger.info('numCPUs=' + numCPUs);
}

if (cluster.isMaster && numCPUs !== 0) {
    // Fork workers.
    for (var i = 0; i < numCPUs; i++) {
        cluster.fork();
    }

    cluster.on('death', function (worker) {
        'use strict';
        logger.warning('worker ' + worker.pid + ' died');
    });
} else {
    logger.debug('cluster worker', cluster);

    var fs = require('fs');
    var express = require('express');
    var logic = require('./agent_logic');
    var async = require('async');
    var emitter = require('./emitter_module').getEmitter();
    var evLsnr = require('./ev_lsnr');
    var cbLsnr = require('./ev_callback_lsnr');

    var servers = [];
    var app = express.createServer();
    app.prefix = "UNSEC:";
    app.port = config.agent.port;
    app._backlog = 2048;
    servers.push(app);

    logger.info("config.enableSecure", config.enableSecure);
    if (config.enableSecure === true || config.enableSecure === "true" || config.enableSecure === 1) {
        if (!config.agent.crt_path) {
            var options_dir = {
                key: path.resolve(dirModule, '../utils/server.key'),
                cert: path.resolve(dirModule, '../utils/server.crt')
            };
        } else {
            var options_dir = {
                key: path.resolve(config.agent.crt_path, 'server.key'),
                cert: path.resolve(config.agent.crt_path, 'server.crt')
            };
        }

        /*checks whether the cert files exist or not
         and starts the appSec server*/

        if (path.existsSync(options_dir.key) &&
            path.existsSync(options_dir.cert) &&
            fs.statSync(options_dir.key).isFile() &&
            fs.statSync(options_dir.cert).isFile()) {

            var options = {
                key: fs.readFileSync(options_dir.key),
                cert: fs.readFileSync(options_dir.cert)
            };
            logger.info("valid certificates");
        } else {
            logger.debug('certs not found', options_dir);
            throw new Error("No valid certificates were found in the given path");
        }

        var appSec = express.createServer(options);
        appSec.prefix = "SEC:";
        appSec.port = Number(config.agent.port) + 1;

        servers.push(appSec);
    }

    servers.forEach(function (server) {
        server.use(express.query());
        server.use(express.bodyParser());
        server.use(express.limit(config.agent.max_req_size));
        server.use(prefixer.prefixer(server.prefix));
        server.use(sendrender.sendRender());
        server.use("/", express.static(__dirname + '/public'));
        server.del('/trans/:id_trans', logic.deleteTrans);
        //app.get('/trans/:id_trans/state/:state?', logic.transState);
        server.get('/trans/:id_trans', logic.transMeta);
        server.put('/trans/:id_trans', logic.putTransMeta);
        server.post('/trans/:id_trans/payload', logic.payloadTrans);
        server.post('/trans/:id_trans/expirationDate', logic.expirationDate);
        server.post('/trans/:id_trans/callback', logic.callbackTrans);
        server.post('/trans', logic.postTrans);
        server.get('/queue/:id', logic.getQueue);
        server.post('/queue/:id/pop', logic.popQueue);
    });

//Add subscribers
    async.parallel([evLsnr.init(emitter), cbLsnr.init(emitter)],
        function onSubscribed() {
            'use strict';
            // logger.debug('onSubscribed()', []);
            servers.forEach(function (server) {
                server.listen(server.port);
                logger.info('PopBox listening on', server.prefix+server.port);
            });
        });
    /* servers.forEach(function (server) {
     server.listen(server.port);
     });*/
}

/*
 process.on('uncaughtException', function onUncaughtException (err) {
 'use strict';
 logger.warning('onUncaughtException', err);
 });
 */

<|endoftext|>


<commit_before>(function($) {
	var has_VML, create_canvas_for, add_shape_to, clear_canvas, shape_from_area,
		canvas_style, fader, hex_to_decimal, css3color, is_image_loaded, options_from_area;

	has_VML = document.namespaces;
	has_canvas = !!document.createElement('canvas').getContext;

	if(!(has_canvas || has_VML)) {
		$.fn.maphilight = function() { return this; };
		return;
	}

	if(has_canvas) {
		fader = function(element, opacity, interval) {
			if(opacity <= 1) {
				element.style.opacity = opacity;
				window.setTimeout(fader, 10, element, opacity + 0.1, 10);
			}
		};

		hex_to_decimal = function(hex) {
			return Math.max(0, Math.min(parseInt(hex, 16), 255));
		};
		css3color = function(color, opacity) {
			return 'rgba('+hex_to_decimal(color.substr(0,2))+','+hex_to_decimal(color.substr(2,2))+','+hex_to_decimal(color.substr(4,2))+','+opacity+')';
		};
		create_canvas_for = function(img) {
			var c = $('<canvas style="width:'+img.width+'px;height:'+img.height+'px;"></canvas>').get(0);
			c.getContext("2d").clearRect(0, 0, c.width, c.height);
			return c;
		};
		add_shape_to = function(canvas, shape, coords, options, name) {
			var i, context = canvas.getContext('2d');
			context.beginPath();
			if(shape == 'rect') {
				context.rect(coords[0], coords[1], coords[2] - coords[0], coords[3] - coords[1]);
			} else if(shape == 'poly') {
				context.moveTo(coords[0], coords[1]);
				for(i=2; i < coords.length; i+=2) {
					context.lineTo(coords[i], coords[i+1]);
				}
			} else if(shape == 'circ') {
				context.arc(coords[0], coords[1], coords[2], 0, Math.PI * 2, false);
			}
			context.closePath();
			if(options.fill) {
				context.fillStyle = css3color(options.fillColor, options.fillOpacity);
				context.fill();
			}
			if(options.stroke) {
				context.strokeStyle = css3color(options.strokeColor, options.strokeOpacity);
				context.lineWidth = options.strokeWidth;
				context.stroke();
			}
			if(options.fade) {
				fader(canvas, 0);
			}
		};
		clear_canvas = function(canvas) {
			canvas.getContext('2d').clearRect(0, 0, canvas.width,canvas.height);
		};
	} else {   // ie executes this code
		create_canvas_for = function(img) {
			return $('<var style="zoom:1;overflow:hidden;display:block;width:'+img.width+'px;height:'+img.height+'px;"></var>').get(0);
		};
		add_shape_to = function(canvas, shape, coords, options, name) {
			var fill, stroke, opacity, e;
			fill = '<v:fill color="#'+options.fillColor+'" opacity="'+(options.fill ? options.fillOpacity : 0)+'" />';
			stroke = (options.stroke ? 'strokeweight="'+options.strokeWidth+'" stroked="t" strokecolor="#'+options.strokeColor+'"' : 'stroked="f"');
			opacity = '<v:stroke opacity="'+options.strokeOpacity+'"/>';
			if(shape == 'rect') {
				e = $('<v:rect name="'+name+'" filled="t" '+stroke+' style="zoom:1;margin:0;padding:0;display:block;position:absolute;left:'+coords[0]+'px;top:'+coords[1]+'px;width:'+(coords[2] - coords[0])+'px;height:'+(coords[3] - coords[1])+'px;"></v:rect>');
			} else if(shape == 'poly') {
				e = $('<v:shape name="'+name+'" filled="t" '+stroke+' coordorigin="0,0" coordsize="'+canvas.width+','+canvas.height+'" path="m '+coords[0]+','+coords[1]+' l '+coords.join(',')+' x e" style="zoom:1;margin:0;padding:0;display:block;position:absolute;top:0px;left:0px;width:'+canvas.width+'px;height:'+canvas.height+'px;"></v:shape>');
			} else if(shape == 'circ') {
				e = $('<v:oval name="'+name+'" filled="t" '+stroke+' style="zoom:1;margin:0;padding:0;display:block;position:absolute;left:'+(coords[0] - coords[2])+'px;top:'+(coords[1] - coords[2])+'px;width:'+(coords[2]*2)+'px;height:'+(coords[2]*2)+'px;"></v:oval>');
			}
			e.get(0).innerHTML = fill+opacity;
			$(canvas).append(e);
		};
		clear_canvas = function(canvas) {
			$(canvas).find('[name=highlighted]').remove();
		};
	}

	shape_from_area = function(area) {
		var i, coords = area.getAttribute('coords').split(',');
		for (i=0; i < coords.length; i++) { coords[i] = parseFloat(coords[i]); }
		return [area.getAttribute('shape').toLowerCase().substr(0,4), coords];
	};

	options_from_area = function(area, options) {
		var $area = $(area);
		return $.extend({}, options, $.metadata ? $area.metadata() : false, $area.data('maphilight'));
	};

	is_image_loaded = function(img) {
		if(!img.complete) { return false; } // IE
		if(typeof img.naturalWidth != "undefined" && img.naturalWidth == 0) { return false; } // Others
		return true;
	};

	canvas_style = {
		position: 'absolute',
		left: 0,
		top: 0,
		padding: 0,
		border: 0
	};

	var ie_hax_done = false;
	$.fn.maphilight = function(opts) {
		opts = $.extend({}, $.fn.maphilight.defaults, opts);

		if($.browser.msie && !ie_hax_done) {
			document.namespaces.add("v", "urn:schemas-microsoft-com:vml");
			var style = document.createStyleSheet();
			var shapes = ['shape','rect', 'oval', 'circ', 'fill', 'stroke', 'imagedata', 'group','textbox'];
			$.each(shapes,
				function() {
					style.addRule('v\\:' + this, "behavior: url(#default#VML); antialias:true");
				}
			);
			ie_hax_done = true;
		}

		return this.each(function() {
			var img, wrap, options, map, canvas, canvas_always, mouseover, highlighted_shape, usemap;
			img = $(this);

			if(!is_image_loaded(this)) {
				// If the image isn't fully loaded, this won't work right.  Try again later.
				return window.setTimeout(function() {
					img.maphilight(opts);
				}, 200);
			}

			options = $.extend({}, opts, $.metadata ? img.metadata() : false, img.data('maphilight'));

			// jQuery bug with Opera, results in full-url#usemap being returned from jQuery's attr.
			// So use raw getAttribute instead.
			usemap = img.get(0).getAttribute('usemap');

			map = $('map[name="'+usemap.substr(1)+'"]');

			if(!(img.is('img') && usemap && map.size() > 0)) { return; }

			if(img.hasClass('maphilighted')) {
				// We're redrawing an old map, probably to pick up changes to the options.
				// Just clear out all the old stuff.
				var wrapper = img.parent();
				img.insertBefore(wrapper);
				wrapper.remove();
				$(map).unbind('.maphilight').find('area[coords]').unbind('.maphilight');
			}

			wrap = $('

').css({
				display:'block',
				background:'url('+this.src+')',
				position:'relative',
				padding:0,
				width:this.width,
				height:this.height
				});
			if(options.wrapClass) {
				if(options.wrapClass === true) {
					wrap.addClass($(this).attr('class'));
				} else {
					wrap.addClass(options.wrapClass);
				}
			}
			img.before(wrap).css('opacity', 0).css(canvas_style).remove();
			if($.browser.msie) { img.css('filter', 'Alpha(opacity=0)'); }
			wrap.append(img);

			canvas = create_canvas_for(this);
			$(canvas).css(canvas_style);
			canvas.height = this.height;
			canvas.width = this.width;

			mouseover = function(e) {
				var shape, area_options;
				area_options = options_from_area(this, options);
				if(
					!area_options.neverOn
					&&
					!area_options.alwaysOn
				) {
					shape = shape_from_area(this);
					add_shape_to(canvas, shape[0], shape[1], area_options, "highlighted");
					if(area_options.groupBy && $(this).attr(area_options.groupBy)) {
						var first = this;
						map.find('area['+area_options.groupBy+'='+$(this).attr(area_options.groupBy)+']').each(function() {
							if(this != first) {
								var subarea_options = options_from_area(this, options);
								if(!subarea_options.neverOn && !subarea_options.alwaysOn) {
									var shape = shape_from_area(this);
									add_shape_to(canvas, shape[0], shape[1], subarea_options, "highlighted");
								}
							}
						});
					}
				}
			}

			$(map).bind('alwaysOn.maphilight', function() {
				// Check for areas with alwaysOn set. These are added to a *second* canvas,
				// which will get around flickering during fading.
				if(canvas_always) {
					clear_canvas(canvas_always)
				}
				if(!has_canvas) {
					$(canvas).empty();
				}
				$(map).find('area[coords]').each(function() {
					var shape, area_options;
					area_options = options_from_area(this, options);
					if(area_options.alwaysOn) {
						if(!canvas_always && has_canvas) {
							canvas_always = create_canvas_for(img.get());
							$(canvas_always).css(canvas_style);
							canvas_always.width = img.width();
							canvas_always.height = img.height();
							img.before(canvas_always);
						}
						shape = shape_from_area(this);
						if (has_canvas) {
							add_shape_to(canvas_always, shape[0], shape[1], area_options, "");
						} else {
							add_shape_to(canvas, shape[0], shape[1], area_options, "");
						}
					}
				});
			});

			if(options.alwaysOn) {
				$(map).find('area[coords]').each(mouseover);
			} else {
				$(map).find('area[coords]')
					.trigger('alwaysOn.maphilight')
					.bind('mouseover.maphilight', mouseover)
					.bind('mouseout.maphilight', function(e) { clear_canvas(canvas); });
			}

			img.before(canvas); // if we put this after, the mouseover events wouldn't fire.

			img.addClass('maphilighted');
		});
	};
	$.fn.maphilight.defaults = {
		fill: true,
		fillColor: '000000',
		fillOpacity: 0.2,
		stroke: true,
		strokeColor: 'ff0000',
		strokeOpacity: 1,
		strokeWidth: 1,
		fade: true,
		alwaysOn: false,
		neverOn: false,
		groupBy: false,
		wrapClass: true
	};
})(jQuery);
<commit_msg>was working in Chrome, FF, Safari and IE6 -- but highlighting on mouseover, when grouping by href, always omitted one section in IE7 and IE8<commit_after>(function($) {
	var has_VML, create_canvas_for, add_shape_to, clear_canvas, shape_from_area,
		canvas_style, fader, hex_to_decimal, css3color, is_image_loaded, options_from_area;

	has_VML = document.namespaces;
	has_canvas = !!document.createElement('canvas').getContext;

	if(!(has_canvas || has_VML)) {
		$.fn.maphilight = function() { return this; };
		return;
	}

	if(has_canvas) {
		fader = function(element, opacity, interval) {
			if(opacity <= 1) {
				element.style.opacity = opacity;
				window.setTimeout(fader, 10, element, opacity + 0.1, 10);
			}
		};

		hex_to_decimal = function(hex) {
			return Math.max(0, Math.min(parseInt(hex, 16), 255));
		};
		css3color = function(color, opacity) {
			return 'rgba('+hex_to_decimal(color.substr(0,2))+','+hex_to_decimal(color.substr(2,2))+','+hex_to_decimal(color.substr(4,2))+','+opacity+')';
		};
		create_canvas_for = function(img) {
			var c = $('<canvas style="width:'+img.width+'px;height:'+img.height+'px;"></canvas>').get(0);
			c.getContext("2d").clearRect(0, 0, c.width, c.height);
			return c;
		};
		add_shape_to = function(canvas, shape, coords, options, name) {
			var i, context = canvas.getContext('2d');
			context.beginPath();
			if(shape == 'rect') {
				context.rect(coords[0], coords[1], coords[2] - coords[0], coords[3] - coords[1]);
			} else if(shape == 'poly') {
				context.moveTo(coords[0], coords[1]);
				for(i=2; i < coords.length; i+=2) {
					context.lineTo(coords[i], coords[i+1]);
				}
			} else if(shape == 'circ') {
				context.arc(coords[0], coords[1], coords[2], 0, Math.PI * 2, false);
			}
			context.closePath();
			if(options.fill) {
				context.fillStyle = css3color(options.fillColor, options.fillOpacity);
				context.fill();
			}
			if(options.stroke) {
				context.strokeStyle = css3color(options.strokeColor, options.strokeOpacity);
				context.lineWidth = options.strokeWidth;
				context.stroke();
			}
			if(options.fade) {
				fader(canvas, 0);
			}
		};
		clear_canvas = function(canvas) {
			canvas.getContext('2d').clearRect(0, 0, canvas.width,canvas.height);
		};
	} else {   // ie executes this code
		create_canvas_for = function(img) {
			return $('<var style="zoom:1;overflow:hidden;display:block;width:'+img.width+'px;height:'+img.height+'px;"></var>').get(0);
		};
		add_shape_to = function(canvas, shape, coords, options, name) {
			var fill, stroke, opacity, e;
			fill = '<v:fill color="#'+options.fillColor+'" opacity="'+(options.fill ? options.fillOpacity : 0)+'" />';
			stroke = (options.stroke ? 'strokeweight="'+options.strokeWidth+'" stroked="t" strokecolor="#'+options.strokeColor+'"' : 'stroked="f"');
			opacity = '<v:stroke opacity="'+options.strokeOpacity+'"/>';
			if(shape == 'rect') {
				e = $('<v:rect name="'+name+'" filled="t" '+stroke+' style="zoom:1;margin:0;padding:0;display:block;position:absolute;left:'+coords[0]+'px;top:'+coords[1]+'px;width:'+(coords[2] - coords[0])+'px;height:'+(coords[3] - coords[1])+'px;"></v:rect>');
			} else if(shape == 'poly') {
				e = $('<v:shape name="'+name+'" filled="t" '+stroke+' coordorigin="0,0" coordsize="'+canvas.width+','+canvas.height+'" path="m '+coords[0]+','+coords[1]+' l '+coords.join(',')+' x e" style="zoom:1;margin:0;padding:0;display:block;position:absolute;top:0px;left:0px;width:'+canvas.width+'px;height:'+canvas.height+'px;"></v:shape>');
			} else if(shape == 'circ') {
				e = $('<v:oval name="'+name+'" filled="t" '+stroke+' style="zoom:1;margin:0;padding:0;display:block;position:absolute;left:'+(coords[0] - coords[2])+'px;top:'+(coords[1] - coords[2])+'px;width:'+(coords[2]*2)+'px;height:'+(coords[2]*2)+'px;"></v:oval>');
			}
			e.get(0).innerHTML = fill+opacity;
			$(canvas).append(e);
		};
		clear_canvas = function(canvas) {
			$(canvas).find('[name=highlighted]').remove();
		};
	}

	shape_from_area = function(area) {
		var i, coords = area.getAttribute('coords').split(',');
		for (i=0; i < coords.length; i++) { coords[i] = parseFloat(coords[i]); }
		return [area.getAttribute('shape').toLowerCase().substr(0,4), coords];
	};

	options_from_area = function(area, options) {
		var $area = $(area);
		return $.extend({}, options, $.metadata ? $area.metadata() : false, $area.data('maphilight'));
	};

	is_image_loaded = function(img) {
		if(!img.complete) { return false; } // IE
		if(typeof img.naturalWidth != "undefined" && img.naturalWidth == 0) { return false; } // Others
		return true;
	};

	canvas_style = {
		position: 'absolute',
		left: 0,
		top: 0,
		padding: 0,
		border: 0
	};

	var ie_hax_done = false;
	$.fn.maphilight = function(opts) {
		opts = $.extend({}, $.fn.maphilight.defaults, opts);

		if($.browser.msie && !ie_hax_done) {
			document.namespaces.add("v", "urn:schemas-microsoft-com:vml");
			var style = document.createStyleSheet();
			var shapes = ['shape','rect', 'oval', 'circ', 'fill', 'stroke', 'imagedata', 'group','textbox'];
			$.each(shapes,
				function() {
					style.addRule('v\\:' + this, "behavior: url(#default#VML); antialias:true");
				}
			);
			ie_hax_done = true;
		}

		return this.each(function() {
			var img, wrap, options, map, canvas, canvas_always, mouseover, highlighted_shape, usemap;
			img = $(this);

			if(!is_image_loaded(this)) {
				// If the image isn't fully loaded, this won't work right.  Try again later.
				return window.setTimeout(function() {
					img.maphilight(opts);
				}, 200);
			}

			options = $.extend({}, opts, $.metadata ? img.metadata() : false, img.data('maphilight'));

			// jQuery bug with Opera, results in full-url#usemap being returned from jQuery's attr.
			// So use raw getAttribute instead.
			usemap = img.get(0).getAttribute('usemap');

			map = $('map[name="'+usemap.substr(1)+'"]');

			if(!(img.is('img') && usemap && map.size() > 0)) { return; }

			if(img.hasClass('maphilighted')) {
				// We're redrawing an old map, probably to pick up changes to the options.
				// Just clear out all the old stuff.
				var wrapper = img.parent();
				img.insertBefore(wrapper);
				wrapper.remove();
				$(map).unbind('.maphilight').find('area[coords]').unbind('.maphilight');
			}

			wrap = $('

').css({
				display:'block',
				background:'url('+this.src+')',
				position:'relative',
				padding:0,
				width:this.width,
				height:this.height
				});
			if(options.wrapClass) {
				if(options.wrapClass === true) {
					wrap.addClass($(this).attr('class'));
				} else {
					wrap.addClass(options.wrapClass);
				}
			}
			img.before(wrap).css('opacity', 0).css(canvas_style).remove();
			if($.browser.msie) { img.css('filter', 'Alpha(opacity=0)'); }
			wrap.append(img);

			canvas = create_canvas_for(this);
			$(canvas).css(canvas_style);
			canvas.height = this.height;
			canvas.width = this.width;

			mouseover = function(e) {
				var shape, area_options;
				area_options = options_from_area(this, options);
				if(
					!area_options.neverOn
					&&
					!area_options.alwaysOn
				) {
					shape = shape_from_area(this);
					add_shape_to(canvas, shape[0], shape[1], area_options, "highlighted");
					if(area_options.groupBy && $(this).attr(area_options.groupBy)) {
						var first = this;
						map.find('area['+area_options.groupBy+'='+$(this).attr(area_options.groupBy)+']').each(function() {
							if(this != first) {
								var subarea_options = options_from_area(this, options);
								if(!subarea_options.neverOn && !subarea_options.alwaysOn) {
									var shape = shape_from_area(this);
									add_shape_to(canvas, shape[0], shape[1], subarea_options, "highlighted");
								}
							}
						});
					}
					// workaround for IE7, IE8 not rendering the final rectangle in a group
					$(canvas).append('<v:rect></v:rect>');
				}
			}

			$(map).bind('alwaysOn.maphilight', function() {
				// Check for areas with alwaysOn set. These are added to a *second* canvas,
				// which will get around flickering during fading.
				if(canvas_always) {
					clear_canvas(canvas_always)
				}
				if(!has_canvas) {
					$(canvas).empty();
				}
				$(map).find('area[coords]').each(function() {
					var shape, area_options;
					area_options = options_from_area(this, options);
					if(area_options.alwaysOn) {
						if(!canvas_always && has_canvas) {
							canvas_always = create_canvas_for(img.get());
							$(canvas_always).css(canvas_style);
							canvas_always.width = img.width();
							canvas_always.height = img.height();
							img.before(canvas_always);
						}
						shape = shape_from_area(this);
						if (has_canvas) {
							add_shape_to(canvas_always, shape[0], shape[1], area_options, "");
						} else {
							add_shape_to(canvas, shape[0], shape[1], area_options, "");
						}
					}
				});
			});

			if(options.alwaysOn) {
				$(map).find('area[coords]').each(mouseover);
			} else {
				$(map).find('area[coords]')
					.trigger('alwaysOn.maphilight')
					.bind('mouseover.maphilight', mouseover)
					.bind('mouseout.maphilight', function(e) { clear_canvas(canvas); });
			}

			img.before(canvas); // if we put this after, the mouseover events wouldn't fire.

			img.addClass('maphilighted');
		});
	};
	$.fn.maphilight.defaults = {
		fill: true,
		fillColor: '000000',
		fillOpacity: 0.2,
		stroke: true,
		strokeColor: 'ff0000',
		strokeOpacity: 1,
		strokeWidth: 1,
		fade: true,
		alwaysOn: false,
		neverOn: false,
		groupBy: false,
		wrapClass: true
	};
})(jQuery);
<|endoftext|>


<commit_before>var UNDEFINED = 'undefined';
var exec = require('child_process').exec;

var sof = {
    0xc0: true,
    0xc1: true,
    0xc2: true,
    0xc3: true,
    0xc5: true,
    0xc6: true,
    0xc7: true,
    0xc9: true,
    0xca: true,
    0xcb: true,
    0xcd: true,
    0xce: true,
    0xcf: true
};

function u16(buf, o) {
    return buf[o] << 8 | buf[o + 1];
}

function u32(buf, o) {
    return buf[o] << 24 | buf[o + 1] << 16 | buf[o + 2] << 8 | buf[o + 3];
}

if (typeof(setImmediate) === UNDEFINED) {
    global.setImmediate = function(cb) {
        process.nextTick(cb);
    };
}

exports.extension = function(name) {
    var index = name.lastIndexOf('.');

    if (index !== -1)
        name = name.substring(index + 1);

    return name;
};

exports.contentType = function(ext) {

    var extension = {
        'ai': 'application/postscript',
        'aif': 'audio/x-aiff',
        'aifc': 'audio/x-aiff',
        'aiff': 'audio/x-aiff',
        'asc': 'text/plain',
        'atom': 'application/atom+xml',
        'au': 'audio/basic',
        'avi': 'video/x-msvideo',
        'bcpio': 'application/x-bcpio',
        'bin': 'application/octet-stream',
        'bmp': 'image/bmp',
        'cdf': 'application/x-netcdf',
        'cgm': 'image/cgm',
        'class': 'application/octet-stream',
        'cpio': 'application/x-cpio',
        'cpt': 'application/mac-compactpro',
        'csh': 'application/x-csh',
        'css': 'text/css',
        'dcr': 'application/x-director',
        'dif': 'video/x-dv',
        'dir': 'application/x-director',
        'djv': 'image/vnd.djvu',
        'djvu': 'image/vnd.djvu',
        'dll': 'application/octet-stream',
        'dmg': 'application/octet-stream',
        'dms': 'application/octet-stream',
        'doc': 'application/msword',
        'dtd': 'application/xml-dtd',
        'dv': 'video/x-dv',
        'dvi': 'application/x-dvi',
        'dxr': 'application/x-director',
        'eps': 'application/postscript',
        'etx': 'text/x-setext',
        'exe': 'application/octet-stream',
        'ez': 'application/andrew-inset',
        'gif': 'image/gif',
        'gram': 'application/srgs',
        'grxml': 'application/srgs+xml',
        'gtar': 'application/x-gtar',
        'hdf': 'application/x-hdf',
        'hqx': 'application/mac-binhex40',
        'htm': 'text/html',
        'html': 'text/html',
        'ice': 'x-conference/x-cooltalk',
        'ico': 'image/x-icon',
        'ics': 'text/calendar',
        'ief': 'image/ief',
        'ifb': 'text/calendar',
        'iges': 'model/iges',
        'igs': 'model/iges',
        'jnlp': 'application/x-java-jnlp-file',
        'jp2': 'image/jp2',
        'jpe': 'image/jpeg',
        'jpeg': 'image/jpeg',
        'jpg': 'image/jpeg',
        'js': 'application/x-javascript',
        'kar': 'audio/midi',
        'latex': 'application/x-latex',
        'lha': 'application/octet-stream',
        'lzh': 'application/octet-stream',
        'm3u': 'audio/x-mpegurl',
        'm4a': 'audio/mp4a-latm',
        'm4b': 'audio/mp4a-latm',
        'm4p': 'audio/mp4a-latm',
        'm4u': 'video/vnd.mpegurl',
        'm4v': 'video/x-m4v',
        'mac': 'image/x-macpaint',
        'man': 'application/x-troff-man',
        'mathml': 'application/mathml+xml',
        'me': 'application/x-troff-me',
        'mesh': 'model/mesh',
        'mid': 'audio/midi',
        'midi': 'audio/midi',
        'mif': 'application/vnd.mif',
        'mov': 'video/quicktime',
        'movie': 'video/x-sgi-movie',
        'mp2': 'audio/mpeg',
        'mp3': 'audio/mpeg',
        'mp4': 'video/mp4',
        'mpe': 'video/mpeg',
        'mpeg': 'video/mpeg',
        'mpg': 'video/mpeg',
        'mpga': 'audio/mpeg',
        'ms': 'application/x-troff-ms',
        'msh': 'model/mesh',
        'mv4': 'video/mv4',
        'mxu': 'video/vnd.mpegurl',
        'nc': 'application/x-netcdf',
        'oda': 'application/oda',
        'ogg': 'application/ogg',
        'pbm': 'image/x-portable-bitmap',
        'pct': 'image/pict',
        'pdb': 'chemical/x-pdb',
        'pdf': 'application/pdf',
        'pgm': 'image/x-portable-graymap',
        'pgn': 'application/x-chess-pgn',
        'pic': 'image/pict',
        'pict': 'image/pict',
        'png': 'image/png',
        'pnm': 'image/x-portable-anymap',
        'pnt': 'image/x-macpaint',
        'pntg': 'image/x-macpaint',
        'ppm': 'image/x-portable-pixmap',
        'ppt': 'application/vnd.ms-powerpoint',
        'ps': 'application/postscript',
        'qt': 'video/quicktime',
        'qti': 'image/x-quicktime',
        'qtif': 'image/x-quicktime',
        'ra': 'audio/x-pn-realaudio',
        'ram': 'audio/x-pn-realaudio',
        'ras': 'image/x-cmu-raster',
        'rdf': 'application/rdf+xml',
        'rgb': 'image/x-rgb',
        'rm': 'application/vnd.rn-realmedia',
        'roff': 'application/x-troff',
        'rtf': 'text/rtf',
        'rtx': 'text/richtext',
        'sgm': 'text/sgml',
        'sgml': 'text/sgml',
        'sh': 'application/x-sh',
        'shar': 'application/x-shar',
        'silo': 'model/mesh',
        'sit': 'application/x-stuffit',
        'skd': 'application/x-koan',
        'skm': 'application/x-koan',
        'skp': 'application/x-koan',
        'skt': 'application/x-koan',
        'smi': 'application/smil',
        'smil': 'application/smil',
        'snd': 'audio/basic',
        'so': 'application/octet-stream',
        'spl': 'application/x-futuresplash',
        'src': 'application/x-wais-source',
        'sv4cpio': 'application/x-sv4cpio',
        'sv4crc': 'application/x-sv4crc',
        'svg': 'image/svg+xml',
        'swf': 'application/x-shockwave-flash',
        't': 'application/x-troff',
        'tar': 'application/x-tar',
        'tcl': 'application/x-tcl',
        'tex': 'application/x-tex',
        'texi': 'application/x-texinfo',
        'texinfo': 'application/x-texinfo',
        'tif': 'image/tiff',
        'tiff': 'image/tiff',
        'tr': 'application/x-troff',
        'tsv': 'text/tab-separated-values',
        'txt': 'text/plain',
        'ustar': 'application/x-ustar',
        'vcd': 'application/x-cdlink',
        'vrml': 'model/vrml',
        'vxml': 'application/voicexml+xml',
        'wav': 'audio/x-wav',
        'wbmp': 'image/vnd.wap.wbmp',
        'wbmxl': 'application/vnd.wap.wbxml',
        'wml': 'text/vnd.wap.wml',
        'wmlc': 'application/vnd.wap.wmlc',
        'woff': 'font/woff',
        'wmls': 'text/vnd.wap.wmlscript',
        'wmlsc': 'application/vnd.wap.wmlscriptc',
        'wrl': 'model/vrml',
        'xbm': 'image/x-xbitmap',
        'xht': 'application/xhtml+xml',
        'xhtml': 'application/xhtml+xml',
        'xls': 'application/vnd.ms-excel',
        'xml': 'application/xml',
        'xpm': 'image/x-xpixmap',
        'xsl': 'application/xml',
        'xslt': 'application/xslt+xml',
        'xul': 'application/vnd.mozilla.xul+xml',
        'xwd': 'image/x-xwindowdump',
        'xyz': 'chemical/x-xyz',
        'zip': 'application/zip'
    };

    return extension[ext.toLowerCase()] || 'application/octet-stream';
};

if (!String.prototype.padLeft) {
    String.prototype.padLeft = function(max, c) {
        var self = this.toString();
        return new Array(Math.max(0, max - self.length + 1)).join(c || ' ') + self;
    };
}

if (!String.prototype.padRight) {
    String.prototype.padRight = function(max, c) {
        var self = this.toString();
        return self + new Array(Math.max(0, max - self.length + 1)).join(c || ' ');
    };
}

if (!String.prototype.trim) {
    String.prototype.trim = function() {
        return this.replace(/^[\s]+|[\s]+$/g, '');
    };
}

exports.dimensionGIF = function(buffer) {
    return {
        width: buffer[6],
        height: buffer[8]
    };
};

// MIT
// Written by TJ Holowaychuk
// visionmedia
exports.dimensionJPG = function(buffer) {

    var len = buffer.length;
    var o = 0;

    var jpeg = 0xff == buffer[0] && 0xd8 == buffer[1];

    if (!jpeg)
        return null;

    o += 2;

    while (o < len) {
        while (0xff != buffer[o]) o++;
        while (0xff == buffer[o]) o++;

        if (!sof[buffer[o]]) {
            o += u16(buffer, ++o);
            continue;
        }

        var w = u16(buffer, o + 6);
        var h = u16(buffer, o + 4);

        return {
            width: w,
            height: h
        };
    }

    return null;
};

// MIT
// Written by TJ Holowaychuk
// visionmedia
exports.dimensionPNG = function(buffer) {
    return {
        width: u32(buffer, 16),
        height: u32(buffer, 16 + 4)
    };
};

exports.parseIndex = function(id) {

    var length = id.length;
    var beg = 0;

    id = id.toString().replace(/\-/g, '');

    for (var i = 0; i < length; i++) {
        if (id[i] !== '0') {
            beg = i;
            break;
        }
    }

    return parseInt(id.substring(beg), 10);
};<commit_msg>Clean code.<commit_after>var UNDEFINED = 'undefined';
var exec = require('child_process').exec;

var SOF = {
	0xc0: true,
	0xc1: true,
	0xc2: true,
	0xc3: true,
	0xc5: true,
	0xc6: true,
	0xc7: true,
	0xc9: true,
	0xca: true,
	0xcb: true,
	0xcd: true,
	0xce: true,
	0xcf: true
};

var EXTENSION = {
	'ai': 'application/postscript',
	'aif': 'audio/x-aiff',
	'aifc': 'audio/x-aiff',
	'aiff': 'audio/x-aiff',
	'asc': 'text/plain',
	'atom': 'application/atom+xml',
	'au': 'audio/basic',
	'avi': 'video/x-msvideo',
	'bcpio': 'application/x-bcpio',
	'bin': 'application/octet-stream',
	'bmp': 'image/bmp',
	'cdf': 'application/x-netcdf',
	'cgm': 'image/cgm',
	'class': 'application/octet-stream',
	'cpio': 'application/x-cpio',
	'cpt': 'application/mac-compactpro',
	'csh': 'application/x-csh',
	'css': 'text/css',
	'dcr': 'application/x-director',
	'dif': 'video/x-dv',
	'dir': 'application/x-director',
	'djv': 'image/vnd.djvu',
	'djvu': 'image/vnd.djvu',
	'dll': 'application/octet-stream',
	'dmg': 'application/octet-stream',
	'dms': 'application/octet-stream',
	'doc': 'application/msword',
	'dtd': 'application/xml-dtd',
	'dv': 'video/x-dv',
	'dvi': 'application/x-dvi',
	'dxr': 'application/x-director',
	'eps': 'application/postscript',
	'etx': 'text/x-setext',
	'exe': 'application/octet-stream',
	'ez': 'application/andrew-inset',
	'gif': 'image/gif',
	'gram': 'application/srgs',
	'grxml': 'application/srgs+xml',
	'gtar': 'application/x-gtar',
	'hdf': 'application/x-hdf',
	'hqx': 'application/mac-binhex40',
	'htm': 'text/html',
	'html': 'text/html',
	'ice': 'x-conference/x-cooltalk',
	'ico': 'image/x-icon',
	'ics': 'text/calendar',
	'ief': 'image/ief',
	'ifb': 'text/calendar',
	'iges': 'model/iges',
	'igs': 'model/iges',
	'jnlp': 'application/x-java-jnlp-file',
	'jp2': 'image/jp2',
	'jpe': 'image/jpeg',
	'jpeg': 'image/jpeg',
	'jpg': 'image/jpeg',
	'js': 'application/x-javascript',
	'kar': 'audio/midi',
	'latex': 'application/x-latex',
	'lha': 'application/octet-stream',
	'lzh': 'application/octet-stream',
	'm3u': 'audio/x-mpegurl',
	'm4a': 'audio/mp4a-latm',
	'm4b': 'audio/mp4a-latm',
	'm4p': 'audio/mp4a-latm',
	'm4u': 'video/vnd.mpegurl',
	'm4v': 'video/x-m4v',
	'mac': 'image/x-macpaint',
	'man': 'application/x-troff-man',
	'mathml': 'application/mathml+xml',
	'me': 'application/x-troff-me',
	'mesh': 'model/mesh',
	'mid': 'audio/midi',
	'midi': 'audio/midi',
	'mif': 'application/vnd.mif',
	'mov': 'video/quicktime',
	'movie': 'video/x-sgi-movie',
	'mp2': 'audio/mpeg',
	'mp3': 'audio/mpeg',
	'mp4': 'video/mp4',
	'mpe': 'video/mpeg',
	'mpeg': 'video/mpeg',
	'mpg': 'video/mpeg',
	'mpga': 'audio/mpeg',
	'ms': 'application/x-troff-ms',
	'msh': 'model/mesh',
	'mv4': 'video/mv4',
	'mxu': 'video/vnd.mpegurl',
	'nc': 'application/x-netcdf',
	'oda': 'application/oda',
	'ogg': 'application/ogg',
	'pbm': 'image/x-portable-bitmap',
	'pct': 'image/pict',
	'pdb': 'chemical/x-pdb',
	'pdf': 'application/pdf',
	'pgm': 'image/x-portable-graymap',
	'pgn': 'application/x-chess-pgn',
	'pic': 'image/pict',
	'pict': 'image/pict',
	'png': 'image/png',
	'pnm': 'image/x-portable-anymap',
	'pnt': 'image/x-macpaint',
	'pntg': 'image/x-macpaint',
	'ppm': 'image/x-portable-pixmap',
	'ppt': 'application/vnd.ms-powerpoint',
	'ps': 'application/postscript',
	'qt': 'video/quicktime',
	'qti': 'image/x-quicktime',
	'qtif': 'image/x-quicktime',
	'ra': 'audio/x-pn-realaudio',
	'ram': 'audio/x-pn-realaudio',
	'ras': 'image/x-cmu-raster',
	'rdf': 'application/rdf+xml',
	'rgb': 'image/x-rgb',
	'rm': 'application/vnd.rn-realmedia',
	'roff': 'application/x-troff',
	'rtf': 'text/rtf',
	'rtx': 'text/richtext',
	'sgm': 'text/sgml',
	'sgml': 'text/sgml',
	'sh': 'application/x-sh',
	'shar': 'application/x-shar',
	'silo': 'model/mesh',
	'sit': 'application/x-stuffit',
	'skd': 'application/x-koan',
	'skm': 'application/x-koan',
	'skp': 'application/x-koan',
	'skt': 'application/x-koan',
	'smi': 'application/smil',
	'smil': 'application/smil',
	'snd': 'audio/basic',
	'so': 'application/octet-stream',
	'spl': 'application/x-futuresplash',
	'src': 'application/x-wais-source',
	'sv4cpio': 'application/x-sv4cpio',
	'sv4crc': 'application/x-sv4crc',
	'svg': 'image/svg+xml',
	'swf': 'application/x-shockwave-flash',
	't': 'application/x-troff',
	'tar': 'application/x-tar',
	'tcl': 'application/x-tcl',
	'tex': 'application/x-tex',
	'texi': 'application/x-texinfo',
	'texinfo': 'application/x-texinfo',
	'tif': 'image/tiff',
	'tiff': 'image/tiff',
	'tr': 'application/x-troff',
	'tsv': 'text/tab-separated-values',
	'txt': 'text/plain',
	'ustar': 'application/x-ustar',
	'vcd': 'application/x-cdlink',
	'vrml': 'model/vrml',
	'vxml': 'application/voicexml+xml',
	'wav': 'audio/x-wav',
	'wbmp': 'image/vnd.wap.wbmp',
	'wbmxl': 'application/vnd.wap.wbxml',
	'wml': 'text/vnd.wap.wml',
	'wmlc': 'application/vnd.wap.wmlc',
	'woff': 'font/woff',
	'wmls': 'text/vnd.wap.wmlscript',
	'wmlsc': 'application/vnd.wap.wmlscriptc',
	'wrl': 'model/vrml',
	'xbm': 'image/x-xbitmap',
	'xht': 'application/xhtml+xml',
	'xhtml': 'application/xhtml+xml',
	'xls': 'application/vnd.ms-excel',
	'xml': 'application/xml',
	'xpm': 'image/x-xpixmap',
	'xsl': 'application/xml',
	'xslt': 'application/xslt+xml',
	'xul': 'application/vnd.mozilla.xul+xml',
	'xwd': 'image/x-xwindowdump',
	'xyz': 'chemical/x-xyz',
	'zip': 'application/zip'
};

function u16(buf, o) {
	return buf[o] << 8 | buf[o + 1];
}

function u32(buf, o) {
	return buf[o] << 24 | buf[o + 1] << 16 | buf[o + 2] << 8 | buf[o + 3];
}

if (typeof(setImmediate) === UNDEFINED) {
	global.setImmediate = function(cb) {
		process.nextTick(cb);
	};
}

exports.extension = function(name) {
	var index = name.lastIndexOf('.');
	if (index !== -1)
		name = name.substring(index + 1);
	return name;
};

exports.contentType = function(ext) {
	return EXTENSION[ext.toLowerCase()] || 'application/octet-stream';
};

if (!String.prototype.padLeft) {
	String.prototype.padLeft = function(max, c) {
		var self = this.toString();
		return new Array(Math.max(0, max - self.length + 1)).join(c || ' ') + self;
	};
}

if (!String.prototype.padRight) {
	String.prototype.padRight = function(max, c) {
		var self = this.toString();
		return self + new Array(Math.max(0, max - self.length + 1)).join(c || ' ');
	};
}

if (!String.prototype.trim) {
	String.prototype.trim = function() {
		return this.replace(/^[\s]+|[\s]+$/g, '');
	};
}

exports.dimensionGIF = function(buffer) {
	return {
		width: buffer[6],
		height: buffer[8]
	};
};

// MIT
// Written by TJ Holowaychuk
// visionmedia
exports.dimensionJPG = function(buffer) {

	var len = buffer.length;
	var o = 0;

	var jpeg = 0xff == buffer[0] && 0xd8 == buffer[1];

	if (!jpeg)
		return null;

	o += 2;

	while (o < len) {
		while (0xff != buffer[o]) o++;
		while (0xff == buffer[o]) o++;

		if (!SOF[buffer[o]]) {
			o += u16(buffer, ++o);
			continue;
		}

		var w = u16(buffer, o + 6);
		var h = u16(buffer, o + 4);

		return {
			width: w,
			height: h
		};
	}

	return null;
};

// MIT
// Written by TJ Holowaychuk
// visionmedia
exports.dimensionPNG = function(buffer) {
	return {
		width: u32(buffer, 16),
		height: u32(buffer, 16 + 4)
	};
};

exports.parseIndex = function(id) {

	var length = id.length;
	var beg = 0;

	id = id.toString().replace(/\-/g, '');

	for (var i = 0; i < length; i++) {
		if (id[i] !== '0') {
			beg = i;
			break;
		}
	}

	return parseInt(id.substring(beg), 10);
};<|endoftext|>


<commit_before>'use strict'

import React, { PropTypes } from 'react'
import ReactDOM from 'react-dom'
import uniqueId from 'lodash/fp/uniqueId'

const Audio = React.createClass({
  play () {
    ReactDOM.findDOMNode(this).play()
  },

  pause () {
    ReactDOM.findDOMNode(this).pause()
  },

  getDefaultProps () {
    return {
      autoPlay: false,
      controls: false,
      loop: false,
      preload: 'metadata',
      uniqueId: uniqueId('audio/')
    }
  },

  componentWillMount () {
    this.props.onMount()
  },

  componentDidMount () {
    const audio = ReactDOM.findDOMNode(this)
    const { onEnded, onPause, onPlaying } = this.props
    audio.addEventListener('ended', onEnded)
    audio.addEventListener('pause', onPause)
    audio.addEventListener('playing', onPlaying)
  },

  componentWillUnmount () {
    const audio = ReactDOM.findDOMNode(this)
    const { onEnded, onPause, onPlaying, onUnmount } = this.props
    audio.removeEventListener('ended', onEnded)
    audio.removeEventListener('pause', onPause)
    audio.removeEventListener('playing', onPlaying)
    onUnmount()
  },

  componentDidUpdate (prevProps) {
    if (this.props.command !== 'none' && this.props.command !== prevProps.command) this[this.props.command]()
  },

  render () {
    const { autoPlay, controls, loop, preload, src } = this.props

    return (
      <audio
        autoPlay={autoPlay}
        controls={controls}
        loop={loop}
        preload={preload}
        src={src}
      />
    )
  },

  propTypes: {
    autoPlay: PropTypes.bool,
    command: PropTypes.oneOf(['play', 'pause', 'none']).isRequired(),
    controls: PropTypes.bool,
    loop: PropTypes.bool,
    onEnded: PropTypes.func.isRequired,
    onMount: PropTypes.func.isRequired,
    onPause: PropTypes.func.isRequired,
    onPlaying: PropTypes.func.isRequired,
    onUnmount: PropTypes.func.isRequired,
    preload: PropTypes.oneOf(['none', 'metadata', 'auto']),
    src: PropTypes.string.isRequired,
    uniqueId: PropTypes.string
  }
})

export default Audio
<commit_msg>moar bug fix<commit_after>'use strict'

import React, { PropTypes } from 'react'
import ReactDOM from 'react-dom'
import uniqueId from 'lodash/fp/uniqueId'

const Audio = React.createClass({
  play () {
    ReactDOM.findDOMNode(this).play()
  },

  pause () {
    ReactDOM.findDOMNode(this).pause()
  },

  getDefaultProps () {
    return {
      autoPlay: false,
      controls: false,
      loop: false,
      preload: 'metadata',
      uniqueId: uniqueId('audio/')
    }
  },

  componentWillMount () {
    this.props.onMount()
  },

  componentDidMount () {
    const audio = ReactDOM.findDOMNode(this)
    const { onEnded, onPause, onPlaying } = this.props
    audio.addEventListener('ended', onEnded)
    audio.addEventListener('pause', onPause)
    audio.addEventListener('playing', onPlaying)
  },

  componentWillUnmount () {
    const audio = ReactDOM.findDOMNode(this)
    const { onEnded, onPause, onPlaying, onUnmount } = this.props
    audio.removeEventListener('ended', onEnded)
    audio.removeEventListener('pause', onPause)
    audio.removeEventListener('playing', onPlaying)
    onUnmount()
  },

  componentDidUpdate (prevProps) {
    if (this.props.command !== 'none' && this.props.command !== prevProps.command) this[this.props.command]()
  },

  render () {
    const { autoPlay, controls, loop, preload, src } = this.props

    return (
      <audio
        autoPlay={autoPlay}
        controls={controls}
        loop={loop}
        preload={preload}
        src={src}
      />
    )
  },

  propTypes: {
    autoPlay: PropTypes.bool,
    command: PropTypes.oneOf(['play', 'pause', 'none']).isRequired,
    controls: PropTypes.bool,
    loop: PropTypes.bool,
    onEnded: PropTypes.func.isRequired,
    onMount: PropTypes.func.isRequired,
    onPause: PropTypes.func.isRequired,
    onPlaying: PropTypes.func.isRequired,
    onUnmount: PropTypes.func.isRequired,
    preload: PropTypes.oneOf(['none', 'metadata', 'auto']),
    src: PropTypes.string.isRequired,
    uniqueId: PropTypes.string
  }
})

export default Audio
<|endoftext|>


<commit_before>var mongoose = require('mongoose');

exports.split_db_url = function(db_url)
{
    var parts = db_url.split('/');
    var conf = {
        db:parts[3],
        collection: 'session',
        clear_interval: 0
    };

    if(parts[2] != 'localhost')
    {
        var middle_part_parts = parts[2].split(':');
        conf['username'] = middle_part_parts[0];
        conf['password'] = middle_part_parts[1].split('@')[0];
        conf['host'] = middle_part_parts[1].split('@')[1];
        conf['port'] = Number(middle_part_parts[2]);
    }
    else
    {
        conf['host'] = 'localhost';
        conf['port'] = 27017;
    }
    return conf;
};

exports.create_cached_model = function()
{
    var schema = arguments[1];
    var model = mongoose.model.apply(mongoose,arguments);
    return exports.cached_model(model,schema);
}

exports.cached_model = function(model,schema)
{
    model.cached = {};

    var invalidate = function(next){
        model.cached = {};
        if(next)
            next();
    };

    schema.pre('save',invalidate);
    schema.pre('remove',invalidate);

    model.findCached = function(){
        var query = arguments[0];
        var str = query + '';
        var callback = arguments[arguments.length-1];
        if(model.cached[str])
            callback(model.cached[str]);
        else
        {
            arguments[arguments.length-1] = function(err,docs)
            {
                if(!err)
                    model.cached[str] = docs;
                callback(err,docs);
            };
            model.find.apply(model,arguments);
        }
    };

    model.findOneCached = function(){
        var query = arguments[0];
        var str = query + '';
        var callback = arguments[arguments.length-1];
        if(model.cached[str])
            callback(model.cached[str]);
        else
        {
            arguments[arguments.length-1] = function(err,docs)
            {
                if(!err)
                    model.cached[str] = docs;
                callback(err,docs);
            };
            model.find.apply(model,arguments);
        }
    };
    return model;
};

exports.config_model = function(name, schema_fields){
    var ext = exports.extend_model(name,{},schema_fields,'site_configs');
    return ext.model;//exports.cached_model(ext.model,ext.schema);
};

exports.extend_model = function(name, base_schema, schema, collection,schemaFunc) {
    for (var key in base_schema)
        if (!schema[key]) schema[key] = base_schema[key];
    schema._type = {type:String, 'default':name,editable:false};
    var schemaObj = new mongoose.Schema(schema);
    if(schemaFunc)
        schemaFunc(schemaObj);
    var model = mongoose.model(name, schemaObj, collection);
    var old_find = model.find;
    model.find = function () {
        var params = arguments.length ? arguments[0] : {};
        params['_type'] = name;
        if (arguments.length)
            arguments[0] = params;
        else
            arguments = [params];
        return old_find.apply(this, arguments);
    };
    var old_findOne = model.findOne;
    model.findOne = function () {
        var params = arguments.length ? arguments[0] : {};
        params['_type'] = name;
        if (arguments.length)
            arguments[0] = params;
        else
            arguments = [params];
        return old_findOne.apply(this, arguments);
    };
    return {model:model, schema:schemaObj};
};

/*
 * Date Format 1.2.3
 * (c) 2007-2009 Steven Levithan <stevenlevithan.com>
 * MIT license
 *
 * Includes enhancements by Scott Trenda <scott.trenda.net>
 * and Kris Kowal <cixar.com/~kris.kowal/>
 *
 * Accepts a date, a mask, or a date and a mask.
 * Returns a formatted version of the given date.
 * The date defaults to the current date/time.
 * The mask defaults to dateFormat.masks.default.
 */

var dateFormat = exports.dateFormat = function () {
    var	token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
        timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
        timezoneClip = /[^-+\dA-Z]/g,
        pad = function (val, len) {
            val = String(val);
            len = len || 2;
            while (val.length < len) val = "0" + val;
            return val;
        };

    // Regexes and supporting functions are cached through closure
    return function (date, mask, utc) {
        var dF = dateFormat;

        // You can't provide utc if you skip other args (use the "UTC:" mask prefix)
        if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
            mask = date;
            date = undefined;
        }

        // Passing date through Date applies Date.parse, if necessary
        date = date ? new Date(date) : new Date;
        if (isNaN(date)) throw SyntaxError("invalid date");

        mask = String(dF.masks[mask] || mask || dF.masks["default"]);

        // Allow setting the utc argument via the mask
        if (mask.slice(0, 4) == "UTC:") {
            mask = mask.slice(4);
            utc = true;
        }

        var	_ = utc ? "getUTC" : "get",
            d = date[_ + "Date"](),
            D = date[_ + "Day"](),
            m = date[_ + "Month"](),
            y = date[_ + "FullYear"](),
            H = date[_ + "Hours"](),
            M = date[_ + "Minutes"](),
            s = date[_ + "Seconds"](),
            L = date[_ + "Milliseconds"](),
            o = utc ? 0 : date.getTimezoneOffset(),
            flags = {
                d:    d,
                dd:   pad(d),
                ddd:  dF.i18n.dayNames[D],
                dddd: dF.i18n.dayNames[D + 7],
                m:    m + 1,
                mm:   pad(m + 1),
                mmm:  dF.i18n.monthNames[m],
                mmmm: dF.i18n.monthNames[m + 12],
                yy:   String(y).slice(2),
                yyyy: y,
                h:    H % 12 || 12,
                hh:   pad(H % 12 || 12),
                H:    H,
                HH:   pad(H),
                M:    M,
                MM:   pad(M),
                s:    s,
                ss:   pad(s),
                l:    pad(L, 3),
                L:    pad(L > 99 ? Math.round(L / 10) : L),
                t:    H < 12 ? "a"  : "p",
                tt:   H < 12 ? "am" : "pm",
                T:    H < 12 ? "A"  : "P",
                TT:   H < 12 ? "AM" : "PM",
                Z:    utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
                o:    (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
                S:    ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
            };

        return mask.replace(token, function ($0) {
            return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
        });
    };
}();

// Some common format strings
dateFormat.masks = {
    "default":      "ddd mmm dd yyyy HH:MM:ss",
    shortDate:      "m/d/yy",
    mediumDate:     "mmm d, yyyy",
    longDate:       "mmmm d, yyyy",
    fullDate:       "dddd, mmmm d, yyyy",
    shortTime:      "h:MM TT",
    mediumTime:     "h:MM:ss TT",
    longTime:       "h:MM:ss TT Z",
    isoDate:        "yyyy-mm-dd",
    isoTime:        "HH:MM:ss",
    isoDateTime:    "yyyy-mm-dd'T'HH:MM:ss",
    isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};

// Internationalization strings
dateFormat.i18n = {
    dayNames: [
        "ראשון",
        "שני",
        "שלישי",
        "רביעי",
        "חמישי",
        "שישי",
        "שבת",
        "ראשון",
        "שני",
        "שלישי",
        "רביעי",
        "חמישי",
        "שישי",
        "שבת"
    ],
    monthNames: [
        "ינואר",
        "פברואר",
        "מרץ",
        "אפריל",
        "מאי",
        "יוני",
        "יולי",
        "אוגוסט",
        "סםטמבר",
        "אוקטובר",
        "נובמבר",
        "דצמבר",
        "ינואר",
        "פברואר",
        "מרץ",
        "אפריל",
        "מאי",
        "יוני",
        "יולי",
        "אוגוסט",
        "סםטמבר",
        "אוקטובר",
        "נובמבר",
        "דצמבר"
    ]
};

// For convenience...
Date.prototype.format = function (mask, utc) {
    return dateFormat(this, mask, utc);
};<commit_msg>just push<commit_after> var mongoose = require('mongoose');

exports.split_db_url = function(db_url)
{
    var parts = db_url.split('/');
    var conf = {
        db:parts[3],
        collection: 'session',
        clear_interval: 0
    };

    if(parts[2] != 'localhost')
    {
        var middle_part_parts = parts[2].split(':');
        conf['username'] = middle_part_parts[0];
        conf['password'] = middle_part_parts[1].split('@')[0];
        conf['host'] = middle_part_parts[1].split('@')[1];
        conf['port'] = Number(middle_part_parts[2]);
    }
    else
    {
        conf['host'] = 'localhost';
        conf['port'] = 27017;
    }
    return conf;
};

exports.create_cached_model = function()
{
    var schema = arguments[1];
    var model = mongoose.model.apply(mongoose,arguments);
    return exports.cached_model(model,schema);
}

exports.cached_model = function(model,schema)
{
    model.cached = {};

    var invalidate = function(next){
        model.cached = {};
        if(next)
            next();
    };

    schema.pre('save',invalidate);
    schema.pre('remove',invalidate);

    model.findCached = function(){
        var query = arguments[0];
        var str = query + '';
        var callback = arguments[arguments.length-1];
        if(model.cached[str])
            callback(model.cached[str]);
        else
        {
            arguments[arguments.length-1] = function(err,docs)
            {
                if(!err)
                    model.cached[str] = docs;
                callback(err,docs);
            };
            model.find.apply(model,arguments);
        }
    };

    model.findOneCached = function(){
        var query = arguments[0];
        var str = query + '';
        var callback = arguments[arguments.length-1];
        if(model.cached[str])
            callback(model.cached[str]);
        else
        {
            arguments[arguments.length-1] = function(err,docs)
            {
                if(!err)
                    model.cached[str] = docs;
                callback(err,docs);
            };
            model.find.apply(model,arguments);
        }
    };
    return model;
};

exports.config_model = function(name, schema_fields){
    var ext = exports.extend_model(name,{},schema_fields,'site_configs');
    return ext.model;//exports.cached_model(ext.model,ext.schema);
};

exports.extend_model = function(name, base_schema, schema, collection,schemaFunc) {
    for (var key in base_schema)
        if (!schema[key]) schema[key] = base_schema[key];
    schema._type = {type:String, 'default':name,editable:false};
    var schemaObj = new mongoose.Schema(schema);
    if(schemaFunc)
        schemaFunc(schemaObj);
    var model = mongoose.model(name, schemaObj, collection);
    var old_find = model.find;
    model.find = function () {
        var params = arguments.length ? arguments[0] : {};
        params['_type'] = name;
        if (arguments.length)
            arguments[0] = params;
        else
            arguments = [params];
        return old_find.apply(this, arguments);
    };
    var old_findOne = model.findOne;
    model.findOne = function () {
        var params = arguments.length ? arguments[0] : {};
        params['_type'] = name;
        if (arguments.length)
            arguments[0] = params;
        else
            arguments = [params];
        return old_findOne.apply(this, arguments);
    };
    return {model:model, schema:schemaObj};
};

/*
 * Date Format 1.2.3
 * (c) 2007-2009 Steven Levithan <stevenlevithan.com>
 * MIT license
 *
 * Includes enhancements by Scott Trenda <scott.trenda.net>
 * and Kris Kowal <cixar.com/~kris.kowal/>
 *
 * Accepts a date, a mask, or a date and a mask.
 * Returns a formatted version of the given date.
 * The date defaults to the current date/time.
 * The mask defaults to dateFormat.masks.default.
 */

var dateFormat = exports.dateFormat = function () {
    var	token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
        timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
        timezoneClip = /[^-+\dA-Z]/g,
        pad = function (val, len) {
            val = String(val);
            len = len || 2;
            while (val.length < len) val = "0" + val;
            return val;
        };

    // Regexes and supporting functions are cached through closure
    return function (date, mask, utc) {
        var dF = dateFormat;

        // You can't provide utc if you skip other args (use the "UTC:" mask prefix)
        if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
            mask = date;
            date = undefined;
        }

        // Passing date through Date applies Date.parse, if necessary
        date = date ? new Date(date) : new Date;
        if (isNaN(date)) throw SyntaxError("invalid date");

        mask = String(dF.masks[mask] || mask || dF.masks["default"]);

        // Allow setting the utc argument via the mask
        if (mask.slice(0, 4) == "UTC:") {
            mask = mask.slice(4);
            utc = true;
        }

        var	_ = utc ? "getUTC" : "get",
            d = date[_ + "Date"](),
            D = date[_ + "Day"](),
            m = date[_ + "Month"](),
            y = date[_ + "FullYear"](),
            H = date[_ + "Hours"](),
            M = date[_ + "Minutes"](),
            s = date[_ + "Seconds"](),
            L = date[_ + "Milliseconds"](),
            o = utc ? 0 : date.getTimezoneOffset(),
            flags = {
                d:    d,
                dd:   pad(d),
                ddd:  dF.i18n.dayNames[D],
                dddd: dF.i18n.dayNames[D + 7],
                m:    m + 1,
                mm:   pad(m + 1),
                mmm:  dF.i18n.monthNames[m],
                mmmm: dF.i18n.monthNames[m + 12],
                yy:   String(y).slice(2),
                yyyy: y,
                h:    H % 12 || 12,
                hh:   pad(H % 12 || 12),
                H:    H,
                HH:   pad(H),
                M:    M,
                MM:   pad(M),
                s:    s,
                ss:   pad(s),
                l:    pad(L, 3),
                L:    pad(L > 99 ? Math.round(L / 10) : L),
                t:    H < 12 ? "a"  : "p",
                tt:   H < 12 ? "am" : "pm",
                T:    H < 12 ? "A"  : "P",
                TT:   H < 12 ? "AM" : "PM",
                Z:    utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
                o:    (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
                S:    ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
            };

        return mask.replace(token, function ($0) {
            return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
        });
    };
}();

// Some common format strings
dateFormat.masks = {
    "default":      "ddd mmm dd yyyy HH:MM:ss",
    shortDate:      "m/d/yy",
    mediumDate:     "mmm d, yyyy",
    longDate:       "mmmm d, yyyy",
    fullDate:       "dddd, mmmm d, yyyy",
    shortTime:      "h:MM TT",
    mediumTime:     "h:MM:ss TT",
    longTime:       "h:MM:ss TT Z",
    isoDate:        "yyyy-mm-dd",
    isoTime:        "HH:MM:ss",
    isoDateTime:    "yyyy-mm-dd'T'HH:MM:ss",
    isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};

// Internationalization strings
dateFormat.i18n = {
    dayNames: [
        "ראשון",
        "שני",
        "שלישי",
        "רביעי",
        "חמישי",
        "שישי",
        "שבת",
        "ראשון",
        "שני",
        "שלישי",
        "רביעי",
        "חמישי",
        "שישי",
        "שבת"
    ],
    monthNames: [
        "ינואר",
        "פברואר",
        "מרץ",
        "אפריל",
        "מאי",
        "יוני",
        "יולי",
        "אוגוסט",
        "סםטמבר",
        "אוקטובר",
        "נובמבר",
        "דצמבר",
        "ינואר",
        "פברואר",
        "מרץ",
        "אפריל",
        "מאי",
        "יוני",
        "יולי",
        "אוגוסט",
        "סםטמבר",
        "אוקטובר",
        "נובמבר",
        "דצמבר"
    ]
};

// For convenience...
Date.prototype.format = function (mask, utc) {
    return dateFormat(this, mask, utc);
};<|endoftext|>


<commit_before>
module.exports = function(grunt) {
    var path = require('path');

    grunt.loadNpmTasks('grunt-contrib-jade');

    var buildDir = require('../buildDir.js')();

    var mainPathInterfix = path.join('src', 'modules') + path.sep;
    var jadePathInterfix = path.join('jade','views') + path.sep;

    var dest = path.join(buildDir, 'tmp', 'views');
    var rootDest = path.join(buildDir);
    var files = grunt.file.expandMapping([
        path.join('src', 'modules', '**', '*.jade')
        ], dest, {
            rename: function(base, destPath) {
                var res = path.join(base, destPath.replace(/\.jade$/, '.js'));
                res = res.replace(mainPathInterfix, '');
                res = res.replace(jadePathInterfix, '');
                return res;
            }
        });
    var indexFile = [];
    indexFile.push({
        src: 'src/index.jade',
        dest: path.join(buildDir,'index.html')
    });
    grunt.config('jade', {
        devall: {
            options: {
                amd: true,
                client: true,
                compileDebug: false,
                namespace: 'TEMPLATES',
                processName: function(filename){
                    var res = filename.replace(/\.jade$/, '');
                    res = res.replace(mainPathInterfix, '');
                    res = path.join('views',res.replace(jadePathInterfix, ''));
                    console.log("jade : " + res + " compiled");
                    return res;
                }
            },
            files: files
        },
        devindex: {
            options: {
                client: false,
                processName: function(filename){
                    console.log("jade : " + filename + " compiled");
                }
            },
            files: indexFile
        }
    });
};
<commit_msg>Fix jade task issue for windows environment<commit_after>
module.exports = function(grunt) {
    var path = require('path');

    grunt.loadNpmTasks('grunt-contrib-jade');

    var buildDir = require('../buildDir.js')();

    //For windows build replace \ by /
    var mainPathInterfix = (path.join('src', 'modules') + path.sep).replace(/\\/g,'/');
    var jadePathInterfix = (path.join('jade','views') + path.sep).replace(/\\/g,'/');

    var dest = path.join(buildDir, 'tmp', 'views');
    var rootDest = path.join(buildDir);
    var files = grunt.file.expandMapping([
        path.join('src', 'modules', '**', '*.jade')
        ], dest, {
            rename: function(base, destPath) {
                var res = path.join(base, destPath.replace(/\.jade$/, '.js')).replace(/\\/g,'/');
                res = res.replace(mainPathInterfix, '').replace(/\\/g,'/');
                res = res.replace(jadePathInterfix, '').replace(/\\/g,'/');
                return res;
            }
        });
    var indexFile = [];
    indexFile.push({
        src: 'src/index.jade',
        dest: path.join(buildDir,'index.html')
    });
    grunt.config('jade', {
        devall: {
            options: {
                amd: true,
                client: true,
                compileDebug: false,
                namespace: 'TEMPLATES',
                processName: function(filename){
                    var res = filename.replace(/\.jade$/, '');
                    res = res.replace(/\\/g,'/');
                    res = res.replace(mainPathInterfix, '');
                    res = path.join('views',res.replace(jadePathInterfix, '')).replace(/\\/g,'/');

                    console.log("jade : " + res + " compiled");
                    return res;
                }
            },
            files: files
        },
        devindex: {
            options: {
                client: false,
                processName: function(filename){
                    console.log("jade : " + filename + " compiled");
                }
            },
            files: indexFile
        }
    });
};
<|endoftext|>


<commit_before>import d3 from 'd3';

// Traffic Stops global defaults
export default {
  end_year: 2005,     // start-year for reporting requirement
  end_year: new Date().getUTCFullYear(),       // end-date for latest dataset
  races: [
    'white',
    'black',
    'native_american',
    'asian',
    'other'
  ],
  census_ethnicities: [
    'hispanic',
    'non_hispanic'
  ],
  pprint: d3.map({
    'white': 'White',
    'black': 'Black',
    'native_american': 'Native American',
    'asian': 'Asian',
    'other': 'Other',
    'hispanic': 'Hispanic',
    'non-hispanic': 'Non-hispanic'
  }),
  ethnicities: [
    'White',
    'Black',
    'Hispanic',
    'Unknown',
  ],
  colors: [
    "#1C9647", // dark green
    "#3F5EAB", // dark blue
    "#A7D16B", // light green
    "#66ACDD", // light blue
    "#7A76B7", // purple
    "#DC8F27", // orange
  ],
  baseline_color: "black",
  single_color: "#5C0808",
  purpose_order: d3.map({ // strings must match PURPOSE_CHOICES
    'Equipment': 0,
    'Moving Violation': 1,
    'Registration': 2,
  }),
};
<commit_msg>fix variable name typo<commit_after>import d3 from 'd3';

// Traffic Stops global defaults
export default {
  start_year: 2005,     // start-year for reporting requirement
  end_year: new Date().getUTCFullYear(),       // end-date for latest dataset
  races: [
    'white',
    'black',
    'native_american',
    'asian',
    'other'
  ],
  census_ethnicities: [
    'hispanic',
    'non_hispanic'
  ],
  pprint: d3.map({
    'white': 'White',
    'black': 'Black',
    'native_american': 'Native American',
    'asian': 'Asian',
    'other': 'Other',
    'hispanic': 'Hispanic',
    'non-hispanic': 'Non-hispanic'
  }),
  ethnicities: [
    'White',
    'Black',
    'Hispanic',
    'Unknown',
  ],
  colors: [
    "#1C9647", // dark green
    "#3F5EAB", // dark blue
    "#A7D16B", // light green
    "#66ACDD", // light blue
    "#7A76B7", // purple
    "#DC8F27", // orange
  ],
  baseline_color: "black",
  single_color: "#5C0808",
  purpose_order: d3.map({ // strings must match PURPOSE_CHOICES
    'Equipment': 0,
    'Moving Violation': 1,
    'Registration': 2,
  }),
};
<|endoftext|>


<commit_before>var setErrorMessage = function(statusCode, msg) {
    return {
        code: statusCode,
        message: msg
    };
};

var createIterator = function(arr) {
    currentIndex = 0;

    return {
        next: function() {
            return (currentIndex < arr.length ? {
                value: arr[currentIndex++],
                done: false
            } : { done: true });
        }
    };
};

var waterfall = function(funcs, callback) {
    callback = callback || function() {};

    if(!Array.isArray(funcs))
        throw new Error("funcs are not of type array");
    else if(funcs.length <= 0)
        throw new Error("array is empty!");

    var iterator = createIterator(funcs);

    var obj = function() {
        var nxt = iterator.next();
        var err = arguments[0];
        var args = [];

        //not so nice looking copy to keep vm optimizations
        for(var i = (nxt.done ? 0 : 1), l = arguments.length; i < l; i++)
            args.push(arguments[i]);
        args.push(obj);

        if(!nxt.done && !err)
            nxt.value.apply(nxt.value, args);
        else
            callback.apply(callback, (!err ? args : err));
    };

    obj();
};

var loginClient = function(client, tries) {
    tries = tries || 0;

    waterfall([
        client.getCSRF.bind(client),
        client.setLogin.bind(client),
        client._getAuthToken.bind(client)
    ], function _loginCredentialCheck(err) {
        if(err) {
            if(tries < 2) {
                client.log("an error occured while trying to log in", 0, "red");
                client.log("err: " + err.code, 1, "red");
                client.log("trying to reconnect...", 0);
                loginClient(client, ++tries);
            } else {
                client.log("couldn't log in.", 0, "red");
                client.emit(client.LOGIN_ERROR, "couldn't log in");
            }
        } else {
            client._loggedIn.call(client);
        }
    });
};

var decode = function(str) {
    if(typeof str !== "string")
        return str;

    return str
    .replace(/"/g, '"')
    .replace(/'/g, '\'')
    .replace(/&/g, '&')
    .replace(/</g, '<')
    .replace(/>/g, '>');
};

exports.setErrorMessage = setErrorMessage;
exports.createIterator = createIterator;
exports.loginClient = loginClient;
exports.waterfall = waterfall;
exports.decode = decode;
<commit_msg>changed replacement for quotes<commit_after>var setErrorMessage = function(statusCode, msg) {
    return {
        code: statusCode,
        message: msg
    };
};

var createIterator = function(arr) {
    currentIndex = 0;

    return {
        next: function() {
            return (currentIndex < arr.length ? {
                value: arr[currentIndex++],
                done: false
            } : { done: true });
        }
    };
};

var waterfall = function(funcs, callback) {
    callback = callback || function() {};

    if(!Array.isArray(funcs))
        throw new Error("funcs are not of type array");
    else if(funcs.length <= 0)
        throw new Error("array is empty!");

    var iterator = createIterator(funcs);

    var obj = function() {
        var nxt = iterator.next();
        var err = arguments[0];
        var args = [];

        //not so nice looking copy to keep vm optimizations
        for(var i = (nxt.done ? 0 : 1), l = arguments.length; i < l; i++)
            args.push(arguments[i]);
        args.push(obj);

        if(!nxt.done && !err)
            nxt.value.apply(nxt.value, args);
        else
            callback.apply(callback, (!err ? args : err));
    };

    obj();
};

var loginClient = function(client, tries) {
    tries = tries || 0;

    waterfall([
        client.getCSRF.bind(client),
        client.setLogin.bind(client),
        client._getAuthToken.bind(client)
    ], function _loginCredentialCheck(err) {
        if(err) {
            if(tries < 2) {
                client.log("an error occured while trying to log in", 0, "red");
                client.log("err: " + err.code, 1, "red");
                client.log("trying to reconnect...", 0);
                loginClient(client, ++tries);
            } else {
                client.log("couldn't log in.", 0, "red");
                client.emit(client.LOGIN_ERROR, "couldn't log in");
            }
        } else {
            client._loggedIn.call(client);
        }
    });
};

var decode = function(str) {
    if(typeof str !== "string")
        return str;

    return str
    .replace(/"/g, '\\\"')
    .replace(/'/g, '\'')
    .replace(/&/g, '&')
    .replace(/</g, '<')
    .replace(/>/g, '>');
};

exports.setErrorMessage = setErrorMessage;
exports.createIterator = createIterator;
exports.loginClient = loginClient;
exports.waterfall = waterfall;
exports.decode = decode;
<|endoftext|>


<commit_before>"use strict";

module.exports = function(grunt, data) {
    var extend = require("extend"),
        defaults = {
            "cache" : true,
            "crawl": false,
            "customTests": [],
            "dest": "assets/js/vendor/modernizr.js",
            "tests": [
                "touchevents",
                "cssanimations",
                "cssfilters",
                "fontface",
                "csstransforms",
                "csstransforms3d",
                "csstransitions",
                "webp"
            ],
            "options": [
                "domPrefixes",
                "prefixes",
                "mq",
                "prefixed",
                "prefixedCSS",
                "prefixedCSSValue",
                "testAllProps",
                "testProp",
                "testStyles",
                "html5printshiv",
                "setClasses"
            ],
            "uglify": true
        },
        config = {
            dev: {},
            production: {}
        };

    extend(config.dev, defaults, {uglify: false});
    extend(config.production, defaults, {cache: false});

    config.dev.dest = "src/" + config.dev.dest;
    config.production.dest = "build/" + config.production.dest;

    // console.log(config);

    return config;
};
<commit_msg>Added fullscreen test for Modernizr<commit_after>"use strict";

module.exports = function(grunt, data) {
    var extend = require("extend"),
        defaults = {
            "cache" : true,
            "crawl": false,
            "customTests": [],
            "dest": "assets/js/vendor/modernizr.js",
            "tests": [
                "touchevents",
                "cssanimations",
                "cssfilters",
                "fontface",
                "csstransforms",
                "csstransforms3d",
                "csstransitions",
                "webp",
                "fullscreen",
            ],
            "options": [
                "domPrefixes",
                "prefixes",
                "mq",
                "prefixed",
                "prefixedCSS",
                "prefixedCSSValue",
                "testAllProps",
                "testProp",
                "testStyles",
                "html5printshiv",
                "setClasses"
            ],
            "uglify": true
        },
        config = {
            dev: {},
            production: {}
        };

    extend(config.dev, defaults, {uglify: false});
    extend(config.production, defaults, {cache: false});

    config.dev.dest = "src/" + config.dev.dest;
    config.production.dest = "build/" + config.production.dest;

    // console.log(config);

    return config;
};
<|endoftext|>


<commit_before>module.exports = Cmds.addCommand({
    cmds: [';mute ', ';mutehammer '],

    requires: {
        guild: true,
        loud: false,
    },

    desc: 'Mute a user (in all guild channels) and add the mute to their record',

    args: '([@user] | [id] | [name]) ([mute_length_hours]) ([reason])',

    example: 'vae 2 being weird',

    // /////////////////////////////////////////////////////////////////////////////////////////

    func: (cmd, args, msgObj, speaker, channel, guild) => {
        args = args.trim();

        const data = Util.getDataFromString(args,
            [
                [
                    function (str) {
                        return Util.getMemberByMixed(str, guild) || Util.isId(str);
                    },
                ],
                [
                    function (str) {
                        const timeHours = Util.matchWholeNumber(str);
                        return timeHours;
                    },
                ],
                [
                    function (str) {
                        let mult;
                        str = str.toLowerCase();
                        if (str.substr(str.length - 1, 1) == 's') str = str.substr(0, str.length - 1);
                        if (str == 'millisecond' || str == 'ms') mult = 1 / 60 / 60 / 1000;
                        if (str == 'second' || str == 's' || str == 'sec') mult = 1 / 60 / 60;
                        if (str == 'minute' || str == 'm' || str == 'min') mult = 1 / 60;
                        if (str == 'hour' || str == 'h') mult = 1;
                        if (str == 'day' || str == 'd') mult = 24;
                        if (str == 'week' || str == 'w') mult = 24 * 7;
                        if (str == 'month' || str == 'mo') mult = 24 * 30.42;
                        if (str == 'year' || str == 'y') mult = 24 * 365.2422;
                        return mult;
                    },
                ],
            ]
        , true);

        if (!data) {
            return Util.sendEmbed(channel, 'Mute Failed', 'User not found', Util.makeEmbedFooter(speaker), null, 0x00E676, null);
        }

        console.log(`Mute Arg Data: ${data}`);

        const member = data[0];
        const mult = data[2] || 1;
        const time = data[1] * 1000 * 60 * 60 * mult;
        const reason = data[3];

        Mutes.addMute(guild, channel, member, speaker, { 'time': time, 'reason': reason });

        return true;
    },
});
<commit_msg>Fixed bug due to JS returning 0 when you multiply a number with null<commit_after>module.exports = Cmds.addCommand({
    cmds: [';mute ', ';mutehammer '],

    requires: {
        guild: true,
        loud: false,
    },

    desc: 'Mute a user (in all guild channels) and add the mute to their record',

    args: '([@user] | [id] | [name]) ([mute_length_hours]) ([reason])',

    example: 'vae 2 being weird',

    // /////////////////////////////////////////////////////////////////////////////////////////

    func: (cmd, args, msgObj, speaker, channel, guild) => {
        args = args.trim();

        const data = Util.getDataFromString(args,
            [
                [
                    function (str) {
                        return Util.getMemberByMixed(str, guild) || Util.isId(str);
                    },
                ],
                [
                    function (str) {
                        const timeHours = Util.matchWholeNumber(str);
                        return timeHours;
                    },
                ],
                [
                    function (str) {
                        let mult;
                        str = str.toLowerCase();
                        if (str.substr(str.length - 1, 1) == 's') str = str.substr(0, str.length - 1);
                        if (str == 'millisecond' || str == 'ms') mult = 1 / 60 / 60 / 1000;
                        if (str == 'second' || str == 's' || str == 'sec') mult = 1 / 60 / 60;
                        if (str == 'minute' || str == 'm' || str == 'min') mult = 1 / 60;
                        if (str == 'hour' || str == 'h') mult = 1;
                        if (str == 'day' || str == 'd') mult = 24;
                        if (str == 'week' || str == 'w') mult = 24 * 7;
                        if (str == 'month' || str == 'mo') mult = 24 * 30.42;
                        if (str == 'year' || str == 'y') mult = 24 * 365.2422;
                        return mult;
                    },
                ],
            ]
        , true);

        if (!data) {
            return Util.sendEmbed(channel, 'Mute Failed', 'User not found', Util.makeEmbedFooter(speaker), null, 0x00E676, null);
        }

        console.log(`Mute Arg Data: ${data}`);

        const member = data[0];
        const mult = data[2] || 1;
        const time = data[1] ? data[1] * 1000 * 60 * 60 * mult : null;
        const reason = data[3];

        Mutes.addMute(guild, channel, member, speaker, { 'time': time, 'reason': reason });

        return true;
    },
});
<|endoftext|>