<commit_before>function ContentBuilder (servico) {
	this.servico = servico;
	this.docContent = [];
	this.parseHtml = new ParseHtml();
}

ContentBuilder.prototype.addContent = function (content) {
	this.docContent.push(content);
};

ContentBuilder.prototype.addNewLine = function () {
	this.addContent('\n');
};

ContentBuilder.prototype.buildNome = function () {
	this.addContent({ text: this.servico.nome + ' (' + this.servico.sigla + ')', style: 'header' });
	this.addNewLine();
};

ContentBuilder.prototype.buildDescricao = function () {
	this.addContent({ text: 'O que é?', style: 'subheader' });
	this.addNewLine();
	this.addContent({ text: this.servico.descricao, style: 'paragraph' });
	this.addNewLine();
};

ContentBuilder.prototype.buildSolicitantes = function () {
	var self = this;

	this.addContent({ text: 'Quem pode utilizar este serviço?', style: 'subheader' });
	this.addNewLine();

	$(this.servico.solicitantes).each(function(index, solicitante) {
		self.addContent({ text: solicitante.tipo , style: 'thirdheader' });
		self.addContent({ text: solicitante.requisitos , style: 'paragraph' });
		self.addNewLine();
	});

	this.addContent({ text: '', style: 'paragraph', pageBreak: 'after' });
};

ContentBuilder.prototype.buildTempoTotalEstimado = function () {
	this.addContent({ text: 'Quanto tempo leva?', style: 'subheader' });
	this.addNewLine();
	this.addContent({ text: this.servico.tempoTotalEstimado.max + ' ' + this.servico.tempoTotalEstimado.unidade, style: 'paragraph' });
	this.addNewLine();
};

ContentBuilder.prototype.buildLegislacoes = function () {
	var content = [];
	var textoHtml = markdown.toHTML(this.servico.legislacoes[0]);

	this.addContent({ text: 'Legislação', style: 'subheader' });
	this.addNewLine();

	this.parseHtml.parseHtml(content, textoHtml);
	this.docContent = this.docContent.concat(content);
	this.addNewLine();
};

ContentBuilder.prototype.buildNomesPopulares = function () {
	this.addContent({ text: 'Você também pode conhecer este serviço como: ' + this.servico.nomesPopulares.join(', ') + '.', style: 'paragraph' });
	this.addNewLine();
};

ContentBuilder.prototype.buildGratuidade = function () {
	this.addContent({ text: this.servico.gratuito ? 'Este serviço é gratuito para o cidadão.' : '', style: 'paragraph' });
	this.addNewLine();
};

ContentBuilder.prototype.buildOutrasInformacoes = function () {
	this.addContent({ text: 'Outras informações', style: 'subheader' });
	this.addNewLine();
	this.buildNomesPopulares();
	this.buildGratuidade();
};

ContentBuilder.prototype.buildEtapa = function (index, etapa) {
	this.addContent({ text: 'Etapa ' + (index + 1) + ' - ' + etapa.titulo, style: 'thirdheader' });
	this.addNewLine();
	this.addContent({ text: etapa.descricao, style: 'paragraph' });
	this.addNewLine();

	if(etapa.documentos.items.length > 0) { this.buildDocumentos(etapa.documentos); }
	if(etapa.custos.items.length > 0) { this.buildCustos(etapa.custos); }
	if(etapa.canaisDePrestacao.items.length > 0) { this.buildCanais(etapa.canaisDePrestacao); }
};

ContentBuilder.prototype.buildDocumentos = function (documentos) {
	this.addContent({ text: 'Documentos necessários para esta etapa:', style: 'thirdheader' });
	this.addNewLine();

	var documentosDoc = [];

	documentosDoc.push({ text: 'Documentação comum para todos', style: 'thirdheader' });
	documentosDoc.push({ ul: documentos.items, style: 'list' });
	documentosDoc.push('\n');

	$(documentos.casos).each(function(index, caso) {
		documentosDoc.push({ text: caso.descricao, style: 'thirdheader' });
		documentosDoc.push({ ul: caso.items, style: 'list' });
	});

	this.addContent({
		style: 'tableExample',
		table: {
			body: [
				[{ stack: documentosDoc}]
			]
		},
		layout: {
            paddingLeft: function(i, node) { return 10; },
            paddingRight: function(i, node) { return 10; },
            paddingTop: function(i, node) { return 10; },
            paddingBottom: function(i, node) { return 10; }
        }
	});
};

ContentBuilder.prototype.buildCustos = function (custos) {
	this.addContent({ text: 'Custos para esta etapa:', style: 'thirdheader' });
	this.addNewLine();

	var custosDoc = [];

	custosDoc.push({ text: 'Custos padrão', style: 'thirdheader' });

	$(custos.items).each(function(index, custo) {
		custosDoc.push({ ul: [ custo.descricao + ': ' + custo.valor ], style: 'list' });
	});

	custosDoc.push('\n');

	$(custos.casos).each(function(index, caso) {
		custosDoc.push({ text: caso.descricao, style: 'thirdheader' });
		$(caso.items).each(function(index, custo) {
			custosDoc.push({ ul: [ custo.descricao + ': ' + custo.valor ], style: 'list' });
		});
	});

	this.addContent({
		style: 'tableExample',
		table: {
			body: [
				[{ stack: custosDoc}]
			]
		},
		layout: {
            paddingLeft: function(i, node) { return 10; },
            paddingRight: function(i, node) { return 10; },
            paddingTop: function(i, node) { return 10; },
            paddingBottom: function(i, node) { return 10; }
        }
	});
};

ContentBuilder.prototype.buildCanais = function (canais) {
	this.addContent({ text: 'Canais de comunicação com este serviço:', style: 'thirdheader' });
	this.addNewLine();

	var canaisDoc = [];

	this.addContent({ text: 'Canais de prestação padrão', style: 'thirdheader' });

	$(canais.items).each(function(index, canal) {
		canaisDoc.push({ ul: [ canal.tipo + ': ' + canal.descricao ], style: 'list' });
	});

	canaisDoc.push('\n');

	$(canais.casos).each(function(index, caso) {
		canaisDoc.push({ text: caso.descricao, style: 'thirdheader' });
		$(caso.items).each(function(index, canal) {
			canaisDoc.push({ ul: [ canal.tipo + ': ' + canal.descricao ], style: 'list' });
		});
	});

	this.addContent({
		style: 'tableExample',
		table: {
			body: [
				[{ stack: canaisDoc}]
			]
		},
		layout: {
            paddingLeft: function(i, node) { return 10; },
            paddingRight: function(i, node) { return 10; },
            paddingTop: function(i, node) { return 10; },
            paddingBottom: function(i, node) { return 10; }
        }
	});
};

ContentBuilder.prototype.buildEtapas = function () {
	var self = this;

	this.addContent({ text: 'Etapas para a realização desse serviço', style: 'subheader' });
	this.addNewLine();

	$(this.servico.etapas).each(function(index, etapa){
		self.buildEtapa(index, etapa);
	});
};

ContentBuilder.prototype.buildContent = function () {
	this.buildNome();
	this.buildDescricao();
	this.buildSolicitantes();
	this.buildEtapas();
	this.buildTempoTotalEstimado();
	this.buildLegislacoes();
	this.buildOutrasInformacoes();

	return this.docContent;
};
<commit_msg>Arrumando canais de prestação padrão<commit_after>function ContentBuilder (servico) {
	this.servico = servico;
	this.docContent = [];
	this.parseHtml = new ParseHtml();
}

ContentBuilder.prototype.addContent = function (content) {
	this.docContent.push(content);
};

ContentBuilder.prototype.addNewLine = function () {
	this.addContent('\n');
};

ContentBuilder.prototype.buildNome = function () {
	this.addContent({ text: this.servico.nome + ' (' + this.servico.sigla + ')', style: 'header' });
	this.addNewLine();
};

ContentBuilder.prototype.buildDescricao = function () {
	this.addContent({ text: 'O que é?', style: 'subheader' });
	this.addNewLine();
	this.addContent({ text: this.servico.descricao, style: 'paragraph' });
	this.addNewLine();
};

ContentBuilder.prototype.buildSolicitantes = function () {
	var self = this;

	this.addContent({ text: 'Quem pode utilizar este serviço?', style: 'subheader' });
	this.addNewLine();

	$(this.servico.solicitantes).each(function(index, solicitante) {
		self.addContent({ text: solicitante.tipo , style: 'thirdheader' });
		self.addContent({ text: solicitante.requisitos , style: 'paragraph' });
		self.addNewLine();
	});

	this.addContent({ text: '', style: 'paragraph', pageBreak: 'after' });
};

ContentBuilder.prototype.buildTempoTotalEstimado = function () {
	this.addContent({ text: 'Quanto tempo leva?', style: 'subheader' });
	this.addNewLine();
	this.addContent({ text: this.servico.tempoTotalEstimado.max + ' ' + this.servico.tempoTotalEstimado.unidade, style: 'paragraph' });
	this.addNewLine();
};

ContentBuilder.prototype.buildLegislacoes = function () {
	var content = [];
	var textoHtml = markdown.toHTML(this.servico.legislacoes[0]);

	this.addContent({ text: 'Legislação', style: 'subheader' });
	this.addNewLine();

	this.parseHtml.parseHtml(content, textoHtml);
	this.docContent = this.docContent.concat(content);
	this.addNewLine();
};

ContentBuilder.prototype.buildNomesPopulares = function () {
	this.addContent({ text: 'Você também pode conhecer este serviço como: ' + this.servico.nomesPopulares.join(', ') + '.', style: 'paragraph' });
	this.addNewLine();
};

ContentBuilder.prototype.buildGratuidade = function () {
	this.addContent({ text: this.servico.gratuito ? 'Este serviço é gratuito para o cidadão.' : '', style: 'paragraph' });
	this.addNewLine();
};

ContentBuilder.prototype.buildOutrasInformacoes = function () {
	this.addContent({ text: 'Outras informações', style: 'subheader' });
	this.addNewLine();
	this.buildNomesPopulares();
	this.buildGratuidade();
};

ContentBuilder.prototype.buildEtapa = function (index, etapa) {
	this.addContent({ text: 'Etapa ' + (index + 1) + ' - ' + etapa.titulo, style: 'thirdheader' });
	this.addNewLine();
	this.addContent({ text: etapa.descricao, style: 'paragraph' });
	this.addNewLine();

	if(etapa.documentos.items.length > 0) { this.buildDocumentos(etapa.documentos); }
	if(etapa.custos.items.length > 0) { this.buildCustos(etapa.custos); }
	if(etapa.canaisDePrestacao.items.length > 0) { this.buildCanais(etapa.canaisDePrestacao); }
};

ContentBuilder.prototype.buildDocumentos = function (documentos) {
	this.addContent({ text: 'Documentos necessários para esta etapa:', style: 'thirdheader' });
	this.addNewLine();

	var documentosDoc = [];

	documentosDoc.push({ text: 'Documentação comum para todos', style: 'thirdheader' });
	documentosDoc.push({ ul: documentos.items, style: 'list' });
	documentosDoc.push('\n');

	$(documentos.casos).each(function(index, caso) {
		documentosDoc.push({ text: caso.descricao, style: 'thirdheader' });
		documentosDoc.push({ ul: caso.items, style: 'list' });
	});

	this.addContent({
		style: 'tableExample',
		table: {
			body: [
				[{ stack: documentosDoc}]
			]
		},
		layout: {
            paddingLeft: function(i, node) { return 10; },
            paddingRight: function(i, node) { return 10; },
            paddingTop: function(i, node) { return 10; },
            paddingBottom: function(i, node) { return 10; }
        }
	});
};

