<commit_before>Date.prototype.toDateInputValue = (function() {
    var local = new Date(this);
    local.setMinutes(this.getMinutes() - this.getTimezoneOffset());
    return local.toJSON().slice(0,10);
});

var admonitus = {};
admonitus.transFreqNoToName = function(num)
{
	switch (num)
	{
	case 0:
		return "One-time";
	case 1:
		return "Daily";
	case 2:
		return "Weekly";
	case 3:
		return "Monthly";
	default:
		return "Invalid";
	}
}

var reminderTable = {};
reminderTable.addRow = function (rowNr, data, highlight)
{
	newrow = $("#template").clone();

	this.updateRow(newrow, rowNr, data[0], data[1]);

	newrow.insertAfter("#template");

	newrow.show();

	if(highlight)
	{
		newrow.effect("highlight", { color: "#AACCE8"}, 1500);
	}
}

reminderTable.updateRow = function (tr, id, data1, data2)
{
	tr.find("td.number").text(id + 1);
	tr.find("span.text").text(data1['text']);
	tr.find("input.text").val(data1['text']);
	tr.find("button[name=deleteButton]").attr('data-id', data1['id']);
	tr.attr("id", data1['id']);
	tr.find("span.startingat").text(new Date(data1['datestart']).format('d-M-Y'))
	tr.find(".startingat").val(new Date(data1['datestart']).toDateInputValue())

	tr.find("span.frequency").text(
		admonitus.transFreqNoToName(data1['frequency'])
	);
	tr.find(".frequency").val(data1['frequency']);
	tr.find(".numFriends").text(data2);
}

var friendsTable = {};
friendsTable.addRow = function(data, highlight, reminderId)
{
	newrow = $("#friendTemplate").clone();

	newrow.attr("id", "");
	newrow.attr("data-id", data['id']);

	newrow.find("span.email").text(data['email']);
	newrow.find("button[name=deleteFriendButton]").attr('data-id', data['id']);
	newrow.find("button[name=deleteFriendButton]").attr('data-reminder-id', reminderId);

	newrow.show();
	newrow.insertAfter("#friendTemplate");
	if(highlight)
	{
		newrow.effect("highlight", { color: "#AACCE8"}, 1500);
	}
}

var mainObj = function() {
	var self = this;

	this.refreshRemindersList = function()
	{
		$.ajax({
			type : "GET",
			dataType : "json",
			url : "/Admonitus/ctl/Reminder/get",
			success : function(response) {

				$("#remindersList > tbody").find("tr:gt(1)").remove();

				$.each(response.data, function(index, entry) {
					reminderTable.addRow(index, entry);
				});
			}

		});
	}

	this.switchToLoggedIn = function(response)
	{
		$("#userPicture").attr("src", "/Admonitus/ctl/User/getPicture?timestamp=" + new Date().getTime());
		$("#emailAddress").text(response.data.email);
		$(".loggedOut").hide();
		$(".loggedIn").show();
		self.refreshRemindersList();
		$('#reminderForm input[name=text]').focus();
	}

	this.switchToLoggedOut = function()
	{
		$(".loggedOut").show();
		$(".loggedIn").hide();
	}

	this.refreshSingleReminderRow = function(id)
	{
		$.ajax({
			type: "GET",
			dataType: "json",
			url: "/Admonitus/ctl/Reminder/getSingle/" + id,
			context: self,
			success: function(response)
			{
				if(response.success)
				{
					reminderTable.updateRow($("#" + id), id, response.data[0], response.data[1])
					tr.effect("highlight", { color: "#A8D9A8"}, 1000);
				}
				else
				{
					$("#jsonErrorText").text(response.error);
					$('#jsonErrorModal').modal('show');
				}
			}
		});
	}

	$(document).on("click", "button[name=editButton]",
		function (e)
		{
			e.preventDefault();
			id = $(this).parent().parent().attr("id");
			$("#remindersList > tbody > tr[id=" + id + "]").find(".reminderView").hide();
			$("#remindersList > tbody > tr[id=" + id + "]").find(".reminderEdit").show();
		}
	);

	$(document).on("click", "button[name=saveButton]",
		function(e)
		{
			e.preventDefault();
			id = $(this).parent().parent().attr("id");
			var tr = $("#remindersList > tbody > tr[id=" + id + "]");

			var request = {
				"frequency": tr.find("select[name=frequency] option:selected").val(),
				"text": tr.find("input[name=text]").val(),
				"startingat": tr.find("input[name=startingat]").val()
			}

			$.ajax({
				type: "POST",
				dataType: "json",
				url: "/Admonitus/ctl/Reminder/edit/" + id,
				data: request,
				context: self,
				success: function(response)
				{
					if(response.success)
					{
						reminderTable.updateRow($("#" + id), id, response.data)
						tr.find(".reminderView").show();
						tr.find(".reminderEdit").hide();
						tr.effect("highlight", { color: "#A8D9A8"}, 1000);
					}
					else
					{
						$("#jsonErrorText").text(response.error);
						$('#jsonErrorModal').modal('show');
					}
				}
			});
		}
	);

	$("input[name=startingat]").val((new Date()).toDateInputValue());

	$(document).on("click", "#registerButton",
		function(e)
		{
			e.preventDefault();
			var request = {
					"email": $("input[id=registerEmail]").val(),
					"password1": $("input[id=registerPassword1]").val(),
					"password2": $("input[id=registerPassword2]").val()
				}
				$.ajax({
					type: "POST",
					dataType: "json",
					url: "/Admonitus/ctl/User/register",
					data: request,
					context: self,
					success: function(response)
					{
						if(response.success)
						{
							$("#registerForm").hide();
							$("#registerCompleted").show();
						}
						else
						{
							$("#jsonErrorText").text(response.error);
							$('#jsonErrorModal').modal('show');
						}
					}
				});
		}

	);

	$(document).on("click", "#logoutButton",
		function(e)
		{
			e.preventDefault();
			$.ajax({
				type: "GET",
				dataType: "json",
				url: "/Admonitus/ctl/User/logout",
				context: self,
				success: function(response)
				{
					if(response.success)
					{
						self.switchToLoggedOut();
					}
					else
					{
						$("#jsonErrorText").text(response.error);
						$('#jsonErrorModal').modal('show');
					}
				}
			});
		}
	);

	$(document).on("click", "#loginButton",
		function(e)
		{
			e.preventDefault();
			var request = {
				"email": $("input[id=loginEmail]").val(),
				"password": $("input[id=loginPassword]").val()
			}
			$.ajax({
				type: "POST",
				dataType: "json",
				url: "/Admonitus/ctl/User/login",
				data: request,
				context: self,
				success: function(response)
				{
					if(response.success)
					{
						self.switchToLoggedIn(response);
						$("#loginForm")[0].reset();
					}
					else
					{
						$("#jsonErrorText").text(response.error);
						$('#jsonErrorModal').modal('show');
					}
				}
			});
		}
	);

	$("#deleteModal").on('show.bs.modal',
		function(e)
		{
	    	$("button[name=deleteConfirm]").attr("data-id", $(e.relatedTarget).data('id'));
		}
	);

	$("#friendModal").on('show.bs.modal',
		function(e)
		{
			var id = $(e.relatedTarget).parent().parent().attr('id');
			$("#friendModal button[id=addFriend]").attr('data-id', id);

			$("#friendsTable > tbody").find("tr:gt(1)").remove();

			$.ajax(
				{
					type: "GET",
					dataType: "json",
					url: "/Admonitus/ctl/Reminder/getFriends/" + id,
					success: function(response)
					{
						if(response.success)
						{
							$.each(response.data, function(index, entry) {
								friendsTable.addRow(entry, false, id);
							});
						}
					}
				}
			);
		}
	);

	$('#friendModal').on('shown.bs.modal',
		function () {
	    	$('#friendEmail').focus();
		}
	);

	$(document).on('click', "#friendModal button[id=addFriend]",
		function(e)
		{
			e.preventDefault();

			var id = $(this).attr("data-id");

			var request =
			{
				email: $("#friendModal input[id=friendEmail]").val()
			}

			$.ajax(
				{
					type: "POST",
					dataType: "json",
					data: request,
					url: "/Admonitus/ctl/Reminder/addFriend/" + id,
					context: self,
					success: function(response)
					{
						if(response.success)
						{
							$("#friendModal form")[0].reset();
							friendsTable.addRow(response.data, true, id);
							this.refreshSingleReminderRow(id);
						}
						else
						{
							$("#jsonErrorText").text(response.error);
							$('#jsonErrorModal').modal('show');
						}
					}
				}
			)
		}
	);

	$(document).on('click', "button[name=deleteConfirm]",
		function(e)
		{
			var id = $(this).attr("data-id");
			console.log("Delete id " + id);

			$.ajax({
				type: "GET",
				dataType: "json",
				url: "/Admonitus/ctl/Reminder/delete/" + id,
				success:
					function(response)
					{
						if(response.success)
						{
							$("#remindersList").find("tr[id=" + id + "]").remove();
						}
						else
						{
							$("#jsonErrorText").text(response.error);
							$('#jsonErrorModal').modal('show');
						}
					}
			});
		}
	);

	$(document).on('click', "button[name='friendButton']",
		function (e)
		{
			e.preventDefault();
		}
	);

	$(document).on('click', "button[name=deleteFriendButton]",
		function(e)
		{
			var id = $(this).attr("data-id");
			var reminderId = $(this).attr("data-reminder-id");

			$.ajax({
				type: "POST",
				dataType: "json",
				url: "/Admonitus/ctl/Reminder/deleteFriend/" + id,
				context: self,
				success: function(response)
				{
					if(response.success)
					{
						$("#friendsTable tr[data-id=" + id + "]").remove();
						this.refreshSingleReminderRow(reminderId);
					}
					else
					{
						$("#jsonErrorText").text(response.error);
						$('#jsonErrorModal').modal('show');
					}
				}
			});

		}
	);

	$(document).on('click', "button[name='addReminder']", function(e) {
		e.preventDefault();

		var request = {
			"frequency": $("#new select[name=frequency] option:selected").val(),
			"text": $("#new input[name=text]").val(),
			"startingat": $("#new input[name=startingat]").val()
		}

		$.ajax({
			type : "POST",
			dataType : "json",
			url : "/Admonitus/ctl/Reminder/add",
			data : request,
			context: self,
			success: function(response)
			{
				if(response.success)
				{
					reminderTable.addRow(0, response.data, true)
					$("#new input[name=text]").val("");
					$("#new select[name=frequency]").val(2);
					$("#new input[name=startingat]").val((new Date()).toDateInputValue());
				}
				else
				{
					$("#jsonErrorText").text(response.error);
					$('#jsonErrorModal').modal('show');
				}
			}
		});
	});

	/* Initialization */
	$.ajax({
		type: "GET",
		dataType: "json",
		url: "/Admonitus/ctl/User/isLoggedIn",
		context: self,
		success: function(response)
		{
			if(response.data)
			{
				self.switchToLoggedIn(response);
			}
		}
	});

	$('#loginEmail').focus();

	$("[data-toggle=popover]").popover({
	    html: true,
	    container: 'body',
		content: function()
			{
	            var html = $('#picturePopoverContent').clone();
	            var jq = html
	            jq.find("input[type=file]").addClass("user-file");
	            return jq.html();
	        }
	});

	$(document).on("click", "#uploadPictureButton",
		function(e)
		{
			e.preventDefault();
		    var upl = fileuploader({
		        selector: '.user-file',
		        file_input_name: 'file',
		        url: '/Admonitus/ctl/User/setPicture',
		        headers: {
		            'myCsrfToken': '!334234#2344$234234@@234'
		        },
		        data: {
		            'filename': 'myfile',
		            'type': 'other'
		        },
		        onsubmit: function(xhr){
		            console.log("Starting upload for: " + xhr.fu.file.name);
		            console.log("Upload uuid: " + xhr.fu.uuid);
		        },
		        oncomplete: function(data, status, xhr){
		            console.log('complete');
		            console.log(data);
		            $("#userPicture").attr("src", "/Admonitus/ctl/User/getPicture?timestamp=" + new Date().getTime());
		        },
		        onerror: function(data, status, xhr){
		            console.log(data);
		        }
		    });
		}
	);

}

