<commit_before>////////////////////////////////////////////////////////////////////////////////
// Directory Walker
//
// Walks directories recursively and executes handlers on each object.
// Only synchronous walking is supported because async can only be done
// with CPS (continuation-passing style), which is complicated and adds
// restrictions to the callbacks.
////////////////////////////////////////////////////////////////////////////////
/*global require, exports, process, console */
var	$fs = require('fs'),

// - dirHandler: called for each directory
// - fileHandler: called for each file
// - options:
//   - filter: regex for filtering file names
walker = function (dirHandler, fileHandler, options) {
	// defaults
	dirHandler = dirHandler || function () { };
	fileHandler = fileHandler || function () { };
	options = options || { filter: new RegExp('^.+\\.(wmv|avi|mov|mp4)$', 'ig'), hidden: false };

	var self = {
		// synchronous directory walking
		// when the function returns, the whole process has completed
		// - root: root path
		// - maxDepth: maximum depth
		walkSync: function (root, maxDepth) {
			var	fileCount = 0,
					hasMaxDepth = typeof maxDepth !== 'undefined';

			// recursive inner function
			// - relative: path relative to root
			console.log("WALKER - walking path: " + root + (hasMaxDepth ?  ", max depth: " + maxDepth : ""));

			(function walk(relative, depth) {
				if (++fileCount % 16 === 0) {
					process.stdout.write(".");
				}

				var	i,
						files,
						path = root + relative,
						stats;

				// obtaining file stats
				try {
					stats = $fs.lstatSync(path);
				} catch (e_exist) {
					throw "The specified path: " + path + " doesn't exist or is inaccessible.";
				}

				if (stats.isDirectory()) {
					// listing directory
					try {
						files = $fs.readdirSync(path);
					} catch (e_perm) {
						// returning on insufficient permissions
						return;
					}

					// calling directory callback
					dirHandler(relative, stats);

					// processing directory contents
					for (i = 0; i < files.length; i++) {
						// optionally excluding hidden files
						if ((options.hidden || files[i][0] !== '.') &&
							(!hasMaxDepth || depth < maxDepth)) {
							walk(relative + '/' + files[i], depth + 1);
						}
					}
				} else if (stats.isFile()) {
					// calling file handler
					if (path.match(options.filter)) {
						fileHandler(relative, stats);
					}
				}
			})('', 0);

			if (fileCount > 16) {
				process.stdout.write("\n");
			}

			return self;
		}
	};

	return self;
};

// exports
exports.walker = walker;

<commit_msg>mkv support<commit_after>////////////////////////////////////////////////////////////////////////////////
// Directory Walker
//
// Walks directories recursively and executes handlers on each object.
// Only synchronous walking is supported because async can only be done
// with CPS (continuation-passing style), which is complicated and adds
// restrictions to the callbacks.
////////////////////////////////////////////////////////////////////////////////
/*global require, exports, process, console */
var	$fs = require('fs'),

// - dirHandler: called for each directory
// - fileHandler: called for each file
// - options:
//   - filter: regex for filtering file names
walker = function (dirHandler, fileHandler, options) {
	// defaults
	dirHandler = dirHandler || function () { };
	fileHandler = fileHandler || function () { };
	options = options || { filter: new RegExp('^.+\\.(wmv|avi|mov|mp4|mkv)$', 'ig'), hidden: false };

	var self = {
		// synchronous directory walking
		// when the function returns, the whole process has completed
		// - root: root path
		// - maxDepth: maximum depth
		walkSync: function (root, maxDepth) {
			var	fileCount = 0,
					hasMaxDepth = typeof maxDepth !== 'undefined';

			// recursive inner function
			// - relative: path relative to root
			console.log("WALKER - walking path: " + root + (hasMaxDepth ?  ", max depth: " + maxDepth : ""));

			(function walk(relative, depth) {
				if (++fileCount % 16 === 0) {
					process.stdout.write(".");
				}

				var	i,
						files,
						path = root + relative,
						stats;

				// obtaining file stats
				try {
					stats = $fs.lstatSync(path);
				} catch (e_exist) {
					throw "The specified path: " + path + " doesn't exist or is inaccessible.";
				}

				if (stats.isDirectory()) {
					// listing directory
					try {
						files = $fs.readdirSync(path);
					} catch (e_perm) {
						// returning on insufficient permissions
						return;
					}

					// calling directory callback
					dirHandler(relative, stats);

					// processing directory contents
					for (i = 0; i < files.length; i++) {
						// optionally excluding hidden files
						if ((options.hidden || files[i][0] !== '.') &&
							(!hasMaxDepth || depth < maxDepth)) {
							walk(relative + '/' + files[i], depth + 1);
						}
					}
				} else if (stats.isFile()) {
					// calling file handler
					if (path.match(options.filter)) {
						fileHandler(relative, stats);
					}
				}
			})('', 0);

			if (fileCount > 16) {
				process.stdout.write("\n");
			}

			return self;
		}
	};

	return self;
};

// exports
exports.walker = walker;

<|endoftext|>


<commit_before>const expect = require('expect');
const request = require('supertest');

const { app } = require('./../server');
const { Todo } = require('./../models/todo');

beforeEach(done => {
  Todo.remove({}).then(() => done());
});

describe('POST /todos', () => {
  it('should create a new todo', done => {
    let text = 'Test todo text';

    request(app)
      .post('/todos')
      .send({ text })
      .expect(200)
      .expect(res => expect(res.body.text).toBe(text))
      .end((err, res) => {
        if (err) {
          return done(err);
        }
        Todo.find()
          .then(todos => {
            expect(todos.length).toBe(1);
            expect(todos[0].text).toBe(text);
            done();
          })
          .catch(e => done(e));
      });
  });

  it('should not create todo with invalid body data', done => {
    request(app).post('/todos').send({}).expect(400).end((err, res) => {
      if (err) {
        return done(err);
      }
      Todo.find()
        .then(todos => {
          expect(todos.length).toBe(0);
          done();
        })
        .catch(e => done(e));
    });
  });
});
<commit_msg>Add tests for GET /todos<commit_after>const expect = require('expect');
const request = require('supertest');

const { app } = require('./../server');
const { Todo } = require('./../models/todo');

const todos = [{ text: 'First test todo' }, { text: 'Second test todo' }];

beforeEach(done => {
  Todo.remove({})
    .then(() => {
      return Todo.insertMany(todos);
    })
    .then(() => done());
});

describe('POST /todos', () => {
  it('should create a new todo', done => {
    let text = 'Test todo text';

    request(app)
      .post('/todos')
      .send({ text })
      .expect(200)
      .expect(res => expect(res.body.text).toBe(text))
      .end((err, res) => {
        if (err) {
          return done(err);
        }
        Todo.find({ text })
          .then(todos => {
            expect(todos.length).toBe(1);
            expect(todos[0].text).toBe(text);
            done();
          })
          .catch(e => done(e));
      });
  });

  it('should not create todo with invalid body data', done => {
    request(app).post('/todos').send({}).expect(400).end((err, res) => {
      if (err) {
        return done(err);
      }
      Todo.find()
        .then(todos => {
          expect(todos.length).toBe(2);
          done();
        })
        .catch(e => done(e));
    });
  });
});

describe('GET /todos', () => {
  it('should create a new todo', done => {
    request(app)
      .get('/todos')
      .expect(200)
      .expect(res => {
        expect(res.body.todos.length).toBe(2);
      })
      .end(done);
  });
});
<|endoftext|>


<commit_before>'use strict';   // dont touch
var plugin = []; // dont touch
this.command = []; // dont touch
this.commandName = []; // dont touch
this.gamemodeId = []; // dont touch
this.gamemode = []; // dont touch
this.addToHelp = []; // dont touch

// [General]
this.name = "GiveMeMinionsToo"; // Name of plugin REQUIRED
this.author = "AJS - Dev"; // author REQUIRED
this.description = 'Gives minions to people randomly'; // Desciprtion
this.compatVersion = ''; // compatable with (optional)
this.version = '1.0.0'; // version REQUIRED

// [Extra Commands]
this.commandName[0] = "gmm"; // plugin add-on command names
this.addToHelp[0] = "gmm      : Give me minions command"; // help command add-on (adds this string to the help command)
this.command[0] = function(gameServer,split) {
  if (split[1] == "power") {
    gameServer.GMMpower = !gameServer.GMMpower;
    var s = gameServer.GMMpower ? "on" : "off";
    console.log("[Console] Turned " + s + " plugin");
    return;
  } else if (split[1] = "kill") {
    try {
   clearTimeout(gameServer.intervalTM)
   console.log("[Console] Successevly forced killed give me minions");
   return;
   } catch (e) {
     console.log("[Console] Failed to kill the givememinions plugin")
     return;
   }

  } else {
    console.log("[Console] Please specify a command! Available: Power, Kill");
  }

}; // extra command location

// [Extra Gamemodes]
this.gamemodeId[0] = ''; // gamemodeids of extra plugin gamemodes
this.gamemode[0] = ''; // gamemode location

// [Configs]
this.config = {
switchIntervalTime: 10000,
minionGiveAmount: 30,
botGetMinions: 1,
setPerInterval:  2

}
this.configfile = 'config.ini'

// [Functions]
this.init = function (gameServer, config) {
  this.config = config;
  gameServer.intervalTM;
  gameServer.GMMpower = true;
  gameServer.gmpid = [];
  try {
    clearTimeout(gameServer.intervalTM);
  } catch (e) {
    // nothing
  }
  this.start(gameServer);
  console.log("[Console] Give me minions running!")
  // init, Used to do stuff such as overriding things

};
this.getrandom = function(gameServer) {
  var newrandom = [];
  var a = 0;
  for (var i in gameServer.clients) { // protection, just in case
    if (this.config.botGetMinions == 1 && gameServer.clients[i] && gameServer.gmpid.indexOf(gameServer.clients[i].playerTracker.pID) == -1 && !gameServer.clients[i].playerTracker.owner) {
    newrandom[a] = gameServer.clients[i].playerTracker;
    a ++;
    } else if (gameServer.clients[i].playerTracker.socket.remoteAddress && gameServer.clients[i] && gameServer.gmpid.indexOf(gameServer.clients[i].playerTracker.pID) == -1 && !gameServer.clients[i].playerTracker.owner) {
      newrandom[a] = gameServer.clients[i].playerTracker;
    a ++;
    }
  }
  var item = newrandom[Math.floor(Math.random()*newrandom.length)];
  return item;
}

this.start = function(gameServer) {
  var inttim = function() {
  gameServer.intervalTM = setTimeout(function() {
    if (gameServer.running && gameServer.GMMpower) {
    var nsplit = [];
    nsplit[1] = "destroy";
    gameServer.consoleService.execCommand("minion", nsplit)
    for (var i = 0; i<this.config.setPerInterval; i++) {
      var random = this.getrandom(gameServer)
      gameServer.gmpid.push(random.pID)
      var nsplit = [];
      nsplit[1] = random.pID;
      nsplit[2] = this.config.minionGiveAmount;
      gameServer.consoleService.execCommand("minion", nsplit);
    }

    }
    inttim() // loop
  }.bind(this), this.config.switchIntervalTime)

  }.bind(this);
  inttim(); // startloop
}

this.onSecond = function (gameServer) {

  // called every second
};

module.exports = this; // dont touch
<commit_msg>Update index.js<commit_after>'use strict';   // dont touch
var plugin = []; // dont touch
this.command = []; // dont touch
this.commandName = []; // dont touch
this.gamemodeId = []; // dont touch
this.gamemode = []; // dont touch
this.addToHelp = []; // dont touch

// [General]
this.name = "GiveMeMinionsToo"; // Name of plugin REQUIRED
this.author = "AJS - Dev"; // author REQUIRED
this.description = 'Gives minions to people randomly'; // Desciprtion
this.compatVersion = ''; // compatable with (optional)
this.version = '1.0.0'; // version REQUIRED

