<commit_before>var education = {
	"schools" : [
	{
		"name" : "Ramapo College of New Jersey",
		"location" : "Mahwah, New Jersey",
		"degree" : "Bachelors of Arts",
		"majors": [
		"Economics"
		],
		"dates" : "Spring 2014",
		"url": "http://www.ramapo.edu",
	}],
	"onlineCourses": [
		{
		"title" : "Intro to programming Nanodegree",
		"date" : "December 2015 to May 2016",
		"url" : "https://www.udacity.com/course/intro-to-programming-nanodegree--nd000",
		"school": "Udacity"
	},
	{
		"title" : "Front end programming Nanodegree",
		"date" : "June 2016 to present",
		"url" : "https://www.udacity.com/course/front-end-web-developer-nanodegree--nd001?v=fe1",
		"school" : "Udacity"
	}
	]
};

var bio = {
	"name": "Michael Speranza",
	"role": "Michael Speranza - Looking for Entry-level Front-end Oppurtunity",
	"contacts": {
		"mobile": "2012751982",
		"github": "https://github.com/mikespe",
		"email": "mikesperanza34@gmail.com",
		"location": "Glen Rock, NJ"
	},
	"skills": [
		"HTML",
		"CSS",
		"Wireframing",
		"Mockup to Code",
		"JavaScript",
		"jQuery",
		"Bootstrap",
		"Grunt",
		"Gulp",
		"MySql",
		"Wordpress",
		"CRP Optimization",
		"Responsive Design",
		"Image Optimization",
		"Mobile-Friendly Design",
		"Git",
		"CSS frameworks",
		"Problem Solving"
	],
	"biopic": "images/me.PNG",
	"welcomeMessage": "Hey, Welcome to Michael Speranza's Resume",
	"githublink": "https://github.com/mikespe",
	"resumelink": "https://docs.google.com/document/d/1PHuvJZ5vSpaUvBwst4Gxx_wVsizSlYZgzjhhcWMgS9Y/edit?usp=sharing"
};

var work = {
	"jobs" : [
	{
		"employer" : "H Grant Designs LLC",
		"link" : "http://hgrantdesigns.com/",
		"title" : "Frontend Programming Consultant",
		"location" : "Glen Rock, NJ",
		"dates" : "October 2016 to Present",
		"description" : "Solve and consult on a variety of HTML,CSS,Javascript,Design, and Optimization issues"
	},
	{
		"employer" : "Konica Minolta",
		"link" : "http://konicaminolta.us/",
		"title" : "Purchasing Administrator",
		"location" : "Ramsey, NJ",
		"dates" : "Dec 2014 to Nov 2015",
		"description" : "Reconciled any and all problems involving the process of receiving and sending Purchase orders to vendors"
	},

	{
		"employer" : "General Exports Network",
		"link" : "http://www.globalexportnetwork.com/en/about-us/",
		"title" : "Research Analyst",
		"location" : "Mahwah, NJ",
		"dates" : "Feb 2014 to Dec 2014",
		"description" : "Provided detailed reports and research rundowns on several marketplaces and products"
	}
	]
};

var projects = {
	"projects" : [
	{
		"title" : "Frogger game",
		"link" : "https://mikespe.github.io/FroggerJS/",
		"dates" : "September 2016",
		"description" : "Browser frogger using Object oriented JS",
		"images" : ["images/frogger.PNG"]
	},
	{
		"title" : "Responsive Blog",
		"link" : "https://mikespe.github.io/responsive-portfolio-example/",
		"dates" : "July 2016",
		"description" : "Simple picture and link layout, Responsive design",
		"images" : ["images/bootstrap.PNG"]
	}
	]
    };

projects.display = function() {
	for(x = 0; x < projects.projects.length; x++) {
		$("#projects").append(HTMLprojectStart);

		var formattedtitle = HTMLprojectTitle.replace("%data%", projects.projects[x].title).replace("#", projects.projects[x].link);
		$(".project-entry:last").append(formattedtitle);

		var formattedHTMLprojectDates = HTMLprojectDates.replace("%data%", projects.projects[x].dates);
		$(".project-entry:last").append(formattedHTMLprojectDates);

		var formattedHTMLprojectDescription = HTMLprojectDescription.replace("%data%", projects.projects[x].description);
		$(".project-entry:last").append(formattedHTMLprojectDescription);

		var formattedHTMLprojectImage = HTMLprojectImage.replace("%data%", projects.projects[x].images);
		$(".project-entry:last").append(formattedHTMLprojectImage);
	}
};

work.display = function(){
	for(items = 0; items < work.jobs.length; items++) {
		$("#workExperience").append(HTMLworkStart);
		var formattedemployer = HTMLworkEmployer.replace("%data%", work.jobs[items].employer).replace("#", work.jobs[items].link);
		var formattedtitle = HTMLworkTitle.replace("%data%", work.jobs[items].title);
		var together = formattedemployer +
			formattedtitle;
		var formattedlocation = HTMLworkLocation.replace("%data%", work.jobs[items].location);
		var formatteddates = HTMLworkDates.replace("%data%", work.jobs[items].dates);
		var formatteddescription = HTMLworkDescription.replace("%data%", work.jobs[items].description);
		$(".work-entry:last").append(together);
		$(".work-entry:last").append(formattedlocation);
		$(".work-entry:last").append(formatteddates);
		$(".work-entry:last").append(formatteddescription);
		}
		};

education.display = function(){
	for(items = 0; items < education.schools.length; items++) {
		$("#education").append(HTMLschoolStart);
		var formattedHTMLschoolName = HTMLschoolName.replace("%data%", education.schools[items].name).replace("#", education.schools[items].url);
		var formattedHTMLschoolDegree = HTMLschoolDegree.replace("%data%", education.schools[items].degree);
		var formattedHTMLschoolLocation = HTMLschoolLocation.replace("%data%", education.schools[items].location);
		var formattedHTMLschoolDates = HTMLschoolDates.replace("%data%", education.schools[items].dates);
		$(".education-entry:last").append(formattedHTMLschoolName + formattedHTMLschoolDegree);
		$(".education-entry:last").append(formattedHTMLschoolLocation);
		$(".education-entry:last").append(formattedHTMLschoolDates);
		var formattedHTMLschoolMajor2 = HTMLschoolMajor.replace("%data%", education.schools[items].majors);
		var formattedHTMLonlineURL = HTMLonlineURL.replace("%data%", education.schools[items].url);
		$(".education-entry:last").append(formattedHTMLschoolMajor2);
	}
		for(i = 0; i < education.onlineCourses.length; i++) {
		$("#education").append(HTMLschoolStart);
		$("#education-entry:last").append(HTMLonlineClasses);
		var formattedHTMLonlineTitle = HTMLonlineTitle.replace("%data%", education.onlineCourses[i].title).replace("#", education.onlineCourses[i].url);
		var formattedHTMLonlineSchool = HTMLonlineSchool.replace("%data%", education.onlineCourses[i].school);
		var formattedHTMLonlineURL = HTMLonlineURL.replace("%data%", education.onlineCourses[i].url);
		var formattedHTMLonlineDates = HTMLonlineDates.replace("%data%", education.onlineCourses[i].date);
		$(".education-entry:last").append(formattedHTMLonlineTitle + formattedHTMLonlineSchool);
		$(".education-entry:last").append(formattedHTMLonlineDates);
	}
};

bio.display = function(){
	$("#header").append(HTMLskillsStart);
	var topc = $('#topContacts');
	var footc = $("#footerContacts");
	for(x=0; x<bio.skills.length; x++) {
		var formattedskills = HTMLskills.replace("%data%", bio.skills[x]);
		$("#skills").append(formattedskills);
		}
	var formattedname = HTMLheaderName.replace("%data%", name);
	var formattedHTMLemail = HTMLemail.replace("%data%", bio.contacts.email);
	topc.append(formattedHTMLemail);
	footc.append(formattedHTMLemail);
	var formattedrole = HTMLheaderRole.replace("%data%", bio.role);
	$("#header").prepend(formattedrole);
	$("#header").prepend(formattedname);
	var formattedcell = HTMLmobile.replace("%data%", bio.contacts.mobile);
	topc.prepend(formattedcell);
	footc.prepend(formattedcell);
	var pic = HTMLbioPic.replace("%data%", bio.biopic);
	$("#main").prepend(pic);
	var formattedwelcome = HTMLwelcomeMsg.replace("%data%", bio.welcomeMessage);
    $("#header").prepend(formattedwelcome);
	var formattedHTMLgithub = HTMLgithub.replace("%data%", bio.contacts.github).replace("#", bio.contacts.githublink);
	topc.append(formattedHTMLgithub);
	footc.append(formattedHTMLgithub);
	var formattedHTMLlocation = HTMLlocation.replace("%data%", bio.contacts.location);
	topc.append(formattedHTMLlocation);
	footc.append(formattedHTMLlocation);
	var formattedHTMLresume = HTMLresume.replace("%data%", bio.resumelink);
	topc.prepend(formattedHTMLresume);
	};

//$("#main").append(internationalizeButton);
function inName() {
	name = name.trim().split(" ");
	name[1] = name[1].toUpperCase();
	name[0] = name[0].slice(0,1).toUpperCase() + name[0].slice(1).toLowerCase();
	return name[0] + " " + name[1];
}

projects.display();
work.display();
education.display();
bio.display();

// DOESNT WORK WHEN HOSTING ON GITHUB$("#mapDiv").append(googleMap);
<commit_msg>add neighborhood map<commit_after>var education = {
	"schools" : [
	{
		"name" : "Ramapo College of New Jersey",
		"location" : "Mahwah, New Jersey",
		"degree" : "Bachelors of Arts",
		"majors": [
		"Economics"
		],
		"dates" : "Spring 2014",
		"url": "http://www.ramapo.edu",
	}],
	"onlineCourses": [
		{
		"title" : "Intro to programming Nanodegree",
		"date" : "December 2015 to May 2016",
		"url" : "https://www.udacity.com/course/intro-to-programming-nanodegree--nd000",
		"school": "Udacity"
	},
	{
		"title" : "Front end programming Nanodegree",
		"date" : "June 2016 to present",
		"url" : "https://www.udacity.com/course/front-end-web-developer-nanodegree--nd001?v=fe1",
		"school" : "Udacity"
	}
	]
};

var bio = {
	"name": "Michael Speranza",
	"role": "Michael Speranza - Looking for Entry-level Front-end Oppurtunity",
	"contacts": {
		"mobile": "2012751982",
		"github": "https://github.com/mikespe",
		"email": "mikesperanza34@gmail.com",
		"location": "Glen Rock, NJ"
	},
	"skills": [
		"HTML",
		"CSS",
		"JavaScript",
		"jQuery",
		"Bootstrap",
		"Wireframing",
		"Mockup to Code",
		"Grunt",
		"Gulp",
		"Sql",
		"php",
		"Python",
		"AJAX",
		"Wordpress",
		"CRP Optimization",
		"Responsive Design",
		"Image Optimization",
		"Mobile-Friendly Design",
		"Git",
		"CSS frameworks",
		"Problem Solving"
	],
	"biopic": "images/me.PNG",
	"welcomeMessage": "Hey, Welcome to Michael Speranza's Resume",
	"githublink": "https://github.com/mikespe",
	"resumelink": "https://docs.google.com/document/d/1PHuvJZ5vSpaUvBwst4Gxx_wVsizSlYZgzjhhcWMgS9Y/edit?usp=sharing"
};

