<commit_before>var Game = (function() {

  function Game(voxelSource) {
    var self = this
    this.voxelSource = voxelSource
    this.texturePath = '/textures/'
    this.container = '#container'
    this.cubeSize = 25
    this.chunkDistance = 2
    this.startingPosition = new THREE.Vector3(35,1024,35)
    this.worldOrigin = new THREE.Vector3(0,0,0)

    this.material = this.loadTextures([ 'grass', 'grass_dirt', 'brick' ])

    this.height = window.innerHeight
    this.width = window.innerWidth
    this.scene = scene = new THREE.Scene()
    this.camera = this.createCamera(scene)
    this.renderer = this.createRenderer()
    this.controls = this.createControls()
    this.addLights(this.scene)
    this.moveToPosition(this.startingPosition)
    this.chunker = new Chunker(this)
    var chunks = this.chunker.generateMissingChunks(this.worldOrigin)
    this.addStats()
    window.addEventListener( 'resize', this.onWindowResize.bind(this), false )
    window.addEventListener( 'mousedown', this.onMouseDown.bind(this), false )
    this.tick()
  }

  Game.prototype.moveToPosition = function(position) {
    var pos = this.controls.yawObject.position
    pos.x = position.x
    pos.y = position.y
    pos.z = position.z
  }

  Game.prototype.onWindowResize = function() {
    this.camera.aspect = window.innerWidth / window.innerHeight
    this.camera.updateProjectionMatrix()
    this.renderer.setSize( window.innerWidth, window.innerHeight )
  }

  Game.prototype.addMarker = function(position) {
    var geometry = new THREE.SphereGeometry( 1, 4, 4 );
		var material = new THREE.MeshPhongMaterial( { color: 0xffffff, shading: THREE.FlatShading } );
		var mesh = new THREE.Mesh( geometry, material );
		mesh.position.copy(position)
		this.scene.add(mesh)
  }

  Game.prototype.onMouseDown = function(e) {
    var intersection = this.raycast()
    if (!intersection) return
		var hitVoxel = this.voxelAtPosition(intersection, 0)
		var c = this.chunker.chunkAtPosition(intersection)
		this.chunker.generateChunk(c[0], c[1], c[2])
  }

  Game.prototype.intersectAllMeshes = function(start, direction) {
    var meshes = []
    Object.keys(game.chunker.meshes).map(function(key) {
      meshes.push(game.chunker.meshes[key].surfaceMesh)
    })
    var d = direction.subSelf(start).normalize()
    var ray = new THREE.Raycaster(start, d)
    var intersections = ray.intersectObjects( meshes )
    if (intersections.length === 0) return false
    var intersection = intersections[0]
    var p = new THREE.Vector3()
    p.copy(intersection.point)
    p.x += d.x
    p.y += d.y
    p.z += d.z
    return p
  }

  Game.prototype.raycast = function() {
    var start = this.controls.yawObject.position.clone()
    var direction = this.camera.matrixWorld.multiplyVector3(new THREE.Vector3(0,0,-1))
    var intersects = this.intersectAllMeshes(start, direction)
    return intersects
  }

  Game.prototype.loadTextures = function(names) {
    var self = this;
    return new THREE.MeshFaceMaterial(names.map(function (name) {
      var tex = THREE.ImageUtils.loadTexture(self.texturePath + name + ".png")
      tex.magFilter = THREE.NearestFilter
      tex.minFilter = THREE.LinearMipMapLinearFilter

      return new THREE.MeshLambertMaterial({
        map: tex,
        ambient: 0xbbbbbb
      })
    }))
  }

  Game.prototype.createCamera = function() {
    var camera;
    camera = new THREE.PerspectiveCamera(60, this.width / this.height, 1, 10000)
    camera.lookAt(new THREE.Vector3(0, 0, 0))
    this.scene.add(camera)
    return camera
  }

  Game.prototype.createControls = function() {
    var controls = new THREE.PointerLockControls(this.camera)
    this.scene.add( controls.yawObject )
    return controls
  }

  Game.prototype.createRenderer = function() {
    if( Detector.webgl ){
      renderer = new THREE.WebGLRenderer({
        antialias: true
      })
    } else {
      renderer = new THREE.CanvasRenderer()
    }
    renderer.setSize(this.width, this.height)
    renderer.setClearColorHex(0xBFD1E5, 1.0)
    renderer.clear()
    document.querySelector(this.container).appendChild(renderer.domElement)
    return renderer
  }

  Game.prototype.addStats = function() {
    stats = new Stats()
    stats.domElement.style.position  = 'absolute'
    stats.domElement.style.bottom  = '0px'
    document.body.appendChild( stats.domElement )
  }

  Game.prototype.addLights = function(scene) {
    var ambientLight, directionalLight
    ambientLight = new THREE.AmbientLight(0xaaaaaa)
    scene.add(ambientLight)
    var light	= new THREE.DirectionalLight( Math.random() * 0xffffff )
    light.position.set( Math.random(), Math.random(), Math.random() ).normalize()
    scene.add( light )
  };

  Game.prototype.currentMesh = function() {
    var cid = game.chunker.chunkAtPosition(game.controls.yawObject.position).join('|')
    return game.chunker.meshes[cid]
  }

  Game.prototype.cameraRotation = function() {
    var xAngle = this.controls.pitchObject.rotation.x
    var yAngle = this.controls.yawObject.rotation.y
    return {x: xAngle, y: yAngle}
  }

  Game.prototype.getCollisions = function(position) {
    var self = this
    var p = position.clone()
    var w = self.cubeSize / 4 // width of player cube
    var h = self.cubeSize // height of player cube

    var vertices = {
      bottom: [
        new THREE.Vector3(p.x - w, p.y - h, p.z - w),
        new THREE.Vector3(p.x - w, p.y - h, p.z + w),
        new THREE.Vector3(p.x + w, p.y - h, p.z - w),
        new THREE.Vector3(p.x + w, p.y - h, p.z + w)
      ],
      middle: [
        new THREE.Vector3(p.x - w, p.y, p.z - w),
        new THREE.Vector3(p.x - w, p.y, p.z + w),
        new THREE.Vector3(p.x + w, p.y, p.z - w),
        new THREE.Vector3(p.x + w, p.y, p.z + w)
      ],
      top: [
        new THREE.Vector3(p.x - w, p.y + h, p.z - w),
        new THREE.Vector3(p.x - w, p.y + h, p.z + w),
        new THREE.Vector3(p.x + w, p.y + h, p.z - w),
        new THREE.Vector3(p.x + w, p.y + h, p.z + w)
      ],
    }

    return {
      bottom: vertices.bottom.map(check).filter(Boolean),
      middle: vertices.middle.map(check).filter(Boolean),
      top: vertices.top.map(check).filter(Boolean)
    }

    function check(vertex) {
      return self.voxelAtPosition(vertex) && vertex
    }
  }

  Game.prototype.voxelIndex = function(pos) {
    var size = this.voxelSource.chunkSize
    var x = (size + Math.floor(pos.x / this.cubeSize)) % size
    var y = (size + Math.floor(pos.y / this.cubeSize)) % size
    var z = (size + Math.floor(pos.z / this.cubeSize)) % size
    var vidx = x + y*size + z*size*size
    return vidx
  }

  Game.prototype.voxelAtPosition = function(pos, val) {
    var ckey = this.chunker.chunkAtPosition(pos).join('|')
    var chunk = this.chunker.chunks[ckey]
    if (!chunk) return false
    var vidx = this.voxelIndex(pos)
    if (!vidx) return false
    if (typeof val !== 'undefined') {
      chunk.voxels[vidx] = val
    }
    var v = chunk.voxels[vidx]
    return v
  }

  Game.prototype.tick = function() {
    var self = this
    requestAnimationFrame( this.tick.bind(this) )
    var dt = Date.now() - this.time
    if (!this.time) dt = 1
    var cam = this.camera.position

    this.controls.update(dt, function (pos, velocity) {
      var collisions = self.getCollisions(game.controls.yawObject.position)

      if (collisions.middle.length) {
        game.controls.yawObject.translateX(-velocity.x)
        game.controls.yawObject.translateZ(-velocity.z)
        velocity.x *= -1
        velocity.z *= -1
      }

      if (collisions.bottom.length) {
        this.gravityEnabled = false
        velocity.y = Math.max(0, velocity.y)
      }
      else {
        this.gravityEnabled = true
      }
    })

    this.renderer.render(this.scene, this.camera)
    stats.update()
    this.time = Date.now()
  }

  return Game

})()
;
<commit_msg>no more random lights<commit_after>var Game = (function() {

  function Game(voxelSource) {
    var self = this
    this.voxelSource = voxelSource
    this.texturePath = '/textures/'
    this.container = '#container'
    this.cubeSize = 25
    this.chunkDistance = 2
    this.startingPosition = new THREE.Vector3(35,1024,35)
    this.worldOrigin = new THREE.Vector3(0,0,0)

    this.material = this.loadTextures([ 'grass', 'grass_dirt', 'brick' ])

    this.height = window.innerHeight
    this.width = window.innerWidth
    this.scene = scene = new THREE.Scene()
    this.camera = this.createCamera(scene)
    this.renderer = this.createRenderer()
    this.controls = this.createControls()
    this.addLights(this.scene)
    this.moveToPosition(this.startingPosition)
    this.chunker = new Chunker(this)
    var chunks = this.chunker.generateMissingChunks(this.worldOrigin)
    this.addStats()
    window.addEventListener( 'resize', this.onWindowResize.bind(this), false )
    window.addEventListener( 'mousedown', this.onMouseDown.bind(this), false )
    this.tick()
  }

  Game.prototype.moveToPosition = function(position) {
    var pos = this.controls.yawObject.position
    pos.x = position.x
    pos.y = position.y
    pos.z = position.z
  }

  Game.prototype.onWindowResize = function() {
    this.camera.aspect = window.innerWidth / window.innerHeight
    this.camera.updateProjectionMatrix()
    this.renderer.setSize( window.innerWidth, window.innerHeight )
  }

  Game.prototype.addMarker = function(position) {
    var geometry = new THREE.SphereGeometry( 1, 4, 4 );
		var material = new THREE.MeshPhongMaterial( { color: 0xffffff, shading: THREE.FlatShading } );
		var mesh = new THREE.Mesh( geometry, material );
		mesh.position.copy(position)
		this.scene.add(mesh)
  }

  Game.prototype.onMouseDown = function(e) {
    var intersection = this.raycast()
    if (!intersection) return
		var hitVoxel = this.voxelAtPosition(intersection, 0)
		var c = this.chunker.chunkAtPosition(intersection)
		this.chunker.generateChunk(c[0], c[1], c[2])
  }

  Game.prototype.intersectAllMeshes = function(start, direction) {
    var meshes = []
    Object.keys(game.chunker.meshes).map(function(key) {
      meshes.push(game.chunker.meshes[key].surfaceMesh)
    })
    var d = direction.subSelf(start).normalize()
    var ray = new THREE.Raycaster(start, d)
    var intersections = ray.intersectObjects( meshes )
    if (intersections.length === 0) return false
    var intersection = intersections[0]
    var p = new THREE.Vector3()
    p.copy(intersection.point)
    p.x += d.x
    p.y += d.y
    p.z += d.z
    return p
  }

  Game.prototype.raycast = function() {
    var start = this.controls.yawObject.position.clone()
    var direction = this.camera.matrixWorld.multiplyVector3(new THREE.Vector3(0,0,-1))
    var intersects = this.intersectAllMeshes(start, direction)
    return intersects
  }

  Game.prototype.loadTextures = function(names) {
    var self = this;
    return new THREE.MeshFaceMaterial(names.map(function (name) {
      var tex = THREE.ImageUtils.loadTexture(self.texturePath + name + ".png")
      tex.magFilter = THREE.NearestFilter
      tex.minFilter = THREE.LinearMipMapLinearFilter

      return new THREE.MeshLambertMaterial({
        map: tex,
        ambient: 0xbbbbbb
      })
    }))
  }

  Game.prototype.createCamera = function() {
    var camera;
    camera = new THREE.PerspectiveCamera(60, this.width / this.height, 1, 10000)
    camera.lookAt(new THREE.Vector3(0, 0, 0))
    this.scene.add(camera)
    return camera
  }

  Game.prototype.createControls = function() {
    var controls = new THREE.PointerLockControls(this.camera)
    this.scene.add( controls.yawObject )
    return controls
  }

  Game.prototype.createRenderer = function() {
    if( Detector.webgl ){
      renderer = new THREE.WebGLRenderer({
        antialias: true
      })
    } else {
      renderer = new THREE.CanvasRenderer()
    }
    renderer.setSize(this.width, this.height)
    renderer.setClearColorHex(0xBFD1E5, 1.0)
    renderer.clear()
    document.querySelector(this.container).appendChild(renderer.domElement)
    return renderer
  }

  Game.prototype.addStats = function() {
    stats = new Stats()
    stats.domElement.style.position  = 'absolute'
    stats.domElement.style.bottom  = '0px'
    document.body.appendChild( stats.domElement )
  }

  Game.prototype.addLights = function(scene) {
    var ambientLight, directionalLight
    ambientLight = new THREE.AmbientLight(0xaaaaaa)
    scene.add(ambientLight)
    var light	= new THREE.DirectionalLight( 0xffffff )
    light.position.set( Math.random(), Math.random(), Math.random() ).normalize()
    scene.add( light )
  };

  Game.prototype.currentMesh = function() {
    var cid = game.chunker.chunkAtPosition(game.controls.yawObject.position).join('|')
    return game.chunker.meshes[cid]
  }

  Game.prototype.cameraRotation = function() {
    var xAngle = this.controls.pitchObject.rotation.x
    var yAngle = this.controls.yawObject.rotation.y
    return {x: xAngle, y: yAngle}
  }

  Game.prototype.getCollisions = function(position) {
    var self = this
    var p = position.clone()
    var w = self.cubeSize / 4 // width of player cube
    var h = self.cubeSize // height of player cube

    var vertices = {
      bottom: [
        new THREE.Vector3(p.x - w, p.y - h, p.z - w),
        new THREE.Vector3(p.x - w, p.y - h, p.z + w),
        new THREE.Vector3(p.x + w, p.y - h, p.z - w),
        new THREE.Vector3(p.x + w, p.y - h, p.z + w)
      ],
      middle: [
        new THREE.Vector3(p.x - w, p.y, p.z - w),
        new THREE.Vector3(p.x - w, p.y, p.z + w),
        new THREE.Vector3(p.x + w, p.y, p.z - w),
        new THREE.Vector3(p.x + w, p.y, p.z + w)
      ],
      top: [
        new THREE.Vector3(p.x - w, p.y + h, p.z - w),
        new THREE.Vector3(p.x - w, p.y + h, p.z + w),
        new THREE.Vector3(p.x + w, p.y + h, p.z - w),
        new THREE.Vector3(p.x + w, p.y + h, p.z + w)
      ],
    }

    return {
      bottom: vertices.bottom.map(check).filter(Boolean),
      middle: vertices.middle.map(check).filter(Boolean),
      top: vertices.top.map(check).filter(Boolean)
    }

    function check(vertex) {
      return self.voxelAtPosition(vertex) && vertex
    }
  }

  Game.prototype.voxelIndex = function(pos) {
    var size = this.voxelSource.chunkSize
    var x = (size + Math.floor(pos.x / this.cubeSize)) % size
    var y = (size + Math.floor(pos.y / this.cubeSize)) % size
    var z = (size + Math.floor(pos.z / this.cubeSize)) % size
    var vidx = x + y*size + z*size*size
    return vidx
  }

  Game.prototype.voxelAtPosition = function(pos, val) {
    var ckey = this.chunker.chunkAtPosition(pos).join('|')
    var chunk = this.chunker.chunks[ckey]
    if (!chunk) return false
    var vidx = this.voxelIndex(pos)
    if (!vidx) return false
    if (typeof val !== 'undefined') {
      chunk.voxels[vidx] = val
    }
    var v = chunk.voxels[vidx]
    return v
  }

  Game.prototype.tick = function() {
    var self = this
    requestAnimationFrame( this.tick.bind(this) )
    var dt = Date.now() - this.time
    if (!this.time) dt = 1
    var cam = this.camera.position

    this.controls.update(dt, function (pos, velocity) {
      var collisions = self.getCollisions(game.controls.yawObject.position)

      if (collisions.middle.length) {
        game.controls.yawObject.translateX(-velocity.x)
        game.controls.yawObject.translateZ(-velocity.z)
        velocity.x *= -1
        velocity.z *= -1
      }

      if (collisions.bottom.length) {
        this.gravityEnabled = false
        velocity.y = Math.max(0, velocity.y)
      }
      else {
        this.gravityEnabled = true
      }
    })

    this.renderer.render(this.scene, this.camera)
    stats.update()
    this.time = Date.now()
  }

  return Game

})()
;
<|endoftext|>


