<commit_before>
var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update });

function preload() {

    game.load.spritesheet('ship', 'assets/sprites/humstar.png', 32, 32);
    game.load.spritesheet('veggies', 'assets/sprites/fruitnveg32wh37.png', 32, 32);
    game.load.image('ball', 'assets/sprites/shinyball.png');
    game.load.image('white', 'assets/sprites/white.png');
    game.load.image('clown', 'assets/sprites/clown.png');
}

var ship;
var cursors;
var customBounds;
var collisionGroupBalls;
var balls;
var collisionGroupPlayers;
var collisionGroupWalls;
var wallMaterial;

function create() {
    game.world.setBounds(-600, -400, 1200, 800);

    //  The bounds of our physics simulation
    var bounds = new Phaser.Rectangle(-500, -300, 1000, 600);

    game.physics.startSystem(Phaser.Physics.P2JS);

    game.physics.p2.restitution = 0.6;
    game.physics.p2.setImpactEvents(true);

    //  Some balls to collide with
    balls = game.add.physicsGroup(Phaser.Physics.P2JS);

    collisionGroupPlayers = game.physics.p2.createCollisionGroup();
    collisionGroupBalls = game.physics.p2.createCollisionGroup();
    collisionGroupWalls = game.physics.p2.createCollisionGroup();

    game.physics.p2.updateBoundsCollisionGroup();
    game.cameraPos = new Phaser.Point(0,0);
    game.cameraLerp = 0.02;

    //  Create a new custom sized bounds, within the world bounds
    createPreviewBounds(bounds.x, bounds.y, bounds.width, bounds.height);
    var ballMaterial = game.physics.p2.createMaterial('ballMaterial');
    var wallMaterial = game.physics.p2.createMaterial('wallMaterial');
    var playerMaterial = game.physics.p2.createMaterial('wallMaterial');

    var ballBallCM = game.physics.p2.createContactMaterial(
    	ballMaterial, ballMaterial,
    	{restitution: 0.8}
    );

    var ballPlayerCM = game.physics.p2.createContactMaterial(
    	ballMaterial, playerMaterial,
    	{restitution: 0.3}
    );

    for (var i = 0; i < 20; i++)
    {
        var ball = balls.create(bounds.randomX, bounds.randomY, 'ball');
        ball.scale.set(1.3);
        ball.body.setCircle(16 * 1.3);
        ball.body.mass = 0.5;
        ball.body.setMaterial(ballMaterial);
        ball.body.damping = 0.5;
        ball.body.setCollisionGroup(collisionGroupBalls);
        ball.body.collides([collisionGroupPlayers, collisionGroupBalls, collisionGroupWalls]);
    }

    ship = game.add.sprite(bounds.centerX, bounds.centerY, 'white');
    ship.tint = 0xdd8822;
    ship.inner_image = game.add.sprite(0,0,'clown');
    ship.inner_image.anchor.setTo(0.5);
    ship.inner_image.scale.set(0.7);
    ship.addChild(ship.inner_image);

    ship.scale.set(2);
    ship.smoothed = false;
    //ship.animations.add('fly', [0,1,2,3,4,5], 10, true);
    //ship.play('fly');

    //  Create our physics body. A circle assigned the playerCollisionGroup
    game.physics.p2.enable(ship, false);

    ship.body.fixedRotation = true;
    ship.body.setCircle(28);
    ship.body.damping = 0.9;
    ship.body.restitution = 0.2;
    ship.body.setCollisionGroup(collisionGroupPlayers);
    ship.body.collides([collisionGroupPlayers, collisionGroupBalls]);
    ship.body.coolDown = 0;
    ship.body.setMaterial(playerMaterial);

    //  Just to display the bounds
    var graphics = game.add.graphics(bounds.x, bounds.y);
    graphics.lineStyle(4, 0xffd900, 1);
    graphics.drawRect(0, 0, bounds.width, bounds.height);

    cursors = game.input.keyboard.addKeys({
    	'up': Phaser.KeyCode.UP,
    	'down': Phaser.KeyCode.DOWN,
    	'left': Phaser.KeyCode.LEFT,
    	'right': Phaser.KeyCode.RIGHT,
    	'shoot': Phaser.KeyCode.X
   	});

}

function createPreviewBounds(x, y, w, h) {

    customBounds = { left: null, right: null, top: null, bottom: null };
    var sim = game.physics.p2;

    //  If you want to use your own collision group then set it here and un-comment the lines below
    //var mask = sim.boundsCollisionGroup.mask;
    var mask = collisionGroupWalls.mask;

    customBounds.left = new p2.Body({ mass: 0, position: [ sim.pxmi(x), sim.pxmi(y) ], angle: 1.5707963267948966 });
    customBounds.left.addShape(new p2.Plane());
    //customBounds.left.setMaterial(wallMaterial);
    customBounds.left.shapes[0].collisionGroup = mask;
    customBounds.left.shapes[0].collisionMask = collisionGroupBalls.mask;

    customBounds.right = new p2.Body({ mass: 0, position: [ sim.pxmi(x + w), sim.pxmi(y) ], angle: -1.5707963267948966 });
    customBounds.right.addShape(new p2.Plane());
    //customBounds.right.setMaterial(wallMaterial);
    customBounds.right.shapes[0].collisionGroup = mask;
    customBounds.right.shapes[0].collisionMask = collisionGroupBalls.mask;

    customBounds.top = new p2.Body({ mass: 0, position: [ sim.pxmi(x), sim.pxmi(y) ], angle: -3.141592653589793 });
    customBounds.top.addShape(new p2.Plane());
    //customBounds.top.setMaterial(wallMaterial);
    customBounds.top.shapes[0].collisionGroup = mask;
    customBounds.top.shapes[0].collisionMask = collisionGroupBalls.mask;

    customBounds.bottom = new p2.Body({ mass: 0, position: [ sim.pxmi(x), sim.pxmi(y + h) ] });
    customBounds.bottom.addShape(new p2.Plane());
    //customBounds.bottom.setMaterial(wallMaterial);
    customBounds.bottom.shapes[0].collisionGroup = mask;
    customBounds.bottom.shapes[0].collisionMask = collisionGroupBalls.mask;

    sim.world.addBody(customBounds.left);
    sim.world.addBody(customBounds.right);
    sim.world.addBody(customBounds.top);
    sim.world.addBody(customBounds.bottom);
}

var maxAccel = 400;
var shootingAccel = 200;

function update() {
	if (cursors.shoot.isDown) {
		ship.body.isShooting = true;
	}
	else {
		ship.body.isShooting = false;
	}

	var accel = ship.body.isShooting ? shootingAccel : maxAccel;

    if (cursors.left.isDown)
    {
    	ship.body.force.x = -accel;
    }
    else if (cursors.right.isDown)
    {
        ship.body.force.x = accel;
    }

    if (cursors.up.isDown)
    {
    	ship.body.force.y = -accel;
    }
    else if (cursors.down.isDown)
    {
        ship.body.force.y = accel;
    }

    var b1 = ship.body;
    if (b1.isShooting && ship.body.coolDown < game.time.totalElapsedSeconds()) {
	    for (var k=0; k<balls.children.length; k++) {
	    	var b2 = balls.children[k].body;
		    var diffx = b1.x - b2.x;
			var diffy = b1.y - b2.y;
			var len = Math.sqrt(diffx*diffx + diffy*diffy);
			if (len > 57) continue;
			b1.coolDown = game.time.totalElapsedSeconds() + 0.1;

			diffx /= len;
			diffy /= len;

			var power = 400;
			b2.velocity.x -= diffx * power;
			b2.velocity.y -= diffy * power;
	    }
	}

	game.cameraPos.x += (ship.x - game.cameraPos.x) * game.cameraLerp; // smoothly adjust the x position
	game.cameraPos.y += (ship.y - game.cameraPos.y) * game.cameraLerp; // smoothly adjust the y position
	game.camera.focusOnXY(game.cameraPos.x, game.cameraPos.y); // apply smoothed virtual positions to actual camera
}
<commit_msg>Made field smaller to show up on blog properly<commit_after>
var game = new Phaser.Game(600, 480, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update });

function preload() {

    game.load.spritesheet('ship', 'assets/sprites/humstar.png', 32, 32);
    game.load.spritesheet('veggies', 'assets/sprites/fruitnveg32wh37.png', 32, 32);
    game.load.image('ball', 'assets/sprites/shinyball.png');
    game.load.image('white', 'assets/sprites/white.png');
    game.load.image('clown', 'assets/sprites/clown.png');
}

var ship;
var cursors;
var customBounds;
var collisionGroupBalls;
var balls;
var collisionGroupPlayers;
var collisionGroupWalls;
var wallMaterial;