$("document").ready(mainObj);
<commit_msg>Fix edit handling<commit_after>Date.prototype.toDateInputValue = (function() {
    var local = new Date(this);
    local.setMinutes(this.getMinutes() - this.getTimezoneOffset());
    return local.toJSON().slice(0,10);
});

var admonitus = {};
admonitus.transFreqNoToName = function(num)
{
	switch (num)
	{
	case 0:
		return "One-time";
	case 1:
		return "Daily";
	case 2:
		return "Weekly";
	case 3:
		return "Monthly";
	default:
		return "Invalid";
	}
}

var reminderTable = {};
reminderTable.addRow = function (rowNr, data1, data2, highlight)
{
	newrow = $("#template").clone();

	this.updateRow(newrow, rowNr, data1, data2);

	newrow.insertAfter("#template");

	newrow.show();

	if(highlight)
	{
		newrow.effect("highlight", { color: "#AACCE8"}, 1500);
	}
}

reminderTable.updateRow = function (tr, id, data1, data2)
{
	tr.find("td.number").text(id + 1);
	tr.find("span.text").text(data1['text']);
	tr.find("input.text").val(data1['text']);
	tr.find("button[name=deleteButton]").attr('data-id', data1['id']);
	tr.attr("id", data1['id']);
	tr.find("span.startingat").text(new Date(data1['datestart']).format('d-M-Y'))
	tr.find(".startingat").val(new Date(data1['datestart']).toDateInputValue())

	tr.find("span.frequency").text(
		admonitus.transFreqNoToName(data1['frequency'])
	);
	tr.find(".frequency").val(data1['frequency']);
	tr.find(".numFriends").text(data2);
}

var friendsTable = {};
friendsTable.addRow = function(data, highlight, reminderId)
{
	newrow = $("#friendTemplate").clone();

	newrow.attr("id", "");
	newrow.attr("data-id", data['id']);

	newrow.find("span.email").text(data['email']);
	newrow.find("button[name=deleteFriendButton]").attr('data-id', data['id']);
	newrow.find("button[name=deleteFriendButton]").attr('data-reminder-id', reminderId);

	newrow.show();
	newrow.insertAfter("#friendTemplate");
	if(highlight)
	{
		newrow.effect("highlight", { color: "#AACCE8"}, 1500);
	}
}

var mainObj = function() {
	var self = this;

	this.refreshRemindersList = function()
	{
		$.ajax({
			type : "GET",
			dataType : "json",
			url : "/Admonitus/ctl/Reminder/get",
			success : function(response) {

				$("#remindersList > tbody").find("tr:gt(1)").remove();

				$.each(response.data, function(index, entry) {
					reminderTable.addRow(index, entry[0], entry[1]);
				});
			}

		});
	}

	this.switchToLoggedIn = function(response)
	{
		$("#userPicture").attr("src", "/Admonitus/ctl/User/getPicture?timestamp=" + new Date().getTime());
		$("#emailAddress").text(response.data.email);
		$(".loggedOut").hide();
		$(".loggedIn").show();
		self.refreshRemindersList();
		$('#reminderForm input[name=text]').focus();
	}

	this.switchToLoggedOut = function()
	{
		$(".loggedOut").show();
		$(".loggedIn").hide();
	}

	this.refreshSingleReminderRow = function(id)
	{
		$.ajax({
			type: "GET",
			dataType: "json",
			url: "/Admonitus/ctl/Reminder/getSingle/" + id,
			context: self,
			success: function(response)
			{
				if(response.success)
				{
					reminderTable.updateRow($("#" + id), id, response.data[0], response.data[1]);
				}
				else
				{
					$("#jsonErrorText").text(response.error);
					$('#jsonErrorModal').modal('show');
				}
			}
		});
	}

	$(document).on("click", "button[name=editButton]",
		function (e)
		{
			e.preventDefault();
			id = $(this).parent().parent().attr("id");
			$("#remindersList > tbody > tr[id=" + id + "]").find(".reminderView").hide();
			$("#remindersList > tbody > tr[id=" + id + "]").find(".reminderEdit").show();
		}
	);

	$(document).on("click", "button[name=saveButton]",
		function(e)
		{
			e.preventDefault();
			id = $(this).parent().parent().attr("id");
			var tr = $("#remindersList > tbody > tr[id=" + id + "]");

			var request = {
				"frequency": tr.find("select[name=frequency] option:selected").val(),
				"text": tr.find("input[name=text]").val(),
				"startingat": tr.find("input[name=startingat]").val()
			}

			$.ajax({
				type: "POST",
				dataType: "json",
				url: "/Admonitus/ctl/Reminder/edit/" + id,
				data: request,
				context: self,
				success: function(response)
				{
					if(response.success)
					{
						reminderTable.updateRow($("#" + id), id, response.data)
						tr.find(".reminderView").show();
						tr.find(".reminderEdit").hide();
						tr.effect("highlight", { color: "#A8D9A8"}, 1000);
					}
					else
					{
						$("#jsonErrorText").text(response.error);
						$('#jsonErrorModal').modal('show');
					}
				}
			});
		}
	);

	$("input[name=startingat]").val((new Date()).toDateInputValue());

	$(document).on("click", "#registerButton",
		function(e)
		{
			e.preventDefault();
			var request = {
					"email": $("input[id=registerEmail]").val(),
					"password1": $("input[id=registerPassword1]").val(),
					"password2": $("input[id=registerPassword2]").val()
				}
				$.ajax({
					type: "POST",
					dataType: "json",
					url: "/Admonitus/ctl/User/register",
					data: request,
					context: self,
					success: function(response)
					{
						if(response.success)
						{
							$("#registerForm").hide();
							$("#registerCompleted").show();
						}
						else
						{
							$("#jsonErrorText").text(response.error);
							$('#jsonErrorModal').modal('show');
						}
					}
				});
		}

	);

	$(document).on("click", "#logoutButton",
		function(e)
		{
			e.preventDefault();
			$.ajax({
				type: "GET",
				dataType: "json",
				url: "/Admonitus/ctl/User/logout",
				context: self,
				success: function(response)
				{
					if(response.success)
					{
						self.switchToLoggedOut();
					}
					else
					{
						$("#jsonErrorText").text(response.error);
						$('#jsonErrorModal').modal('show');
					}
				}
			});
		}
	);

	$(document).on("click", "#loginButton",
		function(e)
		{
			e.preventDefault();
			var request = {
				"email": $("input[id=loginEmail]").val(),
				"password": $("input[id=loginPassword]").val()
			}
			$.ajax({
				type: "POST",
				dataType: "json",
				url: "/Admonitus/ctl/User/login",
				data: request,
				context: self,
				success: function(response)
				{
					if(response.success)
					{
						self.switchToLoggedIn(response);
						$("#loginForm")[0].reset();
					}
					else
					{
						$("#jsonErrorText").text(response.error);
						$('#jsonErrorModal').modal('show');
					}
				}
			});
		}
	);

	$("#deleteModal").on('show.bs.modal',
		function(e)
		{
	    	$("button[name=deleteConfirm]").attr("data-id", $(e.relatedTarget).data('id'));
		}
	);

	$("#friendModal").on('show.bs.modal',
		function(e)
		{
			var id = $(e.relatedTarget).parent().parent().attr('id');
			$("#friendModal button[id=addFriend]").attr('data-id', id);

			$("#friendsTable > tbody").find("tr:gt(1)").remove();

			$.ajax(
				{
					type: "GET",
					dataType: "json",
					url: "/Admonitus/ctl/Reminder/getFriends/" + id,
					success: function(response)
					{
						if(response.success)
						{
							$.each(response.data, function(index, entry) {
								friendsTable.addRow(entry, false, id);
							});
						}
					}
				}
			);
		}
	);

	$('#friendModal').on('shown.bs.modal',
		function () {
	    	$('#friendEmail').focus();
		}
	);

	$(document).on('click', "#friendModal button[id=addFriend]",
		function(e)
		{
			e.preventDefault();

			var id = $(this).attr("data-id");

			var request =
			{
				email: $("#friendModal input[id=friendEmail]").val()
			}

			$.ajax(
				{
					type: "POST",
					dataType: "json",
					data: request,
					url: "/Admonitus/ctl/Reminder/addFriend/" + id,
					context: self,
					success: function(response)
					{
						if(response.success)
						{
							$("#friendModal form")[0].reset();
							friendsTable.addRow(response.data, true, id);
							this.refreshSingleReminderRow(id);
						}
						else
						{
							$("#jsonErrorText").text(response.error);
							$('#jsonErrorModal').modal('show');
						}
					}
				}
			)
		}
	);

	$(document).on('click', "button[name=deleteConfirm]",
		function(e)
		{
			var id = $(this).attr("data-id");

			$.ajax({
				type: "GET",
				dataType: "json",
				url: "/Admonitus/ctl/Reminder/delete/" + id,
				success:
					function(response)
					{
						if(response.success)
						{
							$("#remindersList").find("tr[id=" + id + "]").remove();
						}
						else
						{
							$("#jsonErrorText").text(response.error);
							$('#jsonErrorModal').modal('show');
						}
					}
			});
		}
	);

	$(document).on('click', "button[name='friendButton']",
		function (e)
		{
			e.preventDefault();
		}
	);

	$(document).on('click', "button[name=deleteFriendButton]",
		function(e)
		{
			var id = $(this).attr("data-id");
			var reminderId = $(this).attr("data-reminder-id");

			$.ajax({
				type: "POST",
				dataType: "json",
				url: "/Admonitus/ctl/Reminder/deleteFriend/" + id,
				context: self,
				success: function(response)
				{
					if(response.success)
					{
						$("#friendsTable tr[data-id=" + id + "]").remove();
						this.refreshSingleReminderRow(reminderId);
					}
					else
					{
						$("#jsonErrorText").text(response.error);
						$('#jsonErrorModal').modal('show');
					}
				}
			});

		}
	);

	$(document).on('click', "button[name='addReminder']", function(e) {
		e.preventDefault();

		var request = {
			"frequency": $("#new select[name=frequency] option:selected").val(),
			"text": $("#new input[name=text]").val(),
			"startingat": $("#new input[name=startingat]").val()
		}

		$.ajax({
			type : "POST",
			dataType : "json",
			url : "/Admonitus/ctl/Reminder/add",
			data : request,
			context: self,
			success: function(response)
			{
				if(response.success)
				{
					reminderTable.addRow(0, response.data, 0, true)
					$("#new input[name=text]").val("");
					$("#new select[name=frequency]").val(2);
					$("#new input[name=startingat]").val((new Date()).toDateInputValue());
				}
				else
				{
					$("#jsonErrorText").text(response.error);
					$('#jsonErrorModal').modal('show');
				}
			}
		});
	});

	/* Initialization */
	$.ajax({
		type: "GET",
		dataType: "json",
		url: "/Admonitus/ctl/User/isLoggedIn",
		context: self,
		success: function(response)
		{
			if(response.data)
			{
				self.switchToLoggedIn(response);
			}
		}
	});

	$('#loginEmail').focus();

	$("[data-toggle=popover]").popover({
	    html: true,
	    container: 'body',
		content: function()
			{
	            var html = $('#picturePopoverContent').clone();
	            var jq = html
	            jq.find("input[type=file]").addClass("user-file");
	            return jq.html();
	        }
	});

	$(document).on("click", "#uploadPictureButton",
		function(e)
		{
			e.preventDefault();
		    var upl = fileuploader({
		        selector: '.user-file',
		        file_input_name: 'file',
		        url: '/Admonitus/ctl/User/setPicture',
		        headers: {
		            'myCsrfToken': '!334234#2344$234234@@234'
		        },
		        data: {
		            'filename': 'myfile',
		            'type': 'other'
		        },
		        onsubmit: function(xhr){
		            console.log("Starting upload for: " + xhr.fu.file.name);
		            console.log("Upload uuid: " + xhr.fu.uuid);
		        },
		        oncomplete: function(data, status, xhr){
		            console.log('complete');
		            console.log(data);
		            $("#userPicture").attr("src", "/Admonitus/ctl/User/getPicture?timestamp=" + new Date().getTime());
		        },
		        onerror: function(data, status, xhr){
		            console.log(data);
		        }
		    });
		}
	);

}