<commit_before>import _ from 'lodash';

export class UpdateReducer {
  reduce(json, state) {
    if (json.providerStatus) {
      this.reduceProviderStatus(json.providerStatus, state);
    }
    if (json.checkPayee) {
      console.log('update', json);
      this.reduceCheckPayee(json.checkPayee, state);
    }
    if (json["change-provider"]) {
      this.reduceChangeProvider(json["change-provider"], state);
    }
    if (json["change-wallet"]) {
      this.changeWallet(json["change-wallet"], state);
    }
    if (json.psbt) {
      this.reducePsbt(json.psbt, state);
    }
    if (json["btc-state"]) {
      this.reduceBtcState(json["btc-state"], state);
    }
    if (json["new-tx"]) {
      this.reduceNewTx(json["new-tx"], state);
    }
    if (json["cancel-tx"]) {
      this.reduceCancelTx(json["cancel-tx"], state);
    }
    if (json.address) {
      this.reduceAddress(json.address, state);
    }
  }

  reduceProviderStatus(json, state) {
    state.providerPerms[json.provider] = json.permitted;
  }

  reduceCheckPayee(json, state) {
    state.shipWallets[json.payee] = json.hasWallet;
  }

  reduceChangeProvider(json, state) {
    state.provider = json;
  }

  reduceChangeWallet(json, state) {
    state.wallet = json;
  }

  reducePsbt(json, state) {
    state.psbt = json;
  }

  reduceBtcState(json, state) {
    state.btcState = json;
  }

  reduceNewTx(json, state) {
    let old = _.findIndex(state.history, (h) => {
      if (!h) return false;
      return ( h.txid.dat === json.txid.dat &&
               h.txid.wid === json.txid.wid );
    });
    if (old !== -1) {
      delete state.history[old];
    }
    if (json.recvd === null) {
      state.history.unshift(json);
    }
    // we expect history to have null recvd values first, and the rest in
    // descending order
    let insertionIndex = _.findIndex(state.history, (h) => {
      if (!h) return false;
      return ((h.recvd < json.recvd) && (h.recvd !== null));
    });
    state.history.splice(insertionIndex, 0, json);
  }

  reduceCancelTx(json, state) {
    let entryIndex = _.findIndex(state.history, (h) => {
      return ((json.wid === h.txid.wid) && (json.dat === h.txid.dat));
    });
    state.history[entryIndex].failure = true;
  }

  reduceAddress(json, state) {
    state.address = json;
  }
}
<commit_msg>btc: fix transaction ordering<commit_after>import _ from 'lodash';

export class UpdateReducer {
  reduce(json, state) {
    if (json.providerStatus) {
      this.reduceProviderStatus(json.providerStatus, state);
    }
    if (json.checkPayee) {
      console.log('update', json);
      this.reduceCheckPayee(json.checkPayee, state);
    }
    if (json["change-provider"]) {
      this.reduceChangeProvider(json["change-provider"], state);
    }
    if (json["change-wallet"]) {
      this.changeWallet(json["change-wallet"], state);
    }
    if (json.psbt) {
      this.reducePsbt(json.psbt, state);
    }
    if (json["btc-state"]) {
      this.reduceBtcState(json["btc-state"], state);
    }
    if (json["new-tx"]) {
      this.reduceNewTx(json["new-tx"], state);
    }
    if (json["cancel-tx"]) {
      this.reduceCancelTx(json["cancel-tx"], state);
    }
    if (json.address) {
      this.reduceAddress(json.address, state);
    }
  }

  reduceProviderStatus(json, state) {
    state.providerPerms[json.provider] = json.permitted;
  }

  reduceCheckPayee(json, state) {
    state.shipWallets[json.payee] = json.hasWallet;
  }

  reduceChangeProvider(json, state) {
    state.provider = json;
  }

  reduceChangeWallet(json, state) {
    state.wallet = json;
  }

  reducePsbt(json, state) {
    state.psbt = json;
  }

  reduceBtcState(json, state) {
    state.btcState = json;
  }

  reduceNewTx(json, state) {
    let old = _.findIndex(state.history, (h) => {
      return ( h.txid.dat === json.txid.dat &&
               h.txid.wid === json.txid.wid );
    });
    if (old !== -1) {
      delete state.history.splice(old, 1);
    }
    if (json.recvd === null) {
      state.history.unshift(json);
    } else {
      // we expect history to have null recvd values first, and the rest in
      // descending order
      let insertionIndex = _.findIndex(state.history, (h) => {
        return ((h.recvd < json.recvd) && (h.recvd !== null));
      });
      state.history.splice(insertionIndex, 0, json);
    }
  }

  reduceCancelTx(json, state) {
    let entryIndex = _.findIndex(state.history, (h) => {
      return ((json.wid === h.txid.wid) && (json.dat === h.txid.dat));
    });
    state.history[entryIndex].failure = true;
  }

  reduceAddress(json, state) {
    state.address = json;
  }
}
<|endoftext|>


<commit_before>var fs = require('fs');
var pathLib = require('path');

var through = require('through');

var nativeNodeModules = ["fs", "path", "require", "exports", "module"];