// [Extra Commands]
this.commandName[0] = "gmm"; // plugin add-on command names
this.addToHelp[0] = "gmm      : Give me minions command"; // help command add-on (adds this string to the help command)
this.command[0] = function(gameServer,split) {
  if (split[1] == "power") {
    gameServer.GMMpower = !gameServer.GMMpower;
    var s = gameServer.GMMpower ? "on" : "off";
    console.log("[Console] Turned " + s + " plugin");
    return;
  } else if (split[1] = "kill") {
    try {
   clearTimeout(gameServer.intervalTM)
   console.log("[Console] Successevly forced killed give me minions");
   return;
   } catch (e) {
     console.log("[Console] Failed to kill the givememinions plugin")
     return;
   }

  } else {
    console.log("[Console] Please specify a command! Available: Power, Kill");
  }

}; // extra command location

// [Extra Gamemodes]
this.gamemodeId[0] = ''; // gamemodeids of extra plugin gamemodes
this.gamemode[0] = ''; // gamemode location

// [Configs]
this.config = {
switchIntervalTime: 10000,
minionGiveAmount: 30,
botGetMinions: 1,
setPerInterval:  2

}
this.configfile = 'config.ini'

// [Functions]
this.init = function (gameServer, config) {
  this.config = config;
  gameServer.intervalTM;
  gameServer.GMMpower = true;
  gameServer.gmpid = [];
  try {
    clearTimeout(gameServer.intervalTM);
  } catch (e) {
    // nothing
  }
  this.start(gameServer);
  console.log("[Console] Give me minions running!")
  // init, Used to do stuff such as overriding things

};
this.getrandom = function(gameServer) {
  var newrandom = [];
  var a = 0;
  for (var i in gameServer.clients) { // protection, just in case
    if (this.config.botGetMinions == 1 && gameServer.clients[i] && gameServer.gmpid.indexOf(gameServer.clients[i].playerTracker.pID) == -1 && !gameServer.clients[i].playerTracker.owner) {
    newrandom[a] = gameServer.clients[i].playerTracker;
    a ++;
    } else if (gameServer.clients[i].playerTracker.socket.remoteAddress && gameServer.clients[i] && gameServer.gmpid.indexOf(gameServer.clients[i].playerTracker.pID) == -1 && !gameServer.clients[i].playerTracker.owner) {
      newrandom[a] = gameServer.clients[i].playerTracker;
    a ++;
    }
  }
  var item = newrandom[Math.floor(Math.random()*newrandom.length)];
  return item;
}

this.start = function(gameServer) {
  var inttim = function() {
  gameServer.intervalTM = setTimeout(function() {
    if (gameServer.running && gameServer.GMMpower) {
    var nsplit = [];
    nsplit[1] = "destroy";
    gameServer.consoleService.execCommand("minion", nsplit)
    for (var i = 0; i<this.config.setPerInterval; i++) {
      var random = this.getrandom(gameServer)
      if (!random) break;
      gameServer.gmpid.push(random.pID)
      var nsplit = [];
      nsplit[1] = random.pID;
      nsplit[2] = this.config.minionGiveAmount;
      gameServer.consoleService.execCommand("minion", nsplit);
    }

    }
    inttim() // loop
  }.bind(this), this.config.switchIntervalTime)

  }.bind(this);
  inttim(); // startloop
}

this.onSecond = function (gameServer) {

  // called every second
};

module.exports = this; // dont touch
<|endoftext|>


<commit_before>'use strict';

var uuid = require('uuid');
var logtron = require('logtron');
var RelayRequest = require('./relay-request.js');

module.exports = Endpoints;

function Endpoints(app) {
    if (!(this instanceof Endpoints)) {
        return new Endpoints(app);
    }

    var self = this;

    self.app = app;
    var channel = self.app.clients.loggerChannel;
    var thrift = self.app.clients.tchannelThrift;

    var endpointHandler = channel.handler;
    endpointHandler.logger = channel.logger;
    thrift.register(endpointHandler, 'Logger::init', app, self.init);
    thrift.register(endpointHandler, 'Logger::log', app, self.log);

    channel.handler = RingpopHandler({
        realHandler: endpointHandler,
        channel: self.app.clients.ringpopChannel,
        ringpop: self.app.clients.ringpop
    });
}

function RingpopHandler(options) {
    if (!(this instanceof RingpopHandler)) {
        return new RingpopHandler(options);
    }

    var self = this;

    self.realHandler = options.realHandler;
    self.ringpop = options.ringpop;
    self.channel = options.channel;
}

RingpopHandler.prototype.handleRequest =
function handleRequest(req, buildRes) {
    var self = this;

    var shardKey = req.headers.shardKey;
    if (!shardKey) {
        req.headers.shardKey = shardKey = uuid();
    }

    var dest = self.ringpop.lookup(shardKey);
    if (self.ringpop.whoami() === dest) {
        return self.realHandler.handleRequest(req, buildRes);
    }

    var outreq = new RelayRequest(self.channel, req, buildRes);
    outreq.createOutRequest(dest);
};

Endpoints.prototype.init =
function init(app, req, head, body, cb) {
    var logger = logtron({
        meta: {
            team: body.team,
            project: body.project
        },
        backends: logtron.defaultBackends({
            kafka: {
                leafHost: body.kafkaHost,
                leafPort: body.kafkaPort
            }
        })
    });
    var token = req.headers.shardKey;

    app.loggerInstances[token] = logger;

    cb(null, {
        ok: true,
        body: {
            token: token
        }
    });
};

Endpoints.prototype.log =
function log(app, req, head, body, cb) {
    var logger = app.loggerInstances[req.headers.shardKey];

    logger[body.level](body.message, {}, onLogged);

    function onLogged() {
        cb(null, {
            ok: true,
            body: null
        });
    }
};
<commit_msg>use the logger channel<commit_after>'use strict';

var uuid = require('uuid');
var logtron = require('logtron');
var RelayRequest = require('./relay-request.js');

module.exports = Endpoints;

function Endpoints(app) {
    if (!(this instanceof Endpoints)) {
        return new Endpoints(app);
    }

    var self = this;

    self.app = app;
    var channel = self.app.clients.loggerChannel;
    var thrift = self.app.clients.tchannelThrift;

    var endpointHandler = channel.handler;
    endpointHandler.logger = channel.logger;
    thrift.register(endpointHandler, 'Logger::init', app, self.init);
    thrift.register(endpointHandler, 'Logger::log', app, self.log);

    channel.handler = RingpopHandler({
        realHandler: endpointHandler,
        channel: self.app.clients.loggerChannel,
        ringpop: self.app.clients.ringpop
    });
}

function RingpopHandler(options) {
    if (!(this instanceof RingpopHandler)) {
        return new RingpopHandler(options);
    }

    var self = this;

    self.realHandler = options.realHandler;
    self.ringpop = options.ringpop;
    self.channel = options.channel;
}

RingpopHandler.prototype.handleRequest =
function handleRequest(req, buildRes) {
    var self = this;

    var shardKey = req.headers.shardKey;
    if (!shardKey) {
        req.headers.shardKey = shardKey = uuid();
    }

    var dest = self.ringpop.lookup(shardKey);
    if (self.ringpop.whoami() === dest) {
        return self.realHandler.handleRequest(req, buildRes);
    }

    var outreq = new RelayRequest(self.channel, req, buildRes);
    outreq.createOutRequest(dest);
};

Endpoints.prototype.init =
function init(app, req, head, body, cb) {
    var logger = logtron({
        meta: {
            team: body.team,
            project: body.project
        },
        backends: logtron.defaultBackends({
            kafka: {
                leafHost: body.kafkaHost,
                leafPort: body.kafkaPort
            }
        })
    });
    var token = req.headers.shardKey;

    app.loggerInstances[token] = logger;

    cb(null, {
        ok: true,
        body: {
            token: token
        }
    });
};

Endpoints.prototype.log =
function log(app, req, head, body, cb) {
    var logger = app.loggerInstances[req.headers.shardKey];

    logger[body.level](body.message, {}, onLogged);

    function onLogged() {
        cb(null, {
            ok: true,
            body: null
        });
    }
};
<|endoftext|>


<commit_before><commit_msg>Added Jefferson County Public Library.<commit_after><|endoftext|>


<commit_before>import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router-dom';
import Billing from './Billing';

class Header extends Component {
  renderLoggedInNav() {
    switch (this.props.auth) {
      case null:
        return 'Updating...';
      case false:
        return Login With Google;
      default:
        return [

<Billing />
,

Logout
,
        ];
    }
  }

  render() {
    const brandLink = (this.props.auth) ? '/surveys' : '/';
    return (

          <Link
            to={brandLink}
            className="left brand-logo"
          >
            Campaigner
          </Link>

            {this.renderLoggedInNav()}

    );
  }
}

function mapStateToProps({ auth }) {
  return { auth };
}

export default connect(mapStateToProps)(Header);
<commit_msg>Added credit value to header<commit_after>import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router-dom';
import Billing from './Billing';

class Header extends Component {
  renderLoggedInNav() {
    switch (this.props.auth) {
      case null:
        return 'Updating...';
      case false:
        return Login With Google;
      default:
        return [

<Billing />
,

            Credits: {this.props.auth.credits}

,

Logout
,
        ];
    }
  }

  render() {
    const brandLink = (this.props.auth) ? '/surveys' : '/';
    return (

          <Link
            to={brandLink}
            className="left brand-logo"
          >
            Campaigner
          </Link>

            {this.renderLoggedInNav()}

    );
  }
}

function mapStateToProps({ auth }) {
  return { auth };
}

export default connect(mapStateToProps)(Header);
<|endoftext|>


<commit_before>const { getVehiclesInRange, updateVehicleStatus, getVehicle, getVehicles, updateVehiclePosition, getPosition, getLatestPositionUpdate } = require('../store/vehicles');
const { getBidsForRequest } = require('../store/bids');
const { getLatestMission, updateMission } = require('../store/missions');
const { createMissionUpdate } = require('../store/mission_updates');
const { hasStore } = require('../lib/environment');
const missionProgress = require('../simulation/missionProgress');
const { calculateNextCoordinate } = require('../simulation/vehicles');

const getStatus = async (req, res) => {
  const { lat, long, requestId, user_id } = req.query;
  const status = 'idle';
  const latestMission = await getLatestMission(user_id);
  const bids = (!hasStore() || !requestId) ? [] : await getBidsForRequest(requestId);
  let vehicles = [];
  if (hasStore()) {
    if (bids.length > 0) {
      vehicles = await getVehicles(bids.map(bid => bid.vehicle_id));
    } else {
      vehicles = await getVehiclesInRange(
        { lat: parseFloat(lat), long: parseFloat(long) },
        7000,
      );
    }
  }

  if (latestMission) {
    switch (latestMission.status) {
    case 'awaiting_signatures': {
      let elapsedTime = Date.now() - latestMission.user_signed_at;
      let elapsedSeconds = ((elapsedTime % 60000) / 1000).toFixed(0);
      if (elapsedSeconds > 6) {
        await updateMission(latestMission.mission_id, {'vehicle_signed_at': Date.now(), 'status': 'in_progress'});
        await updateVehicleStatus(latestMission.vehicle_id, 'travelling_pickup');
        await createMissionUpdate(latestMission.mission_id, 'travelling_pickup');
      }
      res.json({status, vehicles, bids});
      break;
    }
    case 'in_progress': {
      const mission = latestMission;
      let vehicle = await getVehicle(latestMission.vehicle_id);
      const status = 'in_mission';
      const currentStatus = missionProgress[vehicle.status];

      if (currentStatus.conditionForNextUpdate(latestMission)){
        const timestampString = currentStatus.nextMissionUpdate + '_at';
        let timestampObject = {};
        timestampObject[timestampString] = Date.now();
        await updateMission(latestMission.mission_id, timestampObject);
        await createMissionUpdate(latestMission.mission_id, currentStatus.nextMissionUpdate);
        await updateVehicleStatus(latestMission.vehicle_id, currentStatus.nextVehicleStatus);
      }

      if (currentStatus.nextMissionStatus){
        await updateMission(latestMission.mission_id, {status: currentStatus.nextMissionStatus});
      }

      if (currentStatus.vehicleIsMoving){
        const leg = vehicle.status.split('_')[1]; // pickup or dropoff
        const latestPositionUpdate = await getLatestPositionUpdate(vehicle);
        const positionLastUpdatedAt = latestPositionUpdate[1];
        const previousPosition =  await getPosition(latestPositionUpdate[0]);
        const newCoords = await calculateNextCoordinate(vehicle, mission, leg, positionLastUpdatedAt, previousPosition);
        await updateVehiclePosition(vehicle, newCoords.long, newCoords.lat);
        // refresh vehicle object
        vehicle = await getVehicle(vehicle.id);
      }

      vehicles = [vehicle];
      res.json({status, vehicles, bids, mission});
      break;
    }
    }
  } else {
    res.json({ status, vehicles, bids });
  }
};