$("document").ready(mainObj);
<|endoftext|>


<commit_before><commit_msg>feat: use all `desiredCapabilities` in driver<commit_after><|endoftext|>


<commit_before>import Emitter from 'component-emitter';

import { name as NAME, version as VERSION } from '../package.json';
import dataAttributesToObject from './data-attributes-to-object';
import interval from './interval';

const INIT = 'init';
const START = 'start';
const TYPE = 'type';
const LOOP = 'loop';
const STOP = 'stop';
const DESTROY = 'destroy';

const EVENTS = {
  INIT,
  START,
  TYPE,
  LOOP,
  STOP,
  DESTROY,
};

const ATTRIBUTE_OPTION_NAMES = [
  'text',
  'interval',
  'auto-start',
  'loop',
  'loop-interval',
  'empty-text',
];

const DEFAULTS = {
  text: 'This is the default text.',
  interval: [200, 300],
  autoStart: true,
  loop: false,
  // loopInterval: DEFAULTS.interval,
  emptyText: '\u00A0',
};

const autotyper = {
  init(...args) {
    let element;
    let options;

    if (process.env.NODE_ENV === 'test') {
      if (args[0] instanceof window.HTMLElement) {
        [element, options = {}] = args;
      } else {
        [options = {}] = args;
      }
    } else if (args[0] instanceof HTMLElement) {
      [element, options = {}] = args;
    } else {
      [options = {}] = args;
    }

    if (element) {
      const text = element.innerHTML.trim();
      const attributeOptions = Object.assign(
        dataAttributesToObject(element, ATTRIBUTE_OPTION_NAMES, NAME),
        JSON.parse(element.getAttribute(`data-${NAME}`)),
      );

      this.element = element;
      this.settings = Object.assign(
        {},
        DEFAULTS,
        (text && { text }),
        attributeOptions,
        options,
      );
      this.originalText = text;
    } else {
      this.element = element;
      this.settings = Object.assign({}, DEFAULTS, options);
      this.originalText = this.settings.text;
    }

    this.settings.loopInterval = this.settings.loopInterval || this.settings.interval;

    this.isRunning = false;

    if (this.settings.autoStart === true) {
      this.start();
    } else {
      const delay = parseInt(this.settings.autoStart, 10);

      if (!isNaN(delay)) {
        setTimeout(() => this.start(), delay);
      }
    }

    this.emit(INIT);

    return this;
  },
  start() {
    if (this.isRunning) {
      return this;
    }

    clearTimeout(this.timeout);

    this.isRunning = true;

    this.letterTotal = this.settings.text.length;
    this.letterCount = 0;

    if (this.settings.loop) {
      if (typeof this.settings.loop === 'number') {
        this.loopTotal = this.settings.loop;
      }

      this.loopCount = 0;
    }

    this.type();

    this.emit(START);

    return this;
  },
  setText(text) {
    this.text = text;

    if (this.element) {
      this.element.innerHTML = text;
    }

    return this;
  },
  type() {
    let text;

    this.tick(interval(this.settings.interval));

    if (this.letterCount > this.letterTotal) {
      if (this.settings.loop) {
        return this.loop();
      }

      return this.stop();
    }

    if (this.letterCount === 0) {
      text = this.settings.emptyText;
    } else {
      text = this.settings.text.substring(0, this.letterCount);
    }

    this.setText(text);

    this.emit(TYPE, text);

    this.letterCount += 1;

    return this;
  },
  stop() {
    if (!this.isRunning) {
      return this;
    }

    clearTimeout(this.timeout);

    this.isRunning = false;

    this.emit(STOP);

    return this;
  },
  resetText() {
    this.setText(this.originalText);

    return this;
  },
  destroy() {
    if (this.isRunning) {
      this.stop();
    }

    this.emit(DESTROY);

    this.off();

    this.element = null;
  },
  tick(duration) {
    clearTimeout(this.timeout);

    if (duration === 0) {
      return this.type();
    }

    this.timeout = setTimeout(() => this.type(), duration);

    return this;
  },
  loop() {
    this.tick(interval(this.settings.loopInterval));

    if (this.loopCount === this.loopTotal) {
      return this.stop();
    }

    this.loopCount += 1;

    this.letterTotal = this.settings.text.length;
    this.letterCount = 0;

    this.emit(LOOP, this.loopCount);

    return this;
  },
};

Emitter(autotyper);

export {
  autotyper as default,
  NAME,
  DEFAULTS,
  EVENTS,
  VERSION,
};
<commit_msg>fix: emit start event before triggering `type()`<commit_after>import Emitter from 'component-emitter';

import { name as NAME, version as VERSION } from '../package.json';
import dataAttributesToObject from './data-attributes-to-object';
import interval from './interval';

const INIT = 'init';
const START = 'start';
const TYPE = 'type';
const LOOP = 'loop';
const STOP = 'stop';
const DESTROY = 'destroy';

const EVENTS = {
  INIT,
  START,
  TYPE,
  LOOP,
  STOP,
  DESTROY,
};

const ATTRIBUTE_OPTION_NAMES = [
  'text',
  'interval',
  'auto-start',
  'loop',
  'loop-interval',
  'empty-text',
];

const DEFAULTS = {
  text: 'This is the default text.',
  interval: [200, 300],
  autoStart: true,
  loop: false,
  // loopInterval: DEFAULTS.interval,
  emptyText: '\u00A0',
};

const autotyper = {
  init(...args) {
    let element;
    let options;

    if (process.env.NODE_ENV === 'test') {
      if (args[0] instanceof window.HTMLElement) {
        [element, options = {}] = args;
      } else {
        [options = {}] = args;
      }
    } else if (args[0] instanceof HTMLElement) {
      [element, options = {}] = args;
    } else {
      [options = {}] = args;
    }

    if (element) {
      const text = element.innerHTML.trim();
      const attributeOptions = Object.assign(
        dataAttributesToObject(element, ATTRIBUTE_OPTION_NAMES, NAME),
        JSON.parse(element.getAttribute(`data-${NAME}`)),
      );

      this.element = element;
      this.settings = Object.assign(
        {},
        DEFAULTS,
        (text && { text }),
        attributeOptions,
        options,
      );
      this.originalText = text;
    } else {
      this.element = element;
      this.settings = Object.assign({}, DEFAULTS, options);
      this.originalText = this.settings.text;
    }

    this.settings.loopInterval = this.settings.loopInterval || this.settings.interval;

    this.isRunning = false;

    if (this.settings.autoStart === true) {
      this.start();
    } else {
      const delay = parseInt(this.settings.autoStart, 10);

      if (!isNaN(delay)) {
        setTimeout(() => this.start(), delay);
      }
    }

    this.emit(INIT);

    return this;
  },
  start() {
    if (this.isRunning) {
      return this;
    }

    clearTimeout(this.timeout);

    this.isRunning = true;

    this.letterTotal = this.settings.text.length;
    this.letterCount = 0;

    if (this.settings.loop) {
      if (typeof this.settings.loop === 'number') {
        this.loopTotal = this.settings.loop;
      }

      this.loopCount = 0;
    }

    this.emit(START);

    this.type();

    return this;
  },
  setText(text) {
    this.text = text;

    if (this.element) {
      this.element.innerHTML = text;
    }

    return this;
  },
  type() {
    let text;

    this.tick(interval(this.settings.interval));

    if (this.letterCount > this.letterTotal) {
      if (this.settings.loop) {
        return this.loop();
      }

      return this.stop();
    }

    if (this.letterCount === 0) {
      text = this.settings.emptyText;
    } else {
      text = this.settings.text.substring(0, this.letterCount);
    }

    this.setText(text);

    this.emit(TYPE, text);

    this.letterCount += 1;

    return this;
  },
  stop() {
    if (!this.isRunning) {
      return this;
    }

    clearTimeout(this.timeout);

    this.isRunning = false;

    this.emit(STOP);

    return this;
  },
  resetText() {
    this.setText(this.originalText);

    return this;
  },
  destroy() {
    if (this.isRunning) {
      this.stop();
    }

    this.emit(DESTROY);

    this.off();

    this.element = null;
  },
  tick(duration) {
    clearTimeout(this.timeout);

    if (duration === 0) {
      return this.type();
    }

    this.timeout = setTimeout(() => this.type(), duration);

    return this;
  },
  loop() {
    this.tick(interval(this.settings.loopInterval));

    if (this.loopCount === this.loopTotal) {
      return this.stop();
    }

    this.loopCount += 1;

    this.letterTotal = this.settings.text.length;
    this.letterCount = 0;

    this.emit(LOOP, this.loopCount);

    return this;
  },
};

