<commit_before>//v1.0 as Starting Point
//v2.0 Cleaning up code. Setting up Menu Structure and Initial Settings.

var version = '2.0 Beta';
var SCBversion = '3.03'; //Last SandCastle Builder version tested

//Declare and Initialize Variables
var incoming_ONG = 0;
var NinjaAutoClickStatus = 1;
var Time_to_ONG = 1800000;
var lootBoxes = ['boosts', 'ninj', 'cyb', 'hpt', 'bean', 'chron', 'badges', 'badgesav'];

//BB Options Variables
var AudioAlertsStatus = 3;
var audio_Bell = new Audio("http://xenko.comxa.com/Ship_Bell.mp3");
	audio_Bell.volume = 1;
var audio_Chime = new Audio("http://xenko.comxa.com/Chime.mp3");
	audio_Chime.volume = 1;
var BorderAlertStatus = 1;
var description = "Error";
var IdleStatus = 0;
var RKAlertFrequency = 8;
var RKAutoClickStatus = 1;
var RKPlayAudio = 1;

//RK Variables
var start = -1;
var content = "empty";
var LCAutoClickStatus = 0;
var LCSolution = 'blank';
var len = 0;
var Logicat = 0;
var oldRKLocation = -1;
var oldRC = Molpy.redactedClicks - 1;
var oldLC = Molpy.Boosts['Logicat'].power - 1;
var RKLevel = '-1';
var RKLocation = '123';
var RKNew = 1;
var RKNewAudio = 1;
var RKTimer = Molpy.redactedToggle - Molpy.redactedCountup;

Molpy.redactedPuzzleTarget = true;

//Ninja AutoClicker and Border Warnings
function Ninja() {
    if (Molpy.ninjad == 0) {
        if (Molpy.npbONG == 0 && BorderAlertStatus == 1) {
			$("#beach").css("border","4px solid red");
        }
        else {
            incoming_ONG = 0;
            if (NinjaAutoClickStatus == 1) {
                Molpy.ClickBeach();
				Molpy.Notify('Ninja Auto Click', 1);
				if (BorderAlertStatus == 1) {
					$("#beach").css("border","1px solid white");
				}
            }
            else if (BorderAlertStatus == 1) {
            $("#beach").css("border","4px solid green");
            }

        }
	}
    else if (Time_to_ONG <= 15000) {
		if (BorderAlertStatus == 1) {
			$("#beach").css("border","4px solid yellow");
		}
        if (incoming_ONG == 0 && (AudioAlertsStatus == 3 || AudioAlertsStatus == 4)) {
			audio_Chime.play();
			incoming_ONG = 1;
        }
    }
    else if (BorderAlertStatus == 1) {
        $("#beach").css("border","1px solid white");
	}
}

function ToggleMenus(wantOpen) {
	for (i=0, len = lootBoxes.length; i < len; i++) {
		if (lootBoxes[i] == wantOpen) {
			if (Molpy.options.showhide[lootBoxes[i]] != 1) {
				showhideToggle(lootBoxes[i]);
			}
		}
		else {
			if (Molpy.options.showhide[lootBoxes[i]]) {
				showhideToggle(lootBoxes[i]);
			}
		}
	}
}

function FindRK() {
	/*
	RV of 1 is Sand Tools
	RV of 2 is Castle Tools
	RV of 3 is Boosts Main Page
	RV of 4 is Boosts Menus, Hill People Tech, etc.
	RV of 5 is Badges Earned
	RV of 6 is Badges Available
	*/

	//Determines RK location
	RKLocation = '123';
	if (Molpy.redactedVisible > 3) {
		RKLocation = Molpy.redactedGr;
	}

	//Opens RK location
	ToggleMenus(RKLocation);

	//Resets old RK variables
	oldRKLocation = Molpy.redactedVisible;
	oldRC = Molpy.redactedClicks;
	oldLC = Molpy.Boosts['Logicat'].power;
}

function ManualRKClick() {

}