var work = {
	"jobs" : [
	{
		"employer" : "H Grant Designs LLC",
		"link" : "http://hgrantdesigns.com/",
		"title" : "Frontend Programming Consultant",
		"location" : "Glen Rock, NJ",
		"dates" : "October 2016 to Present",
		"description" : "Solve and consult on a variety of HTML,CSS,Javascript,Design, and Optimization issues"
	},
	{
		"employer" : "Konica Minolta",
		"link" : "http://konicaminolta.us/",
		"title" : "Purchasing Administrator",
		"location" : "Ramsey, NJ",
		"dates" : "Dec 2014 to Nov 2015",
		"description" : "Reconciled any and all problems involving the process of receiving and sending Purchase orders to vendors"
	},

	{
		"employer" : "General Exports Network",
		"link" : "http://www.globalexportnetwork.com/en/about-us/",
		"title" : "Research Analyst",
		"location" : "Mahwah, NJ",
		"dates" : "Feb 2014 to Dec 2014",
		"description" : "Provided detailed reports and research rundowns on several marketplaces and products"
	}
	]
};

var projects = {
	"projects" : [
		{
			"title" : "Neighborhood Map",
			"link" : "https://github.com/mikespe/neighborhood-map",
			"dates" : "December 2016",
			"description" : "Interactive Map Created Entirely by me using Google Maps API, Foursquare API, Javascript, jQuery and Knockout.JS",
			"images" : ["images/neighborhoodmap.PNG"]
		},
	{
		"title" : "Frogger game",
		"link" : "https://mikespe.github.io/FroggerJS/",
		"dates" : "September 2016",
		"description" : "Browser frogger using Object oriented JS",
		"images" : ["images/frogger.PNG"]
	},
	]
    };

projects.display = function() {
	for(x = 0; x < projects.projects.length; x++) {
		$("#projects").append(HTMLprojectStart);

		var formattedtitle = HTMLprojectTitle.replace("%data%", projects.projects[x].title).replace("#", projects.projects[x].link);
		$(".project-entry:last").append(formattedtitle);

		var formattedHTMLprojectDates = HTMLprojectDates.replace("%data%", projects.projects[x].dates);
		$(".project-entry:last").append(formattedHTMLprojectDates);

		var formattedHTMLprojectDescription = HTMLprojectDescription.replace("%data%", projects.projects[x].description);
		$(".project-entry:last").append(formattedHTMLprojectDescription);

		var formattedHTMLprojectImage = HTMLprojectImage.replace("%data%", projects.projects[x].images);
		$(".project-entry:last").append(formattedHTMLprojectImage);
	}
};

work.display = function(){
	for(items = 0; items < work.jobs.length; items++) {
		$("#workExperience").append(HTMLworkStart);
		var formattedemployer = HTMLworkEmployer.replace("%data%", work.jobs[items].employer).replace("#", work.jobs[items].link);
		var formattedtitle = HTMLworkTitle.replace("%data%", work.jobs[items].title);
		var together = formattedemployer +
			formattedtitle;
		var formattedlocation = HTMLworkLocation.replace("%data%", work.jobs[items].location);
		var formatteddates = HTMLworkDates.replace("%data%", work.jobs[items].dates);
		var formatteddescription = HTMLworkDescription.replace("%data%", work.jobs[items].description);
		$(".work-entry:last").append(together);
		$(".work-entry:last").append(formattedlocation);
		$(".work-entry:last").append(formatteddates);
		$(".work-entry:last").append(formatteddescription);
		}
		};

education.display = function(){
	for(items = 0; items < education.schools.length; items++) {
		$("#education").append(HTMLschoolStart);
		var formattedHTMLschoolName = HTMLschoolName.replace("%data%", education.schools[items].name).replace("#", education.schools[items].url);
		var formattedHTMLschoolDegree = HTMLschoolDegree.replace("%data%", education.schools[items].degree);
		var formattedHTMLschoolLocation = HTMLschoolLocation.replace("%data%", education.schools[items].location);
		var formattedHTMLschoolDates = HTMLschoolDates.replace("%data%", education.schools[items].dates);
		$(".education-entry:last").append(formattedHTMLschoolName + formattedHTMLschoolDegree);
		$(".education-entry:last").append(formattedHTMLschoolLocation);
		$(".education-entry:last").append(formattedHTMLschoolDates);
		var formattedHTMLschoolMajor2 = HTMLschoolMajor.replace("%data%", education.schools[items].majors);
		var formattedHTMLonlineURL = HTMLonlineURL.replace("%data%", education.schools[items].url);
		$(".education-entry:last").append(formattedHTMLschoolMajor2);
	}
		for(i = 0; i < education.onlineCourses.length; i++) {
		$("#education").append(HTMLschoolStart);
		$("#education-entry:last").append(HTMLonlineClasses);
		var formattedHTMLonlineTitle = HTMLonlineTitle.replace("%data%", education.onlineCourses[i].title).replace("#", education.onlineCourses[i].url);
		var formattedHTMLonlineSchool = HTMLonlineSchool.replace("%data%", education.onlineCourses[i].school);
		var formattedHTMLonlineURL = HTMLonlineURL.replace("%data%", education.onlineCourses[i].url);
		var formattedHTMLonlineDates = HTMLonlineDates.replace("%data%", education.onlineCourses[i].date);
		$(".education-entry:last").append(formattedHTMLonlineTitle + formattedHTMLonlineSchool);
		$(".education-entry:last").append(formattedHTMLonlineDates);
	}
};

bio.display = function(){
	$("#header").append(HTMLskillsStart);
	var topc = $('#topContacts');
	var footc = $("#footerContacts");
	for(x=0; x<bio.skills.length; x++) {
		var formattedskills = HTMLskills.replace("%data%", bio.skills[x]);
		$("#skills").append(formattedskills);
		}
	var formattedname = HTMLheaderName.replace("%data%", name);
	var formattedHTMLemail = HTMLemail.replace("%data%", bio.contacts.email);
	topc.append(formattedHTMLemail);
	footc.append(formattedHTMLemail);
	var formattedrole = HTMLheaderRole.replace("%data%", bio.role);
	$("#header").prepend(formattedrole);
	$("#header").prepend(formattedname);
	var formattedcell = HTMLmobile.replace("%data%", bio.contacts.mobile);
	topc.prepend(formattedcell);
	footc.prepend(formattedcell);
	var pic = HTMLbioPic.replace("%data%", bio.biopic);
	$("#main").prepend(pic);
	var formattedwelcome = HTMLwelcomeMsg.replace("%data%", bio.welcomeMessage);
    $("#header").prepend(formattedwelcome);
	var formattedHTMLgithub = HTMLgithub.replace("%data%", bio.contacts.github).replace("#", bio.contacts.githublink);
	topc.append(formattedHTMLgithub);
	footc.append(formattedHTMLgithub);
	var formattedHTMLlocation = HTMLlocation.replace("%data%", bio.contacts.location);
	topc.append(formattedHTMLlocation);
	footc.append(formattedHTMLlocation);
	var formattedHTMLresume = HTMLresume.replace("%data%", bio.resumelink);
	topc.prepend(formattedHTMLresume);
	};

//$("#main").append(internationalizeButton);
function inName() {
	name = name.trim().split(" ");
	name[1] = name[1].toUpperCase();
	name[0] = name[0].slice(0,1).toUpperCase() + name[0].slice(1).toLowerCase();
	return name[0] + " " + name[1];
}

projects.display();
work.display();
education.display();
bio.display();

// DOESNT WORK WHEN HOSTING ON GITHUB$("#mapDiv").append(googleMap);
<|endoftext|>


<commit_before>const { BrowserWindow } = require('electron');
const path = require('path');
const Store = require('electron-store');
const semver = require('semver');
const Window = require('./Window');
const competitions = require('../competitions/competitions');
const changelogWindow = require('./changelog-window');

class PortalWindow extends Window {
  open() {
    if (this.window !== null) {
      this.window.focus();
      return;
    }

    this.window = new BrowserWindow({
      width: 940,
      height: 600,
      useContentSize: true,
      icon: this.iconPath,
      resizable: false,
      show: false,
    });

    this.window.competitions = competitions;

    const packageData = require('../../package.json');
    this.window.version = packageData.version;

    const config = new Store();
    const lastVersion = config.get('lastVersion', '1.0.0');

    if (semver.gt(packageData.version, lastVersion)) {
      this.window.on('show', () => changelogWindow.open());
      config.set('lastVersion', packageData.version);
    }

    this.setMenu(null);
    this.window.loadURL('file:///' + path.resolve(__dirname, '../public/portal.html'));

    this.attachEvents();
  }
}

module.exports = new PortalWindow();
<commit_msg>Fix portal window size<commit_after>const { BrowserWindow } = require('electron');
const path = require('path');
const Store = require('electron-store');
const semver = require('semver');
const Window = require('./Window');
const competitions = require('../competitions/competitions');
const changelogWindow = require('./changelog-window');

class PortalWindow extends Window {
  open() {
    if (this.window !== null) {
      this.window.focus();
      return;
    }

    this.window = new BrowserWindow({
      width: 943,
      height: 600,
      useContentSize: true,
      icon: this.iconPath,
      resizable: false,
      show: false,
    });

    this.window.competitions = competitions;

    const packageData = require('../../package.json');
    this.window.version = packageData.version;

    const config = new Store();
    const lastVersion = config.get('lastVersion', '1.0.0');

    if (semver.gt(packageData.version, lastVersion)) {
      this.window.on('show', () => changelogWindow.open());
      config.set('lastVersion', packageData.version);
    }

    this.setMenu(null);
    this.window.loadURL('file:///' + path.resolve(__dirname, '../public/portal.html'));

    this.attachEvents();
  }
}

module.exports = new PortalWindow();
<|endoftext|>


<commit_before>'use strict';

function rijksdriehoek(λ, φ) {
  // Coordinates of origin (Amersfoort)
  var x0 = 155000.0;
  var y0 = 463000.0;
  var φ0 = 52.15517440;
  var λ0 =  5.38720621;
  var R = [
    {"p":0, "q":1, "R": 190094.945},
    {"p":1, "q":1, "R": -11832.228},
    {"p":2, "q":1, "R": -114.221},
    {"p":0, "q":3, "R": -32.391},
    {"p":1, "q":0, "R": -0.705},
    {"p":3, "q":1, "R": -2.340},
    {"p":1, "q":3, "R": -0.608},
    {"p":0, "q":2, "R": -0.008},
    {"p":2, "q":3, "R": 0.148}]
  var S = [
    {"p":1, "q":0, "S": 309056.544},
    {"p":0, "q":2, "S": 3638.893},
    {"p":2, "q":0, "S": 73.077},
    {"p":1, "q":2, "S": -157.984},
    {"p":3, "q":0, "S": 59.788},
    {"p":0, "q":1, "S": 0.433},
    {"p":2, "q":2, "S": -6.439},
    {"p":1, "q":1, "S": -0.032},
    {"p":0, "q":4, "S": 0.092},
    {"p":1, "q":4, "S": -0.054}]
  var dφ = 0.36*(180*φ/Math.PI - φ0);
  var dλ = 0.36*(180*λ/Math.PI - λ0);
  var x = x0;
  for (var i = 0; i < R.length; ++i) {
    var p = R[i].p;
    var q = R[i].q;
    var r = R[i].R;
    x += r*Math.pow(dφ, p)*Math.pow(dλ, q);
  }
  var y = y0;
  for (var i = 0; i < S.length; ++i) {
    var p = S[i].p;
    var q = S[i].q;
    var s = S[i].S;
    y += s*Math.pow(dφ, p)*Math.pow(dλ, q);
  }
  return [x, y];
}