Emitter(autotyper);

export {
  autotyper as default,
  NAME,
  DEFAULTS,
  EVENTS,
  VERSION,
};
<|endoftext|>


<commit_before>Meteor.startup(function() {
  console.log('startup');
  // populates the HVAC and Lighting collections
  Meteor.call('querysystem');
});

var metadatakeydescriptions = {
'LightingZone': 'Name for logical space that is under common lighting control, e.g. "Room 213 Overheads"',
'HVACZone': 'Name for the group of spaces that are controlled by the same thermostat, e.g. "South Offices"',
'Building': 'Name of the building',
'SourceName': 'Auto-generated name of sMAP Driver',
'System': 'Which domain this device belongs to (Auto-generated)',
'Driver': 'sMAP Driver module path',
'Device': 'What is this device? e.g. Thermostat, Lighting Controller, Sensor',
'Group': 'Unique number for a lighting controller (start at 1, 2, etc)',
'Floor': 'Which floor in the building this is installed',
'Model': 'The model of the device, e.g. "CT80 RTA"',
'Name': 'Human-readable name for your convenience',
'Room': 'Room where device is installed',
'Role': 'What purpose this device fulfills within the system, e.g. "Building Lighting", "Task Lighting", etc',
'Site': 'Auto-generated unique identifier for this installation',
'_id': 'Mongo record identifier',
};

var Dashboard = {};

Dashboard.render_schedules = function(){
  // This seems to insure that schedules and master_schedule are loaded
  // .. but I thought this would be taken care of by waitOn?
  Meteor.subscribe('schedules', function(){
    Meteor.subscribe('master_schedule', function(){
      var scheds = Schedules.find().fetch();
      Dashboard.master_schedule = MasterSchedule.findOne({});

      // Shouldn't be neeed when we remove autopublish
      delete Dashboard.master_schedule._id;

      _.each(Dashboard.master_schedule, function(val, key){
        var day_sched = _.find(scheds, function(s){ return s.name == val });
        $('#'+key).css('background-color', day_sched.color);
      });

      /*
      $(".day-tooltip").tooltip({
        title: function(){
          return Dashboard.master_schedule[this.id];
        },
        placement: 'bottom',
      });
      */

      var m = moment();
      $('.day').removeClass('current-day');
      $('#'+Dashboard.day_names[m.day()]).addClass('current-day');

      _.each($('.schedulerow'), function(val, idx) {
        var t = moment(val.getAttribute('data-time'), 'HH:mm');
        var name = val.getAttribute('id');
        if (m.unix() > t.unix()) {
          $('.schedulerow').removeClass('current-period');
          $('#'+name).addClass('current-period');
        }
      });
    });
  });
};

Dashboard.day_names = {'7': 'sun', '1': 'mon',
                       '2': 'tue', '3': 'wed',
                       '4': 'thu', '5': 'fri',
                       '6': 'sat'
};

UI.registerHelper('getValue', function(obj) {
  if (this.timeseries[obj] != undefined){
    var unit = this.timeseries[obj].Properties.UnitofMeasure;
    var p = Points.find({'uuid': this.timeseries[obj].uuid}).fetch()[0];
    var value = p.value;
    if (unit == 'C') {
      value = value * 1.8 + 32;
    }
    return Number((value).toFixed(1));
  }
});

/*
 * Returns a text description of a metadata key
 */
UI.registerHelper('getDescription', function(key) {
    return metadatakeydescriptions[key] || '';
});

Template.dashboard.created = function() {
  // populates the HVAC and Lighting collections
  Meteor.call('querysystem');
};

Template.general_control_widget.GeneralControlAll = function() {
  return GeneralControl.find({});
};

Template.hvacbuildingcolumn.HVACAll = function() {
  return HVAC.find({});
};

Template.lightingbuildingcolumn.LightingAll = function() {
  var lighting = Lighting.find({'role': 'Building Lighting'}).fetch();
  // for each unique zone
  var zones = [];
  _.each(_.uniq(_.pluck(lighting, 'lightingzone')), function(val, idx) {
    var groups = _.filter(lighting, function(o) { return o.lightingzone == val; });
    zones[idx] = groups;
  });
  return zones;
};

Template.light_zone_widget.zone = function() {
  return this[0].lightingzone;
};

Template.light_zone_widget.groups = function() {
  return this;
};

Template.light_zone_widget.internals = function() {
  var lighting = Lighting.find({'role': 'Task Lighting', 'lightingzone': this[0].lightingzone});
  return lighting;
};

Template.light_zone_widget.sensors = function() {
  return Monitoring.find({'lightingzone': this[0].lightingzone});
};

Template.hvac_zone_widget.sensors = function() {
  return Monitoring.find({'hvaczone': this.hvaczone});
};

Template.generalbuildingcolumn.powermeterAll = function() {
  // find everything with a /demand endpoint
  return Monitoring.find({'timeseries.demand': {'$exists': true}});
};

Template.schedule_widget.helpers({
  isNamed: function(path){
    return path == this.path;
  }
});

Template.schedule_widget.schedule = function(){
  var m = moment();
  var master = MasterSchedule.findOne({});
  var sch_name = master[Dashboard.day_names[m.day()]]
  var sched = Schedules.find({'name': sch_name}).fetch()[0];
  return sched;
};

Template.schedule_widget.rendered = Dashboard.render_schedules;

Template.zone_detail.points = function() {
  return this.points;
};

Template.zone_detail.helpers({
  is_hvac: function(val) {
    return val == 'hvac';
  },
  is_lighting: function(val) {
    return val == 'lighting';
  }
});

Template.thermostat.helpers({
  has: function(val) {
    return this.timeseries[val]
  },
  uuid: function(val) {
    if (this.timeseries[val]) {
      if (this.timeseries[val].Actuator) {
        return this.timeseries[val].Actuator.uuid+"_hvac";
      } else {
        return this.timeseries[val].uuid+"_hvac";
      }
    }
    return ''
  }
});

Template.lightinggroup.helpers({
  has: function(val) {
    return this.timeseries[val]
  },
  uuid: function(val) {
    if (this.timeseries[val]) {
      if (this.timeseries[val].Actuator) {
        return this.timeseries[val].Actuator.uuid+"_lighting";
      } else {
        return this.timeseries[val].uuid+"_lighting";
      }
    }
    return ''
  }
});

Template.room_detail.helpers({
  uuid: function(val) {
    if (this.timeseries[val]) {
      if (this.timeseries[val].Actuator) {
        return this.timeseries[val].Actuator.uuid+"_control";
      } else {
        return this.timeseries[val].uuid+"_control";
      }
    }
    return ''
  }
});

Template.point.rendered = function(arg) {
  var p = Points.find({'uuid': this.data.uuid}).fetch()[0];
  if (p.ActuatorUUID) {
    var rend = UI.renderWithData(Template.actuator_display, p);
    var pointid = '#'+p.ActuatorUUID;
  } else {
    var rend = UI.renderWithData(Template.point_display, p);
    var pointid = '#'+p.uuid;
  }
  if (this.data.Metadata.System == 'Lighting') {
    UI.insert(rend, $(pointid+'_lighting').get(0));
  } else if (this.data.Metadata.System == 'HVAC') {
    UI.insert(rend, $(pointid+'_hvac').get(0));
  } else if (this.data.Metadata.System == 'GeneralControl') {
    UI.insert(rend, $(pointid+'_control').get(0));
  }
};

Template.hvac_zone_widget.rendered = function(){
  var restrict0 = 'Path="' + this.data.path;
  var restrict = restrict0 + '/temp_cool" or '
               + restrict0 + '/temp_heat" or '
               + restrict0 + '/temp"';
  var id = this.data._id;
  var q = "select * where " + restrict;
  Meteor.call("query", q, function(err, res) {
    var tags = res;
    Meteor.call("latest", restrict, 1000, function(err, res){
      var mydata = _.map(res, function(o){
        var tag = _.find(tags, function(t){ return t.uuid == o.uuid });
        var rv = _.extend(o, tag);
        return rv
      });
      var margin = 30;
      var width = $(window).width() / 3 - 2 * margin;
      var height = 100;
      var x = d3.scale.linear().range([0, width]);
      var y = d3.scale.linear().range([height, 0]);
      var line = d3.svg.line()
                   .interpolate("basis")
                   .x(function(d) { return x(d.time); })
                   .y(function(d) { return y(d.value); });

      function hvac_zone_summary(elemId, data){
        var extents = _.map(data, function(d){
          var readings = _.zip.apply(_, d.Readings);
          var timestamps = readings[0];
          var values = readings[1];
          rv = {
            'xmin': _.min(timestamps),
            'ymin': _.min(values),
            'xmax': _.max(timestamps),
            'ymax': _.max(values),
          }
          return rv;
        });
        var yextent = [ _.min(_.pluck(extents, 'ymin')), _.max(_.pluck(extents, 'ymax'))];
        var xextent = [ _.min(_.pluck(extents, 'xmin')), _.max(_.pluck(extents, 'xmax'))];
        x.domain(xextent);
        y.domain(yextent);

        var temp = _.find(data, function(d){
          return _.last(d.Path.split("/")) == "temp";
        });
        var temp_cool = _.find(data, function(d){
          return _.last(d.Path.split("/")) == "temp_cool";
        });
        var temp_heat = _.find(data, function(d){
          return _.last(d.Path.split("/")) == "temp_heat";
        });

        temp = jsonify(temp.Readings);
        temp_cool = jsonify(temp_cool.Readings);
        temp_heat = jsonify(temp_heat.Readings);

        var svg = d3.select(elemId)
          .append('svg')
          .attr('class', 'HVAC-zone-summary')
          .attr('width', width)
          .attr('height', height)

        svg.append('path')
          .datum(temp)
          .attr('class', 'templine')
          .attr('d', line);

        svg.append('path')
          .datum(temp_cool)
          .attr('class', 'cooltempline')
          .attr('d', line);

        svg.append('path')
          .datum(temp_heat)
          .attr('class', 'heattempline')
          .attr('d', line);

      }
      hvac_zone_summary("#HVAC-zone-summary-" + id, mydata);
    });
  });

  // render sparklines for sensors
  var sensors = Monitoring.find({'hvaczone': this.data.hvaczone}).fetch();
  _.each(sensors, function(s){
    var restrict = 'Path="' + s.path + '/temperature"';
    Meteor.call("latest", restrict, 100, function(err, res){
      if (res[0] != undefined){
        var mydata = jsonify(res[0].Readings);
        sparkline("#sparkline-temperature-container-" + s._id, mydata, 100, 25, false);
      }
    });
  });
  _.each(sensors, function(s){
    var restrict = 'Path="' + s.path + '/humidity"';
    Meteor.call("latest", restrict, 100, function(err, res){
      var mydata = jsonify(res[0].Readings);
      sparkline("#sparkline-humidity-container-" + s._id, mydata, 100, 25, false);
    });
  });

}