function RedundaKitty() {
	//Refresh Timer Variable
	RKTimer = Molpy.redactedToggle - Molpy.redactedCountup;

	//If a RedundaKitty is active
	if (Molpy.redactedVisible > 0) {

		//Checks if RK is new
		if (RKNew == 1 || Molpy.redactedVisible != oldRKLocation || Molpy.redactedClicks > oldRC || Molpy.Boosts['Logicat'].power != oldLC) {
			RKNewAudio = 1;
			RKNew = 0;
			//Finds RK if appropriate BeachBall option enabled
			if (RKAutoClickStatus > 0) {
				FindRK();
			}
		}

		//Determines if it is an RK or LC
		//If RK is visible
		if ($('#redacteditem').length) {
			$('#redacteditem').css("border","2px solid red"); //Highlights RK
			content = $('#redacteditem').html();
			//If RK contains word statement, it is a LC.
			if (content.indexOf("statement") !== -1) {
				//Molpy.Notify('Logicat Found', 1);
				Logicat = 1;
			}
			//Otherwise it is an RK
			else {
				Logicat = 0;
				start = content.indexOf("ClickRedacted");
				content = content.substring(start,start+17);
				content = content.replace(/[&\/\\#,+()$~%.'":*?<>{}]/g,'');
				len = content.length;
				RKLevel = content.substring(13,len);
				if (RKLevel != 0) {
					Molpy.Notify('RedundaKitty Level is: ' + RKLevel, 1);
				}
			}
		}
		//If RK not visible, LC to 99.
		else {
			Logicat = 99;
		}

		//Clicks RK if AutoClick Enabled
		if (RKAutoClickStatus == 2 && Logicat == 0 ) {
			Molpy.ClickRedacted(RKLevel);
			RKNew = 1;
			RKLocation = '123';
			ToggleMenus('123');
		}
		//Solves LC if AutoClick enabled
		else if (Logicat == 1 && LCAutoClickStatus == 1) {
			SolveLogicat();
			RKNew = 1;
			RKLocation = '123';
			ToggleMenus('123');
		}

		//Redundakitty Notifications for Manual Clicking (Title Bar, Audio)
		else {
			document.title = "! kitten !";
			//If RK Audio Alerts Enabled
			if (AudioAlertsStatus == 1 || AudioAlertsStatus == 3) {
				//If proper mNP and hasn't yet played this mNP
				if (Math.floor(RKTimer % RKAlertFrequency) == 0 && RKPlayAudio == 1) {
					audio_Bell.play();
					RKPlayAudio = 0;
				}
				else {
					RKPlayAudio = 1;
				}
			}
		}
	}
	//If no RK active, update title Timer. Reset some variables.
	else {
		document.title = RKTimer;
		oldRKLocation = -1;
		RKNew = 1;
		RKPlayAudio = 0;
	}
}

function SolveLogicat() {
	var i = 65;
	do
		{LCSolution = String.fromCharCode(i);
		i++;
		Molpy.Notify('Target: ' Molpy.redactedPuzzleTarget, 1);
		Molpy.Notify('Found: ' + Molpy.redactedSGen.StatementValue(LCSolution), 1);
		}
	while (Molpy.redactedPuzzleTarget != Molpy.redactedSGen.StatementValue(LCSolution));
	Molpy.ClickRedactedPuzzle(LCSolution);

	/*while (Molpy.redactedPuzzleTarget != undefined) {
		LCSolution = String.fromCharCode(i);
		if (Molpy.redactedPuzzleTarget == Molpy.redactedSGen.StatementValue(LCSolution)) {
			Molpy.ClickRedactedPuzzle(LCSolution);
			Molpy.redactedPuzzleTarget = undefined;
		}
		else {i++;}
	}*/
}

function SwitchOption(option) {
	switch (option) {
		case 'RKAutoClick':
			RKAutoClickStatus++;
			if (RKAutoClickStatus > 2) {RKAutoClickStatus = 0;}
			status = RKAutoClickStatus;
			break;
		case 'LCAutoClick':
			LCAutoClickStatus++;
			if (LCAutoClickStatus > 1) {LCAutoClickStatus = 0;}
			status = LCAutoClickStatus;
			break;
		case 'NinjaAutoClick':
			NinjaAutoClickStatus++;
			if (NinjaAutoClickStatus > 1) {NinjaAutoClickStatus = 0;}
			status = NinjaAutoClickStatus;
			break;
		case 'BorderAlert':
			BorderAlertStatus++;
			if (BorderAlertStatus > 1) {
				BorderAlertStatus = 0;
				$("#beach").css("border","1px solid white");
			}
			status = BorderAlertStatus;
			break;
		case 'AudioAlerts':
			AudioAlertsStatus++;
			if (AudioAlertsStatus > 3) {AudioAlertsStatus = 0;}
			status = AudioAlertsStatus;
			break;
	}
	DisplayDescription(option, status);
}

function DisplayDescription(option, status) {
	error = 0;
	if (option == 'LCAutoClick' || option == 'NinjaAutoClick' || option == 'BorderAlert') {
		if (status == 0) {description = 'Off';}
		else if (status == 1) {description = 'On';}
		else {Molpy.Notify('Display Description Error', 1);}
	}
	else if (option == 'AudioAlerts') {
		if (status == 0) {description = 'Off';}
		else if (status == 1) {description = 'RK Only'; RKPlayAudio = 1;}
		else if (status == 2) {description = 'ONG Only';}
		else if (status == 3) {description = 'RK and ONG'; RKPlayAudio = 1;}
		else {Molpy.Notify('Display Description Error - Audio Alerts: ' + status, 1);}
	}
	else if (option == 'RKAutoClick') {
		if (status == 0) {description = 'Off';}
		else if (status == 1) {description = 'Find RK Only'; RKNew = 1;}
		else if (status == 2) {description = 'On'; RKNew = 1;}
		else {Molpy.Notify('Display Description Error - RKAutoClick: ' + status, 1);}
	}
	else {
		Molpy.Notify(option + ' is not a valid option', 1);
		error = 1;
	}

	if (error == 0) {g(option + 'Desc').innerHTML = '
' + description;}
}

//Beach Ball Startup
//Set Settings
if (Molpy.Got('Kitnip') == 1){RKAlertFrequency = 10;}

//Create Menu
$('#optionsItems').append('

BeachBall Settings

');
$('#optionsItems').append('

Redundakitty Auto Click

');
$('#optionsItems').append('

Logicat Auto Click

');
$('#optionsItems').append('

Ninja Auto Click

');
$('#optionsItems').append('

Ninja Visual Alert

');
$('#optionsItems').append('

Audio Alerts

');
$('#optionsItems').append('

Spawn RK

');
//$('#optionsItems').append('

Blank

');
DisplayDescription('RKAutoClick', RKAutoClickStatus);
DisplayDescription('LCAutoClick', LCAutoClickStatus);
DisplayDescription('NinjaAutoClick', NinjaAutoClickStatus);
DisplayDescription('BorderAlert', BorderAlertStatus);
DisplayDescription('AudioAlerts', AudioAlertsStatus);

function MainLoop() {
	Molpy.Notify('BeachBall version ' + version + ' loaded for SandCastle Builder version ' + SCBversion, 1);
	setInterval(function() {
		//Molpy.Notify('1 mNP', 0);
		Time_to_ONG = (Molpy.NPlength * 1000) - Molpy.ONGelapsed;
		RedundaKitty();
		Ninja();
	}, 1800);
}

//Run Main Loop after 1 second startup delay
setTimeout(MainLoop, 1000);

function SpawnRK() {
	Molpy.redactedCountup = Molpy.redactedToggle - 1;
}

<commit_msg>Fixing LC solver<commit_after>//v1.0 as Starting Point
//v2.0 Cleaning up code. Setting up Menu Structure and Initial Settings.

var version = '2.0 Beta';
var SCBversion = '3.03'; //Last SandCastle Builder version tested

//Declare and Initialize Variables
var incoming_ONG = 0;
var NinjaAutoClickStatus = 1;
var Time_to_ONG = 1800000;
var lootBoxes = ['boosts', 'ninj', 'cyb', 'hpt', 'bean', 'chron', 'badges', 'badgesav'];

//BB Options Variables
var AudioAlertsStatus = 3;
var audio_Bell = new Audio("http://xenko.comxa.com/Ship_Bell.mp3");
	audio_Bell.volume = 1;
var audio_Chime = new Audio("http://xenko.comxa.com/Chime.mp3");
	audio_Chime.volume = 1;
var BorderAlertStatus = 1;
var description = "Error";
var IdleStatus = 0;
var RKAlertFrequency = 8;
var RKAutoClickStatus = 1;
var RKPlayAudio = 1;

//RK Variables
var start = -1;
var content = "empty";
var LCAutoClickStatus = 0;
var LCSolution = 'blank';
var len = 0;
var Logicat = 0;
var oldRKLocation = -1;
var oldRC = Molpy.redactedClicks - 1;
var oldLC = Molpy.Boosts['Logicat'].power - 1;
var RKLevel = '-1';
var RKLocation = '123';
var RKNew = 1;
var RKNewAudio = 1;
var RKTimer = Molpy.redactedToggle - Molpy.redactedCountup;

//Ninja AutoClicker and Border Warnings
function Ninja() {
    if (Molpy.ninjad == 0) {
        if (Molpy.npbONG == 0 && BorderAlertStatus == 1) {
			$("#beach").css("border","4px solid red");
        }
        else {
            incoming_ONG = 0;
            if (NinjaAutoClickStatus == 1) {
                Molpy.ClickBeach();
				Molpy.Notify('Ninja Auto Click', 1);
				if (BorderAlertStatus == 1) {
					$("#beach").css("border","1px solid white");
				}
            }
            else if (BorderAlertStatus == 1) {
            $("#beach").css("border","4px solid green");
            }

        }
	}
    else if (Time_to_ONG <= 15000) {
		if (BorderAlertStatus == 1) {
			$("#beach").css("border","4px solid yellow");
		}
        if (incoming_ONG == 0 && (AudioAlertsStatus == 3 || AudioAlertsStatus == 4)) {
			audio_Chime.play();
			incoming_ONG = 1;
        }
    }
    else if (BorderAlertStatus == 1) {
        $("#beach").css("border","1px solid white");
	}
}

function ToggleMenus(wantOpen) {
	for (i=0, len = lootBoxes.length; i < len; i++) {
		if (lootBoxes[i] == wantOpen) {
			if (Molpy.options.showhide[lootBoxes[i]] != 1) {
				showhideToggle(lootBoxes[i]);
			}
		}
		else {
			if (Molpy.options.showhide[lootBoxes[i]]) {
				showhideToggle(lootBoxes[i]);
			}
		}
	}
}

function FindRK() {
	/*
	RV of 1 is Sand Tools
	RV of 2 is Castle Tools
	RV of 3 is Boosts Main Page
	RV of 4 is Boosts Menus, Hill People Tech, etc.
	RV of 5 is Badges Earned
	RV of 6 is Badges Available
	*/

	//Determines RK location
	RKLocation = '123';
	if (Molpy.redactedVisible > 3) {
		RKLocation = Molpy.redactedGr;
	}

	//Opens RK location
	ToggleMenus(RKLocation);

	//Resets old RK variables
	oldRKLocation = Molpy.redactedVisible;
	oldRC = Molpy.redactedClicks;
	oldLC = Molpy.Boosts['Logicat'].power;
}

function ManualRKClick() {

}

function RedundaKitty() {
	//Refresh Timer Variable
	RKTimer = Molpy.redactedToggle - Molpy.redactedCountup;

	//If a RedundaKitty is active
	if (Molpy.redactedVisible > 0) {

		//Checks if RK is new
		if (RKNew == 1 || Molpy.redactedVisible != oldRKLocation || Molpy.redactedClicks > oldRC || Molpy.Boosts['Logicat'].power != oldLC) {
			RKNewAudio = 1;
			RKNew = 0;
			//Finds RK if appropriate BeachBall option enabled
			if (RKAutoClickStatus > 0) {
				FindRK();
			}
		}

		//Determines if it is an RK or LC
		//If RK is visible
		if ($('#redacteditem').length) {
			$('#redacteditem').css("border","2px solid red"); //Highlights RK
			content = $('#redacteditem').html();
			//If RK contains word statement, it is a LC.
			if (content.indexOf("statement") !== -1) {
				//Molpy.Notify('Logicat Found', 1);
				Logicat = 1;
			}
			//Otherwise it is an RK
			else {
				Logicat = 0;
				start = content.indexOf("ClickRedacted");
				content = content.substring(start,start+17);
				content = content.replace(/[&\/\\#,+()$~%.'":*?<>{}]/g,'');
				len = content.length;
				RKLevel = content.substring(13,len);
				if (RKLevel != 0) {
					Molpy.Notify('RedundaKitty Level is: ' + RKLevel, 1);
				}
			}
		}
		//If RK not visible, LC to 99.
		else {
			Logicat = 99;
		}

		//Clicks RK if AutoClick Enabled
		if (RKAutoClickStatus == 2 && Logicat == 0 ) {
			Molpy.ClickRedacted(RKLevel);
			RKNew = 1;
			RKLocation = '123';
			ToggleMenus('123');
		}
		//Solves LC if AutoClick enabled
		else if (Logicat == 1 && LCAutoClickStatus == 1) {
			SolveLogicat();
			RKNew = 1;
			RKLocation = '123';
			ToggleMenus('123');
		}

		//Redundakitty Notifications for Manual Clicking (Title Bar, Audio)
		else {
			document.title = "! kitten !";
			//If RK Audio Alerts Enabled
			if (AudioAlertsStatus == 1 || AudioAlertsStatus == 3) {
				//If proper mNP and hasn't yet played this mNP
				if (Math.floor(RKTimer % RKAlertFrequency) == 0 && RKPlayAudio == 1) {
					audio_Bell.play();
					RKPlayAudio = 0;
				}
				else {
					RKPlayAudio = 1;
				}
			}
		}
	}
	//If no RK active, update title Timer. Reset some variables.
	else {
		document.title = RKTimer;
		oldRKLocation = -1;
		RKNew = 1;
		RKPlayAudio = 0;
	}
}

function SolveLogicat() {
	var i = 65;
	do
		{LCSolution = String.fromCharCode(i);
		i++;
		Molpy.Notify('Target: ' LCSolution, 1);
		Molpy.Notify('Found: ' + Molpy.redactedSGen.StatementValue(LCSolution), 1);
		}
	while (Molpy.redactedPuzzleTarget != Molpy.redactedSGen.StatementValue(LCSolution));
	Molpy.ClickRedactedPuzzle(LCSolution);

	/*while (Molpy.redactedPuzzleTarget != undefined) {
		LCSolution = String.fromCharCode(i);
		if (Molpy.redactedPuzzleTarget == Molpy.redactedSGen.StatementValue(LCSolution)) {
			Molpy.ClickRedactedPuzzle(LCSolution);
			Molpy.redactedPuzzleTarget = undefined;
		}
		else {i++;}
	}*/
}

function SwitchOption(option) {
	switch (option) {
		case 'RKAutoClick':
			RKAutoClickStatus++;
			if (RKAutoClickStatus > 2) {RKAutoClickStatus = 0;}
			status = RKAutoClickStatus;
			break;
		case 'LCAutoClick':
			LCAutoClickStatus++;
			if (LCAutoClickStatus > 1) {LCAutoClickStatus = 0;}
			status = LCAutoClickStatus;
			break;
		case 'NinjaAutoClick':
			NinjaAutoClickStatus++;
			if (NinjaAutoClickStatus > 1) {NinjaAutoClickStatus = 0;}
			status = NinjaAutoClickStatus;
			break;
		case 'BorderAlert':
			BorderAlertStatus++;
			if (BorderAlertStatus > 1) {
				BorderAlertStatus = 0;
				$("#beach").css("border","1px solid white");
			}
			status = BorderAlertStatus;
			break;
		case 'AudioAlerts':
			AudioAlertsStatus++;
			if (AudioAlertsStatus > 3) {AudioAlertsStatus = 0;}
			status = AudioAlertsStatus;
			break;
	}
	DisplayDescription(option, status);
}

function DisplayDescription(option, status) {
	error = 0;
	if (option == 'LCAutoClick' || option == 'NinjaAutoClick' || option == 'BorderAlert') {
		if (status == 0) {description = 'Off';}
		else if (status == 1) {description = 'On';}
		else {Molpy.Notify('Display Description Error', 1);}
	}
	else if (option == 'AudioAlerts') {
		if (status == 0) {description = 'Off';}
		else if (status == 1) {description = 'RK Only'; RKPlayAudio = 1;}
		else if (status == 2) {description = 'ONG Only';}
		else if (status == 3) {description = 'RK and ONG'; RKPlayAudio = 1;}
		else {Molpy.Notify('Display Description Error - Audio Alerts: ' + status, 1);}
	}
	else if (option == 'RKAutoClick') {
		if (status == 0) {description = 'Off';}
		else if (status == 1) {description = 'Find RK Only'; RKNew = 1;}
		else if (status == 2) {description = 'On'; RKNew = 1;}
		else {Molpy.Notify('Display Description Error - RKAutoClick: ' + status, 1);}
	}
	else {
		Molpy.Notify(option + ' is not a valid option', 1);
		error = 1;
	}

	if (error == 0) {g(option + 'Desc').innerHTML = '
' + description;}
}

//Beach Ball Startup
//Set Settings
if (Molpy.Got('Kitnip') == 1){RKAlertFrequency = 10;}

//Create Menu
$('#optionsItems').append('

BeachBall Settings

');
$('#optionsItems').append('

Redundakitty Auto Click

');
$('#optionsItems').append('

Logicat Auto Click

');
$('#optionsItems').append('

Ninja Auto Click

');
$('#optionsItems').append('

Ninja Visual Alert

');
$('#optionsItems').append('

Audio Alerts

');
$('#optionsItems').append('

Spawn RK

');
//$('#optionsItems').append('

Blank

');
DisplayDescription('RKAutoClick', RKAutoClickStatus);
DisplayDescription('LCAutoClick', LCAutoClickStatus);
DisplayDescription('NinjaAutoClick', NinjaAutoClickStatus);
DisplayDescription('BorderAlert', BorderAlertStatus);
DisplayDescription('AudioAlerts', AudioAlertsStatus);

function MainLoop() {
	Molpy.Notify('BeachBall version ' + version + ' loaded for SandCastle Builder version ' + SCBversion, 1);
	setInterval(function() {
		//Molpy.Notify('1 mNP', 0);
		Time_to_ONG = (Molpy.NPlength * 1000) - Molpy.ONGelapsed;
		RedundaKitty();
		Ninja();
	}, 1800);
}

//Run Main Loop after 1 second startup delay
setTimeout(MainLoop, 1000);

function SpawnRK() {
	Molpy.redactedCountup = Molpy.redactedToggle - 1;
}

<|endoftext|>


<commit_before>require(
    [
        'iso-svg/lib',
        'iso-svg/Surface',
        'iso-svg/Camera',
        'iso-svg/Projector',
        'iso-svg/meshes/Icosahedron',
        'iso-svg/meshes/Cube',
        'iso-svg/meshes/Sphere'
    ],
    function (lib, Surface, Camera, Projector, Icosahedron, Cube, Sphere) {

        "use strict";

        var surface = Surface.create({});
        var camera = Camera.create({
            zoom: 100,
            mode: Camera.ISOMETRIC
        });
        var projector = Projector.create({
            surface: surface,
            camera: camera
        });

        var sphere = Sphere.create(
            {
                levelOfDetail: 3,
                spikiness: 0.1
            }
        );
        projector.mesh(sphere);

        // var cube = Cube.create();
        // projector.mesh(cube);
    }
);<commit_msg>Tweak whitespace.<commit_after>require(
    [
        'iso-svg/lib',
        'iso-svg/Surface',
        'iso-svg/Camera',
        'iso-svg/Projector',
        'iso-svg/meshes/Icosahedron',
        'iso-svg/meshes/Cube',
        'iso-svg/meshes/Sphere'
    ],
    function (lib, Surface, Camera, Projector, Icosahedron, Cube, Sphere) {

        "use strict";

        var surface = Surface.create({});
        var camera = Camera.create({
            zoom: 100,
            mode: Camera.ISOMETRIC
        });
        var projector = Projector.create({
            surface: surface,
            camera: camera
        });

        var sphere = Sphere.create({
            levelOfDetail: 3,
            spikiness: 0.1
        });
        projector.mesh(sphere);

        // var cube = Cube.create();
        // projector.mesh(cube);
    }
);<|endoftext|>


<commit_before>var ThreeDVisualization = Visualization.extend(function(base) {
    return {
        init: function(container, history) {
            base.init(container, history);

            this.particleSystem = null;
            this.snapshot = null;
            this.lastIteration = null;
        },

        /* Private */

        _iterationUpdated: function() {
            this.snapshot = this.history.getSnapshotAtIndex(this.iteration - 1);

            if (this.snapshot) this._setupCells();
            else this._clearCells();
        },

        _update: function() {
            base._update();

            if (this.lastIteration != this.iteration) {
                this._iterationUpdated();
                this.lastIteration = this.iteration;
            }
        },

        _clearCells: function() {
            if (this.particleSystem) this.scene.remove(this.particleSystem);
        },

        _setupCells: function() {
            var padding = 50,
                dimensions = this.snapshot.getModelDimensions(),
                numX = dimensions[0],
                numY = dimensions[1],
                numZ = dimensions[2],
                originX = -(numX * padding) / 2,
                originY = -(numY * padding) / 2,
                originZ = -(numZ * padding) / 2;

            var particles = new THREE.Geometry(),
                material = new THREE.ParticleBasicMaterial({
                    color: 0xFFFFFF,
                    size: 20,
                    map: THREE.ImageUtils.loadTexture(
                        "img/particle.png"
                    ),
                    blending: THREE.AdditiveBlending,
                    transparent: true
                }),
                particleSystem = new THREE.ParticleSystem(particles, material);

            particleSystem.sortParticles = true;

            for (var x = 0; x < numX; x++) {
                for (var y = 0; y < numY; y++) {
                    for (var z = 0; z < numZ; z++) {
                        var pX = originX + x * padding,
                            pY = originY + y * padding,
                            pZ = originZ + z * padding,
                            particle = new THREE.Vector3(pX, pY, pZ);

                        particles.vertices.push(particle);
                    }
                }
            }

            this._clearCells();
            this.scene.add(particleSystem);

            this.particleSystem = particleSystem;
        }
    };
});
<commit_msg>Controlling padding independently for each dimension<commit_after>var ThreeDVisualization = Visualization.extend(function(base) {
    return {
        init: function(container, history) {
            base.init(container, history);

            this.particleSystem = null;
            this.snapshot = null;
            this.lastIteration = null;
        },

        /* Private */

        _iterationUpdated: function() {
            this.snapshot = this.history.getSnapshotAtIndex(this.iteration - 1);

            if (this.snapshot) this._setupCells();
            else this._clearCells();
        },

        _update: function() {
            base._update();

            if (this.lastIteration != this.iteration) {
                this._iterationUpdated();
                this.lastIteration = this.iteration;
            }
        },

        _clearCells: function() {
            if (this.particleSystem) this.scene.remove(this.particleSystem);
        },

        _setupCells: function() {
            var paddingX = 100,
                paddingY = 100,
                paddingZ = 25,
                dimensions = this.snapshot.getModelDimensions(),
                numX = dimensions[0],
                numY = dimensions[1],
                numZ = dimensions[2],
                originX = -(numX * paddingX) / 2,
                originY = -(numY * paddingY) / 2,
                originZ = -(numZ * paddingZ) / 2;

            var particles = new THREE.Geometry(),
                material = new THREE.ParticleBasicMaterial({
                    color: 0xFFFFFF,
                    size: 20,
                    map: THREE.ImageUtils.loadTexture(
                        "img/particle.png"
                    ),
                    blending: THREE.AdditiveBlending,
                    transparent: true
                }),
                particleSystem = new THREE.ParticleSystem(particles, material);

            particleSystem.sortParticles = true;

            for (var x = 0; x < numX; x++) {
                for (var y = 0; y < numY; y++) {
                    for (var z = 0; z < numZ; z++) {
                        var pX = originX + x * paddingX,
                            pY = originY + y * paddingY,
                            pZ = originZ + z * paddingZ,
                            particle = new THREE.Vector3(pX, pY, pZ);

                        particles.vertices.push(particle);
                    }
                }
            }

            this._clearCells();
            this.scene.add(particleSystem);

            this.particleSystem = particleSystem;
        }
    };
});
<|endoftext|>


<commit_before>var Helpers = (function() {
  return {
    report: reportHTML
  }

  function reportHTML() {
    var report = document.querySelector('#result') ||
        function() {
          var r = document.createElement('div');
          r.id = 'result';
          document.querySelector('body').appendChild(r);
          return r;
      }();
    report.innerHTML += '
' + [].slice.call(arguments).join() + '
';
  }

}());
<commit_msg>Update Helpers.js<commit_after>var Helpers = (function() {
  return {
    report: reportHTML,
    isObj: isPlainObject,
    useJQ: loadJQ
  }

  function reportHTML() {
    var report = document.querySelector('#result') ||
        function() {
          var r = document.createElement('div');
          r.id = 'result';
          document.querySelector('body').appendChild(r);
          return r;
      }();
    report.innerHTML += '
' + [].slice.call(arguments).join() + '
';
  }

  function isPlainObject(item) {
    return (
        item &&
        typeof item === "object" &&
        Object.prototype.toString.call(item) === "object Object" &&
        !item.nodeType
    );
  }

  function loadJQ(cb) {
      if (w.jQuery) {
        return function () {return void( cb && cb());}
      }
      return function () {
        var head  = d.querySelector('head')
           ,jq    = d.createElement('script');
        void( cb && jq.addEventListener('load',cb) );
        jq.src    = '//code.jquery.com/jquery-2.1.1.min.js';
        return head.appendChild(jq);
      };
  }

}());
<|endoftext|>


<commit_before>// https://docs.docker.com/engine/reference/commandline/build/

"use strict";

const _ = require('lodash');
const buildCommand = require('../buildCommand');

const executable = "docker build"

const optionMap = {
  build_arg: values => _.map(values, item => `--build-arg ${item}`).join(" "),
  cpu_shares: () => '--cpu-shares',
  file: value => `-f ${value}`,
  memory: value => `-m ${value}`,
  no_cache: () => '--no-cache',
  quiet: () => '--q',
  tags: values => _.map(values, item => `-t ${item}`).join(" ")
};

function getTarget(config) {
  if(config.path) return config.path;
  if(config.url)  return url;
  else            return ".";
}

module.exports = (config) => {
  let options = _.omit(config, 'path', 'url');
  let target = getTarget(config);
  return buildCommand(executable, options, optionMap, target);
};

// --build-arg=[]                  Set build-time variables
// --cpu-shares                    CPU Shares (relative weight)
// --cgroup-parent=""              Optional parent cgroup for the container
// --cpu-period=0                  Limit the CPU CFS (Completely Fair Scheduler) period
// --cpu-quota=0                   Limit the CPU CFS (Completely Fair Scheduler) quota
// --cpuset-cpus=""                CPUs in which to allow execution, e.g. `0-3`, `0,1`
// --cpuset-mems=""                MEMs in which to allow execution, e.g. `0-3`, `0,1`
// --disable-content-trust=true    Skip image verification
// -f, --file=""                   Name of the Dockerfile (Default is 'PATH/Dockerfile')
// --force-rm                      Always remove intermediate containers
// --help                          Print usage
// --isolation=""                  Container isolation technology
// -m, --memory=""                 Memory limit for all build containers
// --memory-swap=""                A positive integer equal to memory plus swap. Specify -1 to enable unlimited swap.
// --no-cache                      Do not use cache when building the image
// --pull                          Always attempt to pull a newer version of the image
// -q, --quiet                     Suppress the build output and print image ID on success
// --rm=true                       Remove intermediate containers after a successful build
// --shm-size=[]                   Size of `/dev/shm`. The format is `<number><unit>`. `number` must be greater than `0`.  Unit is optional and can be `b` (bytes), `k` (kilobytes), `m` (megabytes), or `g` (gigabytes). If you omit the unit, the system uses bytes. If you omit the size entirely, the system uses `64m`.
// -t, --tag=[]                    Name and optionally a tag in the 'name:tag' format
// --ulimit=[]
<commit_msg>Prettifying<commit_after>// https://docs.docker.com/engine/reference/commandline/build/

"use strict";

const _ = require('lodash');
const buildCommand = require('../buildCommand');

const executable = "docker build"

const optionMap = {
  build_arg:  values  => _.map(
                          values, item => `--build-arg ${item}`)
                          .join(" "),
  cpu_shares: ()      => '--cpu-shares',
  file:       value   => `-f ${value}`,
  memory:     value   => `-m ${value}`,
  no_cache:   ()      => '--no-cache',
  quiet:      ()      => '--q',
  tags:       values  => _.map(
                          values, item => `-t ${item}`)
                          .join(" ")
};

function getTarget(config) {
  if(config.path) return config.path;
  if(config.url)  return url;
  else            return ".";
}

module.exports = (config) => {
  let options = _.omit(config, 'path', 'url');
  let target = getTarget(config);
  return buildCommand(executable, options, optionMap, target);
};

// --build-arg=[]                  Set build-time variables
// --cpu-shares                    CPU Shares (relative weight)
// --cgroup-parent=""              Optional parent cgroup for the container
// --cpu-period=0                  Limit the CPU CFS (Completely Fair Scheduler) period
// --cpu-quota=0                   Limit the CPU CFS (Completely Fair Scheduler) quota
// --cpuset-cpus=""                CPUs in which to allow execution, e.g. `0-3`, `0,1`
// --cpuset-mems=""                MEMs in which to allow execution, e.g. `0-3`, `0,1`
// --disable-content-trust=true    Skip image verification
// -f, --file=""                   Name of the Dockerfile (Default is 'PATH/Dockerfile')
// --force-rm                      Always remove intermediate containers
// --help                          Print usage
// --isolation=""                  Container isolation technology
// -m, --memory=""                 Memory limit for all build containers
// --memory-swap=""                A positive integer equal to memory plus swap. Specify -1 to enable unlimited swap.
// --no-cache                      Do not use cache when building the image
// --pull                          Always attempt to pull a newer version of the image
// -q, --quiet                     Suppress the build output and print image ID on success
// --rm=true                       Remove intermediate containers after a successful build
// --shm-size=[]                   Size of `/dev/shm`. The format is `<number><unit>`. `number` must be greater than `0`.  Unit is optional and can be `b` (bytes), `k` (kilobytes), `m` (megabytes), or `g` (gigabytes). If you omit the unit, the system uses bytes. If you omit the size entirely, the system uses `64m`.
// -t, --tag=[]                    Name and optionally a tag in the 'name:tag' format
// --ulimit=[]
<|endoftext|>


<commit_before>var pg = require('pg');
var geojson = require('../helpers/geojson');
var jsonp = require('../helpers/jsonp');
var settings = require('../settings');

var pgclient = new pg.Client(settings.database);

module.exports.controller = function(app) {

  /* enable CORS */
  app.all('*', function(req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'X-Requested-With');
    next();
  });

  app.get('/vector/:schema/:table/:geom/intersect', function(req, res, next) {
    var queryshape = ' {"type": "Point", "coordinates": [' + req.query['lng'] + ',' + req.query['lat'] + '] }';
    var geom = req.params.geom.toLowerCase();
    if ((geom != 'features') && (geom != 'geometry')) {
      res.status(404).send("Resource '" + geom + "' not found");
      return;
    }
    var schemaname = req.params.schema;
    var tablename = req.params.table;
    var fullname = schemaname + '.' + tablename;
    pgclient.connect(function(err) {
      var spatialcol = 'wkb_geometry';
      var sql;
      var coll;
      if (geom == 'features') {
        sql = 'select st_asgeojson(st_transform(' + spatialcol + ',4326)) as geojson, * from ' + tablename + ' where ST_INTERSECTS(' + spatialcol + ", ST_SetSRID(ST_GeomFromGeoJSON('" + queryshape + "'),4326));";
        coll = {
          type: 'FeatureCollection',
          features: []
        };
        query = pgclient.query(sql);
      }

      query.on('row', function(result) {
        var props = new Object;
        if (!result) {
          return res.send('No data found');
        }
        else {
          if (geom == 'features') {
            coll.features.push(geojson.getFeatureResult(result, spatialcol));
          } else if (geom == 'geometry') {
            var shape = JSON.parse(result.geojson);
            coll.geometries.push(shape);
          }
        }
      });

      query.on('end', function(err, result) {
        res.setHeader('Content-Type', 'application/json');
        res.send(jsonp.getJsonP(req.query.callback, coll));
      });
    });
  });
  app.get('/neighbor/:schema/:table/:geom/intersect', function(req, res, next) {
    var queryshape = "'SRID=4326;POINT(" + req.query['lng'] +' ' + req.query['lat'] + ")'";
    var geom = req.params.geom.toLowerCase();
    if ((geom != 'features') && (geom != 'geometry')) {
      res.status(404).send("Resource '" + geom + "' not found");
      return;
    }
    var schemaname = req.params.schema;
    var tablename = req.params.table;
    var fullname = schemaname + '.' + tablename;
    pgclient.connect(function(err) {
      var spatialcol = 'wkb_geometry';
      var sql;
      var coll;
      if (geom == 'features') {
        sql = 'SELECT ST_AsGeoJson(ST_Transform(b.' + spatialcol + ',4326)) as geojson, * from ' + tablename + ' as a, ' + tablename + ' as b where st_distance(a.' + spatialcol + ',b.' + spatialcol + ') < .00005 and ST_INTERSECTS(a.' + spatialcol + ', ST_GeographyFromText(' + queryshape + '));'
        //sql = 'SELECT ST_AsGeoJson(ST_Transform(b.' + spatialcol + ',4326)) as geojson, * from ' + tablename + ' as a, ' + tablename + ' as b where st_touches(a.' + spatialcol + ',b.' + spatialcol + ') and ST_INTERSECTS(a.' + spatialcol + ', ST_GeographyFromText(' + queryshape + '));'
        coll = {
          type: 'FeatureCollection',
          features: []
        };
        query = pgclient.query(sql);
      }

      query.on('row', function(result) {
        var props = new Object;
        if (!result) {
          return res.send('No data found');
        }
        else {
          if (geom == 'features') {
            coll.features.push(geojson.getFeatureResult(result, spatialcol));
          } else if (geom == 'geometry') {
            var shape = JSON.parse(result.geojson);
            coll.geometries.push(shape);
          }
        }
      });

      query.on('end', function(err, result) {
        res.setHeader('Content-Type', 'application/json');
        res.send(jsonp.getJsonP(req.query.callback, coll));
      });
    });
  });

};
<commit_msg>more stuff to fix problems with post<commit_after>var pg = require('pg');
var geojson = require('../helpers/geojson');
var jsonp = require('../helpers/jsonp');
var settings = require('../settings');

var pgclient = new pg.Client(settings.database);

module.exports.controller = function(app) {

  /* enable CORS */
  app.all('*', function(req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'X-Requested-With');
    next();
  });

  app.get('/vector/:schema/:table/:geom/intersect', function(req, res, next) {
    var queryshape = ' {"type": "Point", "coordinates": [' + req.query['lng'] + ',' + req.query['lat'] + '] }';
    var geom = req.params.geom.toLowerCase();
    if ((geom != 'features') && (geom != 'geometry')) {
      res.status(404).send("Resource '" + geom + "' not found");
      return;
    }
    var schemaname = req.params.schema;
    var tablename = req.params.table;
    var fullname = schemaname + '.' + tablename;
    pgclient.connect(function(err, client, done) {
      var spatialcol = 'wkb_geometry';
      var sql;
      var coll;
      if (geom == 'features') {
        sql = 'select st_asgeojson(st_transform(' + spatialcol + ',4326)) as geojson, * from ' + tablename + ' where ST_INTERSECTS(' + spatialcol + ", ST_SetSRID(ST_GeomFromGeoJSON('" + queryshape + "'),4326));";
        coll = {
          type: 'FeatureCollection',
          features: []
        };
        query = client.query(sql);
      }

      query.on('row', function(result) {
        var props = new Object;
        if (!result) {
          return res.send('No data found');
        }
        else {
          if (geom == 'features') {
            coll.features.push(geojson.getFeatureResult(result, spatialcol));
          } else if (geom == 'geometry') {
            var shape = JSON.parse(result.geojson);
            coll.geometries.push(shape);
          }
        }
      });

      query.on('end', function(err, result, done) {
        done();
        res.setHeader('Content-Type', 'application/json');
        res.send(jsonp.getJsonP(req.query.callback, coll));
      });
    });
  });
  app.get('/neighbor/:schema/:table/:geom/intersect', function(req, res, next) {
    var queryshape = "'SRID=4326;POINT(" + req.query['lng'] +' ' + req.query['lat'] + ")'";
    var geom = req.params.geom.toLowerCase();
    if ((geom != 'features') && (geom != 'geometry')) {
      res.status(404).send("Resource '" + geom + "' not found");
      return;
    }
    var schemaname = req.params.schema;
    var tablename = req.params.table;
    var fullname = schemaname + '.' + tablename;
    pgclient.connect(function(err, client, done) {
      var spatialcol = 'wkb_geometry';
      var sql;
      var coll;
      if (geom == 'features') {
        sql = 'SELECT ST_AsGeoJson(ST_Transform(b.' + spatialcol + ',4326)) as geojson, * from ' + tablename + ' as a, ' + tablename + ' as b where st_distance(a.' + spatialcol + ',b.' + spatialcol + ') < .00005 and ST_INTERSECTS(a.' + spatialcol + ', ST_GeographyFromText(' + queryshape + '));'
        //sql = 'SELECT ST_AsGeoJson(ST_Transform(b.' + spatialcol + ',4326)) as geojson, * from ' + tablename + ' as a, ' + tablename + ' as b where st_touches(a.' + spatialcol + ',b.' + spatialcol + ') and ST_INTERSECTS(a.' + spatialcol + ', ST_GeographyFromText(' + queryshape + '));'
        coll = {
          type: 'FeatureCollection',
          features: []
        };
        query = client.query(sql);
      }

      query.on('row', function(result) {
        var props = new Object;
        if (!result) {
          return res.send('No data found');
        }
        else {
          if (geom == 'features') {
            coll.features.push(geojson.getFeatureResult(result, spatialcol));
          } else if (geom == 'geometry') {
            var shape = JSON.parse(result.geojson);
            coll.geometries.push(shape);
          }
        }
      });

      query.on('end', function(err, result) {
        done();
        res.setHeader('Content-Type', 'application/json');
        res.send(jsonp.getJsonP(req.query.callback, coll));
      });
    });
  });

};
<|endoftext|>


<commit_before>if (Meteor.isClient) {

  // ROUTES

  Router.map(function () {

    this.route('frontpage', { path: '/', template: 'frontpage' });

    this.route('hackers', { path: '/hackers', template: 'hackers' });

    this.route('places', { path: '/places', template: 'places',
      load: function() {
        Session.set('absoluteHeader', true);
        Session.set('inversedHeader', true);
      },
      unload: function() {
        Session.set('absoluteHeader', false);
        Session.set('inversedHeader', false);
      }
    });

    this.route('hacker', { path: '/:localRankHash', template: 'hacker',
      before: function() {
        var city = 'lyon';
        var localRankHash = this.params.localRankHash;
        var localRank = bitHashInv(localRankHash);
        var hacker = Meteor.users.findOne({city: city, localRank: localRank});

        if (!hacker)
          return this.redirect('frontpage');

        Session.set('hackerId', hacker._id);
        Session.set('hacker', hacker);
      }
    });

    this.route('invite', { path: /^\/\+\/(.*)/, template: 'frontpage',
      before: function() {
        var phrase = bitHashInv(this.params[0]);
        Session.set('invitationPhrase', phrase);
        this.redirect('frontpage');
      }
    });

  });

  /* resolve url helpers */

  Router.routes['invite'].url = function(params) {
    return Meteor.absoluteUrl('+/' + params.phrase);
  }

  /* custom functionality */

  // XXX in iron-router you can't call this.redirect() if you want
  // that the unload event must be triggered. Instead you must use
  // Router.go() and then stopping the current route with this.stop()

  // check if there are duplicate accounts, if so request for merge
  var checkDuplicateAccounts = function() {
    if (Session.get('requestMergeDuplicateAccount')) {
      this.render('requestMergeDuplicateAccount');
      this.stop();
    }
  }

  // when login is required, render the frontpage
  var loginRequired = function() {

    if (!isLoggedIn() && Meteor.userId())
      return this.stop(); // login in progress, wait!

    if (!isLoggedIn()) {

      // hold current route so we can redirect after login
      var url = location.pathname + location.search + location.hash;
      Session.set('redirectUrl', url);

      // redirect to frontpage so that the user can login
      Router.go('frontpage');
      this.stop();
    }

  }

  // make sure that user is allowed to enter the site
  var allowedAccess = function() {
    if(Meteor.user() && !Meteor.user().allowAccess) {
      Router.go('hacker', Meteor.user());
      this.stop();
    }
  }

  // check for duplicate accounts, if so request for merge
  Router.before(checkDuplicateAccounts, {except: ['frontpage', 'invite']});

  // make sure the user is logged in, except for the pages below
  Router.before(loginRequired, {except: ['frontpage', 'invite']});

  // make sure that user is allowed to enter the site
  Router.before(allowedAccess, {except: ['invite', 'hacker']})

  // global router configuration
  Router.configure({
    autoRender: false
  });

}

if (Meteor.isServer) {

  // SERVER SIDE routes

  var url = Npm.require('url');

  // make use of the correct domain (canonical)
  // redirect when not at the same hostname as specified in environment variable "ROOT_URL"
  var useCanonicalDomain = function(currentUrlData, appUrlData) {
    if (currentUrlData.host.indexOf(appUrlData.host) === -1)
      return url.format(_.defaults({host: appUrlData.host}, currentUrlData));
    return null;
  }

  // redirect to city if not present in subdomain
  var redirectToCity = function(currentUrlData, appUrlData) {

    // all cities on this app
    var allowedCities = ['lyon'];

    // city where to redirect to
    var defaultCity = 'lyon';

    // current subdomain
    var subdomain = currentUrlData.host.replace(appUrlData.host, '').split('.')[0];

    // redirect if no valid city is specified in the subdomain
    if (!_.contains(allowedCities, subdomain))
      return url.format(_.defaults({host: defaultCity+'.'+appUrlData.host}, currentUrlData));

    return null;
  }

  var redirect = function(url, res) {
    res.writeHead(302, {'Location': url});
    res.end();
  }

  // parse url specified in environment ROOT_URL
  var getAppUrlData = function() {
    return url.parse(Meteor.absoluteUrl());
  }

  // parse current request url
  // XXX: not all properties can be resolved
  var getUrlData = function(request) {
    var currentUrlData = request._parsedUrl;
    currentUrlData.protocol = getAppUrlData().protocol;
    currentUrlData.host = request.headers.host;
    currentUrlData.hostname = request.headers.host.split(':')[0];
    currentUrlData.port = request.headers.host.split(':')[1] || null;
    currentUrlData.href = undefined;
    return currentUrlData
  }

  Router.map(function () {
    this.route('any', {
      where: 'server',
      path: '/*',
      action: function () {
        var currentUrlData = getUrlData(this.request);
        var appUrlData = getAppUrlData();
        var redirectUrl;

        // only run this code on a online server
        if (Meteor.settings.public.environment !== 'local') {

          // make use of the correct domain (canonical)
          if (redirectUrl = useCanonicalDomain(currentUrlData, appUrlData))
            return redirect(redirectUrl, this.response);

          // redirect to the default city if not present in subdomain
          if (redirectUrl = redirectToCity(currentUrlData, appUrlData))
            return redirect(redirectUrl, this.response);
        }

        // otherwise default meteor behaviour
        this.next();
      }
    });
  });
}<commit_msg>fix: cleaning vars<commit_after>if (Meteor.isClient) {

  // ROUTES

  Router.map(function () {

    this.route('frontpage', { path: '/', template: 'frontpage' });

    this.route('hackers', { path: '/hackers', template: 'hackers' });

    this.route('places', { path: '/places', template: 'places',
      load: function() {
        Session.set('absoluteHeader', true);
        Session.set('inversedHeader', true);
      },
      unload: function() {
        Session.set('absoluteHeader', false);
        Session.set('inversedHeader', false);
      }
    });

    this.route('hacker', { path: '/:localRankHash', template: 'hacker',
      before: function() {
        var city = 'lyon';
        var localRankHash = this.params.localRankHash;
        var localRank = bitHashInv(localRankHash);
        var hacker = Meteor.users.findOne({city: city, localRank: localRank});

        if (!hacker)
          return this.redirect('frontpage');

        Session.set('hackerId', hacker._id);
        Session.set('hacker', hacker);
      },
      unload: function() {
        Session.set('hackerId', null);
        Session.set('hacker', null);
      }
    });

    this.route('invite', { path: /^\/\+\/(.*)/, template: 'frontpage',
      before: function() {
        var phrase = bitHashInv(this.params[0]);
        Session.set('invitationPhrase', phrase);
        this.redirect('frontpage');
      }
    });

  });

  /* resolve url helpers */

  Router.routes['invite'].url = function(params) {
    return Meteor.absoluteUrl('+/' + params.phrase);
  }

  /* custom functionality */

  // XXX in iron-router you can't call this.redirect() if you want
  // that the unload event must be triggered. Instead you must use
  // Router.go() and then stopping the current route with this.stop()

  // check if there are duplicate accounts, if so request for merge
  var checkDuplicateAccounts = function() {
    if (Session.get('requestMergeDuplicateAccount')) {
      this.render('requestMergeDuplicateAccount');
      this.stop();
    }
  }

  // when login is required, render the frontpage
  var loginRequired = function() {

    if (!isLoggedIn() && Meteor.userId())
      return this.stop(); // login in progress, wait!

    if (!isLoggedIn()) {

      // hold current route so we can redirect after login
      var url = location.pathname + location.search + location.hash;
      Session.set('redirectUrl', url);

      // redirect to frontpage so that the user can login
      Router.go('frontpage');
      this.stop();
    }

  }

  // make sure that user is allowed to enter the site
  var allowedAccess = function() {
    if(Meteor.user() && !Meteor.user().allowAccess) {
      Router.go('hacker', Meteor.user());
      this.stop();
    }
  }

  // check for duplicate accounts, if so request for merge
  Router.before(checkDuplicateAccounts, {except: ['frontpage', 'invite']});

  // make sure the user is logged in, except for the pages below
  Router.before(loginRequired, {except: ['frontpage', 'invite']});

  // make sure that user is allowed to enter the site
  Router.before(allowedAccess, {except: ['invite', 'hacker']})

  // global router configuration
  Router.configure({
    autoRender: false
  });

}

if (Meteor.isServer) {

  // SERVER SIDE routes

  var url = Npm.require('url');

  // make use of the correct domain (canonical)
  // redirect when not at the same hostname as specified in environment variable "ROOT_URL"
  var useCanonicalDomain = function(currentUrlData, appUrlData) {
    if (currentUrlData.host.indexOf(appUrlData.host) === -1)
      return url.format(_.defaults({host: appUrlData.host}, currentUrlData));
    return null;
  }

  // redirect to city if not present in subdomain
  var redirectToCity = function(currentUrlData, appUrlData) {

    // all cities on this app
    var allowedCities = ['lyon'];

    // city where to redirect to
    var defaultCity = 'lyon';

    // current subdomain
    var subdomain = currentUrlData.host.replace(appUrlData.host, '').split('.')[0];

    // redirect if no valid city is specified in the subdomain
    if (!_.contains(allowedCities, subdomain))
      return url.format(_.defaults({host: defaultCity+'.'+appUrlData.host}, currentUrlData));

    return null;
  }

  var redirect = function(url, res) {
    res.writeHead(302, {'Location': url});
    res.end();
  }

  // parse url specified in environment ROOT_URL
  var getAppUrlData = function() {
    return url.parse(Meteor.absoluteUrl());
  }

  // parse current request url
  // XXX: not all properties can be resolved
  var getUrlData = function(request) {
    var currentUrlData = request._parsedUrl;
    currentUrlData.protocol = getAppUrlData().protocol;
    currentUrlData.host = request.headers.host;
    currentUrlData.hostname = request.headers.host.split(':')[0];
    currentUrlData.port = request.headers.host.split(':')[1] || null;
    currentUrlData.href = undefined;
    return currentUrlData
  }

  Router.map(function () {
    this.route('any', {
      where: 'server',
      path: '/*',
      action: function () {
        var currentUrlData = getUrlData(this.request);
        var appUrlData = getAppUrlData();
        var redirectUrl;

        // only run this code on a online server
        if (Meteor.settings.public.environment !== 'local') {

          // make use of the correct domain (canonical)
          if (redirectUrl = useCanonicalDomain(currentUrlData, appUrlData))
            return redirect(redirectUrl, this.response);

          // redirect to the default city if not present in subdomain
          if (redirectUrl = redirectToCity(currentUrlData, appUrlData))
            return redirect(redirectUrl, this.response);
        }

        // otherwise default meteor behaviour
        this.next();
      }
    });
  });
}<|endoftext|>


<commit_before>function appendSVG(document) {

    /*
     'Normal':[1,0,0,0,0, 0,1,0,0,0, 0,0,1,0,0, 0,0,0,1,0, 0,0,0,0,1],
     'Protanopia':[0.567,0.433,0,0,0, 0.558,0.442,0,0,0, 0,0.242,0.758,0,0, 0,0,0,1,0, 0,0,0,0,1],
     'Protanomaly':[0.817,0.183,0,0,0, 0.333,0.667,0,0,0, 0,0.125,0.875,0,0, 0,0,0,1,0, 0,0,0,0,1],
     'Deuteranopia':[0.625,0.375,0,0,0, 0.7,0.3,0,0,0, 0,0.3,0.7,0,0, 0,0,0,1,0, 0,0,0,0,1],
     'Deuteranomaly':[0.8,0.2,0,0,0, 0.258,0.742,0,0,0, 0,0.142,0.858,0,0, 0,0,0,1,0, 0,0,0,0,1],
     'Tritanopia':[0.95,0.05,0,0,0, 0,0.433,0.567,0,0, 0,0.475,0.525,0,0, 0,0,0,1,0, 0,0,0,0,1],
     'Tritanomaly':[0.967,0.033,0,0,0, 0,0.733,0.267,0,0, 0,0.183,0.817,0,0, 0,0,0,1,0, 0,0,0,0,1],
     'Achromatopsia':[0.299,0.587,0.114,0,0, 0.299,0.587,0.114,0,0, 0.299,0.587,0.114,0,0, 0,0,0,1,0, 0,0,0,0,1],
     'Achromatomaly':[0.618,0.320,0.062,0,0, 0.163,0.775,0.062,0,0, 0.163,0.320,0.516,0,0,0,0,0,1,0,0,0,0,0]
     */

    var svg = '<svg id="colorBlindSVG" version="1.1" xmlns="http://www.w3.org/2000/svg" baseProfile="full"> <filter id="protanopia"> <feColorMatrix type="matrix" values="0.567, 0.433, 0, 0, 0, 0.558, 0.442, 0, 0, 0, 0, 0.242, 0.758, 0, 0, 0, 0, 0, 1, 0" in="SourceGraphic" /> </filter> <filter id="protanomaly"> <feColorMatrix type="matrix" values="0.817,0.183,0,0,0 0.333,0.667,0,0,0 0,0.125,0.875,0,0 0,0,0,1,0" in="SourceGraphic" /> </filter> <filter id="deuteranopia"> <feColorMatrix type="matrix" values="0.625,0.375,0,0,0 0.7,0.3,0,0,0 0,0.3,0.7,0,0 0,0,0,1,0" in="SourceGraphic" /> </filter> <filter id="deuteranomaly"> <feColorMatrix type="matrix" values="0.8,0.2,0,0,0 0.258,0.742,0,0,0 0,0.142,0.858,0,0 0,0,0,1,0" in="SourceGraphic" /> </filter> <filter id="tritanopia"> <feColorMatrix type="matrix" values="0.95,0.05,0,0,0 0,0.433,0.567,0,0 0,0.475,0.525,0,0 0,0,0,1,0" in="SourceGraphic" /> </filter> <filter id="tritanomaly"> <feColorMatrix type="matrix" values="0.967,0.033,0,0,0 0,0.733,0.267,0,0 0,0.183,0.817,0,0 0,0,0,1,0" in="SourceGraphic" /> </filter> <filter id="achromatopsia"> <feColorMatrix type="matrix" values="0.299,0.587,0.114,0,0 0.299,0.587,0.114,0,0 0.299,0.587,0.114,0,0 0,0,0,1,0" in="SourceGraphic" /> </filter> <filter id="achromatomaly"> <feColorMatrix type="matrix" values="0.618,0.320,0.062,0,0 0.163,0.775,0.062,0,0 0.163,0.320,0.516,0,0 0,0,0,1,0" in="SourceGraphic" /> </filter> </svg>';

    var blockColorblindContent = document.getElementById("blockColorblindContent");
    if (blockColorblindContent !== undefined && blockColorblindContent !== null) {
        blockColorblindContent.parentNode.removeChild(blockColorblindContent);
    }

    var iDiv = document.createElement('div');
    iDiv.id = 'blockColorblindContent';
    iDiv.innerHTML = svg;
    document.getElementsByTagName('body')[0].appendChild(iDiv);
}

function changeColors(type) {
    appendSVG(document);
    revertColors(document);

    var css = 'html {' +
        'filter: url(#' + type + '); -webkit-filter: url(#' + type + '); -moz-filter: url(#' + type + '); -o-filter: url(#' + type + '); -ms-filter: url(#' + type + '); ' +
        '}';

    applyingStyle(document, css);
}

function revertColors(document) {
    var css = 'html { -webkit-filter: none; -moz-filter: none; -o-filter: none; -ms-filter: none; }';
    applyingStyle(document, css);
}

function applyingStyle(document, css) {

    var head = document.getElementsByTagName('head')[0],
        style = document.createElement('style');

    style.type = 'text/css';
    if (style.styleSheet) {
        style.styleSheet.cssText = css;
    } else {
        style.appendChild(document.createTextNode(css));
    }
    head.appendChild(style);
}

function execute() {
    chrome.storage.sync.get('colorblindingValue', function (obj) {
        if (obj.colorblindingValue === null || obj.colorblindingValue === undefined) {
            obj.colorblindingValue = "normal";
            chrome.storage.sync.set({'colorblindingValue': obj.colorblindingValue});
        }
        changeColors(obj.colorblindingValue);
    });
}<commit_msg>Fix issue "blockColorblindContent" is showing and taking up space on some websites #5<commit_after>function appendSVG(document) {

    /*
     'Normal':[1,0,0,0,0, 0,1,0,0,0, 0,0,1,0,0, 0,0,0,1,0, 0,0,0,0,1],
     'Protanopia':[0.567,0.433,0,0,0, 0.558,0.442,0,0,0, 0,0.242,0.758,0,0, 0,0,0,1,0, 0,0,0,0,1],
     'Protanomaly':[0.817,0.183,0,0,0, 0.333,0.667,0,0,0, 0,0.125,0.875,0,0, 0,0,0,1,0, 0,0,0,0,1],
     'Deuteranopia':[0.625,0.375,0,0,0, 0.7,0.3,0,0,0, 0,0.3,0.7,0,0, 0,0,0,1,0, 0,0,0,0,1],
     'Deuteranomaly':[0.8,0.2,0,0,0, 0.258,0.742,0,0,0, 0,0.142,0.858,0,0, 0,0,0,1,0, 0,0,0,0,1],
     'Tritanopia':[0.95,0.05,0,0,0, 0,0.433,0.567,0,0, 0,0.475,0.525,0,0, 0,0,0,1,0, 0,0,0,0,1],
     'Tritanomaly':[0.967,0.033,0,0,0, 0,0.733,0.267,0,0, 0,0.183,0.817,0,0, 0,0,0,1,0, 0,0,0,0,1],
     'Achromatopsia':[0.299,0.587,0.114,0,0, 0.299,0.587,0.114,0,0, 0.299,0.587,0.114,0,0, 0,0,0,1,0, 0,0,0,0,1],
     'Achromatomaly':[0.618,0.320,0.062,0,0, 0.163,0.775,0.062,0,0, 0.163,0.320,0.516,0,0,0,0,0,1,0,0,0,0,0]
     */

    var svg = '<svg id="colorBlindSVG" version="1.1" xmlns="http://www.w3.org/2000/svg" baseProfile="full"> <filter id="protanopia"> <feColorMatrix type="matrix" values="0.567, 0.433, 0, 0, 0, 0.558, 0.442, 0, 0, 0, 0, 0.242, 0.758, 0, 0, 0, 0, 0, 1, 0" in="SourceGraphic" /> </filter> <filter id="protanomaly"> <feColorMatrix type="matrix" values="0.817,0.183,0,0,0 0.333,0.667,0,0,0 0,0.125,0.875,0,0 0,0,0,1,0" in="SourceGraphic" /> </filter> <filter id="deuteranopia"> <feColorMatrix type="matrix" values="0.625,0.375,0,0,0 0.7,0.3,0,0,0 0,0.3,0.7,0,0 0,0,0,1,0" in="SourceGraphic" /> </filter> <filter id="deuteranomaly"> <feColorMatrix type="matrix" values="0.8,0.2,0,0,0 0.258,0.742,0,0,0 0,0.142,0.858,0,0 0,0,0,1,0" in="SourceGraphic" /> </filter> <filter id="tritanopia"> <feColorMatrix type="matrix" values="0.95,0.05,0,0,0 0,0.433,0.567,0,0 0,0.475,0.525,0,0 0,0,0,1,0" in="SourceGraphic" /> </filter> <filter id="tritanomaly"> <feColorMatrix type="matrix" values="0.967,0.033,0,0,0 0,0.733,0.267,0,0 0,0.183,0.817,0,0 0,0,0,1,0" in="SourceGraphic" /> </filter> <filter id="achromatopsia"> <feColorMatrix type="matrix" values="0.299,0.587,0.114,0,0 0.299,0.587,0.114,0,0 0.299,0.587,0.114,0,0 0,0,0,1,0" in="SourceGraphic" /> </filter> <filter id="achromatomaly"> <feColorMatrix type="matrix" values="0.618,0.320,0.062,0,0 0.163,0.775,0.062,0,0 0.163,0.320,0.516,0,0 0,0,0,1,0" in="SourceGraphic" /> </filter> </svg>';

    var blockColorblindContent = document.getElementById("blockColorblindContent");
    if (blockColorblindContent !== undefined && blockColorblindContent !== null) {
        blockColorblindContent.parentNode.removeChild(blockColorblindContent);
    }

    var iDiv = document.createElement('div');
    iDiv.id = 'blockColorblindContent';
    iDiv.innerHTML = svg;
    iDiv.style.display = 'none'; //Fix issue "blockColorblindContent" is showing and taking up space on some websites #5
    document.getElementsByTagName('body')[0].appendChild(iDiv);
}

function changeColors(type) {
    appendSVG(document);
    revertColors(document);

    var css = 'html {' +
        'filter: url(#' + type + '); -webkit-filter: url(#' + type + '); -moz-filter: url(#' + type + '); -o-filter: url(#' + type + '); -ms-filter: url(#' + type + '); ' +
        '}';

    applyingStyle(document, css);
}

function revertColors(document) {
    var css = 'html { -webkit-filter: none; -moz-filter: none; -o-filter: none; -ms-filter: none; }';
    applyingStyle(document, css);
}

function applyingStyle(document, css) {

    var head = document.getElementsByTagName('head')[0],
        style = document.createElement('style');

    style.type = 'text/css';
    if (style.styleSheet) {
        style.styleSheet.cssText = css;
    } else {
        style.appendChild(document.createTextNode(css));
    }
    head.appendChild(style);
}

function execute() {
    chrome.storage.sync.get('colorblindingValue', function (obj) {
        if (obj.colorblindingValue === null || obj.colorblindingValue === undefined) {
            obj.colorblindingValue = "normal";
            chrome.storage.sync.set({'colorblindingValue': obj.colorblindingValue});
        }
        changeColors(obj.colorblindingValue);
    });
}
<|endoftext|>


<commit_before>/*
Everything related to changing the graph display, without interaction with
other parts of the system.
*/

// A way to order the connection by creation age
var connection_counter = 0;

function create_paper() {
  return new joint.dia.Paper({
    el: $('#paper'),
    model: graph,
    width: "100%",
    height: "100%",
    gridSize: 10,
    snapLinks: true,
    defaultLink: function (elementView, magnet) {
      connection_counter++;
      return new joint.shapes.incredible.Link({
        counter : connection_counter
      });
    },

    validateConnection: function (vs, ms, vt, mt, e, vl) {
      //console.log(vs,ms,vt,mt,e,vl);

      if (ms && mt && ms.getAttribute('direction') == mt.getAttribute('direction')) {
        return false;
      }

      return true;
    }
  });
}

/**
 * Rescales the paper.
 *
 * Parameters:
 *  - amount: The ratio between the rescaled and current paper
 *            (e.g. '2.0' makes everything appear two times bigger)
 *  - x, y: Coordinates of the point that shall remain stable,
 *          given by pixel coordinates relative to the top left corner of the viewport.
 */
function paper_scale(amount, x, y) {
  var scale = V(paper.viewport).scale().sx;
  var newScale = scale*amount;
  paper.scale(newScale, newScale);

  var ox = paper.options.origin.x;
  var oy = paper.options.origin.y;
  var dx = (newScale - scale)/scale * (x - ox);
  var dy = (newScale - scale)/scale * (y - oy);
  paper.setOrigin(ox - dx, oy - dy);
}

function selectNothing() {
  $.each(graph.getElements(), function (i, el) {
    el.set('selected', false);
  });
}

$(function() {
  paper.on('cell:pointerdown', function (cellView, evt, x, y) {
    var cell = cellView.model;

    if (evt.shiftKey) { return; }

    // Check if this was a click on a delete element
    // This assumes that all visible elements of the delete SVG are direct childs
    // of a <g> element with event="remove" set
    var targetParentEvent = evt.target.parentNode.getAttribute('event');
    if (targetParentEvent && targetParentEvent == "remove" ) {
      cell.remove();
      return;
    }
  });

  paper.on('blank:pointerdown', function (e, x, y) {
    if (e.shiftKey) { return; }

    var pos0 = {x: e.pageX, y: e.pageY};

    document.onmousemove = function(e){
      var pos1 = {x: e.pageX, y: e.pageY};
      paper.setOrigin(
        paper.options.origin.x + pos1.x - pos0.x,
        paper.options.origin.y + pos1.y - pos0.y
      );
      pos0 = pos1;
    };

    document.onmouseup = function(e){
      document.onmousemove = null;
      document.onmouseup = null;
    };
    e.stopPropagation();
  });

  paper.on('blank:pointerclick', function (evt, x, y) {
    if (evt.shiftKey) {
      // ignore
    } else {
      selectNothing();
    }
  });

  paper.on('cell:pointerclick', function (cellView, evt, x, y) {
    var cell = cellView.model;

    if (evt.shiftKey) {
      cell.set('selected', ! cell.get('selected'));
    } else {
      // Deselect everything
      $.each(graph.getElements(), function (i, el) {
        el.set('selected', false);
      });

      if (cell.get('annotation')) {
        var done = false;
        var prmpt = i18n.t('Input proposition');
        var val = cell.get('annotation');
        while (!done) {
          val = window.prompt(prmpt, val);
          if (val) {
            var prettyPrinted = incredibleFormatTerm(val);
            if (prettyPrinted) {
              done = true;
              cell.set('annotation', prettyPrinted);
            } else {
              prmpt = i18n.t('Could not parse, please try again:');
            }
          } else {
            done = true;
          }
        }
      }
    }
  });

  paper.on('element:schieblehre',function(cellView, direction, dx, dy) {
    var basewidth0 = cellView.model.get('schieblehrebasewidth');
    if (basewidth0 === undefined) { basewidth0 = 40; }
    var basewidth1 = basewidth0;
    if (direction == "resize-left") {
      basewidth1 -= dx;
    } else if (direction == "resize-right") {
      basewidth1 += dx;
    } else {
      throw Error("element:schieblehre: Unknown direction " + direction);
    }
    cellView.model.set('schieblehrebasewidth', basewidth1);
    var width0 = cellView.model.get('schieblehrewidth');
    if (width0 === undefined) { width0 = 40; }
    var width1 = Math.max(0, g.snapToGrid(basewidth1, paper.options.gridSize));
    if (width0 != width1) {
      cellView.model.set('schieblehrewidth', width1);
      // Move center accordingly
      if (direction == "resize-left") {
        cellView.model.translate(width0 - width1, 0, {ui: true});
      }
    }
  });

  graph.on('change:position', function (model, pos1, options) {
    if (options.derivedMove) { return; }

    if (model.get('selected')) {
      var dx = options.tx;
      var dy = options.ty;
      if (dx === 0 && dy === 0) { return; }

      $.each(graph.getElements(), function (i, el) {
        if (el.get('selected') && el != model) {
          el.translate(dx,dy, { derivedMove : true });
        }
      });
      $.each(graph.getLinks(), function (i, conn) {
	var source = conn.get('source');
	var target = conn.get('target');
	var connected = source.id || target.id;
	var sourceSelected = source.id && graph.getCell(source.id).get('selected');
	var targetSelected = target.id && graph.getCell(target.id).get('selected');
	if (connected && (!source.id || sourceSelected) && (!target.id || targetSelected)) {
          conn.translate(dx,dy, { derivedMove : true });
	}
      });
    }
  });

  $("#savesvg").on('click', function (){
    // Connect all SVG data that is possibly relevant
    var rules = [];
    $.each(document.styleSheets, function(sheetIndex, sheet) {
      if (sheet.ownerNode.dataset.css) {
        $.each(sheet.cssRules || sheet.rules, function(ruleIndex, rule) {
            rules.push(rule.cssText);
        });
      }
    });
    var bb = paper.getContentBBox();
    var css = rules.join("\n");
    var svg = $("#paper svg")
      .clone()
      .prepend($("<style type='text/css'>").text(css))
      .attr({width: bb.x + bb.width + 10, height: bb.y + bb.height + 10})
      .wrap('<div>')
      .parent()
      .html();
    saveAs(new Blob([svg], {type:"application/svg+xml"}), "incredible-proof.svg");
  });

  $("#paper").on('wheel', function (evt) {
    var up = evt.originalEvent.deltaY < 0;
    paper_scale(up ? 1.1 : 1/1.1, evt.originalEvent.offsetX, evt.originalEvent.offsetY);
  });

  $("#zoom-in").on('click', function (){
    paper_scale(1.2, $("#paper").innerWidth() / 2, $("#paper").innerHeight() / 2);
  });

  $("#zoom-out").on('click', function (){
    paper_scale(1/1.2, $("#paper").innerWidth() / 2, $("#paper").innerHeight() / 2);
   });

  $("#zoom-orig").on('click', function (){
    paper_scale(1/V(paper.viewport).scale().sx, $("#paper").innerWidth() / 2, $("#paper").innerHeight() / 2);
  });

  $("#zoom-fit").on('click', function (){
    var padding = 15;
    var cbb = paper.getContentBBox();
    if (cbb.width !== 0 && cbb.height !== 0) {
      // Only rescale and pan if we have content.
      var scale = V(paper.viewport).scale().sx;
      var w = $("#paper").innerWidth();
      var h = $("#paper").innerHeight();
      scale *= Math.min((w - padding) / cbb.width,
                       (h - padding) / cbb.height);
      paper.scale(scale, scale);

      cbb = paper.getContentBBox();
      var ox = paper.options.origin.x + (w - cbb.width) / 2 - cbb.x;
      var oy = paper.options.origin.y + (h - cbb.height) / 2 - cbb.y;
      paper.setOrigin(ox, oy);
    }
  });

});
<commit_msg>Avoid   in SVG output<commit_after>/*
Everything related to changing the graph display, without interaction with
other parts of the system.
*/

// A way to order the connection by creation age
var connection_counter = 0;

function create_paper() {
  return new joint.dia.Paper({
    el: $('#paper'),
    model: graph,
    width: "100%",
    height: "100%",
    gridSize: 10,
    snapLinks: true,
    defaultLink: function (elementView, magnet) {
      connection_counter++;
      return new joint.shapes.incredible.Link({
        counter : connection_counter
      });
    },

    validateConnection: function (vs, ms, vt, mt, e, vl) {
      //console.log(vs,ms,vt,mt,e,vl);

      if (ms && mt && ms.getAttribute('direction') == mt.getAttribute('direction')) {
        return false;
      }

      return true;
    }
  });
}

/**
 * Rescales the paper.
 *
 * Parameters:
 *  - amount: The ratio between the rescaled and current paper
 *            (e.g. '2.0' makes everything appear two times bigger)
 *  - x, y: Coordinates of the point that shall remain stable,
 *          given by pixel coordinates relative to the top left corner of the viewport.
 */
function paper_scale(amount, x, y) {
  var scale = V(paper.viewport).scale().sx;
  var newScale = scale*amount;
  paper.scale(newScale, newScale);

  var ox = paper.options.origin.x;
  var oy = paper.options.origin.y;
  var dx = (newScale - scale)/scale * (x - ox);
  var dy = (newScale - scale)/scale * (y - oy);
  paper.setOrigin(ox - dx, oy - dy);
}

function selectNothing() {
  $.each(graph.getElements(), function (i, el) {
    el.set('selected', false);
  });
}

$(function() {
  paper.on('cell:pointerdown', function (cellView, evt, x, y) {
    var cell = cellView.model;

    if (evt.shiftKey) { return; }

    // Check if this was a click on a delete element
    // This assumes that all visible elements of the delete SVG are direct childs
    // of a <g> element with event="remove" set
    var targetParentEvent = evt.target.parentNode.getAttribute('event');
    if (targetParentEvent && targetParentEvent == "remove" ) {
      cell.remove();
      return;
    }
  });

  paper.on('blank:pointerdown', function (e, x, y) {
    if (e.shiftKey) { return; }

    var pos0 = {x: e.pageX, y: e.pageY};

    document.onmousemove = function(e){
      var pos1 = {x: e.pageX, y: e.pageY};
      paper.setOrigin(
        paper.options.origin.x + pos1.x - pos0.x,
        paper.options.origin.y + pos1.y - pos0.y
      );
      pos0 = pos1;
    };

    document.onmouseup = function(e){
      document.onmousemove = null;
      document.onmouseup = null;
    };
    e.stopPropagation();
  });

  paper.on('blank:pointerclick', function (evt, x, y) {
    if (evt.shiftKey) {
      // ignore
    } else {
      selectNothing();
    }
  });

  paper.on('cell:pointerclick', function (cellView, evt, x, y) {
    var cell = cellView.model;

    if (evt.shiftKey) {
      cell.set('selected', ! cell.get('selected'));
    } else {
      // Deselect everything
      $.each(graph.getElements(), function (i, el) {
        el.set('selected', false);
      });

      if (cell.get('annotation')) {
        var done = false;
        var prmpt = i18n.t('Input proposition');
        var val = cell.get('annotation');
        while (!done) {
          val = window.prompt(prmpt, val);
          if (val) {
            var prettyPrinted = incredibleFormatTerm(val);
            if (prettyPrinted) {
              done = true;
              cell.set('annotation', prettyPrinted);
            } else {
              prmpt = i18n.t('Could not parse, please try again:');
            }
          } else {
            done = true;
          }
        }
      }
    }
  });

  paper.on('element:schieblehre',function(cellView, direction, dx, dy) {
    var basewidth0 = cellView.model.get('schieblehrebasewidth');
    if (basewidth0 === undefined) { basewidth0 = 40; }
    var basewidth1 = basewidth0;
    if (direction == "resize-left") {
      basewidth1 -= dx;
    } else if (direction == "resize-right") {
      basewidth1 += dx;
    } else {
      throw Error("element:schieblehre: Unknown direction " + direction);
    }
    cellView.model.set('schieblehrebasewidth', basewidth1);
    var width0 = cellView.model.get('schieblehrewidth');
    if (width0 === undefined) { width0 = 40; }
    var width1 = Math.max(0, g.snapToGrid(basewidth1, paper.options.gridSize));
    if (width0 != width1) {
      cellView.model.set('schieblehrewidth', width1);
      // Move center accordingly
      if (direction == "resize-left") {
        cellView.model.translate(width0 - width1, 0, {ui: true});
      }
    }
  });

  graph.on('change:position', function (model, pos1, options) {
    if (options.derivedMove) { return; }

    if (model.get('selected')) {
      var dx = options.tx;
      var dy = options.ty;
      if (dx === 0 && dy === 0) { return; }

      $.each(graph.getElements(), function (i, el) {
        if (el.get('selected') && el != model) {
          el.translate(dx,dy, { derivedMove : true });
        }
      });
      $.each(graph.getLinks(), function (i, conn) {
	var source = conn.get('source');
	var target = conn.get('target');
	var connected = source.id || target.id;
	var sourceSelected = source.id && graph.getCell(source.id).get('selected');
	var targetSelected = target.id && graph.getCell(target.id).get('selected');
	if (connected && (!source.id || sourceSelected) && (!target.id || targetSelected)) {
          conn.translate(dx,dy, { derivedMove : true });
	}
      });
    }
  });

  $("#savesvg").on('click', function (){
    // Connect all SVG data that is possibly relevant
    var rules = [];
    $.each(document.styleSheets, function(sheetIndex, sheet) {
      if (sheet.ownerNode.dataset.css) {
        $.each(sheet.cssRules || sheet.rules, function(ruleIndex, rule) {
            rules.push(rule.cssText);
        });
      }
    });
    var bb = paper.getContentBBox();
    var css = rules.join("\n");
    var svg = $("#paper svg")
      .clone()
      .prepend($("<style type='text/css'>").text(css))
      .attr({width: bb.x + bb.width + 10, height: bb.y + bb.height + 10})
      .wrap('<div>')
      .parent()
      .html()
      .replace(/ /g," ");
    saveAs(new Blob([svg], {type:"application/svg+xml"}), "incredible-proof.svg");
  });

  $("#paper").on('wheel', function (evt) {
    var up = evt.originalEvent.deltaY < 0;
    paper_scale(up ? 1.1 : 1/1.1, evt.originalEvent.offsetX, evt.originalEvent.offsetY);
  });

  $("#zoom-in").on('click', function (){
    paper_scale(1.2, $("#paper").innerWidth() / 2, $("#paper").innerHeight() / 2);
  });

  $("#zoom-out").on('click', function (){
    paper_scale(1/1.2, $("#paper").innerWidth() / 2, $("#paper").innerHeight() / 2);
   });

  $("#zoom-orig").on('click', function (){
    paper_scale(1/V(paper.viewport).scale().sx, $("#paper").innerWidth() / 2, $("#paper").innerHeight() / 2);
  });

  $("#zoom-fit").on('click', function (){
    var padding = 15;
    var cbb = paper.getContentBBox();
    if (cbb.width !== 0 && cbb.height !== 0) {
      // Only rescale and pan if we have content.
      var scale = V(paper.viewport).scale().sx;
      var w = $("#paper").innerWidth();
      var h = $("#paper").innerHeight();
      scale *= Math.min((w - padding) / cbb.width,
                       (h - padding) / cbb.height);
      paper.scale(scale, scale);

      cbb = paper.getContentBBox();
      var ox = paper.options.origin.x + (w - cbb.width) / 2 - cbb.x;
      var oy = paper.options.origin.y + (h - cbb.height) / 2 - cbb.y;
      paper.setOrigin(ox, oy);
    }
  });

});
<|endoftext|>


<commit_before>(function() {
  'use strict';
  angular.module('bradypodionApp', ['bp']).config(function(bpConfigProvider, $urlRouterProvider, $stateProvider) {
    bpConfigProvider.setConfig({
      platform: localStorage.getItem('platform') || 'ios'
    });
    $urlRouterProvider.otherwise('/');
    $stateProvider.state('app', {
      url: '/',
      templateUrl: 'table.html',
      data: {
        transition: 'fade',
        title: 'Bradypodion'
      }
    }).state('animations', {
      url: '/animations',
      templateUrl: 'animations/index.html',
      data: {
        up: 'app'
      }
    }).state('cover', {
      url: '/animations/cover',
      templateUrl: 'animations/transition.html',
      data: {
        transition: 'cover'
      }
    }).state('fade', {
      url: '/animations/fade',
      templateUrl: 'animations/transition.html',
      data: {
        transition: 'fade'
      }
    }).state('scale', {
      url: '/animations/scale',
      templateUrl: 'animations/transition.html',
      data: {
        transition: 'scale'
      }
    }).state('slide', {
      url: '/animations/slide',
      templateUrl: 'animations/transition.html',
      data: {
        transition: 'slide'
      }
    }).state('directives', {
      url: '/directives',
      templateUrl: 'directives/index.html',
      data: {
        up: 'app'
      }
    }).state('button', {
      url: '/directives/button',
      templateUrl: 'directives/button.html'
    }).state('cell', {
      url: '/directives/cell',
      templateUrl: 'directives/cell.html'
    }).state('detail-disclosure', {
      url: '/directives/detail-disclosure',
      templateUrl: 'directives/detail-disclosure.html'
    }).state('detail-disclosure-site', {
      url: '/directives/detail-disclosure/site',
      templateUrl: 'directives/detail-disclosure/site.html',
      data: {
        modal: true
      }
    }).state('detail-disclosure-detail', {
      url: '/directives/detail-disclosure/detail',
      templateUrl: 'directives/detail-disclosure/detail.html'
    }).state('icon', {
      url: '/directives/icon',
      templateUrl: 'directives/icon.html'
    }).state('iscroll', {
      url: '/directives/iscroll',
      templateUrl: 'directives/iscroll.html',
      controller: 'DemoDataCtrl',
      data: {
        title: 'iScroll'
      }
    }).state('iscroll-sticky', {
      url: '/directives/iscroll/sticky',
      templateUrl: 'directives/iscroll/sticky.html',
      data: {
        title: 'iScroll-sticky'
      }
    }).state('navbar', {
      url: '/directives/navbar',
      templateUrl: 'directives/navbar.html'
    }).state('scroll', {
      url: '/directives/scroll',
      templateUrl: 'directives/scroll.html',
      controller: 'DemoDataCtrl'
    }).state('scroll-sticky', {
      url: '/directives/scroll/sticky',
      templateUrl: 'directives/scroll/sticky.html'
    }).state('search', {
      url: '/directives/search',
      templateUrl: 'directives/search.html'
    }).state('tabbar', {
      url: '/directives/tabbar',
      templateUrl: 'directives/tabbar.html'
    }).state('first', {
      parent: 'tabbar',
      url: '/directives/tabbar',
      templateUrl: 'directives/tabbar/screen.html',
      controller: 'DemoTabbarCtrl',
      data: {
        transition: 'fade'
      }
    }).state('second', {
      parent: 'tabbar',
      url: '/directives/tabbar/second',
      templateUrl: 'directives/tabbar/screen.html',
      controller: 'DemoTabbarCtrl',
      data: {
        transition: 'fade'
      }
    }).state('third', {
      parent: 'tabbar',
      url: '/directives/tabbar/third',
      templateUrl: 'directives/tabbar/screen.html',
      controller: 'DemoTabbarCtrl',
      data: {
        transition: 'fade'
      }
    }).state('fourth', {
      parent: 'tabbar',
      url: '/directives/tabbar/fourth',
      templateUrl: 'directives/tabbar/screen.html',
      controller: 'DemoTabbarCtrl',
      data: {
        transition: 'fade'
      }
    }).state('fifth', {
      parent: 'tabbar',
      url: '/directives/tabbar/fifth',
      templateUrl: 'directives/tabbar/screen.html',
      controller: 'DemoTabbarCtrl',
      data: {
        transition: 'fade'
      }
    }).state('table-header', {
      url: '/directives/table-header',
      templateUrl: 'directives/table-header.html'
    }).state('table', {
      url: '/directives/table',
      templateUrl: 'directives/table.html'
    }).state('table-grouped', {
      url: '/directives/table/grouped',
      templateUrl: 'directives/table/grouped.html',
      controller: 'DemoDataCtrl'
    }).state('table-plain', {
      url: '/directives/table/plain',
      templateUrl: 'directives/table/plain.html',
      controller: 'DemoDataCtrl'
    }).state('table-section', {
      url: '/directives/table/section',
      templateUrl: 'directives/table/section.html',
      controller: 'DemoDataCtrl'
    }).state('tap', {
      url: '/directives/tap',
      templateUrl: 'directives/tap.html'
    }).state('toolbar', {
      url: '/directives/toolbar',
      templateUrl: 'directives/toolbar.html'
    });
  }).factory('dummyFriends', function() {
    return [
      {
        name: 'Sandy',
        phone: '555-1276'
      }, {
        name: 'Kirsten',
        phone: '800-BIG-MARY'
      }, {
        name: 'Jimmy',
        phone: '555-4321'
      }, {
        name: 'Julie',
        phone: '555-5678'
      }, {
        name: 'Hailey',
        phone: '555-8765'
      }
    ];
  }).directive('switchTheme', function(bpConfig) {
    return function(scope, element, attrs) {
      var platforms;
      platforms = ['ios', 'android'];
      element.addClass(bpConfig.platform === 'ios' ? 'fa-android' : 'fa-apple');
      scope.toggleTheme = function(e) {
        var index;
        index = platforms.indexOf(bpConfig.platform);
        bpConfig.platform = platforms[++index % 2];
        localStorage.setItem('platform', bpConfig.platform);
        location.reload();
      };
    };
  }).directive('demoTapped', function(bpConfig) {
    return function(scope, element, attrs) {
      scope.tapped = function() {
        scope.random = Math.floor(Math.random() * 100);
      };
    };
  }).controller('DemoDataCtrl', function($scope, dummyFriends) {
    var i, _i, _results;
    $scope.friends = dummyFriends;
    $scope.cells = [];
    _results = [];
    for (i = _i = 0; _i < 300; i = ++_i) {
      _results.push($scope.cells.push(i * Math.random()));
    }
    return _results;
  }).controller('DemoTabbarCtrl', function($state, $scope, dummyFriends) {
    $scope.state = $state.current.name;
    $scope.friends = dummyFriends.sort(function() {
      return 0.5 - Math.random();
    });
  });

}).call(this);
<commit_msg>docs(demo): use iscroll module<commit_after>(function() {
  'use strict';
  angular.module('bradypodionApp', ['bp', 'bp.iscroll']).config(function(bpConfigProvider, $urlRouterProvider, $stateProvider) {
    bpConfigProvider.setConfig({
      platform: localStorage.getItem('platform') || 'ios'
    });
    $urlRouterProvider.otherwise('/');
    $stateProvider.state('app', {
      url: '/',
      templateUrl: 'table.html',
      data: {
        transition: 'fade',
        title: 'Bradypodion'
      }
    }).state('animations', {
      url: '/animations',
      templateUrl: 'animations/index.html',
      data: {
        up: 'app'
      }
    }).state('cover', {
      url: '/animations/cover',
      templateUrl: 'animations/transition.html',
      data: {
        transition: 'cover'
      }
    }).state('fade', {
      url: '/animations/fade',
      templateUrl: 'animations/transition.html',
      data: {
        transition: 'fade'
      }
    }).state('scale', {
      url: '/animations/scale',
      templateUrl: 'animations/transition.html',
      data: {
        transition: 'scale'
      }
    }).state('slide', {
      url: '/animations/slide',
      templateUrl: 'animations/transition.html',
      data: {
        transition: 'slide'
      }
    }).state('directives', {
      url: '/directives',
      templateUrl: 'directives/index.html',
      data: {
        up: 'app'
      }
    }).state('button', {
      url: '/directives/button',
      templateUrl: 'directives/button.html'
    }).state('cell', {
      url: '/directives/cell',
      templateUrl: 'directives/cell.html'
    }).state('detail-disclosure', {
      url: '/directives/detail-disclosure',
      templateUrl: 'directives/detail-disclosure.html'
    }).state('detail-disclosure-site', {
      url: '/directives/detail-disclosure/site',
      templateUrl: 'directives/detail-disclosure/site.html',
      data: {
        modal: true
      }
    }).state('detail-disclosure-detail', {
      url: '/directives/detail-disclosure/detail',
      templateUrl: 'directives/detail-disclosure/detail.html'
    }).state('icon', {
      url: '/directives/icon',
      templateUrl: 'directives/icon.html'
    }).state('iscroll', {
      url: '/directives/iscroll',
      templateUrl: 'directives/iscroll.html',
      controller: 'DemoDataCtrl',
      data: {
        title: 'iScroll'
      }
    }).state('iscroll-sticky', {
      url: '/directives/iscroll/sticky',
      templateUrl: 'directives/iscroll/sticky.html',
      data: {
        title: 'iScroll-sticky'
      }
    }).state('navbar', {
      url: '/directives/navbar',
      templateUrl: 'directives/navbar.html'
    }).state('scroll', {
      url: '/directives/scroll',
      templateUrl: 'directives/scroll.html',
      controller: 'DemoDataCtrl'
    }).state('scroll-sticky', {
      url: '/directives/scroll/sticky',
      templateUrl: 'directives/scroll/sticky.html'
    }).state('search', {
      url: '/directives/search',
      templateUrl: 'directives/search.html'
    }).state('tabbar', {
      url: '/directives/tabbar',
      templateUrl: 'directives/tabbar.html'
    }).state('first', {
      parent: 'tabbar',
      url: '/directives/tabbar',
      templateUrl: 'directives/tabbar/screen.html',
      controller: 'DemoTabbarCtrl',
      data: {
        transition: 'fade'
      }
    }).state('second', {
      parent: 'tabbar',
      url: '/directives/tabbar/second',
      templateUrl: 'directives/tabbar/screen.html',
      controller: 'DemoTabbarCtrl',
      data: {
        transition: 'fade'
      }
    }).state('third', {
      parent: 'tabbar',
      url: '/directives/tabbar/third',
      templateUrl: 'directives/tabbar/screen.html',
      controller: 'DemoTabbarCtrl',
      data: {
        transition: 'fade'
      }
    }).state('fourth', {
      parent: 'tabbar',
      url: '/directives/tabbar/fourth',
      templateUrl: 'directives/tabbar/screen.html',
      controller: 'DemoTabbarCtrl',
      data: {
        transition: 'fade'
      }
    }).state('fifth', {
      parent: 'tabbar',
      url: '/directives/tabbar/fifth',
      templateUrl: 'directives/tabbar/screen.html',
      controller: 'DemoTabbarCtrl',
      data: {
        transition: 'fade'
      }
    }).state('table-header', {
      url: '/directives/table-header',
      templateUrl: 'directives/table-header.html'
    }).state('table', {
      url: '/directives/table',
      templateUrl: 'directives/table.html'
    }).state('table-grouped', {
      url: '/directives/table/grouped',
      templateUrl: 'directives/table/grouped.html',
      controller: 'DemoDataCtrl'
    }).state('table-plain', {
      url: '/directives/table/plain',
      templateUrl: 'directives/table/plain.html',
      controller: 'DemoDataCtrl'
    }).state('table-section', {
      url: '/directives/table/section',
      templateUrl: 'directives/table/section.html',
      controller: 'DemoDataCtrl'
    }).state('tap', {
      url: '/directives/tap',
      templateUrl: 'directives/tap.html'
    }).state('toolbar', {
      url: '/directives/toolbar',
      templateUrl: 'directives/toolbar.html'
    });
  }).factory('dummyFriends', function() {
    return [
      {
        name: 'Sandy',
        phone: '555-1276'
      }, {
        name: 'Kirsten',
        phone: '800-BIG-MARY'
      }, {
        name: 'Jimmy',
        phone: '555-4321'
      }, {
        name: 'Julie',
        phone: '555-5678'
      }, {
        name: 'Hailey',
        phone: '555-8765'
      }
    ];
  }).directive('switchTheme', function(bpConfig) {
    return function(scope, element, attrs) {
      var platforms;
      platforms = ['ios', 'android'];
      element.addClass(bpConfig.platform === 'ios' ? 'fa-android' : 'fa-apple');
      scope.toggleTheme = function(e) {
        var index;
        index = platforms.indexOf(bpConfig.platform);
        bpConfig.platform = platforms[++index % 2];
        localStorage.setItem('platform', bpConfig.platform);
        location.reload();
      };
    };
  }).directive('demoTapped', function(bpConfig) {
    return function(scope, element, attrs) {
      scope.tapped = function() {
        scope.random = Math.floor(Math.random() * 100);
      };
    };
  }).controller('DemoDataCtrl', function($scope, dummyFriends) {
    var i, _i, _results;
    $scope.friends = dummyFriends;
    $scope.cells = [];
    _results = [];
    for (i = _i = 0; _i < 300; i = ++_i) {
      _results.push($scope.cells.push(i * Math.random()));
    }
    return _results;
  }).controller('DemoTabbarCtrl', function($state, $scope, dummyFriends) {
    $scope.state = $state.current.name;
    $scope.friends = dummyFriends.sort(function() {
      return 0.5 - Math.random();
    });
  });

}).call(this);
<|endoftext|>


<commit_before>var pg = require('pg');
var geojson = require('../helpers/geojson');
var jsonp = require('../helpers/jsonp');
module.exports.controller = function(app) {

  /* enable CORS */
  app.all('*', function(req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'X-Requested-With');
    next();
  });

  app.get('/vector/:schema/:table/:geom/intersect', function(req, res, next) {
    var queryshape = ' {"type": "Point", "coordinates": [' + req.query['lng'] + ',' + req.query['lat'] + '] }';
    var geom = req.params.geom.toLowerCase();
    if ((geom != 'features') && (geom != 'geometry')) {
      res.status(404).send("Resource '" + geom + "' not found");
      return;
    }
    var client = new pg.Client(app.conString);
    var schemaname = req.params.schema;
    var tablename = req.params.table;
    var fullname = schemaname + '.' + tablename;
    client.connect(function(err) {
      var spatialcol = 'wkb_geometry';
      var sql;
      var coll;
      if (geom == 'features') {
        sql = 'select st_asgeojson(st_transform(' + spatialcol + ',4326)) as geojson, * from ' + tablename + ' where ST_INTERSECTS(' + spatialcol + ", ST_SetSRID(ST_GeomFromGeoJSON('" + queryshape + "'),4326));";
        coll = {
          type: 'FeatureCollection',
          features: []
        };
        query = client.query(sql);
      }

      query.on('row', function(result) {
        var props = new Object;
        if (!result) {
          return res.send('No data found');
        }
        else {
          if (geom == 'features') {
            coll.features.push(geojson.getFeatureResult(result, spatialcol));
          } else if (geom == 'geometry') {
            var shape = JSON.parse(result.geojson);
            coll.geometries.push(shape);
          }
        }
      });

      query.on('end', function(err, result) {
        res.setHeader('Content-Type', 'application/json');
        res.send(jsonp.getJsonP(req.query.callback, coll));
      });
    });
  });
  app.get('/neighbor/:schema/:table/:geom/intersect', function(req, res, next) {
    //var queryshape = ' {"type": "Point", "coordinates": [' + req.query['lng'] + ',' + req.query['lat'] + '] }';
    var queryshape = "'SRID=4326;POINT(" + req.query['lng'] +' ' + req.query['lat'] + ")'";
    var geom = req.params.geom.toLowerCase();
    if ((geom != 'features') && (geom != 'geometry')) {
      res.status(404).send("Resource '" + geom + "' not found");
      return;
    }
    var client = new pg.Client(app.conString);
    var schemaname = req.params.schema;
    var tablename = req.params.table;
    var fullname = schemaname + '.' + tablename;
    client.connect(function(err) {
      var spatialcol = 'wkb_geometry';
      var sql;
      var coll;
      if (geom == 'features') {
        sql = 'SELECT ST_AsGeoJson(ST_Transform(b.' + spatialcol + ',4326)) as geojson, * from ' + tablename + ' as a, ' + tablename + ' as b where st_distance(a.' + spatialcol + ',b.' + spatialcol + ')< .5 and ST_INTERSECTS(a.' + spatialcol + ', ST_GeographyFromText(' + queryshape + '));'
        coll = {
          type: 'FeatureCollection',
          features: []
        };
        query = client.query(sql);
      }

      query.on('row', function(result) {
        var props = new Object;
        if (!result) {
          return res.send('No data found');
        }
        else {
          if (geom == 'features') {
            coll.features.push(geojson.getFeatureResult(result, spatialcol));
          } else if (geom == 'geometry') {
            var shape = JSON.parse(result.geojson);
            coll.geometries.push(shape);
          }
        }
      });

      query.on('end', function(err, result) {
        res.setHeader('Content-Type', 'application/json');
        res.send(jsonp.getJsonP(req.query.callback, coll));
      });
    });
  });

    var client = new pg.Client(app.conString);
};
<commit_msg>cleaned up some commented out code, and changed the tolerance for distance in the query<commit_after>var pg = require('pg');
var geojson = require('../helpers/geojson');
var jsonp = require('../helpers/jsonp');
module.exports.controller = function(app) {

  /* enable CORS */
  app.all('*', function(req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'X-Requested-With');
    next();
  });

  app.get('/vector/:schema/:table/:geom/intersect', function(req, res, next) {
    var queryshape = ' {"type": "Point", "coordinates": [' + req.query['lng'] + ',' + req.query['lat'] + '] }';
    var geom = req.params.geom.toLowerCase();
    if ((geom != 'features') && (geom != 'geometry')) {
      res.status(404).send("Resource '" + geom + "' not found");
      return;
    }
    var client = new pg.Client(app.conString);
    var schemaname = req.params.schema;
    var tablename = req.params.table;
    var fullname = schemaname + '.' + tablename;
    client.connect(function(err) {
      var spatialcol = 'wkb_geometry';
      var sql;
      var coll;
      if (geom == 'features') {
        sql = 'select st_asgeojson(st_transform(' + spatialcol + ',4326)) as geojson, * from ' + tablename + ' where ST_INTERSECTS(' + spatialcol + ", ST_SetSRID(ST_GeomFromGeoJSON('" + queryshape + "'),4326));";
        coll = {
          type: 'FeatureCollection',
          features: []
        };
        query = client.query(sql);
      }

      query.on('row', function(result) {
        var props = new Object;
        if (!result) {
          return res.send('No data found');
        }
        else {
          if (geom == 'features') {
            coll.features.push(geojson.getFeatureResult(result, spatialcol));
          } else if (geom == 'geometry') {
            var shape = JSON.parse(result.geojson);
            coll.geometries.push(shape);
          }
        }
      });

      query.on('end', function(err, result) {
        res.setHeader('Content-Type', 'application/json');
        res.send(jsonp.getJsonP(req.query.callback, coll));
      });
    });
  });
  app.get('/neighbor/:schema/:table/:geom/intersect', function(req, res, next) {
    var queryshape = "'SRID=4326;POINT(" + req.query['lng'] +' ' + req.query['lat'] + ")'";
    var geom = req.params.geom.toLowerCase();
    if ((geom != 'features') && (geom != 'geometry')) {
      res.status(404).send("Resource '" + geom + "' not found");
      return;
    }
    var client = new pg.Client(app.conString);
    var schemaname = req.params.schema;
    var tablename = req.params.table;
    var fullname = schemaname + '.' + tablename;
    client.connect(function(err) {
      var spatialcol = 'wkb_geometry';
      var sql;
      var coll;
      if (geom == 'features') {
        sql = 'SELECT ST_AsGeoJson(ST_Transform(b.' + spatialcol + ',4326)) as geojson, * from ' + tablename + ' as a, ' + tablename + ' as b where st_distance(a.' + spatialcol + ',b.' + spatialcol + ')< .00005 and ST_INTERSECTS(a.' + spatialcol + ', ST_GeographyFromText(' + queryshape + '));'
        coll = {
          type: 'FeatureCollection',
          features: []
        };
        query = client.query(sql);
      }

      query.on('row', function(result) {
        var props = new Object;
        if (!result) {
          return res.send('No data found');
        }
        else {
          if (geom == 'features') {
            coll.features.push(geojson.getFeatureResult(result, spatialcol));
          } else if (geom == 'geometry') {
            var shape = JSON.parse(result.geojson);
            coll.geometries.push(shape);
          }
        }
      });

      query.on('end', function(err, result) {
        res.setHeader('Content-Type', 'application/json');
        res.send(jsonp.getJsonP(req.query.callback, coll));
      });
    });
  });

    var client = new pg.Client(app.conString);
};
<|endoftext|>