<commit_before>(function () {
    "use strict";

    // Enable nodelists to work with the spread operator
    NodeList.prototype[Symbol.iterator] = Array.prototype[Symbol.iterator];

    // Event symbol
    const EVENT_SYM = Symbol("events");

    // Browser constructor
    function Browser() {
        this[EVENT_SYM] = {};
        this.currentUrl = "";
        this.faviconLocs = new Map;
        this.favorites = new Map;
        this.loading = false;
        this.isFullscreen = false;
        this.roamingFolder = Windows.Storage.ApplicationData.current.roamingFolder;
        this.appView = Windows.UI.ViewManagement.ApplicationView.getForCurrentView();
    }

    Browser.prototype = {
        constructor: Browser,

        // Simple event management - listen for a particular event
        on (type, listener) {
            let listeners = this[EVENT_SYM][type] || (this[EVENT_SYM][type] = []);

            if (listeners.indexOf(listener) < 0) {
                listeners.push(listener);
            }
            return this;
        },

        // Simple event management - stop listening for a particular event
        off (type, listener) {
            let listeners = this[EVENT_SYM][type],
                index = listeners ? listeners.indexOf(listener) : -1;

            if (index > -1) {
                listeners.splice(index, 1);
            }
            return this;
        },

        // Simple event management - trigger a particular event
        trigger (type) {
            let event = { type };
            let listeners = this[EVENT_SYM][type] || [];

            listeners.forEach(listener => listener.call(this, event));
            return this;
        }
    };

    // Create browser instance
    let browser = new Browser;

    // Holds the fullscreen message timeout ID
    let fullscreenMessageTimeoutId;

    addEventListener("DOMContentLoaded", function () {
        // Get the UI elements
        Object.assign(this, {
            "addFavButton": document.querySelector("#addFavButton"),
            "backButton": document.querySelector("#backButton"),
            "citation": document.querySelector("#citation"),
            "clearCacheButton": document.querySelector("#clearCacheButton"),
            "clearFavButton": document.querySelector("#clearFavButton"),
            "container": document.querySelector(".container"),
            "element": document.querySelector("#browser"),
            "favButton": document.querySelector("#favButton"),
            "favicon": document.querySelector("#favicon"),
            "favList": document.querySelector("#favorites"),
            "favMenu": document.querySelector("#favMenu"),
            "forwardButton": document.querySelector("#forwardButton"),
            "fullscreenButton": document.querySelector("#goFullscreen"),
            "fullscreenMessage": document.querySelector("#fullscreenMessage"),
            "hideFullscreenLink": document.querySelector("#hideFullscreen"),
            "progressRing": document.querySelector(".ring"),
            "settingsButton": document.querySelector("#settingsButton"),
            "settingsMenu": document.querySelector("#settingsMenu"),
            "stopButton": document.querySelector("#stopButton"),
            "tweetIcon": document.querySelector("#tweet"),
            "urlInput": document.querySelector("#urlInput"),
            "webview": document.querySelector("#WebView")
        });

        // Apply the fullscreen mode
        this.applyFullscreenMode = (state) => {
            let mode = state;
            if (typeof state != "boolean") {
                mode = this.appView.isFullScreenMode;
                if (mode === this.isFullscreen) {
                    return;
                }
            }
            this.isFullscreen = mode;
            if (this.isFullscreen) {
                // Go fullscreen
                this.element.classList.add("fullscreen");
                this.fullscreenMessage.style.display = "block";
                this.fullscreenMessage.classList.add("show");
                this.fullscreenButton.textContent = "Exit full screen (F11)";

                // Clear the timeout again to ensure there are no race conditions
                clearTimeout(fullscreenMessageTimeoutId);
                fullscreenMessageTimeoutId = setTimeout(this.hideFullscreenMessage, 4e3);
            }
            else {
                // Hide fullscreen
                this.element.classList.remove("fullscreen");
                this.fullscreenMessage.style.display = "none";
                this.fullscreenButton.textContent = "Go full screen (F11)";
                this.hideFullscreenMessage();
            }
        };

        // Close the menu
        this.closeMenu = () => {
            if (!this.element.className.includes("animate")) {
                return;
            }
            let onTransitionEnd = () => {
                this.element.removeEventListener("transitionend", onTransitionEnd);
                this.togglePerspective();
                this.toggleFavMenu(true);
                this.scrollFavoritesToTop();
                this.toggleSettingsMenu(true);
            };

            this.element.addEventListener("transitionend", onTransitionEnd);
            this.togglePerspectiveAnimation();

            // Reset the title bar colors
            this.setDefaultAppBarColors();
        };

        // Handle keyboard shortcuts
        this.handleShortcuts = keyCode => {
            switch (keyCode) {
                case this.KEYS.ESC:
                    if (this.isFullscreen) {
                        this.appView.exitFullScreenMode();
                    }
                    break;

                case this.KEYS.F11:
                    this.appView[this.isFullscreen ? "exitFullScreenMode" : "tryEnterFullScreenMode"]();
                    break;

                case this.KEYS.L:
                    if (!this.isFullscreen) {
                        this.urlInput.focus();
                        this.urlInput.select();
                    }
                    break;
            }
        };

        // Hide the fullscreen message
        this.hideFullscreenMessage = () => {
            clearTimeout(fullscreenMessageTimeoutId);
            this.fullscreenMessage.classList.remove("show");
        };

        // Open the menu
        this.openMenu = () => {
            this.togglePerspective();

            setImmediate(() => {
                this.togglePerspectiveAnimation();

                // Adjust AppBar colors to match new background color
                this.setOpenMenuAppBarColors();
            });
        };

        // Apply CSS transitions when opening and closing the menus
        this.togglePerspective = () => {
            this.element.classList.toggle("modalview");
        };
        this.togglePerspectiveAnimation = () => {
            this.element.classList.toggle("animate");
        };

        // Hot key codes
        this.KEYS = { "ESC": 27, "L": 76, "F11": 122 };

        // Set the initial states
        this.backButton.disabled = true;
        this.forwardButton.disabled = true;

        // Use a proxy to workaround a WinRT issue with Object.assign
        this.titleBar = new Proxy(this.appView.titleBar, {
            "get": (target, key) => target[key],
            "set": (target, key, value) => (target[key] = value, true)
        });

        // Listen for fullscreen mode hot keys
        addEventListener("keydown", e => {
            let k = e.keyCode;
            if (k === this.KEYS.ESC || k === this.KEYS.F11 || (e.ctrlKey && k === this.KEYS.L)) {
                this.handleShortcuts(k);
            }
        });

        // Listen for a change in fullscreen mode
        this.appView.addEventListener("visibleboundschanged", () => this.applyFullscreenMode());

        // Listen for a click on the skewed container to close the menu
        this.container.addEventListener("click", () => this.closeMenu());

        // Listen for the hide fullscreen link
        this.hideFullscreenLink.addEventListener("click", () => this.appView.exitFullScreenMode());

        // Initialize fullscreen mode
        this.applyFullscreenMode(false);

        // Navigate to the start page
        this.webview.navigate("http://www.microsoft.com/");

        // Fire event
        this.trigger("init");
    }.bind(browser));

    // Export `browser`
    window.browser = browser;
})();
<commit_msg>set start page to use https<commit_after>(function () {
    "use strict";

    // Enable nodelists to work with the spread operator
    NodeList.prototype[Symbol.iterator] = Array.prototype[Symbol.iterator];

    // Event symbol
    const EVENT_SYM = Symbol("events");

    // Browser constructor
    function Browser() {
        this[EVENT_SYM] = {};
        this.currentUrl = "";
        this.faviconLocs = new Map;
        this.favorites = new Map;
        this.loading = false;
        this.isFullscreen = false;
        this.roamingFolder = Windows.Storage.ApplicationData.current.roamingFolder;
        this.appView = Windows.UI.ViewManagement.ApplicationView.getForCurrentView();
    }

    Browser.prototype = {
        constructor: Browser,

        // Simple event management - listen for a particular event
        on (type, listener) {
            let listeners = this[EVENT_SYM][type] || (this[EVENT_SYM][type] = []);

            if (listeners.indexOf(listener) < 0) {
                listeners.push(listener);
            }
            return this;
        },

        // Simple event management - stop listening for a particular event
        off (type, listener) {
            let listeners = this[EVENT_SYM][type],
                index = listeners ? listeners.indexOf(listener) : -1;

            if (index > -1) {
                listeners.splice(index, 1);
            }
            return this;
        },

        // Simple event management - trigger a particular event
        trigger (type) {
            let event = { type };
            let listeners = this[EVENT_SYM][type] || [];

            listeners.forEach(listener => listener.call(this, event));
            return this;
        }
    };

    // Create browser instance
    let browser = new Browser;

    // Holds the fullscreen message timeout ID
    let fullscreenMessageTimeoutId;

    addEventListener("DOMContentLoaded", function () {
        // Get the UI elements
        Object.assign(this, {
            "addFavButton": document.querySelector("#addFavButton"),
            "backButton": document.querySelector("#backButton"),
            "citation": document.querySelector("#citation"),
            "clearCacheButton": document.querySelector("#clearCacheButton"),
            "clearFavButton": document.querySelector("#clearFavButton"),
            "container": document.querySelector(".container"),
            "element": document.querySelector("#browser"),
            "favButton": document.querySelector("#favButton"),
            "favicon": document.querySelector("#favicon"),
            "favList": document.querySelector("#favorites"),
            "favMenu": document.querySelector("#favMenu"),
            "forwardButton": document.querySelector("#forwardButton"),
            "fullscreenButton": document.querySelector("#goFullscreen"),
            "fullscreenMessage": document.querySelector("#fullscreenMessage"),
            "hideFullscreenLink": document.querySelector("#hideFullscreen"),
            "progressRing": document.querySelector(".ring"),
            "settingsButton": document.querySelector("#settingsButton"),
            "settingsMenu": document.querySelector("#settingsMenu"),
            "stopButton": document.querySelector("#stopButton"),
            "tweetIcon": document.querySelector("#tweet"),
            "urlInput": document.querySelector("#urlInput"),
            "webview": document.querySelector("#WebView")
        });

        // Apply the fullscreen mode
        this.applyFullscreenMode = (state) => {
            let mode = state;
            if (typeof state != "boolean") {
                mode = this.appView.isFullScreenMode;
                if (mode === this.isFullscreen) {
                    return;
                }
            }
            this.isFullscreen = mode;
            if (this.isFullscreen) {
                // Go fullscreen
                this.element.classList.add("fullscreen");
                this.fullscreenMessage.style.display = "block";
                this.fullscreenMessage.classList.add("show");
                this.fullscreenButton.textContent = "Exit full screen (F11)";

                // Clear the timeout again to ensure there are no race conditions
                clearTimeout(fullscreenMessageTimeoutId);
                fullscreenMessageTimeoutId = setTimeout(this.hideFullscreenMessage, 4e3);
            }
            else {
                // Hide fullscreen
                this.element.classList.remove("fullscreen");
                this.fullscreenMessage.style.display = "none";
                this.fullscreenButton.textContent = "Go full screen (F11)";
                this.hideFullscreenMessage();
            }
        };

        // Close the menu
        this.closeMenu = () => {
            if (!this.element.className.includes("animate")) {
                return;
            }
            let onTransitionEnd = () => {
                this.element.removeEventListener("transitionend", onTransitionEnd);
                this.togglePerspective();
                this.toggleFavMenu(true);
                this.scrollFavoritesToTop();
                this.toggleSettingsMenu(true);
            };

            this.element.addEventListener("transitionend", onTransitionEnd);
            this.togglePerspectiveAnimation();

            // Reset the title bar colors
            this.setDefaultAppBarColors();
        };

        // Handle keyboard shortcuts
        this.handleShortcuts = keyCode => {
            switch (keyCode) {
                case this.KEYS.ESC:
                    if (this.isFullscreen) {
                        this.appView.exitFullScreenMode();
                    }
                    break;

                case this.KEYS.F11:
                    this.appView[this.isFullscreen ? "exitFullScreenMode" : "tryEnterFullScreenMode"]();
                    break;

                case this.KEYS.L:
                    if (!this.isFullscreen) {
                        this.urlInput.focus();
                        this.urlInput.select();
                    }
                    break;
            }
        };

        // Hide the fullscreen message
        this.hideFullscreenMessage = () => {
            clearTimeout(fullscreenMessageTimeoutId);
            this.fullscreenMessage.classList.remove("show");
        };

        // Open the menu
        this.openMenu = () => {
            this.togglePerspective();

            setImmediate(() => {
                this.togglePerspectiveAnimation();

                // Adjust AppBar colors to match new background color
                this.setOpenMenuAppBarColors();
            });
        };

        // Apply CSS transitions when opening and closing the menus
        this.togglePerspective = () => {
            this.element.classList.toggle("modalview");
        };
        this.togglePerspectiveAnimation = () => {
            this.element.classList.toggle("animate");
        };

        // Hot key codes
        this.KEYS = { "ESC": 27, "L": 76, "F11": 122 };

        // Set the initial states
        this.backButton.disabled = true;
        this.forwardButton.disabled = true;

        // Use a proxy to workaround a WinRT issue with Object.assign
        this.titleBar = new Proxy(this.appView.titleBar, {
            "get": (target, key) => target[key],
            "set": (target, key, value) => (target[key] = value, true)
        });

        // Listen for fullscreen mode hot keys
        addEventListener("keydown", e => {
            let k = e.keyCode;
            if (k === this.KEYS.ESC || k === this.KEYS.F11 || (e.ctrlKey && k === this.KEYS.L)) {
                this.handleShortcuts(k);
            }
        });

        // Listen for a change in fullscreen mode
        this.appView.addEventListener("visibleboundschanged", () => this.applyFullscreenMode());

        // Listen for a click on the skewed container to close the menu
        this.container.addEventListener("click", () => this.closeMenu());

        // Listen for the hide fullscreen link
        this.hideFullscreenLink.addEventListener("click", () => this.appView.exitFullScreenMode());

        // Initialize fullscreen mode
        this.applyFullscreenMode(false);

        // Navigate to the start page
        this.webview.navigate("https://www.microsoft.com/");

        // Fire event
        this.trigger("init");
    }.bind(browser));

    // Export `browser`
    window.browser = browser;
})();
<|endoftext|>