Template.power_meter_widget.rendered = function(){
  var restrict = 'Path="' + this.data.path + '/demand"';
  var myid = this.data._id;
  Meteor.call("latest", restrict, 1000, function(err, res){
    if (err) {
        console.log(err);
    }
    var mydata = res[0].Readings;
    mydata = jsonify(mydata);
    sparkline("#sparkline-container-" + myid, mydata, 250, 50, false);
  });
}
<commit_msg>Get 4 hours of data instead of 1k points<commit_after>Meteor.startup(function() {
  console.log('startup');
  // populates the HVAC and Lighting collections
  Meteor.call('querysystem');
});

var metadatakeydescriptions = {
'LightingZone': 'Name for logical space that is under common lighting control, e.g. "Room 213 Overheads"',
'HVACZone': 'Name for the group of spaces that are controlled by the same thermostat, e.g. "South Offices"',
'Building': 'Name of the building',
'SourceName': 'Auto-generated name of sMAP Driver',
'System': 'Which domain this device belongs to (Auto-generated)',
'Driver': 'sMAP Driver module path',
'Device': 'What is this device? e.g. Thermostat, Lighting Controller, Sensor',
'Group': 'Unique number for a lighting controller (start at 1, 2, etc)',
'Floor': 'Which floor in the building this is installed',
'Model': 'The model of the device, e.g. "CT80 RTA"',
'Name': 'Human-readable name for your convenience',
'Room': 'Room where device is installed',
'Role': 'What purpose this device fulfills within the system, e.g. "Building Lighting", "Task Lighting", etc',
'Site': 'Auto-generated unique identifier for this installation',
'_id': 'Mongo record identifier',
};

var Dashboard = {};

Dashboard.render_schedules = function(){
  // This seems to insure that schedules and master_schedule are loaded
  // .. but I thought this would be taken care of by waitOn?
  Meteor.subscribe('schedules', function(){
    Meteor.subscribe('master_schedule', function(){
      var scheds = Schedules.find().fetch();
      Dashboard.master_schedule = MasterSchedule.findOne({});

      // Shouldn't be neeed when we remove autopublish
      delete Dashboard.master_schedule._id;

      _.each(Dashboard.master_schedule, function(val, key){
        var day_sched = _.find(scheds, function(s){ return s.name == val });
        $('#'+key).css('background-color', day_sched.color);
      });

      /*
      $(".day-tooltip").tooltip({
        title: function(){
          return Dashboard.master_schedule[this.id];
        },
        placement: 'bottom',
      });
      */

      var m = moment();
      $('.day').removeClass('current-day');
      $('#'+Dashboard.day_names[m.day()]).addClass('current-day');

      _.each($('.schedulerow'), function(val, idx) {
        var t = moment(val.getAttribute('data-time'), 'HH:mm');
        var name = val.getAttribute('id');
        if (m.unix() > t.unix()) {
          $('.schedulerow').removeClass('current-period');
          $('#'+name).addClass('current-period');
        }
      });
    });
  });
};

Dashboard.day_names = {'7': 'sun', '1': 'mon',
                       '2': 'tue', '3': 'wed',
                       '4': 'thu', '5': 'fri',
                       '6': 'sat'
};

UI.registerHelper('getValue', function(obj) {
  if (this.timeseries[obj] != undefined){
    var unit = this.timeseries[obj].Properties.UnitofMeasure;
    var p = Points.find({'uuid': this.timeseries[obj].uuid}).fetch()[0];
    var value = p.value;
    if (unit == 'C') {
      value = value * 1.8 + 32;
    }
    return Number((value).toFixed(1));
  }
});

/*
 * Returns a text description of a metadata key
 */
UI.registerHelper('getDescription', function(key) {
    return metadatakeydescriptions[key] || '';
});

Template.dashboard.created = function() {
  // populates the HVAC and Lighting collections
  Meteor.call('querysystem');
};

Template.general_control_widget.GeneralControlAll = function() {
  return GeneralControl.find({});
};

Template.hvacbuildingcolumn.HVACAll = function() {
  return HVAC.find({});
};

Template.lightingbuildingcolumn.LightingAll = function() {
  var lighting = Lighting.find({'role': 'Building Lighting'}).fetch();
  // for each unique zone
  var zones = [];
  _.each(_.uniq(_.pluck(lighting, 'lightingzone')), function(val, idx) {
    var groups = _.filter(lighting, function(o) { return o.lightingzone == val; });
    zones[idx] = groups;
  });
  return zones;
};

Template.light_zone_widget.zone = function() {
  return this[0].lightingzone;
};

Template.light_zone_widget.groups = function() {
  return this;
};

Template.light_zone_widget.internals = function() {
  var lighting = Lighting.find({'role': 'Task Lighting', 'lightingzone': this[0].lightingzone});
  return lighting;
};

Template.light_zone_widget.sensors = function() {
  return Monitoring.find({'lightingzone': this[0].lightingzone});
};

Template.hvac_zone_widget.sensors = function() {
  return Monitoring.find({'hvaczone': this.hvaczone});
};

Template.generalbuildingcolumn.powermeterAll = function() {
  // find everything with a /demand endpoint
  return Monitoring.find({'timeseries.demand': {'$exists': true}});
};

Template.schedule_widget.helpers({
  isNamed: function(path){
    return path == this.path;
  }
});

Template.schedule_widget.schedule = function(){
  var m = moment();
  var master = MasterSchedule.findOne({});
  var sch_name = master[Dashboard.day_names[m.day()]]
  var sched = Schedules.find({'name': sch_name}).fetch()[0];
  return sched;
};

Template.schedule_widget.rendered = Dashboard.render_schedules;

Template.zone_detail.points = function() {
  return this.points;
};

Template.zone_detail.helpers({
  is_hvac: function(val) {
    return val == 'hvac';
  },
  is_lighting: function(val) {
    return val == 'lighting';
  }
});

Template.thermostat.helpers({
  has: function(val) {
    return this.timeseries[val]
  },
  uuid: function(val) {
    if (this.timeseries[val]) {
      if (this.timeseries[val].Actuator) {
        return this.timeseries[val].Actuator.uuid+"_hvac";
      } else {
        return this.timeseries[val].uuid+"_hvac";
      }
    }
    return ''
  }
});

Template.lightinggroup.helpers({
  has: function(val) {
    return this.timeseries[val]
  },
  uuid: function(val) {
    if (this.timeseries[val]) {
      if (this.timeseries[val].Actuator) {
        return this.timeseries[val].Actuator.uuid+"_lighting";
      } else {
        return this.timeseries[val].uuid+"_lighting";
      }
    }
    return ''
  }
});

Template.room_detail.helpers({
  uuid: function(val) {
    if (this.timeseries[val]) {
      if (this.timeseries[val].Actuator) {
        return this.timeseries[val].Actuator.uuid+"_control";
      } else {
        return this.timeseries[val].uuid+"_control";
      }
    }
    return ''
  }
});

Template.point.rendered = function(arg) {
  var p = Points.find({'uuid': this.data.uuid}).fetch()[0];
  if (p.ActuatorUUID) {
    var rend = UI.renderWithData(Template.actuator_display, p);
    var pointid = '#'+p.ActuatorUUID;
  } else {
    var rend = UI.renderWithData(Template.point_display, p);
    var pointid = '#'+p.uuid;
  }
  if (this.data.Metadata.System == 'Lighting') {
    UI.insert(rend, $(pointid+'_lighting').get(0));
  } else if (this.data.Metadata.System == 'HVAC') {
    UI.insert(rend, $(pointid+'_hvac').get(0));
  } else if (this.data.Metadata.System == 'GeneralControl') {
    UI.insert(rend, $(pointid+'_control').get(0));
  }
};