ContentBuilder.prototype.buildCustos = function (custos) {
	this.addContent({ text: 'Custos para esta etapa:', style: 'thirdheader' });
	this.addNewLine();

	var custosDoc = [];

	custosDoc.push({ text: 'Custos padrão', style: 'thirdheader' });

	$(custos.items).each(function(index, custo) {
		custosDoc.push({ ul: [ custo.descricao + ': ' + custo.valor ], style: 'list' });
	});

	custosDoc.push('\n');

	$(custos.casos).each(function(index, caso) {
		custosDoc.push({ text: caso.descricao, style: 'thirdheader' });
		$(caso.items).each(function(index, custo) {
			custosDoc.push({ ul: [ custo.descricao + ': ' + custo.valor ], style: 'list' });
		});
	});

	this.addContent({
		style: 'tableExample',
		table: {
			body: [
				[{ stack: custosDoc}]
			]
		},
		layout: {
            paddingLeft: function(i, node) { return 10; },
            paddingRight: function(i, node) { return 10; },
            paddingTop: function(i, node) { return 10; },
            paddingBottom: function(i, node) { return 10; }
        }
	});
};

ContentBuilder.prototype.buildCanais = function (canais) {
	this.addContent({ text: 'Canais de comunicação com este serviço:', style: 'thirdheader' });
	this.addNewLine();

	var canaisDoc = [];

	canaisDoc.push({ text: 'Canais de prestação padrão', style: 'thirdheader' });

	$(canais.items).each(function(index, canal) {
		canaisDoc.push({ ul: [ canal.tipo + ': ' + canal.descricao ], style: 'list' });
	});

	canaisDoc.push('\n');

	$(canais.casos).each(function(index, caso) {
		canaisDoc.push({ text: caso.descricao, style: 'thirdheader' });
		$(caso.items).each(function(index, canal) {
			canaisDoc.push({ ul: [ canal.tipo + ': ' + canal.descricao ], style: 'list' });
		});
	});

	this.addContent({
		style: 'tableExample',
		table: {
			body: [
				[{ stack: canaisDoc}]
			]
		},
		layout: {
            paddingLeft: function(i, node) { return 10; },
            paddingRight: function(i, node) { return 10; },
            paddingTop: function(i, node) { return 10; },
            paddingBottom: function(i, node) { return 10; }
        }
	});
};

ContentBuilder.prototype.buildEtapas = function () {
	var self = this;

	this.addContent({ text: 'Etapas para a realização desse serviço', style: 'subheader' });
	this.addNewLine();

	$(this.servico.etapas).each(function(index, etapa){
		self.buildEtapa(index, etapa);
	});
};

ContentBuilder.prototype.buildContent = function () {
	this.buildNome();
	this.buildDescricao();
	this.buildSolicitantes();
	this.buildEtapas();
	this.buildTempoTotalEstimado();
	this.buildLegislacoes();
	this.buildOutrasInformacoes();

	return this.docContent;
};
<|endoftext|>


<commit_before>var OAE = require("../../oae-util/lib/OAE.js");

OAE.runQuery("CREATE TABLE users (KEY uuid PRIMARY KEY, tenantId text, institutionalId text, firstName text, lastName text, email text, " +
             "picture text) WITH comment='user information' AND read_repair_chance = 1.0;");
<commit_msg>Simplifying require statement<commit_after>var OAE = require("oae-util/lib/OAE");

OAE.runQuery("CREATE TABLE users (KEY uuid PRIMARY KEY, tenantId text, institutionalId text, firstName text, lastName text, email text, " +
             "picture text) WITH comment='user information' AND read_repair_chance = 1.0;");
<|endoftext|>


<commit_before>/*!
 * dependsOn v1.0.2
 * a jQuery plugin to facilitate the handling of form field dependencies.
 *
 * Copyright (c) 2015 David Street
 * @license the MIT license.
 */