<commit_before>var playerPos = [50,50,0,[0,false],100];
var keys = [];
keyPressed = function() {
        keys[keyCode] = true;
};
keyReleased = function() {
        if (keys[32]===true) {
            playerPos[3][1] = true;
        }
        keys[keyCode] = false;
};
var inputHandler = function() {
        if (keys[65]===true) {
            playerPos[2]-=15;
        } if (keys[68]===true) {
            playerPos[2]+=15;
        }
        if (playerPos[2]<400) {
        playerPos[2]+=1600;
        }
        if (playerPos[2]>1575) {
        playerPos[2]-=1600;
        }
        if (playerPos[3][1]===true) {
            playerPos[3][0]+=40;
        }
        if (playerPos[3][0]>180) {
            playerPos[3][1] = false;
            playerPos[3][0] = 0;
        }
};
var area = 0;
var areas = [
    [
    [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],
    [1,9,0,0,0,0,1,0,0,0,0,0,0,0,0,1],
    [1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1],
    [1,0,0,0,0,0,2,0,0,0,0,0,3,0,0,1],
    [1,0,0,4,0,0,2,0,0,0,0,0,0,0,0,1],
    [1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1],
    [1,0,4,0,0,0,1,0,0,0,0,0,0,0,0,1],
    [1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1],
    [1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1],
    [1,1,2,2,1,1,1,1,1,2,2,1,1,1,1,1],
    [1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1],
    [1,0,0,0,0,0,1,0,0,0,0,0,3,0,0,1],
    [1,0,0,3,0,0,2,0,0,0,0,3,0,0,0,1],
    [1,0,0,0,0,0,2,0,0,0,3,0,0,0,0,1],
    [1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1],
    [1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1],

],
[
    [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],
    [1,9,0,0,0,0,0,0,0,0,0,0,0,0,0,1],
    [1,0,0,0,0,4,0,0,0,0,4,0,0,0,0,1],
    [1,0,0,0,0,0,0,4,0,0,0,0,4,0,0,1],
    [1,0,0,4,0,0,4,0,0,0,0,0,1,2,2,1],
    [1,0,0,0,0,0,1,1,1,2,2,1,1,0,0,1],
    [1,2,2,2,1,1,1,3,0,0,0,0,0,0,0,1],
    [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1],
    [1,0,0,0,0,0,0,0,3,0,0,0,0,0,0,1],
    [1,0,0,0,0,3,0,0,3,0,0,0,0,3,0,1],
    [1,0,0,0,3,3,0,0,0,0,0,0,0,0,0,1],
    [1,0,0,0,0,0,0,0,0,0,0,0,3,0,0,1],
    [1,0,0,3,0,0,0,0,0,0,0,3,0,0,0,1],
    [1,0,0,0,0,0,0,0,0,0,3,0,0,1,1,1],
    [1,0,0,0,0,0,3,0,0,0,0,0,0,0,0,1],
    [1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1],

],
];
var Timeout = -1;
var mobs = [];
var AIs = function() {
    for (var k = 0; k < mobs.length; k++) {
        if (mobs[k][2]>0) {
            if (mobs[k][3]===0&&mobs[k][5]===true){
                if (dist(playerPos[0],playerPos[1],mobs[k][0],mobs[k][1])<10) {
                    playerPos[4]--;
                }
                for (var h = 0 ; h <mobs.length;h++) {
                    if (min(dist(mobs[k][0],mobs[k][1],playerPos[0],playerPos[1]),dist(mobs[h][0],mobs[h][1],playerPos[0],playerPos[1]))===dist(mobs[k][0],mobs[k][1],playerPos[0],playerPos[1])) {
                        if (mobs[k][0]>playerPos[0]) {
                            mobs[k][0]-=0.15;
                        } else {
                            mobs[k][0]+=0.15;
                        }
                        if (mobs[k][1]>playerPos[1]) {
                            mobs[k][1]-=0.15;
                        } else {
                            mobs[k][1]+=0.15;
                        }
                    }
                }
            }
            if (mobs[k][5]===false&&mobs[k][3]===0) {
                if (dist(playerPos[0],playerPos[1],mobs[k][0],mobs[k][1])<75) {
                    mobs[k][5]=true;
                }
                mobs[k][4][2]--;
                if (mobs[k][4][2]<=0) {
                    mobs[k][4][2]= random(0,50);
                    mobs[k][4][0]= random(-0.5,0.5);
                    mobs[k][4][1]= random(-0.5,0.5);

                }
                mobs[k][0]+=mobs[k][4][0];
                mobs[k][1]+=mobs[k][4][1];
            }
            if (mobs[k][3]===1) {
                mobs[k][4][2]--;
                if (mobs[k][4][2]<=0) {
                    mobs[k][4][2]= random(0,50);
                    mobs[k][4][0]= random(-1,1);
                    mobs[k][4][1]= random(-1,1);

                }
                mobs[k][0]+=mobs[k][4][0];
                mobs[k][1]+=mobs[k][4][1];
            }
            for (var j = 0; j < areas[area].length;j++) {
                for (var i = 0; i < areas[area][j].length;i++) {
                    var x = i*25;
                    var y = j*25;
                    if (areas[area][j][i]===1) {
                        if (mobs[k][0]>=x&&mobs[k][0]<x+25&&mobs[k][1]<y+5&&mobs[k][1]>y-5) {
                            mobs[k][1] = y-5;
                        }
                        if (mobs[k][0]>=x&&mobs[k][0]<x+25&&mobs[k][1]<y+30&&mobs[k][1]>y+20) {
                            mobs[k][1] = y+30;
                        }
                        if (mobs[k][0]>x-5&&mobs[k][0]<x+5&&mobs[k][1]<=y+25&&mobs[k][1]>=y) {
                            mobs[k][0] = x-5;
                        }
                        if (mobs[k][0]>x+20&&mobs[k][0]<x+30&&mobs[k][1]<=y+25&&mobs[k][1]>=y) {
                            mobs[k][0] = x+30;
                        }
                    }
                    if (areas[area][j][i]===2&&dist(x+12,y+12,playerPos[0],playerPos[1])>75) {

                        if (mobs[k][0]>=x&&mobs[k][0]<x+25&&mobs[k][1]<y+5&&mobs[k][1]>y-5) {
                            mobs[k][1] = y-5;
                        }
                        if (mobs[k][0]>=x&&mobs[k][0]<x+25&&mobs[k][1]<y+30&&mobs[k][1]>y+20) {
                            mobs[k][1] = y+30;
                        }
                        if (mobs[k][0]>x-5&&mobs[k][0]<x+5&&mobs[k][1]<=y+25&&mobs[k][1]>=y) {
                            mobs[k][0] = x-5;
                        }
                        if (mobs[k][0]>x+20&&mobs[k][0]<x+30&&mobs[k][1]<=y+25&&mobs[k][1]>=y) {
                            mobs[k][0] = x+30;
                        }
                    }

                }
            }
        }
    }
};
var backdrop = function() {
    var areaColors = [[color(170, 236, 247),color(11, 82, 56),true],[color(50,50,50),color(0,0,0),false]];
    background(areaColors[area][0]);
    if (areaColors[area][2]===true) {
    fill(255, 213, 0);
    ellipse(600-playerPos[2],100,150,150);

    }
    fill(areaColors[area][1]);
    rect(0,200,width,200);
    };
