<commit_before>const fs = require('fs');
const Elm = require('./elm');
const walk = require('walk');
const walker = walk.walk("/tmp", {
    followLinks: false
})
const cp = require('child_process');

var targetFiles = cp.execSync('find ../elm-format-package-repo-stats/repos -name "*.elm" -type f').toString().split('\n').filter(x => x.length > 0);

targetFiles = targetFiles.map(function(f) {
        var stats = fs.statSync(f);
        var fileSizeInBytes = stats["size"];
        return [f, fileSizeInBytes];
    }).filter(x => x)
    .sort((x, y) => x[1] - y[1])
    .slice(0, 1000);

var app = Elm.Main.worker();

var counter = 0;
var failed = 0;
app.ports.parseResponse.subscribe(function(result) {
    counter++;
    if (result[1] === 'Nothing') {
        console.log(counter + ' Analysed file:', result[0], 'in milliseconds ' + result[2]);
        console.log('  > Failed');
        failed++;
    }

    analyseNextFile();
});

function analyseNextFile() {
    const next = targetFiles.shift();
    if (!next) {
        console.log('Failed:', failed);
        console.log('Counter:', counter);
        return;
    }
    if (next[1] > 10 * 1024) {
        console.log("Skip file due to greater than 10kb");
        analyseNextFile();
        return;
    }

    const content = fs.readFileSync(next[0], {
        encoding: 'utf-8'
    }).toString();

    var matched = content.match(/\nport [a-z][a-zA-Z0-9_]*'? =/);
    if (matched) {
      console.log(matched[0]);
      analyseNextFile();
      return;
    }

    app.ports.onFile.send([next[0], content]);
}

analyseNextFile();
<commit_msg>Ignore infix notation for functions (0.17). 45 to go<commit_after>const fs = require('fs');
const Elm = require('./elm');
const walk = require('walk');
const walker = walk.walk("/tmp", {
    followLinks: false
})
const cp = require('child_process');

var targetFiles = cp.execSync('find ../elm-format-package-repo-stats/repos -name "*.elm" -type f').toString().split('\n').filter(x => x.length > 0);

targetFiles = targetFiles.map(function(f) {
        var stats = fs.statSync(f);
        var fileSizeInBytes = stats["size"];
        return [f, fileSizeInBytes];
    }).filter(x => x)
    .sort((x, y) => x[1] - y[1])
    .slice(0, 1000);

var app = Elm.Main.worker();

var counter = 0;
var failed = 0;
app.ports.parseResponse.subscribe(function(result) {
    counter++;
    if (result[1] === 'Nothing') {
        console.log(counter + ' Analysed file:', result[0], 'in milliseconds ' + result[2]);
        console.log('  > Failed');
        failed++;
    }

    analyseNextFile();
});

function analyseNextFile() {
    const next = targetFiles.shift();
    if (!next) {
        console.log('Failed:', failed);
        console.log('Counter:', counter);
        return;
    }
    if (next[1] > 10 * 1024) {
        console.log("Skip file due to greater than 10kb");
        analyseNextFile();
        return;
    }

    const content = fs.readFileSync(next[0], {
        encoding: 'utf-8'
    }).toString();

    var matched =
      content.match(/\nport [a-z][a-zA-Z0-9_]*'? =/) ||
      content.match(/`[a-z][a-zA-Z0-9_]*`/);

    if (matched) {
      analyseNextFile();
      return;
    }

    app.ports.onFile.send([next[0], content]);
}

analyseNextFile();
<|endoftext|>


<commit_before>GS.GameVersion = "build 10 (august 20, 2014)";
GS.BuildMessage = "added in this build: rebindable keys";

GS.GameStates = {
	Dispose: 0,
	PreLoad: 1,
	Loading: 2,
	PostLoad: 3,
	Play: 4,
	Menu: 5,
};

GS.Game = function() {
	GS.Base.call(this);

	GS.Settings.loadSettings();

	this.state = GS.GameStates.PreLoad;
	this.nextState = null;
	this.updated = false;
	this.firstLoad = true;
	this.firstPlay = true;
	this.mapWon = false;
	this.restartedLevel = false;

	this.antialias = false;
	this.clearColor = 0x336699;
	this.cameraFov = GS.Settings.fov;
	this.cameraFar = 1500;

	this.noMenu = false;
	this.useAssetsZip = false;

	if (GS.BuildOverride === true) {
		this.useAssetsZip = true;
	}

	this.showFPS = GS.Settings.showFPS;
	this.showPerformanceDebugMeters = false;
};

GS.Game.prototype = GS.inherit(GS.Base, {
	constructor: GS.Game,

	init: function() {
		GS.DebugUI.init();
		GS.DebugUI.visible = false;

		this.loadingUI = new GS.LoadingUI();
		this.loadingUI.init();

		this.uiManager = new GS.UIManager();
		this.uiManager.init();

		this.soundManager = new GS.SoundManager();
		this.soundManager.init();

		this.musicManager = new GS.MusicManager();
		this.musicManager.init();

		this.initAssetLoader();

		this.keys = {
			Enter: 13,
			Escape: 27,
			Tab: 9,
		};

		GS.Base.prototype.init.call(this);

		this.graphicsManager = new GS.GraphicsManager(this.renderer, this.camera);
		this.graphicsManager.init();
	},

	preLoad: function() {
		this.uiManager.reset();

		this.loadingUI.percentLoaded = 0;
		this.loadingUI.show();

		this.scene = new THREE.Scene();
		this.scene.fog = new THREE.Fog(new THREE.Color().setRGB(0, 0, 0).getHex(), 500, 900);

		if (!this.assetLoader.loaded) {
			this.assetLoader.load();
			this.nextState = GS.GameStates.Loading;
		} else {
			this.nextState = GS.GameStates.PostLoad;
		}
	},

	initAssetLoader: function() {
		var that = this;

		if (this.useAssetsZip) {
			this.assetLoader = new GS.ZipAssetLoader(this.soundManager.ctx);
		} else {
			this.assetLoader = new GS.AssetLoader(this.soundManager.ctx);
		}

		this.assetLoader.init();
		this.assetLoader.addEventListener("progress", function(e) {
			that.loadingUI.updateProgress(e);
		});
		this.assetLoader.addEventListener("load", function(e) {
			that.loadingUI.updateProgress(e);
			that.nextState = GS.GameStates.PostLoad;
		});
	},

	postLoad: function() {
		if (this.firstLoad) {
			this.loadingUI.spinnerOnly = true;
			this.uiManager.initComponents(this.assetLoader.assets);
			this.openMenu();
			this.firstLoad = false;

			if (this.noMenu) {
				this.newGame();
			}
		} else {
			this.initComponents(this.assetLoader.assets);
			this.uiManager.initComponents(this.assetLoader.assets, this.grid);
			this.uiManager.useIngameMenu();

			// GAME.grid.exportMapToOBJ();

			this.nextState = GS.GameStates.Play;
			this.graphicsManager.monochromeEnabled = false;

			if (this.grid.aiManager.script !== undefined && !this.restartedLevel) {
				this.musicManager.playTrack(this.grid.aiManager.script.musicTrack);
			}
			this.restartedLevel = false;

			if (this.firstPlay) {
				this.firstPlay = false;
			}
		}
	},

	play: function() {
		GS.InputHelper.checkPressedKeys();

		if (!GS.InputHelper.keysPressed && GS.InputHelper.isKeyDown(this.keys.Escape)) {
			this.openMenu();
		}

		if (!this.grid.aiManager.mapWon && !GS.InputHelper.keysPressed && GS.InputHelper.isKeyDown(this.keys.Tab)) {
			this.uiManager.automap.visible = !this.uiManager.automap.visible;
			this.uiManager.overrideRedraw = true;
			this.graphicsManager.monochromeEnabled = this.uiManager.automap.visible;
		}

		if (this.grid.player.dead && !GS.InputHelper.keysPressed && GS.InputHelper.isKeyDown(this.keys.Enter)) {
			this.restartLevel();
		}

		if (this.grid.aiManager.mapWon && !GS.InputHelper.keysPressed && GS.InputHelper.isKeyDown(this.keys.Enter)) {
			if (this.grid.aiManager.script.nextMap !== undefined) {
				this.playerPersistencePackage = this.grid.player.getPersistencePackage();
				this.loadLevel(this.grid.aiManager.script.nextMap);
			}
		}

		if (!this.mapWon && this.grid.aiManager.mapWon) {
			this.mapWon = true;
			this.onMapWon();
		}

		if (!this.grid.aiManager.mapWon) {
			this.grid.update();
			TWEEN.update();
		}
		GS.DebugUI.update();

		this.uiManager.update();
	},

	onMapWon: function() {
		this.graphicsManager.monochromeEnabled = false;

		this.trackMapWonEvent();
	},

	trackMapWonEvent: function() {
		/* jshint ignore:start */
		if (ga !== undefined) {
			var mapName = this.grid.map.name;
			var timeSpent = this.grid.aiManager.timeSpent;
			var seconds = Math.floor(Math.floor(timeSpent) / 1000);
			var fps = Math.floor(GS.DebugUI.valueTracking.fps.avg);

			var str = mapName + " " + seconds + "s " + fps + "fps";
			ga("send", "event", "level", "complete", str);
		}
		/* jshint ignore:end */
	},

	menu: function() {
		GS.InputHelper.checkPressedKeys();

		if (!GS.InputHelper.keysPressed && GS.InputHelper.isKeyDown(this.keys.Escape)) {
			if (this.grid !== undefined) {
				this.closeMenu();
			}
		}

		this.uiManager.update();
	},

	openMenu: function() {
		this.nextState = GS.GameStates.Menu;

		if (this.grid !== undefined) {
			this.grid.player.inMenu = true;
			this.grid.player.controls.disable();
			this.grid.player.controls.detachEvents();
		}

		this.graphicsManager.monochromeEnabled = true;
		this.uiManager.menuActive = true;

		GS.DebugUI.visible = false;
	},

	closeMenu: function() {
		this.nextState = GS.GameStates.Play;

		if (this.grid !== undefined) {
			this.grid.player.inMenu = false;
			this.grid.player.controls.attachEvents();
			this.grid.player.controls.enable();
			this.grid.aiManager.resume();

			if (this.mapWon || !this.uiManager.automap.visible) {
				this.graphicsManager.monochromeEnabled = false;
			}
		} else {
			this.graphicsManager.monochromeEnabled = false;
		}

		this.uiManager.menuActive = false;
		GS.DebugUI.visible = GS.Settings.showHUD;
	},

	restartLevel: function() {
		this.nextState = GS.GameStates.Dispose;
		this.restartedLevel = true;
	},

	loadLevel: function(name) {
		if (this.uiManager.menuActive) {
			this.closeMenu();
		}

		this.mapName = name;
		this.nextState = GS.GameStates.Dispose;
	},

	newGame: function() {
		if (this.uiManager.menuActive) {
			this.closeMenu();
		}

		this.mapName = "airstrip1";
		this.nextState = GS.GameStates.Dispose;
	},

	initComponents: function(assets) {
		var that = this;
		var map = this.assetLoader.mapLoader.parse(assets[GS.AssetTypes.Map][this.mapName]);
		this.mapWon = false;

		var viewFactory = new GS.ViewFactory(this.renderer, map, assets);
		viewFactory.init();
		var gridFactory = new GS.GridFactory(viewFactory, this.soundManager, this.renderer, this.scene, this.camera);
		this.grid = gridFactory.getGrid(map);

		this.soundManager.initSounds(assets[GS.AssetTypes.Sound]);
		this.musicManager.initTracks(assets[GS.AssetTypes.MusicTrack]);

		if (this.playerPersistencePackage !== undefined) {
			this.grid.player.applyPersistencePackage(this.playerPersistencePackage);
			this.playerPersistencePackage = undefined;
		}

		this.grid.update();
		this.graphicsManager.setGrid(this.grid);

		this.grid.player.controls.addEventListener("pointerLockDisabled", function() { that.openMenu(); });

		// console.log("collision triangles", viewFactory.triangleCount);
	},

	update: function() {
		if (this.showPerformanceDebugMeters) {
			var time = window.performance.now();
		}

		if (this.state == GS.GameStates.Dispose) {
			if (!this.updated) {
				this.updated = true;
				this.dispose();
			}
		} else
		if (this.state == GS.GameStates.PreLoad) {
			if (!this.updated) {
				this.updated = true;
				this.preLoad();
			}
		} else
		if (this.state == GS.GameStates.Loading) {
			this.updated = true;
		} else
		if (this.state == GS.GameStates.PostLoad) {
			if (!this.updated) {
				this.updated = true;
				this.postLoad();
			}
		} else
		if (this.state == GS.GameStates.Play) {
			this.updated = true;
			this.play();
		} else
		if (this.state == GS.GameStates.Menu) {
			this.updated = true;
			this.menu();
		}

		if (this.nextState != null) {
			if (this.updated) {
				if (this.nextState == GS.GameStates.Play || this.nextState == GS.GameStates.Menu) {
					this.loadingUI.hide();
					this.uiManager.show();
				}

				this.state = this.nextState;
				this.nextState = null;
				this.updated = false;
			}
		}

		if (this.showPerformanceDebugMeters) {
			this.updateTime = (window.performance.now() - time).toFixed(2);
			GS.DebugUI.trackNumericValue("updateTime", this.updateTime);
		}
	},

	draw: function() {
		if (this.showPerformanceDebugMeters) {
			var time = window.performance.now();
		}

		if (this.state == GS.GameStates.PreLoad) {
			this.loadingUI.draw();
		} else
		if (this.state == GS.GameStates.Loading) {
			this.loadingUI.draw();
		} else
		if (this.state == GS.GameStates.PostLoad) {
			this.loadingUI.draw();
		} else
		if (this.state == GS.GameStates.Play || this.state == GS.GameStates.Menu) {
			if (this.grid !== undefined) {
				this.graphicsManager.draw();
			}

			this.uiManager.draw();
		}

		if (this.showPerformanceDebugMeters) {
			this.drawTime = (window.performance.now() - time).toFixed(2);
			GS.DebugUI.trackNumericValue("drawTime", this.drawTime);
		}
	},

	onResize: function() {
		GS.Base.prototype.onResize.call(this);

		this.uiManager.onResize();
		this.loadingUI.onResize();

		if (this.graphicsManager !== undefined) {
			this.graphicsManager.onResize();
		}

		if (this.grid !== undefined) {
			this.grid.onResize();
			this.grid.player.playerView.onResize();
		}
	},

	updateFov: function() {
		this.cameraFov = GS.Settings.fov;
		this.camera.fov = GS.Settings.fov;
		this.camera.updateProjectionMatrix();

		if (this.state == GS.GameStates.Play) {
			this.grid.updateFov();
		}
	},

	disposeEnd: function() {
		TWEEN.removeAll();
		this.grid = undefined;
		this.graphicsManager.reset();
		this.scene = undefined;
		this.uiManager.dispose();

		this.nextState = GS.GameStates.PreLoad;
	},

	dispose: function() {
		var that = this;

		if (this.grid !== undefined) {
			this.grid.player.controls.dispose(function() {
				that.disposeEnd();
			});
		} else {
			this.disposeEnd();
		}
	},
});

var GAME;
window.addEventListener("load", function() {
	GS.Detector.run(function() {
		GAME = new GS.Game();
		GAME.init();
	});
}, false);<commit_msg>fix GA undefined error<commit_after>GS.GameVersion = "build 10 (august 20, 2014)";
GS.BuildMessage = "added in this build: rebindable keys";

GS.GameStates = {
	Dispose: 0,
	PreLoad: 1,
	Loading: 2,
	PostLoad: 3,
	Play: 4,
	Menu: 5,
};

GS.Game = function() {
	GS.Base.call(this);

	GS.Settings.loadSettings();

	this.state = GS.GameStates.PreLoad;
	this.nextState = null;
	this.updated = false;
	this.firstLoad = true;
	this.firstPlay = true;
	this.mapWon = false;
	this.restartedLevel = false;

	this.antialias = false;
	this.clearColor = 0x336699;
	this.cameraFov = GS.Settings.fov;
	this.cameraFar = 1500;

	this.noMenu = false;
	this.useAssetsZip = false;

	if (GS.BuildOverride === true) {
		this.useAssetsZip = true;
	}

	this.showFPS = GS.Settings.showFPS;
	this.showPerformanceDebugMeters = false;
};

GS.Game.prototype = GS.inherit(GS.Base, {
	constructor: GS.Game,

	init: function() {
		GS.DebugUI.init();
		GS.DebugUI.visible = false;

		this.loadingUI = new GS.LoadingUI();
		this.loadingUI.init();

		this.uiManager = new GS.UIManager();
		this.uiManager.init();

		this.soundManager = new GS.SoundManager();
		this.soundManager.init();

		this.musicManager = new GS.MusicManager();
		this.musicManager.init();

		this.initAssetLoader();

		this.keys = {
			Enter: 13,
			Escape: 27,
			Tab: 9,
		};

		GS.Base.prototype.init.call(this);

		this.graphicsManager = new GS.GraphicsManager(this.renderer, this.camera);
		this.graphicsManager.init();
	},

	preLoad: function() {
		this.uiManager.reset();

		this.loadingUI.percentLoaded = 0;
		this.loadingUI.show();

		this.scene = new THREE.Scene();
		this.scene.fog = new THREE.Fog(new THREE.Color().setRGB(0, 0, 0).getHex(), 500, 900);

		if (!this.assetLoader.loaded) {
			this.assetLoader.load();
			this.nextState = GS.GameStates.Loading;
		} else {
			this.nextState = GS.GameStates.PostLoad;
		}
	},

	initAssetLoader: function() {
		var that = this;

		if (this.useAssetsZip) {
			this.assetLoader = new GS.ZipAssetLoader(this.soundManager.ctx);
		} else {
			this.assetLoader = new GS.AssetLoader(this.soundManager.ctx);
		}

		this.assetLoader.init();
		this.assetLoader.addEventListener("progress", function(e) {
			that.loadingUI.updateProgress(e);
		});
		this.assetLoader.addEventListener("load", function(e) {
			that.loadingUI.updateProgress(e);
			that.nextState = GS.GameStates.PostLoad;
		});
	},

	postLoad: function() {
		if (this.firstLoad) {
			this.loadingUI.spinnerOnly = true;
			this.uiManager.initComponents(this.assetLoader.assets);
			this.openMenu();
			this.firstLoad = false;

			if (this.noMenu) {
				this.newGame();
			}
		} else {
			this.initComponents(this.assetLoader.assets);
			this.uiManager.initComponents(this.assetLoader.assets, this.grid);
			this.uiManager.useIngameMenu();

			// GAME.grid.exportMapToOBJ();

			this.nextState = GS.GameStates.Play;
			this.graphicsManager.monochromeEnabled = false;

			if (this.grid.aiManager.script !== undefined && !this.restartedLevel) {
				this.musicManager.playTrack(this.grid.aiManager.script.musicTrack);
			}
			this.restartedLevel = false;

			if (this.firstPlay) {
				this.firstPlay = false;
			}
		}
	},

	play: function() {
		GS.InputHelper.checkPressedKeys();

		if (!GS.InputHelper.keysPressed && GS.InputHelper.isKeyDown(this.keys.Escape)) {
			this.openMenu();
		}

		if (!this.grid.aiManager.mapWon && !GS.InputHelper.keysPressed && GS.InputHelper.isKeyDown(this.keys.Tab)) {
			this.uiManager.automap.visible = !this.uiManager.automap.visible;
			this.uiManager.overrideRedraw = true;
			this.graphicsManager.monochromeEnabled = this.uiManager.automap.visible;
		}

		if (this.grid.player.dead && !GS.InputHelper.keysPressed && GS.InputHelper.isKeyDown(this.keys.Enter)) {
			this.restartLevel();
		}

		if (this.grid.aiManager.mapWon && !GS.InputHelper.keysPressed && GS.InputHelper.isKeyDown(this.keys.Enter)) {
			if (this.grid.aiManager.script.nextMap !== undefined) {
				this.playerPersistencePackage = this.grid.player.getPersistencePackage();
				this.loadLevel(this.grid.aiManager.script.nextMap);
			}
		}

		if (!this.mapWon && this.grid.aiManager.mapWon) {
			this.mapWon = true;
			this.onMapWon();
		}

		if (!this.grid.aiManager.mapWon) {
			this.grid.update();
			TWEEN.update();
		}
		GS.DebugUI.update();

		this.uiManager.update();
	},

	onMapWon: function() {
		this.graphicsManager.monochromeEnabled = false;

		this.trackMapWonEvent();
	},

	trackMapWonEvent: function() {
		/* jshint ignore:start */
		if (typeof ga !== "undefined") {
			var mapName = this.grid.map.name;
			var timeSpent = this.grid.aiManager.timeSpent;
			var seconds = Math.floor(Math.floor(timeSpent) / 1000);
			var fps = Math.floor(GS.DebugUI.valueTracking.fps.avg);

			var str = mapName + " " + seconds + "s " + fps + "fps";
			ga("send", "event", "level", "complete", str);
		}
		/* jshint ignore:end */
	},

	menu: function() {
		GS.InputHelper.checkPressedKeys();

		if (!GS.InputHelper.keysPressed && GS.InputHelper.isKeyDown(this.keys.Escape)) {
			if (this.grid !== undefined) {
				this.closeMenu();
			}
		}

		this.uiManager.update();
	},

	openMenu: function() {
		this.nextState = GS.GameStates.Menu;

		if (this.grid !== undefined) {
			this.grid.player.inMenu = true;
			this.grid.player.controls.disable();
			this.grid.player.controls.detachEvents();
		}

		this.graphicsManager.monochromeEnabled = true;
		this.uiManager.menuActive = true;

		GS.DebugUI.visible = false;
	},

	closeMenu: function() {
		this.nextState = GS.GameStates.Play;

		if (this.grid !== undefined) {
			this.grid.player.inMenu = false;
			this.grid.player.controls.attachEvents();
			this.grid.player.controls.enable();
			this.grid.aiManager.resume();

			if (this.mapWon || !this.uiManager.automap.visible) {
				this.graphicsManager.monochromeEnabled = false;
			}
		} else {
			this.graphicsManager.monochromeEnabled = false;
		}

		this.uiManager.menuActive = false;
		GS.DebugUI.visible = GS.Settings.showHUD;
	},

	restartLevel: function() {
		this.nextState = GS.GameStates.Dispose;
		this.restartedLevel = true;
	},

	loadLevel: function(name) {
		if (this.uiManager.menuActive) {
			this.closeMenu();
		}

		this.mapName = name;
		this.nextState = GS.GameStates.Dispose;
	},

	newGame: function() {
		if (this.uiManager.menuActive) {
			this.closeMenu();
		}

		this.mapName = "airstrip1";
		this.nextState = GS.GameStates.Dispose;
	},

	initComponents: function(assets) {
		var that = this;
		var map = this.assetLoader.mapLoader.parse(assets[GS.AssetTypes.Map][this.mapName]);
		this.mapWon = false;

		var viewFactory = new GS.ViewFactory(this.renderer, map, assets);
		viewFactory.init();
		var gridFactory = new GS.GridFactory(viewFactory, this.soundManager, this.renderer, this.scene, this.camera);
		this.grid = gridFactory.getGrid(map);

		this.soundManager.initSounds(assets[GS.AssetTypes.Sound]);
		this.musicManager.initTracks(assets[GS.AssetTypes.MusicTrack]);

		if (this.playerPersistencePackage !== undefined) {
			this.grid.player.applyPersistencePackage(this.playerPersistencePackage);
			this.playerPersistencePackage = undefined;
		}

		this.grid.update();
		this.graphicsManager.setGrid(this.grid);

		this.grid.player.controls.addEventListener("pointerLockDisabled", function() { that.openMenu(); });

		// console.log("collision triangles", viewFactory.triangleCount);
	},

	update: function() {
		if (this.showPerformanceDebugMeters) {
			var time = window.performance.now();
		}

		if (this.state == GS.GameStates.Dispose) {
			if (!this.updated) {
				this.updated = true;
				this.dispose();
			}
		} else
		if (this.state == GS.GameStates.PreLoad) {
			if (!this.updated) {
				this.updated = true;
				this.preLoad();
			}
		} else
		if (this.state == GS.GameStates.Loading) {
			this.updated = true;
		} else
		if (this.state == GS.GameStates.PostLoad) {
			if (!this.updated) {
				this.updated = true;
				this.postLoad();
			}
		} else
		if (this.state == GS.GameStates.Play) {
			this.updated = true;
			this.play();
		} else
		if (this.state == GS.GameStates.Menu) {
			this.updated = true;
			this.menu();
		}

		if (this.nextState != null) {
			if (this.updated) {
				if (this.nextState == GS.GameStates.Play || this.nextState == GS.GameStates.Menu) {
					this.loadingUI.hide();
					this.uiManager.show();
				}

				this.state = this.nextState;
				this.nextState = null;
				this.updated = false;
			}
		}

		if (this.showPerformanceDebugMeters) {
			this.updateTime = (window.performance.now() - time).toFixed(2);
			GS.DebugUI.trackNumericValue("updateTime", this.updateTime);
		}
	},

	draw: function() {
		if (this.showPerformanceDebugMeters) {
			var time = window.performance.now();
		}

		if (this.state == GS.GameStates.PreLoad) {
			this.loadingUI.draw();
		} else
		if (this.state == GS.GameStates.Loading) {
			this.loadingUI.draw();
		} else
		if (this.state == GS.GameStates.PostLoad) {
			this.loadingUI.draw();
		} else
		if (this.state == GS.GameStates.Play || this.state == GS.GameStates.Menu) {
			if (this.grid !== undefined) {
				this.graphicsManager.draw();
			}

			this.uiManager.draw();
		}

		if (this.showPerformanceDebugMeters) {
			this.drawTime = (window.performance.now() - time).toFixed(2);
			GS.DebugUI.trackNumericValue("drawTime", this.drawTime);
		}
	},

	onResize: function() {
		GS.Base.prototype.onResize.call(this);

		this.uiManager.onResize();
		this.loadingUI.onResize();

		if (this.graphicsManager !== undefined) {
			this.graphicsManager.onResize();
		}

		if (this.grid !== undefined) {
			this.grid.onResize();
			this.grid.player.playerView.onResize();
		}
	},

	updateFov: function() {
		this.cameraFov = GS.Settings.fov;
		this.camera.fov = GS.Settings.fov;
		this.camera.updateProjectionMatrix();

		if (this.state == GS.GameStates.Play) {
			this.grid.updateFov();
		}
	},

	disposeEnd: function() {
		TWEEN.removeAll();
		this.grid = undefined;
		this.graphicsManager.reset();
		this.scene = undefined;
		this.uiManager.dispose();

		this.nextState = GS.GameStates.PreLoad;
	},

	dispose: function() {
		var that = this;

		if (this.grid !== undefined) {
			this.grid.player.controls.dispose(function() {
				that.disposeEnd();
			});
		} else {
			this.disposeEnd();
		}
	},
});

var GAME;
window.addEventListener("load", function() {
	GS.Detector.run(function() {
		GAME = new GS.Game();
		GAME.init();
	});
}, false);<|endoftext|>


<commit_before>import * as style from "./style"

const render = Object.create(null), renderStyle = Object.create(null)

let doc = null

export default function toDOM(node, options) {
  doc = options.document
  return renderNodes(node.content, options)
}

toDOM.renderNode = renderNode

function elt(name, ...children) {
  let dom = doc.createElement(name)
  for (let i = 0; i < children.length; i++) {
    let child = children[i]
    dom.appendChild(typeof child == "string" ? doc.createTextNode(child) : child)
  }
  return dom
}

function wrap(node, options, type) {
  let dom = elt(type || node.type.name)
  if (node.type.contains != "inline")
    renderNodesInto(node.content, dom, options)
  else if (options.renderInlineFlat)
    renderInlineContentFlat(node.content, dom, options)
  else
    renderInlineContent(node.content, dom, options)
  return dom
}

function wrapIn(type) {
  return function(node, options) { return wrap(node, options, type) }
}

function renderNodes(nodes, options) {
  let frag = doc.createDocumentFragment()
  renderNodesInto(nodes, frag, options)
  return frag
}

function renderNode(node, options, offset) {
  let dom = render[node.type.name](node, options)
  if (options.onRender)
    dom = options.onRender(node, dom, offset) || dom
  return dom
}

function renderNodesInto(nodes, where, options) {
  for (let i = 0; i < nodes.length; i++)
    where.appendChild(renderNode(nodes[i], options, i))
}

function renderInlineContent(nodes, where, options) {
  let top = where
  let active = []
  for (let i = 0; i < nodes.length; i++) {
    let node = nodes[i], styles = node.styles
    let keep = 0
    for (; keep < Math.min(active.length, styles.length); ++keep)
      if (!style.same(active[keep], styles[keep])) break
    while (keep < active.length) {
      active.pop()
      top = top.parentNode
    }
    while (active.length < styles.length) {
      let add = styles[active.length]
      active.push(add)
      top = top.appendChild(renderStyle[add.type](add))
    }
    top.appendChild(renderNode(node, options, i))
  }
}

function renderInlineContentFlat(nodes, where, options) {
  let offset = 0
  for (let i = 0; i < nodes.length; i++) {
    let node = nodes[i], styles = node.styles
    let dom = renderNode(node, options, i)
    for (let j = styles.length - 1; j >= 0; j--) {
      let wrap = renderStyle[styles[j].type](styles[j])
      wrap.appendChild(dom)
      dom = wrap
    }
    dom = options.renderInlineFlat(node, dom, offset) || dom
    where.appendChild(dom)
    offset += node.size
  }
}

// Block nodes

render.blockquote = wrap

render.code_block = node => {
  let code = elt("code", node.textContent)
  if (node.attrs.params) {
    code.className = node.attrs.params.replace(/(^|\s+)/g, "$&lang-")
    code.setAttribute("mm-params", node.attrs.params)
  }
  return elt("pre", code)
}

render.heading = (node, options) => wrap(node, options, "h" + node.attrs.level)

render.horizontal_rule = node => {
  let dom = elt("hr")
  dom.setAttribute("mm-markup", node.attrs.markup)
  return dom
}

render.bullet_list = (node, options) => {
  let dom = wrap(node, options, "ul")
  dom.setAttribute("mm-bullet", node.attrs.bullet)
  if (node.attrs.tight) dom.setAttribute("mm-tight", "true")
  return dom
}

render.ordered_list = (node, options) => {
  let dom = wrap(node, options, "ol")
  if (node.attrs.order > 1) dom.setAttribute("start", node.attrs.order)
  if (node.attrs.tight) dom.setAttribute("mm-tight", "true")
  return dom
}

render.list_item = wrapIn("li")

render.paragraph = wrapIn("p")

render.html_block = node => {
  let dom = elt("div")
  dom.innerHTML = node.attrs.html
  dom.setAttribute("mm-html", "html_block")
  return dom
}

// Inline content

render.text = node => doc.createTextNode(node.text)

render.image = node => {
  let dom = elt("img")
  dom.setAttribute("src", node.attrs.src)
  if (node.attrs.title) dom.setAttribute("title", node.attrs.title)
  if (node.attrs.alt) dom.setAttribute("alt", node.attrs.alt)
  return dom
}

render.hard_break = node => elt("br")

render.html_tag = node => {
  let dom = elt("span")
  dom.innerHTML = node.attrs.html
  dom.setAttribute("mm-html", "html_tag")
  return dom
}

// Inline styles

renderStyle.em = () => elt("em")

renderStyle.strong = () => elt("strong")

renderStyle.code = () => elt("code")

renderStyle.link = style => {
  let dom = elt("a")
  dom.setAttribute("href", style.href)
  if (style.title) dom.setAttribute("title", style.title)
  return dom
}
<commit_msg>Fix cursor finding in code blocks<commit_after>import * as style from "./style"

const render = Object.create(null), renderStyle = Object.create(null)

let doc = null

export default function toDOM(node, options) {
  doc = options.document
  return renderNodes(node.content, options)
}

toDOM.renderNode = renderNode

function elt(name, ...children) {
  let dom = doc.createElement(name)
  for (let i = 0; i < children.length; i++) {
    let child = children[i]
    dom.appendChild(typeof child == "string" ? doc.createTextNode(child) : child)
  }
  return dom
}

function wrap(node, options, type) {
  let dom = elt(type || node.type.name)
  if (node.type.contains != "inline")
    renderNodesInto(node.content, dom, options)
  else if (options.renderInlineFlat)
    renderInlineContentFlat(node.content, dom, options)
  else
    renderInlineContent(node.content, dom, options)
  return dom
}

function wrapIn(type) {
  return function(node, options) { return wrap(node, options, type) }
}

function renderNodes(nodes, options) {
  let frag = doc.createDocumentFragment()
  renderNodesInto(nodes, frag, options)
  return frag
}

function renderNode(node, options, offset) {
  let dom = render[node.type.name](node, options)
  if (options.onRender)
    dom = options.onRender(node, dom, offset) || dom
  return dom
}

function renderNodesInto(nodes, where, options) {
  for (let i = 0; i < nodes.length; i++)
    where.appendChild(renderNode(nodes[i], options, i))
}

function renderInlineContent(nodes, where, options) {
  let top = where
  let active = []
  for (let i = 0; i < nodes.length; i++) {
    let node = nodes[i], styles = node.styles
    let keep = 0
    for (; keep < Math.min(active.length, styles.length); ++keep)
      if (!style.same(active[keep], styles[keep])) break
    while (keep < active.length) {
      active.pop()
      top = top.parentNode
    }
    while (active.length < styles.length) {
      let add = styles[active.length]
      active.push(add)
      top = top.appendChild(renderStyle[add.type](add))
    }
    top.appendChild(renderNode(node, options, i))
  }
}

function renderInlineContentFlat(nodes, where, options) {
  let offset = 0
  for (let i = 0; i < nodes.length; i++) {
    let node = nodes[i], styles = node.styles
    let dom = renderNode(node, options, i)
    for (let j = styles.length - 1; j >= 0; j--) {
      let wrap = renderStyle[styles[j].type](styles[j])
      wrap.appendChild(dom)
      dom = wrap
    }
    dom = options.renderInlineFlat(node, dom, offset) || dom
    where.appendChild(dom)
    offset += node.size
  }
}

// Block nodes

render.blockquote = wrap

render.code_block = (node, options) => {
  let code = wrap(node, options, "code")
  if (node.attrs.params) {
    code.className = node.attrs.params.replace(/(^|\s+)/g, "$&lang-")
    code.setAttribute("mm-params", node.attrs.params)
  }
  return elt("pre", code)
}

render.heading = (node, options) => wrap(node, options, "h" + node.attrs.level)

render.horizontal_rule = node => {
  let dom = elt("hr")
  dom.setAttribute("mm-markup", node.attrs.markup)
  return dom
}

render.bullet_list = (node, options) => {
  let dom = wrap(node, options, "ul")
  dom.setAttribute("mm-bullet", node.attrs.bullet)
  if (node.attrs.tight) dom.setAttribute("mm-tight", "true")
  return dom
}

render.ordered_list = (node, options) => {
  let dom = wrap(node, options, "ol")
  if (node.attrs.order > 1) dom.setAttribute("start", node.attrs.order)
  if (node.attrs.tight) dom.setAttribute("mm-tight", "true")
  return dom
}

render.list_item = wrapIn("li")

render.paragraph = wrapIn("p")

render.html_block = node => {
  let dom = elt("div")
  dom.innerHTML = node.attrs.html
  dom.setAttribute("mm-html", "html_block")
  return dom
}

// Inline content

render.text = node => doc.createTextNode(node.text)

render.image = node => {
  let dom = elt("img")
  dom.setAttribute("src", node.attrs.src)
  if (node.attrs.title) dom.setAttribute("title", node.attrs.title)
  if (node.attrs.alt) dom.setAttribute("alt", node.attrs.alt)
  return dom
}

render.hard_break = node => elt("br")

render.html_tag = node => {
  let dom = elt("span")
  dom.innerHTML = node.attrs.html
  dom.setAttribute("mm-html", "html_tag")
  return dom
}

// Inline styles

renderStyle.em = () => elt("em")

renderStyle.strong = () => elt("strong")

renderStyle.code = () => elt("code")

renderStyle.link = style => {
  let dom = elt("a")
  dom.setAttribute("href", style.href)
  if (style.title) dom.setAttribute("title", style.title)
  return dom
}
<|endoftext|>


<commit_before>L.RestoreAction = L.EditAction.extend({
  initialize: function(map, overlay, options) {
    var mode = L.Utils.getNestedVal(overlay, 'editing', '_mode');
    var edited = overlay.edited;

    options = options || {};
    options.toolbarIcon = {
      svg: true,
      html: 'restore',
      tooltip: overlay.options.translation.restoreImage,
      className: edited && mode !== 'lock' ? '' : 'disabled',
    };

    L.EditAction.prototype.initialize.call(this, map, overlay, options);
  },

  addHooks: function() {
    var ov = this._overlay;

    L.DomEvent.on(ov, {
      edit: this._enableAction,
      restore: this._disableAction,
    }, this);

    ov.restore();
  },
});
<commit_msg>Update RestoreAction.js<commit_after>L.RestoreAction = L.EditAction.extend({
  initialize(map, overlay, options) {
    var mode = L.Utils.getNestedVal(overlay, 'editing', '_mode');
    var edited = overlay.edited;

    options = options || {};
    options.toolbarIcon = {
      svg: true,
      html: 'restore',
      tooltip: overlay.options.translation.restoreImage,
      className: edited && mode !== 'lock' ? '' : 'disabled',
    };

    L.EditAction.prototype.initialize.call(this, map, overlay, options);
  },

    addHooks() {
    var ov = this._overlay;

    L.DomEvent.on(ov, {
      edit: this._enableAction,
      restore: this._disableAction,
    }, this);

    ov.restore();
  },
});
<|endoftext|>


<commit_before>(function() {
  function qualifyURL(url) {
    var img = document.createElement('img');
    img.src = url; // set string url
    url = img.src; // get qualified url
    img.src = null; // no server request
    return url;
  }

  var transmission_session_id = "";

  $(document).ready(function() {
    $("tr.group_torrent>td>span>a[href*=torrents\\.php\\?action\\=download]").each(function() {
      $this = $(this);
      href = $this.attr("href");
      url = qualifyURL(href);
      //$new_anchor = $("SB");
      $new_anchor = $(document.createElement("a"));
      $new_anchor.attr("href", "#");
      $new_anchor.html("SB");
      $this.after($new_anchor).after(" | ");
      $new_anchor.click(function(event) {
        event.preventDefault();
        $(this).html(chrome.extension.getURL("throbber.gif"));
        $throbber = $(document.createElement("img"));
        $throbber.attr("src", chrome.extension.getURL("throbber.gif"));
        $(this).html($throbber);
        $anchor = $(this);
        request_obj = {
          method: "torrent-add",
          arguments: {
            filename: url
          }
        };
        var retries = 4;
        var fail_fxn = function(xhr) {
          retries--;
          if (retries <= 0) {
            $fail_icon = $(document.createElement("img"));
            $fail_icon.attr("src", chrome.extension.getURL("stop32.png"));
            $anchor.html($fail_icon);
            return;
          }
          transmission_session_id = xhr.getResponseHeader("X-Transmission-Session-Id");
          this.headers["X-Transmission-Session-Id"] = transmission_session_id;
          $.ajax(this).fail(fail_fxn);
        }
        $.ajax({
          url: "http://bt.cshaus.com/transmission/rpc",
          data: JSON.stringify(request_obj),
          contentType: "application/json; charset=utf-8",
          type: "POST",
          headers: {
            "X-Transmission-Session-Id": transmission_session_id
          },
          success: function(data) {
            $success_icon = $(document.createElement("img"));
            $success_icon.attr("src", chrome.extension.getURL("check32.png"));
            $anchor.html($success_icon);
          },
        }).fail(fail_fxn);
      });
    });
  });
})();
<commit_msg>added hack to make it work with animebyt.es<commit_after>(function() {
  function qualifyURL(url) {
    var img = document.createElement('img');
    img.src = url; // set string url
    url = img.src; // get qualified url
    img.src = null; // no server request
    return url;
  }

  var transmission_session_id = "";

  $(document).ready(function() {
    var mod_fxn = function() {
      $this = $(this);
      href = $this.attr("href");
      url = qualifyURL(href);
      //$new_anchor = $("SB");
      $new_anchor = $(document.createElement("a"));
      $new_anchor.attr("href", "#");
      $new_anchor.html("SB");
      $this.after($new_anchor).after(" | ");
      $new_anchor.click(function(event) {
        event.preventDefault();
        $(this).html(chrome.extension.getURL("throbber.gif"));
        $throbber = $(document.createElement("img"));
        $throbber.attr("src", chrome.extension.getURL("throbber.gif"));
        $(this).html($throbber);
        $anchor = $(this);
        request_obj = {
          method: "torrent-add",
          arguments: {
            filename: url
          }
        };
        var retries = 4;
        var fail_fxn = function(xhr) {
          retries--;
          if (retries <= 0) {
            $fail_icon = $(document.createElement("img"));
            $fail_icon.attr("src", chrome.extension.getURL("stop32.png"));
            $anchor.html($fail_icon);
            return;
          }
          transmission_session_id = xhr.getResponseHeader("X-Transmission-Session-Id");
          this.headers["X-Transmission-Session-Id"] = transmission_session_id;
          $.ajax(this).fail(fail_fxn);
        }
        $.ajax({
          url: "http://bt.cshaus.com/transmission/rpc",
          data: JSON.stringify(request_obj),
          contentType: "application/json; charset=utf-8",
          type: "POST",
          headers: {
            "X-Transmission-Session-Id": transmission_session_id
          },
          success: function(data) {
            $success_icon = $(document.createElement("img"));
            $success_icon.attr("src", chrome.extension.getURL("check32.png"));
            $anchor.html($success_icon);
          },
        }).fail(fail_fxn);
      });
    };

    $("tr.group_torrent>td>span>a[href*=torrents]").each(mod_fxn);
    // hack to make it work with animebyt.es
    $("tr.group_torrent>td>span>span>a[href*=torrents2]").each(mod_fxn);
  });
})();
<|endoftext|>


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

    uniforms1 = {
	time: { type: "f", value: 1.0 },
	resolution: { type: "v2", value: new THREE.Vector2() }
    };

    /* --- Global Variables --- */
    var container, stats;
    var camera, controls, scene, renderer;
    var cross;

    /* --- Main Event Loop --- */
    var clock = new THREE.Clock();
    var RENDER = new THREE.WebGLRenderer({antialias: true, autoClearFocus: false});
    init();
    animate();

    /* --- Init --- */
    function init() {
	camera = new THREE.PerspectiveCamera(60, $("#render").width() / window.innerHeight, 1, 1000);
	camera.position.x = 175;
	camera.position.y = 40;
	camera.position.z = 75;

	controls = new THREE.OrbitControls(camera, document.getElementById("render"));
	controls.addEventListener('change', render);

	scene = new THREE.Scene();
	scene.fog = new THREE.FogExp2(0x000000, 0.002);

    /**/

    var lavaTexture = new THREE.ImageUtils.loadTexture( './lava.jpg');
    lavaTexture.wrapS = lavaTexture.wrapT = THREE.RepeatWrapping;
    // multiplier for distortion speed
    var baseSpeed = 0.02;
    // number of times to repeat texture in each direction
    var repeatS = repeatT = 4.0;

    // texture used to generate "randomness", distort all other textures
    var noiseTexture = new THREE.ImageUtils.loadTexture( './lava.jpg' );
    noiseTexture.wrapS = noiseTexture.wrapT = THREE.RepeatWrapping;
    // magnitude of noise effect
    var noiseScale = 0.1;

    // texture to additively blend with base image texture
    var blendTexture = new THREE.ImageUtils.loadTexture( './lava.jpg' );
    blendTexture.wrapS = blendTexture.wrapT = THREE.RepeatWrapping;
    // multiplier for distortion speed
    var blendSpeed = 0.01;
    // adjust lightness/darkness of blended texture
    var blendOffset = 0.25;

    // texture to determine normal displacement
    var bumpTexture = noiseTexture;
    bumpTexture.wrapS = bumpTexture.wrapT = THREE.RepeatWrapping;
    // multiplier for distortion speed
    var bumpSpeed   = 0.002;
    // magnitude of normal displacement
    var bumpScale   = 5.0;

    // use "this." to create global object
    this.customUniforms = {
        baseTexture:    { type: "t", value: lavaTexture },
        baseSpeed:      { type: "f", value: baseSpeed },
        repeatS:        { type: "f", value: repeatS },
        repeatT:        { type: "f", value: repeatT },
        noiseTexture:   { type: "t", value: noiseTexture },
        noiseScale:     { type: "f", value: noiseScale },
        blendTexture:   { type: "t", value: blendTexture },
        blendSpeed:     { type: "f", value: blendSpeed },
        blendOffset:    { type: "f", value: blendOffset },
        bumpTexture:    { type: "t", value: bumpTexture },
        bumpSpeed:      { type: "f", value: bumpSpeed },
        bumpScale:      { type: "f", value: bumpScale },
        alpha:          { type: "f", value: 1.0 },
        time:           { type: "f", value: 1.0 }
    };

    // create custom material from the shader code above
    //   that is within specially labeled script tags
    var customMaterial = new THREE.ShaderMaterial(
    {
        uniforms: customUniforms,
        vertexShader:   document.getElementById( 'vertexShader'   ).textContent,
        fragmentShader: document.getElementById( 'fragment_shader3' ).textContent
    }   );

    var ballGeometry = new THREE.SphereGeometry(1, 1, 1);
    var ball = new THREE.Mesh(  ballGeometry, customMaterial );
    ball.position.set(0, 0, 0);
    scene.add( ball );

    this.particleGeometry = new THREE.Geometry();
    for (var i = 0; i < 100; i++)
        particleGeometry.vertices.push( new THREE.Vector3(0,0,0) );

    var discTexture = THREE.ImageUtils.loadTexture( 'images/disc.png' );

    // properties that may vary from particle to particle.
    // these values can only be accessed in vertex shaders!
    //  (pass info to fragment shader via vColor.)
    this.attributes =
    {
        customColor:     { type: 'c',  value: [] },
        customOffset:    { type: 'f',  value: [] },
    };

    var particleCount = particleGeometry.vertices.length
    for( var v = 0; v < particleCount; v++ )
    {
        attributes.customColor.value[ v ] = new THREE.Color().setHSL( 1 - v / particleCount, 1.0, 0.5 );
        attributes.customOffset.value[ v ] = 6.282 * (v / particleCount); // not really used in shaders, move elsewhere
    }

    // values that are constant for all particles during a draw call
    this.uniforms =
    {
        time:      { type: "f", value: 1.0 },
        texture:   { type: "t", value: discTexture },
    };

    var shaderMaterial = new THREE.ShaderMaterial(
    {
        uniforms:       uniforms,
        attributes:     attributes,
        vertexShader:   document.getElementById( 'vertexshader' ).textContent,
        fragmentShader: document.getElementById( 'fragmentshader' ).textContent,
        transparent: true, // alphaTest: 0.5,  // if having transparency issues, try including: alphaTest: 0.5,
        // blending: THREE.AdditiveBlending, depthTest: false,
        // I guess you don't need to do a depth test if you are alpha blending
        //
    });

    var particleCube = new THREE.ParticleSystem( particleGeometry, shaderMaterial );
    particleCube.position.set(0, 85, 0);
    particleCube.dynamic = true;
    // in order for transparency to work correctly, we need sortParticles = true.
    //  but this won't work if we calculate positions in vertex shader,
    //  so positions need to be calculated in the update function,
    //  and set in the geometry.vertices array
    particleCube.sortParticles = true;
    //scene.add( particleCube );

    var NODES = {}; // { "url": ["url", "url", ...] , id] };

    function connect(a, b) {

        var lineGeometry = new THREE.Geometry();
        var vertArray = lineGeometry.vertices;
        vertArray.push( new THREE.Vector3((100-5*a)*Math.cos(a*Math.PI/4), (100-5*a)*Math.sin(a*Math.PI/4), 10*a),
                        new THREE.Vector3((100-5*b)*Math.cos(b*Math.PI/4), (100-5*b)*Math.sin(b*Math.PI/4), 10*b) );
        lineGeometry.computeLineDistances();
        var lineMaterial = new THREE.LineBasicMaterial( { color: 0xffffff } );
        var line = new THREE.Line( lineGeometry, lineMaterial );
        scene.add(line);
    }

    function addNode(url, id, links) {

        var material = new THREE.ShaderMaterial( {
            uniforms: uniforms1,
            vertexShader: document.getElementById('vertexShader').textContent,
            fragmentShader: document.getElementById("fragment_shader3").textContent
        });

        var GEOMETRY = new THREE.SphereGeometry(4*links.length, 4*links.length, 4*links.length);
        var mesh = new THREE.Mesh(GEOMETRY, material);
        mesh.position.x = (100-5*id)*Math.cos(id*Math.PI/4);
        mesh.position.y = (100-5*id)*Math.sin(id*Math.PI/4);
        mesh.position.z = 10*id;
        scene.add(mesh);

        //for (var j = 1; j < links.length; j++) {
            //connect(n, links[j]);//links[j]);
            //addLink(n, n + 1);//links[j]);
        //}
    }

    function addUrl(url) {
        //url =  {url: [url1, ..., url3] }
        var L = url[1].length;
        if (Object.keys(url)[0] in NODES) {
            // Check for new leafs
            for (var k = 0; k < L; k++) {
                for (var m = 0; m < NODES[Object.keys(url)[0]]) {
                    if (url[1][k] != -1) {

                    } else {

                    }
                }
            }
        } else {
            //

        }
    }

    for (var i = 0; i < 16; i++) {

        addNode("google.com", [9, 8]);
	}

	var material = new THREE.MeshPhongMaterial({color: 0x00ff00, reflectivity: .1, emissive: 0xff0000});
	var mesh = new THREE.Mesh(GEOMETRY, material);
	mesh.position.x = 0;
	mesh.position.y = 0;
	mesh.position.z = 0;
	//mesh.rotation.x = eval(WHAT);
	mesh.updateMatrix();
	mesh.matrixAutoUpdate = false;
	//scene.add(mesh);

    light = new THREE.DirectionalLight(0x00ffff, 100);
	light.position.set(50, 100, 50);
	scene.add(light);

	light = new THREE.DirectionalLight(0x00ff00, 100);
	light.position.set(0, 50, 100);
	scene.add(light);

	light = new THREE.AmbientLight(0xffAA11);
	scene.add(light);

	renderer = RENDER;
	renderer.setClearColor(0x11051C, 1); //scene.fog.color
	renderer.setSize($("#render").width(), window.innerHeight);
	$("#canvas").replaceWith(renderer.domElement);

	$("#render").on('resize', function() {
	    camera.aspect = $("#render").width() / window.innerHeight;
	    camera.updateProjectionMatrix();

	    renderer.setSize($("#render").width(), window.innerHeight);
	    render();
	});
    }

    /* --- OnWindowResize --- */
    function onWindowResize( event ) {

	uniforms1.resolution.value.x = window.innerWidth;
	uniforms1.resolution.value.y = window.innerHeight;

	uniforms2.resolution.value.x = window.innerWidth;
	uniforms2.resolution.value.y = window.innerHeight;

	camera.aspect = window.innerWidth / window.innerHeight;
	camera.updateProjectionMatrix();

	renderer.setSize(window.innerWidth, window.innerHeight);

    }

    /* --- Animate --- */
    function animate() {
	render();
	requestAnimationFrame(animate);
	controls.update();
    }

    /* --- Render --- */
    function render() {

	var delta = clock.getDelta();
	uniforms1.time.value += delta * 5;
	/*
	for (var i = 0; i < scene.children.length; i++) {

	    var object = scene.children[ i ];

	    object.rotation.y += delta * 0.5 * ( i % 2 ? 1 : -1 ) + i / 256;
	    object.rotation.x += delta * 0.5 * ( i % 2 ? -1 : 1 ) - i / 512;

	}
	*/
	renderer.render( scene, camera );
    }
});
<commit_msg>Pre-sleep PUSH<commit_after>$(document).ready(function() {

    uniforms1 = {
	time: { type: "f", value: 1.0 },
	resolution: { type: "v2", value: new THREE.Vector2() }
    };

    /* --- Global Variables --- */
    var container, stats;
    var camera, controls, scene, renderer;
    var cross;

    /* --- Main Event Loop --- */
    var clock = new THREE.Clock();
    var GEOMETRY = new THREE.SphereGeometry(8, 8, 8);
    var RENDER = new THREE.WebGLRenderer({antialias: true, autoClearFocus: false});
    init();
    animate();

    /* --- Init --- */
    function init() {
	camera = new THREE.PerspectiveCamera(60, $("#render").width() / window.innerHeight, 1, 1000);
	camera.position.x = 175;
	camera.position.y = 40;
	camera.position.z = 75;

	controls = new THREE.OrbitControls(camera, document.getElementById("render"));
	controls.addEventListener('change', render);

	scene = new THREE.Scene();
	scene.fog = new THREE.FogExp2(0x000000, 0.002);

	/**/

	var lavaTexture = new THREE.ImageUtils.loadTexture( './lava.jpg');
	lavaTexture.wrapS = lavaTexture.wrapT = THREE.RepeatWrapping;
	// multiplier for distortion speed
	var baseSpeed = 0.02;
	// number of times to repeat texture in each direction
	var repeatS = repeatT = 4.0;

	// texture used to generate "randomness", distort all other textures
	var noiseTexture = new THREE.ImageUtils.loadTexture( './lava.jpg' );
	noiseTexture.wrapS = noiseTexture.wrapT = THREE.RepeatWrapping;
	// magnitude of noise effect
	var noiseScale = 0.1;

	// texture to additively blend with base image texture
	var blendTexture = new THREE.ImageUtils.loadTexture( './lava.jpg' );
	blendTexture.wrapS = blendTexture.wrapT = THREE.RepeatWrapping;
	// multiplier for distortion speed
	var blendSpeed = 0.01;
	// adjust lightness/darkness of blended texture
	var blendOffset = 0.25;

	// texture to determine normal displacement
	var bumpTexture = noiseTexture;
	bumpTexture.wrapS = bumpTexture.wrapT = THREE.RepeatWrapping;
	// multiplier for distortion speed
	var bumpSpeed   = 0.002;
	// magnitude of normal displacement
	var bumpScale   = 5.0;

	// use "this." to create global object
	this.customUniforms = {
            baseTexture:    { type: "t", value: lavaTexture },
            baseSpeed:      { type: "f", value: baseSpeed },
            repeatS:        { type: "f", value: repeatS },
            repeatT:        { type: "f", value: repeatT },
            noiseTexture:   { type: "t", value: noiseTexture },
            noiseScale:     { type: "f", value: noiseScale },
            blendTexture:   { type: "t", value: blendTexture },
            blendSpeed:     { type: "f", value: blendSpeed },
            blendOffset:    { type: "f", value: blendOffset },
            bumpTexture:    { type: "t", value: bumpTexture },
            bumpSpeed:      { type: "f", value: bumpSpeed },
            bumpScale:      { type: "f", value: bumpScale },
            alpha:          { type: "f", value: 1.0 },
            time:           { type: "f", value: 1.0 }
	};

	// create custom material from the shader code above
	//   that is within specially labeled script tags
	var customMaterial = new THREE.ShaderMaterial(
	    {
		uniforms: customUniforms,
		vertexShader:   document.getElementById( 'vertexShader'   ).textContent,
		fragmentShader: document.getElementById( 'fragment_shader3' ).textContent
	    }   );

	var ballGeometry = new THREE.SphereGeometry(1, 1, 1);
	var ball = new THREE.Mesh(  ballGeometry, customMaterial );
	ball.position.set(0, 0, 0);
	scene.add( ball );

	this.particleGeometry = new THREE.Geometry();
	for (var i = 0; i < 100; i++)
            particleGeometry.vertices.push( new THREE.Vector3(0,0,0) );

	var discTexture = THREE.ImageUtils.loadTexture( 'images/disc.png' );

	// properties that may vary from particle to particle.
	// these values can only be accessed in vertex shaders!
	//  (pass info to fragment shader via vColor.)
	this.attributes =
	    {
		customColor:     { type: 'c',  value: [] },
		customOffset:    { type: 'f',  value: [] },
	    };

	var particleCount = particleGeometry.vertices.length
	for( var v = 0; v < particleCount; v++ )
	{
            attributes.customColor.value[ v ] = new THREE.Color().setHSL( 1 - v / particleCount, 1.0, 0.5 );
            attributes.customOffset.value[ v ] = 6.282 * (v / particleCount); // not really used in shaders, move elsewhere
	}

	// values that are constant for all particles during a draw call
	this.uniforms =
	    {
		time:      { type: "f", value: 1.0 },
		texture:   { type: "t", value: discTexture },
	    };

	var shaderMaterial = new THREE.ShaderMaterial(
	    {
		uniforms:       uniforms,
		attributes:     attributes,
		vertexShader:   document.getElementById( 'vertexshader' ).textContent,
		fragmentShader: document.getElementById( 'fragmentshader' ).textContent,
		transparent: true, // alphaTest: 0.5,  // if having transparency issues, try including: alphaTest: 0.5,
		// blending: THREE.AdditiveBlending, depthTest: false,
		// I guess you don't need to do a depth test if you are alpha blending
		//
	    });

	var particleCube = new THREE.ParticleSystem( particleGeometry, shaderMaterial );
	particleCube.position.set(0, 85, 0);
	particleCube.dynamic = true;
	// in order for transparency to work correctly, we need sortParticles = true.
	//  but this won't work if we calculate positions in vertex shader,
	//  so positions need to be calculated in the update function,
	//  and set in the geometry.vertices array
	particleCube.sortParticles = true;
	//scene.add( particleCube );

	var NODES = []; // { "url": [["url", "url", ...] , id] };

	function addLink(a, b) {

	    var lineGeometry = new THREE.Geometry();
	    var vertArray = lineGeometry.vertices;
	    vertArray.push( new THREE.Vector3((100-5*a)*Math.cos(a*Math.PI/4), (100-5*a)*Math.sin(a*Math.PI/4), 10*a),
			    new THREE.Vector3((100-5*b)*Math.cos(b*Math.PI/4), (100-5*b)*Math.sin(b*Math.PI/4), 10*b) );
	    lineGeometry.computeLineDistances();
	    var lineMaterial = new THREE.LineBasicMaterial( { color: 0xffffff } );
	    var line = new THREE.Line( lineGeometry, lineMaterial );
	    scene.add(line);
	}

	function addNode(url, links) {

	    var n = NODES.length;
	    NODES.push([n, url, links]);
	    var material = new THREE.ShaderMaterial( {
		uniforms: uniforms1,
		vertexShader: document.getElementById('vertexShader').textContent,
		fragmentShader: document.getElementById("fragment_shader3").textContent
	    });
            var mesh = new THREE.Mesh( GEOMETRY, material );
	    mesh.position.x = (100-5*n)*Math.cos(n*Math.PI/4);
	    mesh.position.y = (100-5*n)*Math.sin(n*Math.PI/4);
	    mesh.position.z = 10*n;
	    scene.add( mesh );

	    for (var j = 1; j < links.length; j++) {
		addLink(n, links[j]);//links[j]);
		//addLink(n, n + 1);//links[j]);
	    }
	}

	for (var a = 0; a < 16; a++) {

            addNode("google.com", [9, 8]);
	}

	var material = new THREE.MeshPhongMaterial({color: 0x00ff00, reflectivity: .1, emissive: 0xff0000});
	var mesh = new THREE.Mesh(GEOMETRY, material);
	mesh.position.x = 0;
	mesh.position.y = 0;
	mesh.position.z = 0;
	//mesh.rotation.x = eval(WHAT);
	mesh.updateMatrix();
	mesh.matrixAutoUpdate = false;
	//scene.add(mesh);

	light = new THREE.DirectionalLight(0x00ffff, 100);
	light.position.set(50, 100, 50);
	scene.add(light);

	light = new THREE.DirectionalLight(0x00ff00, 100);
	light.position.set(0, 50, 100);
	scene.add(light);

	light = new THREE.AmbientLight(0xffAA11);
	scene.add(light);

	renderer = RENDER;
	renderer.setClearColor(0x11051C, 1); //scene.fog.color
	renderer.setSize($("#render").width(), window.innerHeight);
	$("#canvas").replaceWith(renderer.domElement);

	$("#render").on('resize', function() {
	    camera.aspect = $("#render").width() / window.innerHeight;
	    camera.updateProjectionMatrix();

	    renderer.setSize($("#render").width(), window.innerHeight);
	    render();
	});
    }

    /* --- OnWindowResize --- */
    function onWindowResize( event ) {

	uniforms1.resolution.value.x = window.innerWidth;
	uniforms1.resolution.value.y = window.innerHeight;

	uniforms2.resolution.value.x = window.innerWidth;
	uniforms2.resolution.value.y = window.innerHeight;

	camera.aspect = window.innerWidth / window.innerHeight;
	camera.updateProjectionMatrix();

	renderer.setSize(window.innerWidth, window.innerHeight);

    }

    /* --- Animate --- */
    function animate() {
	render();
	requestAnimationFrame(animate);
	controls.update();
    }

    /* --- Render --- */
    function render() {

	var delta = clock.getDelta();
	uniforms1.time.value += delta * 5;
	//camera.rotateOnAxis((new THREE.Vector3(0, 1, 0)).normalize(), degInRad(1));
	/*
	  for (var i = 0; i < scene.children.length; i++) {

	  var object = scene.children[ i ];

	  object.rotation.y += delta * 0.5 * ( i % 2 ? 1 : -1 ) + i / 256;
	  object.rotation.x += delta * 0.5 * ( i % 2 ? -1 : 1 ) - i / 512;

	  }
	*/
	renderer.render( scene, camera );
    }
});
<|endoftext|>