rijksdriehoek.invert = function(x, y) {
  // Coordinates of origin (Amersfoort)
  var x0 = 155000.0;
  var y0 = 463000.0;
  var φ0 = 52.15517440;
  var λ0 =  5.38720621;
  var K = [
    {"p":0, "q":1, "K":3235.65389},
    {"p":2, "q":0, "K": -32.58297},
    {"p":0, "q":2, "K":  -0.24750},
    {"p":2, "q":1, "K":  -0.84978},
    {"p":0, "q":3, "K":  -0.06550},
    {"p":2, "q":2, "K":  -0.01709},
    {"p":1, "q":0, "K":  -0.00738},
    {"p":4, "q":0, "K":   0.00530},
    {"p":2, "q":3, "K":  -0.00039},
    {"p":4, "q":1, "K":   0.00033},
    {"p":1, "q":1, "K":  -0.00012}];
  var L = [
    {"p":1, "q":0, "L":5260.52916},
    {"p":1, "q":1, "L": 105.94684},
    {"p":1, "q":2, "L":   2.45656},
    {"p":3, "q":0, "L":  -0.81885},
    {"p":1, "q":3, "L":   0.05594},
    {"p":3, "q":1, "L":  -0.05607},
    {"p":0, "q":1, "L":   0.01199},
    {"p":3, "q":2, "L":  -0.00256},
    {"p":1, "q":4, "L":   0.00128}];
  var dx = (x - x0)/1E5;
  var dy = (y - y0)/1E5;
  var φ = φ0;
  for (var i = 0; i < K.length; ++i) {
    var p = K[i].p;
    var q = K[i].q;
    var k = K[i].K;
    φ += k*Math.pow(dx, p)*Math.pow(dy, q)/3600;
  }
  var λ = λ0;
  for (var i = 0; i < L.length; ++i) {
    var p = L[i].p;
    var q = L[i].q;
    var l = L[i].L;
    λ += l*Math.pow(dx, p)*Math.pow(dy, q)/3600;
  }
  return [180*λ/Math.PI, 180*φ/Math.PI];
};

d3.geo.rijksdriehoek = function() {
  return d3.geo.projection(rijksdriehoek);
}

<commit_msg>Removed use strict<commit_after>
function rijksdriehoek(λ, φ) {
  // Coordinates of origin (Amersfoort)
  var x0 = 155000.0;
  var y0 = 463000.0;
  var φ0 = 52.15517440;
  var λ0 =  5.38720621;
  var R = [
    {"p":0, "q":1, "R": 190094.945},
    {"p":1, "q":1, "R": -11832.228},
    {"p":2, "q":1, "R": -114.221},
    {"p":0, "q":3, "R": -32.391},
    {"p":1, "q":0, "R": -0.705},
    {"p":3, "q":1, "R": -2.340},
    {"p":1, "q":3, "R": -0.608},
    {"p":0, "q":2, "R": -0.008},
    {"p":2, "q":3, "R": 0.148}]
  var S = [
    {"p":1, "q":0, "S": 309056.544},
    {"p":0, "q":2, "S": 3638.893},
    {"p":2, "q":0, "S": 73.077},
    {"p":1, "q":2, "S": -157.984},
    {"p":3, "q":0, "S": 59.788},
    {"p":0, "q":1, "S": 0.433},
    {"p":2, "q":2, "S": -6.439},
    {"p":1, "q":1, "S": -0.032},
    {"p":0, "q":4, "S": 0.092},
    {"p":1, "q":4, "S": -0.054}]
  var dφ = 0.36*(180*φ/Math.PI - φ0);
  var dλ = 0.36*(180*λ/Math.PI - λ0);
  var x = x0;
  for (var i = 0; i < R.length; ++i) {
    var p = R[i].p;
    var q = R[i].q;
    var r = R[i].R;
    x += r*Math.pow(dφ, p)*Math.pow(dλ, q);
  }
  var y = y0;
  for (var i = 0; i < S.length; ++i) {
    var p = S[i].p;
    var q = S[i].q;
    var s = S[i].S;
    y += s*Math.pow(dφ, p)*Math.pow(dλ, q);
  }
  return [x, y];
}

rijksdriehoek.invert = function(x, y) {
  // Coordinates of origin (Amersfoort)
  var x0 = 155000.0;
  var y0 = 463000.0;
  var φ0 = 52.15517440;
  var λ0 =  5.38720621;
  var K = [
    {"p":0, "q":1, "K":3235.65389},
    {"p":2, "q":0, "K": -32.58297},
    {"p":0, "q":2, "K":  -0.24750},
    {"p":2, "q":1, "K":  -0.84978},
    {"p":0, "q":3, "K":  -0.06550},
    {"p":2, "q":2, "K":  -0.01709},
    {"p":1, "q":0, "K":  -0.00738},
    {"p":4, "q":0, "K":   0.00530},
    {"p":2, "q":3, "K":  -0.00039},
    {"p":4, "q":1, "K":   0.00033},
    {"p":1, "q":1, "K":  -0.00012}];
  var L = [
    {"p":1, "q":0, "L":5260.52916},
    {"p":1, "q":1, "L": 105.94684},
    {"p":1, "q":2, "L":   2.45656},
    {"p":3, "q":0, "L":  -0.81885},
    {"p":1, "q":3, "L":   0.05594},
    {"p":3, "q":1, "L":  -0.05607},
    {"p":0, "q":1, "L":   0.01199},
    {"p":3, "q":2, "L":  -0.00256},
    {"p":1, "q":4, "L":   0.00128}];
  var dx = (x - x0)/1E5;
  var dy = (y - y0)/1E5;
  var φ = φ0;
  for (var i = 0; i < K.length; ++i) {
    var p = K[i].p;
    var q = K[i].q;
    var k = K[i].K;
    φ += k*Math.pow(dx, p)*Math.pow(dy, q)/3600;
  }
  var λ = λ0;
  for (var i = 0; i < L.length; ++i) {
    var p = L[i].p;
    var q = L[i].q;
    var l = L[i].L;
    λ += l*Math.pow(dx, p)*Math.pow(dy, q)/3600;
  }
  return [180*λ/Math.PI, 180*φ/Math.PI];
};

d3.geo.rijksdriehoek = function() {
  return d3.geo.projection(rijksdriehoek);
}

<|endoftext|>


<commit_before>// Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';

var TypedError = require('error/typed');
var WrappedError = require('error/wrapped');

// All exported errors must be in sorted order

module.exports.Arg1OverLengthLimit = TypedError({
    type: 'tchannel.arg1-over-length-limit',
    message: 'arg 1 length {length} is larger than the limit {limit}',
    length: null,
    limit: null
});

module.exports.ArgChunkGapError = TypedError({
    type: 'tchannel.arg-chunk.gap',
    message: 'arg chunk gap, current: {current} got: {got}',
    current: null,
    got: null
});

module.exports.ArgChunkOutOfOrderError = TypedError({
    type: 'tchannel.arg-chunk.out-of-order',
    message: 'out of order arg chunk, current: {current} got: {got}',
    current: null,
    got: null
});

module.exports.ChecksumError = TypedError({
    type: 'tchannel.checksum',
    message: 'invalid checksum (type {checksumType}) expected: {expectedValue} actual: {actualValue}',
    checksumType: null,
    expectedValue: null,
    actualValue: null
});

module.exports.DuplicateHeaderKeyError = TypedError({
    type: 'tchannel.duplicate-header-key',
    message: 'duplicate header key {key}',
    offset: null,
    endOffset: null,
    key: null,
    value: null,
    priorValue: null
});

module.exports.InvalidArgumentError = TypedError({
    type: 'tchannel.invalid-argument',
    message: 'invalid argument, expected array or null',
    argType: null,
    argConstructor: null
});

module.exports.InvalidErrorCodeError = TypedError({
    type: 'tchannel.invalid-error-code',
    message: 'invalid tchannel error code {errorCode}',
    errorCode: null,
    originalId: null
});

module.exports.InvalidFrameTypeError = TypedError({
    type: 'tchannel.invalid-frame-type',
    message: 'invalid frame type {typeNumber}',
    typeNumber: null
});

module.exports.InvalidHandlerError = TypedError({
    type: 'tchannel.invalid-handler',
    message: 'invalid handler function'
});

module.exports.InvalidHandlerForRegister = TypedError({
    type: 'tchannel.invalid-handler.for-registration',
    message: 'Found unexpected handler when calling `.register()`.\n' +
        'You cannot set a custom handler when using `.register()`.\n' +
        '`.register()` is deprecated; use a proper handler.',
    handlerType: null,
    handler: null
});

module.exports.InvalidJSONBody = TypedError({
    type: 'tchannel-handler.json.invalid-body',
    message: 'Invalid error body, expected a typed-error',
    isSerializationError: true,
    head: null,
    body: null
});

module.exports.JSONBodyParserError = WrappedError({
    type: 'tchannel-json-handler.parse-error.body-failed',
    message: 'Could not parse body (arg3) argument.\n' +
        'Expected JSON encoded arg3 for endpoint {endpoint}.\n' +
        'Got {bodyStr} instead of JSON.',
    isSerializationError: true,
    endpoint: null,
    direction: null,
    bodyStr: null
});

module.exports.JSONBodyStringifyError = WrappedError({
    type: 'tchannel-json-handler.stringify-error.body-failed',
    message: 'Could not stringify body (res2) argument.\n' +
        'Expected JSON serializable res2 for endpoint {endpoint}.',
    isSerializationError: true,
    endpoint: null,
    body: null,
    direction: null
});

module.exports.JSONHeadParserError = WrappedError({
    type: 'tchannel-json-handler.parse-error.head-failed',
    message: 'Could not parse head (arg2) argument.\n' +
        'Expected JSON encoded arg2 for endpoint {endpoint}.\n' +
        'Got {headStr} instead of JSON.',
    isSerializationError: true,
    endpoint: null,
    direction: null,
    headStr: null
});

module.exports.JSONHeadStringifyError = WrappedError({
    type: 'tchannel-json-handler.stringify-error.head-failed',
    message: 'Could not stringify head (res1) argument.\n' +
        'Expected JSON serializable res1 for endpoint {endpoint}.',
    isSerializationError: true,
    endpoint: null,
    head: null,
    direction: null
});

module.exports.MaxPendingError = TypedError({
    type: 'tchannel.max-pending',
    message: 'maximum pending requests exceeded (limit was {pending})',
    pending: null
});

module.exports.MaxPendingForServiceError = TypedError({
    type: 'tchannel.max-pending-for-service',
    message: 'maximum pending requests exceeded for service (limit was {pending} for service {serviceName})',
    pending: null,
    serviceName: null
});

module.exports.MissingInitHeaderError = TypedError({
    type: 'tchannel.missing-init-header',
    message: 'missing init frame header {field}',
    field: null
});

module.exports.NoPeerAvailable = TypedError({
    type: 'tchannel.no-peer-available',
    message: 'no peer available for request'
});

module.exports.NoServiceHandlerError = TypedError({
    type: 'tchannel.no-service-handler',
    message: 'unknown service {serviceName}',
    serviceName: null
});

module.exports.NullKeyError = TypedError({
    type: 'tchannel.null-key',
    message: 'null key',
    offset: null,
    endOffset: null
});

module.exports.ReconstructedError = TypedError({
    type: 'tchannel.hydrated-error.default-type',
    message: 'TChannel json hydrated error;' +
        ' this message should be replaced with an upstream error message'
});

module.exports.RequestAlreadyDone = TypedError({
    type: 'tchannel.request-already-done',
    message: 'cannot {attempted}, request already done',
    attempted: null
});

module.exports.RequestFrameState = TypedError({
    type: 'tchannel.request-frame-state',
    message: 'cannot send {attempted} in {state} request state',
    attempted: null,
    state: null
});