module.exports = function(mains, opts) {
    if (!Array.isArray(mains)) mains = [mains].filter(Boolean);

    opts = opts || Object.create(null);
    opts.modules = Object.create(null); // {id, path, contents, deps}

    var cache = opts.cache;
    if (cache)
        cache.files = cache.files || Object.create(null);

    if (!opts.ignore)
        opts.ignore = [];
    else
        opts.ignore = opts.ignore.reduce(function(map, ignore) {
            map[ignore] = true;
            return map;
        }, {});

    if (opts.debug)
        opts.transforms = [wrapUMD, debugSrc];

    if (!opts.transforms)
        opts.transforms = [];

    opts.transforms.push(removeLicenceComments, wrapUMD);

    if (opts.pathConfig) {
        opts.paths = opts.paths || opts.pathConfig.paths;
        opts.root = opts.root || opts.pathConfig.root;
        opts.packages = opts.packages || opts.pathConfig.packages;
        opts.pathMap = opts.pathMap || opts.pathConfig.pathMap;
    }

    var root = opts.root || "";
    var paths = opts.paths || {};
    var pathMap = opts.pathMap;
    opts.packages && opts.packages.forEach(function(pkg) {
        paths[pkg.name] = pkg;
    });

    function idToPath(mod, cb) {
        if (!mod.id && mod.path)
            return cb(null, mod.path);
        var id = mod.id;

        if (id.indexOf("!") != -1) {
            var chunks = id.split("!");
            id = chunks[1];
            mod.loaderModule = chunks[0];
        }

        id = resolveModuleId(id, paths);
        if (pathMap)
            id = resolveModulePath(id, pathMap);
        if (!mod.loaderModule && !/\.js$/.test(id))
            id += ".js";
        cb(null, id);
    }

    function readModule(mod, cb) {
        if (typeof mod == "string")
            mod = {id: mod};

        var id = mod.id;
        if (opts.modules[id]) {
            return cb(null, null);
        }

        if (opts.ignore[id]) {
            ignoreDep(mod);
            return cb();
        }

        opts.modules[id] = mod;

        idToPath(mod, function(err, path) {
            var filepath = absolutePath(root, path);
            mod.path = path;
            mod.file = filepath;

            if (cache && cache.files[mod.file] != undefined) {
                return setModuleSource(mod, cache.files[mod.file], cb);
            }

            fs.readFile(filepath, 'utf8', function (err, src) {
                if (err)  {
                    if (err.code == 'ENOENT' || err.code == "ENOTDIR") {
                        ignoreDep(mod);
                        cb();
                        return;
                    }
                    if (err.code == 'EMFILE') {
                        opts.modules[id] = null;
                        wait(err, mod, cb);
                        return;
                    }
                    return output.emit('error', err);
                }
                setModuleSource(mod, src, cb);
            });
        });
    }

    function setModuleSource(mod, src, cb) {
        if (cache)
            cache.files[mod.file] = src;
        mod.source = src;
        // todo: support loaders other than text?
        if (!mod.noRequire && !mod.literal && !mod.loaderModule && !mod.noDeps) {
            mod.deps = getDeps(src, mod.id);
            // console.log(mod.id, mod.deps)
            mod.deps.forEach(function(dep) {
                addToQueue(dep, mod);
            });
        }
        cb(null, mod);
    }

    function ignoreDep(mod) {
        var parent = mod.parent || {};
        if (nativeNodeModules[mod.id] === -1) {
            console.log("file '" + mod.file + "' doesn't exisit");
            console.log("ignoring dependency '" + mod.id + "' of '" + parent.id + "'");
        }
        if (!parent.ignoredDeps)
            parent.ignoredDeps = [];
        parent.ignoredDeps.push(mod);
    }

    var output = through();

    var pending = [];
    var active = 0;
    var maxActive = 100;
    var waitT = 0, timer;

    function addToQueue(id, parent) {
        var mod = typeof id == "string"
            ? {id: id, parent: parent}
            : id;
        pending.push(mod);
    }

    function wait(err, mod) {
        active--;
        pending.push(mod);
        if (active > 0) {
            if (active > 2 && active < maxActive)
                maxActive = active;
        } else if (waitT < 5000) {
            if (!timer) {
                waitT = 1.5 * waitT + 1 +0.001 * waitT * waitT;
                timer = setTimeout(function() {
                    timer = null;
                    takeFromQueue();
                    if (active)
                        waitT = 0;
                }, waitT);
            }
        } else {
            output.emit('error', err);
        }
    }

    function takeFromQueue() {
        while (active < maxActive) {
            var mod = pending.pop();
            if (!mod)
                break;
            active++;
            readModule(mod, onModuleReady);
        }
    }

    function onModuleReady(err, module) {
        active--;
        // console.log("pending", pending)
        if (module && module.source != undefined) {
            applyTransforms(module);
            output.queue(module);
        } else if (module) {
            module.parent = null;
            console.dir(module);
        }

        if (pending.length || active)
            takeFromQueue();
        else
            end();
    }

    function end() {
        opts._createDepMap && fs.writeFileSync("dep_map.js", JSON.stringify(opts.modules, function(key, val) {
            if (key == "source")
                return val && val[0];
            if (key == "parent")
                return val && val.id;
            return val;
        }, 4));
        process.nextTick(function() {
            output.emit("end");
        });
    }

    function applyTransforms(module) {
        if (!module.source || module.literal)
            return; // console.log(module)
        var transforms = module.transforms || opts.transforms;
        transforms.forEach(function(transform) {
            transform(module);
        });
    }

    mains.forEach(function(dep) {
        addToQueue(dep, {id: "#root"});
    });
    takeFromQueue();

    return output;
};