<commit_before>const Episode = require('./episode');

const cheerio = require('cheerio');
const debug = require('debug')('malapi:anime');

const request = require('../util/request');
const utils = require('../util/parsing');

const searchUrl = '/anime.php?c[]=a&c[]=b&c[]=c&c[]=d&c[]=e&c[]=f&c[]=g';

class Anime {
  constructor(object) {
    Object.assign(this, object);
  }

  getEpisodes() {
    return request(this.episodesLink).then(resp => {
      const $ = cheerio.load(resp.body);

      const episodes = $('table.episode_list.ascend tr.episode-list-data').map((i, el) => (
        new Episode({
          alt: $(el).find('.episode-title span').text().trim(),
          name: $(el).find('.episode-title a').text().trim(),
          number: $(el).find('.episode-number').text().trim(),
          url: $(el).find('.episode-title a').attr('href'),
          aid: this.id,
        })
      )).get();

      return episodes;
    });
  }

  static search(term) {
    return request(searchUrl, { query: { q: term } }).then(resp => {
      const $ = cheerio.load(resp.body);

      let results = $(".list table tr:contains('add')");
      results = results.map((i, el) =>
        ({
          name: $(el).find('a.hoverinfo_trigger').text().trim(),
          url: $(el).find('a.hoverinfo_trigger').attr('href'),
          id: $(el).find('a.hoverinfo_trigger').attr('id').replace('sarea', ''),
          type: $(el).find('td.borderClass').eq(2).text()
            .trim(),
        })
      ).get();

      return results;
    });
  }

