<commit_before>if(!Images) {
  var Images = {
    avatarTeam: "https://www.kasandbox.org/programming-images/avatars/avatar-team.png",
    aqualineSeed: "https://www.kasandbox.org/programming-images/avatars/aqualine-seed.png",
    aqualineSeedling: "https://www.kasandbox.org/programming-images/avatars/aqualine-seedling.png",
    aqualineSapling: "https://www.kasandbox.org/programming-images/avatars/aqualine-sapling.png",
    aqualineTree: "https://www.kasandbox.org/programming-images/avatars/aqualine-tree.png",
    aqualineUltimate: "https://www.kasandbox.org/programming-images/avatars/aqualine-ultimate.png",
    duskpinSeed: "https://www.kasandbox.org/programming-images/avatars/duskpin-seed.png",
    duskpinSeedling: "https://www.kasandbox.org/programming-images/avatars/duskpin-seedling.png",
    duskpinSapling: "https://www.kasandbox.org/programming-images/avatars/duskpin-sapling.png",
    duskpinTree: "https://www.kasandbox.org/programming-images/avatars/duskpin-tree.png",
    duskpinUltimate: "https://www.kasandbox.org/programming-images/avatars/duskpin-ultimate.png",
    leafersSeed: "https://www.kasandbox.org/programming-images/avatars/leafers-seed.png",
    leafersSeedling: "https://www.kasandbox.org/programming-images/avatars/leafers-seedling.png",
    leafersSapling: "https://www.kasandbox.org/programming-images/avatars/leafers-sapling.png",
    leafersTree: "https://www.kasandbox.org/programming-images/avatars/leafers-tree.png",
    leafersUltimate: "https://www.kasandbox.org/programming-images/avatars/leafers-ultimate.png",
    piceratopsSeed: "https://www.kasandbox.org/programming-images/avatars/piceratops-seed.png",
    piceratopsSeedling: "https://www.kasandbox.org/programming-images/avatars/piceratops-seedling.png",
    piceratopsSapling: "https://www.kasandbox.org/programming-images/avatars/piceratops-sapling.png",
    piceratopsTree: "https://www.kasandbox.org/programming-images/avatars/piceratops-tree.png",
    piceratopsUltimate: "https://www.kasandbox.org/programming-images/avatars/piceratops-ultimate.png",
    primosaurSeed: "https://www.kasandbox.org/programming-images/avatars/primosaur-seed.png",
    primosaurSeedling: "https://www.kasandbox.org/programming-images/avatars/primosaur-seedling.png",
    primosaurSapling: "https://www.kasandbox.org/programming-images/avatars/primosaur-sapling.png",
    primosaurTree: "https://www.kasandbox.org/programming-images/avatars/primosaur-tree.png",
    primosaurUltimate: "https://www.kasandbox.org/programming-images/avatars/primosaur-ultimate.png",
    starkySeed: "https://www.kasandbox.org/programming-images/avatars/starky-seed.png",
    starkySeedling: "https://www.kasandbox.org/programming-images/avatars/starky-seedling.png",
    starkySapling: "https://www.kasandbox.org/programming-images/avatars/starky-sapling.png",
    starkyTree: "https://www.kasandbox.org/programming-images/avatars/starky-tree.png",
    starkyUltimate: "https://www.kasandbox.org/programming-images/avatars/starky-ultimate.png",
    leafBlue: "https://www.kasandbox.org/programming-images/avatars/leaf-blue.png",
    leafGreen: "https://www.kasandbox.org/programming-images/avatars/leaf-green.png",
    leafGray: "https://www.kasandbox.org/programming-images/avatars/leaf-gray.png",
    leafOrange: "https://www.kasandbox.org/programming-images/avatars/leaf-orange.png",
    leafRed: "https://www.kasandbox.org/programming-images/avatars/leaf-red.png",
    leafYellow: "https://www.kasandbox.org/programming-images/avatars/leaf-yellow.png",
    marcimus: "https://www.kasandbox.org/programming-images/avatars/marcimus.png",
    marcimusOrange: "https://www.kasandbox.org/programming-images/avatars/marcimus-orange.png",
    marcimusPurple: "https://www.kasandbox.org/programming-images/avatars/marcimus-purple.png",
    marcimusRed: "https://www.kasandbox.org/programming-images/avatars/marcimus-red.png",
    mrPants: "https://www.kasandbox.org/programming-images/avatars/mr-pants.png",
    mrPantsGreen: "https://www.kasandbox.org/programming-images/avatars/mr-pants-green.png",
    mrPantsOrange: "https://www.kasandbox.org/programming-images/avatars/mr-pants-orange.png",
    mrPantsPink: "https://www.kasandbox.org/programming-images/avatars/mr-pants-pink.png",
    mrPantsPurple: "https://www.kasandbox.org/programming-images/avatars/mr-pants-purple.png",
    mrPantsWithHat: "https://www.kasandbox.org/programming-images/avatars/mr-pants-with-hats.png",
    oldSpiceMan: "https://www.kasandbox.org/programming-images/avatars/old-spice-man.png",
    oldSpiceManBlue: "https://www.kasandbox.org/programming-images/avatars/old-spice-man.png",
    orangeJuiceSquid: "https://www.kasandbox.org/programming-images/avatars/orange-juice-squid.png",
    purplePi: "https://www.kasandbox.org/programming-images/avatars/purple-pi.png",
    purplePiPink: "https://www.kasandbox.org/programming-images/avatars/purple-pi-pink.png",
    purplePiTeal: "https://www.kasandbox.org/programming-images/avatars/purple-pi-teal.png",
    questionMark: "https://www.kasandbox.org/programming-images/avatars/questionmark.png",
    robotFemale1: "https://www.kasandbox.org/programming-images/avatars/robot_female_1.png",
    robotFemale2: "https://www.kasandbox.org/programming-images/avatars/robot_female_2.png",
    robotFemale3: "https://www.kasandbox.org/programming-images/avatars/robot_female_3.png",
    robotMale1: "https://www.kasandbox.org/programming-images/avatars/robot_male_1.png",
    robotMale2: "https://www.kasandbox.org/programming-images/avatars/robot_male_2.png",
    robotMale3: "https://www.kasandbox.org/programming-images/avatars/robot_male_3.png",
    spunkySam: "https://www.kasandbox.org/programming-images/avatars/spunky-sam.png",
    spunkySamGreen: "https://www.kasandbox.org/programming-images/avatars/spunky-sam-green.png",
    spunkySamOrange: "https://www.kasandbox.org/programming-images/avatars/spunky-sam-orange.png",
    spunkySamRed: "https://www.kasandbox.org/programming-images/avatars/spunky-sam-red.png",
    hopperHappy: "https://www.kasandbox.org/programming-images/creatures/Hopper-Happy.png",
    hopperCool: "https://www.kasandbox.org/programming-images/creatures/Hopper-Cool.png",
    hopperJumping: "https://www.kasandbox.org/programming-images/creatures/Hopper-Jumping.png",
    ohNoes: "https://www.kasandbox.org/programming-images/creatures/OhNoes.png",
    babyWinston: "https://www.kasandbox.org/programming-images/creatures/BabyWinston.png",
    Winston: "https://www.kasandbox.org/programming-images/creatures/Winston.png",
  };
}
<commit_msg>Update images.js<commit_after>if(!Images) {
  var Images = {
    avatarTeam: "https://www.kasandbox.org/programming-images/avatars/avatar-team.png",
    aqualineSeed: "https://www.kasandbox.org/programming-images/avatars/aqualine-seed.png",
    aqualineSeedling: "https://www.kasandbox.org/programming-images/avatars/aqualine-seedling.png",
    aqualineSapling: "https://www.kasandbox.org/programming-images/avatars/aqualine-sapling.png",
    aqualineTree: "https://www.kasandbox.org/programming-images/avatars/aqualine-tree.png",
    aqualineUltimate: "https://www.kasandbox.org/programming-images/avatars/aqualine-ultimate.png",
    duskpinSeed: "https://www.kasandbox.org/programming-images/avatars/duskpin-seed.png",
    duskpinSeedling: "https://www.kasandbox.org/programming-images/avatars/duskpin-seedling.png",
    duskpinSapling: "https://www.kasandbox.org/programming-images/avatars/duskpin-sapling.png",
    duskpinTree: "https://www.kasandbox.org/programming-images/avatars/duskpin-tree.png",
    duskpinUltimate: "https://www.kasandbox.org/programming-images/avatars/duskpin-ultimate.png",
    leafersSeed: "https://www.kasandbox.org/programming-images/avatars/leafers-seed.png",
    leafersSeedling: "https://www.kasandbox.org/programming-images/avatars/leafers-seedling.png",
    leafersSapling: "https://www.kasandbox.org/programming-images/avatars/leafers-sapling.png",
    leafersTree: "https://www.kasandbox.org/programming-images/avatars/leafers-tree.png",
    leafersUltimate: "https://www.kasandbox.org/programming-images/avatars/leafers-ultimate.png",
    piceratopsSeed: "https://www.kasandbox.org/programming-images/avatars/piceratops-seed.png",
    piceratopsSeedling: "https://www.kasandbox.org/programming-images/avatars/piceratops-seedling.png",
    piceratopsSapling: "https://www.kasandbox.org/programming-images/avatars/piceratops-sapling.png",
    piceratopsTree: "https://www.kasandbox.org/programming-images/avatars/piceratops-tree.png",
    piceratopsUltimate: "https://www.kasandbox.org/programming-images/avatars/piceratops-ultimate.png",
    primosaurSeed: "https://www.kasandbox.org/programming-images/avatars/primosaur-seed.png",
    primosaurSeedling: "https://www.kasandbox.org/programming-images/avatars/primosaur-seedling.png",
    primosaurSapling: "https://www.kasandbox.org/programming-images/avatars/primosaur-sapling.png",
    primosaurTree: "https://www.kasandbox.org/programming-images/avatars/primosaur-tree.png",
    primosaurUltimate: "https://www.kasandbox.org/programming-images/avatars/primosaur-ultimate.png",
    starkySeed: "https://www.kasandbox.org/programming-images/avatars/starky-seed.png",
    starkySeedling: "https://www.kasandbox.org/programming-images/avatars/starky-seedling.png",
    starkySapling: "https://www.kasandbox.org/programming-images/avatars/starky-sapling.png",
    starkyTree: "https://www.kasandbox.org/programming-images/avatars/starky-tree.png",
    starkyUltimate: "https://www.kasandbox.org/programming-images/avatars/starky-ultimate.png",
    leafBlue: "https://www.kasandbox.org/programming-images/avatars/leaf-blue.png",
    leafGreen: "https://www.kasandbox.org/programming-images/avatars/leaf-green.png",
    leafGray: "https://www.kasandbox.org/programming-images/avatars/leaf-gray.png",
    leafOrange: "https://www.kasandbox.org/programming-images/avatars/leaf-orange.png",
    leafRed: "https://www.kasandbox.org/programming-images/avatars/leaf-red.png",
    leafYellow: "https://www.kasandbox.org/programming-images/avatars/leaf-yellow.png",
    marcimus: "https://www.kasandbox.org/programming-images/avatars/marcimus.png",
    marcimusOrange: "https://www.kasandbox.org/programming-images/avatars/marcimus-orange.png",
    marcimusPurple: "https://www.kasandbox.org/programming-images/avatars/marcimus-purple.png",
    marcimusRed: "https://www.kasandbox.org/programming-images/avatars/marcimus-red.png",
    mrPants: "https://www.kasandbox.org/programming-images/avatars/mr-pants.png",
    mrPantsGreen: "https://www.kasandbox.org/programming-images/avatars/mr-pants-green.png",
    mrPantsOrange: "https://www.kasandbox.org/programming-images/avatars/mr-pants-orange.png",
    mrPantsPink: "https://www.kasandbox.org/programming-images/avatars/mr-pants-pink.png",
    mrPantsPurple: "https://www.kasandbox.org/programming-images/avatars/mr-pants-purple.png",
    mrPantsWithHat: "https://www.kasandbox.org/programming-images/avatars/mr-pants-with-hats.png",
    oldSpiceMan: "https://www.kasandbox.org/programming-images/avatars/old-spice-man.png",
    oldSpiceManBlue: "https://www.kasandbox.org/programming-images/avatars/old-spice-man.png",
    orangeJuiceSquid: "https://www.kasandbox.org/programming-images/avatars/orange-juice-squid.png",
    purplePi: "https://www.kasandbox.org/programming-images/avatars/purple-pi.png",
    purplePiPink: "https://www.kasandbox.org/programming-images/avatars/purple-pi-pink.png",
    purplePiTeal: "https://www.kasandbox.org/programming-images/avatars/purple-pi-teal.png",
    questionMark: "https://www.kasandbox.org/programming-images/avatars/questionmark.png",
    robotFemale1: "https://www.kasandbox.org/programming-images/avatars/robot_female_1.png",
    robotFemale2: "https://www.kasandbox.org/programming-images/avatars/robot_female_2.png",
    robotFemale3: "https://www.kasandbox.org/programming-images/avatars/robot_female_3.png",
    robotMale1: "https://www.kasandbox.org/programming-images/avatars/robot_male_1.png",
    robotMale2: "https://www.kasandbox.org/programming-images/avatars/robot_male_2.png",
    robotMale3: "https://www.kasandbox.org/programming-images/avatars/robot_male_3.png",
    spunkySam: "https://www.kasandbox.org/programming-images/avatars/spunky-sam.png",
    spunkySamGreen: "https://www.kasandbox.org/programming-images/avatars/spunky-sam-green.png",
    spunkySamOrange: "https://www.kasandbox.org/programming-images/avatars/spunky-sam-orange.png",
    spunkySamRed: "https://www.kasandbox.org/programming-images/avatars/spunky-sam-red.png",
    hopperHappy: "https://www.kasandbox.org/programming-images/creatures/Hopper-Happy.png",
    hopperCool: "https://www.kasandbox.org/programming-images/creatures/Hopper-Cool.png",
    hopperJumping: "https://www.kasandbox.org/programming-images/creatures/Hopper-Jumping.png",
    ohNoes: "https://www.kasandbox.org/programming-images/creatures/OhNoes.png",
    babyWinston: "https://www.kasandbox.org/programming-images/creatures/BabyWinston.png",
    winston: "https://www.kasandbox.org/programming-images/creatures/Winston.png",
    blank: "https://www.kasandbox.org/programming-images/cute/Blank.png",
    brownBlock: "https://www.kasandbox.org/programming-images/cute/BrownBlock.png",
    characterBoy: "https://www.kasandbox.org/programming-images/cute/CharacterBoy.png",
    characterCatGirl: "https://www.kasandbox.org/programming-images/cute/CharacterCatGirl.png",
    characterHornGirl: "https://www.kasandbox.org/programming-images/cute/CharacterHornGirl.png",
    characterPinkGirl: "https://www.kasandbox.org/programming-images/cute/CharacterPinkGirl.png",
    characterPrincessGirl: "https://www.kasandbox.org/programming-images/cute/CharacterPrincessGirl.png",
    chestClosed: "https://www.kasandbox.org/programming-images/cute/ChestClosed.png",
    chestLid: "https://www.kasandbox.org/programming-images/cute/ChestLid.png",
    chestOpen: "https://www.kasandbox.org/programming-images/cute/ChestOpen.png",
    dirtBlock: "https://www.kasandbox.org/programming-images/cute/ChestClosed.png",
    doorTallClosed: "https://www.kasandbox.org/programming-images/cute/DoorTallClosed.png",
    doorTallOpen: "https://www.kasandbox.org/programming-images/cute/DoorTallOpen.png",
    enemyBug: "https://www.kasandbox.org/programming-images/cute/EnemyBug.png",
    gemBlue: "https://www.kasandbox.org/programming-images/cute/GemBlue.png",
    gemGreen: "https://www.kasandbox.org/programming-images/cute/GemGreen.png",
    gemOrange: "https://www.kasandbox.org/programming-images/cute/GemOrange.png",
    grassBlock: "https://www.kasandbox.org/programming-images/cute/GrassBlock.png",
    heart: "https://www.kasandbox.org/programming-images/cute/Heart.png",
    key: "https://www.kasandbox.org/programming-images/cute/Key.png",
    plainBlock: "https://www.kasandbox.org/programming-images/cute/PlainBlock.png",
    rampEast: "https://www.kasandbox.org/programming-images/cute/RampEast.png",
    rampNorth: "https://www.kasandbox.org/programming-images/cute/RampNorth.png",
    rampSouth: "https://www.kasandbox.org/programming-images/cute/RampEast.png",
    rampWest: "https://www.kasandbox.org/programming-images/cute/RampWest.png",
    rock: "https://www.kasandbox.org/programming-images/cute/Rock.png",
    roofEast: "https://www.kasandbox.org/programming-images/cute/RampEast.png",
    roofNorth: "https://www.kasandbox.org/programming-images/cute/RampEast.png",
    rampSouth: "https://www.kasandbox.org/programming-images/cute/RampEast.png",
    rampWest: "https://www.kasandbox.org/programming-images/cute/RampEast.png",
    roofNorthEast: "https://www.kasandbox.org/programming-images/cute/RoofNorthEast.png",
    roofNorthWest: "https://www.kasandbox.org/programming-images/cute/RoofNorthWest.png",
    roofSouthEast: "https://www.kasandbox.org/programming-images/cute/RoofSouthEast.png",
    roofSouthWest: "https://www.kasandbox.org/programming-images/cute/RoofSouthWest.png",
    selector: "https://www.kasandbox.org/programming-images/cute/Selector.png",
    shadowEast: "https://www.kasandbox.org/programming-images/cute/ShadowEast.png",
    shadowWest: "https://www.kasandbox.org/programming-images/cute/ShadowWest.png",
    shadowNorth: "https://www.kasandbox.org/programming-images/cute/ShadowNorth.png",
    shadowSouth: "https://www.kasandbox.org/programming-images/cute/ShadowSouth.png",
    shadowNorthEast: "https://www.kasandbox.org/programming-images/cute/ShadowNorthEast.png",
    shadowNorthWest: "https://www.kasandbox.org/programming-images/cute/ShadowNorthWest.png",
    shadowSouthEast: "https://www.kasandbox.org/programming-images/cute/ShadowSouthEast.png",
    shadowSouthWest: "https://www.kasandbox.org/programming-images/cute/ShadowSouthWest.png",
    shadowSideWest: "https://www.kasandbox.org/programming-images/cute/ShadowSideWest.png",
    star: "https://www.kasandbox.org/programming-images/cute/Star.png",
    stoneBlock: "https://www.kasandbox.org/programming-images/cute/StoneBlock.png",
    stoneBlockTall: "https://www.kasandbox.org/programming-images/cute/StoneBlockTall.png",
    treeShort: "https://www.kasandbox.org/programming-images/cute/TreeShort.png",
    treeTall: "https://www.kasandbox.org/programming-images/cute/TreeTall.png",
    treeUgly: "https://www.kasandbox.org/programming-images/cute/TreeUgly.png",
    wallBlock: "https://www.kasandbox.org/programming-images/cute/WallBlock.png",
    wallBlockTall: "https://www.kasandbox.org/programming-images/cute/WallBlockTall.png",
    waterBlock: "https://www.kasandbox.org/programming-images/cute/WaterBlock.png",
    windowTall: "https://www.kasandbox.org/programming-images/cute/WindowTall.png",
    woodBlock: "https://www.kasandbox.org/programming-images/cute/WoodBlock.png",
    background: "https://www.kasandbox.org/programming-images/space/background.png",
    beetleship: "https://www.kasandbox.org/programming-images/space/beetleship.png",
    collisioncircle: "https://www.kasandbox.org/programming-images/space/collisioncircle.png",
    girl1: "https://www.kasandbox.org/programming-images/space/girl1.png",
    girl2: "https://www.kasandbox.org/programming-images/space/girl2.png",
    girl3: "https://www.kasandbox.org/programming-images/space/girl3.png",
    girl4: "https://www.kasandbox.org/programming-images/space/girl4.png",
    girl5: "https://www.kasandbox.org/programming-images/space/girl5.png",
    healthHeart: "https://www.kasandbox.org/programming-images/space/healthheart.png",
    minus: "https://www.kasandbox.org/programming-images/space/minus.png",
    octopus: "https://www.kasandbox.org/programming-images/space/octopus.png",
    planet: "https://www.kasandbox.org/programming-images/space/planet.png",
    plus: "https://www.kasandbox.org/programming-images/space/plus.png",
    rocketShip: "https://www.kasandbox.org/programming-images/space/rocketship.png",
    star2: "https://www.kasandbox.org/programming-images/space/star.png",
    zero: "https://www.kasandbox.org/programming-images/space/0.png",
    one: "https://www.kasandbox.org/programming-images/space/1.png",
    two: "https://www.kasandbox.org/programming-images/space/2.png",
    three: "https://www.kasandbox.org/programming-images/space/3.png",
    four: "https://www.kasandbox.org/programming-images/space/4.png",
    five: "https://www.kasandbox.org/programming-images/space/5.png",
    six: "https://www.kasandbox.org/programming-images/space/6.png",
    seven: "https://www.kasandbox.org/programming-images/space/7.png",
    eight: "https://www.kasandbox.org/programming-images/space/8.png",
    nine: "https://www.kasandbox.org/programming-images/space/9.png",
  };
}
<|endoftext|>