var areaMapHandler = function() {
    Timeout++;
    fill(0,0,0);
    rect(0,400,width,200);
    var size = 200/max(areas[area].length,areas[area][0].length);
    var playerDivider = [playerPos[0]*200/(areas[area][0].length*25),playerPos[1]*200/(areas[area].length*25)];
    noStroke();
    if (playerPos[4]<=0) {
        Timeout = -1;
        mobs = [];
    }
    if (playerPos[1]>areas[area].length*25) {
        area++;
        Timeout = -1;
        mobs = [];
    }
    if (playerPos[1]<0) {
        area--;
        Timeout = -1;
        mobs= [];
    }
    for (var j = 0; j < areas[area].length;j++) {
        for (var i = 0; i < areas[area][j].length;i++) {
            if (areas[area][j][i]===9&&Timeout<=0) {
                playerPos = [i*25,j*25,0,[0,false],100];
            }
            if (areas[area][j][i]===1) {
                fill(255, 255, 255);
                rect(100+i*size,400+j*size,size,size);
                var x = i*25;
                var y = j*25;
                if (dist(playerPos[0],playerPos[1],x,y)<75) {
                    if (playerPos[0]>=x&&playerPos[0]<x+25&&playerPos[1]<y+5&&playerPos[1]>y-5) {
                        playerPos[1] = y-5;
                    }
                    if (playerPos[0]>=x&&playerPos[0]<x+25&&playerPos[1]<y+30&&playerPos[1]>y+20) {
                        playerPos[1] = y+30;
                    }
                    if (playerPos[0]>x-5&&playerPos[0]<x+5&&playerPos[1]<=y+25&&playerPos[1]>=y) {
                        playerPos[0] = x-5;
                    }
                    if (playerPos[0]>x+20&&playerPos[0]<x+30&&playerPos[1]<=y+25&&playerPos[1]>=y) {
                        playerPos[0] = x+30;
                    }
                }
            }
            if (areas[area][j][i]===3&&Timeout===0) {
                mobs.push([i*25,j*25,100,0,[random(-0.5,0.5),random(-0.5,0.5),random(0,50)],false]);
            }
            if (areas[area][j][i]===4&&Timeout===0) {
                mobs.push([i*25,j*25,100,1,[random(-0.5,0.5),random(-0.5,0.5),random(0,50)]]);
            }
        }
    }
    for (var k = 0; k < mobs.length; k++) {
            var mobDivider = [mobs[k][0]*200/(areas[area][0].length*25),mobs[k][1]*200/(areas[area].length*25)];
            if (mobs[k][2]>0&&mobs[k][3]===1) {
                fill(0,255, 0);
                ellipse((mobDivider[0])+100,(mobDivider[1])+400,size/2,size/2);
            }
            if (mobs[k][2]>0&&mobs[k][3]===0) {
                fill(255,0,0);
                ellipse((mobDivider[0])+100,(mobDivider[1])+400,size/2,size/2);
            }
    }
    fill(0,255,0);
    pushMatrix();
    translate((playerDivider[0])+100,(playerDivider[1])+400);
    rotate((playerPos[2]+400)*360/1600);
    quad(-6,3,0,0,6,3,0,-10);
    popMatrix();
    //ellipse((playerDivider[0])+100,(playerDivider[1])+400,10,10);
};
var perspectiveGenerator = function(pointOriginX,pointOriginY,xPan) {
    var ray = function(x,y,xPanPos) {
        var rectsize = 200;
        var recttype= 0;
        var rectfills = [color(255,255,255),color(255,0,0),color(255, 0, 255),color(0,255,0)];
        for (var k = 20; k > 0; k --) {
            var pointCalc = [pointOriginX+(((pointOriginX-x)/20)*k),pointOriginY+(((pointOriginY-y)/20)*k)];
            if (playerPos[2]-200>xPanPos&&playerPos[2]-200<xPanPos+25&&k<2&&keys[87]===true) {
                playerPos[0]+=(pointCalc[0]-playerPos[0])/4;
                playerPos[1]+=(pointCalc[1]-playerPos[1])/4;

            }
            if (playerPos[2]-200>xPanPos&&playerPos[2]-200<xPanPos+25&&k<2&&keys[83]===true) {
                playerPos[0]-=(pointCalc[0]-playerPos[0])/4;
                playerPos[1]-=(pointCalc[1]-playerPos[1])/4;
            }
            for (var j = 0; j < areas[area].length;j++) {
                for (var i = 0; i < areas[area][0].length;i++) {
                    var bx = i*25;
                    var by= j*25;
                    if (areas[area][j][i]===1) {
                        if (pointCalc[0]>bx&&pointCalc[0]<=bx+25&&pointCalc[1]>by&&pointCalc[1]<=by+25&&dist(pointOriginX,pointOriginY,bx,by)<200) {
                            noStroke();
                            rectsize = dist(pointOriginX,pointOriginY,pointCalc[0],pointCalc[1]);

                            recttype = 0;
                        }
                    }
                    if (areas[area][j][i]===2&&dist(bx,by,playerPos[0],playerPos[1])>75) {
                        if (pointCalc[0]>bx&&pointCalc[0]<=bx+25&&pointCalc[1]>by&&pointCalc[1]<=by+25&&dist(pointOriginX,pointOriginY,bx,by)<200) {
                            noStroke();
                            rectsize = dist(pointOriginX,pointOriginY,pointCalc[0],pointCalc[1]);

                            recttype = 2;
                        }
                    }

                }
            }
            for (var h = 0; h < mobs.length;h++) {
                if ((xPan-xPanPos)>-25&&(xPan-xPanPos)<425&&playerPos[3][1]===true&&k<3&&recttype===1) {
                    if (dist(mobs[h][0],mobs[h][1],pointCalc[0],pointCalc[1])<=20&&mobs[h][3]===0) {
                        mobs[h][2]--;
                    }
                }
                if (dist(mobs[h][0],mobs[h][1],pointCalc[0],pointCalc[1])<=10&&mobs[h][2]>0&&mobs[h][3]===0) {
                    rectsize = dist(playerPos[0],playerPos[1],pointCalc[0],pointCalc[1]);
                    recttype = 1;
                }
                if (dist(mobs[h][0],mobs[h][1],pointCalc[0],pointCalc[1])<=10&&mobs[h][2]>0&&mobs[h][3]===1) {
                    rectsize = dist(playerPos[0],playerPos[1],pointCalc[0],pointCalc[1]);
                    recttype = 3;
                }
            }
        }
        if ((xPan-xPanPos)>-25&&(xPan-xPanPos)<425) {
            fill(rectfills[recttype]);
            rect(400-(xPan-xPanPos),rectsize,20,(200-(rectsize))*2);
            fill(0,0,0,rectsize);
            rect(400-(xPan-xPanPos),rectsize,20,(200-(rectsize))*2);

        }
    };
    for (var p = -20; p < 120;p++) {
        if (p<0) {
            ray(pointOriginX-200,pointOriginY+(400-(p*20+400)-200),p*20);
        } else if (p<20) {
            ray(pointOriginX+(p*20-200),pointOriginY-200,p*20);
        } else if (p<40) {
            ray(pointOriginX+200,pointOriginY+(p*20-400)-200,p*20);
        } else if (p<60) {
            ray(pointOriginX+(1200-p*20)-200,pointOriginY+200,p*20);
        } else if (p<80) {
            ray(pointOriginX-200,pointOriginY+(1600-p*20)-200,p*20);
        } else if (p<100) {
            //ray(2000-p*20,pointOriginY-200,p*20);
        }
    }
    fill(0,0,0);
    rect(0,0,200,25);
    fill(0,255,0);
    arc(200,420,600,250,playerPos[3][0]+132,playerPos[3][0]+180);
    rect(0,0,playerPos[4]*2,25);
};
draw = function() {
    inputHandler();
    backdrop();
    perspectiveGenerator(playerPos[0],playerPos[1],playerPos[2]);
    areaMapHandler();
    AIs();
};
<commit_msg>Delete main.js<commit_after><|endoftext|>


<commit_before>// @flow

import * as React from 'react'
import {View, StyleSheet} from 'react-native'
import * as c from '../components/colors'
import {SearchBar} from '../components/searchbar'
import sortBy from 'lodash/sortBy'
import type {Building} from './types'
import {GrabberBar} from './grabber'
import {BuildingList} from './building-list'

type Props = {
	viewState: 'min' | 'mid' | 'max',
	buildings: Array<Building>,
	onFocus: () => any,
	onCancel: () => any,
	onSelect: string => any,
	expandMin: () => any,
	expandMid: () => any,
	expandMax: () => any,
}

type State = {
	query: string,
}

export class BuildingPicker extends React.Component<Props, State> {
	state = {
		query: '',
	}

	componentWillReceiveProps(nextProps: Props) {
		if (
			this.props.viewState === 'max' &&
			this.props.viewState !== nextProps.viewState
		) {
			this.dismissKeyboard()
		}
	}

	searchBar: any = null

	dismissKeyboard = () => {
		this.searchBar.unFocus()
	}

	onSearch = (text: ?string) => {
		let query = text || ''
		this.setState(() => ({query: query.toLowerCase()}))
	}

	performSearch = (text: string) => {
		// Android clear button returns an object
		if (typeof text !== 'string') {
			return this.onSearch(null)
		}

		return this.onSearch(text)
	}

	onSelectBuilding = (id: string) => this.props.onSelect(id)

	render() {
		const {viewState} = this.props

		const search = (
			<SearchBar
				getRef={ref => (this.searchBar = ref)}
				onCancel={this.props.onCancel}
				onChangeText={this.performSearch}
				onFocus={this.props.onFocus}
				onSearchButtonPress={this.dismissKeyboard}
				placeholder="Search for a place"
				style={styles.searchBox}
				textFieldBackgroundColor={c.iosGray}
			/>
		)

		let matches = this.state.query
			? this.props.buildings.filter(b =>
					b.name.toLowerCase().startsWith(this.state.query),
				)
			: this.props.buildings

		matches = sortBy(matches, m => m.name)

		if (viewState === 'min') {
			return (
				<View style={[styles.overlay, styles.overlayMin]}>
					<GrabberBar onPress={this.props.expandMid} />
					{search}
				</View>
			)
		} else if (viewState === 'mid') {
			return (
				<View style={[styles.overlay, styles.overlayMid]}>
					<GrabberBar onPress={this.props.expandMax} />
					{search}
					<BuildingList buildings={matches} onSelect={this.onSelectBuilding} />
				</View>
			)
		} else if (viewState === 'max') {
			return (
				<View style={[styles.overlay, styles.overlayMax]}>
					<GrabberBar onPress={this.props.expandMin} />
					{search}
					<BuildingList buildings={matches} onSelect={this.onSelectBuilding} />
				</View>
			)
		}
	}
}

const styles = StyleSheet.create({
	searchBox: {
		marginHorizontal: 6,
	},
	overlay: {
		backgroundColor: c.white,
		borderTopLeftRadius: 10,
		borderTopRightRadius: 10,
		bottom: 0,
		left: 0,
		paddingHorizontal: 0,
		paddingTop: 0,
		position: 'absolute',
		right: 0,
		shadowColor: c.black,
		shadowOffset: {height: -4},
		shadowOpacity: 0.15,
		shadowRadius: 4,
		zIndex: 2,
	},
	overlayMin: {
		height: 80,
	},
	overlayMid: {
		height: 200,
	},
	overlayMax: {
		top: 20,
	},
})
<commit_msg>Use category picker in map filtering and searching<commit_after>// @flow

import * as React from 'react'
import {View, StyleSheet} from 'react-native'
import * as c from '../components/colors'
import {SearchBar} from '../components/searchbar'
import sortBy from 'lodash/sortBy'
import type {Building} from './types'
import {GrabberBar} from './grabber'
import {CategoryPicker} from './category-picker'
import {BuildingList} from './building-list'

type Props = {
	viewState: 'min' | 'mid' | 'max',
	buildings: Array<Building>,
	onFocus: () => any,
	onCancel: () => any,
	onSelect: string => any,
	expandMin: () => any,
	expandMid: () => any,
	expandMax: () => any,
}

type State = {
	query: string,
	category: string,
}

export class BuildingPicker extends React.Component<Props, State> {
	state = {
		query: '',
		category: 'Buildings',
	}

	componentWillReceiveProps(nextProps: Props) {
		if (
			this.props.viewState === 'max' &&
			this.props.viewState !== nextProps.viewState
		) {
			this.dismissKeyboard()
		}
	}

	searchBar: any = null

	dismissKeyboard = () => {
		this.searchBar.unFocus()
	}

	onSearch = (text: ?string) => {
		let query = text || ''
		this.setState(() => ({query: query.toLowerCase()}))
	}

	performSearch = (text: string) => {
		// Android clear button returns an object
		if (typeof text !== 'string') {
			return this.onSearch(null)
		}

		return this.onSearch(text)
	}

	onSelectBuilding = (id: string) => this.props.onSelect(id)

	onCategoryChange = (category: string) => {
		this.setState(() => ({category}))
	}

	allCategories = ['Buildings', 'Outdoors', 'Parking', 'Athletics']
	categoryLookup = {
		Buildings: 'building',
		Outdoors: 'outdoors',
		Parking: 'parking',
		Athletics: 'athletics',
	}

	render() {
		const {viewState} = this.props

		const search = (
			<SearchBar
				getRef={ref => (this.searchBar = ref)}
				onCancel={this.props.onCancel}
				onChangeText={this.performSearch}
				onFocus={this.props.onFocus}
				onSearchButtonPress={this.dismissKeyboard}
				placeholder="Search for a place"
				style={styles.searchBox}
				textFieldBackgroundColor={c.iosGray}
			/>
		)

		const picker =
			this.state.query.length < 1 ? (
				<CategoryPicker
					categories={this.allCategories}
					onChange={this.onCategoryChange}
					selected={this.state.category}
				/>
			) : null

		let matches = this.state.query
			? this.props.buildings.filter(b =>
					b.name.toLowerCase().startsWith(this.state.query),
				)
			: this.props.buildings

		if (!this.state.query) {
			const selectedCategory = this.categoryLookup[this.state.category]
			matches = matches.filter(b => b.categories[selectedCategory])
		}

		matches = sortBy(matches, m => m.name)

		if (viewState === 'min') {
			return (
				<View style={[styles.overlay, styles.overlayMin]}>
					<GrabberBar onPress={this.props.expandMid} />
					{search}
				</View>
			)
		} else if (viewState === 'mid') {
			return (
				<View style={[styles.overlay, styles.overlayMid]}>
					<GrabberBar onPress={this.props.expandMax} />
					{search}
					{picker}
					<BuildingList buildings={matches} onSelect={this.onSelectBuilding} />
				</View>
			)
		} else if (viewState === 'max') {
			return (
				<View style={[styles.overlay, styles.overlayMax]}>
					<GrabberBar onPress={this.props.expandMin} />
					{search}
					{picker}
					<BuildingList buildings={matches} onSelect={this.onSelectBuilding} />
				</View>
			)
		}
	}
}