  static fromBody(body) {
    const $ = cheerio.load(body);

    const result = {
      title: $('h1').text(),
      id: $('input[name="aid"]').val(),
      image: $('img.ac').attr('src'),
      detailsLink: $('a:contains("Details")').attr('href'),
      episodesLink: $('a:contains("Episodes")').attr('href'),

      alternativeTitles: {
        japanese: utils.parseSidebar($, 'Japanese', true),
        english: utils.parseSidebar($, 'English', true),
        synoynms: utils.parseSidebar($, 'Synonyms', true),
      },

      type: $('span:contains("Type:")').next('a').text(),
      episodes: utils.parseSidebar($, 'Episodes'),

      status: utils.parseSidebar($, 'Status'),
      aired: utils.parseSidebar($, 'Aired'),

      genres: $('span:contains("Genres:")').siblings('a').map((i, el) => $(el).text()).get(),

      classification: utils.parseSidebar($, 'Rating'),

      statistics: {
        score: {
          value: $('span[itemprop="ratingValue"]').text(),
          count: $('span[itemprop="ratingCount"]').text(),
        },
        popularity: utils.parseSidebar($, 'Popularity'),
        members: utils.parseSidebar($, 'Members'),
        favorites: utils.parseSidebar($, 'Favorites'),
        ranking: $('.numbers.ranked > strong').text(),
      },

      synopsis: $("h2:contains('Synopsis')").next('span').text(),
    };

    const adaptations = $("h2:contains('Related Anime')").next('table').find('tr').map((i, el) => (
      {
        type: $(el).find('td').eq(0).text()
          .slice(0, -1),
        name: $(el).find('td').eq(1).text()
          .split(','),
      }
    ));

    result.adaptations = adaptations.get();

    const characters = $('h2:contains("Characters & Voice Actors")')
      .nextAll('table')
      .find('td:nth-child(2) a[href*="/character/"]')
      .map((i, el) => {
        var actorEl = $(el).parent('td').next().find('a');
        var character = {
          name: $(el).text(),
          role: $(el).next().text(),
          actor: $(actorEl).text(),
          language: $(actorEl).siblings('small').text(),
        };
        return character;
      });

    result.characters = characters.get();

    const staff = $('h2:contains("Staff")')
      .nextAll('table')
      .find('td:nth-child(2) a[href*="/people/"]')
      .map((i, el) => {
        var staff = {
          name: $(el).text(),
          role: $(el).siblings('small').text().split(', '),
        };
        return staff;
      });

    result.staff = staff.get();

    const studios = $('span:contains("Studios:")').nextAll('a').map((i, el) => {
      return $(el).text()
    });

    result.studios = studios.get();

    return new Anime(result);
  }