Template.hvac_zone_widget.rendered = function(){
  var restrict0 = 'Path="' + this.data.path;
  var restrict = restrict0 + '/temp_cool" or '
               + restrict0 + '/temp_heat" or '
               + restrict0 + '/temp"';
  var id = this.data._id;
  var q = "select * where " + restrict;
  Meteor.call("query", q, function(err, res) {
    var tags = res;
    // get 4 hours of data
    var qq = "select data in (now -4h, now) where " + restrict
    Meteor.call("query", qq, function(err, res){
      var mydata = _.map(res, function(o){
        var tag = _.find(tags, function(t){ return t.uuid == o.uuid });
        var rv = _.extend(o, tag);
        return rv
      });
      var margin = 30;
      var width = $(window).width() / 3 - 2 * margin;
      var height = 100;
      var x = d3.scale.linear().range([0, width]);
      var y = d3.scale.linear().range([height, 0]);
      var line = d3.svg.line()
                   .interpolate("basis")
                   .x(function(d) { return x(d.time); })
                   .y(function(d) { return y(d.value); });

      function hvac_zone_summary(elemId, data){
        var extents = _.map(data, function(d){
          var readings = _.zip.apply(_, d.Readings);
          var timestamps = readings[0];
          var values = readings[1];
          rv = {
            'xmin': _.min(timestamps),
            'ymin': _.min(values),
            'xmax': _.max(timestamps),
            'ymax': _.max(values),
          }
          return rv;
        });
        var yextent = [ _.min(_.pluck(extents, 'ymin')), _.max(_.pluck(extents, 'ymax'))];
        var xextent = [ _.min(_.pluck(extents, 'xmin')), _.max(_.pluck(extents, 'xmax'))];
        x.domain(xextent);
        y.domain(yextent);

        var temp = _.find(data, function(d){
          return _.last(d.Path.split("/")) == "temp";
        });
        var temp_cool = _.find(data, function(d){
          return _.last(d.Path.split("/")) == "temp_cool";
        });
        var temp_heat = _.find(data, function(d){
          return _.last(d.Path.split("/")) == "temp_heat";
        });

        temp = jsonify(temp.Readings);
        temp_cool = jsonify(temp_cool.Readings);
        temp_heat = jsonify(temp_heat.Readings);

        var svg = d3.select(elemId)
          .append('svg')
          .attr('class', 'HVAC-zone-summary')
          .attr('width', width)
          .attr('height', height)

        svg.append('path')
          .datum(temp)
          .attr('class', 'templine')
          .attr('d', line);

        svg.append('path')
          .datum(temp_cool)
          .attr('class', 'cooltempline')
          .attr('d', line);

        svg.append('path')
          .datum(temp_heat)
          .attr('class', 'heattempline')
          .attr('d', line);

      }
      hvac_zone_summary("#HVAC-zone-summary-" + id, mydata);
    });
  });

  // render sparklines for sensors
  var sensors = Monitoring.find({'hvaczone': this.data.hvaczone}).fetch();
  _.each(sensors, function(s){
    var restrict = 'Path="' + s.path + '/temperature"';
    Meteor.call("latest", restrict, 100, function(err, res){
      if (res[0] != undefined){
        var mydata = jsonify(res[0].Readings);
        sparkline("#sparkline-temperature-container-" + s._id, mydata, 100, 25, false);
      }
    });
  });
  _.each(sensors, function(s){
    var restrict = 'Path="' + s.path + '/humidity"';
    Meteor.call("latest", restrict, 100, function(err, res){
      var mydata = jsonify(res[0].Readings);
      sparkline("#sparkline-humidity-container-" + s._id, mydata, 100, 25, false);
    });
  });

}

Template.power_meter_widget.rendered = function(){
  var restrict = 'Path="' + this.data.path + '/demand"';
  var myid = this.data._id;
  Meteor.call("latest", restrict, 1000, function(err, res){
    if (err) {
        console.log(err);
    }
    var mydata = res[0].Readings;
    mydata = jsonify(mydata);
    sparkline("#sparkline-container-" + myid, mydata, 250, 50, false);
  });
}
<|endoftext|>


<commit_before>// ==UserScript==
// @name         Extrai Stats Totalcorner
// @namespace    http://aposte.me
// @version      0.1.6
// @description  Extrai Stats Totalcorner
// @author       Ronlado Araújo de Farias
// @match        http://www.totalcorner.com/match/today
// @grant        GM_xmlhttpRequest
// ==/UserScript==

$(document).ready(function(){

	//Reinicia a pagina 30 segundos depois ser carregada
	localStorage['reiniciado'] = localStorage['reiniciado'] || false;
	setTimeout(function(){
		if(localStorage['reiniciado']==false) {
			localStorage['reiniciado']=true;
			window.location.reload();
		}
	},30000);

	//Se não estiver aparecendo a columa "on target", define as colunas corretas
    if( $('th:contains(on target)').size()<1 ) {
        $.post('http://www.totalcorner.com/user/select_match_list_columns','asian_handicap=on&corner_score=on&total_corners=on&total_goals=on&dangerous_attack=on&shoot_on=on&shoot_off=on&events=on&save=today');
    }

	$( document ).ajaxComplete(function( event, res, settings) {
		if (!settings.url.includes('api_ongoing_matches') ) return;

		var TABELA_JOGOS={};
		$('[data-match_id]').each(function(i,e){
			TABELA_JOGOS[$(e).attr('data-match_id')]={
				home: $(e).find('.match_home a').text(),
				away: $(e).find('.match_away a').text()
			};
		});

		var DATA=[];
		$(res.responseJSON).each(function(i,j){

			HA=$(j.han.split(',')).size()==2 ? (Number(j.han.split(',')[0]) + Number(j.han.split(',')[1]))/2.0 : Number(j.han.split(',')[0]);
			try{
				DATA.push({
						id:   j.id,
						time_:j.sta,
						home: TABELA_JOGOS[j.id].home,
						away: TABELA_JOGOS[j.id].away,
						HA:   HA,
						gH:   Number(j.hg),
						gA:   Number(j.ag),
						daH:  Number(j.hda),
						daA:  Number(j.ada),
						soH:  Number(j.ho),
						soA:  Number(j.ao),
						sfH:  Number(j.hf),
						sfA:  Number(j.af)
				});
			} catch(e){
				window.location.reload();
			}

		});

		//$.post('http://aposte.me/live/atualiza_live_bet365_REST.php', JSON.stringify(DATA), function(data) {console.log(data) });
		GM_xmlhttpRequest({
			method: "POST",
			url: "http://aposte.me/live/atualiza_live_bet365_REST.php",
			data:  JSON.stringify(DATA),
			onload: function(res){
				console.log(res.responseText);
			}
		});

	});
});<commit_msg>Reinicia TotalCorner 30segs depois<commit_after>// ==UserScript==
// @name         Extrai Stats Totalcorner
// @namespace    http://aposte.me
// @version      0.1.6.1
// @description  Extrai Stats Totalcorner
// @author       Ronlado Araújo de Farias
// @match        http://www.totalcorner.com/match/today
// @grant        GM_xmlhttpRequest
// ==/UserScript==

$(document).ready(function(){

	//Reinicia a pagina 30 segundos depois ser carregada
	localStorage['reiniciado'] = localStorage['reiniciado'] || false;
	setTimeout(function(){
		if(localStorage['reiniciado']==false) {
			localStorage['reiniciado']=true;
			window.location.reload();
		}
		else{
			localStorage['reiniciado']=false;
		}
	},30000);

	//Se não estiver aparecendo a columa "on target", define as colunas corretas
    if( $('th:contains(on target)').size()<1 ) {
        $.post('http://www.totalcorner.com/user/select_match_list_columns','asian_handicap=on&corner_score=on&total_corners=on&total_goals=on&dangerous_attack=on&shoot_on=on&shoot_off=on&events=on&save=today');
    }

	$( document ).ajaxComplete(function( event, res, settings) {
		if (!settings.url.includes('api_ongoing_matches') ) return;

		var TABELA_JOGOS={};
		$('[data-match_id]').each(function(i,e){
			TABELA_JOGOS[$(e).attr('data-match_id')]={
				home: $(e).find('.match_home a').text(),
				away: $(e).find('.match_away a').text()
			};
		});

		var DATA=[];
		$(res.responseJSON).each(function(i,j){

			HA=$(j.han.split(',')).size()==2 ? (Number(j.han.split(',')[0]) + Number(j.han.split(',')[1]))/2.0 : Number(j.han.split(',')[0]);
			try{
				DATA.push({
						id:   j.id,
						time_:j.sta,
						home: TABELA_JOGOS[j.id].home,
						away: TABELA_JOGOS[j.id].away,
						HA:   HA,
						gH:   Number(j.hg),
						gA:   Number(j.ag),
						daH:  Number(j.hda),
						daA:  Number(j.ada),
						soH:  Number(j.ho),
						soA:  Number(j.ao),
						sfH:  Number(j.hf),
						sfA:  Number(j.af)
				});
			} catch(e){
				window.location.reload();
			}

		});

		//$.post('http://aposte.me/live/atualiza_live_bet365_REST.php', JSON.stringify(DATA), function(data) {console.log(data) });
		GM_xmlhttpRequest({
			method: "POST",
			url: "http://aposte.me/live/atualiza_live_bet365_REST.php",
			data:  JSON.stringify(DATA),
			onload: function(res){
				console.log(res.responseText);
			}
		});

	});
});<|endoftext|>


<commit_before>'use strict';

if (global && global.babyTolkCompilerModulePath) {
  require('app-module-path').addPath(global.babyTolkCompilerModulePath);
}

var Path = require('path');
var when = require('when');
var node = require('when/node');
var fs = node.liftAll(require('fs'));
var accord = require('accord');
var minify = require('./minify');

var extensionMap;
var loadedAdapters;
var targetExtension;
var sourceExtension;

// Whitelisted adapters
var adapters = [
  'LiveScript',
  'babel',
  'coco',
  'coffee-script',
  'dogescript',
  'less',
  'markdown',
  'myth',
  'scss',
  'stylus',
  'swig',
  'jade'
];

function load() {
  extensionMap = {};
  loadedAdapters = [];

  Object.keys(accord.all()).map(function (engine) {
    if (adapters.indexOf(engine) === -1) {
      return undefined;
    }

    try {
      return accord.load(engine, global && global.babyTolkCompilerModulePath || null);
    } catch (e) {
      if (e.code !== 'MODULE_NOT_FOUND' && e.message.indexOf('Cannot find module') === -1) {
        console.error(e.message.replace(/^error: ?/i, 'Accord Error: ') + '. Try updating to the latest version');
      }
      // else {
      //   console.error('Missing adapter:', engine);
      // }
    }
  }).filter(function (engine) {
    return engine;
  }).forEach(function (adapter) {
    if (adapter.engineName === 'babel' || adapter.engineName === 'babel-core') {
      // Monkey-patching Babel adapter so that it doesn't try and compile all .js files
      adapter.extensions = ['jsx', 'es6', 'babel'];
    }
    loadedAdapters.push(adapter);
    var extensions = adapter.extensions.map(function (extension) { return '.' + extension; });

    extensions.forEach(function (extension) {
      if (!Array.isArray(extensionMap[extension])) {
        extensionMap[extension] = [];
      }

      extensionMap[extension].push(adapter);
    });
  });

  targetExtension = {};
  sourceExtension = {};

  Object.keys(extensionMap).forEach(function (sourceExt) {
    var adapters = extensionMap[sourceExt];
    var targetExt = '.' + adapters[0].output;

    targetExtension[sourceExt] = targetExt;

    if (!sourceExtension[targetExt]) {
      sourceExtension[targetExt] = [];
    }

    sourceExtension[targetExt].push(sourceExt);
  });
}
load();

var dontCompile = function (pathName) {
  // Baby Tolk wont compile files that begin with an underscore `_`.
  // This is by convention.
  var baseName = Path.basename(pathName);
  return baseName[0] === '_';
};