function normalizeModule(parentId, moduleName) {
    // normalize plugin requires
    if (moduleName.indexOf("!") !== -1) {
        var chunks = moduleName.split("!");
        return normalizeModule(parentId, chunks[0]) + "!" + normalizeModule(parentId, chunks[1]);
    }
    // normalize relative requires
    if (moduleName.charAt(0) == ".") {
        var base = parentId.split("/").slice(0, -1).join("/");
        moduleName = (base || parentId) + "/" + moduleName;

        while (moduleName.indexOf(".") !== -1 && previous != moduleName) {
            var previous = moduleName;
            moduleName = moduleName.replace(/\/\.\//, "/").replace(/[^\/]+\/\.\.\//, "");
        }
    }
    return moduleName;
}
function getSubmodules(src, name) {
    var m = src.replace(/^\s*\/\/.+|^\s*\/\*[\s\S]*?\*\//gm, "")
        .match(/require\(\[([^\]]+)\]/gm);
    if (!m)
        return [];
    var deps = [];
    m.forEach(function(dep) {
        var re = /["']([^"']+?)["']/g;
        var m;
        while ((m = re.exec(dep))) {
            deps.push(normalizeModule(name, m[1]));
        }
    });
    // console.log(deps);
    return deps;
}
function getReqDeps(src, name) {
    var m = src.replace(/^\s*\/\/.+|^\s*\/\*[\s\S]*?\*\//gm, "")
        .match(/require\s*\(\s*(["'][^"'\n\r]+["'])\s*\)/gm);
    if (!m)
        return [];

    return m.map(function(r) {
        r = r.match(/["']([^"']+?)["']/)[1];
        r = normalizeModule(name, r);
        return r;
    });
}
function getAmdDeps(src, name) {
    var m = src.match(/define\(\[[^\]]+\]/gm);
    if (!m)
        return [];

    var deps = [];
    m.forEach(function(dep) {
        var re = /["']([^"']+?)["']/g;
        var m;
        while ((m = re.exec(dep))) {
            deps.push(normalizeModule(name, m[1]));
        }
    });
    // console.log(deps);
    return deps;
}
function getDeps(src, name) {
    return getReqDeps(src, name).concat(getAmdDeps(src, name));
}
function resolveModuleId(id, paths) {
    var chunks = id.split("/");

    var alias = paths[chunks[0]];
    if (typeof alias == "string") {
        chunks[0] = alias;
    } else if (alias) {
        chunks[0] = alias.location;
        if (chunks.length == 1)
            chunks.push(alias.main || alias.name);
    } else if (alias === false) {
        return "";
    }

    return chunks.join("/");
}
function resolveModulePath(id, pathMap) {
    var testPath = id, tail = "";
    if (testPath[0] != "/")
        testPath = "/" + testPath;
    while (testPath) {
        if (pathMap[testPath]) {
            return pathMap[testPath] + (tail && "/" + tail);
        }
        var i = testPath.lastIndexOf("/");
        if (i === -1) break;
        tail = testPath.substr(i + 1) + (tail && "/" + tail);
        testPath = testPath.slice(0, i);
    }
    return id;
}

function absolutePath(root, relative) {
    // console.log(root, relative)
    if (relative[0] == "/" || relative[1] == ":")
        return relative;
    return pathLib.join(root, relative);
}

// src transformations
function removeUseStrict(module) {
    module.source = module.source.replace(/['"]use strict['"];/g, "");
}

function removeLicenceComments(module) {
    module.source = module.source.replace(/(?:(;)|\n|^)\s*\/\*[\d\D]*?\*\/|(\n|^)\s*\/\/.*/g, "$1");
}
function removeLicenceCommentsKeepLines(module) {
    return module.source = module.source.replace(/(?:(;)|\n|^)\s*\/\*[\d\D]*?\*\/|\n\s*\/\/.*/g, function(cm, start) {
        return (start||"") + cm.replace(/.+/g, "");
    });
}

function wrapUMD(module) {
    if (module.loaderModule || module.noRequire)
        return;
    var firstDefineCall = module.source.match(/define\([^)]*/);
    if (firstDefineCall) {
        // check if it is a normal define or some crazy umd trick
        if (/define\(function\s*\(/.test(firstDefineCall[0]))
            return;
        if (/define\(\[[^\]]*\],\s*function\(/.test(firstDefineCall[0]))
            return;
    }
    console.log("wrapping module " + module.id);

    module.source = 'define(function(require, exports, module) {\n'
        + 'var _ = {require: require, exports: exports, module: module};\n'
        + 'exports = undefined; module = undefined;\n'
        + 'function define(name, deps, m) {\n'
        + '    if (typeof name == "function") {\n'
        + '        m = name; deps = ["require", "exports", "module"]; name = _.module.id\n'
        + '    }\n'
        + '    if (typeof name == "object") {\n'
        + '        m = deps; deps = name; name = _.module.id\n'
        + '    }\n'
        + '    if (typeof deps == "function") {\n'
        + '        m = deps; deps = [];\n'
        + '    }\n'
        + '   var ret = m ? m.apply(_.module, deps.map(function(n){return _[n] || require(n)})) : deps\n'
        + '   if (ret) _.module.exports = ret;\n'
        + '}\n'
        + 'define.amd = true;'
        +  module.source
    + '});';

}

function debugSrc(module) {
    if (module.loaderModule)
        return;
    var url = "http://localhost:8181/" + module.id;
    module.source = "try{eval(" + quote(module.source + "\n//@ sourceURL=" + url) + ");}catch(e){throw e.message + url}";
}

function quote(str) {
    return "'"
        + str.replace(/[\\']/g, "\\$&").replace(/\n/g, "\\n")
        + "'";
}

module.exports.resolveModulePath = resolveModulePath;<commit_msg>cleanup<commit_after>var fs = require('fs');
var pathLib = require('path');

var through = require('through');

var nativeNodeModules = ["fs", "path", "require", "exports", "module"];

module.exports = function(mains, opts) {
    if (!Array.isArray(mains)) mains = [mains].filter(Boolean);

    opts = opts || Object.create(null);
    opts.modules = Object.create(null); // {id, path, contents, deps}

    var cache = opts.cache;
    if (cache)
        cache.files = cache.files || Object.create(null);

    if (!opts.ignore)
        opts.ignore = [];
    else
        opts.ignore = opts.ignore.reduce(function(map, ignore) {
            map[ignore] = true;
            return map;
        }, {});

    if (opts.debug)
        opts.transforms = [wrapUMD, debugSrc];

    if (!opts.transforms)
        opts.transforms = [];

    opts.transforms.push(removeLicenceComments, wrapUMD);

    if (opts.pathConfig) {
        opts.paths = opts.paths || opts.pathConfig.paths;
        opts.root = opts.root || opts.pathConfig.root;
        opts.packages = opts.packages || opts.pathConfig.packages;
        opts.pathMap = opts.pathMap || opts.pathConfig.pathMap;
    }

    var root = opts.root || "";
    var paths = opts.paths || {};
    var pathMap = opts.pathMap;
    opts.packages && opts.packages.forEach(function(pkg) {
        paths[pkg.name] = pkg;
    });

    function idToPath(mod, cb) {
        if (!mod.id && mod.path)
            return cb(null, mod.path);
        var id = mod.id;

        if (id.indexOf("!") != -1) {
            var chunks = id.split("!");
            id = chunks[1];
            mod.loaderModule = chunks[0];
        }

        id = resolveModuleId(id, paths);
        if (pathMap)
            id = resolveModulePath(id, pathMap);
        if (!mod.loaderModule && !/\.js$/.test(id))
            id += ".js";
        cb(null, id);
    }

    function readModule(mod, cb) {
        if (typeof mod == "string")
            mod = {id: mod};

        var id = mod.id;
        if (opts.modules[id]) {
            return cb(null, null);
        }

        if (opts.ignore[id]) {
            ignoreDep(mod);
            return cb();
        }

        opts.modules[id] = mod;

        idToPath(mod, function(err, path) {
            var filepath = absolutePath(root, path);
            mod.path = path;
            mod.file = filepath;

            if (cache && cache.files[mod.file] != undefined) {
                return setModuleSource(mod, cache.files[mod.file], cb);
            }

            fs.readFile(filepath, 'utf8', function (err, src) {
                if (err)  {
                    if (err.code == 'ENOENT' || err.code == "ENOTDIR") {
                        ignoreDep(mod);
                        cb();
                        return;
                    }
                    if (err.code == 'EMFILE') {
                        opts.modules[id] = null;
                        wait(err, mod, cb);
                        return;
                    }
                    return output.emit('error', err);
                }
                setModuleSource(mod, src, cb);
            });
        });
    }

    function setModuleSource(mod, src, cb) {
        if (cache)
            cache.files[mod.file] = src;
        mod.source = src;
        // todo: support loaders other than text?
        if (!mod.noRequire && !mod.literal && !mod.loaderModule && !mod.noDeps) {
            mod.deps = getDeps(src, mod.id);
            // console.log(mod.id, mod.deps)
            mod.deps.forEach(function(dep) {
                addToQueue(dep, mod);
            });
        }
        cb(null, mod);
    }

    function ignoreDep(mod) {
        var parent = mod.parent || {};
        if (nativeNodeModules[mod.id] === -1) {
            console.log("file '" + mod.file + "' doesn't exisit");
            console.log("ignoring dependency '" + mod.id + "' of '" + parent.id + "'");
        }
        if (!parent.ignoredDeps)
            parent.ignoredDeps = [];
        parent.ignoredDeps.push(mod);
    }

    var output = through();

    var pending = [];
    var active = 0;
    var maxActive = 100;
    var waitT = 0, timer;

    function addToQueue(id, parent) {
        var mod = typeof id == "string"
            ? {id: id, parent: parent}
            : id;
        pending.push(mod);
    }

    function wait(err, mod) {
        active--;
        pending.push(mod);
        if (active > 0) {
            if (active > 2 && active < maxActive)
                maxActive = active;
        } else if (waitT < 5000) {
            if (!timer) {
                waitT = 1.5 * waitT + 1 +0.001 * waitT * waitT;
                timer = setTimeout(function() {
                    timer = null;
                    takeFromQueue();
                    if (active)
                        waitT = 0;
                }, waitT);
            }
        } else {
            output.emit('error', err);
        }
    }

    function takeFromQueue() {
        while (active < maxActive) {
            var mod = pending.pop();
            if (!mod)
                break;
            active++;
            readModule(mod, onModuleReady);
        }
    }

    function onModuleReady(err, module) {
        active--;
        // console.log("pending", pending)
        if (module && module.source != undefined) {
            applyTransforms(module);
            output.queue(module);
        } else if (module) {
            module.parent = null;
            console.dir(module);
        }

        if (pending.length || active)
            takeFromQueue();
        else
            end();
    }

    function end() {
        opts._createDepMap && fs.writeFileSync("dep_map.js", JSON.stringify(opts.modules, function(key, val) {
            if (key == "source")
                return val && val[0];
            if (key == "parent")
                return val && val.id;
            return val;
        }, 4));
        process.nextTick(function() {
            output.emit("end");
        });
    }

    function applyTransforms(module) {
        if (!module.source || module.literal)
            return; // console.log(module)
        var transforms = module.transforms || opts.transforms;
        transforms.forEach(function(transform) {
            transform(module);
        });
    }

    mains.forEach(function(dep) {
        addToQueue(dep, {id: "#root"});
    });
    takeFromQueue();

    return output;
};

function normalizeModule(parentId, moduleName) {
    // normalize plugin requires
    if (moduleName.indexOf("!") !== -1) {
        var chunks = moduleName.split("!");
        return normalizeModule(parentId, chunks[0]) + "!" + normalizeModule(parentId, chunks[1]);
    }
    // normalize relative requires
    if (moduleName.charAt(0) == ".") {
        var base = parentId.split("/").slice(0, -1).join("/");
        moduleName = (base || parentId) + "/" + moduleName;

        while (moduleName.indexOf(".") !== -1 && previous != moduleName) {
            var previous = moduleName;
            moduleName = moduleName.replace(/\/\.\//, "/").replace(/[^\/]+\/\.\.\//, "");
        }
    }
    return moduleName;
}
function getSubmodules(src, name) {
    var m = src.replace(/^\s*\/\/.+|^\s*\/\*[\s\S]*?\*\//gm, "")
        .match(/require\(\[([^\]]+)\]/gm);
    if (!m)
        return [];
    var deps = [];
    m.forEach(function(dep) {
        var re = /["']([^"']+?)["']/g;
        var m;
        while ((m = re.exec(dep))) {
            deps.push(normalizeModule(name, m[1]));
        }
    });
    // console.log(deps);
    return deps;
}
function getReqDeps(src, name) {
    var m = src.replace(/^\s*\/\/.+|^\s*\/\*[\s\S]*?\*\//gm, "")
        .match(/require\s*\(\s*(["'][^"'\n\r]+["'])\s*\)/gm);
    if (!m)
        return [];

    return m.map(function(r) {
        r = r.match(/["']([^"']+?)["']/)[1];
        r = normalizeModule(name, r);
        return r;
    });
}
function getAmdDeps(src, name) {
    var m = src.match(/define\(\[[^\]]+\]/gm);
    if (!m)
        return [];

    var deps = [];
    m.forEach(function(dep) {
        var re = /["']([^"']+?)["']/g;
        var m;
        while ((m = re.exec(dep))) {
            deps.push(normalizeModule(name, m[1]));
        }
    });
    // console.log(deps);
    return deps;
}
function getDeps(src, name) {
    return getReqDeps(src, name).concat(getAmdDeps(src, name));
}
function resolveModuleId(id, paths) {
    var chunks = id.split("/");

    var alias = paths[chunks[0]];
    if (typeof alias == "string") {
        chunks[0] = alias;
    } else if (alias) {
        chunks[0] = alias.location;
        if (chunks.length == 1)
            chunks.push(alias.main || alias.name);
    } else if (alias === false) {
        return "";
    }

    return chunks.join("/");
}
function resolveModulePath(id, pathMap) {
    var testPath = id, tail = "";
    if (testPath[0] != "/")
        testPath = "/" + testPath;
    while (testPath) {
        if (pathMap[testPath]) {
            return pathMap[testPath] + tail;
        }
        var i = testPath.lastIndexOf("/");
        if (i === -1) break;
        tail = testPath.substr(i) + tail;
        testPath = testPath.slice(0, i);
    }
    return id;
}

function absolutePath(root, relative) {
    // console.log(root, relative)
    if (relative[0] == "/" || relative[1] == ":")
        return relative;
    return pathLib.join(root, relative);
}

// src transformations
function removeUseStrict(module) {
    module.source = module.source.replace(/['"]use strict['"];/g, "");
}

function removeLicenceComments(module) {
    module.source = module.source.replace(/(?:(;)|\n|^)\s*\/\*[\d\D]*?\*\/|(\n|^)\s*\/\/.*/g, "$1");
}
function removeLicenceCommentsKeepLines(module) {
    return module.source = module.source.replace(/(?:(;)|\n|^)\s*\/\*[\d\D]*?\*\/|\n\s*\/\/.*/g, function(cm, start) {
        return (start||"") + cm.replace(/.+/g, "");
    });
}

function wrapUMD(module) {
    if (module.loaderModule || module.noRequire)
        return;
    var firstDefineCall = module.source.match(/define\([^)]*/);
    if (firstDefineCall) {
        // check if it is a normal define or some crazy umd trick
        if (/define\(function\s*\(/.test(firstDefineCall[0]))
            return;
        if (/define\(\[[^\]]*\],\s*function\(/.test(firstDefineCall[0]))
            return;
    }
    console.log("wrapping module " + module.id);

    module.source = 'define(function(require, exports, module) {\n'
        + 'var _ = {require: require, exports: exports, module: module};\n'
        + 'exports = undefined; module = undefined;\n'
        + 'function define(name, deps, m) {\n'
        + '    if (typeof name == "function") {\n'
        + '        m = name; deps = ["require", "exports", "module"]; name = _.module.id\n'
        + '    }\n'
        + '    if (typeof name == "object") {\n'
        + '        m = deps; deps = name; name = _.module.id\n'
        + '    }\n'
        + '    if (typeof deps == "function") {\n'
        + '        m = deps; deps = [];\n'
        + '    }\n'
        + '    if (typeof m != "function") {\n'
        + '        deps = m; m = null;\n'
        + '    }\n'
        + '   var ret = m ? m.apply(_.module, deps.map(function(n){return _[n] || require(n)})) : deps\n'
        + '   if (ret) _.module.exports = ret;\n'
        + '}\n'
        + 'define.amd = true;'
        +  module.source
    + '});';
}

function debugSrc(module) {
    if (module.loaderModule)
        return;
    var url = "http://localhost:8181/" + module.id;
    module.source = "try{eval(" + quote(module.source + "\n//@ sourceURL=" + url) + ");}catch(e){throw e.message + url}";
}

function quote(str) {
    return "'"
        + str.replace(/[\\']/g, "\\$&").replace(/\n/g, "\\n")
        + "'";
}

module.exports.resolveModulePath = resolveModulePath;<|endoftext|>


<commit_before>
var ryver = require('ryver');
var marked = require('marked');

var eventEC = ryver.eventEC;

eventEC.onCollect( 'filter', function( cb ){

  var f = function( fileData, cb ){

    // This filter will only work on text files (of any kind)
    if( fileData.system.mimetype.split('/')[0] !== 'text'){
      ryver.log( "File ignored as mime type is not 'text'" );
      return cb( null, fileData);
    }

    if( fileData.system.fileExt !== '.md' && fileData.system.fileExt !== '.markdown'){
      ryver.log( "File ignored as extension isn't .md or .markdown: ", fileData.system.fileExt );
      return cb( null, fileData )
    }

    marked.setOptions({
      renderer: new marked.Renderer(),
      gfm: true,
      tables: true,
      breaks: false,
      pedantic: false,
      sanitize: true,
      smartLists: true,
      smartypants: true
    });

    fileData.contents = marked( fileData.contents, fileData );

    ryver.log("Changing file extension and mime type to html" );
    ryver.setSystemData( fileData.system, 'fileExt', '.html' );
    ryver.setSystemData( fileData.system, 'mimetype', 'text/html' );

    // All done.
    cb( null, fileData );
  }

  // Return the function just defined as the filter
  cb( null, { name: 'markup-markdown', executor: f } );
});
<commit_msg>Turned off sanitization from Marked<commit_after>
var ryver = require('ryver');
var marked = require('marked');
//var markdown = require('markdown').markdown;

var eventEC = ryver.eventEC;

eventEC.onCollect( 'filter', function( cb ){

  var f = function( fileData, cb ){

    // This filter will only work on text files (of any kind)
    if( fileData.system.mimetype.split('/')[0] !== 'text'){
      ryver.log( "File ignored as mime type is not 'text'" );
      return cb( null, fileData);
    }

    if( fileData.system.fileExt !== '.md' && fileData.system.fileExt !== '.markdown'){
      ryver.log( "File ignored as extension isn't .md or .markdown: ", fileData.system.fileExt );
      return cb( null, fileData )
    }

    marked.setOptions({
      //renderer: new marked.Renderer(),
      gfm: true,
      tables: true,
      breaks: false,
      pedantic: false,
      sanitize: false,
      smartLists: true,
      smartypants: true
    });

    fileData.contents = marked( fileData.contents );
    //fileData.contents = markdown.toHTML( fileData.contents );

    ryver.log("Changing file extension and mime type to html" );
    ryver.setSystemData( fileData.system, 'fileExt', '.html' );
    ryver.setSystemData( fileData.system, 'mimetype', 'text/html' );

    // All done.
    cb( null, fileData );
  }

  // Return the function just defined as the filter
  cb( null, { name: 'markup-markdown', executor: f } );
});
<|endoftext|>


<commit_before>// URL: https://beta.observablehq.com/@randomfractals/chicago-homicides
// Title: Chicago Homicides
// Author: Taras Novak (@randomfractals)
// Version: 52
// Runtime version: 1

const m0 = {
  id: "2c207c68a127a60d@52",
  variables: [
    {
      inputs: ["md"],
      value: (function(md){return(
md`# Chicago Homicides`
)})
    },
    {
      inputs: ["md"],
      value: (function(md){return(
md `Fork this notebook and graph it here!

I'd like to see what other dataViz pros would do plotting Chicago homicides.

Get creative! Some inspirational notebooks I've done parsing this gruesome dataset:

[Chicago Crimes](https://beta.observablehq.com/search?query=Chicago%20Crimes)

I'll drop the latest extended homicides data from 2001 through 8-8-20218 shortly`
)})
    },
    {
      inputs: ["md"],
      value: (function(md){return(
md `## Crime Data`
)})
    },
    {
      name: "dataUrl",
      value: (function(){return(
'https://raw.githubusercontent.com/RandomFractals/ChicagoCrimes/master/data/2018/chicago-crimes-2018.arrow'
)})
    },
    {
      name: "dataTable",
      inputs: ["loadData","dataUrl","arrow"],
      value: (function(loadData,dataUrl,arrow){return(
loadData(dataUrl).then(buffer => arrow.Table.from(new Uint8Array(buffer)))
)})
    },
    {
      name: "fields",
      inputs: ["dataTable"],
      value: (function(dataTable){return(
dataTable.schema.fields.map(f => f.name)
)})
    },
    {
      name: "crimeData",
      inputs: ["groupByField","dataTable"],
      value: (function(groupByField,dataTable){return(
groupByField(dataTable, 'PrimaryType')
)})
    },
    {
      name: "homicides",
      inputs: ["groupByDay","crimeData"],
      value: (function(groupByDay,crimeData){return(
groupByDay(crimeData['HOMICIDE'], 'HOMICIDE')
)})
    },
    {
      from: "@randomfractals/apache-arrow",
      name: "loadData",
      remote: "loadData"
    },
    {
      from: "@randomfractals/apache-arrow",
      name: "toDate",
      remote: "toDate"
    },
    {
      from: "@randomfractals/chicago-crimes-by-type",
      name: "groupByField",
      remote: "groupByField"
    },
    {
      from: "@randomfractals/chicago-crimes-ridgeline",
      name: "groupByDay",
      remote: "groupByDay"
    },
    {
      name: "arrow",
      inputs: ["require"],
      value: (function(require){return(
require('apache-arrow')
)})
    }
  ]
};

const m1 = {
  id: "@randomfractals/apache-arrow",
  variables: [
    {
      name: "loadData",
      value: (function(){return(
async function loadData(dataUrl){
  const response = await fetch(dataUrl);
  return await response.arrayBuffer();
}
)})
    },
    {
      name: "toDate",
      value: (function(){return(
function toDate(timestamp) {
  // Appache Arrow Timestamp is a 64-bit int of milliseconds since the epoch,
  // represented as two 32-bit ints in JS to preserve precision.
  // The fist number is the "low" int and the second number is the "high" int.
  return new Date((timestamp[1] * Math.pow(2, 32) + timestamp[0])/1000);
}
)})
    },
    {
      name: "toDate",
      value: (function(){return(
function toDate(timestamp) {
  // Appache Arrow Timestamp is a 64-bit int of milliseconds since the epoch,
  // represented as two 32-bit ints in JS to preserve precision.
  // The fist number is the "low" int and the second number is the "high" int.
  return new Date((timestamp[1] * Math.pow(2, 32) + timestamp[0])/1000);
}
)})
    }
  ]
};

const m2 = {
  id: "@randomfractals/chicago-crimes-by-type",
  variables: [
    {
      name: "groupByField",
      inputs: ["arrow","toDate"],
      value: (function(arrow,toDate){return(
function groupByField(data, groupField) {
  let groupData, date, location, arrested, info, results = {};
  const dateFilter = arrow.predicate.custom(i => {
    const date = toDate(data.getColumn('Date').get(i));
    return (date.getMonth() <= 6); // through June
  }, b => 1);
  data.filter(dateFilter)
  .scan((index) => {
    const groupFieldData = groupData(index);
    const groupArray = results[groupFieldData];
    if (!groupArray) {
      results[groupFieldData] = [];
    }
    const dataRecord = {};
    dataRecord[groupField] = groupFieldData;
    dataRecord['date'] = toDate(date(index));
    dataRecord['location'] = location(index);
    dataRecord['arrested'] = arrested(index);
    dataRecord['info'] = info(index);
    results[groupFieldData].push(dataRecord);
  }, (batch) => {
    groupData = arrow.predicate.col(groupField).bind(batch);
    date = arrow.predicate.col('Date').bind(batch);
    location = arrow.predicate.col('LocationDescription').bind(batch);
    arrested = arrow.predicate.col('Arrest').bind(batch);
    info = arrow.predicate.col('Description').bind(batch);
  });
  return results;
}
)})
    },
    {
      name: "arrow",
      inputs: ["require"],
      value: (function(require){return(
require('apache-arrow')
)})
    },
    {
      from: "@randomfractals/apache-arrow",
      name: "toDate",
      remote: "toDate"
    }
  ]
};

const m3 = {
  id: "@randomfractals/chicago-crimes-ridgeline",
  variables: [
    {
      name: "groupByDay",
      value: (function(){return(
function groupByDay(dataArray, crimeType) {
  let daily = {};
  dataArray.map(data => {
    const day = data.date.toISOString().substring(0, 10); // ISO date string
    if (!daily[day]) {
      daily[day] = [];
    }
    daily[day].push(data);
  });
  return daily;
}
)})
    }
  ]
};

const notebook = {
  id: "2c207c68a127a60d@52",
  modules: [m0,m1,m2,m3]
};

export default notebook;
<commit_msg>switched to 2001 to 2018 homicides csv data load<commit_after>// URL: https://beta.observablehq.com/@randomfractals/chicago-homicides
// Title: Chicago Homicides
// Author: Taras Novak (@randomfractals)
// Version: 93
// Runtime version: 1

const m0 = {
  id: "2c207c68a127a60d@93",
  variables: [
    {
      inputs: ["md"],
      value: (function(md){return(
md`# Chicago Homicides`
)})
    },
    {
      inputs: ["md"],
      value: (function(md){return(
md `**Fork this notebook and graph it here!**

I'd like to see what other dataViz pros would do plotting Chicago homicides.

Get creative! Some inspirational dataViz notebooks parsing this dataset:

[Chicago Crimes](https://beta.observablehq.com/search?query=Chicago%20Crimes)
`
)})
    },
    {
      inputs: ["md"],
      value: (function(md){return(
md `## Homicides Data`
)})
    },
    {
      name: "dataUrl",
      value: (function(){return(
'https://raw.githubusercontent.com/RandomFractals/ChicagoCrimes/master/data/2018/chicago-homicides-2001-2018.csv'
)})
    },
    {
      name: "homicides",
      inputs: ["d3","dataUrl"],
      value: (function(d3,dataUrl){return(
d3.csv(dataUrl)
)})
    },
    {
      name: "d3",
      inputs: ["require"],
      value: (function(require){return(
require('d3')
)})
    }
  ]
};

const notebook = {
  id: "2c207c68a127a60d@93",
  modules: [m0]
};

export default notebook;
<|endoftext|>


<commit_before>/* global Player, Projectile, Zombie, Explosion, ObjectPoolMaker, FlashMessage */

(function () {
  'use strict';

  var Game = {
    init: function () {
      Game.canvas = document.getElementById('game-canvas');
      Game.context = Game.canvas.getContext('2d');

      Game.loadBackground();
      Game.bind();
      Game.reset();
    },

    hasLeveled: function (level) {
      return Game.score > Game.neededScoreForLevel(level + 1);
    },

    neededScoreForLevel: function (level) {
      return Math.floor(Math.pow(level, 3) * 100) + 1000;
    },

    bind: function () {
      document.addEventListener('keydown', function (e) {
        Game.keysDown[e.keyCode] = true;

        // prevent window from scrolling when pressing UP or DOWN or SPACE
        if (e.keyCode === 38 || e.keyCode === 40 || e.keyCode === 32) {
          e.preventDefault();
        }
        if (!Game.isGameOver && e.keyCode === 80) {
          Game.isPaused = !Game.isPaused;
          Game.gamePause();
        }
      }, false);

      document.addEventListener('keyup', function (e) {
        delete Game.keysDown[e.keyCode];

        // prevent window from scrolling when pressing UP or DOWN or SPACE
        if (e.keyCode === 38 || e.keyCode === 40 || e.keyCode === 32) {
          e.preventDefault();
        }
      }, false);

      window.addEventListener('blur', function () {
        Game.keysDown = {};
      }, false);

      document.getElementById('play-again').addEventListener('click', function () {
        Game.reset();
      }, false);
      document.getElementById('return-play').addEventListener('click', function () {
        Game.isPaused = false;
        Game.gamePause();
      }, false);
    },

    reset: function () {
      // Current game difficulty
      Game.difficulty = 0.01;

      // Max difficulty that Game can reach at any given time
      // It represents the chance percentage of spawning a new Zombie
      Game.maxDifficulty = 0.40;

      // How much difficulty increases after its cooldown elapsed
      Game.difficultyIncrement = 0.005;

      // How long it takes (in seconds) to difficulty to increase
      Game.difficultyCooldown = 4;

      // Last time difficulty was increased
      Game.lastDifficultyIncrease = 0;

      // Time elapsed since Game began
      Game.gameTime = 0;

      // Total score from killing zombies
      Game.score = 0;

      // Maps which keys as currently pressed by e.keyCode
      Game.keysDown = {};

      // Last time a projectile was shot by the player
      Game.lastProjectileTime = 0;

      // How long it takes (in ms) for another projectile to be fired
      Game.projectileCooldown = 225;

      // How much projectile speed improves after each level
      Game.projectileCooldownImprove = 25;

      // Maximum projectile speed (less is faster)
      Game.minProjectileCooldown = 100;

      // Define how many levels it takes to increase projectile power by 1
      // (huge difference)
      Game.powerUpProjectileIn = 10;

      // How many pixels Player and Zombies are constrained by vertically/horizontally
      // (this is interesting according to the background image used)
      Game.verticalBoundary = 35;
      Game.horizontalBoundary = 5;

      Game.isPaused = false;

      Game.isGameOver = false;

      Game.player = new Player(
        Game.canvas.width / 2 - Player.width / 2,
        Game.canvas.height / 2 - Player.height / 2
      );

      // Store pool of objects to be reused for each Entity
      Game.zombiePool = new ObjectPoolMaker(Zombie, 100);
      Game.projectilePool = new ObjectPoolMaker(Projectile, 100);
      Game.explosionPool = new ObjectPoolMaker(Explosion, 100);
      Game.flashMessagePool = new ObjectPoolMaker(FlashMessage, 100);

      document.getElementById('game-overlay').style.display = 'none';
      document.getElementById('game-over').style.display = 'none';
      document.getElementById('game-paused').style.display = 'none';
    },

    loadBackground: function () {
      Game.backgroundReady = false;

      Game.backgroundImg = new Image();
      Game.backgroundImg.src = 'public/images/background.png';

      Game.backgroundImg.onload = function () {
        Game.backgroundReady = true;
      };
    },

    update: function (modifier) {
      if (Game.isPaused) {
        return;
      }

      Game.gameTime += modifier;

      Game.handleInput(modifier);
      Game.handleDifficulty();
      Game.spawnZombies();
      Game.updateEntities(modifier);
    },

    handleInput: function (modifier) {
      if (Game.isGameOver) {
        return;
      }

      var now = Date.now();

      // UP
      if (Game.keysDown[38] && Game.player.y > Game.verticalBoundary) {
        Game.player.setY(Game.player.y - (Game.player.speed * modifier));
      }

      // DOWN
      if (Game.keysDown[40] && Game.player.y < Game.canvas.height - Game.verticalBoundary - Player.height) {
        Game.player.setY(Game.player.y + (Game.player.speed * modifier));
      }

      // RIGHT
      if (Game.keysDown[39] && Game.player.x < Game.canvas.width - Game.horizontalBoundary - Player.width) {
        Game.player.setX(Game.player.x + (Game.player.speed * modifier));
      }

      // LEFT
      if (Game.keysDown[37] && Game.player.x > Game.horizontalBoundary) {
        Game.player.setX(Game.player.x - (Game.player.speed * modifier));
      }

      // SPACE - shoot!
      if (Game.keysDown[32]) {
        // prevent spamming projectiles
        if (now - Game.lastProjectileTime > Game.projectileCooldown) {
          Game.projectilePool.create(
            Game.player.x,
            Game.player.y + (Player.height / 2) - (Projectile.height / 2),
            400,
            Math.floor(Game.player.level / Game.powerUpProjectileIn) + 1
          );
          Game.lastProjectileTime = now;
        }
      }
    },

    handleDifficulty: function () {
      // It gets harder as time goes by..
      if (Game.difficulty < Game.maxDifficulty &&
          Game.gameTime - Game.lastDifficultyIncrease > Game.difficultyCooldown) {
        Game.difficulty += Game.difficultyIncrement;
        Game.lastDifficultyIncrease = Game.gameTime;
      }
    },

    spawnZombies: function () {
      // Create some enemies
      if (Math.random() < Game.difficulty) {
        // resets x coordinate
        // randomize new y coordinate (constrained in available map space)
        Game.zombiePool.create(
          Game.canvas.width,
          Math.random() * (Game.canvas.height - Zombie.height - (2 * Game.verticalBoundary)) + Game.verticalBoundary
        );
      }
    },

    updateEntities: function (modifier) {
      Game.updateProjectilesAndKillZombies(modifier);
      Game.updateZombies(modifier);
      Game.updateExplosions();
      Game.updatePlayer();
      Game.updateFlashMessages(modifier);
    },

    updateProjectilesAndKillZombies: function (modifier) {
      var i,
          j,
          zombie,
          projectile;

      // update all projectiles
      for (i = 0; i < Game.projectilePool.size(); i++) {
        projectile = Game.projectilePool.objectPool()[i];

        projectile.setX(projectile.x + (projectile.speed * modifier));

        // delete projectile if out of the scene
        if (projectile.x > Game.canvas.width) {
          Game.projectilePool.destroy(projectile);
          i--;
        }
        else {
          // kill zombies!
          for (j = 0; j < Game.zombiePool.size(); j++) {
            zombie = Game.zombiePool.objectPool()[j];
            if (projectile.isCollided(zombie)) {
              Game.explosionPool.create(zombie.x, zombie.y);

              // hundred points for each zombie!
              Game.score += 100;

              // Decrease projectile power and
              projectile.power--;
              // destroy projectile if it has no more power
              if (projectile.power === 0) {
                Game.projectilePool.destroy(projectile);
                i--;
              }

              Game.flashMessagePool.create(
                '+ 100',
                zombie.x,
                zombie.y,
                500
              );
              Game.zombiePool.destroy(zombie);
              j--;

              break;
            }
          }
        }
      }
    },

    updateZombies: function (modifier) {
      var zombie,
          i,
          now = Date.now();

      // update all enemies
      for (i = 0; i < Game.zombiePool.size(); i++) {
        zombie = Game.zombiePool.objectPool()[i];
        zombie.update(now);
        zombie.setX(zombie.x - (zombie.speed * modifier));

        // delete zombie if out of the scene
        if (zombie.x + Zombie.width < 0) {
          Game.zombiePool.destroy(zombie);
          i--;
        }
      }
    },

    updateExplosions: function () {
      var i,
          explosion;

      for (i = 0; i < Game.explosionPool.size(); ++i) {
        explosion = Game.explosionPool.objectPool()[i];
        explosion.update();
        if (explosion.currentFrame >= Explosion.framesPosition.length - 1) {
          Game.explosionPool.destroy(explosion);
        }
      }
    },

    updatePlayer: function () {
      var zombie,
          i;

      if (!Game.isGameOver) {
        for (i = 0; i < Game.zombiePool.size(); ++i) {
          zombie = Game.zombiePool.objectPool()[i];
          if (zombie.isCollided(Game.player)) {
            Game.gameOver();
            break;
          }
        }
      }

      // Level up!
      if (Game.hasLeveled(Game.player.level)) {
        Game.player.level += 1;
        Game.flashMessagePool.create(
          'Level ' + Game.player.level,
          Game.player.x,
          Game.player.y,
          700,
          '#E2E215',
          '18px'
        );

        // power up ?
        if (Game.player.level % 10 === 0) {
          Game.flashMessagePool.create(
            'Power Up!',
            Game.player.x,
            Game.player.y - Player.height / 2,
            1000,
            '#34FAC3',
            '16px'
          );
        }

        Game.projectileCooldown -= Game.projectileCooldownImprove;
        if (Game.projectileCooldown < Game.minProjectileCooldown) {
          Game.projectileCooldown = Game.minProjectileCooldown;
        }
      }
    },

    updateFlashMessages: function (modifier) {
      var i,
          flashMessage,
          now = Date.now();

      for (i = 0; i < Game.flashMessagePool.size(); ++i) {
        flashMessage = Game.flashMessagePool.objectPool()[i];
        flashMessage.y -= modifier * 10;
        if (now - flashMessage.createdAt > flashMessage.duration) {
          Game.flashMessagePool.destroy(flashMessage);
        }
      }
    },

    gameOver: function () {
      document.getElementById('game-overlay').style.display = 'block';
      document.getElementById('game-over').style.display = 'block';
      Game.isGameOver = true;
    },

    gamePause: function () {
      var newDisplay = 'block';
      if (document.getElementById('game-paused').style.display === 'block') {
        newDisplay = 'none';
      }
      document.getElementById('game-overlay').style.display = newDisplay;
      document.getElementById('game-paused').style.display = newDisplay;
    },

    render: function () {
      if (Game.isPaused) {
        return;
      }

      var i;

      // Render Background
      if (Game.backgroundReady) {
        Game.context.drawImage(Game.backgroundImg, 0, 0);
      }

      // Render Projectiles
      for (i = 0; i < Game.projectilePool.size(); ++i) {
        Game.projectilePool.objectPool()[i].render(Game.context);
      }

      // Render Explosions
      for (i = 0; i < Game.explosionPool.size(); ++i) {
        Game.explosionPool.objectPool()[i].render(Game.context);
      }

      // Render Zombies
      for (i = 0; i < Game.zombiePool.size(); ++i) {
        Game.zombiePool.objectPool()[i].render(Game.context);
      }

      // Render Player
      if (!Game.isGameOver) {
        Game.player.render(Game.context);
      }

      // Render Flash messages
      for (i = 0; i < Game.flashMessagePool.size(); ++i) {
        Game.flashMessagePool.objectPool()[i].render(Game.context);
      }

      // Render score
      Game.renderStatus();
    },

    renderStatus: function () {
      Game.context.fillStyle = '#fff';
      Game.context.font = '20px Helvetica';
      Game.context.textAlign = 'left';
      Game.context.textBaseline = 'top';

      Game.context.fillText('Score: ' + Game.score, 10, 5);
      Game.context.fillText('Level: ' + Game.player.level, Game.canvas.width - 110, 5);
    }
  };

  // expose Game globally
  window.Game = Game;
}());
<commit_msg>Handle the 'pause' status with gamePause method.<commit_after>/* global Player, Projectile, Zombie, Explosion, ObjectPoolMaker, FlashMessage */

(function () {
  'use strict';

  var Game = {
    init: function () {
      Game.canvas = document.getElementById('game-canvas');
      Game.context = Game.canvas.getContext('2d');

      Game.loadBackground();
      Game.bind();
      Game.reset();
    },

    hasLeveled: function (level) {
      return Game.score > Game.neededScoreForLevel(level + 1);
    },

    neededScoreForLevel: function (level) {
      return Math.floor(Math.pow(level, 3) * 100) + 1000;
    },

    bind: function () {
      document.addEventListener('keydown', function (e) {
        Game.keysDown[e.keyCode] = true;

        // prevent window from scrolling when pressing UP or DOWN or SPACE
        if (e.keyCode === 38 || e.keyCode === 40 || e.keyCode === 32) {
          e.preventDefault();
        }
        if (!Game.isGameOver && e.keyCode === 80) {
          Game.gamePause();
        }
      }, false);

      document.addEventListener('keyup', function (e) {
        delete Game.keysDown[e.keyCode];

        // prevent window from scrolling when pressing UP or DOWN or SPACE
        if (e.keyCode === 38 || e.keyCode === 40 || e.keyCode === 32) {
          e.preventDefault();
        }
      }, false);

      window.addEventListener('blur', function () {
        Game.keysDown = {};
      }, false);

      document.getElementById('play-again').addEventListener('click', function () {
        Game.reset();
      }, false);
      document.getElementById('return-play').addEventListener('click', function () {
        Game.gamePause();
      }, false);
    },

    reset: function () {
      // Current game difficulty
      Game.difficulty = 0.01;

      // Max difficulty that Game can reach at any given time
      // It represents the chance percentage of spawning a new Zombie
      Game.maxDifficulty = 0.40;

      // How much difficulty increases after its cooldown elapsed
      Game.difficultyIncrement = 0.005;

      // How long it takes (in seconds) to difficulty to increase
      Game.difficultyCooldown = 4;

      // Last time difficulty was increased
      Game.lastDifficultyIncrease = 0;

      // Time elapsed since Game began
      Game.gameTime = 0;

      // Total score from killing zombies
      Game.score = 0;

      // Maps which keys as currently pressed by e.keyCode
      Game.keysDown = {};

      // Last time a projectile was shot by the player
      Game.lastProjectileTime = 0;

      // How long it takes (in ms) for another projectile to be fired
      Game.projectileCooldown = 225;

      // How much projectile speed improves after each level
      Game.projectileCooldownImprove = 25;

      // Maximum projectile speed (less is faster)
      Game.minProjectileCooldown = 100;

      // Define how many levels it takes to increase projectile power by 1
      // (huge difference)
      Game.powerUpProjectileIn = 10;

      // How many pixels Player and Zombies are constrained by vertically/horizontally
      // (this is interesting according to the background image used)
      Game.verticalBoundary = 35;
      Game.horizontalBoundary = 5;

      Game.isPaused = false;

      Game.isGameOver = false;

      Game.player = new Player(
        Game.canvas.width / 2 - Player.width / 2,
        Game.canvas.height / 2 - Player.height / 2
      );

      // Store pool of objects to be reused for each Entity
      Game.zombiePool = new ObjectPoolMaker(Zombie, 100);
      Game.projectilePool = new ObjectPoolMaker(Projectile, 100);
      Game.explosionPool = new ObjectPoolMaker(Explosion, 100);
      Game.flashMessagePool = new ObjectPoolMaker(FlashMessage, 100);

      document.getElementById('game-overlay').style.display = 'none';
      document.getElementById('game-over').style.display = 'none';
      document.getElementById('game-paused').style.display = 'none';
    },

    loadBackground: function () {
      Game.backgroundReady = false;

      Game.backgroundImg = new Image();
      Game.backgroundImg.src = 'public/images/background.png';

      Game.backgroundImg.onload = function () {
        Game.backgroundReady = true;
      };
    },

    update: function (modifier) {
      if (Game.isPaused) {
        return;
      }

      Game.gameTime += modifier;

      Game.handleInput(modifier);
      Game.handleDifficulty();
      Game.spawnZombies();
      Game.updateEntities(modifier);
    },

    handleInput: function (modifier) {
      if (Game.isGameOver) {
        return;
      }

      var now = Date.now();

      // UP
      if (Game.keysDown[38] && Game.player.y > Game.verticalBoundary) {
        Game.player.setY(Game.player.y - (Game.player.speed * modifier));
      }

      // DOWN
      if (Game.keysDown[40] && Game.player.y < Game.canvas.height - Game.verticalBoundary - Player.height) {
        Game.player.setY(Game.player.y + (Game.player.speed * modifier));
      }

      // RIGHT
      if (Game.keysDown[39] && Game.player.x < Game.canvas.width - Game.horizontalBoundary - Player.width) {
        Game.player.setX(Game.player.x + (Game.player.speed * modifier));
      }

      // LEFT
      if (Game.keysDown[37] && Game.player.x > Game.horizontalBoundary) {
        Game.player.setX(Game.player.x - (Game.player.speed * modifier));
      }

      // SPACE - shoot!
      if (Game.keysDown[32]) {
        // prevent spamming projectiles
        if (now - Game.lastProjectileTime > Game.projectileCooldown) {
          Game.projectilePool.create(
            Game.player.x,
            Game.player.y + (Player.height / 2) - (Projectile.height / 2),
            400,
            Math.floor(Game.player.level / Game.powerUpProjectileIn) + 1
          );
          Game.lastProjectileTime = now;
        }
      }
    },

    handleDifficulty: function () {
      // It gets harder as time goes by..
      if (Game.difficulty < Game.maxDifficulty &&
          Game.gameTime - Game.lastDifficultyIncrease > Game.difficultyCooldown) {
        Game.difficulty += Game.difficultyIncrement;
        Game.lastDifficultyIncrease = Game.gameTime;
      }
    },

    spawnZombies: function () {
      // Create some enemies
      if (Math.random() < Game.difficulty) {
        // resets x coordinate
        // randomize new y coordinate (constrained in available map space)
        Game.zombiePool.create(
          Game.canvas.width,
          Math.random() * (Game.canvas.height - Zombie.height - (2 * Game.verticalBoundary)) + Game.verticalBoundary
        );
      }
    },

    updateEntities: function (modifier) {
      Game.updateProjectilesAndKillZombies(modifier);
      Game.updateZombies(modifier);
      Game.updateExplosions();
      Game.updatePlayer();
      Game.updateFlashMessages(modifier);
    },

    updateProjectilesAndKillZombies: function (modifier) {
      var i,
          j,
          zombie,
          projectile;

      // update all projectiles
      for (i = 0; i < Game.projectilePool.size(); i++) {
        projectile = Game.projectilePool.objectPool()[i];

        projectile.setX(projectile.x + (projectile.speed * modifier));

        // delete projectile if out of the scene
        if (projectile.x > Game.canvas.width) {
          Game.projectilePool.destroy(projectile);
          i--;
        }
        else {
          // kill zombies!
          for (j = 0; j < Game.zombiePool.size(); j++) {
            zombie = Game.zombiePool.objectPool()[j];
            if (projectile.isCollided(zombie)) {
              Game.explosionPool.create(zombie.x, zombie.y);

              // hundred points for each zombie!
              Game.score += 100;

              // Decrease projectile power and
              projectile.power--;
              // destroy projectile if it has no more power
              if (projectile.power === 0) {
                Game.projectilePool.destroy(projectile);
                i--;
              }

              Game.flashMessagePool.create(
                '+ 100',
                zombie.x,
                zombie.y,
                500
              );
              Game.zombiePool.destroy(zombie);
              j--;

              break;
            }
          }
        }
      }
    },

    updateZombies: function (modifier) {
      var zombie,
          i,
          now = Date.now();

      // update all enemies
      for (i = 0; i < Game.zombiePool.size(); i++) {
        zombie = Game.zombiePool.objectPool()[i];
        zombie.update(now);
        zombie.setX(zombie.x - (zombie.speed * modifier));

        // delete zombie if out of the scene
        if (zombie.x + Zombie.width < 0) {
          Game.zombiePool.destroy(zombie);
          i--;
        }
      }
    },

    updateExplosions: function () {
      var i,
          explosion;

      for (i = 0; i < Game.explosionPool.size(); ++i) {
        explosion = Game.explosionPool.objectPool()[i];
        explosion.update();
        if (explosion.currentFrame >= Explosion.framesPosition.length - 1) {
          Game.explosionPool.destroy(explosion);
        }
      }
    },

    updatePlayer: function () {
      var zombie,
          i;

      if (!Game.isGameOver) {
        for (i = 0; i < Game.zombiePool.size(); ++i) {
          zombie = Game.zombiePool.objectPool()[i];
          if (zombie.isCollided(Game.player)) {
            Game.gameOver();
            break;
          }
        }
      }

      // Level up!
      if (Game.hasLeveled(Game.player.level)) {
        Game.player.level += 1;
        Game.flashMessagePool.create(
          'Level ' + Game.player.level,
          Game.player.x,
          Game.player.y,
          700,
          '#E2E215',
          '18px'
        );

        // power up ?
        if (Game.player.level % 10 === 0) {
          Game.flashMessagePool.create(
            'Power Up!',
            Game.player.x,
            Game.player.y - Player.height / 2,
            1000,
            '#34FAC3',
            '16px'
          );
        }

        Game.projectileCooldown -= Game.projectileCooldownImprove;
        if (Game.projectileCooldown < Game.minProjectileCooldown) {
          Game.projectileCooldown = Game.minProjectileCooldown;
        }
      }
    },

    updateFlashMessages: function (modifier) {
      var i,
          flashMessage,
          now = Date.now();

      for (i = 0; i < Game.flashMessagePool.size(); ++i) {
        flashMessage = Game.flashMessagePool.objectPool()[i];
        flashMessage.y -= modifier * 10;
        if (now - flashMessage.createdAt > flashMessage.duration) {
          Game.flashMessagePool.destroy(flashMessage);
        }
      }
    },

    gameOver: function () {
      document.getElementById('game-overlay').style.display = 'block';
      document.getElementById('game-over').style.display = 'block';
      Game.isGameOver = true;
    },

    gamePause: function () {
      Game.isPaused = !Game.isPaused;

      var newDisplay = 'block';
      if (document.getElementById('game-paused').style.display === 'block') {
        newDisplay = 'none';
      }
      document.getElementById('game-overlay').style.display = newDisplay;
      document.getElementById('game-paused').style.display = newDisplay;
    },

    render: function () {
      if (Game.isPaused) {
        return;
      }

      var i;

      // Render Background
      if (Game.backgroundReady) {
        Game.context.drawImage(Game.backgroundImg, 0, 0);
      }

      // Render Projectiles
      for (i = 0; i < Game.projectilePool.size(); ++i) {
        Game.projectilePool.objectPool()[i].render(Game.context);
      }

      // Render Explosions
      for (i = 0; i < Game.explosionPool.size(); ++i) {
        Game.explosionPool.objectPool()[i].render(Game.context);
      }

      // Render Zombies
      for (i = 0; i < Game.zombiePool.size(); ++i) {
        Game.zombiePool.objectPool()[i].render(Game.context);
      }

      // Render Player
      if (!Game.isGameOver) {
        Game.player.render(Game.context);
      }

      // Render Flash messages
      for (i = 0; i < Game.flashMessagePool.size(); ++i) {
        Game.flashMessagePool.objectPool()[i].render(Game.context);
      }

      // Render score
      Game.renderStatus();
    },

    renderStatus: function () {
      Game.context.fillStyle = '#fff';
      Game.context.font = '20px Helvetica';
      Game.context.textAlign = 'left';
      Game.context.textBaseline = 'top';

      Game.context.fillText('Score: ' + Game.score, 10, 5);
      Game.context.fillText('Level: ' + Game.player.level, Game.canvas.width - 110, 5);
    }
  };

  // expose Game globally
  window.Game = Game;
}());
<|endoftext|>


<commit_before>/**
 * @depends {nrs.js}
 */
var NRS = (function(NRS, $, undefined) {
	NRS.fetchingModalData = false;

	// save the original function object
	var _superModal = $.fn.modal;

	// add locked as a new option
	$.extend(_superModal.Constructor.DEFAULTS, {
		locked: false
	});

	// capture the original hide
	var _hide = _superModal.Constructor.prototype.hide;

	// add the lock, unlock and override the hide of modal
	$.extend(_superModal.Constructor.prototype, {
		// locks the dialog so that it cannot be hidden
		lock: function() {
			this.options.locked = true;
			this.$element.addClass("locked");
		}
		// unlocks the dialog so that it can be hidden by 'esc' or clicking on the backdrop (if not static)
		,
		unlock: function() {
			this.options.locked = false;
			this.$element.removeClass("locked");
		},
		// override the original hide so that the original is only called if the modal is unlocked
		hide: function() {
			if (this.options.locked) return;

			_hide.apply(this, arguments);
		}
	});

	//Reset scroll position of tab when shown.
	$('a[data-toggle="tab"]').on("shown.bs.tab", function(e) {
		var target = $(e.target).attr("href");
		$(target).scrollTop(0);
	})

	$(".add_message").on("change", function(e) {
		if ($(this).is(":checked")) {
			$(this).closest("form").find(".optional_message").fadeIn();
		} else {
			$(this).closest("form").find(".optional_message").hide();
		}
	});

	$(".add_note_to_self").on("change", function(e) {
		if ($(this).is(":checked")) {
			$(this).closest("form").find(".optional_note").fadeIn();
		} else {
			$(this).closest("form").find(".optional_note").hide();
		}
	});

	//hide modal when another one is activated.
	$(".modal").on("show.bs.modal", function(e) {
		var $inputFields = $(this).find("input[name=recipient], input[name=account_id]").not("[type=hidden]");

		$.each($inputFields, function() {
			if ($(this).hasClass("noMask")) {
				$(this).mask("NXT-****-****-****-*****", {
					"noMask": true
				}).removeClass("noMask");
			} else {
				$(this).mask("NXT-****-****-****-*****");
			}
		});

		var $visible_modal = $(".modal.in");

		if ($visible_modal.length) {
			if ($visible_modal.hasClass("locked")) {
				var $btn = $visible_modal.find("button.btn-primary:not([data-dismiss=modal])");
				NRS.unlockForm($visible_modal, $btn, true);
			} else {
				$visible_modal.modal("hide");
			}
		}
	});

	$(".modal").on("shown.bs.modal", function() {
		$(this).find("input[type=text]:first, textarea:first, input[type=password]:first").not("[readonly]").first().focus();
		$(this).find("input[name=converted_account_id]").val("");
		NRS.showedFormWarning = false; //maybe not the best place... we assume forms are only in modals?
	});

	//Reset form to initial state when modal is closed
	$(".modal").on("hidden.bs.modal", function(e) {
		$(this).find("input[name=recipient], input[name=account_id]").not("[type=hidden]").trigger("unmask");

		$(this).find(":input:not(button)").each(function(index) {
			var defaultValue = $(this).data("default");
			var type = $(this).attr("type");
			var tag = $(this).prop("tagName").toLowerCase();

			if (type == "checkbox") {
				if (defaultValue == "checked") {
					$(this).prop("checked", true);
				} else {
					$(this).prop("checked", false);
				}
			} else if (type == "hidden") {
				if (defaultValue !== undefined) {
					$(this).val(defaultValue);
				}
			} else if (tag == "select") {
				if (defaultValue !== undefined) {
					$(this).val(defaultValue);
				} else {
					$(this).find("option:selected").prop("selected", false);
					$(this).find("option:first").prop("selected", "selected");
				}
			} else {
				if (defaultValue !== undefined) {
					$(this).val(defaultValue);
				} else {
					$(this).val("");
				}
			}
		});

		//Hidden form field
		$(this).find("input[name=converted_account_id]").val("");

		//Hide/Reset any possible error messages
		$(this).find(".callout-danger:not(.never_hide), .error_message, .account_info").html("").hide();

		$(this).find(".advanced").hide();

		$(this).find(".recipient_public_key").hide();

		$(this).find(".optional_message, .optional_note").hide();

		$(this).find(".advanced_info a").text($.t("advanced"));

		$(this).find(".advanced_extend").each(function(index, obj) {
			var normalSize = $(obj).data("normal");
			var advancedSize = $(obj).data("advanced");
			$(obj).removeClass("col-xs-" + advancedSize + " col-sm-" + advancedSize + " col-md-" + advancedSize).addClass("col-xs-" + normalSize + " col-sm-" + normalSize + " col-md-" + normalSize);
		});

		var $feeInput = $(this).find("input[name=feeNXT]");

		if ($feeInput.length) {
			var defaultFee = $feeInput.data("default");
			if (!defaultFee) {
				defaultFee = 1;
			}

			$(this).find(".advanced_fee").html(NRS.formatAmount(NRS.convertToNQT(defaultFee)) + " NXT");
		}

		NRS.showedFormWarning = false;
	});

	NRS.showModalError = function(errorMessage, $modal) {
		var $btn = $modal.find("button.btn-primary:not([data-dismiss=modal], .ignore)");

		$modal.find("button").prop("disabled", false);

		$modal.find(".error_message").html(String(errorMessage).escapeHTML()).show();
		$btn.button("reset");
		$modal.modal("unlock");
	}

	NRS.closeModal = function($modal) {
		if (!$modal) {
			$modal = $("div.modal.in:first");
		}

		$modal.find("button").prop("disabled", false);

		var $btn = $modal.find("button.btn-primary:not([data-dismiss=modal], .ignore)");

		$btn.button("reset");
		$modal.modal("unlock");
		$modal.modal("hide");
	}

	$("input[name=feeNXT]").on("change", function() {
		var $modal = $(this).closest(".modal");

		var $feeInfo = $modal.find(".advanced_fee");

		if ($feeInfo.length) {
			$feeInfo.html(NRS.formatAmount(NRS.convertToNQT($(this).val())) + " NXT");
		}
	});

	$(".advanced_info a").on("click", function(e) {
		e.preventDefault();

		var $modal = $(this).closest(".modal");

		var text = $(this).text().toLowerCase();

		if (text == $.t("advanced")) {
			$modal.find(".advanced").not(".optional_note").fadeIn();
		} else {
			$modal.find(".advanced").hide();
		}

		$modal.find(".advanced_extend").each(function(index, obj) {
			var normalSize = $(obj).data("normal");
			var advancedSize = $(obj).data("advanced");

			if (text == "advanced") {
				$(obj).addClass("col-xs-" + advancedSize + " col-sm-" + advancedSize + " col-md-" + advancedSize).removeClass("col-xs-" + normalSize + " col-sm-" + normalSize + " col-md-" + normalSize);
			} else {
				$(obj).removeClass("col-xs-" + advancedSize + " col-sm-" + advancedSize + " col-md-" + advancedSize).addClass("col-xs-" + normalSize + " col-sm-" + normalSize + " col-md-" + normalSize);
			}
		});

		if (text == $.t("advanced")) {
			$(this).text($.t("basic"));
		} else {
			$(this).text($.t("advanced"));
		}
	});

	return NRS;
}(NRS || {}, jQuery));<commit_msg>Don't show note to self until DGS block.<commit_after>/**
 * @depends {nrs.js}
 */
var NRS = (function(NRS, $, undefined) {
	NRS.fetchingModalData = false;

	// save the original function object
	var _superModal = $.fn.modal;

	// add locked as a new option
	$.extend(_superModal.Constructor.DEFAULTS, {
		locked: false
	});

	// capture the original hide
	var _hide = _superModal.Constructor.prototype.hide;

	// add the lock, unlock and override the hide of modal
	$.extend(_superModal.Constructor.prototype, {
		// locks the dialog so that it cannot be hidden
		lock: function() {
			this.options.locked = true;
			this.$element.addClass("locked");
		}
		// unlocks the dialog so that it can be hidden by 'esc' or clicking on the backdrop (if not static)
		,
		unlock: function() {
			this.options.locked = false;
			this.$element.removeClass("locked");
		},
		// override the original hide so that the original is only called if the modal is unlocked
		hide: function() {
			if (this.options.locked) return;

			_hide.apply(this, arguments);
		}
	});

	//Reset scroll position of tab when shown.
	$('a[data-toggle="tab"]').on("shown.bs.tab", function(e) {
		var target = $(e.target).attr("href");
		$(target).scrollTop(0);
	})

	$(".add_message").on("change", function(e) {
		if ($(this).is(":checked")) {
			$(this).closest("form").find(".optional_message").fadeIn();
		} else {
			$(this).closest("form").find(".optional_message").hide();
		}
	});

	$(".add_note_to_self").on("change", function(e) {
		if ($(this).is(":checked")) {
			$(this).closest("form").find(".optional_note").fadeIn();
		} else {
			$(this).closest("form").find(".optional_note").hide();
		}
	});

	//hide modal when another one is activated.
	$(".modal").on("show.bs.modal", function(e) {
		var $inputFields = $(this).find("input[name=recipient], input[name=account_id]").not("[type=hidden]");

		$.each($inputFields, function() {
			if ($(this).hasClass("noMask")) {
				$(this).mask("NXT-****-****-****-*****", {
					"noMask": true
				}).removeClass("noMask");
			} else {
				$(this).mask("NXT-****-****-****-*****");
			}
		});

		var $visible_modal = $(".modal.in");

		if ($visible_modal.length) {
			if ($visible_modal.hasClass("locked")) {
				var $btn = $visible_modal.find("button.btn-primary:not([data-dismiss=modal])");
				NRS.unlockForm($visible_modal, $btn, true);
			} else {
				$visible_modal.modal("hide");
			}
		}
	});

	$(".modal").on("shown.bs.modal", function() {
		$(this).find("input[type=text]:first, textarea:first, input[type=password]:first").not("[readonly]").first().focus();
		$(this).find("input[name=converted_account_id]").val("");
		NRS.showedFormWarning = false; //maybe not the best place... we assume forms are only in modals?
	});

	//Reset form to initial state when modal is closed
	$(".modal").on("hidden.bs.modal", function(e) {
		$(this).find("input[name=recipient], input[name=account_id]").not("[type=hidden]").trigger("unmask");

		$(this).find(":input:not(button)").each(function(index) {
			var defaultValue = $(this).data("default");
			var type = $(this).attr("type");
			var tag = $(this).prop("tagName").toLowerCase();

			if (type == "checkbox") {
				if (defaultValue == "checked") {
					$(this).prop("checked", true);
				} else {
					$(this).prop("checked", false);
				}
			} else if (type == "hidden") {
				if (defaultValue !== undefined) {
					$(this).val(defaultValue);
				}
			} else if (tag == "select") {
				if (defaultValue !== undefined) {
					$(this).val(defaultValue);
				} else {
					$(this).find("option:selected").prop("selected", false);
					$(this).find("option:first").prop("selected", "selected");
				}
			} else {
				if (defaultValue !== undefined) {
					$(this).val(defaultValue);
				} else {
					$(this).val("");
				}
			}
		});

		//Hidden form field
		$(this).find("input[name=converted_account_id]").val("");

		//Hide/Reset any possible error messages
		$(this).find(".callout-danger:not(.never_hide), .error_message, .account_info").html("").hide();

		$(this).find(".advanced").hide();

		$(this).find(".recipient_public_key").hide();

		$(this).find(".optional_message, .optional_note").hide();

		$(this).find(".advanced_info a").text($.t("advanced"));

		$(this).find(".advanced_extend").each(function(index, obj) {
			var normalSize = $(obj).data("normal");
			var advancedSize = $(obj).data("advanced");
			$(obj).removeClass("col-xs-" + advancedSize + " col-sm-" + advancedSize + " col-md-" + advancedSize).addClass("col-xs-" + normalSize + " col-sm-" + normalSize + " col-md-" + normalSize);
		});

		var $feeInput = $(this).find("input[name=feeNXT]");

		if ($feeInput.length) {
			var defaultFee = $feeInput.data("default");
			if (!defaultFee) {
				defaultFee = 1;
			}

			$(this).find(".advanced_fee").html(NRS.formatAmount(NRS.convertToNQT(defaultFee)) + " NXT");
		}

		NRS.showedFormWarning = false;
	});

	NRS.showModalError = function(errorMessage, $modal) {
		var $btn = $modal.find("button.btn-primary:not([data-dismiss=modal], .ignore)");

		$modal.find("button").prop("disabled", false);

		$modal.find(".error_message").html(String(errorMessage).escapeHTML()).show();
		$btn.button("reset");
		$modal.modal("unlock");
	}

	NRS.closeModal = function($modal) {
		if (!$modal) {
			$modal = $("div.modal.in:first");
		}

		$modal.find("button").prop("disabled", false);

		var $btn = $modal.find("button.btn-primary:not([data-dismiss=modal], .ignore)");

		$btn.button("reset");
		$modal.modal("unlock");
		$modal.modal("hide");
	}

	$("input[name=feeNXT]").on("change", function() {
		var $modal = $(this).closest(".modal");

		var $feeInfo = $modal.find(".advanced_fee");

		if ($feeInfo.length) {
			$feeInfo.html(NRS.formatAmount(NRS.convertToNQT($(this).val())) + " NXT");
		}
	});

	$(".advanced_info a").on("click", function(e) {
		e.preventDefault();

		var $modal = $(this).closest(".modal");

		var text = $(this).text().toLowerCase();

		if (text == $.t("advanced")) {
			var not = ".optional_note";
			if (!NRS.dgsBlockPassed) {
				not += ", .dgs_block";
			}
			$modal.find(".advanced").not(not).fadeIn();
		} else {
			$modal.find(".advanced").hide();
		}

		$modal.find(".advanced_extend").each(function(index, obj) {
			var normalSize = $(obj).data("normal");
			var advancedSize = $(obj).data("advanced");

			if (text == "advanced") {
				$(obj).addClass("col-xs-" + advancedSize + " col-sm-" + advancedSize + " col-md-" + advancedSize).removeClass("col-xs-" + normalSize + " col-sm-" + normalSize + " col-md-" + normalSize);
			} else {
				$(obj).removeClass("col-xs-" + advancedSize + " col-sm-" + advancedSize + " col-md-" + advancedSize).addClass("col-xs-" + normalSize + " col-sm-" + normalSize + " col-md-" + normalSize);
			}
		});

		if (text == $.t("advanced")) {
			$(this).text($.t("basic"));
		} else {
			$(this).text($.t("advanced"));
		}
	});

	return NRS;
}(NRS || {}, jQuery));<|endoftext|>


<commit_before>const { Command } = require('klasa');

module.exports = class extends Command {

	constructor(...args) {
		super(...args, 'disable', {
			permLevel: 10,
			description: 'Re-disables or temporarily disables a command/inhibitor/monitor/finalizer. Default state restored on reboot.',
			usage: '<Command:cmd|Inhibitor:inhibitor|Monitor:monitor|Finalizer:finalizer|Event:event>'
		});
	}

	async run(msg, [piece]) {
		if (piece.type === 'event' && piece.name === 'Message') return msg.sendMessage('You probably don\'t want to disable the message event, since you wouldn\'t be able to enable it again');
		piece.disable();
		return msg.sendCode('diff', `+ Successfully disabled ${piece.type}: ${piece.name}`);
	}

};
<commit_msg>prevent disable of commandHandler by default<commit_after>const { Command } = require('klasa');

module.exports = class extends Command {

	constructor(...args) {
		super(...args, 'disable', {
			permLevel: 10,
			description: 'Re-disables or temporarily disables a command/inhibitor/monitor/finalizer/event. Default state restored on reboot.',
			usage: '<Command:cmd|Inhibitor:inhibitor|Monitor:monitor|Finalizer:finalizer|Event:event>'
		});
	}

	async run(msg, [piece]) {
		if ((piece.type === 'event' && piece.name === 'Message') || (piece.type === 'monitor' && piece.name === 'commandHandler')) {
			return msg.sendMessage('You probably don\'t want to disable that, since you wouldn\'t be able to run any command to enable it again');
		}
		piece.disable();
		return msg.sendCode('diff', `+ Successfully disabled ${piece.type}: ${piece.name}`);
	}

};
<|endoftext|>