<commit_before>// insert service worker scripts here
this.addEventListener("install", function (event) {
      event.waitUntil(
        caches.open('v1').then(function (cache) {
          cache.addAll(['/html/',
            '/html/index.html',
          	'/html/img/trapped_lady.jpg',
          	'/html/img/screaming.jpg',
          	'/html/img/location4.jpg',
          	'/html/img/embrace3.jpg',
          	'/html/img/bg.jpg',
          	'/html/img/timer.png'
          	]);
        })
        );
    })

this.addEventListener("fetch", function (event) {
	event.respondWith(caches.match(event.request))
})    <commit_msg>debugging<commit_after>// insert service worker scripts here
this.addEventListener("install", function (event) {
      event.waitUntil(
        caches.open('v1').then(function (cache) {
          cache.addAll(['/html/',
            '/html/index.html',
          	'/html/img/trapped_lady.jpg',
          	'/html/img/screaming.jpg',
          	'/html/img/location4.jpg',
          	'/html/img/embrace3.jpg',
          	'/html/img/bg.jpg',
          	'/html/img/timer.png'
          	]);
        })
        );
    })

this.addEventListener("fetch", function (event) {
	event.respondWith(
    caches.match(event.request);
    );
});    <|endoftext|>


<commit_before>this.addEventListener("install", function (event) {
    event.waitUntil(
        caches.open('v14').then(function (cache) {
         return cache.addAll(['/html/',
          '/html/index.html',
          '/html/manifest.json',
          '/html/emergency.html',
          '/html/js/911.js',
          '/html/js/all_scr.js',
          '/html/js/app.js',
          '/html/js/bootstrap.min.js',
          '/html/js/emergency.js',
          '/html/js/wow.min.js',
          '/html/rs-plugin/js/jquery.themepunch.tools.min.js',
          '/html/rs-plugin/js/jquery.themepunch.revolution.min.js',
          '/html/rs-plugin/assets/timer.png',
          '/html/js/jquery.min.js',
          '/html/js/jquery.parallax-0.2-min.js',
          '/html/css/adaptive.css',
          '/html/css/animate.css',
          '/html/css/bootstrap.css',
          '/html/css/main.css',
          '/html/css/pushy.css',
          '/html/css/font-awesome.css',
          '/html/rs-plugin/css/settings.css',
          '/html/img/trapped_lady.jpg',
          '/html/img/screaming.jpg',
          '/html/img/location4.jpg',
          '/html/img/embrace3.jpg',
          '/html/img/start/bg.jpg',
          '/html/font/fontawesome-webfont.woff?v=4.3.0',
          '/html/font/fontawesome-webfont.woff2?v=4.3.0',
          '/html/rs-plugin/font/revicons.woff?5510888',
          '/html/rs-plugin/font/revicons.ttf?5510888',
          '/html/font/fontawesome-webfont.ttf?v=4.3.0',
          '/html/img/wmb_128x128.png',
          '/html/img/wmb_144x144.png',
          '/html/img/wmb_152x152.png',
          '/html/img/wmb_192x192.png',
          '/html/img/wmb_256x256.png'
          ]);
        })
        );
    });