module.exports = {
  get extensions() {
    return extensionMap;
  },
  get sourceExtensionMap() {
    return sourceExtension;
  },
  get targetExtensionMap() {
    return targetExtension;
  },
  reload: load,
  adapters: loadedAdapters,
  isMinifiable: minify.isMinifiable,
  read: function (pathName, options) {
    options = options || {};

    options.sourceMap = options.sourceMap === false ? false : true;

    var extension = Path.extname(pathName);
    var adapters = extensionMap[extension];
    var adapter = !dontCompile(pathName) && adapters && adapters[0];

    var continuation;

    if (adapter) {
      var transpilerOptions = Object.assign({}, options, {
        sourcemap: options.sourceMap
      });

      if (adapter.engineName === 'node-sass') {
        transpilerOptions.includePaths = [Path.dirname(pathName)];
      }

      var addInfo = function(compiled) {
        compiled.extension = '.' + adapter.output;
        compiled.inputPath = pathName;
        return when.resolve(compiled);
      };

      continuation = adapter.renderFile(pathName, transpilerOptions).then(addInfo);

    } else {
      continuation = fs.readFile(pathName, 'utf8').then(function (source) {
        return when.resolve({
          result: source,
          extension: extension,
          inputPath: pathName
        });
      });
    }

    if (options.minify) {
      continuation = continuation.then(function(compiled) {
        return minify(compiled, options);
      });
    }

    return continuation;
  }
};
<commit_msg>To compile babel files use 'babel.js' extension<commit_after>'use strict';

if (global && global.babyTolkCompilerModulePath) {
  require('app-module-path').addPath(global.babyTolkCompilerModulePath);
}

var Path = require('path');
var when = require('when');
var node = require('when/node');
var fs = node.liftAll(require('fs'));
var accord = require('accord');
var minify = require('./minify');

var extensionMap;
var loadedAdapters;
var targetExtension;
var sourceExtension;

// Whitelisted adapters
var adapters = [
  'LiveScript',
  'babel',
  'coco',
  'coffee-script',
  'dogescript',
  'less',
  'markdown',
  'myth',
  'scss',
  'stylus',
  'swig',
  'jade'
];

function load() {
  extensionMap = {};
  loadedAdapters = [];

  Object.keys(accord.all()).map(function (engine) {
    if (adapters.indexOf(engine) === -1) {
      return undefined;
    }

    try {
      return accord.load(engine, global && global.babyTolkCompilerModulePath || null);
    } catch (e) {
      if (e.code !== 'MODULE_NOT_FOUND' && e.message.indexOf('Cannot find module') === -1) {
        console.error(e.message.replace(/^error: ?/i, 'Accord Error: ') + '. Try updating to the latest version');
      }
      // else {
      //   console.error('Missing adapter:', engine);
      // }
    }
  }).filter(function (engine) {
    return engine;
  }).forEach(function (adapter) {
    if (adapter.engineName === 'babel' || adapter.engineName === 'babel-core') {
      // Monkey-patching Babel adapter so that it doesn't try and compile all .js files
      adapter.extensions = ['babel.js'];
    }
    loadedAdapters.push(adapter);
    var extensions = adapter.extensions.map(function (extension) { return '.' + extension; });

    extensions.forEach(function (extension) {
      if (!Array.isArray(extensionMap[extension])) {
        extensionMap[extension] = [];
      }

      extensionMap[extension].push(adapter);
    });
  });

  targetExtension = {};
  sourceExtension = {};

  Object.keys(extensionMap).forEach(function (sourceExt) {
    var adapters = extensionMap[sourceExt];
    var targetExt = '.' + adapters[0].output;

    targetExtension[sourceExt] = targetExt;

    if (!sourceExtension[targetExt]) {
      sourceExtension[targetExt] = [];
    }

    sourceExtension[targetExt].push(sourceExt);
  });
}
load();

var dontCompile = function (pathName) {
  // Baby Tolk wont compile files that begin with an underscore `_`.
  // This is by convention.
  var baseName = Path.basename(pathName);
  return baseName[0] === '_';
};

module.exports = {
  get extensions() {
    return extensionMap;
  },
  get sourceExtensionMap() {
    return sourceExtension;
  },
  get targetExtensionMap() {
    return targetExtension;
  },
  reload: load,
  adapters: loadedAdapters,
  isMinifiable: minify.isMinifiable,
  read: function (pathName, options) {
    options = options || {};

    options.sourceMap = options.sourceMap === false ? false : true;

    var extension = Path.extname(pathName);
    var adapters = extensionMap[extension];
    var adapter = !dontCompile(pathName) && adapters && adapters[0];

    var continuation;

    if (adapter) {
      var transpilerOptions = Object.assign({}, options, {
        sourcemap: options.sourceMap
      });

      if (adapter.engineName === 'node-sass') {
        transpilerOptions.includePaths = [Path.dirname(pathName)];
      }

      var addInfo = function(compiled) {
        compiled.extension = '.' + adapter.output;
        compiled.inputPath = pathName;
        return when.resolve(compiled);
      };

      continuation = adapter.renderFile(pathName, transpilerOptions).then(addInfo);

    } else {
      continuation = fs.readFile(pathName, 'utf8').then(function (source) {
        return when.resolve({
          result: source,
          extension: extension,
          inputPath: pathName
        });
      });
    }

    if (options.minify) {
      continuation = continuation.then(function(compiled) {
        return minify(compiled, options);
      });
    }

    return continuation;
  }
};
<|endoftext|>


<commit_before><commit_msg>Issue 1703: Firebug lite incorrect reports the evaluation result of "undefined" as "null"<commit_after><|endoftext|>


<commit_before>import { types as tt } from "../tokenizer/types";
import Parser from "./index";
import { reservedWords } from "../util/identifier";

const pp = Parser.prototype;

// Convert existing expression atom to assignable pattern
// if possible.

pp.toAssignable = function (node, isBinding) {
  if (node) {
    switch (node.type) {
      case "Identifier":
      case "ObjectPattern":
      case "ArrayPattern":
      case "AssignmentPattern":
        break;

      case "ObjectExpression":
        node.type = "ObjectPattern";
        for (let prop of (node.properties: Array)) {
          if (prop.type === "SpreadProperty") continue;
          if (prop.kind !== "init") this.raise(prop.key.start, "Object pattern can't contain getter or setter");
          this.toAssignable(prop.value, isBinding);
        }
        break;

      case "ArrayExpression":
        node.type = "ArrayPattern";
        this.toAssignableList(node.elements, isBinding);
        break;

      case "AssignmentExpression":
        if (node.operator === "=") {
          node.type = "AssignmentPattern";
          delete node.operator;
        } else {
          this.raise(node.left.end, "Only '=' operator can be used for specifying default value.");
        }
        break;

      case "MemberExpression":
        if (!isBinding) break;

      default:
        this.raise(node.start, "Assigning to rvalue");
    }
  }
  return node;
};

// Convert list of expression atoms to binding list.

pp.toAssignableList = function (exprList, isBinding) {
  let end = exprList.length;
  if (end) {
    let last = exprList[end - 1];
    if (last && last.type === "RestElement") {
      --end;
    } else if (last && last.type === "SpreadElement") {
      last.type = "RestElement";
      let arg = last.argument;
      this.toAssignable(arg, isBinding);
      if (arg.type !== "Identifier" && arg.type !== "MemberExpression" && arg.type !== "ArrayPattern") {
        this.unexpected(arg.start);
      }
      --end;
    }
  }
  for (let i = 0; i < end; i++) {
    let elt = exprList[i];
    if (elt) this.toAssignable(elt, isBinding);
  }
  return exprList;
};

// Convert list of expression atoms to a list of

pp.toReferencedList = function (exprList) {
  return exprList;
};

// Parses spread element.

pp.parseSpread = function (refShorthandDefaultPos) {
  let node = this.startNode();
  this.next();
  node.argument = this.parseMaybeAssign(refShorthandDefaultPos);
  return this.finishNode(node, "SpreadElement");
};

pp.parseRest = function () {
  let node = this.startNode();
  this.next();
  if (this.match(tt.name) || this.match(tt.bracketL)) {
    node.argument = this.parseBindingAtom();
  } else {
    this.unexpected();
  }
  return this.finishNode(node, "RestElement");
};

// Parses lvalue (assignable) atom.

pp.parseBindingAtom = function () {
  if (this.match(tt.name)) {
    return this.parseIdentifier(true);
  }

  switch (this.state.type) {
    case tt.bracketL:
      let node = this.startNode();
      this.next();
      node.elements = this.parseBindingList(tt.bracketR, true, true);
      return this.finishNode(node, "ArrayPattern");

    case tt.braceL:
      return this.parseObj(true);

    default:
      this.unexpected();
  }
};

pp.parseBindingList = function (close, allowEmpty, allowTrailingComma) {
  var elts = [], first = true;
  while (!this.eat(close)) {
    if (first) first = false;
    else this.expect(tt.comma);
    if (allowEmpty && this.match(tt.comma)) {
      elts.push(null);
    } else if (allowTrailingComma && this.eat(close)) {
      break;
    } else if (this.match(tt.ellipsis)) {
      elts.push(this.parseAssignableListItemTypes(this.parseRest()));
      this.expect(close);
      break;
    } else {
      var left = this.parseMaybeDefault();
      this.parseAssignableListItemTypes(left);
      elts.push(this.parseMaybeDefault(null, null, left));
    }
  }
  return elts;
};

pp.parseAssignableListItemTypes = function (param) {
  return param;
};

// Parses assignment pattern around given atom if possible.

pp.parseMaybeDefault = function (startPos, startLoc, left) {
  startLoc = startLoc || this.state.startLoc;
  startPos = startPos || this.state.start;
  left = left || this.parseBindingAtom();
  if (!this.eat(tt.eq)) return left;

  let node = this.startNodeAt(startPos, startLoc);
  node.left = left;
  node.right = this.parseMaybeAssign();
  return this.finishNode(node, "AssignmentPattern");
};

// Verify that a node is an lval — something that can be assigned
// to.