module.exports = { getStatus };
<commit_msg>fix: create default case when switching on mission status<commit_after>const { getVehiclesInRange, updateVehicleStatus, getVehicle, getVehicles, updateVehiclePosition, getPosition, getLatestPositionUpdate } = require('../store/vehicles');
const { getBidsForRequest } = require('../store/bids');
const { getLatestMission, updateMission } = require('../store/missions');
const { createMissionUpdate } = require('../store/mission_updates');
const { hasStore } = require('../lib/environment');
const missionProgress = require('../simulation/missionProgress');
const { calculateNextCoordinate } = require('../simulation/vehicles');

const getStatus = async (req, res) => {
  const { lat, long, requestId, user_id } = req.query;
  const status = 'idle';
  const latestMission = await getLatestMission(user_id);
  const bids = (!hasStore() || !requestId) ? [] : await getBidsForRequest(requestId);
  let vehicles = [];
  if (hasStore()) {
    if (bids.length > 0) {
      vehicles = await getVehicles(bids.map(bid => bid.vehicle_id));
    } else {
      vehicles = await getVehiclesInRange(
        { lat: parseFloat(lat), long: parseFloat(long) },
        7000,
      );
    }
  }

  if (latestMission) {
    switch (latestMission.status) {
    case 'awaiting_signatures': {
      let elapsedTime = Date.now() - latestMission.user_signed_at;
      let elapsedSeconds = ((elapsedTime % 60000) / 1000).toFixed(0);
      if (elapsedSeconds > 6) {
        await updateMission(latestMission.mission_id, {'vehicle_signed_at': Date.now(), 'status': 'in_progress'});
        await updateVehicleStatus(latestMission.vehicle_id, 'travelling_pickup');
        await createMissionUpdate(latestMission.mission_id, 'travelling_pickup');
      }
      res.json({status, vehicles, bids});
      break;
    }
    case 'in_progress': {
      const mission = latestMission;
      let vehicle = await getVehicle(latestMission.vehicle_id);
      const status = 'in_mission';
      const currentStatus = missionProgress[vehicle.status];

      if (currentStatus.conditionForNextUpdate(latestMission)){
        const timestampString = currentStatus.nextMissionUpdate + '_at';
        let timestampObject = {};
        timestampObject[timestampString] = Date.now();
        await updateMission(latestMission.mission_id, timestampObject);
        await createMissionUpdate(latestMission.mission_id, currentStatus.nextMissionUpdate);
        await updateVehicleStatus(latestMission.vehicle_id, currentStatus.nextVehicleStatus);
      }

      if (currentStatus.nextMissionStatus){
        await updateMission(latestMission.mission_id, {status: currentStatus.nextMissionStatus});
      }

      if (currentStatus.vehicleIsMoving){
        const leg = vehicle.status.split('_')[1]; // pickup or dropoff
        const latestPositionUpdate = await getLatestPositionUpdate(vehicle);
        const positionLastUpdatedAt = latestPositionUpdate[1];
        const previousPosition =  await getPosition(latestPositionUpdate[0]);
        const newCoords = await calculateNextCoordinate(vehicle, mission, leg, positionLastUpdatedAt, previousPosition);
        await updateVehiclePosition(vehicle, newCoords.long, newCoords.lat);
        // refresh vehicle object
        vehicle = await getVehicle(vehicle.id);
      }

      vehicles = [vehicle];
      res.json({status, vehicles, bids, mission});
      break;
    }
    default: {
      res.json({ status, vehicles, bids });
    }
    }
  } else {
    res.json({ status, vehicles, bids });
  }
};

module.exports = { getStatus };
<|endoftext|>


<commit_before>var Highscore = require('../models/highscore.js');
var Highscores = require('../collections/highScoreCollection.js');
var prompts = require('./prompts');
var fs = require('fs');
var path = require('path');

var handlers = {};

var jsFiles = [
		'00-forloop',
		'01-size',
		'02-fizzbuzz',
		'03-jqueryclick',
    '04-slimredux-mapValues',
    '05-slimredux-combineReducers',
    '06-es6-letVariable',
    '07-es6-class',
    '08-es6-promise'
	];

var getRandomJS = function(){
	return jsFiles[Math.floor(Math.random() * jsFiles.length)];
};

handlers.updateHighScore = function(req, res){
	// req.puzzleName = "02-ljsdsdlkf";
	// req.recording = "Existed";
	// req.username = '';
	console.log('promptcontroller.js : updateHighScore being called');
	console.log(req.body);

	new Highscore({ puzzleName: req.body.puzzleName }).fetch()
		.then(function(found) {
      if(found){
        Highscore.where({puzzleName: req.body.puzzleName})
        .destroy()
        .then(function(model){
          new Highscore({
            puzzleName: req.body.puzzleName,
            username: req.body.username,
            recording: req.body.recording
          })
          .save()
          .then(function(highscore){
            res.send(highscore);
          });
        });
      }else{
        new Highscore({
          puzzleName: req.body.puzzleName,
          username: req.body.username,
          recording: req.body.recording
        })
        .save()
        .then(function(highscore){
          res.send(highscore);
        });
      }
    });
};

handlers.getHighScore = function(req, res) {
	var puzzleName = req.query.promptName;
	console.log(puzzleName);

	new Highscore({ puzzleName: puzzleName }).fetch()
			.then(function(found) {
				if (found) {
					console.log('Found record', found);
					res.send(found);
				} else {
					res.send(null);
				}
			});
}

handlers.registerRandomPrompt = function(){
	return fs.readFileSync(path.join(__dirname, '../library/prompts/' + /*req.data.language  ||*/  'js/' + /*req.data.prompt ||*/ getRandomJS() + '.js'), 'utf-8');
};

handlers.random = function(req, res){
	// console.log("__dirname", __dirname);

	fs.readFile(path.join(__dirname, '../library/prompts/' + /*req.data.language  ||*/  'js/' + /*req.data.prompt ||*/ getRandomJS() + '.js'), 'utf-8', function(err, data){
		console.log(err);
		// console.log(data);
		res.send(data);
	});
};

handlers.specific = function(req, res){

	// If query parameter is received, serve specific puzzle, otherwise serve up first puzzle
	if (req.query.puzzleName) {
		puzzleName = req.query.puzzleName;
	} else {
		puzzleName = jsFiles[0];
	}

	fs.readFile(path.join(__dirname, '../library/prompts/' + /*req.data.language  ||*/  'js/' + puzzleName + '.js'), 'utf-8', function(err, data){
		console.log(err);
		// console.log(data);
		res.send(data);
	});

}

handlers.getAllPrompts = function(req, res) {
	res.send(jsFiles);
}

module.exports = handlers;
<commit_msg>[cleanup] edits tabbing/spacing to promptController<commit_after>var Highscore = require('../models/highscore.js');
var Highscores = require('../collections/highScoreCollection.js');
var prompts = require('./prompts');
var fs = require('fs');
var path = require('path');

var handlers = {};

var jsFiles = [
    '00-forloop',
    '01-size',
    '02-fizzbuzz',
    '03-jqueryclick',
    '04-slimredux-mapValues',
    '05-slimredux-combineReducers',
    '06-es6-letVariable',
    '07-es6-class',
    '08-es6-promise'
  ];

var getRandomJS = function(){
  return jsFiles[Math.floor(Math.random() * jsFiles.length)];
};

handlers.updateHighScore = function(req, res){
  // req.puzzleName = "02-ljsdsdlkf";
  // req.recording = "Existed";
  // req.username = '';
  console.log('promptcontroller.js : updateHighScore being called');
  console.log(req.body);

  new Highscore({ puzzleName: req.body.puzzleName }).fetch()
    .then(function(found) {
      if(found){
        Highscore.where({puzzleName: req.body.puzzleName})
        .destroy()
        .then(function(model){
          new Highscore({
            puzzleName: req.body.puzzleName,
            username: req.body.username,
            recording: req.body.recording
          })
          .save()
          .then(function(highscore){
            res.send(highscore);
          });
        });
      }else{
        new Highscore({
          puzzleName: req.body.puzzleName,
          username: req.body.username,
          recording: req.body.recording
        })
        .save()
        .then(function(highscore){
          res.send(highscore);
        });
      }
    });
};

handlers.getHighScore = function(req, res) {
  var puzzleName = req.query.promptName;
  console.log(puzzleName);

  new Highscore({ puzzleName: puzzleName }).fetch()
      .then(function(found) {
        if (found) {
          console.log('Found record', found);
          res.send(found);
        } else {
          res.send(null);
        }
      });
}

handlers.registerRandomPrompt = function(){
  return fs.readFileSync(path.join(__dirname, '../library/prompts/' + /*req.data.language  ||*/  'js/' + /*req.data.prompt ||*/ getRandomJS() + '.js'), 'utf-8');
};

handlers.random = function(req, res){
  // console.log("__dirname", __dirname);

  fs.readFile(path.join(__dirname, '../library/prompts/' + /*req.data.language  ||*/  'js/' + /*req.data.prompt ||*/ getRandomJS() + '.js'), 'utf-8', function(err, data){
    console.log(err);
    // console.log(data);
    res.send(data);
  });
};

handlers.specific = function(req, res){

  // If query parameter is received, serve specific puzzle, otherwise serve up first puzzle
  if (req.query.puzzleName) {
    puzzleName = req.query.puzzleName;
  } else {
    puzzleName = jsFiles[0];
  }

  fs.readFile(path.join(__dirname, '../library/prompts/' + /*req.data.language  ||*/  'js/' + puzzleName + '.js'), 'utf-8', function(err, data){
    console.log(err);
    // console.log(data);
    res.send(data);
  });

}

handlers.getAllPrompts = function(req, res) {
  res.send(jsFiles);
}

module.exports = handlers;
<|endoftext|>


<commit_before>/**
 * Backend controller for handling search queries.
 */

'use strict';
var requestify = require('requestify');
var when = require('when');
var _ = require('lodash');
var MusicJsonToolbox = require('musicjson-toolbox');
var databaseService = require('../services/databaseService');
var databaseConfig = require('../config/database.config.json');

var that = {};

var store = {
  solrResults: [],
  solrQuery: null,
  solrResponse: null,
  melodyMode: null,
  melodyQuery: null,
  melodyResponse: {
    results: [],
    rankingFactor: 0
  },
  res: null
};

/**
 * Merges results of solr and melody search.
 * @returns {Array.<object>} The merged results, that should be returned to the user
 * @private
 */
var _mergeResults = function() {
  var results = store.melodyResponse.results;

  _.each(store.solrResults, function(solrResult) {
    var find = _.find(results, function(result) {
      return result.id === solrResult.id;
    });

    if (find) {
      find.metadata = solrResult.metadata;
      find.highlighting = solrResult.highlighting;
      find.rank += solrResult.rank;
    } else {
      solrResult.rank += store.melodyResponse.rankingFactor;
      results.push(solrResult)
    }

  });

  return results.sort(function(a, b) {
    return a.rank - b.rank;
  });
};

/**
 * Handle POST request for search form.
 * @param {object} req - request object
 * @param {object} res - response object
 */