function create() {
    game.world.setBounds(-600, -400, 1200, 800);

    //  The bounds of our physics simulation
    var bounds = new Phaser.Rectangle(-500, -300, 1000, 600);

    game.physics.startSystem(Phaser.Physics.P2JS);

    game.physics.p2.restitution = 0.6;
    game.physics.p2.setImpactEvents(true);

    //  Some balls to collide with
    balls = game.add.physicsGroup(Phaser.Physics.P2JS);

    collisionGroupPlayers = game.physics.p2.createCollisionGroup();
    collisionGroupBalls = game.physics.p2.createCollisionGroup();
    collisionGroupWalls = game.physics.p2.createCollisionGroup();

    game.physics.p2.updateBoundsCollisionGroup();
    game.cameraPos = new Phaser.Point(0,0);
    game.cameraLerp = 0.04;

    //  Create a new custom sized bounds, within the world bounds
    createPreviewBounds(bounds.x, bounds.y, bounds.width, bounds.height);
    var ballMaterial = game.physics.p2.createMaterial('ballMaterial');
    var wallMaterial = game.physics.p2.createMaterial('wallMaterial');
    var playerMaterial = game.physics.p2.createMaterial('wallMaterial');

    var ballBallCM = game.physics.p2.createContactMaterial(
    	ballMaterial, ballMaterial,
    	{restitution: 0.8}
    );

    var ballPlayerCM = game.physics.p2.createContactMaterial(
    	ballMaterial, playerMaterial,
    	{restitution: 0.3}
    );

    for (var i = 0; i < 20; i++)
    {
        var ball = balls.create(bounds.randomX, bounds.randomY, 'ball');
        ball.scale.set(1.3);
        ball.body.setCircle(16 * 1.3);
        ball.body.mass = 0.5;
        ball.body.setMaterial(ballMaterial);
        ball.body.damping = 0.5;
        ball.body.setCollisionGroup(collisionGroupBalls);
        ball.body.collides([collisionGroupPlayers, collisionGroupBalls, collisionGroupWalls]);
    }

    ship = game.add.sprite(bounds.centerX, bounds.centerY, 'white');
    ship.tint = 0xdd8822;
    ship.inner_image = game.add.sprite(0,0,'clown');
    ship.inner_image.anchor.setTo(0.5);
    ship.inner_image.scale.set(0.7);
    ship.addChild(ship.inner_image);

    ship.scale.set(2);
    ship.smoothed = false;
    //ship.animations.add('fly', [0,1,2,3,4,5], 10, true);
    //ship.play('fly');

    //  Create our physics body. A circle assigned the playerCollisionGroup
    game.physics.p2.enable(ship, false);

    ship.body.fixedRotation = true;
    ship.body.setCircle(28);
    ship.body.damping = 0.9;
    ship.body.restitution = 0.2;
    ship.body.setCollisionGroup(collisionGroupPlayers);
    ship.body.collides([collisionGroupPlayers, collisionGroupBalls]);
    ship.body.coolDown = 0;
    ship.body.setMaterial(playerMaterial);

    //  Just to display the bounds
    var graphics = game.add.graphics(bounds.x, bounds.y);
    graphics.lineStyle(4, 0xffd900, 1);
    graphics.drawRect(0, 0, bounds.width, bounds.height);

    cursors = game.input.keyboard.addKeys({
    	'up': Phaser.KeyCode.UP,
    	'down': Phaser.KeyCode.DOWN,
    	'left': Phaser.KeyCode.LEFT,
    	'right': Phaser.KeyCode.RIGHT,
    	'shoot': Phaser.KeyCode.X
   	});

}

function createPreviewBounds(x, y, w, h) {

    customBounds = { left: null, right: null, top: null, bottom: null };
    var sim = game.physics.p2;

    //  If you want to use your own collision group then set it here and un-comment the lines below
    //var mask = sim.boundsCollisionGroup.mask;
    var mask = collisionGroupWalls.mask;

    customBounds.left = new p2.Body({ mass: 0, position: [ sim.pxmi(x), sim.pxmi(y) ], angle: 1.5707963267948966 });
    customBounds.left.addShape(new p2.Plane());
    //customBounds.left.setMaterial(wallMaterial);
    customBounds.left.shapes[0].collisionGroup = mask;
    customBounds.left.shapes[0].collisionMask = collisionGroupBalls.mask;

    customBounds.right = new p2.Body({ mass: 0, position: [ sim.pxmi(x + w), sim.pxmi(y) ], angle: -1.5707963267948966 });
    customBounds.right.addShape(new p2.Plane());
    //customBounds.right.setMaterial(wallMaterial);
    customBounds.right.shapes[0].collisionGroup = mask;
    customBounds.right.shapes[0].collisionMask = collisionGroupBalls.mask;

    customBounds.top = new p2.Body({ mass: 0, position: [ sim.pxmi(x), sim.pxmi(y) ], angle: -3.141592653589793 });
    customBounds.top.addShape(new p2.Plane());
    //customBounds.top.setMaterial(wallMaterial);
    customBounds.top.shapes[0].collisionGroup = mask;
    customBounds.top.shapes[0].collisionMask = collisionGroupBalls.mask;

    customBounds.bottom = new p2.Body({ mass: 0, position: [ sim.pxmi(x), sim.pxmi(y + h) ] });
    customBounds.bottom.addShape(new p2.Plane());
    //customBounds.bottom.setMaterial(wallMaterial);
    customBounds.bottom.shapes[0].collisionGroup = mask;
    customBounds.bottom.shapes[0].collisionMask = collisionGroupBalls.mask;

    sim.world.addBody(customBounds.left);
    sim.world.addBody(customBounds.right);
    sim.world.addBody(customBounds.top);
    sim.world.addBody(customBounds.bottom);
}

var maxAccel = 400;
var shootingAccel = 200;

function update() {
	if (cursors.shoot.isDown) {
		ship.body.isShooting = true;
	}
	else {
		ship.body.isShooting = false;
	}

	var accel = ship.body.isShooting ? shootingAccel : maxAccel;

    if (cursors.left.isDown)
    {
    	ship.body.force.x = -accel;
    }
    else if (cursors.right.isDown)
    {
        ship.body.force.x = accel;
    }

    if (cursors.up.isDown)
    {
    	ship.body.force.y = -accel;
    }
    else if (cursors.down.isDown)
    {
        ship.body.force.y = accel;
    }

    var b1 = ship.body;
    if (b1.isShooting && ship.body.coolDown < game.time.totalElapsedSeconds()) {
	    for (var k=0; k<balls.children.length; k++) {
	    	var b2 = balls.children[k].body;
		    var diffx = b1.x - b2.x;
			var diffy = b1.y - b2.y;
			var len = Math.sqrt(diffx*diffx + diffy*diffy);
			if (len > 57) continue;
			b1.coolDown = game.time.totalElapsedSeconds() + 0.1;

			diffx /= len;
			diffy /= len;

			var power = 400;
			b2.velocity.x -= diffx * power;
			b2.velocity.y -= diffy * power;
	    }
	}

	game.cameraPos.x += (ship.x - game.cameraPos.x) * game.cameraLerp; // smoothly adjust the x position
	game.cameraPos.y += (ship.y - game.cameraPos.y) * game.cameraLerp; // smoothly adjust the y position
	game.camera.focusOnXY(game.cameraPos.x, game.cameraPos.y); // apply smoothed virtual positions to actual camera
}
<|endoftext|>