module.exports.ResponseAlreadyDone = TypedError({
    type: 'tchannel.response-already-done',
    message: 'cannot send {attempted}, response already done ' +
        'in state: {currentState}',
    attempted: null,
    currentState: null
});

module.exports.ResponseAlreadyStarted = TypedError({
    type: 'tchannel.response-already-started',
    message: 'response already started (state {state})',
    state: null
});

module.exports.ResponseFrameState = TypedError({
    type: 'tchannel.response-frame-state',
    message: 'cannot send {attempted} in {state} response state',
    attempted: null,
    state: null
});

module.exports.SocketClosedError = TypedError({
    type: 'tchannel.socket-closed',
    message: 'socket closed, {reason}',
    reason: null
});

module.exports.SocketError = WrappedError({
    type: 'tchannel.socket',
    message: 'tchannel socket error ({code} from {syscall}): {origMessage}',
    hostPort: null,
    direction: null,
    remoteAddr: null
});

module.exports.TChannelCallReqBeforeInitReqError = TypedError({
    type: 'tchannel.init.call-request-before-init-request',
    message: 'call request before init request'
});

module.exports.TChannelCallReqContBeforeInitReqError = TypedError({
    type: 'tchannel.init.call-request-cont-before-init-request',
    message: 'call request cont before init request'
});

module.exports.TChannelCallResBeforeInitResError = TypedError({
    type: 'tchannel.init.call-response-before-init-response',
    message: 'call response before init response'
});

module.exports.TChannelCallResContBeforeInitResError = TypedError({
    type: 'tchannel.init.call-response-cont-before-init-response',
    message: 'call response cont before init response'
});

module.exports.TChannelConnectionResetError = WrappedError({
    type: 'tchannel.connection.reset',
    message: 'tchannel: {origMessage}'
});

module.exports.TChannelDuplicateInitRequestError = TypedError({
    type: 'tchannel.init.duplicate-init-request',
    message: 'tchannel: duplicate init request'
});

module.exports.TChannelDuplicateInitResponseError = TypedError({
    type: 'tchannel.init.duplicate-init-response',
    message: 'tchannel: duplicate init response'
});

module.exports.TChannelListenError = WrappedError({
    type: 'tchannel.server.listen-failed',
    message: 'tchannel: {origMessage}',
    requestedPort: null,
    host: null
});

module.exports.TChannelReadProtocolError = WrappedError({
    type: 'tchannel.protocol.read-failed',
    message: 'tchannel read failure: {origMessage}',
    remoteName: null,
    localName: null
});

module.exports.TChannelUnhandledFrameTypeError = TypedError({
    type: 'tchannel.unhandled-frame-type',
    message: 'unhandled frame type {typeCode}',
    typeCode: null
});

module.exports.TChannelWriteProtocolError = WrappedError({
    type: 'tchannel.protocol.write-failed',
    message: 'tchannel write failure: {origMessage}',
    remoteName: null,
    localName: null
});

module.exports.ThriftBodyParserError = WrappedError({
    type: 'tchannel-thrift-handler.parse-error.body-failed',
    message: 'Could not parse body (arg3) argument.\n' +
        'Expected Thrift encoded arg3 for endpoint {endpoint}.\n' +
        'Got {bodyBuf} instead of Thrift.\n' +
        'Parsing error was: {causeMessage}.\n',
    isSerializationError: true,
    endpoint: null,
    direction: null,
    ok: null,
    bodyBuf: null
});

module.exports.ThriftBodyStringifyError = WrappedError({
    type: 'tchannel-thrift-handler.stringify-error.body-failed',
    message: 'Could not stringify body (res2) argument.\n' +
        'Expected Thrift serializable res2 for endpoint {endpoint}.',
    isSerializationError: true,
    endpoint: null,
    ok: null,
    body: null,
    direction: null
});

module.exports.ThriftHeadParserError = WrappedError({
    type: 'tchannel-thrift-handler.parse-error.head-failed',
    message: 'Could not parse head (arg2) argument.\n' +
        'Expected Thrift encoded arg2 for endpoint {endpoint}.\n' +
        'Got {headBuf} instead of Thrift.\n' +
        'Parsing error was: {causeMessage}.\n',
    isSerializationError: true,
    endpoint: null,
    ok: null,
    direction: null,
    headBuf: null
});

module.exports.ThriftHeadStringifyError = WrappedError({
    type: 'tchannel-thrift-handler.stringify-error.head-failed',
    message: 'Could not stringify head (res1) argument.\n' +
        'Expected Thrift serializable res1 for endpoint {endpoint}.',
    isSerializationError: true,
    endpoint: null,
    ok: null,
    head: null,
    direction: null
});

module.exports.TimeoutError = TypedError({
    type: 'tchannel.timeout',
    message: 'timed out after {elapsed}ms (limit was {timeout}ms)',
    id: null,
    start: null,
    elapsed: null,
    timeout: null
});

module.exports.TopLevelRegisterError = TypedError({
    type: 'tchannel.top-level-register',
    message: 'Cannot register endpoints points on top-level channel.\n' +
        'Provide serviceName to constructor, or create a sub-channel.'
});

module.exports.TopLevelRequestError = TypedError({
    type: 'tchannel.top-level-request',
    message: 'Cannot make request() on top level tchannel without service or host.\n' +
        'Must provide either a known service, a direct host, or use a sub channel directly.'
});

module.exports.UnimplementedMethod = TypedError({
    message: 'Unimplemented {className}#{methodName}',
    type: 'tchannel.unimplemented-method',
    className: null,
    methodName: null
});

// utilities

module.exports.classify = function classify(err) {
    if (err.isErrorFrame) {
        return err.codeName;
    }

    switch (err.type) {
        case 'tchannel.no-peer-available':
        case 'tchannel.no-service-handler':
        case 'tchannel.max-pending':
        case 'tchannel.max-pending-for-service':
            return 'Declined';

        case 'tchannel.timeout':
            return 'Timeout';

        case 'tchannel-handler.parse-error.body-failed':
        case 'tchannel-handler.parse-error.head-failed':
        case 'tchannel.checksum':
        case 'tchannel.duplicate-header-key':
            return 'BadRequest';

        case 'tchannel.arg-chunk.gap':
        case 'tchannel.arg-chunk.out-of-order':
        case 'tchannel.invalid-code-string':
        case 'tchannel.invalid-error-code':
        case 'tchannel.invalid-frame-type':
        case 'tchannel.missing-init-header':
        case 'tchannel.null-key':
        case 'tchannel.protocol.read-failed':
        case 'tchannel.protocol.write-failed':
        case 'tchannel.unhandled-frame-type':
            return 'ProtocolError';

        case 'tchannel.socket':
        case 'tchannel.socket-closed':
            return 'NetworkError';

        default:
            return null;
    }
};
<commit_msg>s/origMessage/causeMessage/<commit_after>// Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';

var TypedError = require('error/typed');
var WrappedError = require('error/wrapped');

// All exported errors must be in sorted order

module.exports.Arg1OverLengthLimit = TypedError({
    type: 'tchannel.arg1-over-length-limit',
    message: 'arg 1 length {length} is larger than the limit {limit}',
    length: null,
    limit: null
});

module.exports.ArgChunkGapError = TypedError({
    type: 'tchannel.arg-chunk.gap',
    message: 'arg chunk gap, current: {current} got: {got}',
    current: null,
    got: null
});

module.exports.ArgChunkOutOfOrderError = TypedError({
    type: 'tchannel.arg-chunk.out-of-order',
    message: 'out of order arg chunk, current: {current} got: {got}',
    current: null,
    got: null
});

module.exports.ChecksumError = TypedError({
    type: 'tchannel.checksum',
    message: 'invalid checksum (type {checksumType}) expected: {expectedValue} actual: {actualValue}',
    checksumType: null,
    expectedValue: null,
    actualValue: null
});

module.exports.DuplicateHeaderKeyError = TypedError({
    type: 'tchannel.duplicate-header-key',
    message: 'duplicate header key {key}',
    offset: null,
    endOffset: null,
    key: null,
    value: null,
    priorValue: null
});

module.exports.InvalidArgumentError = TypedError({
    type: 'tchannel.invalid-argument',
    message: 'invalid argument, expected array or null',
    argType: null,
    argConstructor: null
});

module.exports.InvalidErrorCodeError = TypedError({
    type: 'tchannel.invalid-error-code',
    message: 'invalid tchannel error code {errorCode}',
    errorCode: null,
    originalId: null
});

module.exports.InvalidFrameTypeError = TypedError({
    type: 'tchannel.invalid-frame-type',
    message: 'invalid frame type {typeNumber}',
    typeNumber: null
});

module.exports.InvalidHandlerError = TypedError({
    type: 'tchannel.invalid-handler',
    message: 'invalid handler function'
});

module.exports.InvalidHandlerForRegister = TypedError({
    type: 'tchannel.invalid-handler.for-registration',
    message: 'Found unexpected handler when calling `.register()`.\n' +
        'You cannot set a custom handler when using `.register()`.\n' +
        '`.register()` is deprecated; use a proper handler.',
    handlerType: null,
    handler: null
});

module.exports.InvalidJSONBody = TypedError({
    type: 'tchannel-handler.json.invalid-body',
    message: 'Invalid error body, expected a typed-error',
    isSerializationError: true,
    head: null,
    body: null
});

module.exports.JSONBodyParserError = WrappedError({
    type: 'tchannel-json-handler.parse-error.body-failed',
    message: 'Could not parse body (arg3) argument.\n' +
        'Expected JSON encoded arg3 for endpoint {endpoint}.\n' +
        'Got {bodyStr} instead of JSON.',
    isSerializationError: true,
    endpoint: null,
    direction: null,
    bodyStr: null
});

module.exports.JSONBodyStringifyError = WrappedError({
    type: 'tchannel-json-handler.stringify-error.body-failed',
    message: 'Could not stringify body (res2) argument.\n' +
        'Expected JSON serializable res2 for endpoint {endpoint}.',
    isSerializationError: true,
    endpoint: null,
    body: null,
    direction: null
});

module.exports.JSONHeadParserError = WrappedError({
    type: 'tchannel-json-handler.parse-error.head-failed',
    message: 'Could not parse head (arg2) argument.\n' +
        'Expected JSON encoded arg2 for endpoint {endpoint}.\n' +
        'Got {headStr} instead of JSON.',
    isSerializationError: true,
    endpoint: null,
    direction: null,
    headStr: null
});

module.exports.JSONHeadStringifyError = WrappedError({
    type: 'tchannel-json-handler.stringify-error.head-failed',
    message: 'Could not stringify head (res1) argument.\n' +
        'Expected JSON serializable res1 for endpoint {endpoint}.',
    isSerializationError: true,
    endpoint: null,
    head: null,
    direction: null
});

module.exports.MaxPendingError = TypedError({
    type: 'tchannel.max-pending',
    message: 'maximum pending requests exceeded (limit was {pending})',
    pending: null
});

module.exports.MaxPendingForServiceError = TypedError({
    type: 'tchannel.max-pending-for-service',
    message: 'maximum pending requests exceeded for service (limit was {pending} for service {serviceName})',
    pending: null,
    serviceName: null
});

module.exports.MissingInitHeaderError = TypedError({
    type: 'tchannel.missing-init-header',
    message: 'missing init frame header {field}',
    field: null
});

module.exports.NoPeerAvailable = TypedError({
    type: 'tchannel.no-peer-available',
    message: 'no peer available for request'
});

module.exports.NoServiceHandlerError = TypedError({
    type: 'tchannel.no-service-handler',
    message: 'unknown service {serviceName}',
    serviceName: null
});