var search = function(req, res) {
  // Reset stored variables from earlier search sessions
  _resetStore();

  // Update stored search
  store.solrQuery = req.body.solrQuery;
  store.melodyMode = req.body.melodyMode;
  store.melodyQuery = req.body.melodyQuery;
  store.res = res;

  // Determine callback by melody mode
  var callback = null;
  if (store.melodyQuery) {
    switch(store.melodyMode) {
      case 'MELODY':
        callback = _searchMelody;
        break;

      case 'INTERVALS':
        callback = _searchIntervals;
        break;

      case 'PARSONS':
        callback = _searchParson;
        break;
    }
  }

  // Request solr API if necessary
  if (store.solrQuery !== false) {
    var solrRequest = requestify.get(store.solrQuery);
    return _handleSolrSearch(when(solrRequest), callback);
  } else {
    callback();
  }
};

/**
 * Manages response from solr search
 * @param {Promise} solrSearchPromise - The solr search promise
 * @param {onSolrCallback} callback - The callback function defined by melody search mode
 * @private
 */
var _handleSolrSearch = function(solrSearchPromise, callback) {
  return solrSearchPromise
    .then(function(response) {
      var solrResponse = response.getBody();
      var highlights = [];
      for (var item in solrResponse.highlighting) {
        if (!solrResponse.highlighting.hasOwnProperty(item)) continue;
        highlights.push({
          id: item,
          fields: solrResponse.highlighting[item]
        });
      }

      var solrResults = [];
      // Preprocess solr response
      for (var i = 0; i < solrResponse.response.docs.length; i++) {
        solrResults.push({
          id: solrResponse.response.docs[i].signature,
          metadata: solrResponse.response.docs[i],
          highlighting: _.find(highlights, function(item) {
            return item.id === solrResponse.response.docs[i].id;
          }),
          rank: i
        });
      }

      // store solr response for later usage
      store.solrResults = solrResults;

      if (callback !== null) {
        callback();
      } else {
        _handleResults();
      }
    });
};

/**
 * Triggers result merging and sends response through response object.
 * @private
 */
var _handleResults = function() {
  var results = _mergeResults();

  // send results
  store.res.json(results);
};

/**
 * Reset stored variables from earlier search sessions.
 * @private
 */
var _resetStore = function() {
  store = {
    solrResults: [],
    solrQuery: null,
    solrResponse: null,
    melodyMode: null,
    melodyQuery: null,
    melodyResponse: {
      results: [],
      rankingFactor: 0
    },
    res: null
  };
};

/**
 * Search in songsheets by parsons code
 * @callback onSolrCallback
 * @private
 */
var _searchParson = function() {
  var parson = '*' + store.melodyQuery.parson;
  var threshold = store.melodyQuery.threshold / 100;
  databaseService.getCollection(
    databaseConfig.collections.songsheets,
    0,
    0,
    function(songsheets, count) {
      var results = [];
      for (var i = 0; i < count; i++) {
        // Calculate similarities between songsheets and search
        var similarities = MusicJsonToolbox.parsonsNgramSimilarity(songsheets[i].json, parson);

        // Determine maximum similarity
        var maxSimilarity = Math.max(...similarities.map(function(item) {
          return item.similarity;
        }));

        // only return results above threshold
        if (maxSimilarity >= threshold) {
          results.push({
            id: songsheets[i].signature,
            abc: songsheets[i].abc,
            json: songsheets[i].json,
            melodic: similarities,
            maxSimilarity: maxSimilarity,
            rank: 1 - maxSimilarity
          });
        }
      }

      // store response
      store.melodyResponse = {
        results: results.sort(function(a, b) {
          return a.rank - b.rank;
        }),
        rankingFactor: parson.length
      };
      _handleResults();
    }
  );
};

/**
 * Search in songsheets by intervals
 * @callback onSolrCallback
 * @private
 */
var _searchIntervals = function() {
  var defaultIntervals = ['*'];
  var intervals = defaultIntervals.concat(store.melodyQuery.intervals.split(' ').map(function(item) {
    return parseInt(item);
  }));
  var threshold = store.melodyQuery.threshold / 100;
  databaseService.getCollection(
    databaseConfig.collections.songsheets,
    0,
    0,
    function(songsheets, count) {
      var results = [];
      for (var i = 0; i < count; i++) {
        // Calculate similarities between songsheets and search
        var similarities = MusicJsonToolbox.intervalNgramSimilarity(songsheets[i].json, intervals);

        // Determine maximum similarity
        var maxSimilarity = Math.max(...similarities.map(function(item) {
          return item.similarity;
        }));

        // only return results above threshold
        if (maxSimilarity >= threshold) {
          results.push({
            id: songsheets[i].signature,
            abc: songsheets[i].abc,
            json: songsheets[i].json,
            melodic: similarities,
            maxSimilarity: maxSimilarity,
            rank: 1 - maxSimilarity
          });
        }
      }

      // store response
      store.melodyResponse = {
        results: results.sort(function(a, b) {
          return a.rank - b.rank;
        }),
        rankingFactor: intervals.length
      };
      _handleResults();
    }
  );
};

/**
 * Search in songsheets by pitch and duration
 * @callback onSolrCallback
 * @private
 */
var _searchMelody = function() {
  var melody = store.melodyQuery.melody;
  var threshold = store.melodyQuery.threshold / 100;
  databaseService.getCollection(
    databaseConfig.collections.songsheets,
    0,
    0,
    function(songsheets, count) {
      var results = [];
      for (var i = 0; i < count; i++) {
        // Calculate distance between songsheets and search
        var similarities = MusicJsonToolbox.pitchDurationNgramSimilarity(
          songsheets[i].json,
          MusicJsonToolbox.pitchDurationValues(
            melody,
            0, 16, 4
          )
        );

        // Determine minimum distance
        var maxSimilarity = Math.max(...similarities.map(function(item) {
          return item.similarity;
        }));

        // only return results above threshold
        if (maxSimilarity >= threshold) {
          results.push({
            id: songsheets[i].signature,
            abc: songsheets[i].abc,
            json: songsheets[i].json,
            melodic: similarities,
            maxSimilarity: maxSimilarity,
            rank: 1 - maxSimilarity
          });
        }
      }

      // store response
      store.melodyResponse = {
        results: results.sort(function(a, b) {
          return a.rank - b.rank;
        }),
        rankingFactor: melody.length
      };
      _handleResults();
    }
  );
};

that.search = search;

module.exports = that;<commit_msg>Update search ranking (include penalty for results that match in melody but not in metadata)<commit_after>/**
 * Backend controller for handling search queries.
 */

'use strict';
var requestify = require('requestify');
var when = require('when');
var _ = require('lodash');
var MusicJsonToolbox = require('musicjson-toolbox');
var databaseService = require('../services/databaseService');
var databaseConfig = require('../config/database.config.json');

var that = {};

var store = {
  solrResults: [],
  solrQuery: null,
  solrResponse: null,
  melodyMode: null,
  melodyQuery: null,
  melodyResponse: {
    results: [],
    rankingFactor: 0
  },
  res: null
};

/**
 * Merges results of solr and melody search.
 * @returns {Array.<object>} The merged results, that should be returned to the user
 * @private
 */
var _mergeResults = function() {
  var results = store.melodyResponse.results;

  _.each(store.solrResults, function(solrResult) {
    var find = _.find(results, function(result) {
      return result.id === solrResult.id;
    });

    if (find) {
      find.metadata = solrResult.metadata;
      find.highlighting = solrResult.highlighting;
      find.rank += solrResult.rank;
    } else {
      solrResult.rank += store.melodyResponse.rankingFactor;
      results.push(solrResult)
    }

  });

  _.each(results, function(melodyResult) {
    var find = _.find(store.solrResults, function(solrResult) {
      return solrResult.id === melodyResult.id;
    });

    if (!find) {
      melodyResult.rank += 0.1;
    }
  });

  return results.sort(function(a, b) {
    return a.rank - b.rank || b.maxSimilarityCount - a.maxSimilarityCount;
  });
};

/**
 * Handle POST request for search form.
 * @param {object} req - request object
 * @param {object} res - response object
 */
var search = function(req, res) {
  // Reset stored variables from earlier search sessions
  _resetStore();

  // Update stored search
  store.solrQuery = req.body.solrQuery;
  store.melodyMode = req.body.melodyMode;
  store.melodyQuery = req.body.melodyQuery;
  store.res = res;

  // Determine callback by melody mode
  var callback = null;
  if (store.melodyQuery) {
    switch(store.melodyMode) {
      case 'MELODY':
        callback = _searchMelody;
        break;

      case 'INTERVALS':
        callback = _searchIntervals;
        break;

      case 'PARSONS':
        callback = _searchParson;
        break;
    }
  }

  // Request solr API if necessary
  if (store.solrQuery !== false) {
    var solrRequest = requestify.get(store.solrQuery);
    return _handleSolrSearch(when(solrRequest), callback);
  } else {
    callback();
  }
};

/**
 * Manages response from solr search
 * @param {Promise} solrSearchPromise - The solr search promise
 * @param {onSolrCallback} callback - The callback function defined by melody search mode
 * @private
 */
var _handleSolrSearch = function(solrSearchPromise, callback) {
  return solrSearchPromise
    .then(function(response) {
      var solrResponse = response.getBody();
      var highlights = [];
      for (var item in solrResponse.highlighting) {
        if (!solrResponse.highlighting.hasOwnProperty(item)) continue;
        highlights.push({
          id: item,
          fields: solrResponse.highlighting[item]
        });
      }

      var solrResults = [];
      // Preprocess solr response
      for (var i = 0; i < solrResponse.response.docs.length; i++) {
        solrResults.push({
          id: solrResponse.response.docs[i].signature,
          metadata: solrResponse.response.docs[i],
          highlighting: _.find(highlights, function(item) {
            return item.id === solrResponse.response.docs[i].id;
          }),
          maxSimilarityCount: 0,
          rank: i / solrResponse.response.docs.length / 10
        });
      }

      // store solr response for later usage
      store.solrResults = solrResults;

      if (callback !== null) {
        callback();
      } else {
        _handleResults();
      }
    });
};

/**
 * Triggers result merging and sends response through response object.
 * @private
 */
var _handleResults = function() {
  var results = _mergeResults();

  // send results
  store.res.json(results);
};

/**
 * Reset stored variables from earlier search sessions.
 * @private
 */
var _resetStore = function() {
  store = {
    solrResults: [],
    solrQuery: null,
    solrResponse: null,
    melodyMode: null,
    melodyQuery: null,
    melodyResponse: {
      results: [],
      rankingFactor: 0
    },
    res: null
  };
};

/**
 * Search in songsheets by parsons code
 * @callback onSolrCallback
 * @private
 */
var _searchParson = function() {
  var parson = '*' + store.melodyQuery.parson;
  var threshold = store.melodyQuery.threshold / 100;
  databaseService.getCollection(
    databaseConfig.collections.songsheets,
    0,
    0,
    function(songsheets, count) {
      var results = [];
      for (var i = 0; i < count; i++) {
        // Calculate similarities between songsheets and search
        var similarities = MusicJsonToolbox.parsonsNgramSimilarity(songsheets[i].json, parson);

        // Determine maximum similarity
        var maxSimilarity = Math.max(...similarities.map(function(item) {
          return item.similarity;
        }));

        // only return results above threshold
        if (maxSimilarity >= threshold) {
          let maxSimilarityCount = similarities.filter(function(item) {
            return item.similarity === maxSimilarity;
          }).length;
          results.push({
            id: songsheets[i].signature,
            abc: songsheets[i].abc,
            json: songsheets[i].json,
            melodic: similarities,
            maxSimilarity: maxSimilarity,
            maxSimilarityCount: maxSimilarityCount,
            rank: 1 - maxSimilarity
          });
        }
      }

      // store response
      store.melodyResponse = {
        results: results.sort(function(a, b) {
          return a.rank - b.rank;
        }),
        rankingFactor: 1
      };
      _handleResults();
    }
  );
};