  static fromUrl(url) {
    debug(`Anime from URL ${url}`);
    return request(url).then(resp => Anime.fromBody(resp.body));
  }

  static fromId(id) {
    debug(`Anime from ID ${id}`);
    return Anime.fromUrl(`/anime/${id}`);
  }

  static fromSearchResult(result) {
    return Anime.fromId(result.id);
  }

  static fromName(name) {
    return Anime.search(name).then(results =>
      Anime.fromSearchResult(results[0])
    );
  }
}

module.exports = Anime;
<commit_msg>Restored removed function and adhered to style guide.<commit_after>const Episode = require('./episode');

const cheerio = require('cheerio');
const debug = require('debug')('malapi:anime');
const xml2js = require('xml2js');

const request = require('../util/request');
const utils = require('../util/parsing');

const searchUrl = '/anime.php?c[]=a&c[]=b&c[]=c&c[]=d&c[]=e&c[]=f&c[]=g';

const parser = new xml2js.Parser({
  explicitRoot: false,
  explicitArray: false,
});

class Anime {
  constructor(object) {
    Object.assign(this, object);
  }

  getEpisodes() {
    return request(this.episodesLink).then(resp => {
      const $ = cheerio.load(resp.body);

      const episodes = $('table.episode_list.ascend tr.episode-list-data').map((i, el) => (
        new Episode({
          alt: $(el).find('.episode-title span').text().trim(),
          name: $(el).find('.episode-title a').text().trim(),
          number: $(el).find('.episode-number').text().trim(),
          url: $(el).find('.episode-title a').attr('href'),
          aid: this.id,
        })
      )).get();

      return episodes;
    });
  }

