<commit_before>/* eslint max-len: [0] */
export default {
  adjectives: ["bulged", "forged", "gnarly", "avenged", "turbo", "almighty", "badass", "burly", "primal", "howling", "maximum", "golden", "wild", "violent", "gutsy", "hostile", "raging", "daring", "bulging", "bold", "furious", "smoldering", "highpowered", "potent", "blackened", "burnt", "sweaty", "supreme", "blazing", "excessive", "transcendent", "chiseled", "bloodied", "musky", "fierce", "strapping", "premium", "stampeding", "weathered", "ruthless", "stubbled", "ballistic", "virile", "ferocious", "nuclear", "vicious", "viscous", "jackboot", "explosive", "fearless", "flexing", "hardened", "zealous", "grizzled", "iron", "carnal", "mighty", "righteous", "deep", "suave", "rugged", "savage", "bearded", "heroic", "gallant", "grizzly", "rabid", "intense", "elite", "powerful", "magnificent", "inglorious", "glorious", "ultimate", "downtrodden", "courageous", "weak", "exploding", "pure", "bad", "relentless", "impossible", "unrelenting", "fiery", "legendary", "bloody", "kicking", "fallen", "pummeled", "grandeur", "fearful"],
  nouns: ["predator", "mustache", "bicep", "might", "brawn", "mettle", "metal", "cigar", "swagger", "shrapnel", "balls", "stallion", "muscle", "guts", "auger", "turkeyleg", "jerky", "meat", "bacon", "steak", "horsepower", "fangs", "brimstone", "hellfire", "scar", "denim", "leather", "claw", "battleaxe", "saber", "nunchuk", "talon", "stranglehold", "overdrive", "piston", "engine", "forge", "cutlass", "buzzsaw", "knuckles", "bourbon", "harley", "machete", "blaster", "warrior", "jetblast", "tornado", "typhoon", "bushwak", "tomahawk", "hurricane", "falcon", "dropkick", "avenger", "warthog", "raptor", "missile", "dragon", "bronco", "motor", "scorpion", "panzer", "tomcat", "torpedo", "corvette", "ferrari", "mustang", "tiger", "oak", "turbo", "shark", "bull", "lion", "eagle", "hawk", "bearskin", "wolf", "badass", "stampede", "ballistic", "deathgrip", "iron", "beard", "bear", "fight", "hounds", "hound", "dog", "dogs", "eye", "hill", "hills", "mountain", "earth", "cannon", "cannons", "infinity", "rulership", "greatness", "magnificence", "titanium", "fist", "glory", "dominance", "phoenix", "flames", "courage", "stratosphere", "weakness", "head", "demon", "feast", "explode", "barrel", "whiskey", "vengeance", "battle", "spoils", "attack", "mount", "heroes", "hero", "valhalla", "peak", "aggression", "goals", "competition", "jaws", "passion", "fire", "ride", "lightning", "thunder", "sun", "love", "night", "legend", "revolution", "banner", "knees", "blood", "kraken", "plane", "mortal", "enemies", "enemy", "mercy", "empire", "hell", "gate", "gates", "victory", "flag", "face", "death", "valley", "fireball", "opponent", "mincemeat", "enemy", "czar", "emperor", "king", "war", "darkness", "fear", "den", "viper", "endurance", "vigor", "spit", "wolves", "eagles"],
  verbs: ["roar", "growl", "bulge", "thrust", "flex", "fight", "dive", "impose", "dominate", "vanquish", "launch", "destroy", "feast", "pursue", "bask", "battle", "gorge", "mount", "scale", "attack", "sail", "conquer", "dominate", "defeat", "rip", "triumph", "stoke", "annihilate", "transcend", "kick", "fall", "breach", "hoist", "punch", "traverse", "manhandle", "pummel", "dethrone", "engulf", "strike", "seize", "dread", "soar", "fly", "run"]
}
<commit_msg>new words<commit_after>/* eslint max-len: [0] */
export default {
  adjectives: ["bulged", "forged", "gnarly", "avenged", "turbo", "almighty", "badass", "burly", "primal", "howling", "max", "maximum", "golden", "wild", "violent", "gutsy", "hostile", "raging", "daring", "bulging", "bold", "furious", "smoldering", "highpowered", "potent", "blackened", "burnt", "sweaty", "supreme", "blazing", "excessive", "transcendent", "chiseled", "bloodied", "musky", "fierce", "strapping", "premium", "stampeding", "weathered", "ruthless", "stubbled", "ballistic", "virile", "ferocious", "nuclear", "vicious", "viscous", "jackboot", "explosive", "fearless", "flexing", "hardened", "zealous", "grizzled", "iron", "carnal", "mighty", "righteous", "deep", "suave", "rugged", "savage", "bearded", "heroic", "gallant", "grizzly", "rabid", "intense", "elite", "powerful", "magnificent", "inglorious", "glorious", "ultimate", "downtrodden", "courageous", "weak", "exploding", "pure", "bad", "relentless", "impossible", "unrelenting", "fiery", "legendary", "bloody", "kicking", "fallen", "pummeled", "grandeur", "fearful", "dry", "greasy", "hanging", "stormy", "tame", "macho", "muscular", "strong", "robust", "brawny", "heavy", "vigorous", "hunky", "mannish", "butch", "super", "brave", "swanson", "tyrannosaurus", "techno", "shaving", "dangerous", "caged", "sharp", "sharpened", "monstrous", "gigantic", "huge", "vehicular", "sauced", "sterling", "flinty", "bareback"],
  nouns: ["challenge", "caution", "camp", "burn", "bruise", "box", "bomb", "barrage", "bar", "predator", "mustache", "bicep", "might", "brawn", "mettle", "metal", "cigar", "swagger", "shrapnel", "balls", "stallion", "muscle", "guts", "auger", "turkeyleg", "jerky", "meat", "bacon", "steak", "horsepower", "fangs", "brimstone", "hellfire", "scar", "denim", "leather", "claw", "baron", "buck", "battleaxe", "saber", "nunchuk", "nunchuck", "talon", "stranglehold", "overdrive", "strap", "storm", "rock", "piston", "engine", "forge", "cutlass", "buzzsaw", "knuckles", "bourbon", "harley", "machete", "blaster", "warrior", "jetblast", "tornado", "typhoon", "bushwak", "tomahawk", "hurricane", "falcon", "dropkick", "avenger", "warthog", "raptor", "missile", "dragon", "bronco", "motor", "scorpion", "panzer", "tomcat", "torpedo", "corvette", "ferrari", "mustang", "tiger", "panther", "oak", "turbo", "chop", "shark", "bull", "lion", "coil", "clip", "eagle", "hawk", "bearskin", "wolf", "badass", "cure", "stampede", "damage", "ballistic", "deathgrip", "iron", "delay", "beard", "desire", "desert", "bear", "fight", "hounds", "hound", "dog", "drain", "dogs", "dust", "eye", "echo", "drill", "drone", "hill", "hills", "mountain", "earth", "cannon", "cannons", "fool", "infinity", "fish", "frame", "fume", "grease", "force", "grill", "deck", "glue", "flood", "fence", "guard", "hammer", "rulership", "greatness", "heap", "heat", "magnificence", "titanium", "fist", "glory", "hook", "dominance", "phoenix", "flames", "courage", "jail", "stratosphere", "rope", "weakness", "lock", "land", "head", "demon", "feast", "explode", "barrel", "mug", "paint", "pine", "peg", "pack", "oil", "nap", "nail", "whiskey", "vengeance", "battle", "spoils", "attack", "mount", "heroes", "hero", "valhalla", "peak", "aggression", "competition", "jaws", "passion", "fire", "ride", "lightning", "saw", "thunder", "sun", "love", "night", "legend", "seal", "revolution", "banner", "shade", "knees", "shelter", "blood", "kraken", "plane", "mortal", "enemies", "enemy", "mercy", "empire", "hell", "gate", "gates", "smoke", "victory", "flag", "spark", "face", "death", "valley", "stain", "stash", "fireball", "opponent", "stitch", "mincemeat", "stunt", "enemy", "czar", "emperor", "king", "war", "darkness", "fear", "den", "tire", "viper", "endurance", "vigor", "toast", "spit", "wolves", "eagles", "ice", "urge", "wizard", "chainsaw", "streetfight", "power", "fightmaster", "sergeant", "uppercut", "fortress", "chest", "scotch", "swanson", "rex", "motorcycle", "barbecue", "armageddon", "viking", "log", "danger", "beer", "lumberjack", "meatslab", "jaw", "cage", "sword", "hulk", "monster", "beef", "truck", "jet", "sauce", "tent", "flint", "cobra", "shotgun", "rifle", "pistol", "bullet", "barfight", "dinosaur", "rodeo"],
  verbs: ["chew", "chase", "chant", "carve", "camp", "bury", "burn", "build", "bruise", "broil", "breed", "break", "bomb", "bolt", "boil", "boast", "bleed", "bite", "bestow", "besiege", "bend", "bellow", "baste", "barter", "bark", "bandage", "bang", "ban", "balk", "awake", "arrest", "answer", "allege", "alert", "jump", "tackle", "drink", "chug", "tear", "kill", "scream", "roar", "growl", "bulge", "thrust", "flex", "fight", "dive", "impose", "dominate", "vanquish", "launch", "destroy", "feast", "pursue", "bask", "battle", "gorge", "mount", "scale", "attack", "sail", "conquer", "dominate", "defeat", "rip", "triumph", "stoke", "annihilate", "transcend", "kick", "fall", "breach", "hoist", "punch", "traverse", "manhandle", "pummel", "dethrone", "engulf", "strike", "seize", "dread", "soar", "fly", "run", "choke", "chomp", "chop", "claim", "climb", "clip", "coach", "command", "cough", "crack", "crash", "crush", "cry", "cure", "curl", "cut", "damage", "dare", "decay", "deceive", "deliver", "demand", "dictate", "die", "dig", "dislike", "divide", "divulge", "drag", "drain", "drip", "drill", "dump", "eat", "encode", "escape", "evacuate", "explode", "explore", "fade", "fail", "fasten", "feed", "fix", "force", "fry", "gaze", "gnaw", "grab", "grill", "grip", "grumble", "grunt", "guard", "gurgle", "handle", "hang", "harass", "harm", "hate", "haunt", "hide", "hijack", "hinder", "hiss", "hit", "howl", "hunt", "hurt", "infect", "infuse", "itch", "jam", "jolt", "knock", "knot", "land", "lift", "marvel", "mate", "measure", "melt", "mend", "merge", "mow", "murder", "park", "plow", "polish", "preserve", "protect", "pry", "pull", "pump", "puncture", "punish", "push", "race", "rave", "reign", "repair", "report", "reprimand", "request", "rescue", "ride", "risk", "rock", "roll", "rot", "rush", "sack", "saw", "scold", "scorch", "scrape", "scratch", "screech", "seal", "search", "sever", "shade", "shave", "shock", "shoot", "shout", "shriek", "signal", "sin", "singe", "ski", "slap", "sleep", "hibernate", "smash", "smoke", "snore", "soak", "spark", "squash", "squeeze", "stab", "stain", "stamp", "stare", "steer", "stitch", "storm", "strengthen", "stretch", "stuff", "strut", "stun", "submerge", "surround", "tame", "taunt", "tempt", "terrify", "test", "thaw", "threaten", "tie", "tow", "track", "trade", "trap", "trim", "trust", "tug", "unite", "watch", "weigh", "whip", "win", "wipe", "work", "wreck", "wrestle", "yield", "uppercut", "barbecue"]
}
<|endoftext|>


<commit_before>// Dean Attali / Beautiful Jekyll 2016