/**
 * Search in songsheets by intervals
 * @callback onSolrCallback
 * @private
 */
var _searchIntervals = function() {
  var defaultIntervals = ['*'];
  var intervals = defaultIntervals.concat(store.melodyQuery.intervals.split(' ').map(function(item) {
    return parseInt(item);
  }));
  var threshold = store.melodyQuery.threshold / 100;
  databaseService.getCollection(
    databaseConfig.collections.songsheets,
    0,
    0,
    function(songsheets, count) {
      var results = [];
      for (var i = 0; i < count; i++) {
        // Calculate similarities between songsheets and search
        var similarities = MusicJsonToolbox.intervalNgramSimilarity(songsheets[i].json, intervals);

        // Determine maximum similarity
        var maxSimilarity = Math.max(...similarities.map(function(item) {
          return item.similarity;
        }));

        // only return results above threshold
        if (maxSimilarity >= threshold) {
          let maxSimilarityCount = similarities.filter(function(item) {
            return item.similarity === maxSimilarity;
          }).length;
          results.push({
            id: songsheets[i].signature,
            abc: songsheets[i].abc,
            json: songsheets[i].json,
            melodic: similarities,
            maxSimilarity: maxSimilarity,
            maxSimilarityCount: maxSimilarityCount,
            rank: 1 - maxSimilarity
          });
        }
      }

      // store response
      store.melodyResponse = {
        results: results.sort(function(a, b) {
          return a.rank - b.rank;
        }),
        rankingFactor: 1
      };
      _handleResults();
    }
  );
};

/**
 * Search in songsheets by pitch and duration
 * @callback onSolrCallback
 * @private
 */
var _searchMelody = function() {
  var melody = store.melodyQuery.melody;
  var threshold = store.melodyQuery.threshold / 100;
  databaseService.getCollection(
    databaseConfig.collections.songsheets,
    0,
    0,
    function(songsheets, count) {
      var results = [];
      for (var i = 0; i < count; i++) {
        // Calculate distance between songsheets and search
        var similarities = MusicJsonToolbox.pitchDurationNgramSimilarity(
          songsheets[i].json,
          MusicJsonToolbox.pitchDurationValues(
            melody,
            0, 16, 4
          )
        );

        // Determine minimum distance
        var maxSimilarity = Math.max(...similarities.map(function(item) {
          return item.similarity;
        }));

        // only return results above threshold
        if (maxSimilarity >= threshold) {
          let maxSimilarityCount = similarities.filter(function(item) {
            return item.similarity === maxSimilarity;
          }).length;
          results.push({
            id: songsheets[i].signature,
            abc: songsheets[i].abc,
            json: songsheets[i].json,
            melodic: similarities,
            maxSimilarity: maxSimilarity,
            maxSimilarityCount: maxSimilarityCount,
            rank: 1 - maxSimilarity
          });
        }
      }

      // store response
      store.melodyResponse = {
        results: results.sort(function(a, b) {
          return a.rank - b.rank;
        }),
        rankingFactor: 1
      };
      _handleResults();
    }
  );
};

that.search = search;

module.exports = that;<|endoftext|>


<commit_before>/* Copyright 2018 Google Inc. All Rights Reserved.

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.
==============================================================================*/

'use strict';

const debug = require('debug')('wall:layout_state_machine');
const geometry = require('lib/geometry');

const stateMachine = require('lib/state_machine');
const time = require('server/util/time');
const ClientControlStateMachine = require('server/modules/client_control_state_machine');
const ModuleStateMachine = require('server/modules/module_state_machine');
const monitor = require('server/monitoring/monitor');

function isDisplayInPoly(rect, poly) {
  // find the center point of this display:
  var cx = rect.w / 2 + rect.x;
  var cy = rect.h / 2 + rect.y;

  return geometry.isInside(poly, cx, cy);
}

class LayoutStateMachine extends stateMachine.Machine {
  constructor() {
    super(new IdleState, debug);

    this.setContext({
      // All known clients. Maps client ID to ClientControlStateMachine.
      clients: {},
      module: null,
    });
  }
  newClient(clientInfo) {
    if (monitor.isEnabled()) {
      monitor.update({layout: {
        time: time.now(),
        event: `newClient: ${clientInfo.rect.serialize()}`,
      }});
    }
    this.context_.clients[clientInfo.socket.id] =
        new ClientControlStateMachine(clientInfo);
    this.state.newClient(clientInfo);
  }
  dropClient(id) {
    if (id in this.context_.clients) {
      let rect = this.context_.clients[id].getClientInfo().rect;
      if (monitor.isEnabled()) {
        monitor.update({layout: {
          time: time.now(),
          event: `dropClient: ${rect.serialize()}`,
        }});
      }
      this.state.dropClient(rect, id);
    } else {
      if (monitor.isEnabled()) {
        monitor.update({layout: {
          time: time.now(),
          event: `dropClient: id ${id}`,
        }});
      }
    }
    delete this.context_.clients[id];
  }
  fadeOut() {
    // Wipe the requested module.
    this.context_.module = null;

    if (monitor.isEnabled()) {
      monitor.update({layout: {
        time: time.now(),
        event: `fadeOut`,
      }});
    }

    return this.state.fadeOut();
  }
  getCurrentModuleInfo() {
    return this.state.getCurrentModuleInfo();
  }
  getClientState() {
    return Object.keys(this.context_.clients)
        .map(k => this.context_.clients[k])
        .map(c => {
          return {
            module: c.getModuleName(),
            rect: c.getClientInfo().rect,
            state: c.state.getName()
          };
        });
  }
  // Tell the state machines to play a module.
  playModule(moduleName) {
    debug(`playModule: ${moduleName}`);
    if (monitor.isEnabled()) {
      monitor.update({layout: {
        time: time.now(),
        event: `playModule: ${moduleName}`,
      }});
    }

    this.context_.module = moduleName;

    // Tell the current state that a request to play a module has arrived.
    return this.state.playModule(moduleName);
  }
}

class IdleState extends stateMachine.State {
  enter(transition) {
    if (monitor.isEnabled()) {
      monitor.update({layout: {
        time: time.now(),
        state: this.getName()
      }});
    }
    this.transition_ = transition;
  }
  newClient(client) {}
  dropClient(rect, id) {}
  getCurrentModuleInfo() {
    return {};
  }
  fadeOut() {
    // We can skip the normal fade out here because we're already faded out.
    return Promise.resolve();
  }
  playModule(moduleName) {
    // Start showing a thing!
    this.transition_(new DisplayState);
  }
}

class DisplayState extends stateMachine.State {
  enter(transition, context) {
    let deadline = time.now();
    if (monitor.isEnabled()) {
      monitor.update({layout: {
        time: time.now(),
        state: this.getName(),
        deadline: deadline,
      }});
    }

    this.transition_ = transition;

    // Make a module state machine (that manages the lifecycle of the module interface for both
    // client and server).
    this.moduleSM_ = new ModuleStateMachine(context.clients);

    this.moduleSM_.setErrorListener(error => {
      throw error;
    });

    // Tell the new module state machines to play any requested modules for this state (if any arrived
    // since we we were told to go here, say, during the fade).
    this.moduleSM_.playModule(context.module, deadline);
  }
  newClient(clientInfo) {
    this.moduleSM_.newClient(clientInfo);
  }
  dropClient(rect, id) {
    this.moduleSM_.dropClient(id);
  }
  fadeOut() {
    return new Promise(resolve => this.transition_(new FadeOutState(this.moduleSM_, resolve)));
  }
  playModule(moduleName) {
    this.moduleSM_.playModule(moduleName, time.now());
  }
  getCurrentModuleInfo() {
    return {
      state: this.moduleSM_.state.getName(),
      deadline: this.moduleSM_.getDeadline(),
    };
  }
}

class FadeOutState extends stateMachine.State {
  constructor(moduleSM, resolve) {
    super();

    this.moduleSM_ = moduleSM;

    this.timer_ = null;

    this.resolves_ = [resolve];
  }
  enter(transition, context) {
    let now = time.now();
    const FADE_OUT_DURATION = 5000;
    let deadline = now + FADE_OUT_DURATION;
    if (monitor.isEnabled()) {
      monitor.update({layout: {
        time: now,
        state: this.getName(),
        deadline: deadline,
      }});
    }

    this.transition_ = transition;
    debug(`Fading out at ${deadline} ms`);
    this.moduleSM_.fadeToBlack(now);
    this.timer_ = setTimeout(() => {
      if (context.module) {
        // Someone told us to switch modules while we were fading!
        // No problem, let's show it!
        transition(new DisplayState);
      } else {
        // We've no one to switch to next, so let's just stay faded out.
        transition(new IdleState);
      }
      this.resolves_.forEach(r => r());
    }, time.until(deadline));
  }
  exit() {
    clearTimeout(this.timer_);
  }
  newClient(clientInfo) {}
  dropClient(id) {}
  fadeOut() {
    return new Promise(resolve => this.resolves_.push(resolve));
  }
  playModule(moduleName) {}
  getCurrentModuleInfo() {
    return {
      state: this.moduleSM_.state.getName(),
      deadline: Infinity,
    };
  }
}

module.exports = LayoutStateMachine;
<commit_msg>Remove unused function from lsm.<commit_after>/* Copyright 2018 Google Inc. All Rights Reserved.

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.
==============================================================================*/

'use strict';

const debug = require('debug')('wall:layout_state_machine');
const geometry = require('lib/geometry');

const stateMachine = require('lib/state_machine');
const time = require('server/util/time');
const ClientControlStateMachine = require('server/modules/client_control_state_machine');
const ModuleStateMachine = require('server/modules/module_state_machine');
const monitor = require('server/monitoring/monitor');

class LayoutStateMachine extends stateMachine.Machine {
  constructor() {
    super(new IdleState, debug);

    this.setContext({
      // All known clients. Maps client ID to ClientControlStateMachine.
      clients: {},
      module: null,
    });
  }
  newClient(clientInfo) {
    if (monitor.isEnabled()) {
      monitor.update({layout: {
        time: time.now(),
        event: `newClient: ${clientInfo.rect.serialize()}`,
      }});
    }
    this.context_.clients[clientInfo.socket.id] =
        new ClientControlStateMachine(clientInfo);
    this.state.newClient(clientInfo);
  }
  dropClient(id) {
    if (id in this.context_.clients) {
      let rect = this.context_.clients[id].getClientInfo().rect;
      if (monitor.isEnabled()) {
        monitor.update({layout: {
          time: time.now(),
          event: `dropClient: ${rect.serialize()}`,
        }});
      }
      this.state.dropClient(rect, id);
    } else {
      if (monitor.isEnabled()) {
        monitor.update({layout: {
          time: time.now(),
          event: `dropClient: id ${id}`,
        }});
      }
    }
    delete this.context_.clients[id];
  }
  fadeOut() {
    // Wipe the requested module.
    this.context_.module = null;

    if (monitor.isEnabled()) {
      monitor.update({layout: {
        time: time.now(),
        event: `fadeOut`,
      }});
    }

    return this.state.fadeOut();
  }
  getCurrentModuleInfo() {
    return this.state.getCurrentModuleInfo();
  }
  getClientState() {
    return Object.keys(this.context_.clients)
        .map(k => this.context_.clients[k])
        .map(c => {
          return {
            module: c.getModuleName(),
            rect: c.getClientInfo().rect,
            state: c.state.getName()
          };
        });
  }
  // Tell the state machines to play a module.
  playModule(moduleName) {
    debug(`playModule: ${moduleName}`);
    if (monitor.isEnabled()) {
      monitor.update({layout: {
        time: time.now(),
        event: `playModule: ${moduleName}`,
      }});
    }

    this.context_.module = moduleName;

    // Tell the current state that a request to play a module has arrived.
    return this.state.playModule(moduleName);
  }
}