  static search(term) {
    return request(searchUrl, { query: { q: term } }).then(resp => {
      const $ = cheerio.load(resp.body);

      let results = $(".list table tr:contains('add')");
      results = results.map((i, el) =>
        ({
          name: $(el).find('a.hoverinfo_trigger').text().trim(),
          url: $(el).find('a.hoverinfo_trigger').attr('href'),
          id: $(el).find('a.hoverinfo_trigger').attr('id').replace('sarea', ''),
          type: $(el).find('td.borderClass').eq(2).text()
            .trim(),
        })
      ).get();

      return results;
    });
  }

  static fromBody(body) {
    const $ = cheerio.load(body);

    const result = {
      title: $('h1').text(),
      id: $('input[name="aid"]').val(),
      image: $('img.ac').attr('src'),
      detailsLink: $('a:contains("Details")').attr('href'),
      episodesLink: $('a:contains("Episodes")').attr('href'),

      alternativeTitles: {
        japanese: utils.parseSidebar($, 'Japanese', true),
        english: utils.parseSidebar($, 'English', true),
        synoynms: utils.parseSidebar($, 'Synonyms', true),
      },

      type: $('span:contains("Type:")').next('a').text(),
      episodes: utils.parseSidebar($, 'Episodes'),

      status: utils.parseSidebar($, 'Status'),
      aired: utils.parseSidebar($, 'Aired'),

      genres: $('span:contains("Genres:")').siblings('a').map((i, el) => $(el).text()).get(),

      classification: utils.parseSidebar($, 'Rating'),

      statistics: {
        score: {
          value: $('span[itemprop="ratingValue"]').text(),
          count: $('span[itemprop="ratingCount"]').text(),
        },
        popularity: utils.parseSidebar($, 'Popularity'),
        members: utils.parseSidebar($, 'Members'),
        favorites: utils.parseSidebar($, 'Favorites'),
        ranking: $('.numbers.ranked > strong').text(),
      },

      synopsis: $("h2:contains('Synopsis')").next('span').text(),
    };

    const adaptations = $("h2:contains('Related Anime')").next('table').find('tr').map((i, el) => (
      {
        type: $(el).find('td').eq(0).text()
          .slice(0, -1),
        name: $(el).find('td').eq(1).text()
          .split(','),
      }
    ));

    result.adaptations = adaptations.get();

    const characters = $('h2:contains("Characters & Voice Actors")')
      .nextAll('table')
      .find('td:nth-child(2) a[href*="/character/"]')
      .map((i, el) => {
        const actorEl = $(el).parent('td').next().find('a');
        const character = {
          name: $(el).text(),
          role: $(el).next().text(),
          actor: $(actorEl).text(),
          language: $(actorEl).siblings('small').text(),
        };
        return character;
      });

    result.characters = characters.get();

    const staff = $('h2:contains("Staff")')
      .nextAll('table')
      .find('td:nth-child(2) a[href*="/people/"]')
      .map((i, el) => {
        const row = {
          name: $(el).text(),
          role: $(el).siblings('small').text().split(', '),
        };
        return row;
      });

    result.staff = staff.get();

    const studios = $('span:contains("Studios:")').nextAll('a').map((i, el) =>
      $(el).text()
    );

    result.studios = studios.get();

    return new Anime(result);
  }