<commit_before>/* globals HMDVRDevice, PositionSensorVRDevice, Promise */
(function () {
  'use strict';

  function VRLoader (url) {
    var self = this;

    self.fsElement = null;
    self.fsEntered = false;

    if ('onmozfullscreenchange' in window) {
      self.fsChangeEventName = 'mozfullscreenchange';
    } else if ('onwebkitfullscreenchange' in window) {
      self.fsChangeEventName = 'webkitfullscreenchange';
    } else {
      self.fsChangeEventName = 'fullscreenchange';
    }

    window.addEventListener(self.fsChangeEventName, self.postFullscreenStatus.bind(self));

    document.getElementById('a-enter-vr-button').addEventListener('click', function () {
      self.requestFullscreen();
      self.postFullscreenStatus.bind(self);
    });

    window.addEventListener('message', function (e) {
      var msg = e.data;
      if (!msg.type) {
        return;
      }

      switch (msg.type) {
        case 'ready':
          console.log('[VRLoader] got ready');
          // Use postMessage to know to know when to start.
          self.iframe.contentWindow.postMessage({type: 'loaderReady'}, '*');
          break;
        case 'navigate':
          console.log('[VRLoader] navigating', msg.data.url);
          self.navigate(msg.data.url);
          break;
        case 'checkVr':
          e.ports[0].postMessage({type: 'checkVr', data: {isVr: self.fsEntered}});
          break;
      }
    });

    if (url) {
      self.injectIframe(url);
    }

    self.vrReady.then(function (data) {
      self.headset = data.headset;  // The HMD.
      self.sensor = data.sensor;  // The HMD's orientation/position sensor.
    }, console.warn.bind(console));
  }

  VRLoader.prototype.postFullscreenStatus = function () {
    this.fsElement = document.fullscreenElement || document.mozFullScreenElement || document.webkitFullscreenElement;
    this.fsEntered = !!this.fsElement;
    var fsData = this.fsEntered ? 'enter' : 'exit';
    this.iframe.contentWindow.postMessage({type: 'fullscreen', data: fsData}, '*');
  };

  VRLoader.prototype.injectIframe = function (url) {
    if (this.injected) {
      return;
    }

    // Element that is used to navigate between VR pages.
    this.container = document.createElement('div');
    this.container.id = 'webvr__container';
    this.container.className = 'webvr__container';
    this.container.style.cssText = 'border: 0; position: absolute; top: 0; left: 0; height: 100%; width: 100%; z-index: 99999';
    document.body.appendChild(this.container);

    this.iframe = document.createElement('iframe');
    this.iframe.setAttribute('allowfullscreen', '');
    this.iframe.id = 'webvr__iframe';
    this.iframe.className = 'webvr__iframe';
    this.iframe.style.cssText = 'border: 0; position: absolute; top: 0; left: 0; height: 100%; width: 100%; z-index: 99999';
    if (url) {
      this.iframe.src = url;
    }
    this.container.appendChild(this.iframe);
    this.iframe.focus();
    this.injected = true;
  };

  VRLoader.prototype.navigate = function (url) {
    var self = this;
    if (!this.injected) {
      this.injectIframe();
    }
    this.iframe.src = url;
    this.iframe.onload = function () {
      self.postFullscreenStatus();
    };
  };

  /**
   * Calls fullscreen with VR mode.
   */
  VRLoader.prototype.requestFullscreen = function () {
    var self = this;
    if (self.fsEntered) {
      return;
    }

    if (self.container.mozRequestFullScreen) {
      self.container.mozRequestFullScreen({vrDisplay: self.headset});
    } else if (self.container.webkitRequestFullscreen) {
      self.container.webkitRequestFullscreen({vrDisplay: self.headset});
    } else if (self.container.requestFullscreen) {
      self.container.requestFullscreen({vrDisplay: self.headset});
    }

    self.iframe.focus();
  };

  /**
   * Handles `navigator.getVRDevices()`.
   *
   * @return {Promise} Resolved with VR devices; rejected if we do not find a headset
   * or its corresponding sensors.
   */
  VRLoader.prototype.vrReady = new Promise(function (resolve, reject) {
    if (!navigator.getVRDevices) {
      return reject('No VR implementation found');
    }

    navigator.getVRDevices().then(function (devices) {
      var headset;
      var sensor;
      var i = 0;

      // Find headset device.
      for (i = 0; i < devices.length; ++i) {
        if (devices[i] instanceof HMDVRDevice) {
          headset = devices[i];
          break;
        }
      }

      if (!headset) {
        return reject('No headset found');
      }

      // Find orientation and position sensors.
      for (i = 0; i < devices.length; ++i) {
        if (devices[i] instanceof PositionSensorVRDevice &&
            devices[i].hardwareUnitId === headset.hardwareUnitId) {
          sensor = devices[i];
          break;
        }
      }

      if (sensor) {
        resolve({
          headset: headset,
          sensor: sensor
        });
      } else {
        reject("Found a headset, but didn't find a position and orientation");
      }
    });
  });

  window.VRLoader = VRLoader;

  return VRLoader;
})();
<commit_msg>remove unused VRLoader (fixes #935)<commit_after><|endoftext|>


<commit_before>var express = require('express');

var app = express.createServer(express.logger());

app.get('/', function(request, response) {
  response.send('Hello World!');
});

var port = process.env.PORT || 5000;
app.listen(port, function() {
  console.log("Listening on " + port);
});<commit_msg>altered to use express 3 syntax<commit_after>var express = require('express');

var port = process.env.PORT || 5000;
var app = express();

app.get('/', function(request, response) {
  response.send('Hello');
});

app.listen(port, function() {
  console.log("Listening on " + port);
});<|endoftext|>


<commit_before>var $ = require('jQuery');

console.log($('body').hasClass('something'));

<commit_msg>Initial app object.<commit_after>module.exports = {
  launch: function () {
    window.app = this;
  }
};

module.exports.launch();

<|endoftext|>


<commit_before>import { sym } from './util';

const _context = sym('context');

export const withContext = (Base = HTMLElement) =>
  class extends Base {
    get context() {
      if (this[_context]) {
        return this[_context];
      }
      let node = this;
      while ((node = node.parentNode || node.host)) {
        if ('context' in node) {
          return node.context;
        }
      }
    }
    set context(context) {
      this[_context] = context;
    }
  };
<commit_msg>Fix rollup build.<commit_after>import { sym } from './util/index';

const _context = sym('context');

export const withContext = (Base = HTMLElement) =>
  class extends Base {
    get context() {
      if (this[_context]) {
        return this[_context];
      }
      let node = this;
      while ((node = node.parentNode || node.host)) {
        if ('context' in node) {
          return node.context;
        }
      }
    }
    set context(context) {
      this[_context] = context;
    }
  };
<|endoftext|>


<commit_before>/**
 *  Copyright 2012 Rackspace
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */

var util = require('util');

var log = require('logmagic').local('service-registry-client.heartbeater');
var sprintf = require('sprintf').sprintf;
var misc = require('rackspace-shared-utils/lib/misc');
var request = require('rackspace-shared-utils/lib/request');
var errors = require('rackspace-shared-utils/lib/errors');

var BaseClient = require('./base').BaseClient;

// interval will be this many seconds than specified to account for latency at different layers.
var INTERVAL_PROACTIVE_SECONDS = 3;

function HeartBeater(username, apiKey, region, options, sessionId, initialToken, timeout) {
  this._sessionId = sessionId;
  this._heartbeatTimeout = timeout;

  if (this._heartbeatTimeout < 15) {
    this._heartbeatInterval = (this._heartbeatTimeout * 0.6);
  }
  else {
    this._heartbeatInterval = (this._heartbeatTimeout * 0.8);
  }

  this._timeoutId = null;
  this._nextToken = initialToken;

  this._stopped = false;

  HeartBeater.super_.call(this, username, apiKey, region, options);
}

util.inherits(HeartBeater, BaseClient);

HeartBeater.prototype._startHeartbeating = function() {
  // TODO: persistent connection doesn't work with 0.8
  var url = sprintf('/sessions/%(sessionId)s/heartbeat',
      {'sessionId': this._sessionId}),
      payload = {'token': this._nextToken},
      reqOptions = {'expectedStatusCode': 200},
      self = this, interval;

  if (process.version.indexOf('v0.6') !== -1) {
    //reqOptions.persistent = true;
  }

  if (this._stopped) {
    return;
  }

  // TODO: Use a persistent connection
  log.debug('Sending heartbeat', {'sessionId': this._sessionId, 'token': this._nextToken});

  this._request(url, 'POST', payload, reqOptions, function(err, res) {
    if (err) {
      log.error('API endpoint returned an error', {'error': err});

      if (!((err instanceof errors.UnexpectedStatusCodeError) && err.statusCode === 404)) {
        // Non 404, immediately re-try heartbeat
        interval = 10;
        self._timeoutId = setTimeout(self._startHeartbeating.bind(self), interval);
        return;
      }

      throw err;
    }

    interval = self._heartbeatInterval;

    // Jitter for the heartbeat interval
    if (interval > 5) {
      interval = interval + misc.getRandomInt(-3, 1) - INTERVAL_PROACTIVE_SECONDS;
    }

    if (interval <= 0) {
      // ugh. put it back and take your chances.
      interval = interval + INTERVAL_GRACE;
    }

    interval = interval * 1000;

    log.debugf('Scheduling next interval for ${interval}s in future',
              {'sessionId': self._sessionId, 'interval': parseInt(interval / 1000, 10)});

    self._nextToken = res.body.token;
    self._timeoutId = setTimeout(self._startHeartbeating.bind(self), interval);
  });
};

HeartBeater.prototype.start = function() {
  log.debug('Starting heartbeating', {'sessionId': this._sessionId});
  this._startHeartbeating();
};

HeartBeater.prototype.stop = function() {
  log.debug('Stopping heartbeating', {'sessionId': this._sessionId});

  this._stopped = true;
  clearTimeout(this._timeoutId);
};

exports.HeartBeater = HeartBeater;
<commit_msg>rename all the variables<commit_after>/**
 *  Copyright 2012 Rackspace
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */

var util = require('util');

var log = require('logmagic').local('service-registry-client.heartbeater');
var sprintf = require('sprintf').sprintf;
var misc = require('rackspace-shared-utils/lib/misc');
var request = require('rackspace-shared-utils/lib/request');
var errors = require('rackspace-shared-utils/lib/errors');

var BaseClient = require('./base').BaseClient;

// interval will be this many seconds than specified to account for latency at different layers.
var INTERVAL_PROACTIVE_SECONDS = 3;

function HeartBeater(username, apiKey, region, options, sessionId, initialToken, timeout) {
  this._sessionId = sessionId;
  this._heartbeatTimeout = timeout;

  if (this._heartbeatTimeout < 15) {
    this._heartbeatInterval = (this._heartbeatTimeout * 0.6);
  }
  else {
    this._heartbeatInterval = (this._heartbeatTimeout * 0.8);
  }

  this._timeoutId = null;
  this._nextToken = initialToken;

  this._stopped = false;

  HeartBeater.super_.call(this, username, apiKey, region, options);
}

util.inherits(HeartBeater, BaseClient);

HeartBeater.prototype._startHeartbeating = function() {
  // TODO: persistent connection doesn't work with 0.8
  var url = sprintf('/sessions/%(sessionId)s/heartbeat',
      {'sessionId': this._sessionId}),
      payload = {'token': this._nextToken},
      reqOptions = {'expectedStatusCode': 200},
      self = this, interval;

  if (process.version.indexOf('v0.6') !== -1) {
    //reqOptions.persistent = true;
  }

  if (this._stopped) {
    return;
  }

  // TODO: Use a persistent connection
  log.debug('Sending heartbeat', {'sessionId': this._sessionId, 'token': this._nextToken});

  this._request(url, 'POST', payload, reqOptions, function(err, res) {
    if (err) {
      log.error('API endpoint returned an error', {'error': err});

      if (!((err instanceof errors.UnexpectedStatusCodeError) && err.statusCode === 404)) {
        // Non 404, immediately re-try heartbeat
        interval = 10;
        self._timeoutId = setTimeout(self._startHeartbeating.bind(self), interval);
        return;
      }

      throw err;
    }

    interval = self._heartbeatInterval;

    // Jitter for the heartbeat interval
    if (interval > 5) {
      interval = interval + misc.getRandomInt(-3, 1) - INTERVAL_PROACTIVE_SECONDS;
    }

    if (interval <= 0) {
      // ugh. put it back and take your chances.
      interval = interval + INTERVAL_PROACTIVE_SECONDS;
    }

    interval = interval * 1000;

    log.debugf('Scheduling next interval for ${interval}s in future',
              {'sessionId': self._sessionId, 'interval': parseInt(interval / 1000, 10)});

    self._nextToken = res.body.token;
    self._timeoutId = setTimeout(self._startHeartbeating.bind(self), interval);
  });
};

HeartBeater.prototype.start = function() {
  log.debug('Starting heartbeating', {'sessionId': this._sessionId});
  this._startHeartbeating();
};

HeartBeater.prototype.stop = function() {
  log.debug('Stopping heartbeating', {'sessionId': this._sessionId});

  this._stopped = true;
  clearTimeout(this._timeoutId);
};

exports.HeartBeater = HeartBeater;
<|endoftext|>


<commit_before>if (!Modernizr.touch) {
    var s = skrollr.init({forceHeight: false});
}

$(document).ready(function() {
    var chart = new google.visualization.PieChart(document.getElementById('piechart'));
    getData(chart);
    setInterval(getData(chart),300);
});

// http://www.hugbot.me/info.json

function getData(chart) {
    $.getJSON("http://localhost/~creinartz/hugbot-frontend/app/test.json", function(data) {
        $('.js_tweet-count').html(data.received);
        var data = google.visualization.arrayToDataTable([
            ['Total', 'Status'],
            ['In Progress',      data.in_progress],
            ['Merged',      data.merged],
            ['Closed',  data.closed]
        ]);
        var options = {
        };
        chart.draw(data, options);
    });
}

<commit_msg>added google charts<commit_after>if (!Modernizr.touch) {
    var s = skrollr.init({forceHeight: false});
}

$(document).ready(function() {
    var chart = new google.visualization.PieChart(document.getElementById('piechart'));
    getData(chart);
    setInterval(getData(chart),300);
});

function getData(chart) {
    $.getJSON("http://www.hugbot.me/info.json", function(data) {
        $('.js_tweet-count').html(data.received);
        var data = google.visualization.arrayToDataTable([
            ['Total', 'Status'],
            ['In Progress',      data.in_progress],
            ['Merged',      data.merged],
            ['Closed',  data.closed]
        ]);
        var options = {
        };
        chart.draw(data, options);
    });
}

<|endoftext|>


<commit_before>document.addEventListener("DOMContentLoaded", function() {
    const {ipcRenderer} = require("electron");

    // titlebar elements
    document.querySelectorAll("#titleBar i").forEach(function(value, index, array) {
        value.addEventListener("click", function() {
            ipcRenderer.sendSync("titleBar", value.getAttribute("data-action"));
        }, false);
    });

    document.querySelector("#titleBar img").addEventListener("click", function() {
        while (document.querySelectorAll("#songs [data-type='audio']").length > 0) {
            document.querySelector("#songs [data-type='audio']").remove();
        }
        ipcRenderer.sendSync("titleBar", "loadFolder");

    });

    ipcRenderer.on("addSong", (event, msg) => {
        const base64 = "data:image/png;base64,";
        var path = msg.path;
        var title = msg.title;
        var artist = msg.artist[0];
        var album = msg.album;
        var duration = formatDuration(msg.duration);
        var cover = msg.cover;
        var moddate = msg.moddate;

        var num = 0;
        var songs = document.querySelectorAll("#songs [data-type='audio']");
        if (songs.length > 0) {
            num = parseInt(songs[songs.length - 1].getAttribute("data-num")) + 1;
        }

        var template = '
';
        template += '';
        template += '
' + artist.toUpperCase() + ' ' + album.toUpperCase() + '
';
        template += '
' + title.toUpperCase() + '' + duration + '

';

        document.getElementById("songs").innerHTML += template;
        updateSong(document.querySelector("#songs [data-num='" + num + "']"));
    });

    function formatDuration(seconds) {
        var sec = Math.round(seconds);
        var min = 0;
        var hour = 0;

        while(sec >= 60) {
            sec -= 60;
            min++;
        }
        if (sec < 10) {
            sec = "0" + sec;
        }

        while (min >= 60) {
            min -= 60;
            hour++;
        }

        if (min < 10) {
            min = "0" + min;
        }

        if (hour > 0) {
            return hour + ":" + min + ":" + sec;
        } else {
            return min + ":" + sec;
        }
    }
}, false);
<commit_msg>Clicking on songs loaded from file system was not playing<commit_after>document.addEventListener("DOMContentLoaded", function() {
    const {ipcRenderer} = require("electron");

    // titlebar elements
    document.querySelectorAll("#titleBar i").forEach(function(value, index, array) {
        value.addEventListener("click", function() {
            ipcRenderer.sendSync("titleBar", value.getAttribute("data-action"));
        }, false);
    });

    document.querySelector("#titleBar img").addEventListener("click", function() {
        while (document.querySelectorAll("#songs [data-type='audio']").length > 0) {
            document.querySelector("#songs [data-type='audio']").remove();
        }
        ipcRenderer.sendSync("titleBar", "loadFolder");

    });

    ipcRenderer.on("addSong", (event, msg) => {
        const base64 = "data:image/png;base64,";
        var path = msg.path;
        var title = msg.title;
        var artist = msg.artist[0];
        var album = msg.album;
        var duration = formatDuration(msg.duration);
        var cover = msg.cover;
        var moddate = msg.moddate;

        var num = 0;
        var songs = document.querySelectorAll("#songs [data-type='audio']");
        if (songs.length > 0) {
            num = parseInt(songs[songs.length - 1].getAttribute("data-num")) + 1;
        }

        var template = '
';
        template += '';
        template += '
' + artist.toUpperCase() + ' ' + album.toUpperCase() + '
';
        template += '
' + title.toUpperCase() + '' + duration + '

';

        document.getElementById("songs").innerHTML += template;

        setTimeout(function() { // else not working
            updateSong(document.querySelector("#songs [data-num='" + num + "']"));
        });
    });

    function formatDuration(seconds) {
        var sec = Math.round(seconds);
        var min = 0;
        var hour = 0;

        while(sec >= 60) {
            sec -= 60;
            min++;
        }
        if (sec < 10) {
            sec = "0" + sec;
        }

        while (min >= 60) {
            min -= 60;
            hour++;
        }

        if (min < 10) {
            min = "0" + min;
        }

        if (hour > 0) {
            return hour + ":" + min + ":" + sec;
        } else {
            return min + ":" + sec;
        }
    }
}, false);
<|endoftext|>


<commit_before>/*
TODO:
-better serialization/deserialization
-error handling if firebase contains malformed data, since we're not the only
ones who can write to it.
-multi part keys
*/

foam.CLASS({
  package: 'com.firebase',
  name: 'FirebaseDAO',
  extends: 'foam.dao.AbstractDAO',
  requires: [
    'foam.dao.ArraySink',
    'foam.net.HTTPRequest',
    'foam.net.EventSource'
  ],
  properties: [
    'of',
    'apppath',
    'secret',
    'eventSource_',
    {
      name: 'timestampProperty'
    },
    {
      name: 'basepath',
      expression: function(apppath, of) {
        return apppath + of.id.replace(/\./g, '/');
      }
    }
  ],
  methods: [
    function put(obj) {
      var req = this.HTTPRequest.create();

      if ( obj.id ) {
        req.method = "PUT";
        req.url = this.basepath
          + "/"
          + encodeURIComponent(obj.id) + ".json";
      } else {
        throw new Error('Server generated IDs not supported.');
        // req.method = 'POST';
        // req.url = this.basepath + '.json';
      }

      if ( this.secret ) {
        req.url += '?auth=' + encodeURIComponent(this.secret);
      }

      req.payload = JSON.stringify({
        data: foam.json.stringify(obj),
        lastUpdate: {
          ".sv": "timestamp"
        }
      });
      req.headers['content-type'] = 'application/json';
      req.headers['accept'] = 'application/json';

      return req.send().then(function(resp) {
        return resp.payload;
      }).then(function(payload) {
        payload = JSON.parse(payload);

        //        if ( obj.id ) {
          var o2 = foam.json.parse(foam.json.parseString(payload.data));
          if ( this.timestampProperty ) {
            this.timestampProperty.set(o2, payload.lastUpdate);
          }
          return o2;
        //        } else {
        //           Server created id
        //        }
      }.bind(this), function(resp) {
        // TODO: Handle various errors.
        return Promise.reject(foam.dao.InternalException.create());
      });
    },
    function remove(obj) {
      debugger;

      var req = this.HTTPRequest.create();
      req.method = "DELETE",
      req.url = this.basepath + "/" + encodeURIComponent(obj.id) + ".json";

      if ( this.secret ) {
        req.url += "?auth=" + encodeURIComponent(this.secret);
      }

      return req.send().then(function() {
        return Promise.resolve();
      }, function() {
        return Promise.reject(foam.dao.InternalException.create());
      });
    },
    function find(id) {
      var req = this.HTTPRequest.create();
      req.method = "GET";
      req.url = this.basepath + "/" + encodeURIComponent(id) + ".json";
      if ( this.secret ) {
        req.url += "?auth=" + encodeURIComponent(this.secret);
      }

      return req.send().then(function(resp) {
        return resp.payload;
      }).then(function(data) {
        if ( data == "null" ) {
          return Promise.reject(foam.dao.ObjectNotFoundException.create({ id: id }));
        }
        try {
          data = JSON.parse(data);

          var obj = foam.json.parse(
            foam.json.parseString(data.data));

          if ( this.timestampProperty ) {
            this.timestampProperty.set(obj, data.lastUpdate);
          }

          return obj;
        } catch(e) {
          return Promise.reject(foam.dao.InternalException.create());
        }
      }.bind(this));
    },
    function startEvents() {
      if ( this.eventSource_ ) {
        return;
      }

      this.eventSource_ = this.EventSource.create({
        uri: this.basepath + '.json?auth=' + this.secret
      })
      this.eventSource_.message.put.sub(this.onPut);
      this.eventSource_.message.patch.sub(this.onPatch);
      this.eventSource_.start();
    },
    function stopEvents() {
      if ( this.eventSource_ ) {
        this.eventSource_.close();
        this.eventSource_.message.put.unsub(this.onPut);
        this.eventSource_.message.patch.unsub(this.onPatch);
        this.clearProperty('eventSource_');
      }
    },
    function select(sink, skip, limit, order, predicate) {
      var req = this.HTTPRequest.create();
      req.method = "GET";
      req.url = this.basepath + ".json";
      if ( this.secret ) req.url += "?auth=" + encodeURIComponent(this.secret);

      var resultSink = sink || this.ArraySink.create();
      sink = this.decorateSink_(resultSink, skip, limit, order, predicate);

      // TODO: This should be streamed for better handling of large responses.
      return req.send().then(function(resp) {
        return resp.payload;
      }).then(function(payload) {
        var data = JSON.parse(payload);
        var fc = this.FlowControl.create();

        for ( var key in data ) {
          if ( fc.stopped ) break;
          if ( fc.errorEvt ) {
            sink.error && sink.error(fc.errorEvt);
            future.set(sink);
            break;
          }

          var obj = foam.json.parse(
            foam.json.parseString(data[key].data));
          if ( this.timestampProperty ) {
            this.timestampProperty.set(obj, data[key].lastUpdate);
          }

          sink.put(obj, null, fc);
        }
        sink.eof();

        return resultSink;
      }.bind(this), function(resp) {
        var e = foam.dao.InternalException.create();
        sink.error(e);
        return Promise.reject(e);
      });
    },
    function sub(firstTopic) {
      this.SUPER.apply(this, arguments);

      if ( firstTopic === 'on' ) {
        // TODO: No reliably way to detect unsubscribes yet
        // so we don't know when to stop streaming events.
        this.startEvents();
      }
    },
  ],
  listeners: [
    function onPut(s, _, _, data) {
      // PATH is one of
      // / -> new objects
      // /key -> new object
      // /key/data -> updated object

      var path = data.path;
      if ( path == "/" ) {
        // All data removed?
        if ( data.data == null ) {
          this.on.reset.pub();
          return;
        }

        for ( var key in data.data ) {
          var obj = foam.json.parse(foam.json.parseString(data.data[key].data));
          if ( this.timestampProperty ) {
            this.timestampProperty.set(obj, data.data[key].lastUpdate);
          }
          this.on.put.pub(obj);
        }
        return;
      } else if ( path.lastIndexOf('/') === 0 ) {
        if ( data.data == null ) {
          var obj = this.of.create();
          obj.id = path.substring(1)
          this.on.remove.pub(obj);
          return;
        }
        var obj = foam.json.parse(foam.json.parseString(data.data.data));
        if ( this.timestampProperty ) {
          this.timestampProperty.set(obj, data.data.lastUpdate);
        }
        this.on.put.pub(obj);
      } else if ( path.indexOf('/data') === path.length - 5 ) {
        // These last two events shouldn't happen unless somebody is editing
        // the underlying firebase data by hand.

        // Data of an existing row updated.
        debugger;
        var id = path.substring(1);
        id = id.substring(0, id.indexOf('/'));
        this.find(id).then(function(obj) {
          this.on.put.pub(obj);
        });

        // var obj = foam.json.parse(foam.json.parseString(data.data));
        // this.on.put.pub(obj);
      } else if ( path.indexOf('/lastUpdate') === path.length - 11 ) {
        // Timestamp of an existing row updated, do anything?
        // presumably if the object itself hasn't been updated we don't care
        // if it has been updated we should get an event for that.

        debugger;
        var id = path.substring(1);
        id = id.substring(0, id.indexOf('/'));
        this.find(id).then(function(obj) {
          this.on.put.pub(obj);
        });
      }
    },
    function onPatch(s, _, _, data) {
          // TODO: What does a patch even look like?
      debugger;
    }
  ]
});
<commit_msg>FirebaseDAO:  Efficiently handle the queries needed for SyncDAO Don't start streaming events until the first select.  This is probably a bit hacksish, but you can always start events manually using .startEvents();<commit_after>/*
TODO:
-better serialization/deserialization
-error handling if firebase contains malformed data, since we're not the only
ones who can write to it.
-multi part keys
*/

foam.CLASS({
  package: 'com.firebase',
  name: 'FirebaseDAO',
  extends: 'foam.dao.AbstractDAO',
  requires: [
    'foam.dao.ArraySink',
    'foam.net.HTTPRequest',
    'foam.net.EventSource',
    'foam.mlang.predicate.Gt',
    'foam.mlang.predicate.Constant'
  ],
  properties: [
    'of',
    'apppath',
    'secret',
    'eventSource_',
    {
      name: 'timestampProperty'
    },
    {
      name: 'basepath',
      expression: function(apppath, of) {
        return apppath + of.id.replace(/\./g, '/');
      }
    },
    'startEventsAt_'
  ],
  methods: [
    function put(obj) {
      var req = this.HTTPRequest.create();

      if ( obj.id ) {
        req.method = "PUT";
        req.url = this.basepath
          + "/"
          + encodeURIComponent(obj.id) + ".json";
      } else {
        throw new Error('Server generated IDs not supported.');
        // req.method = 'POST';
        // req.url = this.basepath + '.json';
      }

      if ( this.secret ) {
        req.url += '?auth=' + encodeURIComponent(this.secret);
      }

      req.payload = JSON.stringify({
        data: foam.json.stringify(obj),
        lastUpdate: {
          ".sv": "timestamp"
        }
      });
      req.headers['content-type'] = 'application/json';
      req.headers['accept'] = 'application/json';

      return req.send().then(function(resp) {
        return resp.payload;
      }).then(function(payload) {
        payload = JSON.parse(payload);

        //        if ( obj.id ) {
          var o2 = foam.json.parse(foam.json.parseString(payload.data));
          if ( this.timestampProperty ) {
            this.timestampProperty.set(o2, payload.lastUpdate);
          }
          return o2;
        //        } else {
        //           Server created id
        //        }
      }.bind(this), function(resp) {
        // TODO: Handle various errors.
        return Promise.reject(foam.dao.InternalException.create());
      });
    },
    function remove(obj) {
      debugger;

      var req = this.HTTPRequest.create();
      req.method = "DELETE",
      req.url = this.basepath + "/" + encodeURIComponent(obj.id) + ".json";

      if ( this.secret ) {
        req.url += "?auth=" + encodeURIComponent(this.secret);
      }

      return req.send().then(function() {
        return Promise.resolve();
      }, function() {
        return Promise.reject(foam.dao.InternalException.create());
      });
    },
    function find(id) {
      var req = this.HTTPRequest.create();
      req.method = "GET";
      req.url = this.basepath + "/" + encodeURIComponent(id) + ".json";
      if ( this.secret ) {
        req.url += "?auth=" + encodeURIComponent(this.secret);
      }

      return req.send().then(function(resp) {
        return resp.payload;
      }).then(function(data) {
        if ( data == "null" ) {
          return Promise.reject(foam.dao.ObjectNotFoundException.create({ id: id }));
        }
        try {
          data = JSON.parse(data);

          var obj = foam.json.parse(
            foam.json.parseString(data.data));

          if ( this.timestampProperty ) {
            this.timestampProperty.set(obj, data.lastUpdate);
          }

          return obj;
        } catch(e) {
          return Promise.reject(foam.dao.InternalException.create());
        }
      }.bind(this));
    },
    function startEvents() {
      if ( this.eventSource_ ) {
        return;
      }

      this.eventSource_ = this.EventSource.create({
        uri: this.basepath + '.json?auth=' + this.secret
      });

      if ( this.startEventsAt_ ) {
        '&orderBy="lastUpdate"&startAt=' + this.startEventsAt_;
      }

      this.eventSource_.message.put.sub(this.onPut);
      this.eventSource_.message.patch.sub(this.onPatch);
      this.eventSource_.start();
    },
    function stopEvents() {
      if ( this.eventSource_ ) {
        this.eventSource_.close();
        this.eventSource_.message.put.unsub(this.onPut);
        this.eventSource_.message.patch.unsub(this.onPatch);
        this.clearProperty('eventSource_');
      }
    },
    function select(sink, skip, limit, order, predicate) {
      var req = this.HTTPRequest.create();
      req.method = "GET";
      req.url = this.basepath + ".json";
      if ( this.secret ) req.url += "?auth=" + encodeURIComponent(this.secret);

      // Efficiently handle GT(lastupdate, #) queries.  Used by the SyncDAO to get
      // all changes.

      if ( predicate && this.timestampProperty &&
           this.Gt.isInstance(predicate) &&
           this.Constant.isInstance(predicate.arg2) &&
           predicate.arg1 === this.timestampProperty ) {

        // TODO: This is a hack to ensure that
        if ( ! this.startEventsAt_ )  {
          this.startEventsAt_ = predicate.arg2.f() + 1;
          this.startEvents();
        }

        req.url += '&orderBy="lastUpdate"&startAt=' + ( predicate.arg2.f() + 1 );
      }

      var resultSink = sink || this.ArraySink.create();
      sink = this.decorateSink_(resultSink, skip, limit, order, predicate);

      // TODO: This should be streamed for better handling of large responses.
      return req.send().then(function(resp) {
        return resp.payload;
      }).then(function(payload) {
        var data = JSON.parse(payload);
        var fc = this.FlowControl.create();

        for ( var key in data ) {
          if ( fc.stopped ) break;
          if ( fc.errorEvt ) {
            sink.error && sink.error(fc.errorEvt);
            future.set(sink);
            break;
          }

          var obj = foam.json.parse(
            foam.json.parseString(data[key].data));
          if ( this.timestampProperty ) {
            this.timestampProperty.set(obj, data[key].lastUpdate);
          }

          sink.put(obj, null, fc);
        }
        sink.eof();

        return resultSink;
      }.bind(this), function(resp) {
        var e = foam.dao.InternalException.create();
        sink.error(e);
        return Promise.reject(e);
      });
    }
  ],
  listeners: [
    function onPut(s, _, _, data) {
      // PATH is one of
      // / -> new objects
      // /key -> new object
      // /key/data -> updated object

      var path = data.path;
      if ( path == "/" ) {
        // All data removed?
        if ( data.data == null ) {
          this.on.reset.pub();
          return;
        }

        for ( var key in data.data ) {
          var obj = foam.json.parse(foam.json.parseString(data.data[key].data));
          if ( this.timestampProperty ) {
            this.timestampProperty.set(obj, data.data[key].lastUpdate);
          }
          this.on.put.pub(obj);
        }
        return;
      } else if ( path.lastIndexOf('/') === 0 ) {
        if ( data.data == null ) {
          var obj = this.of.create();
          obj.id = path.substring(1)
          this.on.remove.pub(obj);
          return;
        }
        var obj = foam.json.parse(foam.json.parseString(data.data.data));
        if ( this.timestampProperty ) {
          this.timestampProperty.set(obj, data.data.lastUpdate);
        }
        this.on.put.pub(obj);
      } else if ( path.indexOf('/data') === path.length - 5 ) {
        // These last two events shouldn't happen unless somebody is editing
        // the underlying firebase data by hand.

        // Data of an existing row updated.
        debugger;
        var id = path.substring(1);
        id = id.substring(0, id.indexOf('/'));
        this.find(id).then(function(obj) {
          this.on.put.pub(obj);
        });

        // var obj = foam.json.parse(foam.json.parseString(data.data));
        // this.on.put.pub(obj);
      } else if ( path.indexOf('/lastUpdate') === path.length - 11 ) {
        // Timestamp of an existing row updated, do anything?
        // presumably if the object itself hasn't been updated we don't care
        // if it has been updated we should get an event for that.

        debugger;
        var id = path.substring(1);
        id = id.substring(0, id.indexOf('/'));
        this.find(id).then(function(obj) {
          this.on.put.pub(obj);
        });
      }
    },
    function onPatch(s, _, _, data) {
          // TODO: What does a patch even look like?
      debugger;
    }
  ]
});
<|endoftext|>


<commit_before>import gulp from 'gulp';
import loadPlugins from 'gulp-load-plugins';
import browserSync from 'browser-sync';
import autoprefixer from 'autoprefixer-core';

const $ = loadPlugins();
const bs = browserSync.create();

// https://github.com/gulpjs/gulp/blob/master/docs/recipes/fast-browserify-builds-with-watchify.md
import browserify from 'browserify';
import watchify from 'watchify';
import source from 'vinyl-source-stream';

let b = browserify({
<% if (includeReact) { -%>
  entries: ['./app/scripts/app.jsx'],
  extensions: ['.jsx'],
<% } else { -%>
  entries: ['./app/scripts/app.js'],
<% } -%>
  debug: true
}, watchify.args);

// only watch for changes in development mode
if (process.env.GULP_ENV !== 'production') {
  b = watchify(b);
}

function bundle() {
  return b.bundle()
    .on('error', msg => {
      delete msg.stream;
      $.util.log(msg);
    })
    .pipe(source('bundle.js'))
    .pipe(gulp.dest('.tmp/scripts'))
    .pipe(bs.stream({once: true}));
}

gulp.task('scripts', bundle);
b.on('update', bundle);

gulp.task('lint', () => {
  return gulp.src([
<% if (includeReact) { -%>
    'app/scripts/**/*.{js,jsx}',
    'test/**/*.{js,jsx}',
<% } else { -%>
    'app/scripts/**/*.js',
    'test/**/*.js',
<% } -%>
    'task/**/*.js'
  ])
    .pipe($.eslint())
    .pipe($.eslint.format())
    .pipe($.eslint.failAfterError());
});

gulp.task('styles', () => {
  return gulp.src('app/styles/**/*.scss')
    .pipe($.plumber())
    .pipe($.sourcemaps.init())
    .pipe($.sass.sync()).on('error', $.sass.logError)
    .pipe($.postcss([autoprefixer]))
    .pipe($.sourcemaps.write())
    .pipe(gulp.dest('.tmp/styles'))
    .pipe(bs.stream());
});

gulp.task('connect:dev', ['scripts', 'styles'], done => {
  bs.init({
    notify: false,
    port: 9000,
    open: false,
    server: {
      baseDir: ['.tmp', 'app']
    }
  }, done);
});

gulp.task('watch:dev', ['connect:dev'], () => {
  gulp.watch([
    'app/index.html',
    'app/images/**/*'
  ]).on('change', bs.reload);

  gulp.watch('app/styles/**/*.scss', ['styles']);
});

gulp.task('serve:dev', ['connect:dev', 'watch:dev']);
<commit_msg>Explain the order of dirs passed to browserSync<commit_after>import gulp from 'gulp';
import loadPlugins from 'gulp-load-plugins';
import browserSync from 'browser-sync';
import autoprefixer from 'autoprefixer-core';

const $ = loadPlugins();
const bs = browserSync.create();

// https://github.com/gulpjs/gulp/blob/master/docs/recipes/fast-browserify-builds-with-watchify.md
import browserify from 'browserify';
import watchify from 'watchify';
import source from 'vinyl-source-stream';

let b = browserify({
<% if (includeReact) { -%>
  entries: ['./app/scripts/app.jsx'],
  extensions: ['.jsx'],
<% } else { -%>
  entries: ['./app/scripts/app.js'],
<% } -%>
  debug: true
}, watchify.args);

// only watch for changes in development mode
if (process.env.GULP_ENV !== 'production') {
  b = watchify(b);
}

function bundle() {
  return b.bundle()
    .on('error', msg => {
      delete msg.stream;
      $.util.log(msg);
    })
    .pipe(source('bundle.js'))
    .pipe(gulp.dest('.tmp/scripts'))
    .pipe(bs.stream({once: true}));
}

gulp.task('scripts', bundle);
b.on('update', bundle);

gulp.task('lint', () => {
  return gulp.src([
<% if (includeReact) { -%>
    'app/scripts/**/*.{js,jsx}',
    'test/**/*.{js,jsx}',
<% } else { -%>
    'app/scripts/**/*.js',
    'test/**/*.js',
<% } -%>
    'task/**/*.js'
  ])
    .pipe($.eslint())
    .pipe($.eslint.format())
    .pipe($.eslint.failAfterError());
});

gulp.task('styles', () => {
  return gulp.src('app/styles/**/*.scss')
    .pipe($.plumber())
    .pipe($.sourcemaps.init())
    .pipe($.sass.sync()).on('error', $.sass.logError)
    .pipe($.postcss([autoprefixer]))
    .pipe($.sourcemaps.write())
    .pipe(gulp.dest('.tmp/styles'))
    .pipe(bs.stream());
});

gulp.task('connect:dev', ['scripts', 'styles'], done => {
  bs.init({
    notify: false,
    port: 9000,
    open: false,
    server: {
      // the order is important, this way files in .tmp
      // will get precedence in case of a name clash
      baseDir: ['.tmp', 'app']
    }
  }, done);
});

gulp.task('watch:dev', ['connect:dev'], () => {
  gulp.watch([
    'app/index.html',
    'app/images/**/*'
  ]).on('change', bs.reload);

  gulp.watch('app/styles/**/*.scss', ['styles']);
});

gulp.task('serve:dev', ['connect:dev', 'watch:dev']);
<|endoftext|>


<commit_before>
var Botkit = require('botkit');
var tasks = ['Task 1', 'Task 2', 'Task 3'];

var formatTasks = function() {
    var out = '';
    for (i = 0; i < tasks.length; ++i) {
        out += ' * ' + tasks[i] + "\n";
    }
    return out;
}

if (!process.env.token) {
  console.log('Error: Specify token in environment');
  process.exit(1);
}

var controller = Botkit.slackbot({
 debug: false
});

controller.spawn({
  token: process.env.token
}).startRTM(function(err) {
  if (err) {
    throw new Error(err);
  }
});

controller.hears(['hello','hi', 'hola'],['direct_message','direct_mention','mention'],function(bot,message) {
    bot.reply(message,"Hola viteh");
});

controller.hears(['quien es el mas gamer?'],['direct_message','direct_mention','mention'],function(bot,message) {
    bot.reply(message, "@lean por lejos! pero le sigue @milhouseonfire");
});

controller.hears(['quien es el que le hace segunda @matu?'],['direct_message','direct_mention','mention'],function(bot,message) {
    bot.reply(message, "claramente @rhaunter");
});

controller.hears(['daily review'], ['direct_message'], function(bot, message) {
    bot.reply(message, "Task list is the following: " + formatTasks());
});

controller.hears(['add task (.*)'], ['direct_message'], function(bot, message) {
    var newTask = message.match[1]; //match[1] is the (.*) group. match[0] is the entire group (open the (.*) doors).
    tasks[tasks.length] = newTask;
    bot.reply(message, "Added task, new task list is the following: " + formatTasks());
});

controller.hears(['dm me'],['direct_message','direct_mention'],function(bot,message) {
  bot.startConversation(message,function(err,convo) {
    convo.say('Heard ya');
  });

  bot.startPrivateConversation(message,function(err,dm) {
    dm.say('Private reply!');
  });

});
<commit_msg>sembot.js * Replace inline code for managing task with taskmanager class<commit_after>
var Botkit = require('botkit');
var TaskManager = require('./taskmanager.js');
var tm = new TaskManager();
tm.add('Task 1');
tm.add('Task 2');
tm.add('Task 3');

if (!process.env.token) {
  console.log('Error: Specify token in environment');
  process.exit(1);
}

var controller = Botkit.slackbot({
 debug: false
});

controller.spawn({
  token: process.env.token
}).startRTM(function(err) {
  if (err) {
    throw new Error(err);
  }
});

controller.hears(['hello','hi', 'hola'],['direct_message','direct_mention','mention'],function(bot,message) {
    bot.reply(message,"Hola viteh");
});

controller.hears(['quien es el mas gamer?'],['direct_message','direct_mention','mention'],function(bot,message) {
    bot.reply(message, "@lean por lejos! pero le sigue @milhouseonfire");
});

controller.hears(['quien es el que le hace segunda @matu?'],['direct_message','direct_mention','mention'],function(bot,message) {
    bot.reply(message, "claramente @rhaunter");
});

controller.hears(['daily review'], ['direct_message'], function(bot, message) {
    bot.reply(message, "Task list is the following: " + tm.asString());
});

controller.hears(['add task (.*)'], ['direct_message'], function(bot, message) {
    var newTask = message.match[1]; //match[1] is the (.*) group. match[0] is the entire group (open the (.*) doors).
    tm.add(newTask);
    bot.reply(message, "Added task, new task list is the following: " + tm.asString());
});

controller.hears(['dm me'],['direct_message','direct_mention'],function(bot,message) {
  bot.startConversation(message,function(err,convo) {
    convo.say('Heard ya');
  });

  bot.startPrivateConversation(message,function(err,dm) {
    dm.say('Private reply!');
  });

});
<|endoftext|>


<commit_before>!function(e,t){"function"==typeof define&&define.amd?define(t):"object"==typeof exports?module.exports=t(require,exports,module):e.gulpWrapUmd=t()}(this,function(){var e,t,r,n={_keyStr:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",decodeArrayBuffer:function(e){var t=e.length/4*3,r=new ArrayBuffer(t);return this.decode(e,r),r},decode:function(e,t){var r=this._keyStr.indexOf(e.charAt(e.length-1)),n=this._keyStr.indexOf(e.charAt(e.length-2)),i=e.length/4*3;64==r&&i--,64==n&&i--;var a,c,h,l,d,f,o,s,u=0,y=0;for(a=t?new Uint8Array(t):new Uint8Array(i),e=e.replace(/[^A-Za-z0-9\+\/=]/g,""),u=0;i>u;u+=3)d=this._keyStr.indexOf(e.charAt(y++)),f=this._keyStr.indexOf(e.charAt(y++)),o=this._keyStr.indexOf(e.charAt(y++)),s=this._keyStr.indexOf(e.charAt(y++)),c=d<<2|f>>4,h=(15&f)<<4|o>>2,l=(3&o)<<6|s,a[u]=c,64!=o&&(a[u+1]=h),64!=s&&(a[u+2]=l);return a}};return e=function(t){var r;return t.length>0?(r=t.length,t[r-1]+(e(t.slice(0,r-1))<<8)):0},t=function(e){var t;return function(){var r,n,i;for(i=[],r=0,n=e.length;n>r;r++)t=e[r],i.push(String.fromCharCode(t));return i}().join("")},r=function(r){var i,a,c,h,l;return r=r.replace("\n","").split(" "),2<=(l=r.length)&&3>=l?"ssh-rsa"===r[0]?(h=n.decode(r[1]),7===e(h.slice(0,4))?"ssh-rsa"===t(h.slice(4,11))?(a=e(h.slice(11,15)),i=15+a,c=e(h.slice(i,i+4)),i+=4+c,i===h.length?!0:"invalid key length"):"invalid key type: "+t(h.slice(4,11)):"invalid key type length"):"invalid key type: "+r[0]:"invalid key structure"}});<commit_msg>Update main.js.<commit_after>!function(e,t){"function"==typeof define&&define.amd?define(t):"object"==typeof exports?module.exports=t(require,exports,module):e.gulpWrapUmd=t()}(this,function(){var e,t,r,n={_keyStr:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",decodeArrayBuffer:function(e){var t=e.length/4*3,r=new ArrayBuffer(t);return this.decode(e,r),r},decode:function(e,t){var r=this._keyStr.indexOf(e.charAt(e.length-1)),n=this._keyStr.indexOf(e.charAt(e.length-2)),i=e.length/4*3;64==r&&i--,64==n&&i--;var a,h,c,d,f,l,o,s,u=0,y=0;for(a=t?new Uint8Array(t):new Uint8Array(i),e=e.replace(/[^A-Za-z0-9\+\/=]/g,""),u=0;i>u;u+=3)f=this._keyStr.indexOf(e.charAt(y++)),l=this._keyStr.indexOf(e.charAt(y++)),o=this._keyStr.indexOf(e.charAt(y++)),s=this._keyStr.indexOf(e.charAt(y++)),h=f<<2|l>>4,c=(15&l)<<4|o>>2,d=(3&o)<<6|s,a[u]=h,64!=o&&(a[u+1]=c),64!=s&&(a[u+2]=d);return a}};return e=function(t){var r;return r=t.length,0===r?0:t[r-1]+(e(t.slice(0,r-1))<<8)},t=function(e){var t;return function(){var r,n,i;for(i=[],r=0,n=e.length;n>r;r++)t=e[r],i.push(String.fromCharCode(t));return i}().join("")},r=function(r){var i,a,h,c,d;return r=r.replace("\n","").split(" "),r.length<2||r.length>3?"invalid key structure":"ssh-rsa"!==r[0]?"invalid key type: "+r[0]:(d=n.decode(r[1]),7!==e(d.slice(0,4))?"invalid key type length":(c=t(d.slice(4,11)),"ssh-rsa"!==c?"invalid key type: "+c:(a=e(d.slice(11,15)),i=15+a,h=e(d.slice(i,+(i+3)+1||9e9)),i+=4+h,i!==d.length?"invalid key length":!0)))}});<|endoftext|>


<commit_before>/**
 * Socket server for MakerFaireSG 2017
 *
 * Listens for `vid` param from SwipeToSend app and `tweet` param from AnimatedTweets app
 * and sends them to the socket client.
 */

// Include config file
var fs = require('fs');
eval(fs.readFileSync('./public/js/config.js') + '');
var port = config.port || 3000;

var http = require('http');
var url = require('url');
var querystring = require('querystring');

var app = http.createServer(function (req, res) {
    var method = req.method;
    var sendResponse = function (jsonObject) {
        res.setHeader('Access-Control-Allow-Origin', '*');
        res.setHeader('Access-Control-Allow-Methods', 'GET, POST');
        res.setHeader('Access-Control-Allow-Headers', 'content-type');

        res.writeHead(200, { "Content-Type": "application/json" });
        res.write(JSON.stringify(jsonObject));
        res.end();
    }

    if ('GET' === method) {
        var urlParts = url.parse(req.url, true);
        var query = urlParts.query;
        var vid = query['vid'] || 0;
        var tweet = query['tweet'] || 0;

        console.log(urlParts.search ? query : urlParts.href);
        io.sockets.emit('vid', vid); // client listening for "vid" param
        io.sockets.emit('tweet', tweet); // client listening for "tweet" param
        sendResponse(query);
    } else if ('POST' === method) {
        var body = '';

        // Consolidate body
        req.on('data', function (data) {
            body += data;
        });

        // When request is ended, emit to socket client
        req.on('end', function () {
            var post = JSON.parse(body);
            var videoId = post.vid;
            var tweet = post.tweet;

            console.log(post);
            io.sockets.emit('vid', videoId); // client listening for "vid" param
            io.sockets.emit('tweet', tweet); // client listening for "tweet" param
            sendResponse(post);
        });
    } else {
        sendResponse({});
    }
});

// Socket.io server listens to our app
var io = require('socket.io').listen(app);

// Emit welcome message on connection
io.sockets.on('connection', function (socket) {
    socket.emit('welcome', { message: 'Connected to Server' });
});

app.listen(port, function () {
    console.log('Node app is running on port', port);
});
<commit_msg>Send vid/tweet param separately<commit_after>/**
 * Socket server for MakerFaireSG 2017
 *
 * Listens for `vid` param from SwipeToSend app and `tweet` param from AnimatedTweets app
 * and sends them to the socket client.
 */

// Include config file
var fs = require('fs');
eval(fs.readFileSync('./public/js/config.js') + '');
var port = config.port || 3000;

var http = require('http');
var url = require('url');
var querystring = require('querystring');

var app = http.createServer(function (req, res) {
    var method = req.method;
    var sendResponse = function (jsonObject) {
        res.setHeader('Access-Control-Allow-Origin', '*');
        res.setHeader('Access-Control-Allow-Methods', 'GET, POST');
        res.setHeader('Access-Control-Allow-Headers', 'content-type');

        res.writeHead(200, { "Content-Type": "application/json" });
        res.write(JSON.stringify(jsonObject));
        res.end();
    }

    if ('GET' === method) {
        var urlParts = url.parse(req.url, true);
        var query = urlParts.query;
        var videoId = query['vid'] || 0;
        var tweet = query['tweet'] || '';

        console.log(urlParts.search ? query : urlParts.href);
        if (videoId) {
            io.sockets.emit('vid', videoId); // client listening for "vid" param
        }
        if (tweet) {
            io.sockets.emit('tweet', tweet); // client listening for "tweet" param
        }
        sendResponse(query);
    } else if ('POST' === method) {
        var body = '';

        // Consolidate body
        req.on('data', function (data) {
            body += data;
        });

        // When request is ended, emit to socket client
        req.on('end', function () {
            var post = JSON.parse(body);
            var videoId = post.vid; || 0
            var tweet = post.tweet || '';

            console.log(post);
            if (videoId) {
                io.sockets.emit('vid', videoId); // client listening for "vid" param
            }
            if (tweet) {
                io.sockets.emit('tweet', tweet); // client listening for "tweet" param
            }
            sendResponse(post);
        });
    } else {
        sendResponse({});
    }
});

// Socket.io server listens to our app
var io = require('socket.io').listen(app);

// Emit welcome message on connection
io.sockets.on('connection', function (socket) {
    socket.emit('welcome', { message: 'Connected to Server' });
});

app.listen(port, function () {
    console.log('Node app is running on port', port);
});
<|endoftext|>


<commit_before>/* -*- Mode: js2; indent-tabs-mode: nil; tab-width: 4; js2-indent-offset: 4; js2-basic-offset: 4; -*-
 * vim: set ts=4 sw=4 et tw=99 ft=js:
 */

import { intrinsic, sanitize_with_regexp } from "./echo-util";
import { moduleGetSlot_id, moduleSetSlot_id, env_unused_id, value_id } from "./common-ids";
import * as b from "./ast-builder";

export class ModuleInfo {
    constructor(is_native) {
        this.slot_num = 0;
        this.exports = new Map();
        this.importList = [];
        this.has_default = false;
        this.is_native = is_native;
    }

    setHasDefaultExport() {
        this.has_default = true;
    }

    hasDefaultExport() {
        return this.has_default;
    }

    addExport(ident, constval) {
        this.exports.set(ident, { constval: constval, slot_num: this.slot_num });
        this.slot_num++;
    }

    addImportSource(source_path) {
        if (this.importList.indexOf(source_path) === -1) this.importList.push(source_path);
    }

    isNative() {
        return this.is_native;
    }
}

export class JSModuleInfo extends ModuleInfo {
    constructor(path) {
        super(false);
        this.path = path;
        let sanitized_path = sanitize_with_regexp(path);
        this.toplevel_function_name = `_ejs_toplevel_${sanitized_path}`;
        this.module_name = `_ejs_module_${sanitized_path}`;
    }

    getExportGetter(ident) {
        let export_info = this.exports.get(ident);
        let function_id = b.identifier(`get_export_${ident}`);
        let loc = (loc = { start: { line: 0, column: 0 } });
        if (export_info.constval) {
            return b.functionExpression(
                function_id,
                [env_unused_id],
                b.blockStatement([b.returnStatement(export_info.constval)], loc),
                [],
                null,
                loc
            );
        } else {
            return b.functionExpression(
                function_id,
                [env_unused_id],
                b.blockStatement(
                    [
                        b.returnStatement(
                            intrinsic(moduleGetSlot_id, [b.literal(this.path), b.literal(ident)])
                        ),
                    ],
                    loc
                ),
                [],
                null,
                loc
            );
        }
    }

    getExportSetter(ident) {
        let function_id = b.identifier(`set_export_${ident}`);
        // we shouldn't generate a setter for const exports
        return b.functionExpression(
            function_id,
            [env_unused_id, value_id],
            b.blockStatement([
                intrinsic(moduleSetSlot_id, [b.literal(this.path), b.literal(ident), value_id]),
            ])
        );
    }
}

export class NativeModuleInfo extends ModuleInfo {
    constructor(name, init_function, link_flags, module_files, ejs_dir) {
        super(true);
        this.path = name;
        this.module_name = name;
        this.init_function = init_function;
        this.link_flags = link_flags.join(" ");
        this.module_files = module_files;
        this.ejs_dir = ejs_dir;
    }
}
<commit_msg>fix something prettier did?<commit_after>/* -*- Mode: js2; indent-tabs-mode: nil; tab-width: 4; js2-indent-offset: 4; js2-basic-offset: 4; -*-
 * vim: set ts=4 sw=4 et tw=99 ft=js:
 */

import { intrinsic, sanitize_with_regexp } from "./echo-util";
import { moduleGetSlot_id, moduleSetSlot_id, env_unused_id, value_id } from "./common-ids";
import * as b from "./ast-builder";

export class ModuleInfo {
    constructor(is_native) {
        this.slot_num = 0;
        this.exports = new Map();
        this.importList = [];
        this.has_default = false;
        this.is_native = is_native;
    }

    setHasDefaultExport() {
        this.has_default = true;
    }

    hasDefaultExport() {
        return this.has_default;
    }

    addExport(ident, constval) {
        this.exports.set(ident, { constval: constval, slot_num: this.slot_num });
        this.slot_num++;
    }

    addImportSource(source_path) {
        if (this.importList.indexOf(source_path) === -1) this.importList.push(source_path);
    }

    isNative() {
        return this.is_native;
    }
}

export class JSModuleInfo extends ModuleInfo {
    constructor(path) {
        super(false);
        this.path = path;
        let sanitized_path = sanitize_with_regexp(path);
        this.toplevel_function_name = `_ejs_toplevel_${sanitized_path}`;
        this.module_name = `_ejs_module_${sanitized_path}`;
    }

    getExportGetter(ident) {
        let export_info = this.exports.get(ident);
        let function_id = b.identifier(`get_export_${ident}`);
        let loc = { start: { line: 0, column: 0 } };
        if (export_info.constval) {
            return b.functionExpression(
                function_id,
                [env_unused_id],
                b.blockStatement([b.returnStatement(export_info.constval)], loc),
                [],
                null,
                loc
            );
        } else {
            return b.functionExpression(
                function_id,
                [env_unused_id],
                b.blockStatement(
                    [
                        b.returnStatement(
                            intrinsic(moduleGetSlot_id, [b.literal(this.path), b.literal(ident)])
                        ),
                    ],
                    loc
                ),
                [],
                null,
                loc
            );
        }
    }

    getExportSetter(ident) {
        let function_id = b.identifier(`set_export_${ident}`);
        // we shouldn't generate a setter for const exports
        return b.functionExpression(
            function_id,
            [env_unused_id, value_id],
            b.blockStatement([
                intrinsic(moduleSetSlot_id, [b.literal(this.path), b.literal(ident), value_id]),
            ])
        );
    }
}

export class NativeModuleInfo extends ModuleInfo {
    constructor(name, init_function, link_flags, module_files, ejs_dir) {
        super(true);
        this.path = name;
        this.module_name = name;
        this.init_function = init_function;
        this.link_flags = link_flags.join(" ");
        this.module_files = module_files;
        this.ejs_dir = ejs_dir;
    }
}
<|endoftext|>


<commit_before>import InputClass from '#input?raw&-styles';

export default Base => class extends InputClass(Base) {
    static displayName = 'core: attach';

    constructor(props) {
        super(props);

        this.state = {
            ...this.state,
            pressed: false,
            value: null
        };
    }

    // file input doesn't allow to change it's value programmatically
    // componentWillReceiveProps() {}

    _onInputMouseDown(e) {
        this.setState({
            pressed: true
        });

        if (this.props.onMouseDown) {
            this.props.onMouseDown(e);
        }
    }

    _onInputMouseUp(e) {
        this.setState({
            pressed: false
        });

        if (this.props.onMouseUp) {
            this.props.onMouseUp(e);
        }
    }

    _onInputMouseLeave(e) {
        super._onInputMouseLeave(e);

        this.setState({
            pressed: false
        });
    }

    render() {
        const template = super.render();

        template.block = 'attach';

        template.mods = {
            ...template.mods,
            pressed: this.state.pressed
        };

        template.content[0].props = {
            ...template.content[0].props,
            type: 'file',
            onMouseDown: ::this._onInputMouseDown,
            onMouseUp: ::this._onInputMouseUp,
            onMouseLeave: ::this._onInputMouseLeave
        };

        if ('value' in this.props) {
            template.content.push({
                elem: 'value',
                tag: 'span',
                props: {
                    key: 'value'
                },
                content: this.props.value
            });
        }

        return template;
    }
};
<commit_msg>:wrench: refactor Attach without cross-component inheritance<commit_after>export default Base => class extends Base {
    static displayName = 'core: attach';
    static defaultProps = {
        disabled: false
    };

    constructor(props) {
        super(props);

        this.state = {
            pressed: false,
            focused: false,
            hovered: false,
            value: null
        };
    }

    // file input doesn't allow to change it's value programmatically
    // componentWillReceiveProps() {}

    _onInputChange(e) {
        this.setState({
            value: e.target.value
        });

        if (this.props.onChange) {
            this.props.onChange(e);
        }
    }

    _onInputFocus(e) {
        this.setState({
            focused: true
        });

        if (this.props.onFocus) {
            this.props.onFocus(e);
        }
    }

    _onInputBlur(e) {
        this.setState({
            focused: false
        });

        if (this.props.onBlur) {
            this.props.onBlur(e);
        }
    }

    _onInputMouseDown(e) {
        this.setState({
            pressed: true
        });

        if (this.props.onMouseDown) {
            this.props.onMouseDown(e);
        }
    }

    _onInputMouseUp(e) {
        this.setState({
            pressed: false
        });

        if (this.props.onMouseUp) {
            this.props.onMouseUp(e);
        }
    }

    _onInputMouseEnter(e) {
        this.setState({
            hovered: true
        });

        if (this.props.onMouseEnter) {
            this.props.onMouseEnter(e);
        }
    }

    _onInputMouseLeave(e) {
        this.setState({
            hovered: false,
            pressed: false
        });

        if (this.props.onMouseLeave) {
            this.props.onMouseLeave(e);
        }
    }

    _renderValue() {
        if (!('value' in this.props)) {
            return null;
        }

        return {
            elem: 'value',
            tag: 'span',
            props: {
                key: 'value'
            },
            content: this.props.value
        };
    }

    _renderChildren() {
        return [].concat(this.props.children);
    }

    val() {
        return this.state.value;
    }

    render() {
        return {
            block: 'attach',
            tag: 'label',
            mods: {
                focused: this.state.focused,
                hovered: this.state.hovered,
                pressed: this.state.pressed,
                disabled: this.props.disabled
            },
            content: [
                {
                    elem: 'control',
                    tag: 'input',
                    props: {
                        type: 'file',
                        ...this.props,
                        value: this.state.value,
                        onChange: ::this._onInputChange,
                        onFocus: ::this._onInputFocus,
                        onBlur: ::this._onInputBlur,
                        onMouseDown: ::this._onInputMouseDown,
                        onMouseUp: ::this._onInputMouseUp,
                        onMouseLeave: ::this._onInputMouseLeave,
                        onMouseEnter: ::this._onInputMouseEnter,
                        ref: 'control',
                        key: 'control'
                    }
                },
                this._renderValue(),
                ...this._renderChildren()
            ]
        };
    }
};
<|endoftext|>


<commit_before>'use strict'

const mixpanel = require('mixpanel')
const config = require('../config')

let _mixpanel = mixpanel.init(config.mixpanel_token)

class Mixpanel {

  static setPerson(sender, profile) {
    _mixpanel.people.set({
      $first_name: profile.first_name,
      $last_name: profile.last_name,
      $created: (new Date()).toISOString(),
      locale: profile.locale,
      timezone: profile.timezone,
      gender: profile.gender
    })
    _mixpanel.identify(sender.id)
  }

  static track(event, sender, message) {
    _mixpanel.track(event, {
      distinctId: sender.id,
      message: message
    })
  }
}

module.exports = Mixpanel<commit_msg>mixpanel identify update<commit_after>'use strict'

const mixpanel = require('mixpanel')
const config = require('../config')

let _mixpanel = mixpanel.init(config.mixpanel_token)

class Mixpanel {

  static setPerson(sender, profile) {
    _mixpanel.identify(sender.id)
    _mixpanel.people.set({
      $first_name: profile.first_name,
      $last_name: profile.last_name,
      $created: (new Date()).toISOString(),
      locale: profile.locale,
      timezone: profile.timezone,
      gender: profile.gender
    })
  }

  static track(event, sender, message) {
    _mixpanel.track(event, {
      distinctId: sender.id,
      message: message
    })
  }
}

module.exports = Mixpanel<|endoftext|>


<commit_before>require('colors');
require('./eventlog');

process.on('uncaughtException', function(err) {
  console.error(err);
});

require('./lib/initConf');

var nconf = require('nconf');

var connectorSetup = require('./connector-setup');

var emptyVars = [ 'LDAP_URL',
                  'LDAP_BASE',
                  'LDAP_BIND_USER',
                  'LDAP_BIND_PASSWORD' ];

connectorSetup.run(__dirname, emptyVars, function(err) {
  if(err) {
    console.log(err.message);
    process.exit(2);
  }

  if(!nconf.get('LDAP_URL')) {
    console.error('edit config.json and add your LDAP settings');
    return process.exit(1);
  }

  require('./ws_validator');

  if (!nconf.get('KERBEROS_AUTH') || process.platform !== 'win32') {
    return;
  }

  var kerberosServer = require('kerberos-server');
  var express  = require('express');
  var passport = require('passport');

  require('./lib/setupPassport');

  var cookieSessions = require('cookie-sessions');
  var app = express();

  //configure the webserver
  app.configure(function(){
    this.set('view engine', 'ejs');
    this.set('views', __dirname + '/views');

    this.use('/wsfed', kerberos_middleware);

    this.use(express.static(__dirname + '/public'));
    this.use(express.logger());

    this.use(express.cookieParser());
    this.use(express.bodyParser());
    this.use(cookieSessions({
      session_key:    'auth0-ad-conn',
      secret:         nconf.get('SESSION_SECRET')
    }));

    this.use(passport.initialize());
    this.use(this.router);
  });

  require('./endpoints').install(app);

  kerberosServer.listen(nconf.get('PORT'), app);

  console.log('listening on http://localhost:' + nconf.get('PORT'));
});<commit_msg>fix minor<commit_after>require('colors');
require('./eventlog');

process.on('uncaughtException', function(err) {
  console.error(err);
});

require('./lib/initConf');

var nconf = require('nconf');

var connectorSetup = require('./connector-setup');

var emptyVars = [ 'LDAP_URL',
                  'LDAP_BASE',
                  'LDAP_BIND_USER',
                  'LDAP_BIND_PASSWORD' ];

connectorSetup.run(__dirname, emptyVars, function(err) {
  if(err) {
    console.log(err.message);
    process.exit(2);
  }

  if(!nconf.get('LDAP_URL')) {
    console.error('edit config.json and add your LDAP settings');
    return process.exit(1);
  }

  require('./ws_validator');

  if (!nconf.get('KERBEROS_AUTH') || process.platform !== 'win32') {
    return;
  }

  var kerberosServer = require('kerberos-server');
  var express  = require('express');
  var passport = require('passport');

  require('./lib/setupPassport');

  var cookieSessions = require('cookie-sessions');
  var app = express();

  //configure the webserver
  app.configure(function(){
    this.set('view engine', 'ejs');
    this.set('views', __dirname + '/views');

    this.use(express.static(__dirname + '/public'));
    this.use(express.logger());

    this.use(express.cookieParser());
    this.use(express.bodyParser());
    this.use(cookieSessions({
      session_key:    'auth0-ad-conn',
      secret:         nconf.get('SESSION_SECRET')
    }));

    this.use(passport.initialize());
    this.use(this.router);
  });

  require('./endpoints').install(app);

  kerberosServer.createServer(nconf.get('PORT'), app);

  console.log('listening on http://localhost:' + nconf.get('PORT'));
});<|endoftext|>