const styles = StyleSheet.create({
	searchBox: {
		marginHorizontal: 6,
	},
	overlay: {
		backgroundColor: c.white,
		borderTopLeftRadius: 10,
		borderTopRightRadius: 10,
		bottom: 0,
		left: 0,
		paddingHorizontal: 0,
		paddingTop: 0,
		position: 'absolute',
		right: 0,
		shadowColor: c.black,
		shadowOffset: {height: -4},
		shadowOpacity: 0.15,
		shadowRadius: 4,
		zIndex: 2,
	},
	overlayMin: {
		height: 80,
	},
	overlayMid: {
		height: 200,
	},
	overlayMax: {
		top: 20,
	},
})
<|endoftext|>


<commit_before>/*
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

/*
 * Copyright 2020 Joyent, Inc.
 */

var net = require('net');
var os = require('os');
var path = require('path');

var apertureConfig = require('aperture-config').config;
var assert = require('assert-plus');
var bunyan = require('bunyan');
var cueball = require('cueball');
var dashdash = require('dashdash');
var dtrace = require('dtrace-provider');
var jsprim = require('jsprim');
var kang = require('kang');
var keyapi = require('keyapi');
var libmanta = require('libmanta');
var mahi = require('mahi');
var once = require('once');
var restify = require('restify');
var vasync = require('vasync');

var app = require('./lib');

///--- Internal Functions

function getMuskieOptions() {
    var options = [
        {
            names: ['file', 'f'],
            type: 'string',
            help: 'Configuration file to use.',
            helpArg: 'FILE'
        },
        {
            names: ['insecure-port', 'i'],
            type: 'positiveInteger',
            help: 'Listen for insecure requests on port.',
            helpArg: 'PORT'
        },
        {
            names: ['port', 'p'],
            type: 'positiveInteger',
            help: 'Listen for secure requests on port.',
            helpArg: 'PORT'
        },
        {
            names: ['verbose', 'v'],
            type: 'arrayOfBool',
            help: 'Verbose output. Use multiple times for more verbose.'
        }
    ];

    return (options);
}

/**
 * Command line option parsing and checking.
 *
 * @returns {Object} A object representing the command line options.
 */
function parseOptions() {
    var opts;
    var parser = new dashdash.Parser({options: getMuskieOptions()});

    try {
        opts = parser.parse(process.argv);
        assert.object(opts, 'options');
    } catch (e) {
        usage(parser, e.message);
    }

    if (!opts.file) {
        usage(parser, '-f option is required');
    }

    return (opts);
}

function usage(parser, message)
{
    console.error('muskie: %s', message);
    console.error('usage: node main.js OPTIONS\n');
    console.error(parser.help());
    process.exit(2);
}

function createMonitoringServer(cfg) {
    /*
     * Set up the monitoring server. This exposes a cueball kang monitoring
     * listener and an artedi-based metric collector.
     *
     * The cueball monitoring listener serves information about the cueball
     * Pools and Sets for connections to mahi, sharks, other services, and also
     * the moray client connections.
     *
     * The artedi-based metric collector is used to track various muskie
     * metrics including operation latency, and request counts.
     */
    var kangOpts;
    var monitorServer;
    var port;
    kangOpts = cueball.poolMonitor.toKangOptions();
    port = cfg.port + 800;

    monitorServer = restify.createServer({ serverName: 'Monitor' });
    monitorServer.get('/metrics', app.getMetricsHandler(cfg.collector));
    monitorServer.get(new RegExp('.*'), kang.knRestifyHandler(kangOpts));

    monitorServer.listen(port, '0.0.0.0', function () {
        cfg.log.info('monitoring server started on port %d', port);
    });
}

function createCueballSharkAgent(sharkCfg) {
    var sharkCueball = {
        resolvers: sharkCfg.resolvers,

        spares: sharkCfg.spares,
        maximum: sharkCfg.maximum,
        /*
         * Note that this path doesn't actually have to be handled by the
         * authcache (any non-5xx response code is accepted, e.g. 404 is fine).
         */
        ping: sharkCfg.ping,
        pingInterval: sharkCfg.pingInterval,
        tcpKeepAliveInitialDelay: sharkCfg.maxIdleTime,

        log: sharkCfg.log,
        recovery: {
            default: {
                retries: sharkCfg.retry.retries,
                timeout: sharkCfg.connectTimeout,
                maxTimeout: sharkCfg.maxTimeout,
                delay: sharkCfg.delay
            },
            /*
             * Avoid SRV retries, since authcache doesn't currently register
             * any useable SRV records for HTTP (it only registers redis).
             */
            'dns_srv': {
                retries: 0,
                timeout: sharkCfg.connectTimeout,
                maxTimeout: sharkCfg.maxTimeout,
                delay: 0
            }
        }
    };

    return (new cueball.HttpAgent(sharkCueball));
}

function onPickerConnect(clients, pickerClient) {
    clients.picker = pickerClient;
}

function createPickerClient(cfg, log, onConnect) {
    var opts = {
        interval: cfg.interval,
        lag: cfg.lag,
        moray: cfg.moray,
        log: log.child({component: 'picker'}, true),
        multiDC: cfg.multiDC,
        defaultMaxStreamingSizeMB: cfg.defaultMaxStreamingSizeMB,
        maxUtilizationPct: cfg.maxUtilizationPct,
        maxOperatorUtilizationPct: cfg.maxOperatorUtilizationPct
    };

    var client = app.picker.createClient(opts);

    client.once('connect', function _onConnect() {
        log.info('picker connected %s', client.toString());
        onConnect(client);
    });
}

function createAuthCacheClient(authCfg, agent) {
    assert.object(authCfg, 'authCfg');
    assert.string(authCfg.url, 'authCfg.url');
    assert.optionalObject(authCfg.typeTable, 'authCfg.typeTable');

    var options = jsprim.deepCopy(authCfg);
    var log = authCfg.log.child({component: 'mahi'}, true);
    options.log = log;

    options.typeTable = options.typeTable || apertureConfig.typeTable || {};
    options.agent = agent;

    return (mahi.createClient(options));
}

function createKeyAPIClient(opts, clients) {
    var log = opts.log.child({component: 'keyapi'}, true);
    var _opts = {
        log: log,
        ufds: opts.ufds
    };

    return (new keyapi(_opts));
}

function onMorayConnect(clients, barrier, morayClient) {
    clients.moray = morayClient;
    barrier.done('createMorayClient');
}

function createMorayClient(cfg, onConnect) {
    assert.object(cfg, 'cfg');
    assert.object(cfg.collector, 'cfg.collector');
    assert.object(cfg.moray, 'cfg.moray');
    assert.object(cfg.moray.log, 'cfg.moray.log');
    assert.object(cfg.moray.morayOptions, 'cfg.moray.morayOptions');

    var opts = cfg.moray;
    var log = opts.log = cfg.moray.log.child({component: 'moray'}, true);
    opts.morayOptions.collector = cfg.collector;

    var client = new libmanta.createMorayClient(opts);

    client.once('error', function (err) {
        client.removeAllListeners('connect');

        log.error(err, 'moray: failed to connect');
    });

    client.once('connect', function _onConnect() {
        client.removeAllListeners('error');

        log.info({
            host: opts.host,
            port: opts.port
        }, 'moray: connected');

        onConnect(client);
    });
}

function clientsConnected(appName, cfg, clients) {
    var server1, server2;
    var log = cfg.log;

    log.info('requisite client connections established, '
    + 'starting muskie servers');

    server1 = app.createServer(cfg, clients, 'ssl');
    server1.on('error', function (err) {
        log.fatal(err, 'server (secure) error');
        process.exit(1);
    });
    server1.listen(cfg.port, function () {
        log.info('%s listening at (trusted port) %s', appName, server1.url);
    });

    server2 = app.createServer(cfg, clients, 'insecure');
    server2.on('error', function (err) {
        log.fatal(err, 'server (clear) error');
        process.exit(1);
    });
    server2.listen(cfg.insecurePort, function () {
        log.info('%s listening at (clear port) %s', appName, server2.url);
    });

    app.startKangServer();
}

///--- Mainline