this.addEventListener('activate', function(event) {
  var cacheWhitelist = ['v14'];

  event.waitUntil(
    caches.keys().then(function(keyList) {
      return Promise.all(keyList.map(function(key) {
        if (cacheWhitelist.indexOf(key) === -1) {
          return caches.delete(key);
        }
      }));
    })
  );
});
this.addEventListener('fetch', function (event) {
	event.respondWith(
    caches.match(event.request)
    );
});

this.addEventListener("push", event => {
   event.waitUntil(() => {
     if (event.data) {
      return Promise.resolve(event.data);
     }
     return fetch("demo_sse.php").then(response => response.json());
).then(data => {
 return this.registration.showNotification(title, {
    body : 'help me',
    icon : 'screaming.jpg',
    vibrate: [200, 100, 200, 100, 400],
    tag : 'request',
    actions : [
    { action : "track", title : "wacth", icon : "fa fa-thumb-up"},
    { action : "Ignore", title : "Ignore", icon : "fa fa-thumb-down"} ]
  });
});

this.addEventListener("notificationclick", event => {
event.waitUntil(() =>
   event.notification.close();
  )

});<commit_msg>error<commit_after>this.addEventListener("install", function (event) {
    event.waitUntil(
        caches.open('v14').then(function (cache) {
         return cache.addAll(['/html/',
          '/html/index.html',
          '/html/manifest.json',
          '/html/emergency.html',
          '/html/js/911.js',
          '/html/js/all_scr.js',
          '/html/js/app.js',
          '/html/js/bootstrap.min.js',
          '/html/js/emergency.js',
          '/html/js/wow.min.js',
          '/html/rs-plugin/js/jquery.themepunch.tools.min.js',
          '/html/rs-plugin/js/jquery.themepunch.revolution.min.js',
          '/html/rs-plugin/assets/timer.png',
          '/html/js/jquery.min.js',
          '/html/js/jquery.parallax-0.2-min.js',
          '/html/css/adaptive.css',
          '/html/css/animate.css',
          '/html/css/bootstrap.css',
          '/html/css/main.css',
          '/html/css/pushy.css',
          '/html/css/font-awesome.css',
          '/html/rs-plugin/css/settings.css',
          '/html/img/trapped_lady.jpg',
          '/html/img/screaming.jpg',
          '/html/img/location4.jpg',
          '/html/img/embrace3.jpg',
          '/html/img/start/bg.jpg',
          '/html/font/fontawesome-webfont.woff?v=4.3.0',
          '/html/font/fontawesome-webfont.woff2?v=4.3.0',
          '/html/rs-plugin/font/revicons.woff?5510888',
          '/html/rs-plugin/font/revicons.ttf?5510888',
          '/html/font/fontawesome-webfont.ttf?v=4.3.0',
          '/html/img/wmb_128x128.png',
          '/html/img/wmb_144x144.png',
          '/html/img/wmb_152x152.png',
          '/html/img/wmb_192x192.png',
          '/html/img/wmb_256x256.png'
          ]);
        })
        );
    });

this.addEventListener('activate', function(event) {
  var cacheWhitelist = ['v14'];

  event.waitUntil(
    caches.keys().then(function(keyList) {
      return Promise.all(keyList.map(function(key) {
        if (cacheWhitelist.indexOf(key) === -1) {
          return caches.delete(key);
        }
      }));
    })
  );
});
this.addEventListener('fetch', function (event) {
	event.respondWith(
    caches.match(event.request);

    this.addEventListener("push", event => {
   event.waitUntil(() => {
     if (event.data) {
      return Promise.resolve(event.data);
     }
     return fetch("demo_sse.php").then(response => response.json());
).then(data => {
 return this.registration.showNotification(title, {
    body : 'help me',
    icon : 'screaming.jpg',
    vibrate: [200, 100, 200, 100, 400],
    tag : 'request',
    actions : [
    { action : "track", title : "wacth", icon : "fa fa-thumb-up"},
    { action : "Ignore", title : "Ignore", icon : "fa fa-thumb-down"} ]
  });
});

this.addEventListener("notificationclick", event => {
event.waitUntil(() =>
   event.notification.close();
  )

});
    );
});

<|endoftext|>


<commit_before>"use strict";

// https://github.com/lhorie/mithril.js/blob/rewrite/docs/v1.x-migration.md#component-controller-function
// Convert `controller` object properties (that are functions) to be called `oninit` instead
module.exports = function(file, api) {
    var j = api.jscodeshift,
        s = api.stats;

    return j(file.source)
        .find(j.Property)
        .filter((p) => (
            p.get("key").getValueProperty("name") === "config" &&
            p.get("value").get("object").getValueProperty("name") === "m" &&
            p.get("value").get("property").getValueProperty("name") === "route"
        ))
        .forEach(() => s("config: m.route"))
        .replaceWith(() => j.property(
            "init",
            j.identifier("oncreate"),
            j.memberExpression(
                j.memberExpression(
                    j.identifier("m"),
                    j.identifier("route")
                ),
                j.identifier("link")
            )
        ))
        .toSource();
};
<commit_msg>Robustify<commit_after>"use strict";

// https://github.com/lhorie/mithril.js/blob/rewrite/docs/v1.x-migration.md#component-controller-function
// Convert `controller` object properties (that are functions) to be called `oninit` instead
module.exports = function(file, api) {
    var j = api.jscodeshift,
        s = api.stats;

    return j(file.source)
        .find(j.Property)
        .filter((p) => (
            p.get("key").value &&
            p.get("key").getValueProperty("name") === "config" &&
            p.get("value", "object").value &&
            p.get("value", "object").getValueProperty("name") === "m" &&
            p.get("value", "property").value &&
            p.get("value", "property").getValueProperty("name") === "route"
        ))
        .forEach(() => s("config: m.route"))
        .replaceWith(() => j.property(
            "init",
            j.identifier("oncreate"),
            j.memberExpression(
                j.memberExpression(
                    j.identifier("m"),
                    j.identifier("route")
                ),
                j.identifier("link")
            )
        ))
        .toSource();
};
<|endoftext|>


<commit_before>///////////////////////////////////////////////////////////////// Library Setup:

var TelegramBot = require('node-telegram-bot-api');
var fs = require('fs');
var exec = require('child_process').exec;
var cron = require('node-cron');

//////////////////////////////////////////////// Load "Ricecab Bot" Information:

var token = '216808904:AAFqAjnnVVpHmKU4ZsExIMNuUdZX8R49YSQ';
var bot = new TelegramBot(token, {polling: true});
var ricecab_id = -116496721;
var bank_acc = '12-3086-0261060-00';
var path = '/home/pi/ricecab_bot/';

/////////////////////////////////////////////////////// Load "User Information":

var users = [
    {id : 133607928, cost: 2.52}, // Evan Lin
    {id : 177677828, cost: 0.48}, // Honour Carmichael
    {id : 177893563, cost: 1.52}, // Carl Velasco
    {id : 187936081, cost: 2.52}, // Amy Lai
    {id : 199377811, cost: 1.21}, // Vincent Wolfgramm-Russel
    {id : 197336637, cost: 2.52}  // Jay Shen
];

function uget_index(id) {
    for (var i = 0; i < users.length; i++) {
        if (users[i].id === id) {return i;}
    }
    return 0;
}

//////////////////////////////////////////////// "Ricecab Bot" Logic Definition:
//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> "/checkin"

bot.onText(/\/checkin/, function(msg, match) {
    var chatId = msg.chat.id;
    var userName = msg.from.first_name + ' ' + msg.from.last_name;
    var userId = msg.from.id;
    var timeStamp = msg.date;

    // FIND MONTHLY SUM >>
    var tripcost = users[uget_index(userId)].cost;
    var cost_sum = get_total_cost(path, userId) + tripcost; // costsum after checkin.
    var n_rides = Number(get_n_rides(path, userId)) + 1; // Number of rides after checkin.
    bot.sendMessage(userId, n_rides);

    // DATA STRING >>
    var data = '['
    + 'CHECKIN:"' + timeStamp + '"'
    + ', NAME:"' + userName + '"'
    + ', ID:"' + userId + '"'
    + ', COST:"' + tripcost + '"'
    + ', MONTHLY_SUM:"' + cost_sum + '"'
    + ']\n';

    // FILE IO >>
    // Make Stats File.
    var l1 = "NAME: " + userName + ", ";
    var l2 = "RIDES: " + n_rides + ", ";
    var l3 = "SUM: $" + cost_sum + "\n";

    fs.writeFile(path + 'stats/' + userId + '.txt', l1 + l2 + l3, function(err) {
        if(err) {
            bot.sendMessage(chatId, "ERROR: '/checkin' stats cannot be compiled.");
            console.log(chatId + " ERROR: '/checkin' stats cannot be compiled.");
        }
    });

    // Append to Log File.
    fs.appendFile(path + 'logs/' + userId + '.txt', data, function(err) {
        if(err) {
            bot.sendMessage(chatId, "ERROR: '/checkin' request error.");
            console.log(chatId + " ERROR: '/checkin' request error.");
        }

        // PREPARE PERSONAL MESSAGE >>
        var checkin_msg = "CHECKIN SUCCESSFUL at '" + timeStamp + "'.\n"
            + "Name: " + userName + ", Cost: $" + tripcost + "\n"
            + "Run /stats for more details.";
        bot.sendMessage(chatId, checkin_msg);

        // PREPARE GLOBAL MESSAGE >>
        bot.sendMessage(ricecab_id, userName + " has checked in.");
    });
    console.log(data); // CONSOLE LOG.

});

//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> "/info"
bot.onText(/\/info/, function(msg, match) {
    var chatId = msg.chat.id;

    fs.readFile(path + 'INFO', function(err, data) {
        if (err) {
            bot.sendMessage(chatId, "ERROR: '/info' request has issues.");
            console.log(chatId + " ERROR: '/info' request has issues.");
        }
        bot.sendMessage(chatId, data.toString());
        console.log("[INFO request on " + chatId + "]");
    });
});

//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> "/stats"
bot.onText(/\/stats/, function(msg, match) {

    var chatId = msg.chat.id;
    var userName = msg.from.first_name + ' ' + msg.from.last_name;
    var userId = msg.from.id;

    // Attempt to refresh stats.
    for (var i = 0; i < users.length; i++) {

    }

    // Output Stats >>

    var l0 = "** STATS **\n";

    exec('cat ' + path + 'stats/*', function(err, file_data) {
        if (err) {
            bot.sendMessage(chatId, l0 + "Nothing to show.");
        } else {
            bot.sendMessage(chatId, l0 + file_data.toString());
        }
        console.log("[STATS request on " + chatId + "]");
    });
});

///////////////////////////////////////////////////////// ADMINISTRATOR COMMANDS

//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> "/\"
bot.onText(/\/go/, function(msg, match) {
    var userName = msg.from.first_name + ' ' + msg.from.last_name;
    if (msg.from.id === 133607928) {
        bot.sendMessage(ricecab_id, "Evan is on his way to the car now!");
        console.log("[GO request by " + userName + ": APPROVED]");
    } else {
        console.log("[GO request by " + userName + ": REJECTED]");
    }
});

//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> "/reset"
bot.onText(/\/reset/, function(msg, match) {
    var userName = msg.from.first_name + ' ' + msg.from.last_name;
    if (msg.from.id === 133607928) {
        reset_all();
        console.log("[RESET request by " + userName + ": APPROVED]");
    } else {
        console.log("[RESET request by " + userName + ": REJECTED]");
    }
});

//////////////////////////////////////////////////////////////////////////// FUN

//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> "/photo"
bot.onText(/\/what_is_evan_doing/, function(msg, match) {
    var chatId = msg.chat.id;
    var userName = msg.from.first_name + ' ' + msg.from.last_name;
    var userId = msg.from.id;
    var timeStamp = new Date();

    if (msg.chat.id !== ricecab_id) {
        access_denied( '/photo', userName, userId, chatId, timeStamp);
    } else {
        access_granted( '/photo', userName, userId, chatId, timeStamp);
        bot.sendMessage(ricecab_id, "Let me find out...");

        var photo_file_dir = (path + 'cam.jpg');
        exec('raspistill -vf -hf -o ' + photo_file_dir, function(err, io_data) {
            if (err) {
                bot.sendMessage(ricecab_id, "ERROR: '/what_is_evan_doing' Unable to generate photo.");
            } else {
                send_photo(ricecab_id, photo_file_dir, timeStamp.toString());
            }
        });
    }
});

///////////////////////////////////////////////////////////////////// AUTOMATION

cron.schedule('* 0 0 1 1-12 *', function() {
    console.log("[RESET request by AUTOMATION: APPROVED]");
    reset_all();
    setTimeout(console.log("[RESET request completed.]"), 1000*60*5); // 5min timeout.
});

function reset_all() {
    var timeStamp = new Date();
    var line = "\n💰*💰*💰*💰*💰*💰*💰*💰*💰\n\n";

    var l0 = "💰💰 PAYDAY INFORMATION 💰💰\n\n"
    + "Hey all! I have just been informed by my master, @evanlinjin, "
    + "that it is time for you all to pay your share of money.\n\n"
    + "Please transfer the required amount of money (shown below) "
    + "to his bank account: " + bank_acc + ".\n";

    exec('cat ' + path + 'stats/*', function(err, file_data) {
        if (err) {
            bot.sendMessage(ricecab_id, l0 + line + "Nothing to show.\n" + line + timeStamp);
        } else {
            bot.sendMessage(ricecab_id, l0 + line + file_data.toString() + line + timeStamp);

            // RESET ALL >>
            exec('rm ' + path + 'stats/* ' + path + 'logs/*', function(err, rm_output) {
                if (err) {
                    bot.sendMessage(ricecab_id, "ERROR: '/reset' request error.");
                    console.log(ricecab_id + " ERROR: '/reset' request error.");
                }
            });
        }
    });
}

/////////////////////////////////////////////////////////////// CAMERA FUNCTIONS

function send_photo(chat_id, photo_file_dir, caption_desc) {
    bot.sendPhoto(chat_id, photo_file_dir, {caption: caption_desc});
}

///////////////////////////////////////////////////// Speech Recognition Arrays.

var SRA_ride = ['give~aride', 'getaride', 'driveme', 'pick~up', 'need~ride'];

var SRA_morning = ['morning', 'touni'];
var SRA_evening = ['evening', 'afternoon', 'wayback', 'fromuni', 'backhome', 'ridehome'];

///////////////////////////////////////////////////////////////////////// Logic.

bot.on('message', function (msg) {
    var chatId = msg.chat.id;
    var user1stName = msg.from.first_name;
    var str = msg.text; str = str.replace(/\s+/g, '').toLowerCase();

    switch (str) {
        case 'whereisevan?':
            bot.sendMessage(chatId, "Good question.");
            break;

        default:
        if (str.search('thanks') !== -1) {
            bot.sendMessage(chatId, "You're Welcome 😘");
        }
        if (if_include(str, SRA_ride) && if_include(str, 'tomorrow')) {

            var rdmsg = [
                "It is understood that ",
                " needs a ride tomorrow ",
                ". Evan will be informed! 🗣👌📢👍📡😊"
            ];

            if (if_include(str, SRA_morning)) {
                bot.sendMessage(chatId, rdmsg[0] + user1stName + rdmsg[1] + SRA_morning[0] + rdmsg[2]);
                inform_admin(user1stName + ' needs a ride tomorrow morning.');
            }
            if (if_include(str, SRA_evening)) {
                bot.sendMessage(chatId, rdmsg[0] + user1stName + rdmsg[1] + SRA_evening[0] + rdmsg[2]);
                inform_admin(user1stName + ' needs a ride tomorrow evening.');
            }
        }
    }
});

////////////////////////////////////////////////// Speech Recognition Functions.

// Should really only check a scentence at a time for accuracy.
function if_include(in_msg, phrases) {

    for (var i = 0; i < phrases.length; i++) {
        if (in_msg.search(phrases[i]) !== -1) {return true;}
        console.log('comparing: ' + in_msg + ' with: ' + phrases[i] + '.');

        // CHECK >> '~' :
        if (phrases[i].search('~') !== -1) {
            var temp_phrases = phrases[i].split('~');
            var n_incld = 0;

            for (var j = 0; j < temp_phrases.length; j++) {
                if (in_msg.search(temp_phrases[j]) !== -1) {n_incld = n_incld + 1;}
            }
            if (n_incld === temp_phrases.length) {return true;}
        }
    }
    return false;
}

//////////////////////////////////////////////// '/checkin' & '/stats' functions

// Get number of rides from specified user.
function get_n_rides(path, user_id) {
    fs.readFile(path + 'logs/' + user_id + '.txt', function(err, data) {
        if (err) {
            var err_msg = "ERROR: Unable to get number of 'checkin's from " + user_id + ". Assuming 0.";
            bot.sendMessage(-116496721, err_msg); console.log(-116496721 + err_msg);
            return 0;
        }

        var file_str = data.toString();
        var n_checkin = 0;

        for (var i = 0; i < file_str.length; i++) {
            if (file_str[i] === '[') { n_checkin += 1; }
        }
        bot.sendMessage(user_id, "within get_n_rides: " + n_checkin);
        return n_checkin;
    });
}

// Get total cost from specified user.
function get_total_cost(path, user_id) {
    fs.readFile(path + 'logs/' + user_id + '.txt', function(err, data) {
        if (err) {
            var err_msg = "ERROR: Unable to get number of 'checkin's from " + user_id + ". Assuming 0.";
            bot.sendMessage(-116496721, err_msg); console.log(-116496721 + err_msg);
        }

        // Convert data to lowercase, spaceless string.
        var file_str = data.toString();
        file_str = file_str.replace(/\s+/g, '').toLowerCase();

        var cmp_str = 'COST';
        var total_cost = 0.00;

        for (var i = 0; i < file_str.length; i++) {

            // Find 'COST' in string.
            if (
                file_str[i] === cmp_str[0] &&
                file_str.slice(i, i + cmp_str.length) === cmp_str
            ) {
                // Move to after 'COST' term.
                i += cmp_str.length;

                // Find positions of two preceeding '"'s.
                var pos_PA = [];
                while (true) {
                    if (file_str[i] === '"') { pos_PA.push(i); }
                    if (pos_PA.length === 2) { break; }
                    i += 1;
                }

                // Extract 'COST' value and add to 'total_cost'.
                total_cost += parseFloat(file_str.slice(pos_PA[0] + 1, pos_PA[1]));
            }
        }
        return total_cost;
    });
    return 0.00;
}

////////////////////////////////////////////////////////// CONSOLE LOG FUNCTIONS

function access_denied(cmd, userName, userId, chatId, timeStamp) {
    var msg = "ON " + timeStamp + " >>\n" +
    "[ACCESS DENIED] CMD: '" + cmd + "'" +
    ", Name: "    + userName +
    ", User ID: " + userId +
    ", Chat ID: " + chatId + "\n";
    console.log(msg);
}

function access_granted(cmd, userName, userId, chatId, timeStamp) {
    var msg = "ON " + timeStamp + " >>\n" +
    "[ACCESS GRANTED] CMD: '" + cmd + "'" +
    ", Name: "    + userName +
    ", User ID: " + userId +
    ", Chat ID: " + chatId + "\n";
    console.log(msg);
}

function inform_admin(admin_msg) {bot.sendMessage(133607928, admin_msg);}
<commit_msg>Begin removing dependance on wc.<commit_after>///////////////////////////////////////////////////////////////// Library Setup:

var TelegramBot = require('node-telegram-bot-api');
var fs = require('fs');
var exec = require('child_process').exec;
var cron = require('node-cron');

//////////////////////////////////////////////// Load "Ricecab Bot" Information:

var token = '216808904:AAFqAjnnVVpHmKU4ZsExIMNuUdZX8R49YSQ';
var bot = new TelegramBot(token, {polling: true});
var ricecab_id = -116496721;
var bank_acc = '12-3086-0261060-00';
var path = '/home/pi/ricecab_bot/';

/////////////////////////////////////////////////////// Load "User Information":

var users = [
    {id : 133607928, cost: 2.52}, // Evan Lin
    {id : 177677828, cost: 0.48}, // Honour Carmichael
    {id : 177893563, cost: 1.52}, // Carl Velasco
    {id : 187936081, cost: 2.52}, // Amy Lai
    {id : 199377811, cost: 1.21}, // Vincent Wolfgramm-Russel
    {id : 197336637, cost: 2.52}  // Jay Shen
];

function uget_index(id) {
    for (var i = 0; i < users.length; i++) {
        if (users[i].id === id) {return i;}
    }
    return 0;
}

//////////////////////////////////////////////// "Ricecab Bot" Logic Definition:
//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> "/checkin"

bot.onText(/\/checkin/, function(msg, match) {
    var chatId = msg.chat.id;
    var userName = msg.from.first_name + ' ' + msg.from.last_name;
    var userId = msg.from.id;
    var timeStamp = msg.date;

    // FIND MONTHLY SUM >>
    var tripcost = users[uget_index(userId)].cost;
    var cost_sum = get_total_cost(path, userId) + tripcost; // costsum after checkin.
    var n_rides = get_n_rides(path, userId) + 1; // Number of rides after checkin.
    bot.sendMessage(userId, n_rides);

    // DATA STRING >>
    var data = '['
    + 'CHECKIN:"' + timeStamp + '"'
    + ', NAME:"' + userName + '"'
    + ', ID:"' + userId + '"'
    + ', COST:"' + tripcost + '"'
    + ', MONTHLY_SUM:"' + cost_sum + '"'
    + ']\n';

    // FILE IO >>
    // Make Stats File.
    var l1 = "NAME: " + userName + ", ";
    var l2 = "RIDES: " + n_rides + ", ";
    var l3 = "SUM: $" + cost_sum + "\n";

    fs.writeFile(path + 'stats/' + userId + '.txt', l1 + l2 + l3, function(err) {
        if(err) {
            bot.sendMessage(chatId, "ERROR: '/checkin' stats cannot be compiled.");
            console.log(chatId + " ERROR: '/checkin' stats cannot be compiled.");
        }
    });

    // Append to Log File.
    fs.appendFile(path + 'logs/' + userId + '.txt', data, function(err) {
        if(err) {
            bot.sendMessage(chatId, "ERROR: '/checkin' request error.");
            console.log(chatId + " ERROR: '/checkin' request error.");
        }

        // PREPARE PERSONAL MESSAGE >>
        var checkin_msg = "CHECKIN SUCCESSFUL at '" + timeStamp + "'.\n"
            + "Name: " + userName + ", Cost: $" + tripcost + "\n"
            + "Run /stats for more details.";
        bot.sendMessage(chatId, checkin_msg);

        // PREPARE GLOBAL MESSAGE >>
        bot.sendMessage(ricecab_id, userName + " has checked in.");
    });
    console.log(data); // CONSOLE LOG.

});

//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> "/info"
bot.onText(/\/info/, function(msg, match) {
    var chatId = msg.chat.id;

    fs.readFile(path + 'INFO', function(err, data) {
        if (err) {
            bot.sendMessage(chatId, "ERROR: '/info' request has issues.");
            console.log(chatId + " ERROR: '/info' request has issues.");
        }
        bot.sendMessage(chatId, data.toString());
        console.log("[INFO request on " + chatId + "]");
    });
});

//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> "/stats"
bot.onText(/\/stats/, function(msg, match) {

    var chatId = msg.chat.id;
    var userName = msg.from.first_name + ' ' + msg.from.last_name;
    var userId = msg.from.id;

    // Attempt to refresh stats.
    for (var i = 0; i < users.length; i++) {

    }

    // Output Stats >>

    var l0 = "** STATS **\n";

    exec('cat ' + path + 'stats/*', function(err, file_data) {
        if (err) {
            bot.sendMessage(chatId, l0 + "Nothing to show.");
        } else {
            bot.sendMessage(chatId, l0 + file_data.toString());
        }
        console.log("[STATS request on " + chatId + "]");
    });
});

///////////////////////////////////////////////////////// ADMINISTRATOR COMMANDS

//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> "/\"
bot.onText(/\/go/, function(msg, match) {
    var userName = msg.from.first_name + ' ' + msg.from.last_name;
    if (msg.from.id === 133607928) {
        bot.sendMessage(ricecab_id, "Evan is on his way to the car now!");
        console.log("[GO request by " + userName + ": APPROVED]");
    } else {
        console.log("[GO request by " + userName + ": REJECTED]");
    }
});

//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> "/reset"
bot.onText(/\/reset/, function(msg, match) {
    var userName = msg.from.first_name + ' ' + msg.from.last_name;
    if (msg.from.id === 133607928) {
        reset_all();
        console.log("[RESET request by " + userName + ": APPROVED]");
    } else {
        console.log("[RESET request by " + userName + ": REJECTED]");
    }
});

//////////////////////////////////////////////////////////////////////////// FUN

//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> "/photo"
bot.onText(/\/what_is_evan_doing/, function(msg, match) {
    var chatId = msg.chat.id;
    var userName = msg.from.first_name + ' ' + msg.from.last_name;
    var userId = msg.from.id;
    var timeStamp = new Date();

    if (msg.chat.id !== ricecab_id) {
        access_denied( '/photo', userName, userId, chatId, timeStamp);
    } else {
        access_granted( '/photo', userName, userId, chatId, timeStamp);
        bot.sendMessage(ricecab_id, "Let me find out...");

        var photo_file_dir = (path + 'cam.jpg');
        exec('raspistill -vf -hf -o ' + photo_file_dir, function(err, io_data) {
            if (err) {
                bot.sendMessage(ricecab_id, "ERROR: '/what_is_evan_doing' Unable to generate photo.");
            } else {
                send_photo(ricecab_id, photo_file_dir, timeStamp.toString());
            }
        });
    }
});

///////////////////////////////////////////////////////////////////// AUTOMATION

cron.schedule('* 0 0 1 1-12 *', function() {
    console.log("[RESET request by AUTOMATION: APPROVED]");
    reset_all();
    setTimeout(console.log("[RESET request completed.]"), 1000*60*5); // 5min timeout.
});

function reset_all() {
    var timeStamp = new Date();
    var line = "\n💰*💰*💰*💰*💰*💰*💰*💰*💰\n\n";

    var l0 = "💰💰 PAYDAY INFORMATION 💰💰\n\n"
    + "Hey all! I have just been informed by my master, @evanlinjin, "
    + "that it is time for you all to pay your share of money.\n\n"
    + "Please transfer the required amount of money (shown below) "
    + "to his bank account: " + bank_acc + ".\n";

    exec('cat ' + path + 'stats/*', function(err, file_data) {
        if (err) {
            bot.sendMessage(ricecab_id, l0 + line + "Nothing to show.\n" + line + timeStamp);
        } else {
            bot.sendMessage(ricecab_id, l0 + line + file_data.toString() + line + timeStamp);

            // RESET ALL >>
            exec('rm ' + path + 'stats/* ' + path + 'logs/*', function(err, rm_output) {
                if (err) {
                    bot.sendMessage(ricecab_id, "ERROR: '/reset' request error.");
                    console.log(ricecab_id + " ERROR: '/reset' request error.");
                }
            });
        }
    });
}

/////////////////////////////////////////////////////////////// CAMERA FUNCTIONS

function send_photo(chat_id, photo_file_dir, caption_desc) {
    bot.sendPhoto(chat_id, photo_file_dir, {caption: caption_desc});
}

///////////////////////////////////////////////////// Speech Recognition Arrays.

var SRA_ride = ['give~aride', 'getaride', 'driveme', 'pick~up', 'need~ride'];

var SRA_morning = ['morning', 'touni'];
var SRA_evening = ['evening', 'afternoon', 'wayback', 'fromuni', 'backhome', 'ridehome'];

///////////////////////////////////////////////////////////////////////// Logic.

bot.on('message', function (msg) {
    var chatId = msg.chat.id;
    var user1stName = msg.from.first_name;
    var str = msg.text; str = str.replace(/\s+/g, '').toLowerCase();

    switch (str) {
        case 'whereisevan?':
            bot.sendMessage(chatId, "Good question.");
            break;

        default:
        if (str.search('thanks') !== -1) {
            bot.sendMessage(chatId, "You're Welcome 😘");
        }
        if (if_include(str, SRA_ride) && if_include(str, 'tomorrow')) {

            var rdmsg = [
                "It is understood that ",
                " needs a ride tomorrow ",
                ". Evan will be informed! 🗣👌📢👍📡😊"
            ];

            if (if_include(str, SRA_morning)) {
                bot.sendMessage(chatId, rdmsg[0] + user1stName + rdmsg[1] + SRA_morning[0] + rdmsg[2]);
                inform_admin(user1stName + ' needs a ride tomorrow morning.');
            }
            if (if_include(str, SRA_evening)) {
                bot.sendMessage(chatId, rdmsg[0] + user1stName + rdmsg[1] + SRA_evening[0] + rdmsg[2]);
                inform_admin(user1stName + ' needs a ride tomorrow evening.');
            }
        }
    }
});

////////////////////////////////////////////////// Speech Recognition Functions.

// Should really only check a scentence at a time for accuracy.
function if_include(in_msg, phrases) {

    for (var i = 0; i < phrases.length; i++) {
        if (in_msg.search(phrases[i]) !== -1) {return true;}
        console.log('comparing: ' + in_msg + ' with: ' + phrases[i] + '.');

        // CHECK >> '~' :
        if (phrases[i].search('~') !== -1) {
            var temp_phrases = phrases[i].split('~');
            var n_incld = 0;

            for (var j = 0; j < temp_phrases.length; j++) {
                if (in_msg.search(temp_phrases[j]) !== -1) {n_incld = n_incld + 1;}
            }
            if (n_incld === temp_phrases.length) {return true;}
        }
    }
    return false;
}

//////////////////////////////////////////////// '/checkin' & '/stats' functions

// Get number of rides from specified user.
function get_n_rides(path, user_id) {
    fs.readFile(path + 'logs/' + user_id + '.txt', function(err, data) {
        if (err) {
            var err_msg = "ERROR: Unable to get number of 'checkin's from " + user_id + ". Assuming 0.";
            bot.sendMessage(-116496721, err_msg); console.log(-116496721 + err_msg);
            return 0;
        }

        var file_str = data.toString();
        var n_checkin = 0;

        for (var i = 0; i < file_str.length; i++) {
            if (file_str[i] === '[') { n_checkin += 1; }
        }
        bot.sendMessage(user_id, "within get_n_rides: " + n_checkin);
        return n_checkin;
    });
}

// Get total cost from specified user.
function get_total_cost(path, user_id) {
    fs.readFile(path + 'logs/' + user_id + '.txt', function(err, data) {
        if (err) {
            var err_msg = "ERROR: Unable to get number of 'checkin's from " + user_id + ". Assuming 0.";
            bot.sendMessage(-116496721, err_msg); console.log(-116496721 + err_msg);
        }

        // Convert data to lowercase, spaceless string.
        var file_str = data.toString();
        file_str = file_str.replace(/\s+/g, '').toLowerCase();

        var cmp_str = 'COST';
        var total_cost = 0.00;

        for (var i = 0; i < file_str.length; i++) {

            // Find 'COST' in string.
            if (
                file_str[i] === cmp_str[0] &&
                file_str.slice(i, i + cmp_str.length) === cmp_str
            ) {
                // Move to after 'COST' term.
                i += cmp_str.length;

                // Find positions of two preceeding '"'s.
                var pos_PA = [];
                while (true) {
                    if (file_str[i] === '"') { pos_PA.push(i); }
                    if (pos_PA.length === 2) { break; }
                    i += 1;
                }

                // Extract 'COST' value and add to 'total_cost'.
                total_cost += parseFloat(file_str.slice(pos_PA[0] + 1, pos_PA[1]));
            }
        }
        return total_cost;
    });
    return 0.00;
}

////////////////////////////////////////////////////////// CONSOLE LOG FUNCTIONS

function access_denied(cmd, userName, userId, chatId, timeStamp) {
    var msg = "ON " + timeStamp + " >>\n" +
    "[ACCESS DENIED] CMD: '" + cmd + "'" +
    ", Name: "    + userName +
    ", User ID: " + userId +
    ", Chat ID: " + chatId + "\n";
    console.log(msg);
}

function access_granted(cmd, userName, userId, chatId, timeStamp) {
    var msg = "ON " + timeStamp + " >>\n" +
    "[ACCESS GRANTED] CMD: '" + cmd + "'" +
    ", Name: "    + userName +
    ", User ID: " + userId +
    ", Chat ID: " + chatId + "\n";
    console.log(msg);
}

function inform_admin(admin_msg) {bot.sendMessage(133607928, admin_msg);}
<|endoftext|>


<commit_before>// jNottery (c) 2014, Tomasz Zduńczyk <tomasz@zdunczyk.org>
// Released under the MIT license.

(function($) {
    var OBJ_NOTE = 0,
        OBJ_SELECTION = 1,
        OBJ_ELEMENT = 2;

    var last_range = null;

    window.tt = function(obj, context) {
        var $obj,
            target,
            obj_type;

        if(!obj) {
            return $();
        } else if(obj instanceof tt.core.Note) {
            if(obj instanceof tt.core.SelectionNote) {
                !obj.range.isValid() && obj.range.refresh();
                $obj = tt.range.getElements(obj.range, obj.id);
            } else
                $obj = obj.element;

            target = obj;
            obj_type = OBJ_NOTE;
        } else if(obj.tt_selection && obj.tt_selection instanceof tt.core.Selection) {
            $obj = obj;
            target = obj.tt_selection;
            obj_type = OBJ_SELECTION;
        } else {
            $obj = new $.fn.init(obj, context);
            obj_type = OBJ_ELEMENT;
        }

        return $.extend({}, $obj, {
            arrowPosition: function(options) {
                return tt.tooltip.arrowPosition($.extend({}, { root: $(this) }, options));
            },
            tooltip: function(options) {
                var first_note,
                    tooltip,
                    add_note_to = $(this),
                    note_factory = function(content) {
                        return new tt.core.ElementNote(add_note_to, content);
                    };

                last_range && tt.range.clear(last_range);

                // stick to one note per element
                switch(obj_type) {
                    case OBJ_NOTE: {
                        add_note_to = target.element;
                        first_note = target;
                        break;
                    }
                    case OBJ_SELECTION: {
                        add_note_to = target.element;
                        last_range = target.range;

                        note_factory = function(content) {
                            last_range = null;
                            return new tt.core.SelectionNote(add_note_to, target.range, content);
                        };

                        break;
                    }
                    default: {
                        $.each(tt.core.getNotes($(this)), function(id, note) {
                            if(note instanceof tt.core.ElementNote) {
                                first_note = note;
                                return false;
                            }
                        });
                    }
                }

                tooltip = tt.tooltip.open($.extend({}, {
                    root: $(this),
                    edit: (first_note ? first_note.id : false),
                    content: (first_note ? first_note.getContent() : ''),
                    init: function(tooltip) {

                        tooltip.on({
                            'btn.edit.click.tt': function() {
                                tt.tooltip.switchEditMode(false);
                            },
                            'btn.facebook.click.tt': function() {
                                tt.vendor.facebook(document.URL);
                            },
                            'btn.twitter.click.tt': function() {
                                tt.vendor.bitly(document.URL, function(short_url) {
                                    tt.vendor.twitter(short_url);
                                });
                            },
                            'btn.link.click.tt': function() {
                                tt.vendor.bitly(document.URL, function(short_url) {
                                    window.prompt('Here is link to this page containing your notes (Ctrl + C to save in clipboard)', short_url);
                                });
                            },
                            'btn.save.click.tt': function() {
                                var agent = navigator.userAgent.toLowerCase(),
                                    letter = 'D';

                                if(window.opera && window.opera.version() < 9)
                                    letter = 'T';
                                else if(agent.indexOf('konqueror') !== -1)
                                    letter = 'B';

                                alert('Your notes are currently encoded in URL. Press ' + (agent.indexOf('mac') !== -1 ? 'Cmd' : 'Ctrl') + ' + ' + letter + ' to bookmark this page and all of your notes at once.');
                            }
                        });
                    }
                }, options));

                tooltip.off('submit.tt').on('submit.tt', function(e, tooltip_obj) {
                    var note_id = tooltip_obj.edit(),
                        content = tooltip_obj.content(),
                        note;

                    if(!content)
                        return false;

                    if(!note_id) {
                        note = note_factory(content);
                        var asd = tt.core.addNote(note);
                        tooltip_obj.edit(asd);
                        tt.range.clear(note.range);
                        tt.range.apply(note.range, asd);
                        tooltip.trigger('new.note.tt', [ tooltip_obj, note ]);
                    } else {
                        note = tt.core.getNote(add_note_to, note_id);
                        note.setContent(content);
                        tooltip.trigger('edit.note.tt', [ tooltip_obj, note ]);
                    }

                    tt.tooltip.switchEditMode(true);
                    tt.core.updateHash();
                });

                tooltip.off('delete.tt').on('delete.tt', function(e, tooltip) {
                    var note_id = tooltip.edit(),
                        note;

                    if(note_id) {
                        note = tt.core.getNote(add_note_to, note_id);

                        if(note.range)
                            tt.range.clear(note.range, note.id);

                        note.remove();
                        $(this).trigger('btn.close.click.tt');

                        tt.core.updateHash();
                    }
                });

                tooltip.off('close.tt');

                if(obj_type === OBJ_SELECTION) {
                    tooltip.on('close.tt', function(e, tooltip) {
                        if(!tooltip.edit()) {
                            tt.range.clear(target.range);
                            last_range = null;
                        }
                    });
                }

                return tooltip;
            },
            init: function(options) {
                if(!rangy.initialized)
                    rangy.init();

                tt.core.init($.extend({}, { root: $(this) }, options));

                if(options && options.vendor)
                    tt.vendor.init(options.vendor);

                return this;
            },
            selection: function() {
                var range = tt.range.getFrom($(this)),
                    result;

                if(range) {
                    tt.range.apply(range);
                    result = tt.range.getElements(range);

                    result.tt_selection = new tt.core.Selection($(this), range);

                    return result;
                }

                return $();
            }
        });
    };

})(window.jQuery);<commit_msg>some minor fixes and refactoring<commit_after>// jNottery (c) 2014, Tomasz Zduńczyk <tomasz@zdunczyk.org>
// Released under the MIT license.

(function($) {
    var OBJ_NOTE = 0,
        OBJ_SELECTION = 1,
        OBJ_ELEMENT = 2;

    var last_range = null;

    window.tt = function(obj, context) {
        var $obj,
            target,
            obj_type;

        if(!obj) {
            return $();
        } else if(obj instanceof tt.core.Note) {
            if(obj instanceof tt.core.SelectionNote) {
                !obj.range.isValid() && obj.range.refresh();
                $obj = tt.range.getElements(obj.range, obj.id);
            } else
                $obj = obj.element;

            target = obj;
            obj_type = OBJ_NOTE;
        } else if(obj.tt_selection && obj.tt_selection instanceof tt.core.Selection) {
            $obj = obj;
            target = obj.tt_selection;
            obj_type = OBJ_SELECTION;
        } else {
            $obj = new $.fn.init(obj, context);
            obj_type = OBJ_ELEMENT;
        }

        return $.extend({}, $obj, {
            arrowPosition: function(options) {
                return tt.tooltip.arrowPosition($.extend({}, { root: $(this) }, options));
            },
            tooltip: function(options) {
                var first_note,
                    tooltip,
                    add_note_to = $(this),
                    note_factory = function(content) {
                        return new tt.core.ElementNote(add_note_to, content);
                    };

                last_range && tt.range.clear(last_range);

                // stick to one note per element
                switch(obj_type) {
                    case OBJ_NOTE: {
                        add_note_to = target.element;
                        first_note = target;
                        break;
                    }
                    case OBJ_SELECTION: {
                        add_note_to = target.element;
                        last_range = target.range;

                        note_factory = function(content) {
                            last_range = null;
                            return new tt.core.SelectionNote(add_note_to, target.range, content);
                        };

                        break;
                    }
                    default: {
                        $.each(tt.core.getNotes($(this)), function(id, note) {
                            if(note instanceof tt.core.ElementNote) {
                                first_note = note;
                                return false;
                            }
                        });
                    }
                }

                tooltip = tt.tooltip.open($.extend({}, {
                    root: $(this),
                    edit: (first_note ? first_note.id : false),
                    content: (first_note ? first_note.getContent() : ''),
                    init: function(tooltip) {

                        tooltip.on({
                            'btn.edit.click.tt': function() {
                                tt.tooltip.switchEditMode(false);
                            },
                            'btn.facebook.click.tt': function() {
                                tt.vendor.facebook(document.URL);
                            },
                            'btn.twitter.click.tt': function() {
                                tt.vendor.bitly(document.URL, function(short_url) {
                                    tt.vendor.twitter(short_url);
                                });
                            },
                            'btn.link.click.tt': function() {
                                tt.vendor.bitly(document.URL, function(short_url) {
                                    window.prompt('Here is link to this page containing your notes (Ctrl + C to save in clipboard)', short_url);
                                });
                            },
                            'btn.save.click.tt': function() {
                                var agent = navigator.userAgent.toLowerCase(),
                                    letter = 'D';

                                if(window.opera && window.opera.version() < 9)
                                    letter = 'T';
                                else if(agent.indexOf('konqueror') !== -1)
                                    letter = 'B';

                                alert('Your notes are currently encoded in URL. Press ' + (agent.indexOf('mac') !== -1 ? 'Cmd' : 'Ctrl') + ' + ' + letter + ' to bookmark this page and all of your notes at once.');
                            }
                        });
                    }
                }, options));

                tooltip.off('submit.tt').on('submit.tt', function(e, tooltip_obj) {
                    var note_id = tooltip_obj.edit(),
                        content = tooltip_obj.content(),
                        note;

                    if(!content)
                        return false;

                    if(!note_id) {
                        note = note_factory(content);
                        var asd = tt.core.addNote(note);
                        tooltip_obj.edit(asd);

                        if(note.range && note.range.isValid()) {
                            tt.range.clear(note.range);
                            tt.range.apply(note.range, asd);
                        }

                        tooltip.trigger('new.note.tt', [ tooltip_obj, note ]);
                    } else {
                        note = tt.core.getNote(add_note_to, note_id);
                        note.setContent(content);
                        tooltip.trigger('edit.note.tt', [ tooltip_obj, note ]);
                    }

                    tt.tooltip.switchEditMode(true);
                    tt.core.updateHash();
                });

                tooltip.off('delete.tt').on('delete.tt', function(e, tooltip_obj) {
                    var note_id = tooltip_obj.edit(),
                        note;

                    if(note_id) {
                        note = tt.core.getNote(add_note_to, note_id);

                        if(note.range)
                            tt.range.clear(note.range, note.id);

                        note.remove();
                        tooltip.trigger('deleted.note.tt', [ tooltip_obj, note_id ]);

                        tt.tooltip.close();

                        tt.core.updateHash();
                    }
                });

                tooltip.off('close.tt');

                if(obj_type === OBJ_SELECTION) {
                    tooltip.on('close.tt', function(e, tooltip) {
                        if(!tooltip.edit() && target.range && target.range.isValid()) {
                            tt.range.clear(target.range);
                            last_range = null;
                        }
                    });
                }

                return tooltip;
            },
            init: function(options) {
                if(!rangy.initialized)
                    rangy.init();

                tt.core.init($.extend({}, { root: $(this) }, options));

                if(options && options.vendor)
                    tt.vendor.init(options.vendor);

                return this;
            },
            selection: function() {
                var range = tt.range.getFrom($(this)),
                    result;

                if(range) {
                    tt.range.apply(range);
                    result = tt.range.getElements(range);

                    result.tt_selection = new tt.core.Selection($(this), range);

                    return result;
                }

                return $();
            }
        });
    };

})(window.jQuery);<|endoftext|>


<commit_before>var $ = require('jbone'),
    _ = require('lodash'),
    astrobench = require('./astrobench')
    tmplApp = require('./templates/app.html'),
    tmplSuite = require('./templates/suite.html'),
    tmplBench = require('./templates/bench.html');

var dictionary = {
    runSuite: 'Run suite',
    stopSuite: 'Stop suite',
    runBenchmark: 'Run benchmark',
    stopBenchmark: 'Stop benchmark',
    runAll: 'Run all tests',
    stopAll: 'Stop all tests'
};

$('#astrobench').html(tmplApp({
    dictionary: dictionary
}));

$('.fn-run-tests').on('click', function(e) {
    e.preventDefault();

    astrobench.abort();

    $('.fn-run-tests').html(dictionary.stopAll);

    if (!astrobench.state.running) {
        astrobench.run({
            onStop: function() {
                $('.fn-run-tests').html(dictionary.runAll);
            }
        });
    }
});

var hilite = function(str) {
    return str
        .replace(/</g, '<')
        .replace(/>/g, '>')
        .replace(/\/\/(.*)/gm, '//$1')
        .replace(/('.*?')/gm, '$1')
        .replace(/(\d+\.\d+)/gm, '$1')
        .replace(/(\d+)/gm, '$1')
        .replace(/\bnew *(\w+)/gm, 'new $1')
        .replace(/\b(function|new|throw|return|var|if|else)\b/gm, '$1');
};

var fnstrip = function(fn) {
    str = fn.toString()
        .replace(/\r\n?|[\n\u2028\u2029]/g, "\n").replace(/^\uFEFF/, '')
        .replace(/^function *\(.*\) *{/, '')
        .replace(/\s+\}$/, '');

    var spaces = str.match(/^\n?( *)/)[1].length,
        tabs = str.match(/^\n?(\t*)/)[1].length,
        re = new RegExp('^\n?' + (tabs ? '\t' : ' ') + '{' + (tabs ? tabs : spaces) + '}', 'gm');

    str = str.replace(re, '');

    return str.trim();
};

var onBenchComplete = function(event, suite) {
    var me = event.target,
        error = me.error,
        hz = me.hz,
        id = me.id,
        stats = me.stats,
        pm = Benchmark.support.java ? '+/-' : '\xb1',
        result = '',
        $bench = $('#bench-' + id),
        $results = $bench.find('.fn-bench-result');

    $bench.find('.fn-run-bench').html(dictionary.runBenchmark);

    if (error) {
        result += error.toString();
        $bench[0].classList.add('warning');
        $results[0].classList.add('error');
    } else {
        if (me.aborted) {
            return $bench.find('.fn-bench-state').html('aborted');
        }

        result += ' x ' + Benchmark.formatNumber(hz.toFixed(hz < 100 ? 2 : 0)) + ' ops/sec ' + pm +
            stats.rme.toFixed(2) + '%';
    }

    if (suite && suite.suite.running === false) {
        onSuiteComplete.call(suite.suite, event, suite);
    }

    $results.html(result);
};

var onSuiteComplete = function(event, suite) {
    suite.$el.find('.fn-run-suite').html(dictionary.runSuite);

    if (event.target.aborted) return;

    var fastest = this.filter('fastest'),
        delta,
        $bench;

    this.forEach(function(bench) {
        if (bench.stats.rme === 0) {
            return;
        }

        $bench = $('#bench-' + bench.id);

        if (fastest.indexOf(bench) !== -1) {
            $bench[0].classList.add('fastest');
            $bench.find('.fn-bench-status').html('(fastest)');
            return;
        }

        delta = (Math.abs(bench.hz - fastest.pluck('hz')) / fastest.pluck('hz') * 100).toFixed(2);
        $bench[0].classList.remove('fastest');
        $bench.find('.fn-bench-status').html('(' + delta + '% slower)');
    });
};

exports.drawSuite = function(suite) {
    suite.$el = $(tmplSuite({
        fnstrip: fnstrip,
        hilite: hilite,
        suite: suite,
        dictionary: dictionary
    }));

    $('.fn-suites').append(suite.$el);

    // dom event binding
    suite.$el
        .on('click', '.fn-run-suite', function(e) {
            e.preventDefault();
            suite.run();
        })
        .on('click', '.fn-show-setup', function(e) {
            if (e.defaultPrevented) return;
            $('.suite-setup', suite.$el)[0].classList.toggle('hidden');
        });

    // suite event binding
    suite.suite
        .on('start', function() {
            suite.$el.find('.fn-run-suite').html(dictionary.stopSuite);
        })
        .on('complete', function(event) {
            onSuiteComplete.call(suite.suite, event, suite);
        })
        .on('cycle', onBenchComplete);
};

exports.drawBench = function(suite, bench) {
    var $bench = $(tmplBench({
            bench: bench,
            fnstrip: fnstrip,
            hilite: hilite,
            dictionary: dictionary
        })),
        // cache state Node for fast writing
        $state = $bench.find('.fn-bench-state');

    var onComplete = function(event) {
        onBenchComplete(event, suite);
    };

    suite.$el.find('.fn-benchs').append($bench);

    // dom event binding
    $bench
        .on('click', '.fn-run-bench', function(e) {
            e.preventDefault();
            suite.runBenchmark(bench.id);
        })
        .on('click', '.fn-show-source', function(e) {
            if (e.defaultPrevented) return;
            $bench[0].classList.toggle('opened');
        });

    // benchmark event binding
    bench
        .on('start', function(event) {
            $bench[0].classList.remove('fastest');
            $bench[0].classList.remove('warning');
            $bench.find('.fn-bench-status, .fn-bench-result').html('');
            $bench.find('.fn-run-bench').html(dictionary.stopBenchmark);

            event.target.off('complete', onComplete);
            event.target.on('complete', onComplete);
        })
        .on('cycle', function() {
            $state.html(Benchmark.formatNumber(this.count) + ' (' + this.stats.sample.length + ' samples)');
        })
};
<commit_msg>minor fixs<commit_after>var $ = require('jbone'),
    _ = require('lodash'),
    astrobench = require('./astrobench')
    tmplApp = require('./templates/app.html'),
    tmplSuite = require('./templates/suite.html'),
    tmplBench = require('./templates/bench.html');

var dictionary = {
    runSuite: 'Run suite',
    stopSuite: 'Stop suite',
    runBenchmark: 'Run benchmark',
    stopBenchmark: 'Stop benchmark',
    runAll: 'Run all tests',
    stopAll: 'Stop all tests'
};

$('#astrobench').html(tmplApp({
    dictionary: dictionary
}));

$('.fn-run-tests').on('click', function(e) {
    e.preventDefault();

    astrobench.abort();

    $('.fn-run-tests').html(dictionary.stopAll);

    if (!astrobench.state.running) {
        astrobench.run({
            onStop: function() {
                $('.fn-run-tests').html(dictionary.runAll);
            }
        });
    }
});

var hilite = function(str) {
    return str
        .replace(/</g, '<')
        .replace(/>/g, '>')
        .replace(/\/\/(.*)/gm, '//$1')
        .replace(/('.*?')/gm, '$1')
        .replace(/(\d+\.\d+)/gm, '$1')
        .replace(/(\d+)/gm, '$1')
        .replace(/\bnew *(\w+)/gm, 'new $1')
        .replace(/\b(function|new|throw|return|var|if|else)\b/gm, '$1');
};

var fnstrip = function(fn) {
    str = fn.toString()
        .replace(/\r\n?|[\n\u2028\u2029]/g, "\n").replace(/^\uFEFF/, '')
        .replace(/^function *\(.*\) *{/, '')
        .replace(/\s+\}$/, '');

    var spaces = str.match(/^\n?( *)/)[1].length,
        tabs = str.match(/^\n?(\t*)/)[1].length,
        re = new RegExp('^\n?' + (tabs ? '\t' : ' ') + '{' + (tabs ? tabs : spaces) + '}', 'gm');

    str = str.replace(re, '');

    return str.trim();
};

var onBenchComplete = function(event, suite) {
    var me = event.target,
        error = me.error,
        hz = me.hz,
        id = me.id,
        stats = me.stats,
        pm = Benchmark.support.java ? '+/-' : '\xb1',
        result = '',
        $bench = $('#bench-' + id),
        $results = $bench.find('.fn-bench-result');

    $bench.find('.fn-run-bench').html(dictionary.runBenchmark);

    if (error) {
        result += error.toString();
        $bench[0].classList.add('warning');
        $results[0].classList.add('error');
    } else {
        if (me.aborted) {
            return $bench.find('.fn-bench-state').html('aborted');
        }

        result += ' x ' + Benchmark.formatNumber(hz.toFixed(hz < 100 ? 2 : 0)) + ' ops/sec ' + pm +
            stats.rme.toFixed(2) + '%';
    }

    if (suite && suite.suite.running === false) {
        onSuiteComplete.call(suite.suite, event, suite);
    }

    $results.html(result);
};

var onSuiteComplete = function(event, suite) {
    suite.$el.find('.fn-run-suite').html(dictionary.runSuite);

    if (event.target.aborted) return;

    var fastest = this.filter('fastest'),
        delta, $bench;

    this.forEach(function(bench) {
        if (bench.stats.rme === 0) return;

        $bench = $('#bench-' + bench.id);

        if (fastest.indexOf(bench) !== -1) {
            $bench[0].classList.add('fastest');
            $bench.find('.fn-bench-status').html('(fastest)');
            return;
        }

        delta = (Math.abs(bench.hz - fastest.pluck('hz')) / fastest.pluck('hz') * 100).toFixed(2);
        $bench[0].classList.remove('fastest');
        $bench.find('.fn-bench-status').html('(' + delta + '% slower)');
    });
};

exports.drawSuite = function(suite) {
    suite.$el = $(tmplSuite({
        fnstrip: fnstrip,
        hilite: hilite,
        suite: suite,
        dictionary: dictionary
    }));

    $('.fn-suites').append(suite.$el);

    // dom event binding
    suite.$el
        .on('click', '.fn-run-suite', function(e) {
            e.preventDefault();
            suite.run();
        })
        .on('click', '.fn-show-setup', function(e) {
            if (e.defaultPrevented) return;
            $('.suite-setup', suite.$el)[0].classList.toggle('hidden');
        });

    // suite event binding
    suite.suite
        .on('start', function() {
            suite.$el.find('.fn-run-suite').html(dictionary.stopSuite);
        })
        .on('complete', function(event) {
            onSuiteComplete.call(suite.suite, event, suite);
        })
        .on('cycle', onBenchComplete);
};

exports.drawBench = function(suite, bench) {
    var $bench = $(tmplBench({
            bench: bench,
            fnstrip: fnstrip,
            hilite: hilite,
            dictionary: dictionary
        })),
        // cache state Node for fast writing
        $state = $bench.find('.fn-bench-state');

    var onComplete = function(event) {
        onBenchComplete(event, suite);
    };

    suite.$el.find('.fn-benchs').append($bench);

    // dom event binding
    $bench
        .on('click', '.fn-run-bench', function(e) {
            e.preventDefault();
            suite.runBenchmark(bench.id);
        })
        .on('click', '.fn-show-source', function(e) {
            if (e.defaultPrevented) return;
            $bench[0].classList.toggle('opened');
        });

    // benchmark event binding
    bench
        .on('start', function(event) {
            $bench[0].classList.remove('fastest');
            $bench[0].classList.remove('warning');
            $bench.find('.fn-bench-status, .fn-bench-result').html('');
            $bench.find('.fn-run-bench').html(dictionary.stopBenchmark);

            event.target.off('complete', onComplete);
            event.target.on('complete', onComplete);
        })
        .on('cycle', function() {
            $state.html(Benchmark.formatNumber(this.count) + ' (' + this.stats.sample.length + ' samples)');
        });
};
<|endoftext|>


<commit_before>import React, { Component } from 'react';

import { Map, Marker, Popup, TileLayer, FeatureGroup } from 'react-leaflet';

class OneMap extends Component {

  render() {
    const position = [60.172059, 24.945831]; // Default to Helsinki's center
    const bounds = [
      [59.9, 24.59],  // SouthWest corner
      [60.43, 25.3]  // NorthEast corner
    ];

    return (
      <Map center={position} zoom={13}>
        <TileLayer
          url='http://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png'
          attribution='© OpenStreetMap contributors'
          minZoom={10} maxZoom={16} zoomControl={true}
        />
        <Marker position={position}>
          <Popup>
            A pretty CSS3 popup.
Easily customizable.
          </Popup>
        </Marker>
      </Map>
    );
  }
}

/*
<FeatureGroup
  ref={(input) => {
    if (!input) return;
    const bounds = input.leafletElement.getBounds();
    if (bounds.isValid()) {
      input.props.map.fitBounds(bounds);
      const viewportBounds = [
        [59.9, 24.59],  // SouthWest corner
        [60.43, 25.3]  // NorthEast corner
      ];  // Wide Bounds of City of Helsinki area
      input.props.map.setMaxBounds(viewportBounds);
    }
  }}
>{contents}</FeatureGroup>
*/

const fetch_places = () => {
    fetch('//localhost:9000/place_data/').then(function(response) {
        // Convert to JSON
        return response.json();
    }).then(function(data) {
        // Yay, `j` is a JavaScript object
        console.log(data);
        return data;
    });
};

class App extends Component {
    constructor(props) {
        super(props);
        this.state = {places: false};
    }

    get_data() {
        this.setState({places: fetch_places()});
    }

    componentDidMount() {
        this.get_data();
    }

    render() {
        return (

            <OneMap />

        );
    }
}

export default App;
<commit_msg>Map shows markers for features from API<commit_after>import React, { Component } from 'react';

import { Map, Marker, Popup, TileLayer, FeatureGroup } from 'react-leaflet';

class OneMap extends Component {

  render() {
    const position = [60.172059, 24.945831]; // Default to Helsinki's center
    const bounds = [
      [59.9, 24.59],  // SouthWest corner
      [60.43, 25.3]  // NorthEast corner
    ];

    const places = this.props.places;
    if (places) {
        let markers = places.features.map((feature) => {

            if (!feature.geometry) return null;

            return (
                <Marker key={feature.properties.name} position={feature.geometry.coordinates.reverse()}>
                    <Popup>
                        {feature.properties.description}
                    </Popup>
                </Marker>
            );
        });

        return (
            <Map center={position} zoom={13}>
                <TileLayer
                    url='http://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png'
                    attribution='© OpenStreetMap contributors'
                    minZoom={10} maxZoom={16} zoomControl={true}
                />
                {markers}
            </Map>
        );
    } else {
        return null;
    }
  }
}

/*
<FeatureGroup
  ref={(input) => {
    if (!input) return;
    const bounds = input.leafletElement.getBounds();
    if (bounds.isValid()) {
      input.props.map.fitBounds(bounds);
      const viewportBounds = [
        [59.9, 24.59],  // SouthWest corner
        [60.43, 25.3]  // NorthEast corner
      ];  // Wide Bounds of City of Helsinki area
      input.props.map.setMaxBounds(viewportBounds);
    }
  }}
>{contents}</FeatureGroup>
*/

const fetch_places = (f) => {
    fetch('//localhost:9000/place_data/').then(function(response) {
        // Convert to JSON
        return response.json();
    }).then(function(data) {
        // Yay, `j` is a JavaScript object
        console.log(data);
        f(data);
    });
};

class App extends Component {
    constructor(props) {
        super(props);
        this.state = {places: false};
    }

    get_data() {
        fetch_places(data => this.setState({places: data}));
    }

    componentDidMount() {
        this.get_data();
    }

    render() {
        return (

            <OneMap places={this.state.places} />

        );
    }
}

export default App;
<|endoftext|>


<commit_before>'use strict'

class Link {

    get id() {

        return (this.linkElement) ? this.linkElement.id : undefined;

    };

    set id(newId) {

        this.linkElement.id = newId; // <? catch?

    };

    get path() {

        return this.linkElement.getAttribute('d');

    };

    set path(newPath) {

        this.linkElement.setAttribute('d', newPath);

    }

    constructor(startDock, endDock = undefined) {

        this.startDock = startDock;
        this.isData = startDock.isData;
        // this.type = startDock.type;

        this.createLink();

        this.id = startDock.id;

        if (endDock) {

            this.endDock = endDock;
            this.update(endDock.position);
            this.set();

        }

        this.startDock.links.push(this);

        // right-sided data docks are never occupied
        startDock.occupied = !(startDock.isRight && startDock.isData);

    };

    createLink() {

        let template = document.querySelector('template#link');
        template = document.importNode(template.content, true);

        this.linkElement = template.querySelector('path');

        const dataName = this.isData ? 'data' : 'exe';
        this.linkElement.style.stroke = Link.color[ dataName ];
        this.linkElement.style.strokeWidth = Link.width[ dataName ];

        Canvas.linkArea.appendChild(this.linkElement);

    };

    edit() {

        delete links[ this.id ];

        this.endDock.links = []; // reset the old endDock
        this.endDock.occupied = false;

        ControlFlow.update(this.endDock.node);

        delete this.endDock;

        return this;

    };

    static updateAll() {

        Object.entries(links).forEach(([ id, link ]) => {

            link.update();

        });

    };

    update(endPoint) {

        if (!endPoint) {

            this.path = Curve.get(this.startDock.position, this.endDock.position);

        } else if (this.startDock.isRight) {

            this.path = Curve.get(this.startDock.position, endPoint);

        } else {

            this.path = Curve.get(endPoint, this.startDock.position);

        }

    };

    // <? is there any refactoring possible here? use linkIndexStartDock = this.startDock.links.indexOf(link);
    remove() {

        // make sure the link is removed from links
        delete links[ this.id ];

        this.linkElement.remove();

        // make it a Dock method <Dock>.unpin(this) where this is <Link>
        const linkIndexStartDock = this.startDock.links.findIndex(link => link.id == this.id);
        this.startDock.links.splice(linkIndexStartDock, 1);

        this.startDock.occupied = false;

        if (this.endDock) {

            const linkIndexSnapDock = this.endDock.links.findIndex(link => link.id == this.id);
            this.endDock.links.splice(linkIndexSnapDock, 1);

            this.endDock.occupied = false;

        }

    };

    set() {

        // add to endDock
        this.endDock.links.push(this);
        this.endDock.occupied = true;

        // swap startDock and endDock if necessary
        if (this.endDock.isRight) {

            [ this.startDock, this.endDock ] = [ this.endDock, this.startDock ];

        }

        const linkId = this.startDock.id + Link.separator + this.endDock.id;
        this.id = linkId;

        // this link already exists
        if (links[ linkId ]) {

            this.remove();

        // link doesn't yet exist
        } else {

            links[ linkId ] = this;

            ControlFlow.update(this.endDock.node);

        }

    };

    static destruct(link) {

        return [ link.startDock.id, link.endDock.id ];

    };

}; let links = {};

Object.assign(Link, {

    separator: '-',

    color: {
        data: 'green',
        exe: 'blue'
    },

    width: {
        data: 3,
        exe: 4
    }

});
<commit_msg>wait a bit for the HTML elements to register before interpreting<commit_after>'use strict'

class Link {

    static separator = '-';
    static color = { data: 'green', exe: 'blue' };
    static width = { data: 3, exe: 4 };

    get id() {

        return (this.linkElement) ? this.linkElement.id : undefined;

    };

    set id(newId) {

        this.linkElement.id = newId; // <? catch?

    };

    get path() {

        return this.linkElement.getAttribute('d');

    };

    set path(newPath) {

        this.linkElement.setAttribute('d', newPath);

    }

    constructor(startDock, endDock = undefined) {

        this.startDock = startDock;
        this.isData = startDock.isData;
        // this.type = startDock.type;

        this.createLink();

        this.id = startDock.id;

        if (endDock) {

            this.endDock = endDock;
            this.update(endDock.position);
            this.set();

        }

        this.startDock.links.push(this);

        // right-sided data docks are never occupied
        startDock.occupied = !(startDock.isRight && startDock.isData);

    };

    createLink() {

        let template = document.querySelector('template#link');
        template = document.importNode(template.content, true);

        this.linkElement = template.querySelector('path');

        const dataName = this.isData ? 'data' : 'exe';
        this.linkElement.style.stroke = Link.color[ dataName ];
        this.linkElement.style.strokeWidth = Link.width[ dataName ];

        Canvas.linkArea.appendChild(this.linkElement);

    };

    edit() {

        delete links[ this.id ];

        this.endDock.links = []; // reset the old endDock
        this.endDock.occupied = false;

        ControlFlow.update(this.endDock.node);

        delete this.endDock;

        return this;

    };

    static updateAll() {

        Object.entries(links).forEach(([ id, link ]) => {

            link.update();

        });

    };

    update(endPoint) {

        if (!endPoint) {

            this.path = Curve.get(this.startDock.position, this.endDock.position);

        } else if (this.startDock.isRight) {

            this.path = Curve.get(this.startDock.position, endPoint);

        } else {

            this.path = Curve.get(endPoint, this.startDock.position);

        }

    };

    // <? is there any refactoring possible here? use linkIndexStartDock = this.startDock.links.indexOf(link);
    remove() {

        // make sure the link is removed from links
        delete links[ this.id ];

        this.linkElement.remove();

        // make it a Dock method <Dock>.unpin(this) where this is <Link>
        const linkIndexStartDock = this.startDock.links.findIndex(link => link.id == this.id);
        this.startDock.links.splice(linkIndexStartDock, 1);

        this.startDock.occupied = false;

        if (this.endDock) {

            const linkIndexSnapDock = this.endDock.links.findIndex(link => link.id == this.id);
            this.endDock.links.splice(linkIndexSnapDock, 1);

            this.endDock.occupied = false;

        }

    };

    set() {

        // add to endDock
        this.endDock.links.push(this);
        this.endDock.occupied = true;

        // swap startDock and endDock if necessary
        if (this.endDock.isRight) {

            [ this.startDock, this.endDock ] = [ this.endDock, this.startDock ];

        }

        const linkId = this.startDock.id + Link.separator + this.endDock.id;
        this.id = linkId;

        // this link already exists
        if (links[ linkId ]) {

            this.remove();

        // link doesn't yet exist
        } else {

            links[ linkId ] = this;

            wait(() => ControlFlow.update(this.endDock.node));

        }

    };

    static destruct(link) {

        return [ link.startDock.id, link.endDock.id ];

    };

}; const links = {};
<|endoftext|>