  static getList(username) {
    return request('/malappinfo.php', { query: { u: username, status: 'all', type: 'anime' } })
    .then(resp => (
      new Promise((resolve) => {
        parser.parseString(resp.body, (err, parsed) => {
          if (typeof parsed.error !== 'undefined') {
            resolve(null);
          }
          resolve(parsed);
        });
      })
    ));
  }

  static fromUrl(url) {
    debug(`Anime from URL ${url}`);
    return request(url).then(resp => Anime.fromBody(resp.body));
  }

  static fromId(id) {
    debug(`Anime from ID ${id}`);
    return Anime.fromUrl(`/anime/${id}`);
  }

  static fromSearchResult(result) {
    return Anime.fromId(result.id);
  }

  static fromName(name) {
    return Anime.search(name).then(results =>
      Anime.fromSearchResult(results[0])
    );
  }
}

module.exports = Anime;
<|endoftext|>


<commit_before>'use strict';

var scene0images = [
  "img/classroom.jpg",
  "img/classroom2.jpg",
  "img/student.png",
  "img/banana.png",
  "img/close.png",
  "img/shit.png",
  "img/digestive-system.png",
  "img/mosca.gif",
  "img/arrow.png",
  "img/sick-person.png"
];
loadImages(scene0images, scene0setup);

playMusic("audio/suikodentierkreis-friendofthegreatplains.m4a");