class IdleState extends stateMachine.State {
  enter(transition) {
    if (monitor.isEnabled()) {
      monitor.update({layout: {
        time: time.now(),
        state: this.getName()
      }});
    }
    this.transition_ = transition;
  }
  newClient(client) {}
  dropClient(rect, id) {}
  getCurrentModuleInfo() {
    return {};
  }
  fadeOut() {
    // We can skip the normal fade out here because we're already faded out.
    return Promise.resolve();
  }
  playModule(moduleName) {
    // Start showing a thing!
    this.transition_(new DisplayState);
  }
}

class DisplayState extends stateMachine.State {
  enter(transition, context) {
    let deadline = time.now();
    if (monitor.isEnabled()) {
      monitor.update({layout: {
        time: time.now(),
        state: this.getName(),
        deadline: deadline,
      }});
    }

    this.transition_ = transition;

    // Make a module state machine (that manages the lifecycle of the module interface for both
    // client and server).
    this.moduleSM_ = new ModuleStateMachine(context.clients);

    this.moduleSM_.setErrorListener(error => {
      throw error;
    });

    // Tell the new module state machines to play any requested modules for this state (if any arrived
    // since we we were told to go here, say, during the fade).
    this.moduleSM_.playModule(context.module, deadline);
  }
  newClient(clientInfo) {
    this.moduleSM_.newClient(clientInfo);
  }
  dropClient(rect, id) {
    this.moduleSM_.dropClient(id);
  }
  fadeOut() {
    return new Promise(resolve => this.transition_(new FadeOutState(this.moduleSM_, resolve)));
  }
  playModule(moduleName) {
    this.moduleSM_.playModule(moduleName, time.now());
  }
  getCurrentModuleInfo() {
    return {
      state: this.moduleSM_.state.getName(),
      deadline: this.moduleSM_.getDeadline(),
    };
  }
}

class FadeOutState extends stateMachine.State {
  constructor(moduleSM, resolve) {
    super();

    this.moduleSM_ = moduleSM;

    this.timer_ = null;

    this.resolves_ = [resolve];
  }
  enter(transition, context) {
    let now = time.now();
    const FADE_OUT_DURATION = 5000;
    let deadline = now + FADE_OUT_DURATION;
    if (monitor.isEnabled()) {
      monitor.update({layout: {
        time: now,
        state: this.getName(),
        deadline: deadline,
      }});
    }

    this.transition_ = transition;
    debug(`Fading out at ${deadline} ms`);
    this.moduleSM_.fadeToBlack(now);
    this.timer_ = setTimeout(() => {
      if (context.module) {
        // Someone told us to switch modules while we were fading!
        // No problem, let's show it!
        transition(new DisplayState);
      } else {
        // We've no one to switch to next, so let's just stay faded out.
        transition(new IdleState);
      }
      this.resolves_.forEach(r => r());
    }, time.until(deadline));
  }
  exit() {
    clearTimeout(this.timer_);
  }
  newClient(clientInfo) {}
  dropClient(id) {}
  fadeOut() {
    return new Promise(resolve => this.resolves_.push(resolve));
  }
  playModule(moduleName) {}
  getCurrentModuleInfo() {
    return {
      state: this.moduleSM_.state.getName(),
      deadline: Infinity,
    };
  }
}

module.exports = LayoutStateMachine;
<|endoftext|>


<commit_before>/**
 * Created by hugo on 2/3/15.
 */

var express = require('express');
var router = express.Router();
var google = require('googleapis');
var youtube = google.youtube('v3');
var keys = require('../config/keys');

router.get('/add-video/:videoId', function (req, res) {
    var videoId = req.params.videoId;

    if (videoId) {
        // Add the current videoId to buffer.
        var buffer = [];
        buffer.push(videoId);

        // Load the mix playlist and add it to buffer.
        var mixPlaylistId = 'RD' + videoId;
        youtube.playlistItems.list({
            key: keys.youtube,
            part: 'id,snippet',
            playlistId: mixPlaylistId,
            maxResults: 50
        }, function (err, data) {
            if (data && data.items) {
                for (i = 0; i < data.items.length; i++) {
                    if (data.items[i].snippet.resourceId.videoId) {
                        var vidId = data.items[i].snippet.resourceId.videoId;
                        if (buffer.indexOf(vidId) === -1) buffer.push(vidId);
                    }
                }

            }
            req.session.buffer = buffer;
            res.end();
        });
    } else {
        res.status(500).end();
    }
});

router.get('/next/', function (req, res) {
    var buffer = req.session.buffer;

    if (buffer.length > 0) {
        var videoId = buffer[0];
        buffer.shift();
        res.send({
            'videoId': videoId
        })
    } else {
        res.status(500).end();
    }
});

module.exports = router;<commit_msg>little comment added<commit_after>/**
 * Created by hugo on 2/3/15.
 */

var express = require('express');
var router = express.Router();
var google = require('googleapis');
var youtube = google.youtube('v3');
var keys = require('../config/keys');

router.get('/add-video/:videoId', function (req, res) {
    var videoId = req.params.videoId;

    if (videoId) {
        // Add the current videoId to buffer.
        var buffer = [];
        buffer.push(videoId);

        // Load the mix playlist and add it to buffer.
        var mixPlaylistId = 'RD' + videoId;
        youtube.playlistItems.list({
            key: keys.youtube,
            part: 'id,snippet',
            playlistId: mixPlaylistId,
            maxResults: 50
        }, function (err, data) {
            if (data && data.items) {
                for (i = 0; i < data.items.length; i++) {
                    if (data.items[i].snippet.resourceId.videoId) {
                        var vidId = data.items[i].snippet.resourceId.videoId;
                        if (buffer.indexOf(vidId) === -1) buffer.push(vidId);
                    }
                }

            }

            // save playlist to session
            req.session.buffer = buffer;
            res.end();
        });
    } else {
        res.status(500).end();
    }
});

router.get('/next/', function (req, res) {
    var buffer = req.session.buffer;

    if (buffer.length > 0) {
        var videoId = buffer[0];
        buffer.shift();
        res.send({
            'videoId': videoId
        })
    } else {
        res.status(500).end();
    }
});

module.exports = router;<|endoftext|>


<commit_before><commit_msg>updated flintbit<commit_after><|endoftext|>


<commit_before>var userCtrl = require('./userController'),
	helpers = require('../config/helpers');

module.exports = function (app) {
  // app is the userRouter injected from middleware.js

  app.post('/login', userCtrl.login);
  app.post('/signup', userCtrl.signup);

  app.use('/table', helpers.decode);
  app.use('/tabs', helpers.decode);
  app.post('/table', userCtrl.getTable);
  app.post('/tabs', userCtrl.toTabs);
};
<commit_msg>rebasing user Ctrl Routes<commit_after>var userCtrl = require('./userController'),
	helpers = require('../config/helpers');

module.exports = function (app) {
  // app is the userRouter injected from middleware.js

  // new auth route
  app.get('/signedin', userCtrl.checkAuth);

  app.post('/login', userCtrl.login);
  app.post('/signup', userCtrl.signup);

  app.use('/table', helpers.decode);
  app.use('/tabs', helpers.decode);
  app.post('/table', userCtrl.getTable);
  app.post('/tabs', userCtrl.toTabs);
};
<|endoftext|>