(function main() {
    const muskie = 'muskie';

    // Parent object for client connection objects.
    var clients = {};

    // DTrace probe setup
    var dtp = dtrace.createDTraceProvider(muskie);
    var client_close = dtp.addProbe('client_close', 'json');
    var socket_timeout = dtp.addProbe('socket_timeout', 'json');

    client_close.dtp = dtp;
    socket_timeout.dtp = dtp;
    dtp.enable();

    const dtProbes = {
        client_close: client_close,
        socket_timeout: socket_timeout
    };

    const opts = parseOptions();
    const cfg = app.configure(muskie, opts, dtProbes);

    /*
     * Create a barrier to ensure client connections that are established
     * asynchronously and are required for muskie to serve a minimal subset of
     * requests are ready prior to starting up the restify servers.
     */
    var barrier = vasync.barrier();

    barrier.on('drain', clientsConnected.bind(null, muskie, cfg, clients));

    /*
     * Establish minimal set of client connections required to begin
     * successfully servicing read requests.
     */

    clients.agent = new cueball.HttpAgent(cfg.cueballHttpAgent);
    clients.mahi = createAuthCacheClient(cfg.auth, clients.agent);

    barrier.start('createMorayClient');
    createMorayClient(cfg, onMorayConnect.bind(null, clients, barrier));

    // Establish other client connections needed for write requests.
    createPickerClient(cfg.storage, cfg.log,
        onPickerConnect.bind(null, clients));
    clients.sharkAgent = createCueballSharkAgent(cfg.sharkConfig);
    clients.keyapi = createKeyAPIClient(cfg);

    // Create monitoring server
    createMonitoringServer(cfg);

    process.on('SIGHUP', process.exit.bind(process, 0));

})();
<commit_msg>MANTA-5345 Muskie hits out of memory error during shard async peer promotion (#75)<commit_after>/*
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

/*
 * Copyright 2020 Joyent, Inc.
 */

var net = require('net');
var os = require('os');
var path = require('path');

var apertureConfig = require('aperture-config').config;
var assert = require('assert-plus');
var bunyan = require('bunyan');
var cueball = require('cueball');
var dashdash = require('dashdash');
var dtrace = require('dtrace-provider');
var jsprim = require('jsprim');
var kang = require('kang');
var keyapi = require('keyapi');
var libmanta = require('libmanta');
var mahi = require('mahi');
var once = require('once');
var restify = require('restify');
var vasync = require('vasync');

var app = require('./lib');

///--- Internal Functions

function getMuskieOptions() {
    var options = [
        {
            names: ['file', 'f'],
            type: 'string',
            help: 'Configuration file to use.',
            helpArg: 'FILE'
        },
        {
            names: ['insecure-port', 'i'],
            type: 'positiveInteger',
            help: 'Listen for insecure requests on port.',
            helpArg: 'PORT'
        },
        {
            names: ['port', 'p'],
            type: 'positiveInteger',
            help: 'Listen for secure requests on port.',
            helpArg: 'PORT'
        },
        {
            names: ['verbose', 'v'],
            type: 'arrayOfBool',
            help: 'Verbose output. Use multiple times for more verbose.'
        }
    ];

    return (options);
}

/**
 * Command line option parsing and checking.
 *
 * @returns {Object} A object representing the command line options.
 */
function parseOptions() {
    var opts;
    var parser = new dashdash.Parser({options: getMuskieOptions()});

    try {
        opts = parser.parse(process.argv);
        assert.object(opts, 'options');
    } catch (e) {
        usage(parser, e.message);
    }

    if (!opts.file) {
        usage(parser, '-f option is required');
    }

    return (opts);
}

function usage(parser, message)
{
    console.error('muskie: %s', message);
    console.error('usage: node main.js OPTIONS\n');
    console.error(parser.help());
    process.exit(2);
}

function createMonitoringServer(cfg) {
    /*
     * Set up the monitoring server. This exposes a cueball kang monitoring
     * listener and an artedi-based metric collector.
     *
     * The cueball monitoring listener serves information about the cueball
     * Pools and Sets for connections to mahi, sharks, other services, and also
     * the moray client connections.
     *
     * The artedi-based metric collector is used to track various muskie
     * metrics including operation latency, and request counts.
     */
    var kangOpts;
    var monitorServer;
    var port;
    kangOpts = cueball.poolMonitor.toKangOptions();
    port = cfg.port + 800;

    monitorServer = restify.createServer({ serverName: 'Monitor' });
    monitorServer.get('/metrics', app.getMetricsHandler(cfg.collector));
    monitorServer.get(new RegExp('.*'), kang.knRestifyHandler(kangOpts));

    monitorServer.listen(port, '0.0.0.0', function () {
        cfg.log.info('monitoring server started on port %d', port);
    });
}

function createCueballSharkAgent(sharkCfg) {
    var sharkCueball = {
        resolvers: sharkCfg.resolvers,

        spares: sharkCfg.spares,
        maximum: sharkCfg.maximum,
        /*
         * Note that this path doesn't actually have to be handled by the
         * authcache (any non-5xx response code is accepted, e.g. 404 is fine).
         */
        ping: sharkCfg.ping,
        pingInterval: sharkCfg.pingInterval,
        tcpKeepAliveInitialDelay: sharkCfg.maxIdleTime,

        log: sharkCfg.log,
        recovery: {
            default: {
                retries: sharkCfg.retry.retries,
                timeout: sharkCfg.connectTimeout,
                maxTimeout: sharkCfg.maxTimeout,
                delay: sharkCfg.delay
            },
            /*
             * Avoid SRV retries, since authcache doesn't currently register
             * any useable SRV records for HTTP (it only registers redis).
             */
            'dns_srv': {
                retries: 0,
                timeout: sharkCfg.connectTimeout,
                maxTimeout: sharkCfg.maxTimeout,
                delay: 0
            }
        }
    };

    return (new cueball.HttpAgent(sharkCueball));
}

function onPickerConnect(clients, pickerClient) {
    clients.picker = pickerClient;
}

function createPickerClient(cfg, log, onConnect) {
    var opts = {
        interval: cfg.interval,
        lag: cfg.lag,
        moray: cfg.moray,
        log: log.child({component: 'picker'}, true),
        multiDC: cfg.multiDC,
        defaultMaxStreamingSizeMB: cfg.defaultMaxStreamingSizeMB,
        maxUtilizationPct: cfg.maxUtilizationPct,
        maxOperatorUtilizationPct: cfg.maxOperatorUtilizationPct
    };

    var client = app.picker.createClient(opts);

    client.once('connect', function _onConnect() {
        log.info('picker connected %s', client.toString());
        onConnect(client);
    });
}

function createAuthCacheClient(authCfg, agent) {
    assert.object(authCfg, 'authCfg');
    assert.string(authCfg.url, 'authCfg.url');
    assert.optionalObject(authCfg.typeTable, 'authCfg.typeTable');

    var options = jsprim.deepCopy(authCfg);
    var log = authCfg.log.child({component: 'mahi'}, true);
    options.log = log;

    options.typeTable = options.typeTable || apertureConfig.typeTable || {};
    options.agent = agent;

    return (mahi.createClient(options));
}

function createKeyAPIClient(opts, clients) {
    var log = opts.log.child({component: 'keyapi'}, true);
    var _opts = {
        log: log,
        ufds: opts.ufds
    };

    return (new keyapi(_opts));
}

function onMorayConnect(clients, barrier, morayClient) {
    clients.moray = morayClient;
    barrier.done('createMorayClient');
}

function createMorayClient(cfg, onConnect) {
    assert.object(cfg, 'cfg');
    assert.object(cfg.collector, 'cfg.collector');
    assert.object(cfg.moray, 'cfg.moray');
    assert.object(cfg.moray.log, 'cfg.moray.log');
    assert.object(cfg.moray.morayOptions, 'cfg.moray.morayOptions');

    var opts = cfg.moray;
    var log = opts.log = cfg.moray.log.child({component: 'moray'}, true);
    opts.morayOptions.collector = cfg.collector;

    var client = new libmanta.createMorayClient(opts);

    client.once('error', function (err) {
        client.removeAllListeners('connect');

        log.error(err, 'moray: failed to connect');
    });

    client.once('connect', function _onConnect() {
        client.removeAllListeners('error');

        log.info({
            host: opts.host,
            port: opts.port
        }, 'moray: connected');

        onConnect(client);
    });
}

function clientsConnected(appName, cfg, clients) {
    var server1, server2;
    var log = cfg.log;

    log.info('requisite client connections established, '
    + 'starting muskie servers');

    server1 = app.createServer(cfg, clients, 'ssl');
    server1.on('error', function onSslServerErr(errOrReq, _res, _err, cb) {
        // HACK to ignore unintended server "error" events due to a subtle
        // bug in restify. http://restify.com/docs/server-api/#errors supports
        // a feature where you can do this:
        //      server.on('<error name>', function (req, res, err, cb) {...});
        // to get an event for particular error cases. That "<error name>"
        // is match against `err.name` from any Error returned from a
        // restify handler, e.g.:
        //      next(new MyWeirdCaseError(...));
        //
        // The subtle bug is that if `err.name === "error"`, then restify will
        // emit an event named "error", which is typically a special case
        // for any EventEmitter:
        //      emitter.on('error', function (err) {...});
        //
        // The intent here is to handle actual "error" events that indicate
        // a severe issue with the server, not to handle some particular
        // handler Error class. So if we get the latter (i.e. the subtle bug),
        // then just ignore it.
        if (cb !== undefined) {
            cb();
            return;
        }
        log.fatal({err: errOrReq}, 'server (secure) error');
        process.exit(1);
    });
    server1.listen(cfg.port, function () {
        log.info('%s listening at (trusted port) %s', appName, server1.url);
    });

    server2 = app.createServer(cfg, clients, 'insecure');
    server2.on('error', function onInsecureServerErr(errOrReq, _res, _err, cb) {
        // HACK to ignore unintended server "error" events due to a subtle
        // bug in restify. See comment above for `server1`.
        if (cb !== undefined) {
            cb();
            return;
        }
        log.fatal({err: errOrReq}, 'server (clear) error');
        process.exit(1);
    });
    server2.listen(cfg.insecurePort, function () {
        log.info('%s listening at (clear port) %s', appName, server2.url);
    });

    app.startKangServer();
}

///--- Mainline

(function main() {
    const muskie = 'muskie';

    // Parent object for client connection objects.
    var clients = {};

    // DTrace probe setup
    var dtp = dtrace.createDTraceProvider(muskie);
    var client_close = dtp.addProbe('client_close', 'json');
    var socket_timeout = dtp.addProbe('socket_timeout', 'json');

    client_close.dtp = dtp;
    socket_timeout.dtp = dtp;
    dtp.enable();

    const dtProbes = {
        client_close: client_close,
        socket_timeout: socket_timeout
    };

    const opts = parseOptions();
    const cfg = app.configure(muskie, opts, dtProbes);

    /*
     * Create a barrier to ensure client connections that are established
     * asynchronously and are required for muskie to serve a minimal subset of
     * requests are ready prior to starting up the restify servers.
     */
    var barrier = vasync.barrier();

    barrier.on('drain', clientsConnected.bind(null, muskie, cfg, clients));

    /*
     * Establish minimal set of client connections required to begin
     * successfully servicing read requests.
     */

    clients.agent = new cueball.HttpAgent(cfg.cueballHttpAgent);
    clients.mahi = createAuthCacheClient(cfg.auth, clients.agent);

    barrier.start('createMorayClient');
    createMorayClient(cfg, onMorayConnect.bind(null, clients, barrier));

    // Establish other client connections needed for write requests.
    createPickerClient(cfg.storage, cfg.log,
        onPickerConnect.bind(null, clients));
    clients.sharkAgent = createCueballSharkAgent(cfg.sharkConfig);
    clients.keyapi = createKeyAPIClient(cfg);

    // Create monitoring server
    createMonitoringServer(cfg);

    process.on('SIGHUP', process.exit.bind(process, 0));

})();
<|endoftext|>


<commit_before>document.addEventListener('DOMContentLoaded', function(){
	function teamValue () {
		return document.forms[0].teams.value;
		}

	document.getElementById('submit').addEventListener("click", function(){
			alert("You clicked the button " + teamValue());
		});
});<commit_msg>Added if else statements for specific alerts<commit_after>document.addEventListener('DOMContentLoaded', function(){
	function teamValue () {
		return document.forms[0].teams.value;
		}

	document.getElementById('submit').addEventListener("click", function(){
			if (teamValue() ==="randomstudent") {
				alert("You clicked the 1st selection of " + teamValue());
			} else if (teamValue() ==="neighboringpair") {
				alert("You clicked the 2nd selection of " + teamValue());
			} else if (teamValue() ==="randompair") {
				alert("You clicked the 3rd selection of " + teamValue());
			} else if (teamValue() ==="randomthree") {
				alert("You clicked the 4th selection of " + teamValue());
			} else if (teamValue() ==="randomnpair") {
				alert("You clicked the 5th selection of " + teamValue());
			}
		});
});

<|endoftext|>


<commit_before>$("#fk-header-id").css("position", "relative");
$("#fk-mainhead-id").css("top", "50px");
$(".pbo-sticky").hide();
$(".shortListButton").hide();

var mbar = '
<input id="voiceSearch" type="text" style="height: 50px;outline: 0;border: 0;width: 50%;font-size:32px;text-align:center;">
';
$("body").prepend(mbar);

$(window).scroll(function() {
    if ($(this).scrollTop()>0){
        $('#fk-mainhead-id').fadeOut();
    }
    else{
      $('#fk-mainhead-id').fadeIn();
    }
});

$("#voiceSearch").click(function(){
    getUserSpeechInput(domAction, function(data){
    	$("#voiceSearch").val(data);
    });
    $("#voiceSearch").blur();
});

(function(){
	$("#voiceSearch").val(localStorage.getItem('vQuery'));
	localStorage.setItem('vQuery', '');
})();
<commit_msg>frontend improvements<commit_after>$("#fk-header-id").css("position", "relative");
$("#fk-mainhead-id").css("top", "50px");
$(".pbo-sticky").hide();
$(".shortListButton").hide();
" no-repeat center";
var mbar = '
<input id="voiceSearch" placeholder="Hi! I am Flippy, Ask Me Anything" type="text" style="cursor:pointer;height: 50px;outline: 0;border: 0;width: 50%;font-size:32px;text-align:center;background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIAAAACACAYAAADDPmHLAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAABXVJREFUeNrsnctx2zAQhpHHITc5t9wkVyDnlhuZCuwOlFTgEuRUoBKUDnTOSXIFoiuQfMuNUgUKMSYnNM2HqAXAXeD/Znac8SQSgv0J7GIBUCkAAAAAhMg7j/9vo8zuMoszu8mtjk1mh8ySzPa56T8fIQCZjDN7yJ1/RfysOnFoe8bYwfOJn2d2cmTrzBaZTdH1w6OdsHPo/Krp757BDcOgOz4d0PlVIdzCJW6df2JoC7jGPhFT5xe2zeMSYCnST5kLACKwyFqA8wtbwl1hzPttdg+3mWMnUABpPm2BAJ/+wlZwH52tYAGcMArQI/+TcENASODeAwGkcOPlrDwQgDZWS8UfBAngW2afMvsiXMh/M/vDpTFS9wPoeGCiXjZ56Jp/nP8+FtD2TWbfIQB7jHJhTBpEgn73XADniOOqQSQQQOBENeIoDAIInGlpKomJUwr6XTgLYiqIYKQn6/yn3p17UP936z4N2B4vRgApAmh7aur29OvfPVpsz44QF+g2XkMA/ebehJh3mz74cSK2h806wEcBAqCmZ8VQfdfgjDqRPHcIkkLCqXMlCODG4mfHlZ9VRx1qREIV5AExdD9cnvYJrhgkJQPwSQAR0sD+QeBEDbt0622fS1+RikpzeHUJlyN6/v8MAbgbOaql4ivLQaWoFNB3AbQx1H6C35n9hAB4Y3M/wUNmv9DFcqFuTGWXAr4XMI9His8BS+8WgbhPAdWqW7UaeM7Src32iO9v7gLoU3RJSqKwVTLeErMICKBnMGZqyNyr16XiS0vG3lQBCzgXg0zm60VEHzfMy0mDSI6V1NGr+Z+7ACYOA7u448k9GHBgAgHwFEAXsaHP2XPsZO5pYKL8gaUApKwESj4KVp5qjhCAnWyB+1Ewtn3tey2Ay1EwlilgCALoonwUzOZ+ArYCAM0UdQi9J1Ff7UIpAs3RnbKh3k7G9p5ArusA8zyI2yt3p31srkkkEEA/4pYovryW7+o1L1QB7LkKgGsQmBKi9I0y/5oX78rA3Btm6wj1pfsJKILU3/EVAuiXmm0G+N5qvFGI5El5WAbmnpv7dBKIdQrIsRgUeyZo1odBOU4BuvBTvOhxouxd1ORS0I8QgBnKp30kHAVTeRufIAA3I8dEva4GDn0UjH0fh1IMqorDVclYZxXXEABvbO4nQAoonKny/AWS3NLAcb4OwOXVKt7fB8StGPRDvZygLWi6qMlVVE2dBjYQAK3Db1ocsVdvl26V4Zzb+xGAWxBIPXtX7ngTt4d6WwXk2kAXFyn32U9AuRKW3X1AEuBQvNFPvX5B1dzA5wCBAgjqHYHvoTlr7NEFYY8AuBI2cAFEEjqcWxZATbuahuJEvd2aXaz/3wTStyJYKnPv6NXr8Ofc7a+Xne/zlA/vCB6YmTKzB29E+P7UUCoJLmBE6PStor/No2jDSuEs4GCsLnS+6cskKdPRFG68nMiS86OKjS2JYAcXmskGzu3sUUeAt2yZ13dnxAx9RyQM/w5HgbZcu8/bPdOWhZtRj8AwVXzuNRZPlwOXLQ7bGg7eZnj6h8kI2hw5NhhElm3W8Lld6wQ7PP12RFA3/K4a/j71Pv9iGK8TV1d5OIK77DCtefqanlITizhN08tYCbwCxtfpYEyYp8+10ZnTwBLuccdcNa+zL5X9cm41vljAJcOMBpS1A0pGMC/FCTO4ghcnRwJYKz4HV4CFALBNAN6leT7tCXRxF98RzxlfXASBgDG3Cjt6gsfUti6s6Qc8CqCiJ5yFCmA7N2jn0nJwcCt7vh4NOzj+dxAAgAAABAAgAAABAAgAQAAAAgAQAIAAAAQAIAAAAQAIAEAAAAIAEACAAAAEACAAAAEACAAAAAAAADjknwADAIAdEd37mBrKAAAAAElFTkSuQmCC);background-repeat:no-repeat;background-position: right; padding:0px 10px;background-size: 24px;">
';
$("body").prepend(mbar);

$(window).scroll(function() {
    if ($(this).scrollTop()>0){
        $('#fk-mainhead-id').fadeOut();
    }
    else{
      $('#fk-mainhead-id').fadeIn();
    }
});

$("#voiceSearch")

$("#voiceSearch").click(function(){
    getUserSpeechInput(domAction, function(data){
    	$("#voiceSearch").val(data);
    });
    $("#voiceSearch").blur();
});

(function(){
	$("#voiceSearch").val(localStorage.getItem('vQuery'));
	localStorage.setItem('vQuery', '');
})();
<|endoftext|>


<commit_before>'use strict';

let RENDERER = PIXI.autoDetectRenderer(640,480);
RENDERER.backgroundColor = 0x7cd3ff;
document.body.appendChild(RENDERER.view);

// pause button
let IS_PAUSED=false;
document.getElementById('PauseBut').onclick=()=>{
  if (IS_PAUSED) {
    T0=performance.now();
    requestAnimationFrame(GAME_LOOP);
  }
  IS_PAUSED=!IS_PAUSED;
}

// gamepad and keyboard controllers
let gamePadPlayerIdxMap=[];
let updateGamepads=()=>{
  let gps = navigator.getGamepads();
  for (let i=0,l=gps.length; i<l; ++i) {
    // if gampepad is active
    if (gps[i]) {
      if (gamePadPlayerIdxMap[i]==undefined) {
        gamePadPlayerIdxMap[i]=createPlayer();
        console.log('created new player for gamepad idx: '+i);
      }
      let c = PLAYERS[gamePadPlayerIdxMap[i]].controller;
      let b=gps[i].buttons;
      c.up     =b[12].pressed;
      c.down   =b[13].pressed;
      c.left   =b[14].pressed;
      c.right  =b[15].pressed;
      c.run    =b[ 2].pressed;
      c.jump   =b[ 0].pressed;
      c.fire   =b[ 7].pressed;
      c.sheild =b[ 6].pressed;
      c.missile=b[ 5].pressed;
      c.bomb   =b[ 4].pressed;
      c.down   =b[13].pressed;
      c.start  =b[ 9].pressed;
      c.select =b[ 8].pressed;
    }

    // else inactive
    else if (gamePadPlayerIdxMap[i]) {
      let p = PLAYERS[gamePadPlayerIdxMap[i]];
      p.destroy();
      gamePadPlayerIdxMap[i]=undefined;
    }
  }
};

let keyboardPlayerIdx=null;
window.addEventListener("keydown", (e)=>{
  if (keyboardPlayerIdx===null && e.keyCode >=37 && e.keyCode <= 40) {
    keyboardPlayerIdx=createPlayer();
    console.log('created new player for keyboard');
  }
  if (keyboardPlayerIdx===null) return;
  let c = PLAYERS[keyboardPlayerIdx].controller;
  switch(e.keyCode) {
    case 32: c.jump =true; break; // spacebar
    case 37: c.left =true; break; // left
    case 38: c.up   =true; break; // up
    case 39: c.right=true; break; // right
    case 40: c.down =true; break; // down
  }
});
window.addEventListener("keyup", (e)=>{
  if (keyboardPlayerIdx===null) return;
  let c = PLAYERS[keyboardPlayerIdx].controller;
  switch(e.keyCode) {
    case 32: c.jump =false; break; // spacebar
    case 37: c.left =false; break; // left
    case 38: c.up   =false; break; // up
    case 39: c.right=false; break; // right
    case 40: c.down =false; break; // down
  }
});

let SCREEN = new PIXI.Container();
SCREEN.update=()=>{
  for (let e of SCREEN.children) e.update();
}

let STAGE = new PIXI.Container();
STAGE.x=0;
STAGE.y=0;
STAGE.scroll_acceleration = .001;
STAGE.scroll_speed_x = 0;
STAGE.scroll_speed_y = 0;
SCREEN.addChild(STAGE);
STAGE.update=()=>{
  for (let e of STAGE.children) e.update();

  // move the stage so the player is near the center of the screen
  let p = PLAYERS[0];
  if (p) {
    STAGE.x -= ((STAGE.x - ((p.x - (RENDERER.width/2)) * -1)) / (RENDERER.width/2)) * ELAPSED_TIME;
    STAGE.y -= ((STAGE.y - ((p.y - (RENDERER.height/2)) * -1)) / (RENDERER.height/2)) * ELAPSED_TIME;
  }
}

// make ground
let GROUND = [];
{ let m=(x,y,w,h,color)=>{
    let g = new PIXI.Graphics();
    if (! x) x=0;
    if (! y) y=0;
    if (! w) w=200;
    if (! h) w=20;
    g.beginFill(color);
    g.drawRect(0, 0, w, h);
    g.endFill();
    g.x=x;
    g.y=y;
    g.climbable = false;
    g.update=()=>{};
    STAGE.addChild(g);
    GROUND.push(g);
  }
  m(40,100,50,1,0x4f844e);
  m(100,200,90,1,0x4f844e);
  m(50,300,400,1,0x4f844e);
  m(80,400,80,1,0x4f844e);
  m(10,440,800,1,0x4f844e);
}

let PLAYERS=[];
let createPlayer=()=>{
  let p = new PIXI.Graphics();
  STAGE.addChild(p);
  p.beginFill(0x0e47a3);
  p.lineStyle(1, 0x000000, 1);
  p.drawRect(0, 0, 4, 20);
  p.endFill();
  p.ground = null;
  p.x = p.prevX = 100;
  p.y = p.prevY = 100;
  p.speed_x = 0;
  p.speed_y = 0;
  p.acceleration_x = .0008;
  p.acceleration_y = .0008;
  p.stop_acceleration_x = .001;
  p.stop_acceleration_y = .0008;
  p.fall_acceleration_y = .002;
  p.fall_acceleration_x = .0006;
  p.max_speed_x = 1;
  p.max_speed_y = 1;
  p.start_jump_speed = .5;
  p.continue_jump_speed = .001;
  p.continue_jump_ms = 900;
  p.jump_end = 0;
  p.destroy=()=>{
    STAGE.removeChild(p);
    var i = PLAYERS.indexOf(p);
    if (i!=-1) PLAYERS.splice(i, 1);
  };
  p.controller={up:false,down:false,left:false,right:false,run:false,jump:false,fire:false,sheild:false,missile:false,bomb:false,start:false,select:false};
  p.update=()=>{
    if (p.ground) {
      // handle x movement (walking)
      if (p.controller.right && p.speed_x >= 0) {
        p.speed_x += p.acceleration_x * ELAPSED_TIME;
      } else if (p.controller.left && p.speed_x <= 0) {
        p.speed_x -= p.acceleration_x * ELAPSED_TIME;
      } else if (p.speed_x > 0) {
        p.speed_x -= p.stop_acceleration_x * ELAPSED_TIME;
        if (p.speed_x < 0) p.speed_x=0;
      } else if (p.speed_x < 0) {
        p.speed_x += p.stop_acceleration_x * ELAPSED_TIME;
        if (p.speed_x > 0) p.speed_x=0;
      }

      // handle y movement (climbing)
      if (p.controller.down && p.speed_y >= 0) {
        p.speed_y += p.acceleration_y * ELAPSED_TIME;
      } else if (p.controller.up && p.speed_y <= 0) {
        p.speed_y -= p.acceleration_y * ELAPSED_TIME;
      } else if (p.speed_y > 0) {
        p.speed_y -= p.stop_acceleration_y * ELAPSED_TIME;
        if (p.speed_y < 0) p.speed_y=0;
      } else if (p.speed_y < 0) {
        p.speed_y += p.stop_acceleration_y * ELAPSED_TIME;
        if (p.speed_y > 0) p.speed_y=0;
      }

      // handle jump
      if (p.controller.jump) {
        p.ground=null;
        p.jump_end = T1 + p.continue_jump_ms;
        p.speed_y = p.start_jump_speed * -1;
      }
    }

    // handle falling
    else {
      p.speed_y += p.fall_acceleration_y * ELAPSED_TIME;

      // handle x movement
      if (p.controller.right && p.speed_x >= 0) {
        p.speed_x += p.fall_acceleration_x * ELAPSED_TIME;
      } else if (p.controller.left && p.speed_x <= 0) {
        p.speed_x -= p.fall_acceleration_x * ELAPSED_TIME;
      }

      if (p.controller.jump) {
        if (T1 > 0 && T1 < p.jump_end) {
          p.speed_y -= (p.continue_jump_speed * ELAPSED_TIME);
        }
      }
    }

    // handle maximum veolcities
    if (p.speed_x > p.max_speed_x)
      p.speed_x=p.max_speed_x;
    else if (p.speed_x < -1*p.max_speed_x)
      p.speed_x=p.max_speed_x*-1;
    if (p.speed_y > p.max_speed_y)
      p.speed_y=p.max_speed_y;
    else if (p.speed_y < -1*p.max_speed_y)
      p.speed_y=p.max_speed_y*-1;

    // update position
    p.prevX = p.x;
    p.prevY = p.y;
    p.x += p.speed_x * ELAPSED_TIME;
    p.y += p.speed_y * ELAPSED_TIME;

    // is the ground still valid
    if (p.ground && (p.x < p.ground.x || (p.x > p.ground.x + p.ground.width))) {
      p.ground=null;
    }

    // handle ground
    if (p.ground) {
      p.y = p.ground.y-p.height;
      p.speed_y=0;
    } else {

      // look for a ground
      for (let g of GROUND) {
        if ((p.x >= g.x && p.x <= (g.x + g.width)) &&
            (p.prevY+p.height <= g.y && p.y+p.height >= g.y)) {
          p.ground = g;
          break;
        }
      }
    }
  }

  let i = PLAYERS.length;
  PLAYERS[i]=p;
  return i;
}

let MSG = new PIXI.Text("", {
  fontFamily: "monospace",
  fontSize: 14,
  fill: "white"
});
SCREEN.addChild(MSG);
MSG.position.set(0, 0);
MSG.update=()=>{
  let p = PLAYERS[0];
  if (p) {
    MSG.text =
      " x:"  + p.x.toFixed(1)
    + " y:"  + p.y.toFixed(1)
    + " vx:" + p.speed_x.toFixed(1)
    + " vy:" + p.speed_y.toFixed(1)
    + " stageX: " + STAGE.x.toFixed(1);
  } else {
    MSG.text='';
  }
}

// game loop
let T0=performance.now();
let T1=0;
let ELAPSED_TIME=0;
let GAME_LOOP=(t1)=>{
  T1=t1;
  ELAPSED_TIME=T1-T0;
  updateGamepads();
  SCREEN.update();
  RENDERER.render(SCREEN);
  T0=T1;
  if (! IS_PAUSED) requestAnimationFrame(GAME_LOOP);
};
GAME_LOOP(T0);
<commit_msg>added run/walk support<commit_after>"use strict";

let RENDERER = PIXI.autoDetectRenderer(640,480);
RENDERER.backgroundColor = 0x7cd3ff;
document.body.appendChild(RENDERER.view);

// pause button
let IS_PAUSED=false;
document.getElementById('PauseBut').onclick=()=>{
  if (IS_PAUSED) {
    T0=performance.now();
    requestAnimationFrame(GAME_LOOP);
  }
  IS_PAUSED=!IS_PAUSED;
}

// gamepad and keyboard controllers
let gamePadPlayerIdxMap=[];
let updateGamepads=()=>{
  let gps = navigator.getGamepads();
  for (let i=0,l=gps.length; i<l; ++i) {
    // if gampepad is active
    if (gps[i]) {
      if (gamePadPlayerIdxMap[i]==undefined) {
        gamePadPlayerIdxMap[i]=createPlayer();
      }
      let c = PLAYERS[gamePadPlayerIdxMap[i]].controller;
      let b=gps[i].buttons;
      c.up     =b[12].pressed;
      c.down   =b[13].pressed;
      c.left   =b[14].pressed;
      c.right  =b[15].pressed;
      c.run    =b[ 2].pressed;
      c.jump   =b[ 0].pressed;
      c.fire   =b[ 7].pressed;
      c.sheild =b[ 6].pressed;
      c.missile=b[ 5].pressed;
      c.bomb   =b[ 4].pressed;
      c.down   =b[13].pressed;
      c.start  =b[ 9].pressed;
      c.select =b[ 8].pressed;
    }

    // else inactive
    else if (gamePadPlayerIdxMap[i]) {
      let p = PLAYERS[gamePadPlayerIdxMap[i]];
      p.destroy();
      gamePadPlayerIdxMap[i]=undefined;
    }
  }
};

let keyboardPlayerIdx=null;
window.addEventListener("keydown", (e)=>{
//console.log(e.keyCode);
  if (keyboardPlayerIdx===null && e.keyCode >=37 && e.keyCode <= 40) {
    keyboardPlayerIdx=createPlayer();
    console.log('created new player for keyboard');
  }
  if (keyboardPlayerIdx===null) return;
  let c = PLAYERS[keyboardPlayerIdx].controller;
  switch(e.keyCode) {
    case 16: c.run  =true; break; // shift
    case 32: c.jump =true; break; // spacebar
    case 37: c.left =true; break; // left
    case 38: c.up   =true; break; // up
    case 39: c.right=true; break; // right
    case 40: c.down =true; break; // down
  }
});
window.addEventListener("keyup", (e)=>{
  if (keyboardPlayerIdx===null) return;
  let c = PLAYERS[keyboardPlayerIdx].controller;
  switch(e.keyCode) {
    case 16: c.run  =false; break; // shift
    case 32: c.jump =false; break; // spacebar
    case 37: c.left =false; break; // left
    case 38: c.up   =false; break; // up
    case 39: c.right=false; break; // right
    case 40: c.down =false; break; // down
  }
});

let SCREEN = new PIXI.Container();
SCREEN.update=()=>{
  for (let e of SCREEN.children) e.update();
}

let STAGE = new PIXI.Container();
STAGE.x=0;
STAGE.y=0;
STAGE.scroll_acceleration = .001;
STAGE.scroll_speed_x = 0;
STAGE.scroll_speed_y = 0;
SCREEN.addChild(STAGE);
STAGE.update=()=>{
  for (let e of STAGE.children) e.update();

  // move the stage so the player is near the center of the screen
  let p = PLAYERS[0];
  if (p) {
    STAGE.x -= ((STAGE.x - ((p.x - (RENDERER.width/2)) * -1)) / (RENDERER.width/2)) * ELAPSED_TIME;
    STAGE.y -= ((STAGE.y - ((p.y - (RENDERER.height/2)) * -1)) / (RENDERER.height/2)) * ELAPSED_TIME;
  }
}

// make ground
let GROUND = [];
{ let m=(x,y,w,h,color)=>{
    let g = new PIXI.Graphics();
    if (! x) x=0;
    if (! y) y=0;
    if (! w) w=200;
    if (! h) w=20;
    g.beginFill(color);
    g.drawRect(0, 0, w, h);
    g.endFill();
    g.x=x;
    g.y=y;
    g.climbable = false;
    g.update=()=>{};
    STAGE.addChild(g);
    GROUND.push(g);
  }
  m(40,100,50,1,0x4f844e);
  m(100,200,90,1,0x4f844e);
  m(50,300,400,1,0x4f844e);
  m(80,400,80,1,0x4f844e);
  m(10,440,2800,1,0x4f844e);
}

let PLAYERS=[];
let createPlayer=()=>{
  let p = new PIXI.Graphics();
  STAGE.addChild(p);
  p.beginFill(0x0e47a3);
  p.lineStyle(1, 0x000000, 1);
  p.drawRect(0, 0, 4, 20);
  p.endFill();
  p.ground = null;
  p.x = p.prevX = 100;
  p.y = p.prevY = 100;
  p.speed_x = 0;
  p.speed_y = 0;
  p.walk_acceleration_x = .0004;
  p.walk_acceleration_y = .0004;
  p.run_acceleration_x = .0008;
  p.run_acceleration_y = .0008;
  p.stop_acceleration_x = .001;
  p.stop_acceleration_y = .0008;
  p.fall_acceleration_y = .002;
  p.fall_acceleration_x = .0004;
  p.walk_max_speed_x = .2;
  p.walk_max_speed_y = .2;
  p.run_max_speed_x = .4;
  p.run_max_speed_y = .4;
  p.start_jump_speed = .5;
  p.continue_jump_speed = .001;
  p.continue_jump_ms = 900;
  p.jump_end = 0;
  p.destroy=()=>{
    STAGE.removeChild(p);
    var i = PLAYERS.indexOf(p);
    if (i!=-1) PLAYERS.splice(i, 1);
  };
  p.controller={up:false,down:false,left:false,right:false,run:false,jump:false,fire:false,sheild:false,missile:false,bomb:false,start:false,select:false};
  p.update=()=>{
    if (p.ground) {

      // handle walk/run x axis movement
      if (p.controller.right && p.speed_x >= 0) {
        if (p.controller.run) {
          p.speed_x += p.run_acceleration_x * ELAPSED_TIME;
          if (p.speed_x > p.run_max_speed_x) {
            p.speed_x=p.run_max_speed_x;
          }
        } else {
          p.speed_x += p.walk_acceleration_x * ELAPSED_TIME;
          if (p.speed_x > p.walk_max_speed_x) {
            p.speed_x=p.walk_max_speed_x;
          }
        }
      } else if (p.controller.left && p.speed_x <= 0) {
        if (p.controller.run) {
          p.speed_x -= p.run_acceleration_x * ELAPSED_TIME;
          if (p.speed_x < (p.run_max_speed_x * -1)) {
            p.speed_x=p.run_max_speed_x * -1;
          }
        } else {
          p.speed_x -= p.walk_acceleration_x * ELAPSED_TIME;
          if (p.speed_x < (p.walk_max_speed_x * -1)) {
            p.speed_x=p.walk_max_speed_x * -1;
          }
        }
      } else if (p.speed_x > 0) {
        p.speed_x -= p.stop_acceleration_x * ELAPSED_TIME;
        if (p.speed_x < 0) p.speed_x=0;
      } else if (p.speed_x < 0) {
        p.speed_x += p.stop_acceleration_x * ELAPSED_TIME;
        if (p.speed_x > 0) p.speed_x=0;
      }

      // handle y movement (climbing)
      if (p.controller.down && p.speed_y >= 0) {
        p.speed_y += p.walk_acceleration_y * ELAPSED_TIME;
      } else if (p.controller.up && p.speed_y <= 0) {
        p.speed_y -= p.walk_acceleration_y * ELAPSED_TIME;
      } else if (p.speed_y > 0) {
        p.speed_y -= p.stop_acceleration_y * ELAPSED_TIME;
        if (p.speed_y < 0) p.speed_y=0;
      } else if (p.speed_y < 0) {
        p.speed_y += p.stop_acceleration_y * ELAPSED_TIME;
        if (p.speed_y > 0) p.speed_y=0;
      }

      // handle jump
      if (p.controller.jump) {
        p.ground=null;
        p.jump_end = T1 + p.continue_jump_ms;
        p.speed_y = p.start_jump_speed * -1;
      }
    }

    // handle falling
    else {
      p.speed_y += p.fall_acceleration_y * ELAPSED_TIME;

      // handle x movement
      if (p.controller.right && p.speed_x >= 0) {
        p.speed_x += p.fall_acceleration_x * ELAPSED_TIME;
        if (p.speed_x > p.run_max_speed_x) {
          p.speed_x=p.run_max_speed_x;
        }
      } else if (p.controller.left && p.speed_x <= 0) {
        p.speed_x -= p.fall_acceleration_x * ELAPSED_TIME;
        if (p.speed_x < p.run_max_speed_x * -1) {
          p.speed_x=p.run_max_speed_x * -1;
        }
      }

      if (p.controller.jump) {
        if (T1 > 0 && T1 < p.jump_end) {
          p.speed_y -= (p.continue_jump_speed * ELAPSED_TIME);
        }
      }
    }

    // update position
    p.prevX = p.x;
    p.prevY = p.y;
    p.x += p.speed_x * ELAPSED_TIME;
    p.y += p.speed_y * ELAPSED_TIME;

    // is the ground still valid
    if (p.ground && (p.x < p.ground.x || (p.x > p.ground.x + p.ground.width))) {
      p.ground=null;
    }

    // handle ground
    if (p.ground) {
      p.y = p.ground.y-p.height;
      p.speed_y=0;
    } else {

      // look for a ground
      for (let g of GROUND) {
        if ((p.x >= g.x && p.x <= (g.x + g.width)) &&
            (p.prevY+p.height <= g.y && p.y+p.height >= g.y)) {
          p.ground = g;
          break;
        }
      }
    }
  }

  let i = PLAYERS.length;
  PLAYERS[i]=p;
  return i;
}

let MSG = new PIXI.Text("", {
  fontFamily: "monospace",
  fontSize: 14,
  fill: "white"
});
SCREEN.addChild(MSG);
MSG.position.set(0, 0);
MSG.update=()=>{
  let p = PLAYERS[0];
  if (p) {
    MSG.text =
      " x:"  + p.x.toFixed(1)
    + " y:"  + p.y.toFixed(1)
    + " vx:" + p.speed_x.toFixed(1)
    + " vy:" + p.speed_y.toFixed(1)
    + " stageX: " + STAGE.x.toFixed(1);
  } else {
    MSG.text='';
  }
}

// game loop
let T0=performance.now();
let T1=0;
let ELAPSED_TIME=0;
let GAME_LOOP=(t1)=>{
  T1=t1;
  ELAPSED_TIME=T1-T0;
  updateGamepads();
  SCREEN.update();
  RENDERER.render(SCREEN);
  T0=T1;
  if (! IS_PAUSED) requestAnimationFrame(GAME_LOOP);
};
GAME_LOOP(T0);
<|endoftext|>


<commit_before>var LABEL_WIDTH = 200,
	VTX_DIST = 40, // Distance between centers of two consecutive vertices
	VTX_RAD = 4,
	LABEL_OFFSET = 10; // Distance between label and center of vertex

// Translate every vertex (hence entire graphic) by this much
var VTX_TRANS = {x: 0, y: 20};

var canvas = d3.select("#canvas");
var sidePanel = d3.select("#side-panel");

// Overall width of canvas
var WIDTH = canvas.style("width");
WIDTH = +(WIDTH.substring(0, WIDTH.length - 2));

// Set height based on the number of vertices
var HEIGHT = VTX_DIST * Math.max(asoiaf_chars.length, tac_chars.length);
canvas.style("height", HEIGHT);

////////////////// Helper functions //////////////////

// Return absolute coordinates of center of vertex
// Accepts either a vertex object or an ID string
function vertexPos(v) {

	// If v is an ID string, use it to retrieve vertex
	if(v.name == undefined)
		v = canvas.select("#" + v).datum();

	var pos = {
		x: (v.series == "tac" ? LABEL_WIDTH : WIDTH - LABEL_WIDTH) + VTX_TRANS.x,
		y: v.index * VTX_DIST + VTX_TRANS.y
	};
	return pos;
}

// Callback for when a vertex is clicked
function vertexClicked(v) {

	// Hide all edges first
	edges.classed("active", false);

	// Select current vertex & deselect all others
	vertices.classed("selected", function(w) {return w.id == v.id;});

	// Show edges incident to the clicked vertex
	edges.classed("active", function(e) {
			return e.l == v.id || e.r == v.id;
		})
		.classed("selected", false);

	// Clear the side panel
	sidePanel.select("#instructions").remove();
	sidePanel.selectAll("div").html("");

	showInfo(v, sidePanel.select("#selected-char"));
}

// Fill selection with info from vertex v
function showInfo(v, selection) {

	selection.html("");

	// We will add text whether the image loads or not
	function addText() {
		selection.append("h2")
		    .html(v.name);

		/* Assume v.wiki_handle is a correctly encoded URL if defined,
		 * e.g. %20 instead of ' '.
		 */
		var wiki_handle = v.wiki_handle;
		if(wiki_handle == undefined)
			wiki_handle = encodeURI(v.name);

		var domain = null;
		var link_url = "http://";
		if(v.series == "tac") {
			domain = "en%2Ewikipedia%2Eorg%2Fw";
			link_url += "en.wikipedia.org/wiki/";
		}
		else {
			domain = "awoiaf%2Ewesteros%2Eorg";
			link_url += "awoiaf.westeros.org/index.php/";
		}
		link_url += wiki_handle;

		url = "wikis.php?domain=" + domain + "&handle=" + wiki_handle;
		var req = new XMLHttpRequest();
		req.open("GET", url, true);

		req.onload = function() {
			var pages = JSON.parse(this.response).query.pages;
			for(var pageid in pages) {
				selection.append("p").html(pages[pageid].extract);
				break; // Only want one page
			}
			selection.append("a")
		        .attr("href", link_url)
		        .html("Read more");
		};

		req.onerror = function() {
			console.log("Error opening " + url);
		};

		req.send();

	};

	// Check for image file first
	var img_url = "pics/" + v.id + ".jpg";
	var img_req = new XMLHttpRequest();
	img_req.open("HEAD", img_url, true);
	img_req.onload = function() {
        if(this.status == 200 || this.status == 0) // File exists; add the image
		    selection.append("img")
		        .attr("src", img_url);
		addText();
	};
	img_req.onerror = addText;

	img_req.send();
}

function edgeClicked(e) {

	// Deselect other edges and select this one
	edges.classed("selected", function(f) {
			return f.l == e.l && f.r == e.r;
		});

	// Get the endpoint of e that is NOT the selected vertex
	var otherV = (canvas.select(".vertex.selected").classed("tac") ? e.r : e.l); // ID
	otherV = canvas.select("#" + otherV).datum(); // Vertex object

	showInfo(otherV, sidePanel.select("#connected-char"));

	// Show connections between characters in a bulleted list
	var connections = d3.select("#connections").html("");
	connections.append("h2")
		.html("Connections");
	var ul = connections.append("ul");
	d3.text("blurbs/" + e.l + "-" + e.r, function(error, blurb) {
			if(error == null) {
				blurb = blurb.split("\n"); // Each newline marks a new bullet
				for(var i = 0; i < blurb.length; i++) {
					blurb[i] = blurb[i].trim();
					if(blurb[i].length == 0) // Skip empty lines
						continue;
					ul.append("li").html(blurb[i]);
				}
			}
			else
				console.log(error);
		});

}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

// Draw vertices
var vertices = canvas.selectAll(".vertex") // Should be empty
	.data(vertexList)
  .enter().append("g")
	.classed("vertex", true)
	.classed("tac", function(v) {return v.series == "tac";})
	.classed("asoiaf", function(v) {return v.series == "asoiaf";})
	.attr("id", function(v) {return v.id;})
	.attr("transform", function(v) {
			var pos = vertexPos(v);
			return "translate(" + pos.x + "," + pos.y + ")";
		});

vertices.append("circle")
	.attr("r", VTX_RAD);

vertices.append("text")
	.text(function(v) {return v.name;})
	.attr("x", function(v) {return v.series == "tac" ? -LABEL_OFFSET : LABEL_OFFSET;})
	.attr("y", 4);

console.log(vertices);
console.log(canvas.style("height"));

// Draw edges

var edges = canvas.selectAll(".edge"); // Should be empty

// Get edge list from the server
var req = new XMLHttpRequest();
req.open("GET", "edges.php", true);
req.onload = function() {
	if(this.status == 200 || this.status == 0) {
		edgeList = JSON.parse(this.response);
		edges = edges.data(edgeList)
		  .enter().append("line")
			.attr("x1", vertexPos("clemence").x) // Use any TAC character
			.attr("y1", function(e) {return vertexPos(e.l).y;})
			.attr("x2", vertexPos("sansa").x) // Use any ASOIAF character
			.attr("y2", function(e) {return vertexPos(e.r).y;})
			.on("click", edgeClicked)
			.classed("edge", true);

		vertices.on("click", vertexClicked);
	}
};
req.send();
<commit_msg>Increase vertex label width<commit_after>var LABEL_WIDTH = 245,
	VTX_DIST = 40, // Distance between centers of two consecutive vertices
	VTX_RAD = 4,
	LABEL_OFFSET = 10; // Distance between label and center of vertex

// Translate every vertex (hence entire graphic) by this much
var VTX_TRANS = {x: 0, y: 20};

var canvas = d3.select("#canvas");
var sidePanel = d3.select("#side-panel");

// Overall width of canvas
var WIDTH = canvas.style("width");
WIDTH = +(WIDTH.substring(0, WIDTH.length - 2));

// Set height based on the number of vertices
var HEIGHT = VTX_DIST * Math.max(asoiaf_chars.length, tac_chars.length);
canvas.style("height", HEIGHT);

////////////////// Helper functions //////////////////

// Return absolute coordinates of center of vertex
// Accepts either a vertex object or an ID string
function vertexPos(v) {

	// If v is an ID string, use it to retrieve vertex
	if(v.name == undefined)
		v = canvas.select("#" + v).datum();

	var pos = {
		x: (v.series == "tac" ? LABEL_WIDTH : WIDTH - LABEL_WIDTH) + VTX_TRANS.x,
		y: v.index * VTX_DIST + VTX_TRANS.y
	};
	return pos;
}

// Callback for when a vertex is clicked
function vertexClicked(v) {

	// Hide all edges first
	edges.classed("active", false);

	// Select current vertex & deselect all others
	vertices.classed("selected", function(w) {return w.id == v.id;});

	// Show edges incident to the clicked vertex
	edges.classed("active", function(e) {
			return e.l == v.id || e.r == v.id;
		})
		.classed("selected", false);

	// Clear the side panel
	sidePanel.select("#instructions").remove();
	sidePanel.selectAll("div").html("");

	showInfo(v, sidePanel.select("#selected-char"));
}

// Fill selection with info from vertex v
function showInfo(v, selection) {

	selection.html("");

	// We will add text whether the image loads or not
	function addText() {
		selection.append("h2")
		    .html(v.name);

		/* Assume v.wiki_handle is a correctly encoded URL if defined,
		 * e.g. %20 instead of ' '.
		 */
		var wiki_handle = v.wiki_handle;
		if(wiki_handle == undefined)
			wiki_handle = encodeURI(v.name);

		var domain = null;
		var link_url = "http://";
		if(v.series == "tac") {
			domain = "en%2Ewikipedia%2Eorg%2Fw";
			link_url += "en.wikipedia.org/wiki/";
		}
		else {
			domain = "awoiaf%2Ewesteros%2Eorg";
			link_url += "awoiaf.westeros.org/index.php/";
		}
		link_url += wiki_handle;

		url = "wikis.php?domain=" + domain + "&handle=" + wiki_handle;
		var req = new XMLHttpRequest();
		req.open("GET", url, true);

		req.onload = function() {
			var pages = JSON.parse(this.response).query.pages;
			for(var pageid in pages) {
				selection.append("p").html(pages[pageid].extract);
				break; // Only want one page
			}
			selection.append("a")
		        .attr("href", link_url)
		        .html("Read more");
		};

		req.onerror = function() {
			console.log("Error opening " + url);
		};

		req.send();

	};

	// Check for image file first
	var img_url = "pics/" + v.id + ".jpg";
	var img_req = new XMLHttpRequest();
	img_req.open("HEAD", img_url, true);
	img_req.onload = function() {
        if(this.status == 200 || this.status == 0) // File exists; add the image
		    selection.append("img")
		        .attr("src", img_url);
		addText();
	};
	img_req.onerror = addText;

	img_req.send();
}

function edgeClicked(e) {

	// Deselect other edges and select this one
	edges.classed("selected", function(f) {
			return f.l == e.l && f.r == e.r;
		});

	// Get the endpoint of e that is NOT the selected vertex
	var otherV = (canvas.select(".vertex.selected").classed("tac") ? e.r : e.l); // ID
	otherV = canvas.select("#" + otherV).datum(); // Vertex object

	showInfo(otherV, sidePanel.select("#connected-char"));

	// Show connections between characters in a bulleted list
	var connections = d3.select("#connections").html("");
	connections.append("h2")
		.html("Connections");
	var ul = connections.append("ul");
	d3.text("blurbs/" + e.l + "-" + e.r, function(error, blurb) {
			if(error == null) {
				blurb = blurb.split("\n"); // Each newline marks a new bullet
				for(var i = 0; i < blurb.length; i++) {
					blurb[i] = blurb[i].trim();
					if(blurb[i].length == 0) // Skip empty lines
						continue;
					ul.append("li").html(blurb[i]);
				}
			}
			else
				console.log(error);
		});

}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

// Draw vertices
var vertices = canvas.selectAll(".vertex") // Should be empty
	.data(vertexList)
  .enter().append("g")
	.classed("vertex", true)
	.classed("tac", function(v) {return v.series == "tac";})
	.classed("asoiaf", function(v) {return v.series == "asoiaf";})
	.attr("id", function(v) {return v.id;})
	.attr("transform", function(v) {
			var pos = vertexPos(v);
			return "translate(" + pos.x + "," + pos.y + ")";
		});

vertices.append("circle")
	.attr("r", VTX_RAD);

vertices.append("text")
	.text(function(v) {return v.name;})
	.attr("x", function(v) {return v.series == "tac" ? -LABEL_OFFSET : LABEL_OFFSET;})
	.attr("y", 4);

console.log(vertices);
console.log(canvas.style("height"));

// Draw edges

var edges = canvas.selectAll(".edge"); // Should be empty

// Get edge list from the server
var req = new XMLHttpRequest();
req.open("GET", "edges.php", true);
req.onload = function() {
	if(this.status == 200 || this.status == 0) {
		edgeList = JSON.parse(this.response);
		edges = edges.data(edgeList)
		  .enter().append("line")
			.attr("x1", vertexPos("clemence").x) // Use any TAC character
			.attr("y1", function(e) {return vertexPos(e.l).y;})
			.attr("x2", vertexPos("sansa").x) // Use any ASOIAF character
			.attr("y2", function(e) {return vertexPos(e.r).y;})
			.on("click", edgeClicked)
			.classed("edge", true);

		vertices.on("click", vertexClicked);
	}
};
req.send();
<|endoftext|>