function scene0setup() {

  scene[0] = new GameScene();
  scene[0].setMusic("audio/suikodentierkreis-friendofthegreatplains.m4a");

  var classroom = new GameBackground("img/classroom.jpg");
  classroom.click = function(mouse) {
    var mousePosition = mouse.data.getLocalPosition(stage);
    console.log(Math.round(mousePosition.x) + "; " + Math.round(mousePosition.y));
  }

  var customText = new GameText("Hello World!!\nHow are you?", {font: "60px Arial", fill: 0x000000, align: "left"});
  customText.setPosition(700, 50);
  customText.setAlpha(0);

  var classroom2 = new GameBackground("img/classroom2.jpg");
  classroom2.click = function(mouse) {
    var mousePosition = mouse.data.getLocalPosition(stage);
    console.log(Math.round(mousePosition.x) + "; " + Math.round(mousePosition.y));
  }

  var student = new GameItem("img/student.png");
  student.setPosition(480, 740);
  student.click = function(mouse) {
    console.log("Clicked on student");

    customText.fadein(600);
  }

  var banana = new GameItem("img/banana.png");
  banana.setPosition(759, 648);
  banana.addGlowEffect();
  banana.click = function(mouse) {
    console.log("Clicked on banana");
    classroom.changeDarkness(200, 600);
    setTimeout(function() {
      student.fadeout(600);
      shit.fadein(600);
      digestiveSystem.fadein(600);
      banana.move(1287, 273, 600);
      banana.changeScale(3, 600);
      closeButton.fadein(600);
    }, 800);
  }

  var shit = new GameItem("img/shit.png");
  shit.setPosition(1308, 773);
  shit.disable();
  shit.addGlowEffect();
  shit.click = function(mouse) {
    console.log("Clicked on shit");
    playSoundEffect("audio/explosion.wav");
  }

  var digestiveSystem = new GameItem("img/digestive-system.png");
  digestiveSystem.setPosition(480, 530);
  digestiveSystem.disable();
  digestiveSystem.addGlowEffect();
  digestiveSystem.setScale(1.3);
  digestiveSystem.click = function(mouse) {
    console.log("Clicked on digestiveSystem");
    playSoundEffect("audio/explosion.wav");
  }

  var closeButton = new GameItem("img/close.png");
  closeButton.setPosition(1840, 65);
  closeButton.disable();
  closeButton.addGlowEffect();
  closeButton.click = function(mouse) {
    console.log("Clicked on close button");
    student.fadein(600);
    shit.fadeout(600);
    digestiveSystem.fadeout(600);
    banana.move(759, 648, 600);
    banana.changeScale(1, 600);
    closeButton.fadeout(600);
    classroom.changeDarkness(0, 600);
    //scene[0].changeBackground(1);
    pauseMusic();
  }

  var arrow = new GameItem("img/arrow.png");
  arrow.setPosition(1700, 550);
  arrow.setScale(0.5);
  arrow.addGlowEffect();
  arrow.click = function(mouse) {
    changeScene(1);
  }

  scene[0].addBackground(classroom);
  scene[0].addBackground(classroom2);
  scene[0].addItem(customText);
  scene[0].addItem(student);
  scene[0].addItem(banana);
  scene[0].addItem(shit);
  scene[0].addItem(digestiveSystem);
  scene[0].addItem(closeButton);
  scene[0].addItem(arrow);

  UpdateScreen();
}
<commit_msg>music is now associated to a scene<commit_after>'use strict';

var scene0images = [
  "img/classroom.jpg",
  "img/classroom2.jpg",
  "img/student.png",
  "img/banana.png",
  "img/close.png",
  "img/shit.png",
  "img/digestive-system.png",
  "img/mosca.gif",
  "img/arrow.png",
  "img/sick-person.png"
];
loadImages(scene0images, scene0setup);

function scene0setup() {

  scene[0] = new GameScene();
  scene[0].setMusic("audio/suikodentierkreis-friendofthegreatplains.m4a");

  var classroom = new GameBackground("img/classroom.jpg");
  classroom.click = function(mouse) {
    var mousePosition = mouse.data.getLocalPosition(stage);
    console.log(Math.round(mousePosition.x) + "; " + Math.round(mousePosition.y));
  }

  var customText = new GameText("Hello World!!\nHow are you?", {font: "60px Arial", fill: 0x000000, align: "left"});
  customText.setPosition(700, 50);
  customText.setAlpha(0);

  var classroom2 = new GameBackground("img/classroom2.jpg");
  classroom2.click = function(mouse) {
    var mousePosition = mouse.data.getLocalPosition(stage);
    console.log(Math.round(mousePosition.x) + "; " + Math.round(mousePosition.y));
  }

  var student = new GameItem("img/student.png");
  student.setPosition(480, 740);
  student.click = function(mouse) {
    console.log("Clicked on student");

    customText.fadein(600);
  }

  var banana = new GameItem("img/banana.png");
  banana.setPosition(759, 648);
  banana.addGlowEffect();
  banana.click = function(mouse) {
    console.log("Clicked on banana");
    classroom.changeDarkness(200, 600);
    setTimeout(function() {
      student.fadeout(600);
      shit.fadein(600);
      digestiveSystem.fadein(600);
      banana.move(1287, 273, 600);
      banana.changeScale(3, 600);
      closeButton.fadein(600);
    }, 800);
  }

  var shit = new GameItem("img/shit.png");
  shit.setPosition(1308, 773);
  shit.disable();
  shit.addGlowEffect();
  shit.click = function(mouse) {
    console.log("Clicked on shit");
    playSoundEffect("audio/explosion.wav");
  }

  var digestiveSystem = new GameItem("img/digestive-system.png");
  digestiveSystem.setPosition(480, 530);
  digestiveSystem.disable();
  digestiveSystem.addGlowEffect();
  digestiveSystem.setScale(1.3);
  digestiveSystem.click = function(mouse) {
    console.log("Clicked on digestiveSystem");
    playSoundEffect("audio/explosion.wav");
  }

  var closeButton = new GameItem("img/close.png");
  closeButton.setPosition(1840, 65);
  closeButton.disable();
  closeButton.addGlowEffect();
  closeButton.click = function(mouse) {
    console.log("Clicked on close button");
    student.fadein(600);
    shit.fadeout(600);
    digestiveSystem.fadeout(600);
    banana.move(759, 648, 600);
    banana.changeScale(1, 600);
    closeButton.fadeout(600);
    classroom.changeDarkness(0, 600);
    //scene[0].changeBackground(1);
    pauseMusic();
  }

  var arrow = new GameItem("img/arrow.png");
  arrow.setPosition(1700, 550);
  arrow.setScale(0.5);
  arrow.addGlowEffect();
  arrow.click = function(mouse) {
    changeScene(1);
  }

  scene[0].addBackground(classroom);
  scene[0].addBackground(classroom2);
  scene[0].addItem(customText);
  scene[0].addItem(student);
  scene[0].addItem(banana);
  scene[0].addItem(shit);
  scene[0].addItem(digestiveSystem);
  scene[0].addItem(closeButton);
  scene[0].addItem(arrow);

  UpdateScreen();

  // After loading the first scene, play the music (only needed for this scene)
  playMusic("audio/suikodentierkreis-friendofthegreatplains.m4a");
}
<|endoftext|>


<commit_before>import knex from '../utils/db';

const userSummaryFields = ['id', 'email'];

export const dbGetUsers = () => (
  knex('users')
    .select(userSummaryFields)
);

export const dbGetUser = id => (
  knex('users')
    .first()
    .where({ id })
);

export const dbUpdateUser = (id, fields) => (
  knex('users')
    .update({ ...fields })
    .where({ id })
);

export const dbDelUser = id => (
  knex('users')
    .where({ id })
    .del()
);

export const dbCreateUser = ({ password, ...fields }) => (
  knex.transaction(async (trx) => {
    const user = await trx('users')
      .insert(fields)
      .returning('*')
      .then(results => results[0]); // return only first result

    await trx('secrets')
      .insert({
        ownerId: user.id,
        password,
      });

    return user;
  })
);
<commit_msg>dbUpdateUser returns all fields<commit_after>import knex from '../utils/db';

const userListFields = ['id', 'email'];

export const dbGetUsers = () => (
  knex('users')
    .select(userListFields)
);

export const dbGetUser = id => (
  knex('users')
    .first()
    .where({ id })
);

export const dbUpdateUser = (id, fields) => (
  knex('users')
    .update({ ...fields })
    .where({ id })
    .returning('*')
);

export const dbDelUser = id => (
  knex('users')
    .where({ id })
    .del()
);

export const dbCreateUser = ({ password, ...fields }) => (
  knex.transaction(async (trx) => {
    const user = await trx('users')
      .insert(fields)
      .returning('*')
      .then(results => results[0]); // return only first result

    await trx('secrets')
      .insert({
        ownerId: user.id,
        password,
      });

    return user;
  })
);
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2011-2013 by Animatron.
 * All rights are reserved.
 *
 * Animatron Player is licensed under the MIT License, see LICENSE.
 *
 * @VERSION
 */

(function() { // anonymous wrapper to exclude global context clash
  var C = anm.C,
      Tween = anm.Tween,
      Tweens = anm.Tweens;
  var _ResMan = __anm.resource_manager;

  C.MOD_AUDIO = 'audio';
  if (anm.M[C.MOD_AUDIO]) throw new Error('AUDIO module already enabled');

  anm.M[C.MOD_AUDIO] = {};
  var m_ctx = anm.M[C.MOD_AUDIO];

  var E = anm.Element;

  // Initialization
  // ----------------------------------------------------------------------------------------------------------------

  m_ctx._audio_ctx = function() {
    var context = window.webkitAudioContext || window.audioContext || window.AudioContext;
    return context ? new context() : null;
  }();

  C.T_VOLUME = 'VOLUME';
  Tween.TWEENS_PRIORITY[C.T_VOLUME] = Tween.TWEENS_COUNT++;
  Tweens[C.T_VOLUME] = function() {
    return function(t, duration, data) {
      if (!this.$._audio_is_loaded) return;
      this.$._audio.volume = data[0] * (1.0 - t) + data[1] * t;
    };
  };

  if (anm.I['ANM']) {
    var Import = anm.I['ANM'];
    var prev_tweentype = Import.tweentype;
    Import.tweentype = function(src) {
      if (src === 7) return C.T_VOLUME;
      return prev_tweentype.apply(this, arguments);
    }
    var prev_tweendata = Import.tweendata;
    Import.tweendata = function(type, src) {
      if ((type === C.T_VOLUME) && src) {
        if (src.length == 2) return src;
        if (src.length == 1) return [ src[0], src[0] ];
      }
      return prev_tweendata.apply(this, arguments);
    }
  }

  // Element functions
  // ----------------------------------------------------------------------------------------------------------------

  var _audio_customRender = function(gtime, ltime, ctx) {
    // TODO: remove
    //return false;
  };

  var _onAudioStart = function(ltime, duration) {
    if (!this._audio_is_loaded || this._audio_is_playing) {
      return false;
    }

    this._audio_is_playing = true;
    var current_time = this._audio_band_offset + ltime;

    if (m_ctx._audio_ctx) {
      this._source = m_ctx._audio_ctx.createBufferSource();
      this._source.buffer = this._audio_buffer;
      this._source.connect(m_ctx._audio_ctx.destination);

      if (this._source.play) {
        this._source.play(0, current_time);
      } else if (this._source.start) {
        this._source.start(0, current_time, this._source.buffer.duration - current_time);
      } else {
        this._source.noteGrainOn(0, current_time, this._source.buffer.duration - current_time);
      }
    } else {
      this._audio.currentTime = current_time;
      this._audio.volume = 1;
      this._audio.play();
    }
  };

  var _onAudioStop = function(ltime, duration) {
    if (this._audio_is_playing) {
      if (m_ctx._audio_ctx) {
        if (this._source.stop) {
          this._source.stop(0);
        } else {
          this._source.noteOff(0);
        }

        this._source = null;
      } else {
        this._audio.pause();
        this._audio.volume = 0;
      }

      this._audio_is_playing = false;
    }
  };

  E._customImporters.push(function(source, type, importer) {
    if ((14 == type)/*ANM*/ ||
        ("0e" == type)/*ANM_INTACT*/) {
      if (importer == "ANM") {
        /** audio **/
        /*
         * array {
         *     14;                         // 0
         *     string;                     // 1, url
         *     number;                     // 2, band offset
         * } *audio_element*;
         */
        this._audio_url = source[1];
        this._audio_band_offset = source[2];
      } else if (importer == "ANM_INTACT") {
        this._audio_band_offset = source.bandOffset;
        this._audio_url = this._audio_format_url(source.url);
      }

      this.isAudio = true;
      this._audio = null;
      this._audio_is_loaded = false;
      this._audio_is_playing = false;
      this._audio_canPlay = false;

      this.on(C.X_START, _onAudioStart);
      this.on(C.X_STOP, _onAudioStop);
      this.on(C.S_STOP, _onAudioStop);
      this.on(C.S_PAUSE, _onAudioStop);

      // assign custom render function
      this.__frameProcessors.push(_audio_customRender);

      this._audioLoad();
    }
  });

  E.prototype._audio_format_url = function(url) {
    return url + (this._mpeg_supported() ? ".mp3" : ".ogg");
  };

  E.__test_elm = null;

  E.prototype._mpeg_supported = function() {
    var a = E.__test_elm ? E.__test_elm : (E.__test_elm = document.createElement('audio'), E.__test_elm);
    return !!(a.canPlayType && a.canPlayType('audio/mpeg;').replace(/no/, ''));
  }

  var prev__hasRemoteResources = E.prototype._hasRemoteResources;
  E.prototype._hasRemoteResources = function() {
    return prev__hasRemoteResources.call(this, arguments) || this.isAudio;
  }

  var prev__getRemoteResources = E.prototype._getRemoteResources;
  E.prototype._getRemoteResources = function() {
    var prev = prev__getRemoteResources.call(this, arguments);
    if (!this.isAudio && !prev) return null;
    if (!this.isAudio) return prev;
        // return [ this._audio_url ].concat(prev || [])
    return prev ? [ this._audio_url ].concat(prev) : [ this._audio_url ];
  }

  function audioErrProxy(src, pass_to) {
    return function(err) {
      // e_.MEDIA_ERR_ABORTED=1
      // e_.MEDIA_ERR_NETWORK=2
      // e_.MEDIA_ERR_DECODE=3
      // e_.MEDIA_ERR_SRC_NOT_SUPPORTED=4
      // e_.MEDIA_ERR_ENCRYPTED=5
      pass_to(new Error('Failed to load audio file from ' + src + ' with error code: ' +
                        err.currentTarget.error.code));
    }
  };

  E.prototype._audioLoad = function() {
    var me = this;

    _ResMan.loadOrGet(me._audio_url,
      function(notify_success, notify_error) { // loader
          if (__anm.conf.doNotLoadAudio) {
            notify_error('Loading audio is turned off');
            return;
          }

          if (m_ctx._audio_ctx) {
            // use Web Audio API if possible

            var loadingDone = function(e) {
              var req = e.target;
              m_ctx._audio_ctx.decodeAudioData(req.response, function onSuccess(decodedBuffer) {
                me._audio_buffer = decodedBuffer;
                me._audio_is_loaded = true;
                notify_success(me);
              }, audioErrProxy(me._audio_url, notify_error));
            };

            var req = new XMLHttpRequest();
            req.open('GET', me._audio_format_url(me._audio_url), true);
            req.responseType = 'arraybuffer';
            req.addEventListener('load', loadingDone, false);
            req.addEventListener('error', audioErrProxy(me._audio_url, notify_error), false);
            req.send();
          } else {
            var el = document.createElement("audio");
            el.setAttribute("preload", "auto");

            var progressListener = function(e) {
              var buffered = el.buffered;
              if (buffered.length == 1) {
                  var end = buffered.end(0);
                  if (el.duration - end < 0.05) {
                    el.removeEventListener("progress", progressListener, false);
                    el.removeEventListener("canplay", canPlayListener, false);
                    notify_success(el);
                    return;
                  }

                  if (me._audio_canPlay && window.chrome) {
                    el.volume = 0;
                    el.currentTime = end;
                    el.play();
                    el.pause();
                  }
              } else if (me._audio_canPlay && buffered.length != 1) {
                // will skip preloading since it seems like it will not work properly anyway:
                // it's a workaround for Android-based browsers which
                // will not allow prebuffering until user will explicitly allow it (by touching something)
                notify_success(el);
              }
            };

            var canPlayListener = function(e) {
              me._audio_canPlay = true;
              progressListener(e);
            };

            el.addEventListener("progress", progressListener, false);
            el.addEventListener("canplay", canPlayListener, false);
            el.addEventListener("error", audioErrProxy(me._audio_url, notify_error), false);

            var addSource = function(audio, url, type) {
                var src = document.createElement("source");
                src.type = type;
                src.src = url;
                src.addEventListener("error", notify_error, false);
                audio.appendChild(src);
            };

            try {
              document.getElementsByTagName("body")[0].appendChild(el);
              addSource(el, me._audio_url + ".mp3", "audio/mpeg");
              addSource(el, me._audio_url + ".ogg", "audio/ogg");
            } catch(e) { notify_error(e); }
          }
      },
      function(audio) { // oncomplete
          me._audio = audio;
          me._audio_is_loaded = true;
      },
      function(err) { __anm.console.error(err ? (err.message || err) : 'Unknown error');
                      /* throw err; */ }); // onerror
  };

})();<commit_msg>fix web audio api (seems to be a race condition)<commit_after>/*
 * Copyright (c) 2011-2013 by Animatron.
 * All rights are reserved.
 *
 * Animatron Player is licensed under the MIT License, see LICENSE.
 *
 * @VERSION
 */