module.exports.NullKeyError = TypedError({
    type: 'tchannel.null-key',
    message: 'null key',
    offset: null,
    endOffset: null
});

module.exports.ReconstructedError = TypedError({
    type: 'tchannel.hydrated-error.default-type',
    message: 'TChannel json hydrated error;' +
        ' this message should be replaced with an upstream error message'
});

module.exports.RequestAlreadyDone = TypedError({
    type: 'tchannel.request-already-done',
    message: 'cannot {attempted}, request already done',
    attempted: null
});

module.exports.RequestFrameState = TypedError({
    type: 'tchannel.request-frame-state',
    message: 'cannot send {attempted} in {state} request state',
    attempted: null,
    state: null
});

module.exports.ResponseAlreadyDone = TypedError({
    type: 'tchannel.response-already-done',
    message: 'cannot send {attempted}, response already done ' +
        'in state: {currentState}',
    attempted: null,
    currentState: null
});

module.exports.ResponseAlreadyStarted = TypedError({
    type: 'tchannel.response-already-started',
    message: 'response already started (state {state})',
    state: null
});

module.exports.ResponseFrameState = TypedError({
    type: 'tchannel.response-frame-state',
    message: 'cannot send {attempted} in {state} response state',
    attempted: null,
    state: null
});

module.exports.SocketClosedError = TypedError({
    type: 'tchannel.socket-closed',
    message: 'socket closed, {reason}',
    reason: null
});

module.exports.SocketError = WrappedError({
    type: 'tchannel.socket',
    message: 'tchannel socket error ({code} from {syscall}): {origMessage}',
    hostPort: null,
    direction: null,
    remoteAddr: null
});

module.exports.TChannelCallReqBeforeInitReqError = TypedError({
    type: 'tchannel.init.call-request-before-init-request',
    message: 'call request before init request'
});

module.exports.TChannelCallReqContBeforeInitReqError = TypedError({
    type: 'tchannel.init.call-request-cont-before-init-request',
    message: 'call request cont before init request'
});

module.exports.TChannelCallResBeforeInitResError = TypedError({
    type: 'tchannel.init.call-response-before-init-response',
    message: 'call response before init response'
});

module.exports.TChannelCallResContBeforeInitResError = TypedError({
    type: 'tchannel.init.call-response-cont-before-init-response',
    message: 'call response cont before init response'
});

module.exports.TChannelConnectionResetError = WrappedError({
    type: 'tchannel.connection.reset',
    message: 'tchannel: {causeMessage}'
});

module.exports.TChannelDuplicateInitRequestError = TypedError({
    type: 'tchannel.init.duplicate-init-request',
    message: 'tchannel: duplicate init request'
});

module.exports.TChannelDuplicateInitResponseError = TypedError({
    type: 'tchannel.init.duplicate-init-response',
    message: 'tchannel: duplicate init response'
});

module.exports.TChannelListenError = WrappedError({
    type: 'tchannel.server.listen-failed',
    message: 'tchannel: {origMessage}',
    requestedPort: null,
    host: null
});

module.exports.TChannelReadProtocolError = WrappedError({
    type: 'tchannel.protocol.read-failed',
    message: 'tchannel read failure: {origMessage}',
    remoteName: null,
    localName: null
});

module.exports.TChannelUnhandledFrameTypeError = TypedError({
    type: 'tchannel.unhandled-frame-type',
    message: 'unhandled frame type {typeCode}',
    typeCode: null
});

module.exports.TChannelWriteProtocolError = WrappedError({
    type: 'tchannel.protocol.write-failed',
    message: 'tchannel write failure: {origMessage}',
    remoteName: null,
    localName: null
});

module.exports.ThriftBodyParserError = WrappedError({
    type: 'tchannel-thrift-handler.parse-error.body-failed',
    message: 'Could not parse body (arg3) argument.\n' +
        'Expected Thrift encoded arg3 for endpoint {endpoint}.\n' +
        'Got {bodyBuf} instead of Thrift.\n' +
        'Parsing error was: {causeMessage}.\n',
    isSerializationError: true,
    endpoint: null,
    direction: null,
    ok: null,
    bodyBuf: null
});

module.exports.ThriftBodyStringifyError = WrappedError({
    type: 'tchannel-thrift-handler.stringify-error.body-failed',
    message: 'Could not stringify body (res2) argument.\n' +
        'Expected Thrift serializable res2 for endpoint {endpoint}.',
    isSerializationError: true,
    endpoint: null,
    ok: null,
    body: null,
    direction: null
});

module.exports.ThriftHeadParserError = WrappedError({
    type: 'tchannel-thrift-handler.parse-error.head-failed',
    message: 'Could not parse head (arg2) argument.\n' +
        'Expected Thrift encoded arg2 for endpoint {endpoint}.\n' +
        'Got {headBuf} instead of Thrift.\n' +
        'Parsing error was: {causeMessage}.\n',
    isSerializationError: true,
    endpoint: null,
    ok: null,
    direction: null,
    headBuf: null
});

module.exports.ThriftHeadStringifyError = WrappedError({
    type: 'tchannel-thrift-handler.stringify-error.head-failed',
    message: 'Could not stringify head (res1) argument.\n' +
        'Expected Thrift serializable res1 for endpoint {endpoint}.',
    isSerializationError: true,
    endpoint: null,
    ok: null,
    head: null,
    direction: null
});

module.exports.TimeoutError = TypedError({
    type: 'tchannel.timeout',
    message: 'timed out after {elapsed}ms (limit was {timeout}ms)',
    id: null,
    start: null,
    elapsed: null,
    timeout: null
});

module.exports.TopLevelRegisterError = TypedError({
    type: 'tchannel.top-level-register',
    message: 'Cannot register endpoints points on top-level channel.\n' +
        'Provide serviceName to constructor, or create a sub-channel.'
});

module.exports.TopLevelRequestError = TypedError({
    type: 'tchannel.top-level-request',
    message: 'Cannot make request() on top level tchannel without service or host.\n' +
        'Must provide either a known service, a direct host, or use a sub channel directly.'
});

module.exports.UnimplementedMethod = TypedError({
    message: 'Unimplemented {className}#{methodName}',
    type: 'tchannel.unimplemented-method',
    className: null,
    methodName: null
});

// utilities

module.exports.classify = function classify(err) {
    if (err.isErrorFrame) {
        return err.codeName;
    }

    switch (err.type) {
        case 'tchannel.no-peer-available':
        case 'tchannel.no-service-handler':
        case 'tchannel.max-pending':
        case 'tchannel.max-pending-for-service':
            return 'Declined';

        case 'tchannel.timeout':
            return 'Timeout';

        case 'tchannel-handler.parse-error.body-failed':
        case 'tchannel-handler.parse-error.head-failed':
        case 'tchannel.checksum':
        case 'tchannel.duplicate-header-key':
            return 'BadRequest';

        case 'tchannel.arg-chunk.gap':
        case 'tchannel.arg-chunk.out-of-order':
        case 'tchannel.invalid-code-string':
        case 'tchannel.invalid-error-code':
        case 'tchannel.invalid-frame-type':
        case 'tchannel.missing-init-header':
        case 'tchannel.null-key':
        case 'tchannel.protocol.read-failed':
        case 'tchannel.protocol.write-failed':
        case 'tchannel.unhandled-frame-type':
            return 'ProtocolError';

        case 'tchannel.socket':
        case 'tchannel.socket-closed':
            return 'NetworkError';

        default:
            return null;
    }
};
<|endoftext|>


<commit_before>// Copyright 2020, University of Colorado Boulder

import joist from './joist.js';

/**
 * Given an array of all possible screens that a sim can have, select and order them according to the relevant query
 * parameters. This also will create a homeScreen if needed, and specify the initialScreen for startup.
 *
 * Parameters suffixed with "Provided" will be true if the that query parameter was actually in the URL, as opposed to
 * the value of the query parameter being the default.
 *
 * @author Chris Klusendorf (PhET Interactive Simulations)
 * @author Michael Kauzmann (PhET Interactive Simulations)
 * @author Sam Reid (PhET Interactive Simulations)
 *
 * @param {Object[]} allSimScreens - all of the screens declared by the sim
 * @param {boolean} homeScreenQueryParameter - from phet.chipper.queryParameters.homeScreen
 * @param {boolean} homeScreenQueryParameterProvided
 * @param {number} initialScreenIndex - from phet.chipper.queryParameters.initialScreen
 * @param {boolean} initialScreenQueryParameterProvided
 * @param {number[]} screensQueryParameter - from phet.chipper.queryParameters.screens
 * @param {boolean} screensQueryParameterProvided
 * @param {function( selectedSimScreens ):HomeScreen} createHomeScreen
 * @returns {{homeScreen:Object, initialScreen:Object, selectedSimScreens:Object[], screens:Object[]}}
 * @throws Error if incompatible data is provided
 */
const selectScreens = ( allSimScreens,
                        homeScreenQueryParameter,
                        homeScreenQueryParameterProvided,
                        initialScreenIndex,
                        initialScreenQueryParameterProvided,
                        screensQueryParameter,
                        screensQueryParameterProvided,
                        createHomeScreen ) => {

  if ( allSimScreens.length === 1 ) {

    // Problems related to query parameters throw errors instead of assertions (so they are not stripped out)
    if ( homeScreenQueryParameterProvided && homeScreenQueryParameter ) {
      throw new Error( 'cannot specify homeScreen=true for single-screen sims' );
    }
  }

  // the sim screens for this runtime, accounting for specifying a subset with `?screens`
  let selectedSimScreens;

  // The screens to be included, and their order, may be specified via a query parameter.
  // For documentation, see the schema for phet.chipper.queryParameters.screens in initialize-globals.js.
  // TODO: Use QueryStringMachine to validate instead, see https://github.com/phetsims/joist/issues/599
  if ( screensQueryParameterProvided ) {
    //REVIEW: Shouldn't we just see if the result is the default value of `null`, instead of checking if it was
    //REVIEW: provided? See https://github.com/phetsims/joist/issues/614
    selectedSimScreens = screensQueryParameter.map( userIndex => {
      const screenIndex = userIndex - 1; // screens query parameter is 1-based
      if ( screenIndex < 0 || screenIndex > allSimScreens.length - 1 ) {
        throw new Error( 'invalid screen index: ' + userIndex );
      }
      return allSimScreens[ screenIndex ];
    } );
  }
  else {
    selectedSimScreens = allSimScreens;
  }

  // Specifying ?homeScreen=false creates a simulation with no homescreen, and hence is incompatible with ?initialScreen=0,
  // which specifies to show the home screen. Note that the default value of initialScreen:0 is ignored when there is
  // no home screen.
  if ( initialScreenQueryParameterProvided && initialScreenIndex === 0 && homeScreenQueryParameter === false ) {
    // TODO: Use QueryStringMachine to validate instead, see https://github.com/phetsims/joist/issues/599
    throw new Error( 'cannot specify initialScreen=0 when home screen is disabled with homeScreen=false' );
  }

  // For a single screen simulation (whether the simulation only declares one screen, or whether the user has specified
  // a single screen via ?screens), there is no home screen, and hence ?initialScreen=0 which requests to show the homescreen
  // on startup should fail.
  if ( initialScreenQueryParameterProvided && initialScreenIndex === 0 && selectedSimScreens.length === 1 ) {
    throw new Error( 'cannot specify initialScreen=0 when one screen is specified with screens=n' );
  }

  const screens = selectedSimScreens.slice();

  let homeScreen = null;

  // If a sim has multiple screens and the query parameter homeScreen=false is not provided, add a HomeScreen
  if ( selectedSimScreens.length > 1 && homeScreenQueryParameter ) {
    homeScreen = createHomeScreen( selectedSimScreens );
    screens.unshift( homeScreen );
  }

  // The first screen for the sim, can be the HomeScreen if applicable
  let initialScreen;
  if ( homeScreen && initialScreenIndex === 0 ) {

    // If the home screen is supplied, then it is at index 0, so use the query parameter value directly (because the
    // query parameter is 1-based). If `?initialScreen` is 0 then there is no offset to apply.
    initialScreen = homeScreen;
  }
  else if ( initialScreenIndex === 0 ) {

    // There is no home screen and the initialScreen query parameter was not supplied, so we select the first sim screen.
    initialScreen = selectedSimScreens[ 0 ];
  }
  else {

    // If the home screen is not supplied, then the first sim screen is at index 0, so subtract 1 from the query parameter.
    initialScreen = allSimScreens[ initialScreenIndex - 1 ];
  }

  if ( screens.indexOf( initialScreen ) === -1 ) {
    throw new Error( 'screen not found: ' + initialScreenIndex );
  }

  return {
    homeScreen: homeScreen,
    initialScreen: initialScreen,
    selectedSimScreens: selectedSimScreens,
    screens: screens
  };
};