<commit_before><commit_msg>Fixing live formatting when beginning with a decimal, or 0 (#1710)<commit_after><|endoftext|>


<commit_before>const register = [];
const providerFound = {};
let checkTimeout = null

class EventBus {
    constructor() {
    }

    inbound(event) {
        console.log(`Got ${event.name}:${event.detail}:${event.time}`)
        if (event && event.name && register[event.name]) {
            console.log(`Calling ${register[event.name].length} handlers`)
            register[event.name].forEach(handler => handler(event));
        } else if (!event.name) {
            console.error(event, "missing name")
        } else {
            console.warn(event, "has no listeners")
        }
    }

    register(request) {
        if (!request.caller) {
            console.error("Couldn't register", request)
        } else if (!request.caller.on || typeof request.caller.on !== "function") {
            console.error("Caller isn't an EventEmitter")
        } else {
            if (request.provides) {
                request.provides.forEach((event) => {
                    request.caller.on(event, this.inbound)
                    providerFound[event] = true;
                })
            }

            if (request.needs) {
                Object.keys(request.needs).forEach((event) => {
                    console.log(`Registering for ${event}`)
                    register[event] = register[event] || [];
                    register[event].push(request.needs[event])
                })
            }

        }
        check()
    }

    check(){
        register.forEach((event)=>{
            if(!providerFound(event)) console.error(`No provider available for ${event}`)
        })
        Object.keys(providerFound).forEach((event)=>{
            if(!register[event]) console.warn(`There's no listener for ${event}`)
        })
    }

}

module.exports = new EventBus()
<commit_msg>event checking<commit_after>const register = [];
const providerFound = {};
let checkTimeout = null

class EventBus {
    constructor() {
    }

    inbound(event) {
        console.log(`Got ${event.name}:${event.detail}:${event.time}`)
        if (event && event.name && register[event.name]) {
            console.log(`Calling ${register[event.name].length} handlers`)
            register[event.name].forEach(handler => handler(event));
        } else if (!event.name) {
            console.error(event, "missing name")
        } else {
            console.warn(event, "has no listeners")
        }
    }

    register(request) {
        if (!request.caller) {
            console.error("Couldn't register", request)
        } else if (!request.caller.on || typeof request.caller.on !== "function") {
            console.error("Caller isn't an EventEmitter")
        } else {
            if (request.provides) {
                request.provides.forEach((event) => {
                    request.caller.on(event, this.inbound)
                    providerFound[event] = true;
                })
            }

            if (request.needs) {
                Object.keys(request.needs).forEach((event) => {
                    console.log(`Registering for ${event}`)
                    register[event] = register[event] || [];
                    register[event].push(request.needs[event])
                })
            }

        }
        EventBus.check()
    }

    check(){
        register.forEach((event)=>{
            if(!providerFound(event)) console.error(`No provider available for ${event}`)
        })
        Object.keys(providerFound).forEach((event)=>{
            if(!register[event]) console.warn(`There's no listener for ${event}`)
        })
    }

}

module.exports = new EventBus()
<|endoftext|>


<commit_before>import mix from 'es6-mixins';

mix();<commit_msg>initial commit.<commit_after>import es6Mixins from 'es6-mixins';

es6Mixins();<|endoftext|>


<commit_before>const ma = require('../dist/main');

// creates a promise that will be resolved after given delay
function makePromise(name, delay) {
  return new Promise((resolve) => {
    console.log(`${name} started`);
    setTimeout(() => {
      console.log(`${name} completed`);
      resolve(name);
    }, delay);
  });
}

ma.js.array([2000, 200, 2]).map((n, index, state) => {
  console.log('------', n, index, state);
  return makePromise(n, n);
}).map((n, index, state) => {
  console.log('------', n, index, state);
  return n-1;
}).map((n, index, state) => {
  console.log('------', n, index, state);
  return n-1;
});;
console.log('run');
<commit_msg>Update example<commit_after>const ma = require('../dist/main');

// creates a promise that will be resolved after given delay
function makePromise(name, delay) {
  return new Promise((resolve) => {
    console.log(`${name} started`);
    setTimeout(() => {
      console.log(`${name} completed`);
      resolve(name);
    }, delay);
  });
}

ma.js.array([2000, 200, 2]).map((n, index, state) => {
  return makePromise(n, n);
}).print().map((n, index, state) => {
  return n-1;
}).print().filter((n, index, state) => {
  return n < 1000;
}).print();
console.log('run');
<|endoftext|>


<commit_before>/* @flow */
import React, {Component} from 'react'
import {Box, Text, Icon} from '../common-adapters'
import {globalStyles, globalColors} from '../styles/style-guide'
import type {Props as IconProps} from '../common-adapters/icon'

import type {Props} from './index'
import type {Device as DeviceType} from '../constants/types/flow-types'

class RevokedHeader extends Component {
  state: {
    expanded: boolean
  };

  constructor (props) {
    super(props)
    this.state = {
      expanded: false
    }
    this.toggleHeader = this.toggleHeader.bind(this)
  }

  toggleHeader () {
    this.setState({expanded: !this.state.expanded})
  }

  render () {
    const iconType = this.state.expanded ? 'fa-caret-down' : 'fa-caret-up'
    return (
      <Box>
        <Box style={stylesRevokedRow} onClick={this.toggleHeader}>
          <Text type='BodySemibold'>Revoked devices</Text>
          <Icon type={iconType} style={{padding: 5}}/>
        </Box>
        {this.state.expanded && this.props.children}
      </Box>
    )
  }
}

class DeviceRow extends Component {
  state: {
    highlighted: boolean
  };
  props: {
    device: DeviceType,
    revoked?: boolean,
    showRemoveDevicePage?: () => void,
    showExistingDevicePage?: () => void
  };

  constructor (props) {
    super(props)
    this.state = {
      highlighted: false
    }
    this.highlightOn = this.highlightOn.bind(this)
    this.highlightOff = this.highlightOff.bind(this)
  }

  highlightOn (e) {
    this.setState({highlighted: true})
  }

  highlightOff (e) {
    this.setState({highlighted: false})
  }

  render () {
    const icon: IconProps.type = {
      'mobile': 'phone-bw-m',
      'desktop': 'computer-bw-s-2',
      'backup': 'paper-key-m'
    }[this.props.device.type]

    let textStyle = {fontStyle: 'italic'}
    if (this.props.revoked) {
      textStyle = {
        ...textStyle,
        color: globalColors.black40,
        textDecoration: 'line-through'
      }
    }

    return (
      <Box key={this.props.device.name} onMouseOver={this.highlightOn} onMouseOut={this.highlightOff} style={{...stylesCommonRow, backgroundColor: this.props.revoked ? globalColors.lightGrey : globalColors.white}}>
        <Box style={this.props.revoked ? stylesRevokedIconColumn : stylesIconColumn}>
          <Icon type={icon}/>
        </Box>
        <Box style={stylesCommonColumn}>
          <Box style={{...globalStyles.flexBoxRow}}>
            <Text style={textStyle} type='Header'>{this.props.device.name}</Text>
          </Box>
          <Box style={{...globalStyles.flexBoxRow}}>
            {this.props.device.isCurrent && <Text type='BodySmall'>Current device</Text>}
          </Box>
        </Box>
        <Box style={{...stylesRevokedColumn}}>
          {!this.props.revoked && this.state.highlighted && <Text style={{color: globalColors.red}} type='BodyPrimaryLink'>Revoke</Text>}
        </Box>
      </Box>
    )
  }
}

const RevokedDescription = () => {
  return (
    <Box style={stylesRevokedDescription}>
      <Text type='BodySemibold' style={{color: globalColors.black40}}>Revoked devices will no longer be able to access your Keybase account.</Text>
    </Box>
  )
}

const RevokedDevices = revokedDevices => {
  return (
    <RevokedHeader>
      <RevokedDescription/>
      {revokedDevices.map(device => <DeviceRow device={device} revoked/>)}
    </RevokedHeader>
  )
}

const DeviceHeader = addNewDevice => {
  return (
    <Box style={stylesCommonRow}>
      <Box style={stylesCommonColumn}>
        <Icon type='devices-add-s'/>
      </Box>
      <Box style={stylesCommonColumn}>
        <Text type='BodyPrimaryLink' onClick={addNewDevice}>Add new...</Text>
      </Box>
    </Box>
  )
}

const Render = ({devices, revokedDevices, waitingForServer, addNewDevice, showRemoveDevicePage, showExistingDevicePage}: Props) => {
  return (
    <Box style={stylesContainer}>
      {DeviceHeader(addNewDevice)}
      {devices && devices.map(device => <DeviceRow device={device} showRemoveDevicePage={showRemoveDevicePage} showExistingDevicePage={showExistingDevicePage}/>)}
      {revokedDevices && RevokedDevices(revokedDevices)}
    </Box>
  )
}

const stylesContainer = {
  ...globalStyles.flexBoxColumn
}

const stylesCommonRow = {
  ...globalStyles.flexBoxRow,
  alignItems: 'center',
  borderTop: 'solid 1px rgba(0, 0, 0, .1)',
  height: 60,
  justifyContent: 'center',
  padding: 8
}

const stylesRevokedRow = {
  ...stylesCommonRow,
  height: 30,
  justifyContent: 'flex-start',
  backgroundColor: globalColors.lightGrey
}

const stylesRevokedDescription = {
  ...stylesCommonRow,
  backgroundColor: globalColors.lightGrey
}

const stylesCommonColumn = {
  padding: 20
}

const stylesRevokedColumn = {
  ...stylesCommonColumn,
  alignSelf: 'center',
  flex: 1,
  textAlign: 'right',
  paddingRight: 20
}

const stylesIconColumn = {
  ...stylesCommonColumn,
  width: 65
}

const stylesRevokedIconColumn = {
  ...stylesIconColumn,
  opacity: 0.2
}

export default Render
<commit_msg>Some fixes from Nojima<commit_after>/* @flow */
import React, {Component} from 'react'
import {Box, Text, Icon} from '../common-adapters'
import {globalStyles, globalColors} from '../styles/style-guide'
import type {Props as IconProps} from '../common-adapters/icon'

import type {Props} from './index'
import type {Device as DeviceType} from '../constants/types/flow-types'

class RevokedHeader extends Component {
  state: {
    expanded: boolean
  };

  constructor (props) {
    super(props)
    this.state = {
      expanded: false
    }
  }

  _toggleHeader (e) {
    this.setState({expanded: !this.state.expanded})
  }

  render () {
    const iconType = this.state.expanded ? 'fa-caret-down' : 'fa-caret-up'
    return (
      <Box>
        <Box style={stylesRevokedRow} onClick={e => this._toggleHeader(e)}>
          <Text type='BodySemibold'>Revoked devices</Text>
          <Icon type={iconType} style={{padding: 5}}/>
        </Box>
        {this.state.expanded && this.props.children}
      </Box>
    )
  }
}

class DeviceRow extends Component {
  state: {
    highlighted: boolean
  };
  props: {
    device: DeviceType,
    revoked?: boolean,
    showRemoveDevicePage?: () => void,
    showExistingDevicePage?: () => void
  };

  constructor (props) {
    super(props)
    this.state = {
      highlighted: false
    }
  }

  _highlighted (h) {
    this.setState({highlighted: h})
  }

  render () {
    const icon: IconProps.type = {
      'mobile': 'phone-bw-m',
      'desktop': 'computer-bw-s-2',
      'backup': 'paper-key-m'
    }[this.props.device.type]

    let textStyle = {fontStyle: 'italic'}
    if (this.props.revoked) {
      textStyle = {
        ...textStyle,
        color: globalColors.black40,
        textDecoration: 'line-through'
      }
    }

    return (
      <Box key={this.props.device.name} onMouseOver={e => this._highlighted(true)} onMouseOut={e => this._highlighted(false)} style={{...stylesCommonRow, backgroundColor: this.props.revoked ? globalColors.lightGrey : globalColors.white}}>
        <Box style={this.props.revoked ? stylesRevokedIconColumn : stylesIconColumn}>
          <Icon type={icon}/>
        </Box>
        <Box style={stylesCommonColumn}>
          <Box style={{...globalStyles.flexBoxRow}}>
            <Text style={textStyle} type='Header'>{this.props.device.name}</Text>
          </Box>
          <Box style={{...globalStyles.flexBoxRow}}>
            {this.props.device.isCurrent && <Text type='BodySmall'>Current device</Text>}
          </Box>
        </Box>
        <Box style={{...stylesRevokedColumn}}>
          {!this.props.revoked && this.state.highlighted && <Text style={{color: globalColors.red}} type='BodyPrimaryLink'>Revoke</Text>}
        </Box>
      </Box>
    )
  }
}

const RevokedDescription = () => {
  return (
    <Box style={stylesRevokedDescription}>
      <Text type='BodySemibold' style={{color: globalColors.black40}}>Revoked devices will no longer be able to access your Keybase account.</Text>
    </Box>
  )
}

const RevokedDevices = ({revokedDevices}) => {
  return (
    <RevokedHeader>
      <RevokedDescription/>
      {revokedDevices.map(device => <DeviceRow key={device.name} device={device} revoked/>)}
    </RevokedHeader>
  )
}

const DeviceHeader = ({addNewDevice}) => {
  return (
    <Box style={stylesCommonRow}>
      <Box style={stylesCommonColumn}>
        <Icon type='devices-add-s'/>
      </Box>
      <Box style={stylesCommonColumn}>
        <Text type='BodyPrimaryLink' onClick={addNewDevice}>Add new...</Text>
      </Box>
    </Box>
  )
}

const Render = ({devices, revokedDevices, waitingForServer, addNewDevice, showRemoveDevicePage, showExistingDevicePage}: Props) => {
  return (
    <Box style={stylesContainer}>
      {<DeviceHeader addNewDevice={addNewDevice} />}
      {devices && devices.map(device => <DeviceRow key={device.name} device={device} showRemoveDevicePage={showRemoveDevicePage} showExistingDevicePage={showExistingDevicePage}/>)}
      {revokedDevices && <RevokedDevices revokedDevices={revokedDevices} />}
    </Box>
  )
}

const stylesContainer = {
  ...globalStyles.flexBoxColumn
}

const stylesCommonRow = {
  ...globalStyles.flexBoxRow,
  alignItems: 'center',
  borderTop: 'solid 1px rgba(0, 0, 0, .1)',
  height: 60,
  justifyContent: 'center',
  padding: 8
}

const stylesRevokedRow = {
  ...stylesCommonRow,
  height: 30,
  justifyContent: 'flex-start',
  backgroundColor: globalColors.lightGrey
}

const stylesRevokedDescription = {
  ...stylesCommonRow,
  backgroundColor: globalColors.lightGrey
}

const stylesCommonColumn = {
  padding: 20
}

const stylesRevokedColumn = {
  ...stylesCommonColumn,
  alignSelf: 'center',
  flex: 1,
  textAlign: 'right',
  paddingRight: 20
}

const stylesIconColumn = {
  ...stylesCommonColumn,
  width: 65
}

const stylesRevokedIconColumn = {
  ...stylesIconColumn,
  opacity: 0.2
}

export default Render
<|endoftext|>


<commit_before><commit_msg>Add guard clauses<commit_after><|endoftext|>


<commit_before>'use strict';

angular.module('demo', ['googleOauth']).

  config(function(TokenProvider) {
    // Demo configuration for the "angular-oauth demo" project on Google.
    // Log in at will!

    // Sorry about this way of getting a relative URL, powers that be.
    var baseUrl = document.URL.replace('example/demo.html', '');

    TokenProvider.extendConfig({
      clientId: '191261111313.apps.googleusercontent.com',
      redirectUri: baseUrl + 'src/oauth2callback.html',  // allow lunching demo from a mirror
      scopes: ["https://www.googleapis.com/auth/userinfo.email"]
    });
  }).

  controller('DemoCtrl', function($scope, $window, Token) {
    $scope.accessToken = Token.get();

    $scope.authenticate = function() {
      var extraParams = $scope.askApproval ? {approval_prompt: 'force'} : {};
      Token.getTokenByPopup(extraParams)
        .then(function(params) {
          // Success getting token from popup.

          var accessToken = params.access_token;
          $scope.accessToken = accessToken;
          $scope.expiresIn = params.expires_in;

          // Verify the token before setting it, to avoid the confused deputy problem.
          Token.verifyAsync(accessToken).
            then(function(data) {
              Token.set(accessToken);
            }, function() {
              alert("Failed to verify token.")
            });

        }, function() {
          // Failure getting token from popup.
          alert("Failed to get token from popup.");
        });
    };
  });<commit_msg>Fix demo bug where unverified scope access token was displayed.<commit_after>'use strict';

angular.module('demo', ['googleOauth']).

  config(function(TokenProvider) {
    // Demo configuration for the "angular-oauth demo" project on Google.
    // Log in at will!

    // Sorry about this way of getting a relative URL, powers that be.
    var baseUrl = document.URL.replace('example/demo.html', '');

    TokenProvider.extendConfig({
      clientId: '191261111313.apps.googleusercontent.com',
      redirectUri: baseUrl + 'src/oauth2callback.html',  // allow lunching demo from a mirror
      scopes: ["https://www.googleapis.com/auth/userinfo.email"]
    });
  }).

  controller('DemoCtrl', function($scope, $window, Token) {
    $scope.accessToken = Token.get();

    $scope.authenticate = function() {
      var extraParams = $scope.askApproval ? {approval_prompt: 'force'} : {};
      Token.getTokenByPopup(extraParams)
        .then(function(params) {
          // Success getting token from popup.

          // Verify the token before setting it, to avoid the confused deputy problem.
          Token.verifyAsync(params.access_token).
            then(function(data) {
              $scope.accessToken = params.access_token;
              $scope.expiresIn = params.expires_in;

              Token.set(params.access_token);
            }, function() {
              alert("Failed to verify token.")
            });

        }, function() {
          // Failure getting token from popup.
          alert("Failed to get token from popup.");
        });
    };
  });<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import { styled } from '@storybook/theming';
import { withState } from 'recompose';
import { opacify } from 'polished';

import { Icons } from '@storybook/components';

const FilterField = styled.input(({ theme }) => ({
  // resets
  appearance: 'none',
  border: 'none',
  boxSizing: 'inherit',
  display: ' block',
  outline: 'none',
  width: ' 100%',
  margin: ' 0',
  background: 'transparent',
  padding: 0,
  fontSize: 'inherit',

  '&:-webkit-autofill': { WebkitBoxShadow: `0 0 0 3em ${theme.color.lightest} inset` },

  '::placeholder': {
    color: theme.color.mediumdark,
  },

  '&:placeholder-shown ~ button': {
    // hide cancel button using CSS only
    opacity: 0,
  },
}));

const CancelButton = styled.button(({ theme }) => ({
  border: 0,
  margin: 0,
  padding: 4,
  textDecoration: 'none',

  background: theme.appBorderColor,
  borderRadius: '1em',
  cursor: 'pointer',
  opacity: 1,
  transition: 'all 150ms ease-out',

  position: 'absolute',
  top: '50%',
  transform: 'translateY(-50%)',
  right: 2,

  '> svg': {
    display: 'block',
    height: 8,
    width: 8,
    color: theme.input.color,
    transition: 'all 150ms ease-out',
  },

  '&:hover': {
    background: opacify(0.1, theme.appBorderColor),
  },
}));

const FilterForm = styled.form(({ theme, focussed }) => ({
  transition: 'all 150ms ease-out',
  borderBottom: '1px solid transparent',
  borderBottomColor: focussed
    ? opacify(0.3, theme.appBorderColor)
    : opacify(0.1, theme.appBorderColor),
  outline: 0,
  position: 'relative',

  input: {
    color: theme.input.color,
    fontSize: theme.typography.size.s2 - 1,
    lineHeight: '20px',
    paddingTop: '2px',
    paddingBottom: '2px',
    paddingLeft: '20px',
  },

  '> svg': {
    transition: 'all 150ms ease-out',
    position: 'absolute',
    top: '50%',
    height: '12px',
    width: '12px',
    transform: 'translateY(-50%)',
    zIndex: '1',

    background: 'transparent',

    path: {
      transition: 'all 150ms ease-out',
      fill: 'currentColor',
      opacity: focussed ? 1 : 0.3,
    },
  },
}));

export const PureSidebarSearch = ({ focussed, onSetFocussed, className, onChange, ...props }) => (
  <FilterForm
    autoComplete="off"
    focussed={focussed}
    className={className}
    onReset={() => onChange('')}
  >
    <FilterField
      type="text"
      autocomplete="off"
      id="storybook-explorer-searchfield"
      onFocus={() => onSetFocussed(true)}
      onBlur={() => onSetFocussed(false)}
      onChange={e => onChange(e.target.value)}
      {...props}
      placeholder={focussed ? 'Type to search...' : 'Press "/" to search...'}
      aria-label="Search stories"
    />
    <Icons icon="search" />
    <CancelButton type="reset" value="reset" title="Clear search">
      <Icons icon="closeAlt" />
    </CancelButton>
  </FilterForm>
);

PureSidebarSearch.propTypes = {
  className: PropTypes.string,
  focussed: PropTypes.bool.isRequired,
  onChange: PropTypes.func.isRequired,
  onSetFocussed: PropTypes.func.isRequired,
};

PureSidebarSearch.defaultProps = {
  className: null,
};

export default withState('focussed', 'onSetFocussed', false)(PureSidebarSearch);
<commit_msg>Fix bug where Sidebar input refreshed on 'Enter' (#7342)<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import { styled } from '@storybook/theming';
import { withState } from 'recompose';
import { opacify } from 'polished';

import { Icons } from '@storybook/components';

const FilterField = styled.input(({ theme }) => ({
  // resets
  appearance: 'none',
  border: 'none',
  boxSizing: 'inherit',
  display: ' block',
  outline: 'none',
  width: ' 100%',
  margin: ' 0',
  background: 'transparent',
  padding: 0,
  fontSize: 'inherit',

  '&:-webkit-autofill': { WebkitBoxShadow: `0 0 0 3em ${theme.color.lightest} inset` },

  '::placeholder': {
    color: theme.color.mediumdark,
  },

  '&:placeholder-shown ~ button': {
    // hide cancel button using CSS only
    opacity: 0,
  },
}));

const CancelButton = styled.button(({ theme }) => ({
  border: 0,
  margin: 0,
  padding: 4,
  textDecoration: 'none',

  background: theme.appBorderColor,
  borderRadius: '1em',
  cursor: 'pointer',
  opacity: 1,
  transition: 'all 150ms ease-out',

  position: 'absolute',
  top: '50%',
  transform: 'translateY(-50%)',
  right: 2,

  '> svg': {
    display: 'block',
    height: 8,
    width: 8,
    color: theme.input.color,
    transition: 'all 150ms ease-out',
  },

  '&:hover': {
    background: opacify(0.1, theme.appBorderColor),
  },
}));

const FilterForm = styled.form(({ theme, focussed }) => ({
  transition: 'all 150ms ease-out',
  borderBottom: '1px solid transparent',
  borderBottomColor: focussed
    ? opacify(0.3, theme.appBorderColor)
    : opacify(0.1, theme.appBorderColor),
  outline: 0,
  position: 'relative',

  input: {
    color: theme.input.color,
    fontSize: theme.typography.size.s2 - 1,
    lineHeight: '20px',
    paddingTop: '2px',
    paddingBottom: '2px',
    paddingLeft: '20px',
  },

  '> svg': {
    transition: 'all 150ms ease-out',
    position: 'absolute',
    top: '50%',
    height: '12px',
    width: '12px',
    transform: 'translateY(-50%)',
    zIndex: '1',

    background: 'transparent',

    path: {
      transition: 'all 150ms ease-out',
      fill: 'currentColor',
      opacity: focussed ? 1 : 0.3,
    },
  },
}));

export const PureSidebarSearch = ({ focussed, onSetFocussed, className, onChange, ...props }) => (
  <FilterForm
    autoComplete="off"
    focussed={focussed}
    className={className}
    onReset={() => onChange('')}
    onSubmit={e => e.preventDefault()}
  >
    <FilterField
      type="text"
      autocomplete="off"
      id="storybook-explorer-searchfield"
      onFocus={() => onSetFocussed(true)}
      onBlur={() => onSetFocussed(false)}
      onChange={e => onChange(e.target.value)}
      {...props}
      placeholder={focussed ? 'Type to search...' : 'Press "/" to search...'}
      aria-label="Search stories"
    />
    <Icons icon="search" />
    <CancelButton type="reset" value="reset" title="Clear search">
      <Icons icon="closeAlt" />
    </CancelButton>
  </FilterForm>
);

PureSidebarSearch.propTypes = {
  className: PropTypes.string,
  focussed: PropTypes.bool.isRequired,
  onChange: PropTypes.func.isRequired,
  onSetFocussed: PropTypes.func.isRequired,
};

PureSidebarSearch.defaultProps = {
  className: null,
};

export default withState('focussed', 'onSetFocussed', false)(PureSidebarSearch);
<|endoftext|>


<commit_before>// * ———————————————————————————————————————————————————————— * //
// * 	remote handler
// *	uploads files to s3
// * ———————————————————————————————————————————————————————— * //
var filesystem = function () {}

// vendor dependencies
var Promise = require('bluebird')
var s3 = require('s3')

// local dependencies
var logger = require(enduro.enduro_path + '/libs/logger')

filesystem.prototype.init = function () {
	// no init required
}

filesystem.prototype.upload = function (filename, path_to_file) {
	var self = this

	return new Promise(function (resolve, reject) {

		var destination_url = self.get_remote_url(filename)

		var client = s3.createClient({
			s3Options: {
				accessKeyId: enduro.config.variables.S3_KEY,
				secretAccessKey: enduro.config.variables.S3_SECRET,
				region: enduro.config.s3.region || 'us-west-1',
			},
		})

		var params = {
			localFile: path_to_file,
			s3Params: {
				Bucket: enduro.config.s3.bucket,
				Key: filename,
			},
		}
		var uploader = client.uploadFile(params)

		uploader.on('error', function (err) {
			console.error('unable to upload:', err.stack)
		})

		uploader.on('end', function () {
			logger.timestamp('File uploaded successfully: ' + destination_url)
			return resolve(destination_url)
		})

	})
}

filesystem.prototype.get_remote_url = function (filename, juicebox) {
	if (enduro.config.s3.cloudfront && !juicebox) {
		return 'https://' + enduro.config.s3.cloudfront + '/' + filename
	} else {
		return 'https://s3-' + (enduro.config.s3.region || 'us-west-1') + '.amazonaws.com/' + enduro.config.s3.bucket + '/' + filename
	}
}

module.exports = new filesystem()
<commit_msg>filesystem s3 conditional for us-ease-1<commit_after>// * ———————————————————————————————————————————————————————— * //
// * 	remote handler
// *	uploads files to s3
// * ———————————————————————————————————————————————————————— * //
var filesystem = function () {}

// vendor dependencies
var Promise = require('bluebird')
var s3 = require('s3')

// local dependencies
var logger = require(enduro.enduro_path + '/libs/logger')

filesystem.prototype.init = function () {
	// no init required
}

filesystem.prototype.upload = function (filename, path_to_file) {
	var self = this

	return new Promise(function (resolve, reject) {

		var destination_url = self.get_remote_url(filename)

		var client = s3.createClient({
			s3Options: {
				accessKeyId: enduro.config.variables.S3_KEY,
				secretAccessKey: enduro.config.variables.S3_SECRET,
				region: enduro.config.s3.region || 'us-west-1',
			},
		})

		var params = {
			localFile: path_to_file,
			s3Params: {
				Bucket: enduro.config.s3.bucket,
				Key: filename,
			},
		}
		var uploader = client.uploadFile(params)

		uploader.on('error', function (err) {
			console.error('unable to upload:', err.stack)
		})

		uploader.on('end', function () {
			logger.timestamp('File uploaded successfully: ' + destination_url)
			return resolve(destination_url)
		})

	})
}

filesystem.prototype.get_remote_url = function (filename, juicebox) {
	if (enduro.config.s3.cloudfront && !juicebox) {
		return 'https://' + enduro.config.s3.cloudfront + '/' + filename
	} else if (enduro.config.s3.region === 'us-east-1') {
		return 'https://s3.amazonaws.com/' + enduro.config.s3.bucket + '/' + filename
	} else {
		return 'https://s3-' + (enduro.config.s3.region || 'us-west-1') + '.amazonaws.com/' + enduro.config.s3.bucket + '/' + filename
	}
}

module.exports = new filesystem()
<|endoftext|>