(function() { // anonymous wrapper to exclude global context clash
  var C = anm.C,
      Tween = anm.Tween,
      Tweens = anm.Tweens;
  var _ResMan = __anm.resource_manager;

  C.MOD_AUDIO = 'audio';
  if (anm.M[C.MOD_AUDIO]) throw new Error('AUDIO module already enabled');

  anm.M[C.MOD_AUDIO] = {};
  var m_ctx = anm.M[C.MOD_AUDIO];

  var E = anm.Element;

  // Initialization
  // ----------------------------------------------------------------------------------------------------------------

  m_ctx._audio_ctx = function() {
    var context = window.webkitAudioContext || window.audioContext || window.AudioContext;
    return context ? new context() : null;
  }();

  C.T_VOLUME = 'VOLUME';
  Tween.TWEENS_PRIORITY[C.T_VOLUME] = Tween.TWEENS_COUNT++;
  Tweens[C.T_VOLUME] = function() {
    return function(t, duration, data) {
      if (!this.$._audio_is_loaded) return;
      this.$._audio.volume = data[0] * (1.0 - t) + data[1] * t;
    };
  };

  if (anm.I['ANM']) {
    var Import = anm.I['ANM'];
    var prev_tweentype = Import.tweentype;
    Import.tweentype = function(src) {
      if (src === 7) return C.T_VOLUME;
      return prev_tweentype.apply(this, arguments);
    }
    var prev_tweendata = Import.tweendata;
    Import.tweendata = function(type, src) {
      if ((type === C.T_VOLUME) && src) {
        if (src.length == 2) return src;
        if (src.length == 1) return [ src[0], src[0] ];
      }
      return prev_tweendata.apply(this, arguments);
    }
  }

  // Element functions
  // ----------------------------------------------------------------------------------------------------------------

  var _audio_customRender = function(gtime, ltime, ctx) {
    // TODO: remove
    //return false;
  };

  var _onAudioStart = function(ltime, duration) {
    if (!this._audio_is_loaded || this._audio_is_playing) {
      return false;
    }

    this._audio_is_playing = true;
    var current_time = this._audio_band_offset + ltime;

    if (m_ctx._audio_ctx) {
      this._source = m_ctx._audio_ctx.createBufferSource();
      this._source.buffer = this._audio;
      this._source.connect(m_ctx._audio_ctx.destination);

      if (this._source.play) {
        this._source.play(0, current_time);
      } else if (this._source.start) {
        this._source.start(0, current_time, this._source.buffer.duration - current_time);
      } else {
        this._source.noteGrainOn(0, current_time, this._source.buffer.duration - current_time);
      }
    } else {
      this._audio.currentTime = current_time;
      this._audio.volume = 1;
      this._audio.play();
    }
  };

  var _onAudioStop = function(ltime, duration) {
    if (this._audio_is_playing) {
      if (m_ctx._audio_ctx) {
        if (this._source.stop) {
          this._source.stop(0);
        } else {
          this._source.noteOff(0);
        }

        this._source = null;
      } else {
        this._audio.pause();
        this._audio.volume = 0;
      }

      this._audio_is_playing = false;
    }
  };

  E._customImporters.push(function(source, type, importer) {
    if ((14 == type)/*ANM*/ ||
        ("0e" == type)/*ANM_INTACT*/) {
      if (importer == "ANM") {
        /** audio **/
        /*
         * array {
         *     14;                         // 0
         *     string;                     // 1, url
         *     number;                     // 2, band offset
         * } *audio_element*;
         */
        this._audio_url = source[1];
        this._audio_band_offset = source[2];
      } else if (importer == "ANM_INTACT") {
        this._audio_band_offset = source.bandOffset;
        this._audio_url = this._audio_format_url(source.url);
      }

      this.isAudio = true;
      this._audio = null;
      this._audio_is_loaded = false;
      this._audio_is_playing = false;
      this._audio_canPlay = false;

      this.on(C.X_START, _onAudioStart);
      this.on(C.X_STOP, _onAudioStop);
      this.on(C.S_STOP, _onAudioStop);
      this.on(C.S_PAUSE, _onAudioStop);

      // assign custom render function
      this.__frameProcessors.push(_audio_customRender);

      this._audioLoad();
    }
  });

  E.prototype._audio_format_url = function(url) {
    return url + (this._mpeg_supported() ? ".mp3" : ".ogg");
  };

  E.__test_elm = null;

  E.prototype._mpeg_supported = function() {
    var a = E.__test_elm ? E.__test_elm : (E.__test_elm = document.createElement('audio'), E.__test_elm);
    return !!(a.canPlayType && a.canPlayType('audio/mpeg;').replace(/no/, ''));
  }

  var prev__hasRemoteResources = E.prototype._hasRemoteResources;
  E.prototype._hasRemoteResources = function() {
    return prev__hasRemoteResources.call(this, arguments) || this.isAudio;
  }

  var prev__getRemoteResources = E.prototype._getRemoteResources;
  E.prototype._getRemoteResources = function() {
    var prev = prev__getRemoteResources.call(this, arguments);
    if (!this.isAudio && !prev) return null;
    if (!this.isAudio) return prev;
        // return [ this._audio_url ].concat(prev || [])
    return prev ? [ this._audio_url ].concat(prev) : [ this._audio_url ];
  }

  function audioErrProxy(src, pass_to) {
    return function(err) {
      // e_.MEDIA_ERR_ABORTED=1
      // e_.MEDIA_ERR_NETWORK=2
      // e_.MEDIA_ERR_DECODE=3
      // e_.MEDIA_ERR_SRC_NOT_SUPPORTED=4
      // e_.MEDIA_ERR_ENCRYPTED=5
      pass_to(new Error('Failed to load audio file from ' + src + ' with error code: ' +
                        err.currentTarget.error.code));
    }
  };

  E.prototype._audioLoad = function() {
    var me = this;

    _ResMan.loadOrGet(me._audio_url,
      function(notify_success, notify_error) { // loader
          if (__anm.conf.doNotLoadAudio) {
            notify_error('Loading audio is turned off');
            return;
          }

          if (m_ctx._audio_ctx) {
            // use Web Audio API if possible

            var loadingDone = function(e) {
              var req = e.target;
              m_ctx._audio_ctx.decodeAudioData(req.response, function onSuccess(decodedBuffer) {
                notify_success(decodedBuffer);
              }, audioErrProxy(me._audio_url, notify_error));
            };

            var req = new XMLHttpRequest();
            req.open('GET', me._audio_format_url(me._audio_url), true);
            req.responseType = 'arraybuffer';
            req.addEventListener('load', loadingDone, false);
            req.addEventListener('error', audioErrProxy(me._audio_url, notify_error), false);
            req.send();
          } else {
            var el = document.createElement("audio");
            el.setAttribute("preload", "auto");

            var progressListener = function(e) {
              var buffered = el.buffered;
              if (buffered.length == 1) {
                  var end = buffered.end(0);
                  if (el.duration - end < 0.05) {
                    el.removeEventListener("progress", progressListener, false);
                    el.removeEventListener("canplay", canPlayListener, false);
                    notify_success(el);
                    return;
                  }

                  if (me._audio_canPlay && window.chrome) {
                    el.volume = 0;
                    el.currentTime = end;
                    el.play();
                    el.pause();
                  }
              } else if (me._audio_canPlay && buffered.length != 1) {
                // will skip preloading since it seems like it will not work properly anyway:
                // it's a workaround for Android-based browsers which
                // will not allow prebuffering until user will explicitly allow it (by touching something)
                notify_success(el);
              }
            };

            var canPlayListener = function(e) {
              me._audio_canPlay = true;
              progressListener(e);
            };

            el.addEventListener("progress", progressListener, false);
            el.addEventListener("canplay", canPlayListener, false);
            el.addEventListener("error", audioErrProxy(me._audio_url, notify_error), false);

            var addSource = function(audio, url, type) {
                var src = document.createElement("source");
                src.type = type;
                src.src = url;
                src.addEventListener("error", notify_error, false);
                audio.appendChild(src);
            };

            try {
              document.getElementsByTagName("body")[0].appendChild(el);
              addSource(el, me._audio_url + ".mp3", "audio/mpeg");
              addSource(el, me._audio_url + ".ogg", "audio/ogg");
            } catch(e) { notify_error(e); }
          }
      },
      function(audio) { // oncomplete
          me._audio = audio;
          me._audio_is_loaded = true;
      },
      function(err) { __anm.console.error(err ? (err.message || err) : 'Unknown error');
                      /* throw err; */ }); // onerror
  };

})();<|endoftext|>