joist.register( 'selectScreens', selectScreens );
export default selectScreens;<commit_msg>Improve type docs, see https://github.com/phetsims/joist/issues/603<commit_after>// Copyright 2020, University of Colorado Boulder

import joist from './joist.js';

/**
 * Given an array of all possible screens that a sim can have, select and order them according to the relevant query
 * parameters. This also will create a homeScreen if needed, and specify the initialScreen for startup.
 *
 * Parameters suffixed with "Provided" will be true if the that query parameter was actually in the URL, as opposed to
 * the value of the query parameter being the default.
 *
 * @author Chris Klusendorf (PhET Interactive Simulations)
 * @author Michael Kauzmann (PhET Interactive Simulations)
 * @author Sam Reid (PhET Interactive Simulations)
 *
 * @param {Screen[]} allSimScreens - all of the screens declared by the sim, duck-typed for tests
 * @param {boolean} homeScreenQueryParameter - from phet.chipper.queryParameters.homeScreen
 * @param {boolean} homeScreenQueryParameterProvided
 * @param {number} initialScreenIndex - from phet.chipper.queryParameters.initialScreen
 * @param {boolean} initialScreenQueryParameterProvided
 * @param {number[]} screensQueryParameter - from phet.chipper.queryParameters.screens
 * @param {boolean} screensQueryParameterProvided
 * @param {function( selectedSimScreens ):HomeScreen} createHomeScreen
 * @returns {{homeScreen:HomeScreen|null, initialScreen:Screen, selectedSimScreens:Screen[], screens:Screen[]}} - duck-typed for tests
 * @throws Error if incompatible data is provided
 */
const selectScreens = ( allSimScreens,
                        homeScreenQueryParameter,
                        homeScreenQueryParameterProvided,
                        initialScreenIndex,
                        initialScreenQueryParameterProvided,
                        screensQueryParameter,
                        screensQueryParameterProvided,
                        createHomeScreen ) => {

  if ( allSimScreens.length === 1 ) {

    // Problems related to query parameters throw errors instead of assertions (so they are not stripped out)
    if ( homeScreenQueryParameterProvided && homeScreenQueryParameter ) {
      throw new Error( 'cannot specify homeScreen=true for single-screen sims' );
    }
  }

  // the sim screens for this runtime, accounting for specifying a subset with `?screens`
  let selectedSimScreens;

  // The screens to be included, and their order, may be specified via a query parameter.
  // For documentation, see the schema for phet.chipper.queryParameters.screens in initialize-globals.js.
  // TODO: Use QueryStringMachine to validate instead, see https://github.com/phetsims/joist/issues/599
  if ( screensQueryParameterProvided ) {
    //REVIEW: Shouldn't we just see if the result is the default value of `null`, instead of checking if it was
    //REVIEW: provided? See https://github.com/phetsims/joist/issues/614
    selectedSimScreens = screensQueryParameter.map( userIndex => {
      const screenIndex = userIndex - 1; // screens query parameter is 1-based
      if ( screenIndex < 0 || screenIndex > allSimScreens.length - 1 ) {
        throw new Error( 'invalid screen index: ' + userIndex );
      }
      return allSimScreens[ screenIndex ];
    } );
  }
  else {
    selectedSimScreens = allSimScreens;
  }

  // Specifying ?homeScreen=false creates a simulation with no homescreen, and hence is incompatible with ?initialScreen=0,
  // which specifies to show the home screen. Note that the default value of initialScreen:0 is ignored when there is
  // no home screen.
  if ( initialScreenQueryParameterProvided && initialScreenIndex === 0 && homeScreenQueryParameter === false ) {
    // TODO: Use QueryStringMachine to validate instead, see https://github.com/phetsims/joist/issues/599
    throw new Error( 'cannot specify initialScreen=0 when home screen is disabled with homeScreen=false' );
  }

  // For a single screen simulation (whether the simulation only declares one screen, or whether the user has specified
  // a single screen via ?screens), there is no home screen, and hence ?initialScreen=0 which requests to show the homescreen
  // on startup should fail.
  if ( initialScreenQueryParameterProvided && initialScreenIndex === 0 && selectedSimScreens.length === 1 ) {
    throw new Error( 'cannot specify initialScreen=0 when one screen is specified with screens=n' );
  }

  const screens = selectedSimScreens.slice();

  let homeScreen = null;

  // If a sim has multiple screens and the query parameter homeScreen=false is not provided, add a HomeScreen
  if ( selectedSimScreens.length > 1 && homeScreenQueryParameter ) {
    homeScreen = createHomeScreen( selectedSimScreens );
    screens.unshift( homeScreen );
  }

  // The first screen for the sim, can be the HomeScreen if applicable
  let initialScreen;
  if ( homeScreen && initialScreenIndex === 0 ) {

    // If the home screen is supplied, then it is at index 0, so use the query parameter value directly (because the
    // query parameter is 1-based). If `?initialScreen` is 0 then there is no offset to apply.
    initialScreen = homeScreen;
  }
  else if ( initialScreenIndex === 0 ) {

    // There is no home screen and the initialScreen query parameter was not supplied, so we select the first sim screen.
    initialScreen = selectedSimScreens[ 0 ];
  }
  else {

    // If the home screen is not supplied, then the first sim screen is at index 0, so subtract 1 from the query parameter.
    initialScreen = allSimScreens[ initialScreenIndex - 1 ];
  }

  if ( screens.indexOf( initialScreen ) === -1 ) {
    throw new Error( 'screen not found: ' + initialScreenIndex );
  }

  return {
    homeScreen: homeScreen,
    initialScreen: initialScreen,
    selectedSimScreens: selectedSimScreens,
    screens: screens
  };
};

joist.register( 'selectScreens', selectScreens );
export default selectScreens;<|endoftext|>


<commit_before>  var chartSize = Math.min(screen.width, screen.height)/1.5;

    var width = chartSize,
        height = chartSize;
    var radius = Math.min(width, height) / 2;

    // Breadcrumb dimensions: width, height, spacing, width of tip/tail.
    var b = {
      w: 75, h: 30, s: 3, t: 10
    };

    // Mapping of step names to colors.
    var colors = d3.scale.category20c();

    // Total size of all segments; we set this later, after loading the data.
    var totalSize = 0;

    var vis = d3.select("#chart").append("svg:svg")
        .attr("width", width)
        .attr("height", height)
        .append("svg:g")
        .attr("id", "container")
        .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");

    var partition = d3.layout.partition()
        .size([2 * Math.PI, radius * radius])
        .value(function(d) { return d.size; });

    var arc = d3.svg.arc()
        .startAngle(function(d) { return d.x; })
        .endAngle(function(d) { return d.x + d.dx; })
        .innerRadius(function(d) { return Math.sqrt(d.y); })
        .outerRadius(function(d) { return Math.sqrt(d.y + d.dy); });

    // Use d3.text and d3.csv.parseRows so that we do not need to have a header
    // row, and can receive the csv as an array of arrays.
    d3.text("account.csv", function(text) {
      var csv = d3.csv.parseRows(text);
      var json = buildHierarchy(csv);
      console.log(json);
      createVisualization(json);
    });

    // Main function to draw and set up the visualization, once we have the data.
    function createVisualization(json) {

      // Basic setup of page elements.
      initializeBreadcrumbTrail();
      drawLegend();
      d3.select("#togglelegend").on("click", toggleLegend);

      // Bounding circle underneath the sunburst, to make it easier to detect
      // when the mouse leaves the parent g.
      vis.append("svg:circle")
          .attr("r", radius)
          .style("opacity", 0);

      // For efficiency, filter nodes to keep only those large enough to see.
      var nodes = partition.nodes(json)
          .filter(function(d) {
          return (d.dx > 0.005); // 0.005 radians = 0.29 degrees
          });

      var path = vis.data([json]).selectAll("path")
          .data(nodes)
          .enter().append("svg:path")
          .attr("display", function(d) { return d.depth ? null : "none"; })
          .attr("d", arc)
          .attr("fill-rule", "evenodd")
          .style("fill", function(d) { return colors((d.children ? d : d.parent).name); })
          .style("opacity", 1)
          .on("mouseover", mouseover);

      // Add the mouseleave handler to the bounding circle.
      d3.select("#container").on("mouseleave", mouseleave);

      // Get total size of the tree = value of root node from partition.
      totalSize = path.node().__data__.value;
     };

    // Fade all but the current sequence, and show it in the breadcrumb trail.
    function mouseover(d) {

      var percentage = (100 * d.value / totalSize).toPrecision(3);
      var percentageString = percentage + "%";
      if (percentage < 0.1) {
        percentageString = "< 0.1%";
      }

      d3.select("#percentage")
          .text(percentageString);

      d3.select("#explanation")
          .style("visibility", "");

      var sequenceArray = getAncestors(d);
      updateBreadcrumbs(sequenceArray, percentageString);

      // Fade all the segments.
      d3.selectAll("path")
          .style("opacity", 0.3);

      // Then highlight only those that are an ancestor of the current segment.
      vis.selectAll("path")
          .filter(function(node) {
                    return (sequenceArray.indexOf(node) >= 0);
                  })
          .style("opacity", 1);
    }

    // Restore everything to full opacity when moving off the visualization.
    function mouseleave(d) {

      // Hide the breadcrumb trail
      d3.select("#trail")
          .style("visibility", "hidden");

      // Deactivate all segments during transition.
      d3.selectAll("path").on("mouseover", null);

      // Transition each segment to full opacity and then reactivate it.
      d3.selectAll("path")
          .transition()
          .duration(1000)
          .style("opacity", 1)
          .each("end", function() {
                  d3.select(this).on("mouseover", mouseover);
                });

      d3.select("#explanation")
          .style("visibility", "hidden");
    }

    // Given a node in a partition layout, return an array of all of its ancestor
    // nodes, highest first, but excluding the root.
    function getAncestors(node) {
      var path = [];
      var current = node;
      while (current.parent) {
        path.unshift(current);
        current = current.parent;
      }
      return path;
    }

    function initializeBreadcrumbTrail() {
      // Add the svg area.
      var trail = d3.select("#sequence").append("svg:svg")
          .attr("width", width)
          .attr("height", 50)
          .attr("id", "trail");
      // Add the label at the end, for the percentage.
      trail.append("svg:text")
        .attr("id", "endlabel")
        .style("fill", "#000");
    }

    // Generate a string that describes the points of a breadcrumb polygon.
    function breadcrumbPoints(d, i) {
      var points = [];
      points.push("0,0");
      points.push(b.w*2.6 + ",0");
      points.push(b.w*2.6 + b.t + "," + (b.h / 2));
      points.push(b.w*2.6 + "," + b.h);
      points.push("0," + b.h);
      if (i > 0) { // Leftmost breadcrumb; don't include 6th vertex.
        points.push(b.t + "," + (b.h / 2));
      }
      return points.join(" ");
    }

    // Update the breadcrumb trail to show the current sequence and percentage.
    function updateBreadcrumbs(nodeArray, percentageString) {

      // Data join; key function combines name and depth (= position in sequence).
      var g = d3.select("#trail")
          .selectAll("g")
          .data(nodeArray, function(d) { return d.name + d.depth; });

      // Add breadcrumb and label for entering nodes.
      var entering = g.enter().append("svg:g");

      entering.append("svg:polygon")
          .attr("points", breadcrumbPoints)
          .style("fill", function(d) { return colors((d.children ? d : d.parent).name); });

      entering.append("svg:text")
          .attr("x", (b.w*2.6 + b.t) / 2)
          .attr("y", b.h / 2)
          .attr("dy", "0.35em")
          .attr("text-anchor", "middle")
          .text(function(d) { return d.name; });

      // Set position for entering and updating nodes.
      g.attr("transform", function(d, i) {
        return "translate(" + i * (b.w*2.6 + b.s) + ", 0)";
      });

      // Remove exiting nodes.
      g.exit().remove();

      // Now move and update the percentage at the end.
      d3.select("#trail").select("#endlabel")
          .attr("x", (nodeArray.length + 0.5) * (b.w*2.6 + b.s))
          .attr("y", b.h / 2)
          .attr("dy", "0.35em")
          .attr("text-anchor", "middle")
          .text(percentageString);

      // Make the breadcrumb trail visible, if it's hidden.
      d3.select("#trail")
          .style("visibility", "");

    }

    function drawLegend() {

      // Dimensions of legend item: width, height, spacing, radius of rounded rect.
      var li = {
        w: 75, h: 30, s: 3, r: 3
      };

      var legend = d3.select("#legend").append("svg:svg")
          .attr("width", li.w)
          .attr("height", d3.keys(colors).length * (li.h + li.s));

      var g = legend.selectAll("g")
          .data(d3.entries(colors))
          .enter().append("svg:g")
          .attr("transform", function(d, i) {
                  return "translate(0," + i * (li.h + li.s) + ")";
               });

      g.append("svg:rect")
          .attr("rx", li.r)
          .attr("ry", li.r)
          .attr("width", li.w)
          .attr("height", li.h)
          .style("fill", function(d) { return d.value; });

      g.append("svg:text")
          .attr("x", li.w / 2)
          .attr("y", li.h / 2)
          .attr("dy", "0.35em")
          .attr("text-anchor", "middle")
          .text(function(d) { return d.key; });
    }

    function toggleLegend() {
      var legend = d3.select("#legend");
      if (legend.style("visibility") == "hidden") {
        legend.style("visibility", "");
      } else {
        legend.style("visibility", "hidden");
      }
    }

    // Take a 2-column CSV and transform it into a hierarchical structure suitable
    // for a partition layout. The first column is a sequence of step names, from
    // root to leaf, separated by hyphens. The second column is a count of how
    // often that sequence occurred.
    function buildHierarchy(csv) {
      var root = {"name": "root", "children": []};
      for (var i = 0; i < csv.length; i++) {
        var sequence = csv[i][0];
        var size = +csv[i][1];
        if (isNaN(size)) { // e.g. if this is a header row
          continue;
        }
        var parts = sequence.split(">");
        var currentNode = root;
        for (var j = 0; j < parts.length; j++) {
          var children = currentNode["children"];
          var nodeName = parts[j];
          var childNode;
          if (j + 1 < parts.length) {
       // Not yet at the end of the sequence; move down the tree.
     	var foundChild = false;
     	for (var k = 0; k < children.length; k++) {
     	  if (children[k]["name"] == nodeName) {
     	    childNode = children[k];
     	    foundChild = true;
     	    break;
     	  }
     	}
      // If we don't already have a child node for this branch, create it.
     	if (!foundChild) {
     	  childNode = {"name": nodeName, "children": []};
     	  children.push(childNode);
     	}
     	currentNode = childNode;
          } else {
     	// Reached the end of the sequence; create a leaf node.
     	childNode = {"name": nodeName, "size": size};
     	children.push(childNode);
          }
        }
      }
      return root;
    };