var main = {

  bigImgEl : null,
  numImgs : null,

  init : function() {
    // Shorten the navbar after scrolling a little bit down
    $(window).scroll(function() {
        if ($(".navbar").offset().top > 50) {
            $(".navbar").addClass("top-nav-short");
        } else {
            $(".navbar").removeClass("top-nav-short");
        }
    });

    // On mobile, hide the avatar when expanding the navbar menu
    $('#main-navbar').on('show.bs.collapse', function () {
      $(".navbar").addClass("top-nav-expanded");
    });
    $('#main-navbar').on('hidden.bs.collapse', function () {
      $(".navbar").removeClass("top-nav-expanded");
    });

    // On mobile, when clicking on a multi-level navbar menu, show the child links
    $('#main-navbar').on("click", ".navlinks-parent", function(e) {
      var target = e.target;
      $.each($(".navlinks-parent"), function(key, value) {
        if (value == target) {
          $(value).parent().toggleClass("show-children");
        } else {
          $(value).parent().removeClass("show-children");
        }
      });
    });

    // Ensure nested navbar menus are not longer than the menu header
    var menus = $(".navlinks-container");
    if (menus.length > 0) {
      var navbar = $("#main-navbar ul");
      var fakeMenuHtml = "

";
      navbar.append(fakeMenuHtml);
      var fakeMenu = $(".fake-menu");

      $.each(menus, function(i) {
        var parent = $(menus[i]).find(".navlinks-parent");
        var children = $(menus[i]).find(".navlinks-children a");
        var words = [];
        $.each(children, function(idx, el) { words = words.concat($(el).text().trim().split(/\s+/)); });
        var maxwidth = 0;
        $.each(words, function(id, word) {
          fakeMenu.html("" + word + "");
          var width =  fakeMenu.width();
          if (width > maxwidth) {
            maxwidth = width;
          }
        });
        $(menus[i]).css('min-width', maxwidth + 'px')
      });

      fakeMenu.remove();
    }

    // show the big header image
    main.initImgs();
  },

  initImgs : function() {
    // If the page was large images to randomly select from, choose an image
    if ($("#header-big-imgs").length > 0) {
      main.bigImgEl = $("#header-big-imgs");
      main.numImgs = main.bigImgEl.attr("data-num-img");

          // 2fc73a3a967e97599c9763d05e564189
	  // set an initial image
	  var imgInfo = main.getImgInfo();
	  var src = imgInfo.src;
	  var desc = imgInfo.desc;
  	  main.setImg(src, desc);

	  // For better UX, prefetch the next image so that it will already be loaded when we want to show it
  	  var getNextImg = function() {
	    var imgInfo = main.getImgInfo();
	    var src = imgInfo.src;
	    var desc = imgInfo.desc;

		var prefetchImg = new Image();
  		prefetchImg.src = src;
		// if I want to do something once the image is ready: `prefetchImg.onload = function(){}`

  		setTimeout(function(){
                  var img = $("

").addClass("big-img-transition").css("background-image", 'url(' + src + ')');
  		  $(".intro-header.big-img").prepend(img);
  		  setTimeout(function(){ img.css("opacity", "1"); }, 50);

		  // after the animation of fading in the new image is done, prefetch the next one
  		  //img.one("transitioned webkitTransitionEnd oTransitionEnd MSTransitionEnd", function(){
		  setTimeout(function() {
		    main.setImg(src, desc);
			img.remove();
  			getNextImg();
		  }, 1000);
  		  //});
  		}, 6000);
  	  };

	  // If there are multiple images, cycle through them
	  if (main.numImgs > 1) {
  	    getNextImg();
	  }
    }
  },

  getImgInfo : function() {
  	var randNum = Math.floor((Math.random() * main.numImgs) + 1);
    var src = main.bigImgEl.attr("data-img-src-" + randNum);
	var desc = main.bigImgEl.attr("data-img-desc-" + randNum);

	return {
	  src : src,
	  desc : desc
	}
  },

  setImg : function(src, desc) {
	$(".intro-header.big-img").css("background-image", 'url(' + src + ')');
	if (typeof desc !== typeof undefined && desc !== false) {
	  $(".img-desc").text(desc).show();
	} else {
	  $(".img-desc").hide();
	}
  }
};

// 2fc73a3a967e97599c9763d05e564189

document.addEventListener('DOMContentLoaded', main.init);
<commit_msg>Update main.js<commit_after>// Dean Attali / Beautiful Jekyll 2016

var main = {

  bigImgEl : null,
  numImgs : null,

  init : function() {
    // Shorten the navbar after scrolling a little bit down
    $(window).scroll(function() {
        if ($(".navbar").offset().top > 50) {
            $(".navbar").addClass("top-nav-short");
        } else {
            $(".navbar").removeClass("top-nav-short");
        }
    });

    // On mobile, hide the avatar when expanding the navbar menu
    $('#main-navbar').on('show.bs.collapse', function () {
      $(".navbar").addClass("top-nav-expanded");
    });
    $('#main-navbar').on('hidden.bs.collapse', function () {
      $(".navbar").removeClass("top-nav-expanded");
    });

    // On mobile, when clicking on a multi-level navbar menu, show the child links
    $('#main-navbar').on("click", ".navlinks-parent", function(e) {
      var target = e.target;
      $.each($(".navlinks-parent"), function(key, value) {
        if (value == target) {
          $(value).parent().toggleClass("show-children");
        } else {
          $(value).parent().removeClass("show-children");
        }
      });
    });

    // Ensure nested navbar menus are not longer than the menu header
    var menus = $(".navlinks-container");
    if (menus.length > 0) {
      var navbar = $("#main-navbar ul");
      var fakeMenuHtml = "

";
      navbar.append(fakeMenuHtml);
      var fakeMenu = $(".fake-menu");

      $.each(menus, function(i) {
        var parent = $(menus[i]).find(".navlinks-parent");
        var children = $(menus[i]).find(".navlinks-children a");
        var words = [];
        $.each(children, function(idx, el) { words = words.concat($(el).text().trim().split(/\s+/)); });
        var maxwidth = 0;
        $.each(words, function(id, word) {
          fakeMenu.html("" + word + "");
          var width =  fakeMenu.width();
          if (width > 400) {
            maxwidth = width;
          }
        });
        $(menus[i]).css('min-width', maxwidth + 'px')
      });

      fakeMenu.remove();
    }

    // show the big header image
    main.initImgs();
  },

  initImgs : function() {
    // If the page was large images to randomly select from, choose an image
    if ($("#header-big-imgs").length > 0) {
      main.bigImgEl = $("#header-big-imgs");
      main.numImgs = main.bigImgEl.attr("data-num-img");

          // 2fc73a3a967e97599c9763d05e564189
	  // set an initial image
	  var imgInfo = main.getImgInfo();
	  var src = imgInfo.src;
	  var desc = imgInfo.desc;
  	  main.setImg(src, desc);

	  // For better UX, prefetch the next image so that it will already be loaded when we want to show it
  	  var getNextImg = function() {
	    var imgInfo = main.getImgInfo();
	    var src = imgInfo.src;
	    var desc = imgInfo.desc;

		var prefetchImg = new Image();
  		prefetchImg.src = src;
		// if I want to do something once the image is ready: `prefetchImg.onload = function(){}`

  		setTimeout(function(){
                  var img = $("

").addClass("big-img-transition").css("background-image", 'url(' + src + ')');
  		  $(".intro-header.big-img").prepend(img);
  		  setTimeout(function(){ img.css("opacity", "1"); }, 50);

		  // after the animation of fading in the new image is done, prefetch the next one
  		  //img.one("transitioned webkitTransitionEnd oTransitionEnd MSTransitionEnd", function(){
		  setTimeout(function() {
		    main.setImg(src, desc);
			img.remove();
  			getNextImg();
		  }, 1000);
  		  //});
  		}, 6000);
  	  };

	  // If there are multiple images, cycle through them
	  if (main.numImgs > 1) {
  	    getNextImg();
	  }
    }
  },

  getImgInfo : function() {
  	var randNum = Math.floor((Math.random() * main.numImgs) + 1);
    var src = main.bigImgEl.attr("data-img-src-" + randNum);
	var desc = main.bigImgEl.attr("data-img-desc-" + randNum);

	return {
	  src : src,
	  desc : desc
	}
  },

  setImg : function(src, desc) {
	$(".intro-header.big-img").css("background-image", 'url(' + src + ')');
	if (typeof desc !== typeof undefined && desc !== false) {
	  $(".img-desc").text(desc).show();
	} else {
	  $(".img-desc").hide();
	}
  }
};

// 2fc73a3a967e97599c9763d05e564189

document.addEventListener('DOMContentLoaded', main.init);
<|endoftext|>


<commit_before>"use strict";

/**
 * Lightweight Console
 *
 * @param consoleDiv dom of div holding the console
 * @param consoleOutDOM dom of text-area for console-output
 * @param consoleInDOM dom of text-input for console-input
 * @param hostname included in motd, may have further use in the future
 * @constructor
 */
function LWConsole(consoleDiv, consoleOutDOM, consoleInDOM, hostname) {
    let consoleOut = "";
    let motd = "Welcome to " + hostname + "!\nType 'help' for help.\n";
    let isInverted = false;
    let commands = [
        {
            name: "help",
            description: "Shows a list of commands",
            visible: true,
            handler: helpCMD
        },
        {
            name: "motd",
            description: "Shows the message of the day",
            visible: true,
            handler: function () {
                return motd;
            }
        },
        {
            name: "echo",
            description: "Displays message on console - no pipes yet :-(",
            visible: true,
            handler: echoCMD
        },
        {
            name: "ip",
            description: "Lookup an IP: Usage: ip [ip] (queries your IP if no argument is provided)",
            visible: true,
            handler: ipCMD
        },
        {
            name: "invert",
            description: "Invert website colors",
            visible: true,
            handler: function () {
                isInverted = !isInverted;
                invert(isInverted);
                return "Page inverted!";
            }
        },
        {
            name: "clear",
            description: "Clears the console",
            visible: true, //Visible in help page?
            handler: function () {
                consoleOut = "";
                consoleOutDOM.value = consoleOut;
            }
        },
        {
            name: "exit",
            description: "Exit console",
            visible: true,
            handler: function () {
                util.toggleConsole();
            }
        },
        {
            name: "kleinhase",
            description: "Secret message",
            visible: false,
            handler: function () {
                return "<3";
            }
        },
        {
            name: "shutdown",
            description: "",
            visible: false,
            handler: function () {
                return "You're not my master!";
            }
        },
        {
            name: "make_me_a_sandwich",
            description: "<3 xkcd",
            visible: false,
            handler: function () {
                return "Make it yourself!";
            }
        },
        {
            name: "rm",
            description: "",
            visible: false,
            handler: function () {
                return "Please don't delete anything. We don't have any backups.";
            }
        },
        {
            name: "ls",
            description: "",
            visible: false,
            handler: function () {
                return "cia_secrets, cute_cat_gifs, videos, passwords.txt";
            }
        }
    ];

    //Get initial state depending on dom
    this.visible = window.getComputedStyle(consoleDiv).getPropertyValue("display") === "flex";

    //Attach key handler to enter key
    document.addEventListener("keydown", function (e) {
        if (consoleInDOM === document.activeElement && e.keyCode == 13) {
            e.preventDefault();
            let value = consoleInDOM.value;
            if (value === "") { //Do not trigger cmd when input is empty
                return;
            }
            sendCMD(value);
            consoleInDOM.value = ""; //Empty after cmd sent
        }
    });

    //Set initial content of textarea
    print(motd);

    //Methods ======================================
    /**
     * Changes visibility of console-div depending on parameter
     * @param state boolean true = visible; false = hidden
     */
    this.show = function (state) {
        if (state) {
            consoleDiv.style.display = "flex";
            this.visible = true;
            //Set focus to console
            consoleInDOM.focus();
        }
        else {
            consoleDiv.style.display = "none";
            this.visible = false;
        }
    };

    /**
     * Getter for visibility state
     * @returns {boolean}
     */
    this.isVisible = function () {
        return this.visible;
    };

    /**
     * Prints message to console and updates cursor position (scroll)
     * @param str message to print
     */
    function print(str) {
        if (str) {
            consoleOut += str + "\n"; //Append string to print and newline
            consoleOutDOM.value = consoleOut; //update textarea text
            consoleOutDOM.scrollTop = consoleOutDOM.scrollHeight; //scroll down in textarea for console-like behavior
        }
    }

    /**
     * Executes user cmd and updates output accordingly
     * @param cmd raw cmd by user
     */
    function sendCMD(cmd) {
        let splitCMD = cmd.split(" "); //split cmd by space (cmd name, args)
        print("> " + cmd); //Print cmd from user
        print(executeCMD(splitCMD)); //Print result of cmd-execution
    }

    /**
     * Takes command as array and calls corresponding cmd-handler on match
     * @param cmd command-array. cmd[0] is command name, cmd[>1] is parameter
     * @returns {String} result of command
     */
    function executeCMD(cmd) {
        for (let i = 0; i < commands.length; i++) {
            if (commands[i].name === cmd[0].toLowerCase()) {
                cmd.shift(); //remove cmd name from array, only leaving args
                return commands[i].handler(cmd); //Execute handler with array of args
            }
        }
        return "Unknown command.";
    }

    // Command handlers

    function helpCMD() {
        let msg = "Available commands:";
        for (let i = 0; i < commands.length; i++) {
            if (commands[i].visible) {
                msg += "\n" + commands[i].name + ": " + commands[i].description;
            }
        }
        return msg;
    }

    function echoCMD(args) {
        let init = true;
        let str = "";

        for (let i = 0; i < args.length; i++) {
            if (!init) {
                str += " ";
            }
            init = false;
            str += args[i];
        }
        return str;
    }

    function ipCMD(args) {
        let queryUrl = "https://ipinfo.io/";

        if (args.length > 1) {
            return "Invalid Syntax! ip [addr]";
        }
        else {
            if (args.length === 1) { //one arg => query arg ip
                queryUrl += args[0] + "/"
            }
        }

        queryUrl += "json";

        let request = new XMLHttpRequest();
        request.onload = function () {
            if (request.status !== 200) {
                print("\nError: ipinfo.io returned code " + request.status);
            }
            print(request.responseText);
        };
        request.onerror = function (e) {
            console.error(e);
            print("Error: Could not send request to ipinfo.io. Check your internet connection.");
        };
        request.open("GET", queryUrl, true);
        request.send();
        return "Getting data ...";
    }

    function invert(state) {
        let invertStr;
        if (state) {
            invertStr = "100%";
        }
        else {
            invertStr = "0%";
        }
        document.getElementById("monitor").style.filter = "invert(" + invertStr + ")";
    }
}

function JSUtil() {
    let lwConsole = new LWConsole(
        document.getElementById("lwConsole"),
        document.getElementById("consoleOut"),
        document.getElementById("consoleIn"),
        window.location.hostname
    );

    this.toggleConsole = function () {
        lwConsole.show(!lwConsole.isVisible());
    };

    /**
     * Handler for  console shortcuts 'C'=> open and 'ESC'=> close
     */
    document.addEventListener("keydown", function (e) {
        if (!lwConsole.isVisible() && e.keyCode == 67) {
            e.preventDefault();
            lwConsole.show(true);
        }
        else if (lwConsole.isVisible() && e.keyCode == 27) {
            e.preventDefault();
            lwConsole.show(false);
        }

    });
}
let util = new JSUtil();<commit_msg>added open-cmd to open links from navigation via command<commit_after>"use strict";

/**
 * Lightweight Console
 *
 * @param consoleDiv dom of div holding the console
 * @param consoleOutDOM dom of text-area for console-output
 * @param consoleInDOM dom of text-input for console-input
 * @param hostname included in motd, may have further use in the future
 * @constructor
 */
function LWConsole(consoleDiv, consoleOutDOM, consoleInDOM, hostname) {
    let consoleOut = "";
    let motd = "Welcome to " + hostname + "!\nType 'help' for help.\n";
    let isInverted = false;
    let commands = [
        {
            name: "help",
            description: "Shows a list of commands",
            visible: true,
            handler: helpCMD
        },
        {
            name: "motd",
            description: "Shows the message of the day",
            visible: true,
            handler: function () {
                return motd;
            }
        },
        {
            name: "open",
            description: "Usage: open [keybase/github/twitter/email",
            visible: true, //Visible in help page?
            handler: openCMD
        },
        {
            name: "echo",
            description: "Displays message on console - no pipes yet :-(",
            visible: true,
            handler: echoCMD
        },
        {
            name: "ip",
            description: "Lookup an IP: Usage: ip [ip] (queries your IP if no argument is provided)",
            visible: true,
            handler: ipCMD
        },
        {
            name: "invert",
            description: "Invert website colors",
            visible: true,
            handler: function () {
                isInverted = !isInverted;
                invert(isInverted);
                return "Page inverted!";
            }
        },
        {
            name: "clear",
            description: "Clears the console",
            visible: true, //Visible in help page?
            handler: function () {
                consoleOut = "";
                consoleOutDOM.value = consoleOut;
            }
        },
        {
            name: "exit",
            description: "Exit console",
            visible: true,
            handler: function () {
                util.toggleConsole();
            }
        },
        {
            name: "kleinhase",
            description: "Secret message",
            visible: false,
            handler: function () {
                return "<3";
            }
        },
        {
            name: "shutdown",
            description: "",
            visible: false,
            handler: function () {
                return "You're not my master!";
            }
        },
        {
            name: "make_me_a_sandwich",
            description: "<3 xkcd",
            visible: false,
            handler: function () {
                return "Make it yourself!";
            }
        },
        {
            name: "rm",
            description: "",
            visible: false,
            handler: function () {
                return "Please don't delete anything. We don't have any backups.";
            }
        },
        {
            name: "ls",
            description: "",
            visible: false,
            handler: function () {
                return "cia_secrets, cute_cat_gifs, videos, passwords.txt";
            }
        }
    ];

    //Get initial state depending on dom
    this.visible = window.getComputedStyle(consoleDiv).getPropertyValue("display") === "flex";

    //Attach key handler to enter key
    document.addEventListener("keydown", function (e) {
        if (consoleInDOM === document.activeElement && e.keyCode == 13) {
            e.preventDefault();
            let value = consoleInDOM.value;
            if (value === "") { //Do not trigger cmd when input is empty
                return;
            }
            sendCMD(value);
            consoleInDOM.value = ""; //Empty after cmd sent
        }
    });

    //Set initial content of textarea
    print(motd);

    //Methods ======================================
    /**
     * Changes visibility of console-div depending on parameter
     * @param state boolean true = visible; false = hidden
     */
    this.show = function (state) {
        if (state) {
            consoleDiv.style.display = "flex";
            this.visible = true;
            //Set focus to console
            consoleInDOM.focus();
        }
        else {
            consoleDiv.style.display = "none";
            this.visible = false;
        }
    };

    /**
     * Getter for visibility state
     * @returns {boolean}
     */
    this.isVisible = function () {
        return this.visible;
    };

    /**
     * Prints message to console and updates cursor position (scroll)
     * @param str message to print
     */
    function print(str) {
        if (str) {
            consoleOut += str + "\n"; //Append string to print and newline
            consoleOutDOM.value = consoleOut; //update textarea text
            consoleOutDOM.scrollTop = consoleOutDOM.scrollHeight; //scroll down in textarea for console-like behavior
        }
    }

    /**
     * Executes user cmd and updates output accordingly
     * @param cmd raw cmd by user
     */
    function sendCMD(cmd) {
        let splitCMD = cmd.split(" "); //split cmd by space (cmd name, args)
        print("> " + cmd); //Print cmd from user
        print(executeCMD(splitCMD)); //Print result of cmd-execution
    }

    /**
     * Takes command as array and calls corresponding cmd-handler on match
     * @param cmd command-array. cmd[0] is command name, cmd[>1] is parameter
     * @returns {String} result of command
     */
    function executeCMD(cmd) {
        for (let i = 0; i < commands.length; i++) {
            if (commands[i].name === cmd[0].toLowerCase()) {
                cmd.shift(); //remove cmd name from array, only leaving args
                return commands[i].handler(cmd); //Execute handler with array of args
            }
        }
        return "Unknown command.";
    }

    // Command handlers

    function helpCMD() {
        let msg = "Available commands:";
        for (let i = 0; i < commands.length; i++) {
            if (commands[i].visible) {
                msg += "\n" + commands[i].name + ": " + commands[i].description;
            }
        }
        return msg;
    }

    function echoCMD(args) {
        let init = true;
        let str = "";

        for (let i = 0; i < args.length; i++) {
            if (!init) {
                str += " ";
            }
            init = false;
            str += args[i];
        }
        return str;
    }

    function ipCMD(args) {
        let queryUrl = "https://ipinfo.io/";

        if (args.length > 1) {
            return "Invalid Syntax! ip [addr]";
        }
        else {
            if (args.length === 1) { //one arg => query arg ip
                queryUrl += args[0] + "/"
            }
        }

        queryUrl += "json";

        let request = new XMLHttpRequest();
        request.onload = function () {
            if (request.status !== 200) {
                print("\nError: ipinfo.io returned code " + request.status);
            }
            print(request.responseText);
        };
        request.onerror = function (e) {
            console.error(e);
            print("Error: Could not send request to ipinfo.io. Check your internet connection.");
        };
        request.open("GET", queryUrl, true);
        request.send();
        return "Getting data ...";
    }

    function openCMD(args) {
        if (args.length !== 1) {
            return "Invalid arguments!";
        }
        let url;
        switch (args[0]) {
            default:
                return "Sorry, I don't know this service";
                break;
            case "keybase":
                url = "//keybase.io/pbz";
                break;
            case "github":
                url = "//github.com/Trikolon";
                break;
            case "twitter":
                url = "//twitter.com/deppaws";
                break;
            case "email":
                url = "mailto:paul@zuehlcke.de";
                break;
        }
        window.open(url);
        return args[0] + " opened.";
    }

    function invert(state) {
        let invertStr;
        if (state) {
            invertStr = "100%";
        }
        else {
            invertStr = "0%";
        }
        document.getElementById("monitor").style.filter = "invert(" + invertStr + ")";
    }
}

function JSUtil() {
    let lwConsole = new LWConsole(
        document.getElementById("lwConsole"),
        document.getElementById("consoleOut"),
        document.getElementById("consoleIn"),
        window.location.hostname
    );

    this.toggleConsole = function () {
        lwConsole.show(!lwConsole.isVisible());
    };

    /**
     * Handler for  console shortcuts 'C'=> open and 'ESC'=> close
     */
    document.addEventListener("keydown", function (e) {
        if (!lwConsole.isVisible() && e.keyCode == 67) {
            e.preventDefault();
            lwConsole.show(true);
        }
        else if (lwConsole.isVisible() && e.keyCode == 27) {
            e.preventDefault();
            lwConsole.show(false);
        }

    });
}
let util = new JSUtil();<|endoftext|>


<commit_before>$(function () {

	const formsEnum = {
		LEFT: 0,
		RIGHT: 1,
		TOP: 2,
		BOTTOM: 3,
		FULLSCREEN: 4
	};

	var currentForm = formsEnum.FULLSCREEN;

	var calcMarkPosition = function (rectSize, rectOffset, posInsideRect) {
		rectSize = $.extend(true, {}, rectSize);
		rectOffset = $.extend(true, {}, rectOffset);
		posInsideRect = $.extend(true, {}, posInsideRect);

		const xThreshold = rectSize.width * 0.3;
		const yThreshold = rectSize.height * 0.4;

		if (posInsideRect.x < xThreshold) {
			currentForm = formsEnum.LEFT;
			rectSize.width /= 2;

		} else if (posInsideRect.x > rectSize.width - xThreshold) {
			currentForm = formsEnum.RIGHT;
			rectSize.width /= 2;
			rectOffset.left += rectSize.width;

		} else if (posInsideRect.y < yThreshold) {
			currentForm = formsEnum.TOP;
			rectSize.height /= 2;

		} else if (posInsideRect.y > rectSize.height - yThreshold) {
			currentForm = formsEnum.BOTTOM;
			rectSize.height /= 2;
			rectOffset.top += rectSize.height;

		} else {
			currentForm = formsEnum.FULLSCREEN;
		}

		return {
			top: rectOffset.top,
			left: rectOffset.left,
			width: rectSize.width,
			height: rectSize.height
		};
	}

	var setMarkPosition = (function () {
		var $mark = $('.mark');
		var positionCache = { top: 0, left: 0, width: 0, height: 0 };

		return function (position) {
			if (positionCache.top === position.top &&
				positionCache.left === position.left &&
				positionCache.width === position.width &&
				positionCache.height === position.height) {
				return;
			}
			positionCache = position;
			$mark.css(positionCache);
		}
	}());

	var onClickHandler = function (e) {
		var html = "";
		switch (currentForm) {

		case formsEnum.LEFT:
		case formsEnum.RIGHT:
			html = '

';
			break;

		case formsEnum.TOP:
		case formsEnum.BOTTOM:
			html = '

';
			break;

		case formsEnum.FULLSCREEN:
			html = "";
			break;
		}

		$(e.target).html(html);
	};

	var onMouseMoveHandler = (function () {
		var $rect = [];
		var rectOffset = {
			top: 0,
			left: 0
		};
		var rectSize = {
			width: 0,
			height: 0
		};

		return function (e) {
			if ($rect[0] !== e.target) {
				$rect = $(e.target);

				rectOffset = $rect.offset();
				rectSize = {
					width: $rect.width(),
					height: $rect.height()
				}

				$('.rect').removeClass('painted');
				$rect.addClass('painted');
			}

			var posInsideRect = {
				x: e.pageX - rectOffset.left,
				y: e.pageY - rectOffset.top
			};

			if (posInsideRect.x < 0 || posInsideRect.y < 0) {
				return;
			}

			setMarkPosition(calcMarkPosition(
				rectSize,
				rectOffset,
				posInsideRect
			));
		}
	}());

	var onContextMenuHandler = function (e) {
		var $parentRect = $(e.target).parent();

		if (!$parentRect.hasClass('rect')) {
			$parentRect = $(e.target);
		}

		var $childrenClone = $parentRect.find('>').children().clone();
		$parentRect.empty().append($childrenClone);

		e.preventDefault();
	};

	$(document)
		.on('contextmenu', '.rect', onContextMenuHandler)
		.on('mousemove', '.rect', onMouseMoveHandler)
		.on('click', '.rect', onClickHandler);
});
<commit_msg>リファクタ<commit_after>$(function () {

	const formsEnum = {
		LEFT: 0,
		RIGHT: 1,
		TOP: 2,
		BOTTOM: 3,
		FULLSCREEN: 4
	};

	var currentForm = formsEnum.FULLSCREEN;

	var calcMarkPosition = function (rectSize, rectOffset, posInsideRect) {
		rectSize = $.extend(true, {}, rectSize);
		rectOffset = $.extend(true, {}, rectOffset);
		posInsideRect = $.extend(true, {}, posInsideRect);

		const xThreshold = rectSize.width * 0.3;
		const yThreshold = rectSize.height * 0.4;

		if (posInsideRect.x < xThreshold) {
			currentForm = formsEnum.LEFT;
			rectSize.width /= 2;

		} else if (posInsideRect.x > rectSize.width - xThreshold) {
			currentForm = formsEnum.RIGHT;
			rectSize.width /= 2;
			rectOffset.left += rectSize.width;

		} else if (posInsideRect.y < yThreshold) {
			currentForm = formsEnum.TOP;
			rectSize.height /= 2;

		} else if (posInsideRect.y > rectSize.height - yThreshold) {
			currentForm = formsEnum.BOTTOM;
			rectSize.height /= 2;
			rectOffset.top += rectSize.height;

		} else {
			currentForm = formsEnum.FULLSCREEN;
		}

		return {
			top: rectOffset.top,
			left: rectOffset.left,
			width: rectSize.width,
			height: rectSize.height
		};
	}

	var setMarkPosition = (function () {
		var $mark = $('.mark');
		var positionCache = { top: 0, left: 0, width: 0, height: 0 };

		return function (position) {
			if (positionCache.top === position.top &&
				positionCache.left === position.left &&
				positionCache.width === position.width &&
				positionCache.height === position.height) {
				return;
			}
			positionCache = position;
			$mark.css(positionCache);
		}
	}());

	var onClickHandler = function (e) {
		var html = "";
		switch (currentForm) {

		case formsEnum.LEFT:
		case formsEnum.RIGHT:
			html = '

';
			break;

		case formsEnum.TOP:
		case formsEnum.BOTTOM:
			html = '

';
			break;

		case formsEnum.FULLSCREEN:
			html = "";
			break;
		}

		$(e.target).html(html);
	};

	var onMouseMoveHandler = (function () {
		var $rect = [];
		var rectOffset = { top: 0, left: 0 };
		var rectSize = { width: 0, height: 0 };

		var updateTargetRect = function (rect) {
			$rect = $(rect);

			rectOffset = $rect.offset();
			rectSize = {
				width: $rect.width(),
				height: $rect.height()
			}

			$('.rect').removeClass('painted');
			$rect.addClass('painted');
		}

		return function (e) {
			if ($rect[0] !== e.target) {
				updateTargetRect(e.target);
			}

			var posInsideRect = {
				x: e.pageX - rectOffset.left,
				y: e.pageY - rectOffset.top
			};

			if (posInsideRect.x < 0 || posInsideRect.y < 0) {
				return;
			}

			setMarkPosition(calcMarkPosition(
				rectSize,
				rectOffset,
				posInsideRect
			));
		}
	}());

	var onContextMenuHandler = function (e) {
		var $parentRect = $(e.target).parent();

		if (!$parentRect.hasClass('rect')) {
			$parentRect = $(e.target);
		}

		var $childrenClone = $parentRect.find('>').children().clone();
		$parentRect.empty().append($childrenClone);

		e.preventDefault();
	};

	$(document)
		.on('contextmenu', '.rect', onContextMenuHandler)
		.on('mousemove', '.rect', onMouseMoveHandler)
		.on('click', '.rect', onClickHandler);
});
<|endoftext|>


<commit_before> /*global window, module, console*/
(function($){
	'use strict';
	var Position = $.Position = function(x, y) {
		this.x = x;
		this.y = y;
	};

	Position.prototype.state = function(){
		return [this.x, this.y];
	};

	Position.prototype.at = function(state) {
		return this.x === state[0] && this.y === state[1];
	};

        var Goal = function(x, y, reward) {
	    Position.call(this, x, y);
	    this._reward = reward;
	};

        Goal.prototype = new Position();

        Goal.prototype.reward = function(){
   	    return this._reward;
        };

	var Maze = $.Maze = function(){
	    this._goals = [];
	    this._obstructions = [];
	    this._boundaries = [];
	    this._state = new Position(0, 0);
	    this.ended = false;
	};

	Maze.prototype.addGoal = function(x, y, reward){
		reward = reward || 1;
		this._goals.push(new Goal(x, y, reward));

	};
	Maze.prototype.goals = function(predicate){
		predicate = predicate || function(){ return true; };
		return this._goals
			.filter(predicate)
			.map(function(position){ return position.state(); });
	};
	Maze.prototype.rewardFor = function(state){
		return this._goals.filter(function(position){
			return position.at(state);
		}).reduce(function(subtotal, current){ return subtotal + current.reward(); }, 0);
	};
	Maze.prototype.addObstruction = function(x, y) {
		this._obstructions.push(new Position(x, y, 0));
	};
	Maze.prototype.obstructions = function(){
		return this._obstructions.map(function(position){ return position.state(); });
	};
	Maze.prototype.isObstructed = function(state) {
	    return this._obstructions.filter(function(position){
			return position.at(state);
		}).length > 0;
	};
        Maze.prototype.isGoal = function(state) {
	    return this._goals.filter(function(position){
			return position.at(state);
		}).length > 0;
	};

        Maze.prototype.tick = function(action) {
	    var currentState = this.currentState(action.state);
	    if(this.isGoal([currentState.x, currentState.y])) {
		this.ended = true;
	    }
	};

	Maze.prototype.currentState = function(state) {
		if(state) {
			this._state = state;
		}

		return this._state;
	};

        Maze.prototype.getPossibleActions = function() {
	    var possibleActions = [
		{state: new Position(this._state.x, this._state.y + 1), action: 'up'},
		{state: new Position(this._state.x + 1, this._state.y), action: 'right'},
		{state: new Position(this._state.x, this._state.y - 1), action: 'down'},
		{state: new Position(this._state.x - 1, this._state.y), action: 'left'}];

		var spliceAction = function(action) {
			return this.filter(function(it) {
				return it.action !== action;
			});
		};

		if(this.isObstructed([this._state.x, this._state.y+1])) {
			possibleActions = spliceAction.call(possibleActions, 'up');
		}
		if(this.isObstructed([this._state.x+1, this._state.y])) {
			possibleActions = spliceAction.call(possibleActions, 'right');
		}
		if(this.isObstructed([this._state.x, this._state.y-1])) {
			possibleActions = spliceAction.call(possibleActions, 'down');
		}
		if(this.isObstructed([this._state.x-1, this._state.y])) {
			possibleActions = spliceAction.call(possibleActions, 'left');
		}
		return possibleActions;
	};
})(window || module.exports);
<commit_msg>remove unused console<commit_after> /*global window, module*/
(function($){
	'use strict';
	var Position = $.Position = function(x, y) {
		this.x = x;
		this.y = y;
	};

	Position.prototype.state = function(){
		return [this.x, this.y];
	};

	Position.prototype.at = function(state) {
		return this.x === state[0] && this.y === state[1];
	};

        var Goal = function(x, y, reward) {
	    Position.call(this, x, y);
	    this._reward = reward;
	};

        Goal.prototype = new Position();

        Goal.prototype.reward = function(){
   	    return this._reward;
        };

	var Maze = $.Maze = function(){
	    this._goals = [];
	    this._obstructions = [];
	    this._boundaries = [];
	    this._state = new Position(0, 0);
	    this.ended = false;
	};

	Maze.prototype.addGoal = function(x, y, reward){
		reward = reward || 1;
		this._goals.push(new Goal(x, y, reward));

	};
	Maze.prototype.goals = function(predicate){
		predicate = predicate || function(){ return true; };
		return this._goals
			.filter(predicate)
			.map(function(position){ return position.state(); });
	};
	Maze.prototype.rewardFor = function(state){
		return this._goals.filter(function(position){
			return position.at(state);
		}).reduce(function(subtotal, current){ return subtotal + current.reward(); }, 0);
	};
	Maze.prototype.addObstruction = function(x, y) {
		this._obstructions.push(new Position(x, y, 0));
	};
	Maze.prototype.obstructions = function(){
		return this._obstructions.map(function(position){ return position.state(); });
	};
	Maze.prototype.isObstructed = function(state) {
	    return this._obstructions.filter(function(position){
			return position.at(state);
		}).length > 0;
	};
        Maze.prototype.isGoal = function(state) {
	    return this._goals.filter(function(position){
			return position.at(state);
		}).length > 0;
	};

        Maze.prototype.tick = function(action) {
	    var currentState = this.currentState(action.state);
	    if(this.isGoal([currentState.x, currentState.y])) {
		this.ended = true;
	    }
	};

	Maze.prototype.currentState = function(state) {
		if(state) {
			this._state = state;
		}

		return this._state;
	};

        Maze.prototype.getPossibleActions = function() {
	    var possibleActions = [
		{state: new Position(this._state.x, this._state.y + 1), action: 'up'},
		{state: new Position(this._state.x + 1, this._state.y), action: 'right'},
		{state: new Position(this._state.x, this._state.y - 1), action: 'down'},
		{state: new Position(this._state.x - 1, this._state.y), action: 'left'}];

		var spliceAction = function(action) {
			return this.filter(function(it) {
				return it.action !== action;
			});
		};

		if(this.isObstructed([this._state.x, this._state.y+1])) {
			possibleActions = spliceAction.call(possibleActions, 'up');
		}
		if(this.isObstructed([this._state.x+1, this._state.y])) {
			possibleActions = spliceAction.call(possibleActions, 'right');
		}
		if(this.isObstructed([this._state.x, this._state.y-1])) {
			possibleActions = spliceAction.call(possibleActions, 'down');
		}
		if(this.isObstructed([this._state.x-1, this._state.y])) {
			possibleActions = spliceAction.call(possibleActions, 'left');
		}
		return possibleActions;
	};
})(window || module.exports);
<|endoftext|>


<commit_before>var audio = undefined;

function parseQuery(q)
{
  var stage1 = q.slice(1).split("&");

  var stage2 = [];
  var stage3 = {};
  for(var i=0;i<stage1.length;++i)
  {
    stage2[i] = stage1[i].split("=");
    stage3[stage2[i][0]] = stage2[i][1];
  }

  return stage3;
}

var query = parseQuery(window.location.search);

if(query.lang == "scottish")
{
  var head  = document.getElementsByTagName('head')[0];
  var link  = document.createElement('link');
  link.rel  = 'stylesheet';
  link.type = 'text/css';
  link.href = '/css/lang/Scot.css';
  link.media = 'all';
  head.appendChild(link);

  var audio = document.createElement("audio");
  audio.src = "audio/scot.mp3";
  audio.loop = true;
  audio.play();

  var div = body.createElement("div");
  div.innerHTML = ''
  body.appendChild(div);
}
<commit_msg>Update tags.js<commit_after>var audio = undefined;

function parseQuery(q)
{
  var stage1 = q.slice(1).split("&");

  var stage2 = [];
  var stage3 = {};
  for(var i=0;i<stage1.length;++i)
  {
    stage2[i] = stage1[i].split("=");
    stage3[stage2[i][0]] = stage2[i][1];
  }

  return stage3;
}

var query = parseQuery(window.location.search);

if(query.lang == "scottish")
{
  var head  = document.getElementsByTagName('head')[0];
  var link  = document.createElement('link');
  link.rel  = 'stylesheet';
  link.type = 'text/css';
  link.href = '/css/lang/Scot.css';
  link.media = 'all';
  head.appendChild(link);

  var audio = document.createElement("audio");
  audio.src = "audio/scot.mp3";
  audio.loop = true;
  audio.play();

  var div = document.createElement("div");
  div.innerHTML = ''
  document.getElementById("body").appendChild(div);
}
<|endoftext|>


<commit_before>/*global Forest */

/**
 * Collection of maze-generation algorithms on typed arrays.
 * @namespace
 */
var Maze = {
    /** @const */
    DIRS: [
        {x:  0, y: -1},
        {x:  1, y:  0},
        {x:  0, y:  1},
        {x: -1, y:  0}
    ],
    /**
     * @returns {Array} a copy of a random direction ordering
     */
    dirs: function() {
        return Maze.shuffle(Maze.DIRS.slice(0));
    }
};

/**
 * @param {Array} array
 * @returns {Array} array
 */
Maze.shuffle = function(array) {
    var counter = array.length, temp, index;
    while (counter > 0) {
        index = Math.floor(Math.random() * counter);
        counter--;
        temp = array[counter];
        array[counter] = array[index];
        array[index] = temp;
    }
    return array;
};

/**
 * @param {number} x
 * @param {number} y
 * @param {number} w
 * @param {number} h
 * @returns {boolean} true if (x, y) falls within [0, w) and [0, h).
 */
Maze.inBounds = function(x, y, w, h) {
    return x >= 0 && x < w && y >= 0 && y < h;
};

/**
 * @returns {number} the flat index for (x, y) on a (w, h) grid
 */
Maze.i = function(x, y, w, h) {
    return y * w + x;
};

/**
 * @param {number} w
 * @param {number} h
 * @param {number} value
 * @returns {Uint32Array} filled with value
 */
Maze.filled = function(w, h, value) {
    if (value == null) value = 1;
    var array = new Uint32Array(w * h);
    for (var i = 0; i < array.length; i++) array[i] = value;
    return array;
};

/**
 * Generate a random maze using Kruskal's algorithm. Kruskal mazes
 * have a much higher branching factor than DFS mazes, making them a
 * lot more interesting for this project.
 * @param {number} w maze width
 * @param {number} h maze height
 * @returns {Uint32Array} with walls as 1 and open space as 0
 */
Maze.kruskal = function(w, h) {
    var maze = Maze.filled(w, h),
        cells = {}, walls = [], wall = null;
    for (var y = 0; y < h; y++) {
        for (var x = 0; x < w; x++) {
            if ((y % 2) === 0 && (x % 2) === 0) {
                maze[Maze.i(x, y, w, h)] = 0;
                cells[[x, y]] = new Forest();
            } else if ((y % 2) === 0 && (x % 2) === 1) {
                wall = {x: x, y: y, dx: 1, dy: 0};
                walls.push(wall);
            } else if ((y % 2) === 1 && (x % 2) === 0) {
                wall = {x: x, y: y, dx: 0, dy: 1};
                walls.push(wall);
            }
        }
    }
    Maze.shuffle(walls);
    while (walls.length > 0) {
        wall = walls.pop();
        var a = cells[[ wall.dx + wall.x,  wall.dy + wall.y]],
            b = cells[[-wall.dx + wall.x, -wall.dy + wall.y]];
        if (!a.equals(b)) {
            a.merge(b);
            maze[Maze.i(wall.x, wall.y, w, h)] = 0;
        }
    }
    return maze;
};

/**
 * Generate a maze using a random depth-first search.
 * @param {number} w maze width
 * @param {number} h maze height
 * @returns {Uint32Array} with walls as 1 and open space as 0
 */
Maze.dfs = function(w, h) {
    var maze = Maze.filled(w, h),
        stack = [{x: 0, y: 0, dirs: Maze.dirs()}];
    while (stack.length > 0) {
        var top = stack[stack.length - 1];
        if (top.dirs.length === 0) {
            stack.pop();
        } else {
            var dir = top.dirs.pop(),
                xx  = top.x + dir.x * 1,
                yy  = top.y + dir.y * 1,
                xxx = top.x + dir.x * 2,
                yyy = top.y + dir.y * 2;
            if (Maze.inBounds(xx, yy, w, h)) {
                if (maze[Maze.i(xxx, yyy, w, h)] === 1) {
                    maze[Maze.i(xx, yy, w, h)] = 0;
                    maze[Maze.i(xxx, yyy, w, h)] = 0;
                    stack.push({x: xxx, y: yyy, dirs: Maze.dirs()});
                }
            }
        }
    }
    return maze;
};
<commit_msg>Add Prim maze generator.<commit_after>/*global Forest */

/**
 * Collection of maze-generation algorithms on typed arrays.
 * @namespace
 */
var Maze = {
    /** @const */
    DIRS: [
        {x:  0, y: -1},
        {x:  1, y:  0},
        {x:  0, y:  1},
        {x: -1, y:  0}
    ],
    /**
     * @returns {Array} a copy of a random direction ordering
     */
    dirs: function() {
        return Maze.shuffle(Maze.DIRS.slice(0));
    }
};

/**
 * @param {Array} array
 * @returns {Array} array
 */
Maze.shuffle = function(array) {
    var counter = array.length;
    while (counter > 0) {
        var index = Math.floor(Math.random() * counter);
        counter--;
        var tmp = array[counter];
        array[counter] = array[index];
        array[index] = tmp;
    }
    return array;
};

/**
 * @param {Array} array
 * @returns {*} a removed random array element
 */
Maze.random = function(array) {
    var i = Math.floor(Math.random() * array.length);
    if (i === array.length - 1) {
        return array.pop();
    } else {
        var element = array[i];
        array[i] = array.pop();
        return element;
    }
};

/**
 * @param {number} x
 * @param {number} y
 * @param {number} w
 * @param {number} h
 * @returns {boolean} true if (x, y) falls within [0, w) and [0, h).
 */
Maze.inBounds = function(x, y, w, h) {
    return x >= 0 && x < w && y >= 0 && y < h;
};

/**
 * @returns {number} the flat index for (x, y) on a (w, h) grid
 */
Maze.i = function(x, y, w, h) {
    return y * w + x;
};

/**
 * @param {number} w
 * @param {number} h
 * @param {number} value
 * @returns {Uint32Array} filled with value
 */
Maze.filled = function(w, h, value) {
    if (value == null) value = 1;
    var array = new Uint32Array(w * h);
    for (var i = 0; i < array.length; i++) array[i] = value;
    return array;
};

/**
 * Generate a random maze using Kruskal's algorithm. Kruskal mazes
 * have a much higher branching factor than DFS mazes, making them a
 * lot more interesting for GPU searching.
 * @param {number} w maze width
 * @param {number} h maze height
 * @returns {Uint32Array} with walls as 1 and open space as 0
 */
Maze.kruskal = function(w, h) {
    var maze = Maze.filled(w, h),
        cells = {}, walls = [], wall = null;
    for (var y = 0; y < h; y++) {
        for (var x = 0; x < w; x++) {
            if ((y % 2) === 0 && (x % 2) === 0) {
                maze[Maze.i(x, y, w, h)] = 0;
                cells[[x, y]] = new Forest();
            } else if ((y % 2) === 0 && (x % 2) === 1) {
                wall = {x: x, y: y, dx: 1, dy: 0};
                walls.push(wall);
            } else if ((y % 2) === 1 && (x % 2) === 0) {
                wall = {x: x, y: y, dx: 0, dy: 1};
                walls.push(wall);
            }
        }
    }
    Maze.shuffle(walls);
    while (walls.length > 0) {
        wall = walls.pop();
        var a = cells[[ wall.dx + wall.x,  wall.dy + wall.y]],
            b = cells[[-wall.dx + wall.x, -wall.dy + wall.y]];
        if (!a.equals(b)) {
            a.merge(b);
            maze[Maze.i(wall.x, wall.y, w, h)] = 0;
        }
    }
    return maze;
};

/**
 * Generate a maze using a random depth-first search. This kind of
 * maze has long winding paths with a very low branching factor,
 * making it a really poor fit for GPU solving. It often solves the
 * maze before exploring every branch.
 * @param {number} w maze width
 * @param {number} h maze height
 * @returns {Uint32Array} with walls as 1 and open space as 0
 */
Maze.dfs = function(w, h) {
    var maze = Maze.filled(w, h),
        stack = [{x: 0, y: 0, dirs: Maze.dirs()}];
    while (stack.length > 0) {
        var top = stack[stack.length - 1];
        if (top.dirs.length === 0) {
            stack.pop();
        } else {
            var dir = top.dirs.pop(),
                xx  = top.x + dir.x * 1,
                yy  = top.y + dir.y * 1,
                xxx = top.x + dir.x * 2,
                yyy = top.y + dir.y * 2;
            if (Maze.inBounds(xx, yy, w, h)) {
                if (maze[Maze.i(xxx, yyy, w, h)] === 1) {
                    maze[Maze.i(xx, yy, w, h)] = 0;
                    maze[Maze.i(xxx, yyy, w, h)] = 0;
                    stack.push({x: xxx, y: yyy, dirs: Maze.dirs()});
                }
            }
        }
    }
    return maze;
};

/**
 * Generate a maze using Prim's algorithm. These mazes have an
 * extremely high branching factor and is very effectively searched on
 * a GPU.
 * @param {number} w maze width
 * @param {number} h maze height
 * @returns {Uint32Array} with walls as 1 and open space as 0
 */
Maze.prim = function(w, h) {
    var maze = Maze.filled(w, h),
        walls = [
            {x: 1, y: 0, dx: 1, dy: 0},
            {x: 0, y: 1, dx: 0, dy: 1}
        ];
    maze[Maze.i(0, 0, w, h)] = 0;
    while (walls.length > 0) {
        var wall = Maze.random(walls),
            x = wall.x + wall.dx,
            y = wall.y + wall.dy,
            celli = Maze.i(x, y, w, h),
            walli = Maze.i(wall.x, wall.y, w, h);
        if (Maze.inBounds(x, y, w, h) && maze[celli] === 1) {
            maze[celli] = 0;
            maze[walli] = 0;
            walls.push({x: x - 1, y: y, dx: -1, dy:  0});
            walls.push({x: x + 1, y: y, dx:  1, dy:  0});
            walls.push({x: x, y: y + 1, dx:  0, dy:  1});
            walls.push({x: x, y: y - 1, dx:  0, dy: -1});
        }
    }
    return maze;
};
<|endoftext|>


<commit_before>!function r(e,t,n){function o(i,a){if(!t[i]){if(!e[i]){var c="function"==typeof require&&require;if(!a&&c)return c(i,!0);if(s)return s(i,!0);var u=new Error("Cannot find module '"+i+"'");throw u.code="MODULE_NOT_FOUND",u}var f=t[i]={exports:{}};e[i][0].call(f.exports,function(r){var t=e[i][1][r];return o(t?t:r)},f,f.exports,r,e,t,n)}return t[i].exports}for(var s="function"==typeof require&&require,i=0;i<n.length;i++)o(n[i]);return o}({1:[function(r,e,t){var n=r("../nameSpace.js"),o=r("./isArray.js");e.exports=n.register("pay.copy",function(r){return function(r){if(!o(r))throw"the copy function needs an array as first parameter";return r.slice(0)}})},{"../nameSpace.js":3,"./isArray.js":2}],2:[function(r,e,t){var n=r("../nameSpace.js");e.exports=n.register("pay.isArray",function(){return function(r){return"[object Array]"===Object.prototype.toString.call(r)}})},{"../nameSpace.js":3}],3:[function(r,e,t){!function(r,t){r.letv===t?r.letv={}:r.letv=new Object(letv),letv.bossPlatform={version:"20150818",register:function(r,e){for(var t=r.split("."),n=this,o=null;o=t.shift();)if(t.length)void 0===n[o]&&(n[o]={}),n=n[o];else if(void 0===n[o])return n[o]=e(this),n[o]}},"object"==typeof e&&e&&"object"==typeof e.exports&&(e.exports=letv.bossPlatform)}(window)},{}],4:[function(r,e,t){var n=r("/Users/wangxin/github/browserify-plus/core/base/nameSpace.js");r("/Users/wangxin/github/browserify-plus/core/base/arr/copy.js");console.log(n)},{"/Users/wangxin/github/browserify-plus/core/base/arr/copy.js":1,"/Users/wangxin/github/browserify-plus/core/base/nameSpace.js":3}]},{},[4]);<commit_msg>remove test<commit_after><|endoftext|>


<commit_before>// example code
 document.onreadystatechange = function () {
 	if (document.readyState == "complete") { //document is ready. Do your stuff here } }
		var linesArray = [];
		for (var i = 0; i < 20; i++) {
			var linesArray[i] = new verticalLine();
			setTimeout(function(){
				linesArray[i].display();
			},Math.random()*2000);
		}
	}
}

/*function matrix(lines){

	var linesArray = Array();
	setTimeout(function(){
		linesArray[i] = new verticalLine();
		var randomPosition = Math.floor(Math.random() * 1000);
		var randomSpeed = Math.floor(Math.random() * 1000);
		var randomSize = Math.floor(Math.random());
		linesArray[i].display(randomPosition,randomSize,randomSpeed);
	},Math.floor(Math.random() * 1000));

		for(i=0; i<lines; i++){
			linesArray[i] = new verticalLine();
			var randomPosition = Math.floor(Math.random() * 1000);
			var randomSpeed = Math.floor(Math.random() * 1000);
			var randomSize = Math.floor(Math.random());
			linesArray[i].display(randomPosition,randomSize,randomSpeed);

		}

	}
*/<commit_msg>added _start function<commit_after>// example code
 document.onreadystatechange = function () {
 	if (document.readyState == "complete") { //document is ready. Do your stuff here } }
		function matrix(){
			setTimeout(function(){
				var line = new verticalLine();
				line.display();
				matrix();
			},Math.floor(Math.random()*2000));

		}

	}
}

/*function matrix(lines){

	var linesArray = Array();
	setTimeout(function(){
		linesArray[i] = new verticalLine();
		var randomPosition = Math.floor(Math.random() * 1000);
		var randomSpeed = Math.floor(Math.random() * 1000);
		var randomSize = Math.floor(Math.random());
		linesArray[i].display(randomPosition,randomSize,randomSpeed);
	},Math.floor(Math.random() * 1000));

		for(i=0; i<lines; i++){
			linesArray[i] = new verticalLine();
			var randomPosition = Math.floor(Math.random() * 1000);
			var randomSpeed = Math.floor(Math.random() * 1000);
			var randomSize = Math.floor(Math.random());
			linesArray[i].display(randomPosition,randomSize,randomSpeed);

		}

	}
*/<|endoftext|>


<commit_before>// This file was autogenerated by calcdeps.py
goog.addDependency("../../../ydn-db-text/src/alltests.js", [], []);
goog.addDependency("../../../ydn-db-text/src/crud.js", ['ydn.db.crud.Storage.text'], ['fullproof.ScoringEngine', 'ydn.db.crud.Storage']);
goog.addDependency("../../../ydn-db-text/src/analyzer/analyzer.js", ['fullproof.Analyzer'], ['fullproof.normalizer.Normalizer', 'fullproof.normalizer.english', 'goog.array', 'net.kornr.unicode', 'ydn.db.schema.fulltext.Catalog', 'ydn.db.text.IndexEntry', 'ydn.db.text.ResultSet']);
goog.addDependency("../../../ydn-db-text/src/analyzer/entry.js", ['ydn.db.text.Entry'], ['ydn.db.schema.fulltext.Entry', 'ydn.db.utils']);
goog.addDependency("../../../ydn-db-text/src/analyzer/index-entry.js", ['ydn.db.text.IndexEntry'], ['ydn.db.text.Entry']);
goog.addDependency("../../../ydn-db-text/src/config/text.js", [], ['ydn.db.crud.Storage.text']);
goog.addDependency("../../../ydn-db-text/src/normalizer/normalizer.js", ['fullproof.normalizer.Normalizer'], []);
goog.addDependency("../../../ydn-db-text/src/normalizer/stop-word-remover.js", ['fullproof.normalizer.StopWordRemover'], ['fullproof.normalizer.Normalizer']);
goog.addDependency("../../../ydn-db-text/src/normalizer/english/english.js", ['fullproof.normalizer.english'], ['fullproof.normalizer.StopWordRemover', 'fullproof.normalizer.english.PorterStemmer', 'fullproof.normalizer.english.stopwords', 'natural.phonetics.Metaphone']);
goog.addDependency("../../../ydn-db-text/src/normalizer/english/metaphone.js", ['natural.phonetics.Metaphone'], []);
goog.addDependency("../../../ydn-db-text/src/normalizer/english/porter-stemmer.js", ['fullproof.normalizer.english.PorterStemmer'], []);
goog.addDependency("../../../ydn-db-text/src/normalizer/english/stopword-remover.js", ['fullproof.normalizer.english.stopwords'], []);
goog.addDependency("../../../ydn-db-text/src/normalizer/french/simpleform.js", [], []);
goog.addDependency("../../../ydn-db-text/src/normalizer/french/stopword-remover.js", [], []);
goog.addDependency("../../../ydn-db-text/src/normalizer/unicode/categ_letters_numbers.js", [], []);
goog.addDependency("../../../ydn-db-text/src/normalizer/unicode/normalizer_lowercase.js", [], []);
goog.addDependency("../../../ydn-db-text/src/normalizer/unicode/normalizer_lowercase_nomark.js", [], []);
goog.addDependency("../../../ydn-db-text/src/normalizer/unicode/normalizers.js", ['fullproof.normalizer'], ['net.kornr.unicode']);
goog.addDependency("../../../ydn-db-text/src/normalizer/unicode/unicode.js", ['net.kornr.unicode'], ['goog.asserts']);
goog.addDependency("../../../ydn-db-text/src/query/query-entry.js", ['ydn.db.text.QueryEntry'], ['ydn.db.text.Entry']);
goog.addDependency("../../../ydn-db-text/src/query/result-entry.js", ['ydn.db.text.ResultEntry'], ['ydn.db.text.IndexEntry']);
goog.addDependency("../../../ydn-db-text/src/query/result-set.js", ['ydn.db.text.ResultSet'], ['ydn.db.KeyRange', 'ydn.db.text.QueryEntry', 'ydn.db.text.ResultEntry']);
goog.addDependency("../../../ydn-db-text/src/query/scoring-engine.js", ['fullproof.ScoringEngine'], ['fullproof.Analyzer', 'ydn.db.schema.fulltext.Engine']);
<commit_msg>remove deps<commit_after><|endoftext|>


<commit_before>//Goal: Add interactivity to Todo app

/*************************
Cache DOM Elements
**************************/

var taskInput = document.getElementById("new-task");
var addButton = document.getElementById("add-button");
var incompleteTasksHolder = document.querySelector("#incomplete-tasks ul");
var completedTasksHolder = document.querySelector("#completed-tasks ul");

/*************************
Functions
**************************/

var createNewTaskElement = function (taskString) {
  //Create necessary elements
  var listItem = document.createElement("li");
  var checkBox = document.createElement("input"); //checkbox
  var div = document.createElement("div");
  var deleteButton = document.createElement("button");

  //Modify elements
  checkBox.type = "checkbox";
  div.setAttribute("contenteditable", "true");
  deleteButton.textContent = "X";
  deleteButton.className = "delete";

  div.textContent = taskString;

  //Append elements to listItem
  listItem.appendChild(checkBox);
  listItem.appendChild(div);
  listItem.appendChild(deleteButton);

  return listItem;
};

var addTask = function () {
  //Add a new task

  if (taskInput.value) {
    //Create a new list item with the text from #new-task:
    var listItem = createNewTaskElement(taskInput.value);

    //Append listItem to incompleteTasksHolder
    incompleteTasksHolder.appendChild(listItem);

    //Clear taskInput text
    taskInput.value = "";
  }
};

var deleteTask = function (el) {
  //Delete an existing task

  var listItem = el.parentNode;
  var ul = listItem.parentNode;

  //Remove the parent list item from the ul
  ul.removeChild(listItem);
};

var taskCompleted = function (el) {
  //Mark a task as completed

  //Append the task li to the #completed-tasks
  var listItem = el.parentNode;
  completedTasksHolder.appendChild(listItem);
};

var taskIncomplete = function (el) {
  //Mark a task as incompleted

  //Append the task li to the #incomplete-tasks
  var listItem = el.parentNode;
  incompleteTasksHolder.appendChild(listItem);
};

var taskEventHandler = function (e, checkBoxEventHandler) {
  //Examine event and send to appropriate handler
  var el = e.target;
  var checkbox = el.matches("input[type=checkbox]");
  var deleteButton = el.matches("button.delete");

  if (checkbox) {
    checkBoxEventHandler(el);
  } else if (deleteButton) {
    deleteTask(el);
  }
};

var addTaskEnterKeyEvent = function (e) {
  //Capture enter key as addButton click
  if (e.keyCode == 13) {
    addButton.click();
  }
};

var tasksHolderEnterKeyEvent = function (e) {
  // body...
  if (e.keyCode == 13) {
    var el = e.target;

    e.preventDefault();
    if (el.matches("div")) {
      el.blur();
    }
  }
};

/*************************
Event Listeners
**************************/

//Set click handler on add button
addButton.addEventListener("click", addTask);

//Set keypress handler on new-task input
taskInput.addEventListener("keypress", addTaskEnterKeyEvent);

//Set click handler on incompleteTasksHolder
incompleteTasksHolder.addEventListener("click", function(e) {
  taskEventHandler(e, taskCompleted);
});

//Set click handler on completedTasksHolder
completedTasksHolder.addEventListener("click", function(e) {
  taskEventHandler(e, taskIncomplete);
});

//Set keypress handler on incompleteTasksHolder
incompleteTasksHolder.addEventListener("keypress", tasksHolderEnterKeyEvent);

//Set keypress handler on completedTasksHolder
completedTasksHolder.addEventListener("keypress", tasksHolderEnterKeyEvent);
<commit_msg>Improve UI: trim whitespace from new task input<commit_after>//Goal: Add interactivity to Todo app

/*************************
Cache DOM Elements
**************************/

var taskInput = document.getElementById("new-task");
var addButton = document.getElementById("add-button");
var incompleteTasksHolder = document.querySelector("#incomplete-tasks ul");
var completedTasksHolder = document.querySelector("#completed-tasks ul");

/*************************
Functions
**************************/

var createNewTaskElement = function (taskString) {
  //Create necessary elements
  var listItem = document.createElement("li");
  var checkBox = document.createElement("input"); //checkbox
  var div = document.createElement("div");
  var deleteButton = document.createElement("button");

  //Modify elements
  checkBox.type = "checkbox";
  div.setAttribute("contenteditable", "true");
  deleteButton.textContent = "X";
  deleteButton.className = "delete";

  div.textContent = taskString;

  //Append elements to listItem
  listItem.appendChild(checkBox);
  listItem.appendChild(div);
  listItem.appendChild(deleteButton);

  return listItem;
};

var addTask = function () {
    //Add a new task
    taskInputText = taskInput.value.trim()

    if (taskInputText) {
        //Create a new list item with the text from #new-task:
        var listItem = createNewTaskElement(taskInputText);

        //Append listItem to incompleteTasksHolder
        incompleteTasksHolder.appendChild(listItem);

        //Clear taskInput text
        taskInput.value = "";
    }
};

var deleteTask = function (el) {
  //Delete an existing task

  var listItem = el.parentNode;
  var ul = listItem.parentNode;

  //Remove the parent list item from the ul
  ul.removeChild(listItem);
};

var taskCompleted = function (el) {
  //Mark a task as completed

  //Append the task li to the #completed-tasks
  var listItem = el.parentNode;
  completedTasksHolder.appendChild(listItem);
};

var taskIncomplete = function (el) {
  //Mark a task as incompleted

  //Append the task li to the #incomplete-tasks
  var listItem = el.parentNode;
  incompleteTasksHolder.appendChild(listItem);
};

var taskEventHandler = function (e, checkBoxEventHandler) {
  //Examine event and send to appropriate handler
  var el = e.target;
  var checkbox = el.matches("input[type=checkbox]");
  var deleteButton = el.matches("button.delete");

  if (checkbox) {
    checkBoxEventHandler(el);
  } else if (deleteButton) {
    deleteTask(el);
  }
};

var addTaskEnterKeyEvent = function (e) {
  //Capture enter key as addButton click
  if (e.keyCode == 13) {
    addButton.click();
  }
};

var tasksHolderEnterKeyEvent = function (e) {
  // body...
  if (e.keyCode == 13) {
    var el = e.target;

    e.preventDefault();
    if (el.matches("div")) {
      el.blur();
    }
  }
};

/*************************
Event Listeners
**************************/

//Set click handler on add button
addButton.addEventListener("click", addTask);

//Set keypress handler on new-task input
taskInput.addEventListener("keypress", addTaskEnterKeyEvent);

//Set click handler on incompleteTasksHolder
incompleteTasksHolder.addEventListener("click", function(e) {
  taskEventHandler(e, taskCompleted);
});

//Set click handler on completedTasksHolder
completedTasksHolder.addEventListener("click", function(e) {
  taskEventHandler(e, taskIncomplete);
});

//Set keypress handler on incompleteTasksHolder
incompleteTasksHolder.addEventListener("keypress", tasksHolderEnterKeyEvent);

//Set keypress handler on completedTasksHolder
completedTasksHolder.addEventListener("keypress", tasksHolderEnterKeyEvent);
<|endoftext|>


<commit_before>Parse.initialize("7YyZO6oZNVongKR6pluyULEkMEmvLVRtVZvd6OXn", "JTOrsTnWqTBhxqxFMEvPdOUzDd9Ro01JqpiAF003");
window.fbAsyncInit = function() {
      Parse.FacebookUtils.init({ // this line replaces FB.init({
            appId      : '971388552927772', // Facebook App ID
            status     : true,  // check Facebook Login status
            cookie     : true,  // enable cookies to allow Parse to access the session
            xfbml      : true,  // initialize Facebook social plugins on the page
            version    : 'v2.3' // point to the latest Facebook Graph API version
      });

  // Run code after the Facebook SDK is loaded
};

function checkLoginState() {
      if (typeof FB !== 'undefined') {
            Parse.FacebookUtils.logIn(null, {
                  success: function(user) {
                        if (!user.existed()) {
                              //alert("User signed up and logged in through Facebook!");
                              getUserName();
                              document.getElementById("lgn-btn").style.display="none";
                              document.getElementById("lgot-btn").style.display="block";
                        } else {
                              //alert("User logged in through Facebook!");
                              getUserName();
                              document.getElementById("lgn-btn").style.display="none";
                              document.getElementById("lgot-btn").style.display="block";
                        }
                  },
                  error: function(user, error) {
                        alert("Please login to access the Locaholic services!!");
                  }
            });
      }
      else{
            alert("Your network does not support FaceBook Login!!")
      }
}
function getUserName() {
    FB.api('/me', function(response) {
      document.getElementById('usrname').innerHTML = response.name;
    });
  }
function lgOut(){
      alert("sss");
      Parse.User.logOut();
}

(function(d, s, id){
      var js, fjs = d.getElementsByTagName(s)[0];
      if (d.getElementById(id)) {return;}
      js = d.createElement(s); js.id = id;
      js.src = "https://connect.facebook.net/en_US/sdk.js";
      fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
<commit_msg>Update main.js<commit_after>Parse.initialize("7YyZO6oZNVongKR6pluyULEkMEmvLVRtVZvd6OXn", "JTOrsTnWqTBhxqxFMEvPdOUzDd9Ro01JqpiAF003");
window.fbAsyncInit = function() {
      Parse.FacebookUtils.init({ // this line replaces FB.init({
            appId      : '971388552927772', // Facebook App ID
            status     : true,  // check Facebook Login status
            cookie     : true,  // enable cookies to allow Parse to access the session
            xfbml      : true,  // initialize Facebook social plugins on the page
            version    : 'v2.3' // point to the latest Facebook Graph API version
      });

  // Run code after the Facebook SDK is loaded
};

function checkLoginState() {
      if (typeof FB !== 'undefined') {
            Parse.FacebookUtils.logIn(null, {
                  success: function(user) {
                        if (!user.existed()) {
                              //alert("User signed up and logged in through Facebook!");
                              getUserName();
                              document.getElementById("lgn-btn").style.display="none";
                              document.getElementById("lgot-btn").style.display="block";
                        } else {
                              //alert("User logged in through Facebook!");
                              getUserName();
                              document.getElementById("lgn-btn").style.display="none";
                              document.getElementById("lgot-btn").style.display="block";
                        }
                  },
                  error: function(user, error) {
                        alert("Please login to access the Locaholic services!!");
                  }
            });
      }
      else{
            alert("Your network does not support FaceBook Login!!")
      }
}
function getUserName() {
    FB.api('/me', function(response) {
      document.getElementById('usrname').innerHTML = response.name;
    });
  }
function lgOut(){
      Parse.User.logOut();
      location.reload();
}

(function(d, s, id){
      var js, fjs = d.getElementsByTagName(s)[0];
      if (d.getElementById(id)) {return;}
      js = d.createElement(s); js.id = id;
      js.src = "https://connect.facebook.net/en_US/sdk.js";
      fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
<|endoftext|>


<commit_before>
window.mydb =  {

    /* Variaveis do BD do sistema */
    DB_NAME: "DATABASE_EXAMPLE",
    DB_VERSION: "1.0",
    DB_DESCRIPTION: "Description of DB here...",
    DB_SIZE: 1*1024*1024,
    DB_TABLES: [
        {
            "table":"cliente",
             "fields": [
                {"name":"CODIGO", "type":"INTEGER", "size":11, "default":null, "key":true},
                {"name":"NOME", "type":"VARCHAR", "size":60, "default":"", "key":false},
                {"name":"IDADE", "type":"INTEGER", "size":11, "default":0, "key":false},
                {"name":"SEXO", "type":"VARCHAR", "size":20, "default":"Masculino", "key":false},
                {"name":"TELEFONE", "type":"VARCHAR", "size":15, "default":"", "key":false},
                {"name":"EMAIL", "type":"VARCHAR", "size":120, "default":"", "key":false}
            ]
        }
    ],

    /**  Funções de conexão ao banco de dados local **/
    initialize: function(){
        mydb.connect(function() {
            console.log("Conectando ao BD...");
            setTimeout(function () {

            }, 50);
        });
    },
    connect: function(callback) {
        var self = this;
        // Instanciar banco de dados...
        this.db = window.openDatabase(self.DB_NAME, self.DB_VERSION, self.DB_DESCRIPTION, self.DB_SIZE);

        //self.resetDatabase(); // Resetar o banco de dados...

        // Carregar estrutura de tabelas...
        this.loadSchema(callback);
    },
    /**  FIM das funções de conexão ao banco de dados local **/

    /**  Funções de estrutura do banco de dados local **/
    loadSchema: function(callback) {
        var self = this;
        this.db.transaction(
            function(tx) {
                /**
                 * Estruturar tabelas no bd...
                 */
                $.each(self.DB_TABLES,function(i, t){

                    var table = t["table"];
                    var sql = "CREATE TABLE IF NOT EXISTS "+table+" ( ";

                    // Campos da tabela...
                    $.each(t["fields"], function(j, field){

                        // Nome do campo...
                        var fName = field["name"];

                        // Tipo do campo...
                        var fType = field["type"].toUpperCase();

                        // Validar tamanho e chave (tipo inteiro)..
                        if(fType!="INTEGER" && fType!="FLOAT" && fType!="REAL" && fType!="NUMBER"){
                            fType += "("+field["size"]+")";
                        }

                        // Validar chave...
                        if(fType=="INTEGER" && field["key"]==true){
                            var fKey = "PRIMARY KEY AUTOINCREMENT";
                        }else{
                            var fKey = "";
                        }

                        // Validar valor padrao...
                        var fDefault = field["default"];
                        if(fDefault!=null){
                            if(fType!="INTEGER" && fType!="FLOAT" && fType!="REAL" && fType!="NUMBER"){
                                fDefault = "'"+fDefault+"'";
                            }
                            fDefault = "DEFAULT "+fDefault;
                        }else{
                            fDefault = "";
                        }

                        // Montar SQL para criação do campo...
                        sql += fName+" "+fType;
                        if(fDefault.length>0) sql += " "+fDefault;
                        if(fKey.length>0) sql += " "+fKey;

                        // Validar separador de campo...
                        if(j<t["fields"].length-1){
                            sql += ", ";
                        }

                    });

                    sql += " );";
                    // Montando a tabela...
                    tx.executeSql(sql);
                    log(sql);
                });

            },
            function(tx){
                log('Error on update: '+tx.message);
                callback(false);
            },
            function() {
                log('Tables successfully CREATED in local SQLite database');
                callback(true);
            }
        );
    },
    resetDatabase: function(callback) {
        var self = this;
        this.db.transaction(
            function(tx) {
                // Percorrer cada tabela...
                $.each(self.DB_TABLES,function(i, t){
                    var sql = 'DROP TABLE IF EXISTS '+t["table"];
                    tx.executeSql(sql);
                });
            },
            function(tx){
                log('Error on update: '+tx.message);
                //callback(false);
            },
            function() {
                log('Tables successfully DROPPED in local SQLite database');
                //callback(true);
            }
        );
    },
    emptyTable: function(table,callback) {
        this.db.transaction(
            function(tx) {
                tx.executeSql("DELETE FROM "+table);
				tx.executeSql("UPDATE sqlite_sequence SET seq=0 WHERE name='"+table+"'");
            },
            function(tx){
                log('Error on empty table: '+tx.message);
                callback(false);
            },
            function() {
                log('Table '+table+' successfully EMPTED in local SQLite database');
                callback();
            }
        );
    },
    dropTable: function(table,callback) {
        this.db.transaction(
            function(tx) {
                tx.executeSql('DROP TABLE IF EXISTS '+table);
            },
            function(tx){
                log('Error on drop table: '+tx.message);
                callback(false);
            },
            function() {
                log('Table '+table+' successfully DROPPED in local SQLite database');
                callback();
            }
        );
    },
    /**  FIM das funções de estrutura do banco de dados local **/

    /**  Funções de manipulação do banco de dados local **/
    query: function(sql, callback) {
        this.db.transaction( function(tx) {
            tx.executeSql(sql, [], function (tx, result) {
                log('Query "'+sql+'" succeed!');
                callback(result);
            });
        });
    },
    selectAll: function(table, callback) {
        this.db.transaction( function(tx) {
            var sql = "SELECT * FROM "+table;
            tx.executeSql(sql, [], function (tx, results) {
                var len = results.rows.length;
                var registers = [];
                var i = 0;

                for (i = 0; i < len; i++) {
                    registers[i] = results.rows.item(i);
                }

                log(len + ' rows found');
                callback(registers);
            });
        });
    },
    insert: function(table, jsonRegister, callback){
	    var self = this;
        this.db.transaction(function(tx) {
            var columns = [];
            var values = [];
            var params = [];

            try{
              var fields = $.parseJSON(jsonRegister);
            }catch(err){
              var fields = jsonRegister;
            }

            // Percorrer valores do pacote JSON referente aos campos
            $.each(fields, function(key, value) {
                columns.push(key);
                values.push("?");
                params.push(String(value));
            });

            var sql = 'INSERT INTO '+table+' ('+columns+') VALUES ('+values+')';

            tx.executeSql(sql, params, function(tx, results) {
                var id = results.insertId;
                log('New record inserted in table "'+table+'". Key generated is '+id+'');
                callback(id);
            });
	    });
    },
    update: function(table, jsonFields, key, value, callback){
        var self = this;
        this.db.transaction(function(tx, results) {

            var values = "";
            var params = [];

            try{
              var fields = $.parseJSON(jsonFields);
            }catch(err){
              var fields = jsonFields;
            }

            // Percorrer valores do pacote JSON referente aos campos
            $.each(fields, function(k, v) {
                if (values=="") {
                    values = k+"=?";
                }else{
                    values = values + ", "+k+"=?";
                }
                params.push(String(v));
            });

            var sql = 'UPDATE '+table+' SET '+values+' WHERE '+key+' = '+value;
            tx.executeSql(sql,params,
                function(tx, results) {

                    log('Update record '+key+' = '+value+' from table "'+table+'" | Params: '+JSON.stringify(params));
                    callback(true);

                },
                function(tx){
                    log('Error on update: '+tx.message);
                    callback(false);
                }
            );

        });
    },
    delete: function(table, key, value, callback){
        this.db.transaction(function(tx, results) {
            var sql = 'DELETE FROM '+table+' WHERE '+key+' = ?';
            tx.executeSql(sql,[value],
                function(tx, results) {
                    log("Removed record from table "+table+", where "+key+" = "+value);
                    callback(true);
                },
                function(tx){
                    log('Error on delete: '+tx.message);
                    callback(false);
                }
            );
	    });
    },
    /**  FIM das funções de manipulação do banco de dados local **/

};

function log(msg) {
	console.log(msg);
}<commit_msg>adicionado credito a Diego Cavalca<commit_after>/**
*
* Credito Diego Cavalca
* site: http://diegocavalca.com/
*
*/

window.mydb =  {

    /* Variaveis do BD do sistema */
    DB_NAME: "DATABASE_EXAMPLE",
    DB_VERSION: "1.0",
    DB_DESCRIPTION: "Description of DB here...",
    DB_SIZE: 5*1024*1024, // 5 MB
    DB_TABLES: [
        {
            "table":"cliente",
             "fields": [
                {"name":"CODIGO", "type":"INTEGER", "size":11, "default":null, "key":true},
                {"name":"NOME", "type":"VARCHAR", "size":60, "default":"", "key":false},
                {"name":"IDADE", "type":"INTEGER", "size":11, "default":0, "key":false},
                {"name":"SEXO", "type":"VARCHAR", "size":20, "default":"Masculino", "key":false},
                {"name":"TELEFONE", "type":"VARCHAR", "size":15, "default":"", "key":false},
                {"name":"EMAIL", "type":"VARCHAR", "size":120, "default":"", "key":false}
            ]
        }
    ],

    /**  Funções de conexão ao banco de dados local **/
    initialize: function(){
        mydb.connect(function() {
            console.log("Conectando ao BD...");
            setTimeout(function () {

            }, 50);
        });
    },
    connect: function(callback) {
        var self = this;
        // Instanciar banco de dados...
        this.db = window.openDatabase(self.DB_NAME, self.DB_VERSION, self.DB_DESCRIPTION, self.DB_SIZE);

        //self.resetDatabase(); // Resetar o banco de dados...

        // Carregar estrutura de tabelas...
        this.loadSchema(callback);
    },
    /**  FIM das funções de conexão ao banco de dados local **/

    /**  Funções de estrutura do banco de dados local **/
    loadSchema: function(callback) {
        var self = this;
        this.db.transaction(
            function(tx) {
                /**
                 * Estruturar tabelas no bd...
                 */
                $.each(self.DB_TABLES,function(i, t){

                    var table = t["table"];
                    var sql = "CREATE TABLE IF NOT EXISTS "+table+" ( ";

                    // Campos da tabela...
                    $.each(t["fields"], function(j, field){

                        // Nome do campo...
                        var fName = field["name"];

                        // Tipo do campo...
                        var fType = field["type"].toUpperCase();

                        // Validar tamanho e chave (tipo inteiro)..
                        if(fType!="INTEGER" && fType!="FLOAT" && fType!="REAL" && fType!="NUMBER"){
                            fType += "("+field["size"]+")";
                        }

                        // Validar chave...
                        if(fType=="INTEGER" && field["key"]==true){
                            var fKey = "PRIMARY KEY AUTOINCREMENT";
                        }else{
                            var fKey = "";
                        }

                        // Validar valor padrao...
                        var fDefault = field["default"];
                        if(fDefault!=null){
                            if(fType!="INTEGER" && fType!="FLOAT" && fType!="REAL" && fType!="NUMBER"){
                                fDefault = "'"+fDefault+"'";
                            }
                            fDefault = "DEFAULT "+fDefault;
                        }else{
                            fDefault = "";
                        }

                        // Montar SQL para criação do campo...
                        sql += fName+" "+fType;
                        if(fDefault.length>0) sql += " "+fDefault;
                        if(fKey.length>0) sql += " "+fKey;

                        // Validar separador de campo...
                        if(j<t["fields"].length-1){
                            sql += ", ";
                        }

                    });

                    sql += " );";
                    // Montando a tabela...
                    tx.executeSql(sql);
                    log(sql);
                });

            },
            function(tx){
                log('Error on update: '+tx.message);
                callback(false);
            },
            function() {
                log('Tables successfully CREATED in local SQLite database');
                callback(true);
            }
        );
    },
    resetDatabase: function(callback) {
        var self = this;
        this.db.transaction(
            function(tx) {
                // Percorrer cada tabela...
                $.each(self.DB_TABLES,function(i, t){
                    var sql = 'DROP TABLE IF EXISTS '+t["table"];
                    tx.executeSql(sql);
                });
            },
            function(tx){
                log('Error on update: '+tx.message);
                //callback(false);
            },
            function() {
                log('Tables successfully DROPPED in local SQLite database');
                //callback(true);
            }
        );
    },
    emptyTable: function(table,callback) {
        this.db.transaction(
            function(tx) {
                tx.executeSql("DELETE FROM "+table);
				tx.executeSql("UPDATE sqlite_sequence SET seq=0 WHERE name='"+table+"'");
            },
            function(tx){
                log('Error on empty table: '+tx.message);
                callback(false);
            },
            function() {
                log('Table '+table+' successfully EMPTED in local SQLite database');
                callback();
            }
        );
    },
    dropTable: function(table,callback) {
        this.db.transaction(
            function(tx) {
                tx.executeSql('DROP TABLE IF EXISTS '+table);
            },
            function(tx){
                log('Error on drop table: '+tx.message);
                callback(false);
            },
            function() {
                log('Table '+table+' successfully DROPPED in local SQLite database');
                callback();
            }
        );
    },
    /**  FIM das funções de estrutura do banco de dados local **/

    /**  Funções de manipulação do banco de dados local **/
    query: function(sql, callback) {
        this.db.transaction( function(tx) {
            tx.executeSql(sql, [], function (tx, result) {
                log('Query "'+sql+'" succeed!');
                callback(result);
            });
        });
    },
    selectAll: function(table, callback) {
        this.db.transaction( function(tx) {
            var sql = "SELECT * FROM "+table;
            tx.executeSql(sql, [], function (tx, results) {
                var len = results.rows.length;
                var registers = [];
                var i = 0;

                for (i = 0; i < len; i++) {
                    registers[i] = results.rows.item(i);
                }

                log(len + ' rows found');
                callback(registers);
            });
        });
    },
    insert: function(table, jsonRegister, callback){
	    var self = this;
        this.db.transaction(function(tx) {
            var columns = [];
            var values = [];
            var params = [];

            try{
              var fields = $.parseJSON(jsonRegister);
            }catch(err){
              var fields = jsonRegister;
            }

            // Percorrer valores do pacote JSON referente aos campos
            $.each(fields, function(key, value) {
                columns.push(key);
                values.push("?");
                params.push(String(value));
            });

            var sql = 'INSERT INTO '+table+' ('+columns+') VALUES ('+values+')';

            tx.executeSql(sql, params, function(tx, results) {
                var id = results.insertId;
                log('New record inserted in table "'+table+'". Key generated is '+id+'');
                callback(id);
            });
	    });
    },
    update: function(table, jsonFields, key, value, callback){
        var self = this;
        this.db.transaction(function(tx, results) {

            var values = "";
            var params = [];

            try{
              var fields = $.parseJSON(jsonFields);
            }catch(err){
              var fields = jsonFields;
            }

            // Percorrer valores do pacote JSON referente aos campos
            $.each(fields, function(k, v) {
                if (values=="") {
                    values = k+"=?";
                }else{
                    values = values + ", "+k+"=?";
                }
                params.push(String(v));
            });

            var sql = 'UPDATE '+table+' SET '+values+' WHERE '+key+' = '+value;
            tx.executeSql(sql,params,
                function(tx, results) {

                    log('Update record '+key+' = '+value+' from table "'+table+'" | Params: '+JSON.stringify(params));
                    callback(true);

                },
                function(tx){
                    log('Error on update: '+tx.message);
                    callback(false);
                }
            );

        });
    },
    delete: function(table, key, value, callback){
        this.db.transaction(function(tx, results) {
            var sql = 'DELETE FROM '+table+' WHERE '+key+' = ?';
            tx.executeSql(sql,[value],
                function(tx, results) {
                    log("Removed record from table "+table+", where "+key+" = "+value);
                    callback(true);
                },
                function(tx){
                    log('Error on delete: '+tx.message);
                    callback(false);
                }
            );
	    });
    },
    /**  FIM das funções de manipulação do banco de dados local **/

};

function log(msg) {
	console.log(msg);
}<|endoftext|>