pp.checkLVal = function (expr, isBinding, checkClashes) {
  switch (expr.type) {
    case "Identifier":
      if (this.state.strict && (reservedWords.strictBind(expr.name) || reservedWords.strict(expr.name))) {
        this.raise(expr.start, (isBinding ? "Binding " : "Assigning to ") + expr.name + " in strict mode");
      }

      if (checkClashes) {
        if (checkClashes[expr.name]) {
          this.raise(expr.start, "Argument name clash in strict mode");
        } else {
          checkClashes[expr.name] = true;
        }
      }
      break;

    case "MemberExpression":
      if (isBinding) this.raise(expr.start, (isBinding ? "Binding" : "Assigning to") + " member expression");
      break;

    case "ObjectPattern":
      for (let prop of (expr.properties: Array)) {
        if (prop.type === "Property") prop = prop.value;
        this.checkLVal(prop, isBinding, checkClashes);
      }
      break;

    case "ArrayPattern":
      for (let elem of (expr.elements: Array)) {
        if (elem) this.checkLVal(elem, isBinding, checkClashes);
      }
      break;

    case "AssignmentPattern":
      this.checkLVal(expr.left, isBinding, checkClashes);
      break;

    case "RestProperty":
    case "RestElement":
      this.checkLVal(expr.argument, isBinding, checkClashes);
      break;

    default:
      this.raise(expr.start, (isBinding ? "Binding" : "Assigning to") + " rvalue");
  }
};
<commit_msg>only allow identifiers as rest expressions<commit_after>import { types as tt } from "../tokenizer/types";
import Parser from "./index";
import { reservedWords } from "../util/identifier";

const pp = Parser.prototype;

// Convert existing expression atom to assignable pattern
// if possible.

pp.toAssignable = function (node, isBinding) {
  if (node) {
    switch (node.type) {
      case "Identifier":
      case "ObjectPattern":
      case "ArrayPattern":
      case "AssignmentPattern":
        break;

      case "ObjectExpression":
        node.type = "ObjectPattern";
        for (let prop of (node.properties: Array)) {
          if (prop.type === "SpreadProperty") continue;
          if (prop.kind !== "init") this.raise(prop.key.start, "Object pattern can't contain getter or setter");
          this.toAssignable(prop.value, isBinding);
        }
        break;

      case "ArrayExpression":
        node.type = "ArrayPattern";
        this.toAssignableList(node.elements, isBinding);
        break;

      case "AssignmentExpression":
        if (node.operator === "=") {
          node.type = "AssignmentPattern";
          delete node.operator;
        } else {
          this.raise(node.left.end, "Only '=' operator can be used for specifying default value.");
        }
        break;

      case "MemberExpression":
        if (!isBinding) break;

      default:
        this.raise(node.start, "Assigning to rvalue");
    }
  }
  return node;
};

// Convert list of expression atoms to binding list.

pp.toAssignableList = function (exprList, isBinding) {
  let end = exprList.length;
  if (end) {
    let last = exprList[end - 1];
    if (last && last.type === "RestElement") {
      --end;
    } else if (last && last.type === "SpreadElement") {
      last.type = "RestElement";
      let arg = last.argument;
      this.toAssignable(arg, isBinding);
      if (arg.type !== "Identifier" && arg.type !== "MemberExpression" && arg.type !== "ArrayPattern") {
        this.unexpected(arg.start);
      }
      --end;
    }
  }
  for (let i = 0; i < end; i++) {
    let elt = exprList[i];
    if (elt) this.toAssignable(elt, isBinding);
  }
  return exprList;
};

// Convert list of expression atoms to a list of

pp.toReferencedList = function (exprList) {
  return exprList;
};

// Parses spread element.

pp.parseSpread = function (refShorthandDefaultPos) {
  let node = this.startNode();
  this.next();
  node.argument = this.parseMaybeAssign(refShorthandDefaultPos);
  return this.finishNode(node, "SpreadElement");
};

pp.parseRest = function () {
  let node = this.startNode();
  this.next();
  node.argument = this.parseIdentifier();
  return this.finishNode(node, "RestElement");
};

// Parses lvalue (assignable) atom.

pp.parseBindingAtom = function () {
  switch (this.state.type) {
    case tt.name:
      return this.parseIdentifier(true);

    case tt.bracketL:
      let node = this.startNode();
      this.next();
      node.elements = this.parseBindingList(tt.bracketR, true, true);
      return this.finishNode(node, "ArrayPattern");

    case tt.braceL:
      return this.parseObj(true);

    default:
      this.unexpected();
  }
};

pp.parseBindingList = function (close, allowEmpty, allowTrailingComma) {
  var elts = [], first = true;
  while (!this.eat(close)) {
    if (first) first = false;
    else this.expect(tt.comma);
    if (allowEmpty && this.match(tt.comma)) {
      elts.push(null);
    } else if (allowTrailingComma && this.eat(close)) {
      break;
    } else if (this.match(tt.ellipsis)) {
      elts.push(this.parseAssignableListItemTypes(this.parseRest()));
      this.expect(close);
      break;
    } else {
      var left = this.parseMaybeDefault();
      this.parseAssignableListItemTypes(left);
      elts.push(this.parseMaybeDefault(null, null, left));
    }
  }
  return elts;
};

pp.parseAssignableListItemTypes = function (param) {
  return param;
};

// Parses assignment pattern around given atom if possible.

pp.parseMaybeDefault = function (startPos, startLoc, left) {
  startLoc = startLoc || this.state.startLoc;
  startPos = startPos || this.state.start;
  left = left || this.parseBindingAtom();
  if (!this.eat(tt.eq)) return left;

  let node = this.startNodeAt(startPos, startLoc);
  node.left = left;
  node.right = this.parseMaybeAssign();
  return this.finishNode(node, "AssignmentPattern");
};

// Verify that a node is an lval — something that can be assigned
// to.

pp.checkLVal = function (expr, isBinding, checkClashes) {
  switch (expr.type) {
    case "Identifier":
      if (this.state.strict && (reservedWords.strictBind(expr.name) || reservedWords.strict(expr.name))) {
        this.raise(expr.start, (isBinding ? "Binding " : "Assigning to ") + expr.name + " in strict mode");
      }

      if (checkClashes) {
        if (checkClashes[expr.name]) {
          this.raise(expr.start, "Argument name clash in strict mode");
        } else {
          checkClashes[expr.name] = true;
        }
      }
      break;

    case "MemberExpression":
      if (isBinding) this.raise(expr.start, (isBinding ? "Binding" : "Assigning to") + " member expression");
      break;

    case "ObjectPattern":
      for (let prop of (expr.properties: Array)) {
        if (prop.type === "Property") prop = prop.value;
        this.checkLVal(prop, isBinding, checkClashes);
      }
      break;

    case "ArrayPattern":
      for (let elem of (expr.elements: Array)) {
        if (elem) this.checkLVal(elem, isBinding, checkClashes);
      }
      break;

    case "AssignmentPattern":
      this.checkLVal(expr.left, isBinding, checkClashes);
      break;

    case "RestProperty":
    case "RestElement":
      this.checkLVal(expr.argument, isBinding, checkClashes);
      break;

    default:
      this.raise(expr.start, (isBinding ? "Binding" : "Assigning to") + " rvalue");
  }
};
<|endoftext|>


<commit_before>'use strict';

var request = require('superagent');
var glimpse = require('glimpse');

module.exports = {
    triggerGetLastestSummaries: function() {
        // TODO: need to pull this out different source
        var uri = '/glimpse/data/history';

        request
            //TODO: this will probably change in time to the below
            //.query({ latest: true })
            .get(uri)
            .set('Accept', 'application/json')
            .end(function(err, res){
                // this is done because we want to delay the response
                if (!FAKE_SERVER) {
                    if (res.ok) {
                        glimpse.emit('data.message.summary.found.remote', res.body);
                    }
                    else {
                        console.log('ERROR: Error reaching server for summary request')
                    }
                }
            });
    },
    triggerGetDetailsFor: function(requestId) {
        // TODO: need to pull this out different source
        var uri = '/glimpse/data/messages/' + requestId;

        request
            .get(uri)
            //TODO: this will probably change in time to the below
            //.query({ context: requestId })
            .set('Accept', 'application/json')
            .end(function(err, res){
                // this is done because we want to delay the response
                if (!FAKE_SERVER) {
                    if (res.ok) {
                        glimpse.emit('data.message.summary.found.remote', res.body);
                    }
                    else {
                        console.log('ERROR: Error reaching server for summary request')
                    }
                }
            });
    }
};
<commit_msg>Updated path for message history resource<commit_after>'use strict';

var request = require('superagent');
var glimpse = require('glimpse');

module.exports = {
    triggerGetLastestSummaries: function() {
        // TODO: need to pull this out different source
        var uri = '/Glimpse/MessageHistory';

        request
            //TODO: this will probably change in time to the below
            //.query({ latest: true })
            .get(uri)
            .set('Accept', 'application/json')
            .end(function(err, res){
                // this is done because we want to delay the response
                if (!FAKE_SERVER) {
                    if (res.ok) {
                        glimpse.emit('data.message.summary.found.remote', res.body);
                    }
                    else {
                        console.log('ERROR: Error reaching server for summary request')
                    }
                }
            });
    },
    triggerGetDetailsFor: function(requestId) {
        // TODO: need to pull this out different source
        var uri = '/Glimpse/MessageHistory/' + requestId;

        request
            .get(uri)
            //TODO: this will probably change in time to the below
            //.query({ context: requestId })
            .set('Accept', 'application/json')
            .end(function(err, res){
                // this is done because we want to delay the response
                if (!FAKE_SERVER) {
                    if (res.ok) {
                        glimpse.emit('data.message.summary.found.remote', res.body);
                    }
                    else {
                        console.log('ERROR: Error reaching server for summary request')
                    }
                }
            });
    }
};
<|endoftext|>


<commit_before>function strval (str) {
  // From: http://phpjs.org/functions
  // +   original by: Brett Zamir (http://brett-zamir.me)
  // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
  // %        note 1: Comment out the entire switch if you want JS-like behavior instead of PHP behavior
  // -    depends on: gettype
  // *     example 1: strval({red: 1, green: 2, blue: 3, white: 4});
  // *     returns 1: 'Array'
  var type = '';

  if (str === null) {
    return '';
  }

  type = this.gettype(str);
  switch (type) {
  case 'boolean':
    if (str === true) {
      return '1';
    }
    return '';
  case 'array':
    return 'Array';
  case 'object':
    return 'Object';
  }

  return str;
}
<commit_msg>Fixed strval#1<commit_after>function strval (str) {
  // From: http://phpjs.org/functions
  // +   original by: Brett Zamir (http://brett-zamir.me)
  // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
  // -    depends on: gettype
  // *     example 1: strval({red: 1, green: 2, blue: 3, white: 4});
  // *     returns 1: 'Object'

  var type = '';

  if (str === null) {
    return '';
  }

  type = this.gettype(str);

  // Comment out the entire switch if you want JS-like
  // behavior instead of PHP behavior
  switch (type) {
  case 'boolean':
    if (str === true) {
      return '1';
    }
    return '';
  case 'array':
    return 'Array';
  case 'object':
    return 'Object';
  }

  return str;
}
<|endoftext|>