<commit_msg>minor updates<commit_after>  var chartSize = Math.min(screen.width, screen.height)/1.5;

    var width = chartSize,
        height = chartSize;
    var radius = Math.min(width, height) / 2;

    // Breadcrumb dimensions: width, height, spacing, width of tip/tail.
    var b = {
      w: 75, h: 30, s: 3, t: 10
    };

    // Mapping of step names to colors.
    var colors = d3.scale.category20c();

    // Total size of all segments; we set this later, after loading the data.
    var totalSize = 0;

    var vis = d3.select("#chart").append("svg:svg")
        .attr("width", width)
        .attr("height", height)
        .append("svg:g")
        .attr("id", "container")
        .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");

    var partition = d3.layout.partition()
        .size([2 * Math.PI, radius * radius])
        .value(function(d) { return d.size; });

    var arc = d3.svg.arc()
        .startAngle(function(d) { return d.x; })
        .endAngle(function(d) { return d.x + d.dx; })
        .innerRadius(function(d) { return Math.sqrt(d.y); })
        .outerRadius(function(d) { return Math.sqrt(d.y + d.dy); });

    // Use d3.text and d3.csv.parseRows so that we do not need to have a header
    // row, and can receive the csv as an array of arrays.
    d3.text("account.csv", function(text) {
      var csv = d3.csv.parseRows(text);
      var json = buildHierarchy(csv);
      console.log(json);
      createVisualization(json);
    });

    // Main function to draw and set up the visualization, once we have the data.
    function createVisualization(json) {

      // Basic setup of page elements.
      initializeBreadcrumbTrail();
      drawLegend();
      d3.select("#togglelegend").on("click", toggleLegend);

      // Bounding circle underneath the sunburst, to make it easier to detect
      // when the mouse leaves the parent g.
      vis.append("svg:circle")
          .attr("r", radius)
          .style("opacity", 0);

      // For efficiency, filter nodes to keep only those large enough to see.
      var nodes = partition.nodes(json)
          .filter(function(d) {
          return (d.dx > 0.005); // 0.005 radians = 0.29 degrees
          });

      var path = vis.data([json]).selectAll("path")
          .data(nodes)
          .enter().append("svg:path")
          .attr("display", function(d) { return d.depth ? null : "none"; })
          .attr("d", arc)
          .attr("fill-rule", "evenodd")
          .style("fill", function(d) { return colors((d.children ? d : d.parent).name); })
          .style("opacity", 1)
          .on("mouseover", mouseover);

      // Add the mouseleave handler to the bounding circle.
      d3.select("#container").on("mouseleave", mouseleave);

      // Get total size of the tree = value of root node from partition.
      totalSize = path.node().__data__.value;
     };

    // Fade all but the current sequence, and show it in the breadcrumb trail.
    function mouseover(d) {

      var percentage = (100 * d.value / totalSize).toPrecision(3);
      var percentageString = percentage + "%";
      if (percentage < 0.1) {
        percentageString = "< 0.1%";
      }

      d3.select("#percentage")
          .text(percentageString);

      d3.select("#explanation")
          .style("visibility", "");

      var sequenceArray = getAncestors(d);
      updateBreadcrumbs(sequenceArray, percentageString);

      // Fade all the segments.
      d3.selectAll("path")
          .style("opacity", 0.3);

      // Then highlight only those that are an ancestor of the current segment.
      vis.selectAll("path")
          .filter(function(node) {
                    return (sequenceArray.indexOf(node) >= 0);
                  })
          .style("opacity", 1);
    }

    // Restore everything to full opacity when moving off the visualization.
    function mouseleave(d) {

      // Hide the breadcrumb trail
      d3.select("#trail")
          .style("visibility", "hidden");

      // Deactivate all segments during transition.
      d3.selectAll("path").on("mouseover", null);

      // Transition each segment to full opacity and then reactivate it.
      d3.selectAll("path")
          .transition()
          .duration(1000)
          .style("opacity", 1)
          .each("end", function() {
                  d3.select(this).on("mouseover", mouseover);
                });

      d3.select("#explanation")
          .style("visibility", "hidden");
    }

    // Given a node in a partition layout, return an array of all of its ancestor
    // nodes, highest first, but excluding the root.
    function getAncestors(node) {
      var path = [];
      var current = node;
      while (current.parent) {
        path.unshift(current);
        current = current.parent;
      }
      return path;
    }

    function initializeBreadcrumbTrail() {
      // Add the svg area.
      var trail = d3.select("#sequence").append("svg:svg")
          .attr("width", width)
          .attr("height", 50)
          .attr("id", "trail");
      // Add the label at the end, for the percentage.
      trail.append("svg:text")
        .attr("id", "endlabel")
        .style("fill", "#000");
    }

    // Generate a string that describes the points of a breadcrumb polygon.
    function breadcrumbPoints(d, i) {
      var points = [];
      points.push("0,0");
      points.push(b.w*2.6 + ",0");
      points.push(b.w*2.6 + b.t + "," + (b.h / 2));
      points.push(b.w*2.6 + "," + b.h);
      points.push("0," + b.h);
      if (i > 0) { // Leftmost breadcrumb; don't include 6th vertex.
        points.push(b.t + "," + (b.h / 2));
      }
      return points.join(" ");
    }

    // Update the breadcrumb trail to show the current sequence and percentage.
    function updateBreadcrumbs(nodeArray, percentageString) {

      // Data join; key function combines name and depth (= position in sequence).
      var g = d3.select("#trail")
          .selectAll("g")
          .data(nodeArray, function(d) { return d.name + d.depth; });

      // Add breadcrumb and label for entering nodes.
      var entering = g.enter().append("svg:g");

      entering.append("svg:polygon")
          .attr("points", breadcrumbPoints)
          .style("fill", function(d) { return colors((d.children ? d : d.parent).name); });

      entering.append("svg:text")
          .attr("x", (b.w*2.6 + b.t) / 2)
          .attr("y", b.h / 2)
          .attr("dy", "0.35em")
          .attr("text-anchor", "middle")
          .text(function(d) { return d.name; });

      // Set position for entering and updating nodes.
      g.attr("transform", function(d, i) {
        return "translate(" + i * (b.w*2.6 + b.s) + ", 0)";
      });

      // Remove exiting nodes.
      g.exit().remove();

      // Now move and update the percentage at the end.
      d3.select("#trail").select("#endlabel")
          .attr("x", (nodeArray.length + 0.1) * (b.w*2.6 + b.s))
          .attr("y", b.h / 2)
          .attr("dy", "0.35em")
          .attr("text-anchor", "middle")
          .text(percentageString);

      // Make the breadcrumb trail visible, if it's hidden.
      d3.select("#trail")
          .style("visibility", "");

    }

    function drawLegend() {

      // Dimensions of legend item: width, height, spacing, radius of rounded rect.
      var li = {
        w: 75, h: 30, s: 3, r: 3
      };

      var legend = d3.select("#legend").append("svg:svg")
          .attr("width", li.w)
          .attr("height", d3.keys(colors).length * (li.h + li.s));

      var g = legend.selectAll("g")
          .data(d3.entries(colors))
          .enter().append("svg:g")
          .attr("transform", function(d, i) {
                  return "translate(0," + i * (li.h + li.s) + ")";
               });

      g.append("svg:rect")
          .attr("rx", li.r)
          .attr("ry", li.r)
          .attr("width", li.w)
          .attr("height", li.h)
          .style("fill", function(d) { return d.value; });

      g.append("svg:text")
          .attr("x", li.w / 2)
          .attr("y", li.h / 2)
          .attr("dy", "0.35em")
          .attr("text-anchor", "middle")
          .text(function(d) { return d.key; });
    }

    function toggleLegend() {
      var legend = d3.select("#legend");
      if (legend.style("visibility") == "hidden") {
        legend.style("visibility", "");
      } else {
        legend.style("visibility", "hidden");
      }
    }

    // Take a 2-column CSV and transform it into a hierarchical structure suitable
    // for a partition layout. The first column is a sequence of step names, from
    // root to leaf, separated by hyphens. The second column is a count of how
    // often that sequence occurred.
    function buildHierarchy(csv) {
      var root = {"name": "root", "children": []};
      for (var i = 0; i < csv.length; i++) {
        var sequence = csv[i][0];
        var size = +csv[i][1];
        if (isNaN(size)) { // e.g. if this is a header row
          continue;
        }
        var parts = sequence.split(">");
        var currentNode = root;
        for (var j = 0; j < parts.length; j++) {
          var children = currentNode["children"];
          var nodeName = parts[j];
          var childNode;
          if (j + 1 < parts.length) {
       // Not yet at the end of the sequence; move down the tree.
     	var foundChild = false;
     	for (var k = 0; k < children.length; k++) {
     	  if (children[k]["name"] == nodeName) {
     	    childNode = children[k];
     	    foundChild = true;
     	    break;
     	  }
     	}
      // If we don't already have a child node for this branch, create it.
     	if (!foundChild) {
     	  childNode = {"name": nodeName, "children": []};
     	  children.push(childNode);
     	}
     	currentNode = childNode;
          } else {
     	// Reached the end of the sequence; create a leaf node.
     	childNode = {"name": nodeName, "size": size};
     	children.push(childNode);
          }
        }
      }
      return root;
    };