(function($){var Dependency=function(selector,qualifiers){this.selector=selector;this.$dependencyObj=$(selector);this.qualifiers=qualifiers};Dependency.prototype.enabled=function(checkAgainst){if($(this.selector+"[disabled]").length>0){if(checkAgainst){return false}}else{if(!checkAgainst){return false}}return true};Dependency.prototype.checked=function(checkAgainst){if(this.$dependencyObj.attr("type")==="checkbox"){if(!this.$dependencyObj.is(":checked")&&checkAgainst||this.$dependencyObj.is(":checked")&&!checkAgainst){return false}}return true};Dependency.prototype.values=function(checkAgainst){var dependencyValue=this.$dependencyObj.val(),length=checkAgainst.length,i=0,match=false;if(this.$dependencyObj.attr("type")==="radio"){dependencyValue=this.$dependencyObj.filter(":checked").val()}for(i;i<length;i+=1){if(typeof dependencyValue==="array"||typeof dependencyValue==="object"){if($(this.$dependencyObj.val()).not($(checkAgainst[i])).length===0&&$(checkAgainst[i]).not($(this.$dependencyObj.val())).length===0){match=true;break}}else{if(checkAgainst[i]===dependencyValue){match=true;break}}}return match};Dependency.prototype.not=function(checkAgainst){var dependencyValue=this.$dependencyObj.val(),length=checkAgainst.length,i=0;if(this.$dependencyObj.attr("type")==="radio"){dependencyValue=this.$dependencyObj.filter(":checked").val()}for(i;i<length;i+=1){if(checkAgainst[i]===dependencyValue){return false}}return true};Dependency.prototype.match=function(checkAgainst){var dependencyValue=this.$dependencyObj.val(),pattern=checkAgainst;return pattern.test(dependencyValue)};Dependency.prototype.contains=function(checkAgainst){var dependencyValue=this.$dependencyObj.val(),i=0;if(typeof dependencyValue==="array"||typeof dependencyValue==="object"){for(i in checkAgainst){if($.inArray(checkAgainst[i],dependencyValue)!==-1){return true}}}else{return this.values(checkAgainst)}return false};Dependency.prototype.email=function(checkAgainst){var emailPattern=/^[_a-zA-Z0-9\-]+(\.[_a-zA-Z0-9\-]+)*@[a-zA-Z0-9\-]+(\.[a-zA-Z0-9\-]+)*\.(([0-9]{1,3})|([a-zA-Z]{2,3})|(aero|coop|info|museum|name))$/;return this.match(emailPattern)===checkAgainst};Dependency.prototype.url=function(checkAgainst){var urlPattern=/(((http|ftp|https):\/\/)|www\.)[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?\^=%&:\/~\+#!]*[\w\-\@?\^=%&\/~\+#])?/g;return this.match(urlPattern)===checkAgainst};Dependency.prototype.doesQualify=function(){var q=0;for(q in this.qualifiers){if(Dependency.prototype.hasOwnProperty(q)&&typeof Dependency.prototype[q]==="function"){if(!this[q](this.qualifiers[q])){return false}}else{if(typeof(this.qualifiers[q]==="function")){return this.qualifiers[q](this.$dependencyObj.val())}}}return true};var DependencySet=function(dependencies){var d=0;this.dependencies=[];for(d in dependencies){this.dependencies.push(new Dependency(d,dependencies[d]))}};DependencySet.prototype.doesQualify=function(){var length=this.dependencies.length,d=0,qualifies=true;for(d;d<length;d+=1){if(!this.dependencies[d].doesQualify()){qualifies=false;break}}return qualifies};var DependencyCollection=function($subject,initalSet,options){this.dependencySets=[];this.$subject=$subject;this.settings=$.extend({disable:true,hide:true,duration:200,onEnable:function(){},onDisable:function(){}},options);this.enableCallback=function(){};this.disableCallback=function(){};this.init(initalSet)};DependencyCollection.prototype.init=function(dependencies){this.addSet(dependencies);this.check(true)};DependencyCollection.prototype.addSet=function(set){var self=this,thisSet=0,numDependencies=0,d=0,dependency;this.dependencySets.push(new DependencySet(set));thisSet=this.dependencySets.length-1;numDependencies=this.dependencySets[thisSet].dependencies.length;for(d;d<numDependencies;d+=1){dependency=this.dependencySets[thisSet].dependencies[d];dependency.$dependencyObj.on("change",function(e){self.triggeredEvent=e;self.triggeredDependency=this;self.check()});if(dependency.$dependencyObj.attr("type")==="text"){dependency.$dependencyObj.on("keypress",function(e){if(e.which&&dependency.$dependencyObj.is(":focus")){if(self.check()){self.triggeredEvent=e;self.triggeredDependency=this;self.check()}}})}}};DependencyCollection.prototype.or=function(dependencies){this.addSet(dependencies);this.check(false);return this};DependencyCollection.prototype.enable=function(noFade){var valueSubject=this.$subject,subjectId=this.$subject.attr("id"),$hideObject;if(this.settings.hasOwnProperty("valueTarget")&&this.settings.valueTarget!==undefined){valueSubject=$(this.settings.valueTarget)}else if(this.$subject[0].nodeName.toLowerCase()!=="input"&&this.$subject[0].nodeName.toLowerCase()!=="textarea"&&this.$subject[0].nodeName.toLowerCase()!=="select"){valueSubject=this.$subject.find("input, textarea, select")}if(this.settings.disable){this.$subject.removeAttr("disabled")}if(this.settings.hide){if(this.$subject.parent()[0].nodeName.toLowerCase()==="label"){$hideObject=this.$subject.parent()}else{$hideObject=this.$subject.add('label[for="'+subjectId+'"]')}if($hideObject.css("display")==="none"){if(noFade){$hideObject.show()}else{$hideObject.fadeIn(this.settings.duration)}}}if(this.settings.hasOwnProperty("valueOnEnable")&&this.settings.valueOnEnable!==undefined){valueSubject.val(this.settings.valueOnEnable)}if(this.settings.hasOwnProperty("checkOnEnable")){if(this.settings.checkOnEnable){valueSubject.attr("checked","checked")}else{valueSubject.removeAttr("checked")}}if(this.settings.hasOwnProperty("toggleClass")&&this.settings.toggleClass!==undefined){this.$subject.addClass(this.settings.toggleClass)}this.settings.onEnable.call(this.triggeredDependency,this.triggeredEvent)};DependencyCollection.prototype.disable=function(noFade){var valueSubject=this.$subject,subjectId=this.$subject.attr("id"),$hideObject;if(this.settings.hasOwnProperty("valueTarget")&&this.settings.valueTarget!==undefined){valueSubject=$(this.settings.valueTarget)}else if(this.$subject[0].nodeName.toLowerCase()!=="input"&&this.$subject[0].nodeName.toLowerCase()!=="textarea"&&this.$subject[0].nodeName.toLowerCase()!=="select"){valueSubject=this.$subject.find("input, textarea, select")}if(this.settings.disable){this.$subject.attr("disabled","disabled")}if(this.settings.hide){if(this.$subject.parent()[0].nodeName.toLowerCase()==="label"){$hideObject=this.$subject.parent()}else{$hideObject=this.$subject.add('label[for="'+subjectId+'"]')}if(noFade){$hideObject.css({display:"none"})}else{$hideObject.fadeOut(this.settings.duration)}}if(this.settings.hasOwnProperty("valueOnDisable")&&this.settings.valueOnDisable!==undefined){valueSubject.val(this.settings.valueOnDisable)}if(this.settings.hasOwnProperty("checkOnDisable")){if(this.settings.checkOnDisable){valueSubject.attr("checked","checked")}else{valueSubject.removeAttr("checked")}}if(this.settings.hasOwnProperty("toggleClass")&&this.settings.toggleClass!==undefined){this.$subject.removeClass(this.settings.toggleClass)}this.settings.onDisable.call(this.triggeredDependency,this.triggeredEvent)};DependencyCollection.prototype.check=function(firstRun){var length=this.dependencySets.length,i=0,qualifies=false;for(i;i<length;i+=1){if(this.dependencySets[i].doesQualify()){qualifies=true;break}}if(qualifies){this.enable(firstRun);return true}else{this.disable(firstRun);return false}};$.fn.dependsOn=function(dependencies,options){var dependencyCollection=new DependencyCollection(this,dependencies,options);return dependencyCollection}})(jQuery);<commit_msg>Remove extraneous min file<commit_after><|endoftext|>


<commit_before>var Data = {
	headers: [],	// Title of each column of data received
	state: {},		// Current flight state
	history: [],	// All past flight states
	localWaypoints: [],	// List of waypoints we're working on
	remoteWaypoints: [],// List of waypoints we've uploaded
};

/*
headers:
	lat, lon, time, pitch, roll, yaw, pitch_rate, roll_rate, yaw_rate,
	kd_gain, kp_gain, ki_gain, ground_speed, altitude, heading,
	pitch_setpoint, roll_setpoint, heading_setpoint, throttle_setpoint,
	altitude_setpoint, int_pitch_setpoint, int_roll_setpoint, int_yaw_setpoint,
	lastCommandSent, errorCodes, cameraStatus, waypointIndex, editing_gain, gpsStatus
*/<commit_msg>Remove waypoints from Data; should be kept internal to Path.<commit_after>var Data = {
	headers: [],	// Title of each column of data received
	state: {},		// Current flight state
	history: [],	// All past flight states
};

/*
headers:
	lat, lon, time, pitch, roll, yaw, pitch_rate, roll_rate, yaw_rate,
	kd_gain, kp_gain, ki_gain, ground_speed, altitude, heading,
	pitch_setpoint, roll_setpoint, heading_setpoint, throttle_setpoint,
	altitude_setpoint, int_pitch_setpoint, int_roll_setpoint, int_yaw_setpoint,
	lastCommandSent, errorCodes, cameraStatus, waypointIndex, editing_gain, gpsStatus
*/<|endoftext|>


<commit_before>(function (server, user) {

    var log = new Log();

    var processPerms = function (perms, fn) {
        var perm, actions, i, length;
        for (perm in perms) {
            if (perms.hasOwnProperty(perm)) {
                actions = perms[perm];
                length = actions.length;
                for (i = 0; i < length; i++) {
                    fn(perm, actions[i]);
                }
            }
        }
    };

    var UserManager = function (serv, tenantId) {
        this.server = serv;
        this.tenantId = tenantId || server.superTenant.tenantId;
        var realmService = server.osgiService('org.wso2.carbon.user.core.service.RealmService'),
            realm = realmService.getTenantUserRealm(this.tenantId);
        this.manager = realm.getUserStoreManager();
        this.authorizer = realm.getAuthorizationManager();
    };
    user.UserManager = UserManager;

    UserManager.prototype.getUser = function (username) {
        if (!this.manager.isExistingUser(username)) {
            return null;
        }
        return new user.User(this, username);
    };
    UserManager.prototype.getRoleListOfUser = function (username) {
	        return this.manager.getRoleListOfUser(username);
	    };
    UserManager.prototype.addUser = function (username, password, roles, claims, profile) {
        this.manager.addUser(username, password, roles || [], claims || null, profile);
    };

    UserManager.prototype.removeUser = function (username) {
        this.manager.deleteUser(username);
    };

    UserManager.prototype.userExists = function (username) {
        return this.manager.isExistingUser(username);
    };

    UserManager.prototype.roleExists = function (role) {
        return this.manager.isExistingRole(role);
    };

    UserManager.prototype.getClaims = function (username, profile) {
        return this.manager.getUserClaimValues(username, profile);
    };
	UserManager.prototype.getClaimsForSet = function (username,claims, profile) {
        return this.manager.getUserClaimValues(username,claims, profile);
    };
    UserManager.prototype.getClaim = function (username, claim, profile) {
        return this.manager.getUserClaimValue(username, claim, profile);
    };

    UserManager.prototype.setClaims = function (username, claims, profile) {
        return this.manager.setUserClaimValues(username, claims, profile);
    };

    UserManager.prototype.setClaim = function (username, claim, value, profile) {
        return this.manager.setUserClaimValue(username, claim, value, profile);
    };

    UserManager.prototype.isAuthorized = function (role, permission, action) {
        return this.authorizer.isRoleAuthorized(role, permission, action);
    };
 	UserManager.prototype.updateRoleListOfUser = function(name, deletedRoles, newRoles){
    return this.manager.updateRoleListOfUser(name, deletedRoles, newRoles);
    };
    UserManager.prototype.updateUserListOfRole = function(name, deletedUsers, newUsers){
    return this.manager.updateUserListOfRole(name, deletedUsers, newUsers);
    };
	UserManager.prototype.listUsers = function () {
        return this.manager.listUsers("*", -1);
    };
    UserManager.prototype.addRole = function (role, users, permissions) {
        var perms = [],
            Permission = Packages.org.wso2.carbon.user.api.Permission;
        processPerms(permissions, function (id, action) {
            perms.push(new Permission(id, action));
        });
        this.manager['addRole(java.lang.String,java.lang.String[],org.wso2.carbon.user.api.Permission[])']
            (role, users, perms);
    };

    UserManager.prototype.removeRole = function (role) {
        this.manager.deleteRole(role);
    };

    UserManager.prototype.allRoles = function () {
        return this.manager.getRoleNames();
    };
	UserManager.prototype.getUserListOfRole = function (role) {
        return this.manager.getUserListOfRole(role);
    };

    /**
     * um.authorizeRole('store-admin', '/permissions/mypermission', 'ui-execute');
     *
     * um.authorizeRole('store-admin', {
     *      '/permissions/myperm1' : ['read', 'write'],
     *      '/permissions/myperm2' : ['read', 'write']
     * });
     *
     * @param role
     * @param permission
     * @param action
     */
    UserManager.prototype.authorizeRole = function (role, permission, action) {
        var that = this;
        if (permission instanceof String || typeof permission === 'string') {
            if (!that.isAuthorized(role, permission, action)) {
                that.authorizer.authorizeRole(role, permission, action);
            }
        } else {
            processPerms(permission, function (id, action) {
                if (!that.isAuthorized(role, id, action)) {
                    that.authorizer.authorizeRole(role, id, action);
                    if (log.isDebugEnabled()) {
                        log.debug('permission added(role:permission:action) - ' + role + ':' + id + ':' + action);
                    }
                }
            });
        }
    };

    /**
     * um.denyRole('store-admin', '/permissions/mypermission', 'ui-execute');
     *
     * um.denyRole('store-admin', {
     *      '/permissions/myperm1' : ['read', 'write'],
     *      '/permissions/myperm2' : ['read', 'write']
     * });
     *
     * @param role
     * @param permission
     * @param action
     */
    UserManager.prototype.denyRole = function (role, permission, action) {
        var deny = this.authorizer.denyRole;
        if (permission instanceof String || typeof permission === 'string') {
            deny(role, permission, action);
        } else {
            processPerms(permission, function (id, action) {
                deny(role, id, action);
            });
        }
    };

}(server, user));
<commit_msg>Update role name<commit_after>(function (server, user) {

    var log = new Log();

    var processPerms = function (perms, fn) {
        var perm, actions, i, length;
        for (perm in perms) {
            if (perms.hasOwnProperty(perm)) {
                actions = perms[perm];
                length = actions.length;
                for (i = 0; i < length; i++) {
                    fn(perm, actions[i]);
                }
            }
        }
    };

    var UserManager = function (serv, tenantId) {
        this.server = serv;
        this.tenantId = tenantId || server.superTenant.tenantId;
        var realmService = server.osgiService('org.wso2.carbon.user.core.service.RealmService'),
            realm = realmService.getTenantUserRealm(this.tenantId);
        this.manager = realm.getUserStoreManager();
        this.authorizer = realm.getAuthorizationManager();
    };
    user.UserManager = UserManager;

    UserManager.prototype.getUser = function (username) {
        if (!this.manager.isExistingUser(username)) {
            return null;
        }
        return new user.User(this, username);
    };
    UserManager.prototype.getRoleListOfUser = function (username) {
	        return this.manager.getRoleListOfUser(username);
	    };
    UserManager.prototype.addUser = function (username, password, roles, claims, profile) {
        this.manager.addUser(username, password, roles || [], claims || null, profile);
    };

    UserManager.prototype.removeUser = function (username) {
        this.manager.deleteUser(username);
    };

    UserManager.prototype.userExists = function (username) {
        return this.manager.isExistingUser(username);
    };

    UserManager.prototype.roleExists = function (role) {
        return this.manager.isExistingRole(role);
    };
	UserManager.prototype.updateRole = function (previousRoleName, newRoleName) {
        return this.manager.updateRoleName(previousRoleName, newRoleName);
    };
    UserManager.prototype.getClaims = function (username, profile) {
        return this.manager.getUserClaimValues(username, profile);
    };
	UserManager.prototype.getClaimsForSet = function (username,claims, profile) {
        return this.manager.getUserClaimValues(username,claims, profile);
    };
    UserManager.prototype.getClaim = function (username, claim, profile) {
        return this.manager.getUserClaimValue(username, claim, profile);
    };

    UserManager.prototype.setClaims = function (username, claims, profile) {
        return this.manager.setUserClaimValues(username, claims, profile);
    };

    UserManager.prototype.setClaim = function (username, claim, value, profile) {
        return this.manager.setUserClaimValue(username, claim, value, profile);
    };

    UserManager.prototype.isAuthorized = function (role, permission, action) {
        return this.authorizer.isRoleAuthorized(role, permission, action);
    };
 	UserManager.prototype.updateRoleListOfUser = function(name, deletedRoles, newRoles){
    return this.manager.updateRoleListOfUser(name, deletedRoles, newRoles);
    };
    UserManager.prototype.updateUserListOfRole = function(name, deletedUsers, newUsers){
    return this.manager.updateUserListOfRole(name, deletedUsers, newUsers);
    };
	UserManager.prototype.listUsers = function () {
        return this.manager.listUsers("*", -1);
    };
    UserManager.prototype.addRole = function (role, users, permissions) {
        var perms = [],
            Permission = Packages.org.wso2.carbon.user.api.Permission;
        processPerms(permissions, function (id, action) {
            perms.push(new Permission(id, action));
        });
        this.manager['addRole(java.lang.String,java.lang.String[],org.wso2.carbon.user.api.Permission[])']
            (role, users, perms);
    };

    UserManager.prototype.removeRole = function (role) {
        this.manager.deleteRole(role);
    };

    UserManager.prototype.allRoles = function () {
        return this.manager.getRoleNames();
    };
	UserManager.prototype.getUserListOfRole = function (role) {
        return this.manager.getUserListOfRole(role);
    };

    /**
     * um.authorizeRole('store-admin', '/permissions/mypermission', 'ui-execute');
     *
     * um.authorizeRole('store-admin', {
     *      '/permissions/myperm1' : ['read', 'write'],
     *      '/permissions/myperm2' : ['read', 'write']
     * });
     *
     * @param role
     * @param permission
     * @param action
     */
    UserManager.prototype.authorizeRole = function (role, permission, action) {
        var that = this;
        if (permission instanceof String || typeof permission === 'string') {
            if (!that.isAuthorized(role, permission, action)) {
                that.authorizer.authorizeRole(role, permission, action);
            }
        } else {
            processPerms(permission, function (id, action) {
                if (!that.isAuthorized(role, id, action)) {
                    that.authorizer.authorizeRole(role, id, action);
                    if (log.isDebugEnabled()) {
                        log.debug('permission added(role:permission:action) - ' + role + ':' + id + ':' + action);
                    }
                }
            });
        }
    };

    /**
     * um.denyRole('store-admin', '/permissions/mypermission', 'ui-execute');
     *
     * um.denyRole('store-admin', {
     *      '/permissions/myperm1' : ['read', 'write'],
     *      '/permissions/myperm2' : ['read', 'write']
     * });
     *
     * @param role
     * @param permission
     * @param action
     */
    UserManager.prototype.denyRole = function (role, permission, action) {
        var deny = this.authorizer.denyRole;
        if (permission instanceof String || typeof permission === 'string') {
            deny(role, permission, action);
        } else {
            processPerms(permission, function (id, action) {
                deny(role, id, action);
            });
        }
    };

}(server, user));
<|endoftext|>


<commit_before>// ==========================================================================
// Project:   The M-Project - Mobile HTML5 Application Framework
// Copyright: (c) M-Way Solutions GmbH. All rights reserved.
// Creator:   Dominik
// Date:      27.10.2010
// License:   Dual licensed under the MIT or GPL Version 2 licenses.
//            http://github.com/mwaylabs/The-M-Project/blob/master/MIT-LICENSE
//            http://github.com/mwaylabs/The-M-Project/blob/master/GPL-LICENSE
// ==========================================================================

m_require('logger.js');

/**
 * @class
 *
 * Object for dispatching all incoming events.
 *
 */
M.EventDispatcher = M.Object.create({

    /**
     * The type of this object.
     *
     * @property {String}
     */
    type: 'M.EventDispatcher',

    /**
     * This method is called whenever an event is triggered within the app.
     *
     * @param {Object} evt The event.
     */
    eventDidHappen: function(evt, paramId) {
        this.delegateEvent(evt.type, evt.currentTarget.id, evt.keyCode, paramId);
    },

    /**
     * This method simulates an event by creating an event object out of parameters
     * passed as a string.
     *
     * @param {String} type The event type.
     * @param {String} id The id that created this event.
     * @param {String} keyCode The key code.
     */
    simulateEvent: function(type, id, keyCode, paramId) {
        this.eventDidHappen({
            type: type,
            currentTarget: {
                id: id
            },
            keyCode: keyCode
        }, paramId);
    },

    /**
     * This method looks for a corresponding event inside the view manager and
     * delegates the call directly to the responsible controller defined by the
     * target and action properties of the view.
     *
     * @param {String} type The type of event that occured, e.g. 'click'.
     * @param {String} id The id of the element that triggered the event.
     * @param {Number} keyCode The keyCode property of the event, necessary for keypress event, e.g. keyCode is 13 when enter is pressed.
     */
    delegateEvent: function(type, id, keyCode, paramId) {
        var view = M.ViewManager.getViewById(id);

        switch(type) {
            case 'click':
                if(view && view.target && view.action && view.type !== 'M.TextFieldView') {
                    view.target[view.action](paramId ? paramId : id);
                }
                break;
            case 'change':
                view.setValueFromDOM();
                break;
            case 'keyup':
                if(keyCode === 13 && view.type === 'M.TextFieldView') {
                    if(view && view.target && view.action) {
                        view.target[view.action](id);
                    }
                }
                break;
            case 'focus':
                view.gotFocus();
                break;
            case 'blur':
                view.lostFocus();
                break;
            case 'orientationchange':
                view.orientationDidChange(evt);
                break;
        }
    }

});

$(document).ready(function() {
    var eventList = 'click change keyup focus blur';
    $('*[id]').bind(eventList, function(evt) { M.EventDispatcher.eventDidHappen(evt);});
});
<commit_msg>Changed event registering from bind() to live(), to bin future DOM elements too<commit_after>// ==========================================================================
// Project:   The M-Project - Mobile HTML5 Application Framework
// Copyright: (c) M-Way Solutions GmbH. All rights reserved.
// Creator:   Dominik
// Date:      27.10.2010
// License:   Dual licensed under the MIT or GPL Version 2 licenses.
//            http://github.com/mwaylabs/The-M-Project/blob/master/MIT-LICENSE
//            http://github.com/mwaylabs/The-M-Project/blob/master/GPL-LICENSE
// ==========================================================================

m_require('logger.js');

/**
 * @class
 *
 * Object for dispatching all incoming events.
 *
 */
M.EventDispatcher = M.Object.create({

    /**
     * The type of this object.
     *
     * @property {String}
     */
    type: 'M.EventDispatcher',

    /**
     * This method is called whenever an event is triggered within the app.
     *
     * @param {Object} evt The event.
     */
    eventDidHappen: function(evt, paramId) {
        this.delegateEvent(evt.type, evt.currentTarget.id, evt.keyCode, paramId);
    },

    /**
     * This method looks for a corresponding event inside the view manager and
     * delegates the call directly to the responsible controller defined by the
     * target and action properties of the view.
     *
     * @param {String} type The type of event that occured, e.g. 'click'.
     * @param {String} id The id of the element that triggered the event.
     * @param {Number} keyCode The keyCode property of the event, necessary for keypress event, e.g. keyCode is 13 when enter is pressed.
     */
    delegateEvent: function(type, id, keyCode, paramId) {
        var view = M.ViewManager.getViewById(id);
        switch(type) {
            case 'click':
                if(view && view.target && view.action && view.type !== 'M.TextFieldView') {
                    view.target[view.action](paramId ? paramId : id);
                }
                if(view && view.internalTarget && view.internalAction) {
                    view.internalTarget[view.internalAction](paramId ? paramId : id);
                }
                break;
            case 'change':
                view.setValueFromDOM();
                break;
            case 'keyup':
                if(keyCode === 13 && view.type === 'M.TextFieldView') {
                    if(view && view.target && view.action) {
                        view.target[view.action](id);
                    }
                }
                break;
            case 'focusin':
                view.gotFocus();
                break;
            case 'focusout':
                view.lostFocus();
                break;
            case 'orientationchange':
                view.orientationDidChange(evt);
                break;
        }
    }

});
<|endoftext|>


<commit_before>import qs from 'querystring'
import version from '../version'

/**
 * Create pre configured axios instance
 * @private
 * @param {Object} axios - Axios library
 * @param {Object} HTTPClientParams - Initialization parameters for the HTTP client
 * @prop {string} space - Space ID
 * @prop {string} accessToken - Access Token
 * @prop {boolean=} insecure - If we should use http instead
 * @prop {string=} host - Alternate host
 * @prop {Object=} agent - HTTP agent for node
 * @prop {Object=} headers - Additional headers
 * @return {Object} Initialized axios instance
 */
export default function createHttpClient (axios, {space, accessToken, insecure, host, agent, headers}) {
  let [hostname, port] = (host && host.split(':')) || []
  hostname = hostname || 'cdn.contentful.com'
  port = port || (insecure ? 80 : 443)
  headers = headers || {}
  headers['Content-Type'] = 'application/vnd.contentful.delivery.v1+json'
  headers['X-Contentful-User-Agent'] = 'contentful.js/' + version

  if (process && process.release && process.release.name === 'node') {
    headers['user-agent'] = 'node.js/' + process.version
  }

  return axios.create({
    baseURL: `${insecure ? 'http' : 'https'}://${hostname}:${port}/spaces/${space}/`,
    headers: headers,
    agent: agent,
    params: {
      access_token: accessToken
    },
    paramsSerializer: params => qs.stringify(params)
  })
}
<commit_msg>fix: Send access token as a header instead of querystring parameter<commit_after>import version from '../version'

/**
 * Create pre configured axios instance
 * @private
 * @param {Object} axios - Axios library
 * @param {Object} HTTPClientParams - Initialization parameters for the HTTP client
 * @prop {string} space - Space ID
 * @prop {string} accessToken - Access Token
 * @prop {boolean=} insecure - If we should use http instead
 * @prop {string=} host - Alternate host
 * @prop {Object=} agent - HTTP agent for node
 * @prop {Object=} headers - Additional headers
 * @return {Object} Initialized axios instance
 */
export default function createHttpClient (axios, {space, accessToken, insecure, host, agent, headers}) {
  let [hostname, port] = (host && host.split(':')) || []
  hostname = hostname || 'cdn.contentful.com'
  port = port || (insecure ? 80 : 443)
  headers = headers || {}
  headers['Authorization'] = 'Bearer ' + accessToken
  headers['Content-Type'] = 'application/vnd.contentful.delivery.v1+json'
  headers['X-Contentful-User-Agent'] = 'contentful.js/' + version

  if (process && process.release && process.release.name === 'node') {
    headers['user-agent'] = 'node.js/' + process.version
  }

  return axios.create({
    baseURL: `${insecure ? 'http' : 'https'}://${hostname}:${port}/spaces/${space}/`,
    headers: headers,
    agent: agent
  })
}
<|endoftext|>


<commit_before>var Select = require('./../index');
Select.prototype.willSelect = Select.prototype._willSelect;
Select.prototype.adjustDropdown = Select.prototype._adjustDropdown;
Select.prototype.addCloseListener = Select.prototype._addCloseListener;
Select.prototype.removeCloseListener = Select.prototype._removeCloseListener;
<commit_msg>Add missing action<commit_after>var Select = require('./../index');
Select.prototype.willSelect = Select.prototype._willSelect;
Select.prototype.adjustDropdown = Select.prototype._adjustDropdown;
Select.prototype.addCloseListener = Select.prototype._addCloseListener;
Select.prototype.removeCloseListener = Select.prototype._removeCloseListener;
Select.prototype.select = Select.prototype._select;
<|endoftext|>


<commit_before>/**
 * @author mrdoob / http://mrdoob.com/
 * @author bhouston / http://exocortex.com/
 * @author stephomi / http://stephaneginier.com/
 */

( function ( THREE ) {

	THREE.Raycaster = function ( origin, direction, near, far ) {

		this.ray = new THREE.Ray( origin, direction );
		// direction is assumed to be normalized (for accurate distance calculations)

		this.near = near || 0;
		this.far = far || Infinity;

	};

	var sphere = new THREE.Sphere();
	var localRay = new THREE.Ray();
	var facePlane = new THREE.Plane();
	var intersectPoint = new THREE.Vector3();
	var matrixPosition = new THREE.Vector3();

	var inverseMatrix = new THREE.Matrix4();

	var descSort = function ( a, b ) {

		return a.distance - b.distance;

	};

	var vA = new THREE.Vector3();
	var vB = new THREE.Vector3();
	var vC = new THREE.Vector3();

	var intersectObject = function ( object, raycaster, intersects ) {

		if ( object instanceof THREE.Sprite ) {

			matrixPosition.setFromMatrixPosition( object.matrixWorld );

			var distance = raycaster.ray.distanceToPoint( matrixPosition );

			if ( distance > object.scale.x ) {

				return intersects;

			}

			intersects.push( {

				distance: distance,
				point: object.position,
				face: null,
				object: object

			} );

		} else if ( object instanceof THREE.LOD ) {

			matrixPosition.setFromMatrixPosition( object.matrixWorld );
			var distance = raycaster.ray.origin.distanceTo( matrixPosition );

			intersectObject( object.getObjectForDistance( distance ), raycaster, intersects );

		} else if ( object instanceof THREE.Mesh ) {

			var geometry = object.geometry;

			// Checking boundingSphere distance to ray

			if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();

			sphere.copy( geometry.boundingSphere );
			sphere.applyMatrix4( object.matrixWorld );

			if ( raycaster.ray.isIntersectionSphere( sphere ) === false ) {

				return intersects;

			}

			// Check boundingBox before continuing

			inverseMatrix.getInverse( object.matrixWorld );
			localRay.copy( raycaster.ray ).applyMatrix4( inverseMatrix );

			if ( geometry.boundingBox !== null ) {

				if ( localRay.isIntersectionBox( geometry.boundingBox ) === false )  {

					return intersects;

				}

			}

			if ( geometry instanceof THREE.BufferGeometry ) {

				var material = object.material;

				if ( material === undefined ) return intersects;

				var attributes = geometry.attributes;

				var a, b, c;
				var precision = raycaster.precision;

				if ( attributes.index !== undefined ) {

					var offsets = geometry.offsets;
					var indices = attributes.index.array;
					var positions = attributes.position.array;

					for ( var oi = 0, ol = offsets.length; oi < ol; ++oi ) {

						var start = offsets[ oi ].start;
						var count = offsets[ oi ].count;
						var index = offsets[ oi ].index;

						for ( var i = start, il = start + count; i < il; i += 3 ) {

							a = index + indices[ i ];
							b = index + indices[ i + 1 ];
							c = index + indices[ i + 2 ];

							vA.set(
								positions[ a * 3 ],
								positions[ a * 3 + 1 ],
								positions[ a * 3 + 2 ]
							);
							vB.set(
								positions[ b * 3 ],
								positions[ b * 3 + 1 ],
								positions[ b * 3 + 2 ]
							);
							vC.set(
								positions[ c * 3 ],
								positions[ c * 3 + 1 ],
								positions[ c * 3 + 2 ]
							);

							if ( material.side === THREE.BackSide ) {

								var intersectionPoint = localRay.intersectTriangle( vC, vB, vA, true );

							} else {

								var intersectionPoint = localRay.intersectTriangle( vA, vB, vC, material.side !== THREE.DoubleSide );

							}

							if ( intersectionPoint === null ) continue;

							intersectionPoint.applyMatrix4( object.matrixWorld );

							var distance = raycaster.ray.origin.distanceTo( intersectionPoint );

							if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue;

							intersects.push( {

								distance: distance,
								point: intersectionPoint,
								indices: [a, b, c],
								face: null,
								faceIndex: null,
								object: object

							} );

						}

					}

				} else {

					var offsets = geometry.offsets;
					var positions = attributes.position.array;

					for ( var i = 0, il = attributes.position.array.length; i < il; i += 3 ) {

						a = i;
						b = i + 1;
						c = i + 2;

						vA.set(
							positions[ a * 3 ],
							positions[ a * 3 + 1 ],
							positions[ a * 3 + 2 ]
						);
						vB.set(
							positions[ b * 3 ],
							positions[ b * 3 + 1 ],
							positions[ b * 3 + 2 ]
						);
						vC.set(
							positions[ c * 3 ],
							positions[ c * 3 + 1 ],
							positions[ c * 3 + 2 ]
						);

						if ( material.side === THREE.BackSide ) {

							var intersectionPoint = localRay.intersectTriangle( vC, vB, vA, true );

						} else {

							var intersectionPoint = localRay.intersectTriangle( vA, vB, vC, material.side !== THREE.DoubleSide );

						}

						if ( intersectionPoint === null ) continue;

						intersectionPoint.applyMatrix4( object.matrixWorld );

						var distance = raycaster.ray.origin.distanceTo( intersectionPoint );

						if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue;

						intersects.push( {

							distance: distance,
							point: intersectionPoint,
							indices: [a, b, c],
							face: null,
							faceIndex: null,
							object: object

						} );

					}

				}

			} else if ( geometry instanceof THREE.Geometry ) {

				var isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
				var objectMaterials = isFaceMaterial === true ? object.material.materials : null;

				var a, b, c, d;
				var precision = raycaster.precision;

				var vertices = geometry.vertices;

				for ( var f = 0, fl = geometry.faces.length; f < fl; f ++ ) {

					var face = geometry.faces[ f ];

					var material = isFaceMaterial === true ? objectMaterials[ face.materialIndex ] : object.material;

					if ( material === undefined ) continue;

					a = vertices[ face.a ];
					b = vertices[ face.b ];
					c = vertices[ face.c ];

					if ( material.morphTargets === true ) {

						var morphTargets = geometry.morphTargets;
						var morphInfluences = object.morphTargetInfluences;

						vA.set( 0, 0, 0 );
						vB.set( 0, 0, 0 );
						vC.set( 0, 0, 0 );

						for ( var t = 0, tl = morphTargets.length; t < tl; t ++ ) {

							var influence = morphInfluences[ t ];

							if ( influence === 0 ) continue;

							var targets = morphTargets[ t ].vertices;

							vA.x += ( targets[ face.a ].x - a.x ) * influence;
							vA.y += ( targets[ face.a ].y - a.y ) * influence;
							vA.z += ( targets[ face.a ].z - a.z ) * influence;

							vB.x += ( targets[ face.b ].x - b.x ) * influence;
							vB.y += ( targets[ face.b ].y - b.y ) * influence;
							vB.z += ( targets[ face.b ].z - b.z ) * influence;

							vC.x += ( targets[ face.c ].x - c.x ) * influence;
							vC.y += ( targets[ face.c ].y - c.y ) * influence;
							vC.z += ( targets[ face.c ].z - c.z ) * influence;

						}

						vA.add( a );
						vB.add( b );
						vC.add( c );

						a = vA;
						b = vB;
						c = vC;

					}

					if ( material.side === THREE.BackSide ) {

						var intersectionPoint = localRay.intersectTriangle( c, b, a, true );

					} else {

						var intersectionPoint = localRay.intersectTriangle( a, b, c, material.side !== THREE.DoubleSide );

					}

					if ( intersectionPoint === null ) continue;

					intersectionPoint.applyMatrix4( object.matrixWorld );

					var distance = raycaster.ray.origin.distanceTo( intersectionPoint );

					if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue;

					intersects.push( {

						distance: distance,
						point: intersectionPoint,
						face: face,
						faceIndex: f,
						object: object

					} );

				}

			}

		} else if ( object instanceof THREE.Line ) {

			var precision = raycaster.linePrecision;
			var precisionSq = precision * precision;

			var geometry = object.geometry;

			if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();

			// Checking boundingSphere distance to ray

			sphere.copy( geometry.boundingSphere );
			sphere.applyMatrix4( object.matrixWorld );

			if ( raycaster.ray.isIntersectionSphere( sphere ) === false ) {

				return intersects;

			}

			inverseMatrix.getInverse( object.matrixWorld );
			localRay.copy( raycaster.ray ).applyMatrix4( inverseMatrix );

			/* if ( geometry instanceof THREE.BufferGeometry ) {

			} else */ if ( geometry instanceof THREE.Geometry ) {

				var vertices = geometry.vertices;
				var nbVertices = vertices.length;
				var interSegment = new THREE.Vector3();
				var interRay = new THREE.Vector3();
				var step = object.type === THREE.LineStrip ? 1 : 2;

				for ( var i = 0; i < nbVertices - 1; i = i + step ) {

					var distSq = localRay.distanceSqToSegment( vertices[ i ], vertices[ i + 1 ], interRay, interSegment );

					if ( distSq > precisionSq ) continue;

					var distance = localRay.origin.distanceTo( interRay );

					if ( distance < raycaster.near || distance > raycaster.far ) continue;

					intersects.push( {

						distance: distance,
						// What do we want? intersection point on the ray or on the segment??
						// point: raycaster.ray.at( distance ),
						point: interSegment.clone().applyMatrix4( object.matrixWorld ),
						face: null,
						faceIndex: null,
						object: object

					} );

				}

			}

		}

	};

	var intersectDescendants = function ( object, raycaster, intersects ) {

		var descendants = object.getDescendants();

		for ( var i = 0, l = descendants.length; i < l; i ++ ) {

			intersectObject( descendants[ i ], raycaster, intersects );

		}
	};

	//

	THREE.Raycaster.prototype.precision = 0.0001;
	THREE.Raycaster.prototype.linePrecision = 1;

	THREE.Raycaster.prototype.set = function ( origin, direction ) {

		this.ray.set( origin, direction );
		// direction is assumed to be normalized (for accurate distance calculations)

	};

	THREE.Raycaster.prototype.intersectObject = function ( object, recursive ) {

		var intersects = [];

		if ( recursive === true ) {

			intersectDescendants( object, this, intersects );

		}

		intersectObject( object, this, intersects );

		intersects.sort( descSort );

		return intersects;

	};

	THREE.Raycaster.prototype.intersectObjects = function ( objects, recursive ) {

		var intersects = [];

		for ( var i = 0, l = objects.length; i < l; i ++ ) {

			intersectObject( objects[ i ], this, intersects );

			if ( recursive === true ) {

				intersectDescendants( objects[ i ], this, intersects );

			}

		}

		intersects.sort( descSort );

		return intersects;

	};

}( THREE ) );
<commit_msg>Raycaster: Support for indexed BufferGeometry with no offsets.<commit_after>/**
 * @author mrdoob / http://mrdoob.com/
 * @author bhouston / http://exocortex.com/
 * @author stephomi / http://stephaneginier.com/
 */

( function ( THREE ) {

	THREE.Raycaster = function ( origin, direction, near, far ) {

		this.ray = new THREE.Ray( origin, direction );
		// direction is assumed to be normalized (for accurate distance calculations)

		this.near = near || 0;
		this.far = far || Infinity;

	};

	var sphere = new THREE.Sphere();
	var localRay = new THREE.Ray();
	var facePlane = new THREE.Plane();
	var intersectPoint = new THREE.Vector3();
	var matrixPosition = new THREE.Vector3();

	var inverseMatrix = new THREE.Matrix4();

	var descSort = function ( a, b ) {

		return a.distance - b.distance;

	};

	var vA = new THREE.Vector3();
	var vB = new THREE.Vector3();
	var vC = new THREE.Vector3();

	var intersectObject = function ( object, raycaster, intersects ) {

		if ( object instanceof THREE.Sprite ) {

			matrixPosition.setFromMatrixPosition( object.matrixWorld );

			var distance = raycaster.ray.distanceToPoint( matrixPosition );

			if ( distance > object.scale.x ) {

				return intersects;

			}

			intersects.push( {

				distance: distance,
				point: object.position,
				face: null,
				object: object

			} );

		} else if ( object instanceof THREE.LOD ) {

			matrixPosition.setFromMatrixPosition( object.matrixWorld );
			var distance = raycaster.ray.origin.distanceTo( matrixPosition );

			intersectObject( object.getObjectForDistance( distance ), raycaster, intersects );

		} else if ( object instanceof THREE.Mesh ) {

			var geometry = object.geometry;

			// Checking boundingSphere distance to ray

			if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();

			sphere.copy( geometry.boundingSphere );
			sphere.applyMatrix4( object.matrixWorld );

			if ( raycaster.ray.isIntersectionSphere( sphere ) === false ) {

				return intersects;

			}

			// Check boundingBox before continuing

			inverseMatrix.getInverse( object.matrixWorld );
			localRay.copy( raycaster.ray ).applyMatrix4( inverseMatrix );

			if ( geometry.boundingBox !== null ) {

				if ( localRay.isIntersectionBox( geometry.boundingBox ) === false )  {

					return intersects;

				}

			}

			if ( geometry instanceof THREE.BufferGeometry ) {

				var material = object.material;

				if ( material === undefined ) return intersects;

				var attributes = geometry.attributes;

				var a, b, c;
				var precision = raycaster.precision;

				if ( attributes.index !== undefined ) {

					var indices = attributes.index.array;
					var positions = attributes.position.array;
					var offsets = geometry.offsets;

					if ( offsets.length === 0 ) {

						offsets = [ { start: 0, count: positions.length, index: 0 } ];

					}

					for ( var oi = 0, ol = offsets.length; oi < ol; ++oi ) {

						var start = offsets[ oi ].start;
						var count = offsets[ oi ].count;
						var index = offsets[ oi ].index;

						for ( var i = start, il = start + count; i < il; i += 3 ) {

							a = index + indices[ i ];
							b = index + indices[ i + 1 ];
							c = index + indices[ i + 2 ];

							vA.set(
								positions[ a * 3 ],
								positions[ a * 3 + 1 ],
								positions[ a * 3 + 2 ]
							);
							vB.set(
								positions[ b * 3 ],
								positions[ b * 3 + 1 ],
								positions[ b * 3 + 2 ]
							);
							vC.set(
								positions[ c * 3 ],
								positions[ c * 3 + 1 ],
								positions[ c * 3 + 2 ]
							);

							if ( material.side === THREE.BackSide ) {

								var intersectionPoint = localRay.intersectTriangle( vC, vB, vA, true );

							} else {

								var intersectionPoint = localRay.intersectTriangle( vA, vB, vC, material.side !== THREE.DoubleSide );

							}

							if ( intersectionPoint === null ) continue;

							intersectionPoint.applyMatrix4( object.matrixWorld );

							var distance = raycaster.ray.origin.distanceTo( intersectionPoint );

							if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue;

							intersects.push( {

								distance: distance,
								point: intersectionPoint,
								indices: [a, b, c],
								face: null,
								faceIndex: null,
								object: object

							} );

						}

					}

				} else {

					var offsets = geometry.offsets;
					var positions = attributes.position.array;

					for ( var i = 0, il = attributes.position.array.length; i < il; i += 3 ) {

						a = i;
						b = i + 1;
						c = i + 2;

						vA.set(
							positions[ a * 3 ],
							positions[ a * 3 + 1 ],
							positions[ a * 3 + 2 ]
						);
						vB.set(
							positions[ b * 3 ],
							positions[ b * 3 + 1 ],
							positions[ b * 3 + 2 ]
						);
						vC.set(
							positions[ c * 3 ],
							positions[ c * 3 + 1 ],
							positions[ c * 3 + 2 ]
						);

						if ( material.side === THREE.BackSide ) {

							var intersectionPoint = localRay.intersectTriangle( vC, vB, vA, true );

						} else {

							var intersectionPoint = localRay.intersectTriangle( vA, vB, vC, material.side !== THREE.DoubleSide );

						}

						if ( intersectionPoint === null ) continue;

						intersectionPoint.applyMatrix4( object.matrixWorld );

						var distance = raycaster.ray.origin.distanceTo( intersectionPoint );

						if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue;

						intersects.push( {

							distance: distance,
							point: intersectionPoint,
							indices: [a, b, c],
							face: null,
							faceIndex: null,
							object: object

						} );

					}

				}

			} else if ( geometry instanceof THREE.Geometry ) {

				var isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
				var objectMaterials = isFaceMaterial === true ? object.material.materials : null;

				var a, b, c, d;
				var precision = raycaster.precision;

				var vertices = geometry.vertices;

				for ( var f = 0, fl = geometry.faces.length; f < fl; f ++ ) {

					var face = geometry.faces[ f ];

					var material = isFaceMaterial === true ? objectMaterials[ face.materialIndex ] : object.material;

					if ( material === undefined ) continue;

					a = vertices[ face.a ];
					b = vertices[ face.b ];
					c = vertices[ face.c ];

					if ( material.morphTargets === true ) {

						var morphTargets = geometry.morphTargets;
						var morphInfluences = object.morphTargetInfluences;

						vA.set( 0, 0, 0 );
						vB.set( 0, 0, 0 );
						vC.set( 0, 0, 0 );

						for ( var t = 0, tl = morphTargets.length; t < tl; t ++ ) {

							var influence = morphInfluences[ t ];

							if ( influence === 0 ) continue;

							var targets = morphTargets[ t ].vertices;

							vA.x += ( targets[ face.a ].x - a.x ) * influence;
							vA.y += ( targets[ face.a ].y - a.y ) * influence;
							vA.z += ( targets[ face.a ].z - a.z ) * influence;

							vB.x += ( targets[ face.b ].x - b.x ) * influence;
							vB.y += ( targets[ face.b ].y - b.y ) * influence;
							vB.z += ( targets[ face.b ].z - b.z ) * influence;

							vC.x += ( targets[ face.c ].x - c.x ) * influence;
							vC.y += ( targets[ face.c ].y - c.y ) * influence;
							vC.z += ( targets[ face.c ].z - c.z ) * influence;

						}

						vA.add( a );
						vB.add( b );
						vC.add( c );

						a = vA;
						b = vB;
						c = vC;

					}

					if ( material.side === THREE.BackSide ) {

						var intersectionPoint = localRay.intersectTriangle( c, b, a, true );

					} else {

						var intersectionPoint = localRay.intersectTriangle( a, b, c, material.side !== THREE.DoubleSide );

					}

					if ( intersectionPoint === null ) continue;

					intersectionPoint.applyMatrix4( object.matrixWorld );

					var distance = raycaster.ray.origin.distanceTo( intersectionPoint );

					if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue;

					intersects.push( {

						distance: distance,
						point: intersectionPoint,
						face: face,
						faceIndex: f,
						object: object

					} );

				}

			}

		} else if ( object instanceof THREE.Line ) {

			var precision = raycaster.linePrecision;
			var precisionSq = precision * precision;

			var geometry = object.geometry;

			if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();

			// Checking boundingSphere distance to ray

			sphere.copy( geometry.boundingSphere );
			sphere.applyMatrix4( object.matrixWorld );

			if ( raycaster.ray.isIntersectionSphere( sphere ) === false ) {

				return intersects;

			}

			inverseMatrix.getInverse( object.matrixWorld );
			localRay.copy( raycaster.ray ).applyMatrix4( inverseMatrix );

			/* if ( geometry instanceof THREE.BufferGeometry ) {

			} else */ if ( geometry instanceof THREE.Geometry ) {

				var vertices = geometry.vertices;
				var nbVertices = vertices.length;
				var interSegment = new THREE.Vector3();
				var interRay = new THREE.Vector3();
				var step = object.type === THREE.LineStrip ? 1 : 2;

				for ( var i = 0; i < nbVertices - 1; i = i + step ) {

					var distSq = localRay.distanceSqToSegment( vertices[ i ], vertices[ i + 1 ], interRay, interSegment );

					if ( distSq > precisionSq ) continue;

					var distance = localRay.origin.distanceTo( interRay );

					if ( distance < raycaster.near || distance > raycaster.far ) continue;

					intersects.push( {

						distance: distance,
						// What do we want? intersection point on the ray or on the segment??
						// point: raycaster.ray.at( distance ),
						point: interSegment.clone().applyMatrix4( object.matrixWorld ),
						face: null,
						faceIndex: null,
						object: object

					} );

				}

			}

		}

	};

	var intersectDescendants = function ( object, raycaster, intersects ) {

		var descendants = object.getDescendants();

		for ( var i = 0, l = descendants.length; i < l; i ++ ) {

			intersectObject( descendants[ i ], raycaster, intersects );

		}
	};

	//

	THREE.Raycaster.prototype.precision = 0.0001;
	THREE.Raycaster.prototype.linePrecision = 1;

	THREE.Raycaster.prototype.set = function ( origin, direction ) {

		this.ray.set( origin, direction );
		// direction is assumed to be normalized (for accurate distance calculations)

	};

	THREE.Raycaster.prototype.intersectObject = function ( object, recursive ) {

		var intersects = [];

		if ( recursive === true ) {

			intersectDescendants( object, this, intersects );

		}

		intersectObject( object, this, intersects );

		intersects.sort( descSort );

		return intersects;

	};

	THREE.Raycaster.prototype.intersectObjects = function ( objects, recursive ) {

		var intersects = [];

		for ( var i = 0, l = objects.length; i < l; i ++ ) {

			intersectObject( objects[ i ], this, intersects );

			if ( recursive === true ) {

				intersectDescendants( objects[ i ], this, intersects );

			}

		}

		intersects.sort( descSort );

		return intersects;

	};

}( THREE ) );
<|endoftext|>


<commit_before>define(['chart-pings', 'common'], function(pings, common) {
    var element = d3.select('#chart').append('svg:svg')
    var elementHeight = parseInt(element.style('height'), 10)

    var xScale = d3.scale.linear()

    var onResize = function() {
        var elementWidth = parseInt(element.style('width'), 10)
        pings.setMax(elementWidth / common.barWidth) // Yes, this a float
        xScale.range([0, elementWidth])
    }
    window.addEventListener('resize', onResize)
    onResize()

    var yScale = function(ping) {
        // 0 -> 0, normalPing -> .1, ∞ -> 1
        var normalPing = 200
        var normalizedPing = Math.atan(ping / normalPing / 10) * 2 / Math.PI

        return normalizedPing * elementHeight
    }

    var selections = (function() {
        var entered, updated, exited
        return {
            entered: function() { return entered },
            updated: function() { return updated },
            exited: function() { return exited },
            update: function() {
                updated = element.selectAll('rect')
                    .data(pings.all(), function(ping) { return ping.start() })
                entered = updated.enter()
                exited = updated.exit()
            }
        }
    })()

    selections.update()

    d3.timer(function() {
        ;[selections.updated(), selections.exited()].forEach(function(selection) {
            selection
                .attr('y', function(ping) { return elementHeight - yScale(ping.lag()) })
                .attr('height', function(ping) { return yScale(ping.lag()) })
                .style('fill-opacity', function(ping) { return ping.end() ? 1 : 0.7 })

            var now = Date.now()
            xScale.domain([now - pings.max() * common.pingInterval, now])
            selection.attr('x', function(ping) { return xScale(ping.start()) })
        })
    })

    return {
        addPing: function() {
            var ping = pings.add()

            selections.update()

            selections.entered().append('svg:rect').attr('width', common.barWidth)

            selections.exited().each(function(ping) {
                if (this.getAttribute('data-exiting')) return
                d3.select(this).transition().duration(common.pingInterval * 2).remove()
                this.setAttribute('data-exiting', true)
            })

            return ping
        }
    }
})
<commit_msg>Reduce work inside the animation loop<commit_after>define(['chart-pings', 'common'], function(pings, common) {
    var element = d3.select('#chart').append('svg:svg')
    var elementHeight = parseInt(element.style('height'), 10)

    var xScale = d3.scale.linear()

    var onResize = function() {
        var elementWidth = parseInt(element.style('width'), 10)
        pings.setMax(elementWidth / common.barWidth) // Yes, this a float
        xScale.range([0, elementWidth])
    }
    window.addEventListener('resize', onResize)
    onResize()

    var yScale = function(lag) {
        // 0 -> 0, normalLag -> .1, ∞ -> 1
        var normalLag = 200
        var normalizedLag = Math.atan(lag / normalLag / 10) * 2 / Math.PI

        return normalizedLag * elementHeight
    }

    var selections = (function() {
        var entered, updated, exited
        return {
            entered: function() { return entered },
            updated: function() { return updated },
            exited: function() { return exited },
            update: function() {
                var data = pings.all().map(function(ping) {
                    return {ping: ping, exiting: false, ended: false}
                })
                updated = element.selectAll('rect')
                    .data(data, function(datum) { return datum.ping.start() })
                entered = updated.enter()
                exited = updated.exit()
            }
        }
    })()

    selections.update()

    d3.timer(function() {
        ;[selections.updated(), selections.exited()].forEach(function(selection) {
            selection.each(function(datum) {
                if (datum.ended) return
                if (datum.ping.end()) datum.ended = true
                d3.select(this)
                    .attr('y', function() { return elementHeight - yScale(datum.ping.lag()) })
                    .attr('height', function() { return yScale(datum.ping.lag()) })
                    .style('fill-opacity', function() { return datum.ping.end() ? 1 : 0.7 })
            })

            var now = Date.now()
            xScale.domain([now - pings.max() * common.pingInterval, now])
            selection.attr('x', function(datum) { return xScale(datum.ping.start()) })
        })
    })

    return {
        addPing: function() {
            var ping = pings.add()

            selections.update()

            selections.entered().append('svg:rect').attr('width', common.barWidth)

            selections.exited().each(function(datum) {
                if (datum.exiting) return
                datum.exiting = true
                d3.select(this).transition().duration(common.pingInterval * 2).remove()
            })

            return ping
        }
    }
})
<|endoftext|>


<commit_before>// History-easy.js version 1.02 by Michael Romanovsky. License: public domain.

// If you find this useful and would like to leave a financial gratuity, you can use this link:
// https://www.gittip.com/agamemnus/

function history_control_object (settings) {
 var history_main = this
 if (typeof settings == "undefined") settings = {}

 history_main.overwrite_first_state = ((typeof settings.overwrite_first_state != "undefined") && (settings.overwrite_first_state == false)) ? false : true
 var var_name                       = (typeof settings.var_name      != "undefined") ? settings.var_name      : 'page'
 history_main.base_filename         = (typeof settings.base_filename != "undefined") ? settings.base_filename : ""
 history_main.onbeforestatechange   = settings.onbeforestatechange // Function to run before the history state change. If it does run the callback (3rd parameter), no history state change is attempted.
 history_main.onstatechange         = settings.onstatechange       // Function to run after the history state change.
 history_main.initial_page          = settings.initial_page        // The initial page (default variable "page") that history should be at.
 history_main.app_url_vars          = settings.app_url_vars        // A set of variables that store the current history state.
 history_main.can_do_popstate       = settings.can_do_popstate     // If defined, accept or reject a popstate by returning true or false.
 history_main.current_state = {}

 var extras = {}
 var next_title = undefined, next_url = undefined, next_callback = undefined

 var first_load = true
 var history_control_locked = false

 // Add a pop state event listener.
 window.addEventListener ('popstate', function (evt) {
  if (history_control_locked || ((typeof history_main.can_do_popstate != "undefined") && (!history_main.can_do_popstate(evt.state)))) {
   set_page_state (history_main.current_state, undefined, false, true)
   return
  }
  history_control_locked = true
  if (evt.state == null) return; set_page_state (evt.state, undefined, false)
 })

 function set_page_state (new_state, settings, record_history, ignore_history) {
  // Update history_main.app_url_vars to match new_state.
  if (typeof history_main.app_url_vars != "undefined") {
   for (var i in history_main.app_url_vars) {delete (history_main.app_url_vars[i])}
   merge_into (history_main.app_url_vars, new_state)
  }

  var hash = formUrlVars (new_state, {record_undefined_values: false})

  // Set the title, url, and callback, if they exist in settings.
  if (typeof settings != "undefined") {
   if (typeof settings.title    != "undefined") history_main.title    = settings.title
   if (typeof settings.url      != "undefined") history_main.url      = settings.url
   if (typeof settings.callback != "undefined") history_main.callback = settings.callback

   if (typeof history_main.url == "undefined") {
    history_main.url = location.protocol + '//' + location.host + location.pathname + history_main.base_filename
    history_main.url += hash
   }
  }

  if (record_history == true) {
   extras[hash]          = {}
   extras[hash].title    = history_main.title
   extras[hash].url      = history_main.url
   extras[hash].callback = history_main.callback
  } else {
   history_main[var_name] = new_state[var_name]
  }

  // Set temporary variables.
  var current_title    = extras[hash].title
  var current_url      = extras[hash].url
  var current_callback = extras[hash].callback

  // Clear history_main.url and history_main.callback.
  delete (history_main.url); delete (history_main.callback)

  // Set the title and run the HTML5 History API pushState / replaceState function.
  document.title = (typeof current_title != "undefined") ? current_title : ""
  if ((record_history == true) || (!!ignore_history)) history[(first_load ? 'replace' : 'push') + 'State'] (new_state, current_title, current_url)

  // Update the current state variable.
  history_main.current_state = new_state

  if (first_load == true) first_load = false

  // Run the ".onstatechange" function property if it exists, then run the "current_callback" function. Otherwise, just run the "current_callback" function.
  // Don't run anything if "ignore_history" is true.
  if (!ignore_history) {
   if (typeof history_main.onstatechange != "undefined") {
    history_main.onstatechange (new_state, function () {
    history_control_locked = false
    if (typeof current_callback != "undefined") current_callback ()})
   } else {
     history_control_locked = false
    if (typeof current_callback != "undefined") current_callback ()
   }
  }
 }

 history_main.load_page = function (new_state, settings) {
  history_control_locked = true
  if (typeof new_state == "undefined") new_state = {}
  if (typeof settings  == "undefined") settings  = {}
  new_state = shallowcopy (new_state)
  settings  = shallowcopy (settings)
  // On first load, run a destructive function that merges the contents window.location with "history_main.app_url_vars".
  // On first load, set the initial page variable's (default: "page") value.
  if ((first_load == true) && (history_main.overwrite_first_state == true)) {
   getUrlVars (new_state)
   if (typeof history_main[var_name] == "undefined") history_main[var_name] = history_main.initial_page
  }
  if (typeof new_state[var_name] == "undefined") new_state[var_name] = history_main[var_name]

  // Run the .onbeforestatechange function property if it exists.
  if (typeof history_main.onbeforestatechange != "undefined") {
   history_main.onbeforestatechange (new_state, settings, function () {set_page_state (new_state, settings, true)})
  } else {
   set_page_state (new_state, settings, true)
  }
 }

 // Form a GET URL string from an array.
 function formUrlVars (variable_list, options) {
  if (typeof options                         == "undefined") options = {}
  if (typeof options.record_undefined_values == "undefined") options.record_undefined_values = true
  var return_value = ""
  for (var i in variable_list) {
  if ((typeof variable_list[i] != "undefined") || (options.record_undefined_values == true)) return_value += "&" + i + "=" + variable_list[i]}
  if (return_value != "") return_value = "?" + return_value.slice(1, return_value.length)
  return return_value
 }

 // Get URL variables from window.location and put them into variable_object as key/value pairs. Returns variable_object.
 function getUrlVars (variable_object) {
  if ((typeof variable_object != "object") || (variable_object == null)) var variable_object = {}
  var variable_list = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&')
  var curlen = variable_list.length
  for (var i = 0; i < curlen; i++) {
   var current_variable = variable_list[i].split('=')
   if (typeof current_variable[1] == "undefined") continue
   variable_object[current_variable[0]] = decodeURIComponent(current_variable[1])
  }
  return variable_object
 }

 // Merge the source into the target.
 function merge_into (target, source) {
  if (typeof source == "undefined") return target
  // Overrides any keys in the target object with keys in the source object.
  for (var property in source) {target[property] = source[property]}
  return target
 }

 // Shallow-copy an object.
 function shallowcopy (source) {
  if ((typeof source !== 'object') || (source == null)) return source
  var copy = ((source instanceof Array) ? [] : {})
  for (var i in source) {
   var property = source[i]
   if ((typeof property != 'object') || (!(property instanceof Array))) {copy[i] = property; continue}
   copy[i] = property.slice ()
  }
  return copy
 }
}
<commit_msg>Control lock.<commit_after>// History-easy.js version 1.02 by Michael Romanovsky. License: public domain.

// If you find this useful and would like to leave a financial gratuity, you can use this link:
// https://www.gittip.com/agamemnus/

function history_control_object (settings) {
 var history_main = this
 if (typeof settings == "undefined") settings = {}

 history_main.overwrite_first_state = ((typeof settings.overwrite_first_state != "undefined") && (settings.overwrite_first_state == false)) ? false : true
 var var_name                       = (typeof settings.var_name      != "undefined") ? settings.var_name      : 'page'
 history_main.base_filename         = (typeof settings.base_filename != "undefined") ? settings.base_filename : ""
 history_main.onbeforestatechange   = settings.onbeforestatechange // Function to run before the history state change. If it does run the callback (3rd parameter), no history state change is attempted.
 history_main.onstatechange         = settings.onstatechange       // Function to run after the history state change.
 history_main.initial_page          = settings.initial_page        // The initial page (default variable "page") that history should be at.
 history_main.app_url_vars          = settings.app_url_vars        // A set of variables that store the current history state.
 history_main.can_do_popstate       = settings.can_do_popstate     // If defined, accept or reject a popstate by returning true or false.
 history_main.current_state = {}

 var extras = {}
 var next_title = undefined, next_url = undefined, next_callback = undefined

 var first_load = true
 var history_control_locked = false

 // Add a pop state event listener.
 window.addEventListener ('popstate', function (evt) {
  if (history_control_locked || ((typeof history_main.can_do_popstate != "undefined") && (!history_main.can_do_popstate(evt.state)))) {
   set_page_state (history_main.current_state, undefined, false, true)
   return
  }
  history_control_locked = true
  if (evt.state == null) return; set_page_state (evt.state, undefined, false)
 })

 function set_page_state (new_state, settings, record_history, ignore_history) {
  // Update history_main.app_url_vars to match new_state.
  if (typeof history_main.app_url_vars != "undefined") {
   for (var i in history_main.app_url_vars) {delete (history_main.app_url_vars[i])}
   merge_into (history_main.app_url_vars, new_state)
  }

  var hash = formUrlVars (new_state, {record_undefined_values: false})

  // Set the title, url, and callback, if they exist in settings.
  if (typeof settings != "undefined") {
   if (typeof settings.title    != "undefined") history_main.title    = settings.title
   if (typeof settings.url      != "undefined") history_main.url      = settings.url
   if (typeof settings.callback != "undefined") history_main.callback = settings.callback

   if (typeof history_main.url == "undefined") {
    history_main.url = location.protocol + '//' + location.host + location.pathname + history_main.base_filename
    history_main.url += hash
   }
  }

  if (record_history == true) {
   extras[hash]          = {}
   extras[hash].title    = history_main.title
   extras[hash].url      = history_main.url
   extras[hash].callback = history_main.callback
  } else {
   history_main[var_name] = new_state[var_name]
  }

  // Set temporary variables.
  var current_title    = extras[hash].title
  var current_url      = extras[hash].url
  var current_callback = extras[hash].callback

  // Clear history_main.url and history_main.callback.
  delete (history_main.url); delete (history_main.callback)

  // Set the title and run the HTML5 History API pushState / replaceState function.
  document.title = (typeof current_title != "undefined") ? current_title : ""
  if ((record_history == true) || (!!ignore_history)) history[(first_load ? 'replace' : 'push') + 'State'] (new_state, current_title, current_url)

  // Update the current state variable.
  history_main.current_state = new_state

  if (first_load == true) first_load = false

  // Run the ".onstatechange" function property if it exists, then run the "current_callback" function. Otherwise, just run the "current_callback" function.
  // Don't run anything if "ignore_history" is true.
  if (!ignore_history) {
   if (typeof history_main.onstatechange != "undefined") {
    history_main.onstatechange (new_state, function () {
    history_control_locked = false
    if (typeof current_callback != "undefined") current_callback ()})
   } else {
     history_control_locked = false
    if (typeof current_callback != "undefined") current_callback ()
   }
  }
 }

 history_main.load_page = function (new_state, settings) {
  if (history_control_locked) return
  history_control_locked = true
  if (typeof new_state == "undefined") new_state = {}
  if (typeof settings  == "undefined") settings  = {}
  new_state = shallowcopy (new_state)
  settings  = shallowcopy (settings)
  // On first load, run a destructive function that merges the contents window.location with "history_main.app_url_vars".
  // On first load, set the initial page variable's (default: "page") value.
  if ((first_load == true) && (history_main.overwrite_first_state == true)) {
   getUrlVars (new_state)
   if (typeof history_main[var_name] == "undefined") history_main[var_name] = history_main.initial_page
  }
  if (typeof new_state[var_name] == "undefined") new_state[var_name] = history_main[var_name]

  // Run the .onbeforestatechange function property if it exists.
  if (typeof history_main.onbeforestatechange != "undefined") {
   history_main.onbeforestatechange (new_state, settings, function () {set_page_state (new_state, settings, true)})
  } else {
   set_page_state (new_state, settings, true)
  }
 }

 // Form a GET URL string from an array.
 function formUrlVars (variable_list, options) {
  if (typeof options                         == "undefined") options = {}
  if (typeof options.record_undefined_values == "undefined") options.record_undefined_values = true
  var return_value = ""
  for (var i in variable_list) {
  if ((typeof variable_list[i] != "undefined") || (options.record_undefined_values == true)) return_value += "&" + i + "=" + variable_list[i]}
  if (return_value != "") return_value = "?" + return_value.slice(1, return_value.length)
  return return_value
 }

 // Get URL variables from window.location and put them into variable_object as key/value pairs. Returns variable_object.
 function getUrlVars (variable_object) {
  if ((typeof variable_object != "object") || (variable_object == null)) var variable_object = {}
  var variable_list = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&')
  var curlen = variable_list.length
  for (var i = 0; i < curlen; i++) {
   var current_variable = variable_list[i].split('=')
   if (typeof current_variable[1] == "undefined") continue
   variable_object[current_variable[0]] = decodeURIComponent(current_variable[1])
  }
  return variable_object
 }

 // Merge the source into the target.
 function merge_into (target, source) {
  if (typeof source == "undefined") return target
  // Overrides any keys in the target object with keys in the source object.
  for (var property in source) {target[property] = source[property]}
  return target
 }

 // Shallow-copy an object.
 function shallowcopy (source) {
  if ((typeof source !== 'object') || (source == null)) return source
  var copy = ((source instanceof Array) ? [] : {})
  for (var i in source) {
   var property = source[i]
   if ((typeof property != 'object') || (!(property instanceof Array))) {copy[i] = property; continue}
   copy[i] = property.slice ()
  }
  return copy
 }
}
<|endoftext|>


<commit_before>function welcomeAnimation() {
    setTimeout(function () {
        var leftDiv = document.getElementById('leftSide');
        var rightDiv = document.getElementById('rightSide');
        var gifHolder = document.getElementById('welcomeGifHolder');
        gifHolder.className += ' animated zoomOut';
        setTimeout(function () {
            gifHolder.remove();
            leftDiv.className = 'animated slideOutLeft';
            rightDiv.className = 'animated slideOutRight';
        }, 500);
    }, 1500);
}
// welcomeAnimation();

// document.getElementById('chatbox').style.bottom = document.getElementById('footer').offsetHeight + 'px';

$(document).ready(function () {
    setTimeout(function () {
        $('#chatbox').removeClass('bounce');
        $('#chatbox').removeClass('infinite');
    }, 2000); //2 segundos para fazer a animacao duas vezes
    $('#chatbox').click(function () {
        $('#chatbox').removeClass('infinite');
        $('#chatbox').removeClass('bounce');
    });

    $('#dismiss-historico').click(function () {
        $('#historico').addClass('animated bounceOutDown');
        // $('#row-historico').html('');
    })
    $('#dismiss-triagem').click(function () {
        // $('#row-info').html('');
        $('#triagem').addClass('animated bounceOutDown');
    })
    $('#dismiss-atendimento').click(function () {
        // $('#row-info').html('');
        $('#atendimento').addClass('animated bounceOutDown');
        $('#row-espera').removeClass('hide');
        setTimeout(function(){
            window.location('/index');
        },5000);
    })

    $('#dismiss-consulta').click(function () {
        // $('#row-info').html('');
        $('#consulta').addClass('animated bounceOutDown');
    })
     $('.collapsible').collapsible();
    $('.modal').modal({
        dismissible: false, // Modal can be dismissed by clicking outside of the modal
        opacity: .5, // Opacity of modal background
        inDuration: 300, // Transition in duration
        outDuration: 200, // Transition out duration
        startingTop: '4%', // Starting top style attribute
        endingTop: '10%', // Ending top style attribute
        ready: function (modal, trigger) { // Callback for Modal open. Modal and trigger parameters available.
            // alert("Ready");
            // console.log(modal, trigger);
        },
        complete: function () {
            // alert('Closed');
        } // Callback for Modal close
    });

});

<commit_msg>Window refresh after atendimento<commit_after>function welcomeAnimation() {
    setTimeout(function () {
        var leftDiv = document.getElementById('leftSide');
        var rightDiv = document.getElementById('rightSide');
        var gifHolder = document.getElementById('welcomeGifHolder');
        gifHolder.className += ' animated zoomOut';
        setTimeout(function () {
            gifHolder.remove();
            leftDiv.className = 'animated slideOutLeft';
            rightDiv.className = 'animated slideOutRight';
        }, 500);
    }, 1500);
}
// welcomeAnimation();

// document.getElementById('chatbox').style.bottom = document.getElementById('footer').offsetHeight + 'px';

$(document).ready(function () {
    setTimeout(function () {
        $('#chatbox').removeClass('bounce');
        $('#chatbox').removeClass('infinite');
    }, 2000); //2 segundos para fazer a animacao duas vezes
    $('#chatbox').click(function () {
        $('#chatbox').removeClass('infinite');
        $('#chatbox').removeClass('bounce');
    });

    $('#dismiss-historico').click(function () {
        $('#historico').addClass('animated bounceOutDown');
        // $('#row-historico').html('');
    })
    $('#dismiss-triagem').click(function () {
        // $('#row-info').html('');
        $('#triagem').addClass('animated bounceOutDown');
    })
    $('#dismiss-atendimento').click(function () {
        // $('#row-info').html('');
        $('#atendimento').addClass('animated bounceOutDown');
        $('#row-espera').removeClass('hide');

        setTimeout(function(){
            window.location.href = '/index';
        },5000);
    })

    $('#dismiss-consulta').click(function () {
        // $('#row-info').html('');
        $('#consulta').addClass('animated bounceOutDown');
    })
     $('.collapsible').collapsible();
    $('.modal').modal({
        dismissible: false, // Modal can be dismissed by clicking outside of the modal
        opacity: .5, // Opacity of modal background
        inDuration: 300, // Transition in duration
        outDuration: 200, // Transition out duration
        startingTop: '4%', // Starting top style attribute
        endingTop: '10%', // Ending top style attribute
        ready: function (modal, trigger) { // Callback for Modal open. Modal and trigger parameters available.
            // alert("Ready");
            // console.log(modal, trigger);
        },
        complete: function () {
            // alert('Closed');
        } // Callback for Modal close
    });

});

<|endoftext|>


<commit_before>var Mmmvc = (function(my) {
  var actions = {
    add      : function() {},
    remove   : function() {},
    update   : function() {},
    populate : function() {},
    empty    : function() {}
  },
  model = {};

  function sync(hash_with_unique_keys) {
    var add_items = _.omit(hash_with_unique_keys, _.keys(model));
    var remove_items = _.omit(model, _.keys(hash_with_unique_keys));

    _.each(_.pick(model, _.keys(hash_with_unique_keys)), function(v,k) {
      _.each(_.keys(model[k]), function(key) {
        if (model[k][key] != hash_with_unique_keys[k][key]) {
          model[k] = hash_with_unique_keys[k];
          actions['update'](k,model[k]);
          return;
        }
      });
    });

    if (_.size(hash_with_unique_keys) == 0 && _.size(model) != 0) { actions['empty'](); }
    if (_.size(model) == 0 && _.size(hash_with_unique_keys) != 0) { actions['populate'](); }

    _.each(add_items, function(value, key) { actions['add'](key, value); });
    _.each(remove_items, function(value, key) { actions['remove'](key, value) });

    model = _.clone(hash_with_unique_keys);
    return true;
  }
  return {
    initialize : function() { actions.empty(); },
    set_action : function(new_hash) {
      if (actions['add']) { actions.add = new_hash.add; }
      if (actions['remove']) { actions.remove = new_hash.remove; }
      if (actions['populate']) { actions.populate = new_hash.populate; }
      if (actions['empty']) { actions.empty = new_hash.empty; }
    },
    sync : sync
  };
});
<commit_msg>update naming to Mmvp<commit_after>var Mmvp = (function(my) {
  var actions = {
    add      : function() {},
    remove   : function() {},
    update   : function() {},
    populate : function() {},
    empty    : function() {}
  },
  model = {};

  function sync(hash_with_unique_keys) {
    var add_items = _.omit(hash_with_unique_keys, _.keys(model));
    var remove_items = _.omit(model, _.keys(hash_with_unique_keys));

    _.each(_.pick(model, _.keys(hash_with_unique_keys)), function(v,k) {
      _.each(_.keys(model[k]), function(key) {
        if (model[k][key] != hash_with_unique_keys[k][key]) {
          model[k] = hash_with_unique_keys[k];
          actions['update'](k,model[k]);
          return;
        }
      });
    });

    if (_.size(hash_with_unique_keys) == 0 && _.size(model) != 0) { actions['empty'](); }
    if (_.size(model) == 0 && _.size(hash_with_unique_keys) != 0) { actions['populate'](); }

    _.each(add_items, function(value, key) { actions['add'](key, value); });
    _.each(remove_items, function(value, key) { actions['remove'](key, value) });

    model = _.clone(hash_with_unique_keys);
    return true;
  }
  return {
    initialize : function() { actions.empty(); },
    set_action : function(new_hash) {
      if (actions['add']) { actions.add = new_hash.add; }
      if (actions['remove']) { actions.remove = new_hash.remove; }
      if (actions['populate']) { actions.populate = new_hash.populate; }
      if (actions['empty']) { actions.empty = new_hash.empty; }
    },
    sync : sync
  };
});
<|endoftext|>