<|endoftext|>


<commit_before>// Copyright 2016, University of Colorado Boulder

/**
 * PhET-iO wrapper type for JS's built-in number type.
 *
 * @author Sam Reid (PhET Interactive Simulations)
 * @author Andrew Adare (PhET Interactive Simulations)
 */
define( function( require ) {
  'use strict';

  // modules
  var assertTypeOf = require( 'PHET_IO/assertions/assertTypeOf' );
  var phetioNamespace = require( 'PHET_IO/phetioNamespace' );
  var phetioInherit = require( 'PHET_IO/phetioInherit' );
  var TObject = require( 'PHET_IO/types/TObject' );

  // valid values for options.units
  var VALID_UNITS = [
    'amperes',
    'becquerels',
    'centimeters',
    'coulombs',
    'degrees Celsius',
    'farads',
    'kilograms',
    'grams',
    'gray',
    'henrys',
    'henries',
    'hertz',
    'joules',
    'katals',
    'kelvins',
    'liters',
    'liters/second',
    'lumens',
    'lux',
    'meters',
    'meters/second',
    'meters/second/second',
    'moles',
    'moles/liter',
    'nanometers',
    'newtons',
    'ohms',
    'pascals',
    'percent',
    'radians',
    'radians/second',
    'seconds',
    'siemens',
    'sieverts',
    'steradians',
    'tesla',
    'unitless',
    'volts',
    'watts',
    'webers'
  ];

  var TNumber = function( units, options ) {
    assert && assert( units, 'All TNumbers should specify units' );
    assert && assert( validUnits.indexOf( units ) >= 0, units + ' is not recognized as a valid unit of measurement' );

    options = _.extend( {
        type: 'FloatingPoint', // either 'FloatingPoint' | 'Integer'
        range: new RangeWithValue( -Infinity, Infinity ),
        stepSize: null, // This will be used for slider increments

        // TODO: enforce that values is of Array type
        values: null // null | {Number[]} if it can only take certain possible values, specify them here, like [0,2,8]
      },
      options
    );
    return phetioInherit( TObject, 'TNumber(' + units + ')', function( instance, phetioID ) {
      TObject.call( this, instance, phetioID );
      assertTypeOf( instance, 'number' );
    }, {}, {
      apiElements: { // named differently than api while it means type composite, see phetioInherit.js
        units: units,
        type: options.type,
        range: options.range,
        values: options.values
      },
      documentation: 'Wrapper for the built-in JS number type (floating point, but also represents integers)',

      fromStateObject: function( stateObject ) {
        return stateObject;
      },

      toStateObject: function( value ) {
        return value;
      },

      getAPI: function() {
        return { // named differently than api while it means type composite, see phetioInherit.js
          units: options.units,
          type: options.type,
          range: options.range,
          values: options.values
        };
      }
    } );
  }

  phetioNamespace.register( 'TNumber', TNumber );

  return TNumber;
} );<commit_msg>Tandem IDs added to Spring.js (ref. #27). Also added 'newtons-second/meters' supported type to TNumber.units.<commit_after>// Copyright 2016, University of Colorado Boulder

/**
 * PhET-iO wrapper type for JS's built-in number type.
 *
 * @author Sam Reid (PhET Interactive Simulations)
 * @author Andrew Adare (PhET Interactive Simulations)
 */
define( function( require ) {
  'use strict';

  // modules
  var assertTypeOf = require( 'PHET_IO/assertions/assertTypeOf' );
  var phetioNamespace = require( 'PHET_IO/phetioNamespace' );
  var phetioInherit = require( 'PHET_IO/phetioInherit' );
  var TObject = require( 'PHET_IO/types/TObject' );

  // valid values for options.units
  var VALID_UNITS = [
    'amperes',
    'becquerels',
    'centimeters',
    'coulombs',
    'degrees Celsius',
    'farads',
    'kilograms',
    'grams',
    'gray',
    'henrys',
    'henries',
    'hertz',
    'joules',
    'katals',
    'kelvins',
    'liters',
    'liters/second',
    'lumens',
    'lux',
    'meters',
    'meters/second',
    'meters/second/second',
    'moles',
    'moles/liter',
    'nanometers',
    'newtons',
    'newtons/meters',
    'newtons-second/meters',
    'ohms',
    'pascals',
    'percent',
    'radians',
    'radians/second',
    'seconds',
    'siemens',
    'sieverts',
    'steradians',
    'tesla',
    'unitless',
    'volts',
    'watts',
    'webers'
  ];

  var TNumber = function( units, options ) {
    assert && assert( units, 'All TNumbers should specify units' );
    assert && assert( validUnits.indexOf( units ) >= 0, units + ' is not recognized as a valid unit of measurement' );

    options = _.extend( {
        type: 'FloatingPoint', // either 'FloatingPoint' | 'Integer'
        range: new RangeWithValue( -Infinity, Infinity ),
        stepSize: null, // This will be used for slider increments

        // TODO: enforce that values is of Array type
        values: null // null | {Number[]} if it can only take certain possible values, specify them here, like [0,2,8]
      },
      options
    );
    return phetioInherit( TObject, 'TNumber(' + units + ')', function( instance, phetioID ) {
      TObject.call( this, instance, phetioID );
      assertTypeOf( instance, 'number' );
    }, {}, {
      apiElements: { // named differently than api while it means type composite, see phetioInherit.js
        units: units,
        type: options.type,
        range: options.range,
        values: options.values
      },
      documentation: 'Wrapper for the built-in JS number type (floating point, but also represents integers)',

      fromStateObject: function( stateObject ) {
        return stateObject;
      },

      toStateObject: function( value ) {
        return value;
      },

      getAPI: function() {
        return { // named differently than api while it means type composite, see phetioInherit.js
          units: options.units,
          type: options.type,
          range: options.range,
          values: options.values
        };
      }
    } );
  }

  phetioNamespace.register( 'TNumber', TNumber );

  return TNumber;
} );<|endoftext|>


<commit_before>var _db = $$fObj$$;
var listeners = {};
_db.on = function (eventName, func, scope) {
	if(eventName.indexOf(' ')>0){
		return eventName.split(' ').map(function(v){
			return _db.on(v,func,scope);
		},_db);
	}
	scope = scope || _db;
	if (!(eventName in listeners)) {
		listeners[eventName] = [];
	}
	listeners[eventName].push(function (a) {
		func.call(scope, a);
	});
};
var _fire = function (eventName, data) {
	if (!(eventName in listeners)) {
		return;
	}
	listeners[eventName].forEach(function (v) {
		v(data);
	});
};
_db.fire = function (eventName, data, transfer) {
	!self._noTransferable ? self.postMessage([
		[eventName], data], transfer) : self.postMessage([
		[eventName], data]);
};
_db.off=function(eventName,func){
	if(eventName.indexOf(' ')>0){
		return eventName.split(' ').map(function(v){
			return _db.off(v,func);
		});
	}
	if(!(eventName in listeners)){
		return;
	}else if(!func){
		delete listeners[eventName];
	}else{
		if(listeners[eventName].indexOf(func)>-1){
			if(listeners[eventName].length>1){
				delete listeners[eventName];
			}else{
				listeners[eventName].splice(listeners[eventName].indexOf(func),1);
			}
		}
	}
};
self.onmessage=function(e){
	if(e.data[0][0]==="com.communistjs"){
		return regMsg(e);
	}else{
		_fire(e.data[0][0],e.data[1]);
	}
};
var regMsg = function(e){
	var cb=function(data,transfer){
		!self._noTransferable?self.postMessage([e.data[0],data],transfer):self.postMessage([e.data[0],data]);
	};
	var result = _db[e.data[1]](e.data[2],cb);
	if(typeof result !== "undefined"){
		cb(result);
	}
};
_db.initialize();<commit_msg>fix strings<commit_after>var _db = $$fObj$$;
var listeners = {};
_db.on = function (eventName, func, scope) {
	if(eventName.indexOf(" ")>0){
		return eventName.split(" ").map(function(v){
			return _db.on(v,func,scope);
		},_db);
	}
	scope = scope || _db;
	if (!(eventName in listeners)) {
		listeners[eventName] = [];
	}
	listeners[eventName].push(function (a) {
		func.call(scope, a);
	});
};
var _fire = function (eventName, data) {
	if (!(eventName in listeners)) {
		return;
	}
	listeners[eventName].forEach(function (v) {
		v(data);
	});
};
_db.fire = function (eventName, data, transfer) {
	!self._noTransferable ? self.postMessage([
		[eventName], data], transfer) : self.postMessage([
		[eventName], data]);
};
_db.off=function(eventName,func){
	if(eventName.indexOf(" ")>0){
		return eventName.split(" ").map(function(v){
			return _db.off(v,func);
		});
	}
	if(!(eventName in listeners)){
		return;
	}else if(!func){
		delete listeners[eventName];
	}else{
		if(listeners[eventName].indexOf(func)>-1){
			if(listeners[eventName].length>1){
				delete listeners[eventName];
			}else{
				listeners[eventName].splice(listeners[eventName].indexOf(func),1);
			}
		}
	}
};
self.onmessage=function(e){
	if(e.data[0][0]==="com.communistjs"){
		return regMsg(e);
	}else{
		_fire(e.data[0][0],e.data[1]);
	}
};
var regMsg = function(e){
	var cb=function(data,transfer){
		!self._noTransferable?self.postMessage([e.data[0],data],transfer):self.postMessage([e.data[0],data]);
	};
	var result = _db[e.data[1]](e.data[2],cb);
	if(typeof result !== "undefined"){
		cb(result);
	}
};
_db.initialize();<|endoftext|>