<commit_before>const equal = require("assert").deepEqual

const SUCCESS = 0
const FAILURE = 1
const EMPTY = 2
const FAILABLE_TAG_V1 = "fv1"

const versionTag = f => f[0]
const kind = f => f[1]
const payload = f => f[2]
const meta = f => f[3]

const success = (payload, meta) => {
  if (payload === undefined) return empty(meta)
  return [FAILABLE_TAG_V1, SUCCESS, payload, meta]
}
const failure = (payload, meta) => [FAILABLE_TAG_V1, FAILURE, payload, meta]
const empty = meta => [FAILABLE_TAG_V1, EMPTY, undefined, meta]

const isSuccess = f => kind(f) === SUCCESS
const isFailure = f => kind(f) === FAILURE
const isEmpty = f => kind(f) === EMPTY
const isFailable = f => {
  if (versionTag(f) === FAILABLE_TAG_V1) {
    if (isSuccess(f) || isFailure(f) || isEmpty(f)) {
      return true
    }
  }
  return false
}

const anyFailed = l => l.filter(isFailure).length > 0
const firstFailure = l => l.filter(isFailure)[0]

const assertSuccess = (f, p) => {
  equal(isSuccess(f), true)
  if (p) equal(payload(f), p)
}

const assertFailure = (f, p) => {
  equal(isFailure(f), true)
  if (p) equal(payload(f), p)
}

const assertEmpty = f => equal(isEmpty(f), true)

const makeItFailable = fn => {
  return async (...args) => {
    try {
      const result = await fn.apply(this, args)
      if (isFailable(result)) return result
      return success(result)
    } catch (err) {
      return failure(err.toString())
    }
  }
}

const clean = o => {
  return Object.keys(o)
    .filter(f => o[f] !== undefined)
    .reduce((r, i) => Object.assign(r, { [i]: o[i] }), {})
}

const kindString = f => {
  switch (kind(f)) {
    case SUCCESS:
      return "success"
    case FAILURE:
      return "failure"
    case EMPTY:
      return "empty"
    default:
      return "unknown"
  }
}

const hydrate = f =>
  clean({
    kind: kindString(f),
    payload: payload(f),
    meta: meta(f)
  })

module.exports = {
  kind,
  payload,
  meta,
  success,
  failure,
  empty,
  isSuccess,
  isFailure,
  isEmpty,
  isFailable,
  assertSuccess,
  assertFailure,
  assertEmpty,
  anyFailed,
  firstFailure,
  makeItFailable,
  hydrate
}
<commit_msg>changing the names of things<commit_after>const equal = require("assert").deepEqual

const SUCCESS = 0
const FAILURE = 1
const EMPTY = 2
const PROTOCOL_V1 = "fv1"

const protocolVersion = f => f[0]
const kind = f => f[1]
const payload = f => f[2]
const meta = f => f[3]

const success = (payload, meta) => {
  if (payload === undefined) return empty(meta)
  return [PROTOCOL_V1, SUCCESS, payload, meta]
}
const failure = (payload, meta) => [PROTOCOL_V1, FAILURE, payload, meta]
const empty = meta => [PROTOCOL_V1, EMPTY, undefined, meta]

const isSuccess = f => kind(f) === SUCCESS
const isFailure = f => kind(f) === FAILURE
const isEmpty = f => kind(f) === EMPTY
const isFailable = f => {
  if (protocolVersion(f) === PROTOCOL_V1) {
    if (isSuccess(f) || isFailure(f) || isEmpty(f)) {
      return true
    }
  }
  return false
}

const anyFailed = l => l.filter(isFailure).length > 0
const firstFailure = l => l.filter(isFailure)[0]

const assertSuccess = (f, p) => {
  equal(isSuccess(f), true)
  if (p) equal(payload(f), p)
}

const assertFailure = (f, p) => {
  equal(isFailure(f), true)
  if (p) equal(payload(f), p)
}

const assertEmpty = f => equal(isEmpty(f), true)

const makeItFailable = fn => {
  return async (...args) => {
    try {
      const result = await fn.apply(this, args)
      if (isFailable(result)) return result
      return success(result)
    } catch (err) {
      return failure(err.toString())
    }
  }
}

const clean = o => {
  return Object.keys(o)
    .filter(f => o[f] !== undefined)
    .reduce((r, i) => Object.assign(r, { [i]: o[i] }), {})
}

const kindString = f => {
  switch (kind(f)) {
    case SUCCESS:
      return "success"
    case FAILURE:
      return "failure"
    case EMPTY:
      return "empty"
    default:
      return "unknown"
  }
}

const hydrate = f =>
  clean({
    kind: kindString(f),
    payload: payload(f),
    meta: meta(f)
  })

module.exports = {
  kind,
  payload,
  meta,
  success,
  failure,
  empty,
  isSuccess,
  isFailure,
  isEmpty,
  isFailable,
  assertSuccess,
  assertFailure,
  assertEmpty,
  anyFailed,
  firstFailure,
  makeItFailable,
  hydrate
}
<|endoftext|>


<commit_before>uv.AreaGraph = function (graphdef, config) {
  var self = this;
  uv.Graph.call(self, graphdef, config).setDefaults().init();

  self.areagroups = [];
  self.dataset = uv.util.getDataArray(self.graphdef);

  var areagroup, areapath, areafunc, idx, len,
    domainData = self.graphdef.dataset[self.graphdef.categories[0]];

  self.axes[self.config.graph.orientation === 'Horizontal' ? 'ver' : 'hor'].scale.domain(domainData.map(function (d) { return d.name; }));

  for (idx = 0, len = self.dataset.length; idx < len; idx = idx + 1) {
    areapath = self.chart.append('g').classed('cg-' + uv.util.formatClassName(self.categories[idx]), true)
                        .append('g').classed('cge-' + uv.util.formatClassName(self.categories[idx]), true).datum(self.dataset[idx]);
    areagroup = { path: areapath, linefunc: undefined, areafunc: undefined, line: undefined, area: undefined };
    self['draw' + self.config.graph.orientation + 'Area'](areagroup, idx);
    self.areagroups.push(areagroup);
  }

  self.finalize();
};

uv.AreaGraph.prototype = uv.util.inherits(uv.Graph);

uv.AreaGraph.prototype.setDefaults = function () {
  var self = this;
  self.graphdef.stepup = 'normal';
  return this;
};

uv.AreaGraph.prototype.drawHorizontalArea = function (areagroup, idx) {
  var self = this,
    color = uv.util.getColorBand(self.config, idx);

  self.axes.ver.scale.rangePoints([0, self.height()]);

  areagroup.linefunc = d3.svg.line()
        .x(function (d) { return self.axes.hor.scale(d.value); })
        .y(function (d) { return self.axes.ver.scale(d.name) + self.axes.ver.scale.rangeBand() / 2; })
        .interpolate(self.config.area.interpolation);

  areagroup.areafunc = d3.svg.area()
        .x0(self.axes.hor.scale(0))
        .x1(areagroup.linefunc.x())
        .y(areagroup.linefunc.y())
        .interpolate(self.config.area.interpolation);

  areagroup.area = areagroup.path.append('svg:path')
        .classed(uv.constants.classes.areapath + idx, true)
        .attr('d', areagroup.areafunc)
        .style('opacity', self.config.area.opacity)
        .style('-moz-opacity', self.config.area.opacity)
        .style('fill', color);

  areagroup.line = areagroup.path.append('svg:path')
        .classed(uv.constants.classes.linepath + idx, true)
        .attr('d', areagroup.linefunc)
        .style('stroke', 'white')
        .style('fill', 'none');

  areagroup.path.selectAll('.' + uv.constants.classes.dot)
        .data(self.dataset[idx])
        .enter().append('circle')
        .classed(uv.constants.classes.dot, true)
        .attr('cx', areagroup.linefunc.x())
        .attr('cy', areagroup.linefunc.y())
        .attr('r', 3.5)
        .style('fill', 'white');
};

uv.AreaGraph.prototype.drawVerticalArea = function (areagroup, idx) {
  var self = this,
    color = uv.util.getColorBand(self.config, idx);

  self.axes.hor.scale.rangePoints([0, self.width()]);

  areagroup.linefunc = d3.svg.line()
        .x(function (d) { return self.axes.hor.scale(d.name) + self.axes.hor.scale.rangeBand() / 2; })
        .y(function (d) { return self.axes.ver.scale(d.value); })
        .interpolate(self.config.area.interpolation);

  areagroup.areafunc = d3.svg.area()
        .x(areagroup.linefunc.x())
        .y0(areagroup.linefunc.y())
        .y1(self.axes.ver.scale(0))
        .interpolate(self.config.area.interpolation);

  areagroup.area = areagroup.path.append('svg:path')
        .classed(uv.constants.classes.areapath + idx, true)
        .attr('d', areagroup.areafunc)
        .style('opacity', self.config.area.opacity)
        .style('-moz-opacity', self.config.area.opacity)
        .style('fill', color);

  areagroup.line = areagroup.path.append('svg:path')
        .classed(uv.constants.classes.linepath + idx, true)
        .attr('d', areagroup.linefunc)
        .style('stroke', 'white')
        .style('fill', 'none');

  areagroup.path.selectAll('.' + uv.constants.classes.dot)
        .data(self.dataset[idx])
        .enter().append('circle')
        .classed(uv.constants.classes.dot, true)
        .attr('cx', areagroup.linefunc.x())
        .attr('cy', areagroup.linefunc.y())
        .attr('r', 3.5)
        .style('fill', 'white');
};
<commit_msg>changed the drawArea function so the color is not white all the time but takes the color from palette (before this on white background the line and points can not be seen)<commit_after>uv.AreaGraph = function (graphdef, config) {
  var self = this;
  uv.Graph.call(self, graphdef, config).setDefaults().init();

  self.areagroups = [];
  self.dataset = uv.util.getDataArray(self.graphdef);

  var areagroup, areapath, areafunc, idx, len,
    domainData = self.graphdef.dataset[self.graphdef.categories[0]];

  self.axes[self.config.graph.orientation === 'Horizontal' ? 'ver' : 'hor'].scale.domain(domainData.map(function (d) { return d.name; }));

  for (idx = 0, len = self.dataset.length; idx < len; idx = idx + 1) {
    areapath = self.chart.append('g').classed('cg-' + uv.util.formatClassName(self.categories[idx]), true)
                        .append('g').classed('cge-' + uv.util.formatClassName(self.categories[idx]), true).datum(self.dataset[idx]);
    areagroup = { path: areapath, linefunc: undefined, areafunc: undefined, line: undefined, area: undefined };
    self['draw' + self.config.graph.orientation + 'Area'](areagroup, idx);
    self.areagroups.push(areagroup);
  }

  self.finalize();
};

uv.AreaGraph.prototype = uv.util.inherits(uv.Graph);

uv.AreaGraph.prototype.setDefaults = function () {
  var self = this;
  self.graphdef.stepup = 'normal';
  return this;
};

uv.AreaGraph.prototype.drawHorizontalArea = function (areagroup, idx) {
  var self = this,
    color = uv.util.getColorBand(self.config, idx);

  self.axes.ver.scale.rangePoints([0, self.height()]);

  areagroup.linefunc = d3.svg.line()
        .x(function (d) { return self.axes.hor.scale(d.value); })
        .y(function (d) { return self.axes.ver.scale(d.name) + self.axes.ver.scale.rangeBand() / 2; })
        .interpolate(self.config.area.interpolation);

  areagroup.areafunc = d3.svg.area()
        .x0(self.axes.hor.scale(0))
        .x1(areagroup.linefunc.x())
        .y(areagroup.linefunc.y())
        .interpolate(self.config.area.interpolation);

  areagroup.area = areagroup.path.append('svg:path')
        .classed(uv.constants.classes.areapath + idx, true)
        .attr('d', areagroup.areafunc)
        .style('opacity', self.config.area.opacity)
        .style('-moz-opacity', self.config.area.opacity)
        .style('fill', color);

  areagroup.line = areagroup.path.append('svg:path')
        .classed(uv.constants.classes.linepath + idx, true)
        .attr('d', areagroup.linefunc)
        .style('stroke', color)
        .style('fill', 'none');

  areagroup.path.selectAll('.' + uv.constants.classes.dot)
        .data(self.dataset[idx])
        .enter().append('circle')
        .classed(uv.constants.classes.dot, true)
        .attr('cx', areagroup.linefunc.x())
        .attr('cy', areagroup.linefunc.y())
        .attr('r', 3.5)
        .style('fill', color);
};

uv.AreaGraph.prototype.drawVerticalArea = function (areagroup, idx) {
  var self = this,
    color = uv.util.getColorBand(self.config, idx);

  self.axes.hor.scale.rangePoints([0, self.width()]);

  areagroup.linefunc = d3.svg.line()
        .x(function (d) { return self.axes.hor.scale(d.name) + self.axes.hor.scale.rangeBand() / 2; })
        .y(function (d) { return self.axes.ver.scale(d.value); })
        .interpolate(self.config.area.interpolation);

  areagroup.areafunc = d3.svg.area()
        .x(areagroup.linefunc.x())
        .y0(areagroup.linefunc.y())
        .y1(self.axes.ver.scale(0))
        .interpolate(self.config.area.interpolation);

  areagroup.area = areagroup.path.append('svg:path')
        .classed(uv.constants.classes.areapath + idx, true)
        .attr('d', areagroup.areafunc)
        .style('opacity', self.config.area.opacity)
        .style('-moz-opacity', self.config.area.opacity)
        .style('fill', color);

  areagroup.line = areagroup.path.append('svg:path')
        .classed(uv.constants.classes.linepath + idx, true)
        .attr('d', areagroup.linefunc)
        .style('stroke', color)
        .style('fill', 'none');

  areagroup.path.selectAll('.' + uv.constants.classes.dot)
        .data(self.dataset[idx])
        .enter().append('circle')
        .classed(uv.constants.classes.dot, true)
        .attr('cx', areagroup.linefunc.x())
        .attr('cy', areagroup.linefunc.y())
        .attr('r', 3.5)
        .style('fill', color);
};
<|endoftext|>


<commit_before>/**
 * Room I/O is a socket wrapper which implements the basic functions of io part
 * @type {*|exports|module.exports}
 */
var express = require('express');
var io = require('socket.io')();
var rooms = require ('./models/rooms');
var app = require('../app');
var auth = require('./auth');

var lobby = rooms.getLobby();
var hashOfUserObjects = {};

var listen = function (server) {
	io.listen(server);
	console.log(app.locals);
	console.log('Server Started and Socket listened on ' + app.get('server-port'));
}

var roomio = io.of('/room');

roomio.on('connection', function (socket) {

	var clientId;
	var clientName;
	auth.verify(socket.handshake.token, function(err, decoded){
		if(err){
			console.log(err);
		} else{
			clientId = decoded.id;
			clientName = decoded.name;
		}
	});

	console.log('a user: ' + clientId + ' connected');
	console.log(socket.request.headers);

	hashOfUserObjects[clientId] = [];
	var socketClient = new rooms.SocketClient(clientId, socket);
	socketClient.joinRoom('0dab2c05-af24-46f3-80b0-41e4dd3d64bf');
	socketClient.groupBroadcast('message', {});

	/**
	 * Message IO Handler
	 * */
	socketClient.on('msgToGroup', msgToGroup);

	socketClient.on('msgToRoom', msgToRoom);

	socketClient.on('msgToUser', msgToUser);

	/**
	 * Canvas IO Handler
	 * */
	roomio.emit('canvasState', getAllCanvasObjects());

	socketClient.on('canvasAction', canvasAction);

	socketClient.on('canvasUndo', canvasUndo);

	socketClient.on('canvasClear', canvasClear);

	/*
	* WebRTC IO Handler
	* */
	socketClient.on('Emit Message', onSetupMessage(socketClient));

	/*
	* User Status Handler
	* */
	socketClient.on('New User', onNewUser(socketClient, socketClient.socketID));

    socketClient.on('disconnect', onDisconnection(socketClient));

	// -------- End of Web RTC IO -----------//
});

/**
 * ================ User Status IO =================
 * =================================================
 * */
function onNewUser(socketClient, clientId) {
	return function(message) {
		console.log('===================================== Got New User:', message);	        // for a real app, would be room only (not broadcast)

		addNewUserToList(clientId);
		responseIDToClient(socketClient, clientId);
		responseExistingUserToClient(socketClient);
		broadCastID(socketClient, clientId);
	}
}

function broadCastID(socketClient, ID) {
	socketClient.roomBroadcast('New Joined', {'userID':ID});
}

function onDisconnection(socketClient) {
	return function() {
		console.log('Disconnection: ', socketClient.userID);

		// Set disconnect value
		socketClient.setDisconnect();

		// Notify client side WebRTC on user leave
		socketClient.notifyGroupUsersOnUserLeave(socketClient.userID);
	}
}

/**
 * ================== WebRTC IO ===================
 * =================================================
 * */
var userIDList = [];
function addNewUserToList(curID) {
	userIDList.push(curID);
}

function responseIDToClient(socketClient, ID) {
	socketClient.emit('Assigned ID', {'assignedID': ID});
}

// Repond with all existing connected user in current group except myself
function responseExistingUserToClient(socketClient) {
	var currentGroupUserList = socketClient.getCurrentGroupUserList();
	var groupUserIDList = [];
	for (var index in currentGroupUserList) {
		if (currentGroupUserList[index].socketID != socketClient.socketID) {
			groupUserIDList.push(currentGroupUserList[index].socketID);
		}
	}
	socketClient.emit('Existing UserList', {'userIDList': groupUserIDList});
}

function onSetupMessage(socketClient) {
	return function(message) {
		console.log('!!!!!!! Set Up MESSAGE');
		socketClient.roomBroadcast('Setup Message', message);
	}
}

/**
 * ================== Message IO ===================
 * =================================================
 * */
var msgToGroup = function (msg) {
	console.log(msg);
	var user = lobby.getUser(clientId);
	if(user == null){
		console.log('no such user');
	}else{
		lobby.getUser(clientId).groupBroadcast('msgToGroup', clientName + msg);
	}
};

var msgToRoom = function (msg) {
	console.log(msg);
	var user = lobby.getUser(clientId);
	if(user == null){
		console.log('no such user');
	}else{
		lobby.getUser(clientId).roomBroadcast('msgToRoom', clientName + msg);
	}
};

var msgToUser = function (msg, receiverId) {
	console.log(msg);
	var user = lobby.getUser(clientId);
	if(user == null){
		console.log('no such user');
		this.emit('systemMsg', 'no such user');
	}else{
		lobby.getUser(clientId).personalMessage('msgToUser', clientName + msg, receiverId);
	}
};

/**
 * =================== Canvas IO ===================
 * =================================================
 * */
var canvasAction = function (action) {
	var clientId = socket.id;
	console.log(clientId);
	hashOfUserObjects[clientId].push(action);

	roomio.emit('canvasState', getAllCanvasObjects());

	// console.log(redisClient.lpush('canvasAction', action));

	// canvasio.emit('canvasAction', action);
	console.log(hashOfUserObjects);
};

var canvasUndo = function () {
	var clientId = socket.id;
	hashOfUserObjects[clientId].pop();
	roomio.emit('canvasState', getAllCanvasObjects());
};

var canvasClear = function(){
	clearAllCanvasObjects();
	roomio.emit('canvasState', getAllCanvasObjects());
};

var getAllCanvasObjects = function () {
	var currentCavansObjects = [];
	for (var userObjectsKey in hashOfUserObjects) {
		currentCavansObjects = currentCavansObjects.concat(hashOfUserObjects[userObjectsKey]);
		// console.log(hashOfUserObjects[userObjectsKey]);
	}
	return currentCavansObjects;
};

var clearAllCanvasObjects = function () {
	for (var userObjectsKey in hashOfUserObjects) {
		hashOfUserObjects[userObjectsKey] = [];
	}
};

module.exports.listen = listen;<commit_msg>Fix message IO handler callback<commit_after>/**
 * Room I/O is a socket wrapper which implements the basic functions of io part
 * @type {*|exports|module.exports}
 */
var express = require('express');
var io = require('socket.io')();
var rooms = require ('./models/rooms');
var app = require('../app');
var auth = require('./auth');

var lobby = rooms.getLobby();
var hashOfUserObjects = {};

var listen = function (server) {
	io.listen(server);
	console.log(app.locals);
	console.log('Server Started and Socket listened on ' + app.get('server-port'));
}

var roomio = io.of('/room');

roomio.on('connection', function (socket) {

	var clientId;
	var clientName;
	auth.verify(socket.handshake.token, function(err, decoded){
		if(err){
			console.log(err);
		} else{
			clientId = decoded.id;
			clientName = decoded.name;
		}
	});

	console.log('a user: ' + clientId + ' connected');
	console.log(socket.request.headers);

	hashOfUserObjects[clientId] = [];
	var socketClient = new rooms.SocketClient(clientId, socket);
	socketClient.joinRoom('0dab2c05-af24-46f3-80b0-41e4dd3d64bf');
	socketClient.groupBroadcast('message', {});

	/**
	 * Message IO Handler
	 * */
	socketClient.on('msgToGroup', msgToGroup(clientId, clientName));

	socketClient.on('msgToRoom', msgToRoom(clientId, clientName));

	socketClient.on('msgToUser', msgToUser(clientId, clientName));

	/**
	 * Canvas IO Handler
	 * */
	roomio.emit('canvasState', getAllCanvasObjects());

	socketClient.on('canvasAction', canvasAction);

	socketClient.on('canvasUndo', canvasUndo);

	socketClient.on('canvasClear', canvasClear);

	/*
	* WebRTC IO Handler
	* */
	socketClient.on('Emit Message', onSetupMessage(socketClient));

	/*
	* User Status Handler
	* */
	socketClient.on('New User', onNewUser(socketClient, socketClient.socketID));

    socketClient.on('disconnect', onDisconnection(socketClient));

	// -------- End of Web RTC IO -----------//
});

/**
 * ================ User Status IO =================
 * =================================================
 * */
function onNewUser(socketClient, clientId) {
	return function(message) {
		console.log('===================================== Got New User:', message);	        // for a real app, would be room only (not broadcast)

		addNewUserToList(clientId);
		responseIDToClient(socketClient, clientId);
		responseExistingUserToClient(socketClient);
		broadCastID(socketClient, clientId);
	}
}

function broadCastID(socketClient, ID) {
	socketClient.roomBroadcast('New Joined', {'userID':ID});
}

function onDisconnection(socketClient) {
	return function() {
		console.log('Disconnection: ', socketClient.userID);

		// Set disconnect value
		socketClient.setDisconnect();

		// Notify client side WebRTC on user leave
		socketClient.notifyGroupUsersOnUserLeave(socketClient.userID);
	}
}

/**
 * ================== WebRTC IO ===================
 * =================================================
 * */
var userIDList = [];
function addNewUserToList(curID) {
	userIDList.push(curID);
}

function responseIDToClient(socketClient, ID) {
	socketClient.emit('Assigned ID', {'assignedID': ID});
}

// Repond with all existing connected user in current group except myself
function responseExistingUserToClient(socketClient) {
	var currentGroupUserList = socketClient.getCurrentGroupUserList();
	var groupUserIDList = [];
	for (var index in currentGroupUserList) {
		if (currentGroupUserList[index].socketID != socketClient.socketID) {
			groupUserIDList.push(currentGroupUserList[index].socketID);
		}
	}
	socketClient.emit('Existing UserList', {'userIDList': groupUserIDList});
}

function onSetupMessage(socketClient) {
	return function(message) {
		console.log('!!!!!!! Set Up MESSAGE');
		socketClient.roomBroadcast('Setup Message', message);
	}
}

/**
 * ================== Message IO ===================
 * =================================================
 * */
var msgToGroup = function (clientId, clientName) {
	return function(msg) {
		console.log(msg);
		var user = lobby.getUser(clientId);
		if(user == null){
			console.log('no such user');
		}else{
			lobby.getUser(clientId).groupBroadcast('msgToGroup', clientName + msg);
		}
	}
};

var msgToRoom = function (clientId, clientName) {
	return function(msg) {
		console.log(msg);
		var user = lobby.getUser(clientId);
		if(user == null){
			console.log('no such user');
		}else{
			lobby.getUser(clientId).roomBroadcast('msgToRoom', clientName + msg);
		}
	};
};

var msgToUser = function (clientId, clientName) {
	return function(msg) {
		console.log(msg);
		var receiverId = getReceiverId(msg);
		var user = lobby.getUser(clientId);
		if(user == null){
			console.log('no such user');
			this.emit('systemMsg', 'no such user');
		}else{
			lobby.getUser(clientId).personalMessage('msgToUser', clientName + msg, receiverId);
		}
	}
};

var getReceiverId = function (msg) {
	return msg.receiverId;
}

/**
 * =================== Canvas IO ===================
 * =================================================
 * */
var canvasAction = function (action) {
	var clientId = socket.id;
	console.log(clientId);
	hashOfUserObjects[clientId].push(action);

	roomio.emit('canvasState', getAllCanvasObjects());

	// console.log(redisClient.lpush('canvasAction', action));

	// canvasio.emit('canvasAction', action);
	console.log(hashOfUserObjects);
};

var canvasUndo = function () {
	var clientId = socket.id;
	hashOfUserObjects[clientId].pop();
	roomio.emit('canvasState', getAllCanvasObjects());
};

var canvasClear = function(){
	clearAllCanvasObjects();
	roomio.emit('canvasState', getAllCanvasObjects());
};

var getAllCanvasObjects = function () {
	var currentCavansObjects = [];
	for (var userObjectsKey in hashOfUserObjects) {
		currentCavansObjects = currentCavansObjects.concat(hashOfUserObjects[userObjectsKey]);
		// console.log(hashOfUserObjects[userObjectsKey]);
	}
	return currentCavansObjects;
};

var clearAllCanvasObjects = function () {
	for (var userObjectsKey in hashOfUserObjects) {
		hashOfUserObjects[userObjectsKey] = [];
	}
};

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


<commit_before>module.exports = {
  rootDir: process.cwd(),
  packagesDir: "packages/",
  scanPatterns: [
    "<rootDir>/packages/**/lib/**/*.d.ts",
    "!<rootDir>/packages/**/lib/**/data/*.ts",
    "!<rootDir>/packages/seq",
    "!<rootDir>/packages/test-artillery",
    "!<rootDir>/packages/servestatic",
    "!<rootDir>/packages/testing/{bootstrap,inject,invoke,loadInjector}.ts",
    "!<rootDir>/packages/integration",
    "!<rootDir>/packages/integration-express",
    "!node_modules"
  ],
  outputDir: "<rootDir>/docs/api",
  baseUrl: "/api",
  jsonOutputDir: "<rootDir>/docs/.vuepress/public",
  scope: "@tsed",
  modules: {
    "core": "core",
    "di": "di",
    "common": {
      "config": "common/config",
      "converters": "common/converters",
      "filters": "common/filters",
      "jsonschema": "common/jsonschema",
      "mvc": "common/mvc",
      "interceptors": "common/interceptors",
      "server": "common/server"
    },
    "exceptions": "exceptions",
    "ajv": "ajv",
    "mongoose": "mongoose",
    "multipartfiles": "multipartfiles",
    "passport": "passport",
    "servestatic": "servestatic",
    "socketio": "socketio",
    "swagger": "swagger",
    "typeorm": "typeorm",
    "testing": "testing"
  }
};
<commit_msg>chore: fix documentation deployment<commit_after>module.exports = {
  rootDir: process.cwd(),
  packagesDir: "packages/",
  scanPatterns: [
    "<rootDir>/packages/**/lib/**/*.d.ts",
    "!<rootDir>/packages/**/lib/**/data/*.ts",
    "!<rootDir>/packages/seq",
    "!<rootDir>/packages/test-artillery",
    "!<rootDir>/packages/servestatic",
    "!<rootDir>/packages/testing/{bootstrap,inject,invoke,loadInjector}.ts",
    "!<rootDir>/packages/integration",
    "!<rootDir>/packages/integration-express",
    "!<rootDir>/packages/schema",
    "!<rootDir>/packages/json-mapper",
    "!<rootDir>/packages/common/mvc/utils",
    "!<rootDir>/packages/common/mvc/constants",
    "!<rootDir>/packages/common/converters/constants",
    "!<rootDir>/packages/common/jsonschema/utils/decoratorSchemaFactory",
    "!node_modules"
  ],
  outputDir: "<rootDir>/docs/api",
  baseUrl: "/api",
  jsonOutputDir: "<rootDir>/docs/.vuepress/public",
  scope: "@tsed",
  modules: {
    "core": "core",
    "di": "di",
    "common": {
      "config": "common/config",
      "converters": "common/converters",
      "filters": "common/filters",
      "jsonschema": "common/jsonschema",
      "mvc": "common/mvc",
      "interceptors": "common/interceptors",
      "server": "common/server"
    },
    "exceptions": "exceptions",
    "ajv": "ajv",
    "mongoose": "mongoose",
    "multipartfiles": "multipartfiles",
    "passport": "passport",
    "servestatic": "servestatic",
    "socketio": "socketio",
    "swagger": "swagger",
    "typeorm": "typeorm",
    "testing": "testing"
  }
};
<|endoftext|>


<commit_before>'use strict';

module.exports = function (language) {
  var osrmTextInstructionsOptions = {
    hooks: {
        tokenizedInstruction: function (instruction) {
          // enclose {way_name}, {rotary_name} and {destination} vars with ..
          // also support optional grammar or other var option after colon like {way_name:accusative}
          return instruction.replace(/\{(\w+):?\w*\}/g, function (token, tag) {
            switch (tag) {
              case 'way_name':
              case 'rotary_name':
              case 'destination':
                return '' + token + '';
            }
            return token;
        });
      }
    }
  };
  var osrmTextInstructions = require('osrm-text-instructions')('v5', language, osrmTextInstructionsOptions);

  function stepToText(step) {
    try {
      return osrmTextInstructions.compile(step);
    } catch(err) {
      console.log('Error when compiling text instruction', err, step);
      return undefined;
    }
  }

  function stepToLanes(step) {
    var lanes = step.intersections[0].lanes;

    if (!lanes) return [];

    return lanes.map(function(l) {
      var classes = ['leaflet-routing-icon', 'lanes'];
      if (!l.valid) classes.push(['invalid']);

      // check maneuver direction matches this lane one(s)
      var maneuverIndication = l.indications.indexOf(step.maneuver.modifier);
      var indication = (maneuverIndication === -1) ? l.indications[0] : step.maneuver.modifier;

      var icon;
      switch (indication) {
      case 'right':
      case 'sharp right':
        icon = 'turn-right';
        break;
      case 'slight right':
        icon = 'bear-right';
        break;
      case 'left':
      case 'slight left':
        icon = 'turn-left';
        break
      case 'sharp left':
        icon = 'bear-left';
        break;
      case 'uturn':
        icon = 'u-turn';
        break;
      //case 'straight':
      //case 'none':
      default:
        icon = 'continue';
        break;
      }
      classes.push('leaflet-routing-icon-' + icon);

      var span = L.DomUtil.create('span', classes.join(' '));

      // gray out lane icon if it's not for this maneuver
      if (maneuverIndication === -1)
        L.DomUtil.setOpacity(span, 0.5);

      return span;
    });
  }

  var L = require('leaflet');
  L.Routing = L.Routing || {};

  L.Routing.ItineraryBuilder = L.Class.extend({
    options: {
      containerClassName: ''
    },

    initialize: function(options) {
      L.setOptions(this, options);
    },

    createContainer: function(className) {
      var table = L.DomUtil.create('table', className || ''),
        colgroup = L.DomUtil.create('colgroup', '', table);

      L.DomUtil.create('col', 'leaflet-routing-instruction-icon', colgroup);
      L.DomUtil.create('col', 'leaflet-routing-instruction-text', colgroup);
      L.DomUtil.create('col', 'leaflet-routing-instruction-distance', colgroup);

      return table;
    },

    createStepsContainer: function() {
      return L.DomUtil.create('tbody', '');
    },

    createStep: function(text, distance, icon, steps) {
      var row = L.DomUtil.create('tr', '', steps),
        span,
        td;

      // icon
      td = L.DomUtil.create('td', '', row);
      span = L.DomUtil.create('span', 'leaflet-routing-icon leaflet-routing-icon-' + icon, td);
      td.appendChild(span);

      // text instruction
      td = L.DomUtil.create('td', '', row);
      // keep HTML tags instead:
      // td.appendChild(document.createTextNode(stepToText(text)));
      td.innerHTML = stepToText(text);

      // lanes
      var l = stepToLanes(text);
      if (l) {
        td.appendChild(document.createElement('br'));
        l.forEach(function(laneIcon) {
          td.appendChild(laneIcon);
        });
      }

      // distance steps
      // filter distance after arrival
      if (distance !== '0 m') {
        td = L.DomUtil.create('td', 'distance', row);
        td.appendChild(document.createTextNode(distance));
      }

      return row;
    }
  });

  return L.Routing;
}
<commit_msg>Fix sharp/slight left icon name misprint (#235)<commit_after>'use strict';

module.exports = function (language) {
  var osrmTextInstructionsOptions = {
    hooks: {
        tokenizedInstruction: function (instruction) {
          // enclose {way_name}, {rotary_name} and {destination} vars with ..
          // also support optional grammar or other var option after colon like {way_name:accusative}
          return instruction.replace(/\{(\w+):?\w*\}/g, function (token, tag) {
            switch (tag) {
              case 'way_name':
              case 'rotary_name':
              case 'destination':
                return '' + token + '';
            }
            return token;
        });
      }
    }
  };
  var osrmTextInstructions = require('osrm-text-instructions')('v5', language, osrmTextInstructionsOptions);

  function stepToText(step) {
    try {
      return osrmTextInstructions.compile(step);
    } catch(err) {
      console.log('Error when compiling text instruction', err, step);
      return undefined;
    }
  }

  function stepToLanes(step) {
    var lanes = step.intersections[0].lanes;

    if (!lanes) return [];

    return lanes.map(function(l) {
      var classes = ['leaflet-routing-icon', 'lanes'];
      if (!l.valid) classes.push(['invalid']);

      // check maneuver direction matches this lane one(s)
      var maneuverIndication = l.indications.indexOf(step.maneuver.modifier);
      var indication = (maneuverIndication === -1) ? l.indications[0] : step.maneuver.modifier;

      var icon;
      switch (indication) {
      case 'right':
        icon = 'turn-right';
        break;
      case 'sharp right':
        icon = 'sharp-right';
        break;
      case 'slight right':
        icon = 'bear-right';
        break;
      case 'left':
        icon = 'turn-left';
        break;
      case 'sharp left':
        icon = 'sharp-left';
        break;
      case 'slight left':
        icon = 'bear-left';
        break;
      case 'uturn':
        icon = 'u-turn';
        break;
      //case 'straight':
      //case 'none':
      default:
        icon = 'continue';
        break;
      }
      classes.push('leaflet-routing-icon-' + icon);

      var span = L.DomUtil.create('span', classes.join(' '));

      // gray out lane icon if it's not for this maneuver
      if (maneuverIndication === -1)
        L.DomUtil.setOpacity(span, 0.5);

      return span;
    });
  }

  var L = require('leaflet');
  L.Routing = L.Routing || {};

  L.Routing.ItineraryBuilder = L.Class.extend({
    options: {
      containerClassName: ''
    },

    initialize: function(options) {
      L.setOptions(this, options);
    },

    createContainer: function(className) {
      var table = L.DomUtil.create('table', className || ''),
        colgroup = L.DomUtil.create('colgroup', '', table);

      L.DomUtil.create('col', 'leaflet-routing-instruction-icon', colgroup);
      L.DomUtil.create('col', 'leaflet-routing-instruction-text', colgroup);
      L.DomUtil.create('col', 'leaflet-routing-instruction-distance', colgroup);

      return table;
    },

    createStepsContainer: function() {
      return L.DomUtil.create('tbody', '');
    },

    createStep: function(text, distance, icon, steps) {
      var row = L.DomUtil.create('tr', '', steps),
        span,
        td;

      // icon
      td = L.DomUtil.create('td', '', row);
      span = L.DomUtil.create('span', 'leaflet-routing-icon leaflet-routing-icon-' + icon, td);
      td.appendChild(span);

      // text instruction
      td = L.DomUtil.create('td', '', row);
      // keep HTML tags instead:
      // td.appendChild(document.createTextNode(stepToText(text)));
      td.innerHTML = stepToText(text);

      // lanes
      var l = stepToLanes(text);
      if (l) {
        td.appendChild(document.createElement('br'));
        l.forEach(function(laneIcon) {
          td.appendChild(laneIcon);
        });
      }

      // distance steps
      // filter distance after arrival
      if (distance !== '0 m') {
        td = L.DomUtil.create('td', 'distance', row);
        td.appendChild(document.createTextNode(distance));
      }

      return row;
    }
  });

  return L.Routing;
}
<|endoftext|>


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

var rnaSequenceView = function(upi) {
	this.upi = upi;
};

rnaSequenceView.prototype.initialize = function() {

	obj = this;

	load_xrefs();
	activate_tooltips();
	activate_literature_references();
	activate_species_tree();
	enable_show_species_tab_action();
	enable_species_tree_scroll_action();

	function load_xrefs() {
      xref_loader = new xrefLoader(obj.upi);
      xref_loader.load_xrefs();
	};

	function activate_tooltips() {
      $('body').tooltip({
          selector: '.help',
          delay: { show: 200, hide: 100 }
      });
	};

	function activate_literature_references() {
      $(document).on('click', '.literature-refs-retrieve', function(){
          var $this = $(this);
          var accession = $this.data('accession');
          var target = $this.siblings('.literature-refs-content');

          insert_content = function(data) {
              var source = $("#handlebars-literature-reference-tmpl").html();
              var template = Handlebars.compile(source);
              var wrapper  = {refs: data};
              target.html(template(wrapper));
          };

          activate_abstract_buttons = function() {
              $this.siblings().find('.abstract-btn').EuropePMCAbstracts({
                'target_class': '.abstract-text',
                'pubmed_id_data_attribute': 'pubmed-id',
                'msg': {
                  'show_abstract': 'Show abstract',
                  'hide_abstract': 'Hide abstract',
                }
              });
          };

          if ( target.html().length > 0 ) {
              target.slideToggle();
          } else {
            $.get('/api/v1/accession/' + accession + '/citations', function(data){
                insert_content(data);
                activate_abstract_buttons();
                target.slideDown();
            });
          }
      });
	};

	function activate_species_tree() {
      var d3_species_tree = $('#d3-species-tree');
      if(!document.createElement('svg').getAttributeNS){
        d3_species_tree.html('Your browser does not support SVG');
      } else {
        $.ajax({
          url: "/rna/" + obj.upi + "/lineage",
          dataType: "json",
          success: function(data) {
            var tree = $('#d3-species-tree');
            tree.hide().html('');
            d3SpeciesTree(data, '#d3-species-tree');
            tree.fadeIn();
          },
          error: function() {
            var source = $("#handlebars-loading-error-tmpl").html();
            var msg = Handlebars.compile(source);
            d3_species_tree.hide().html(msg).fadeIn();
          }
        });
      }
    };

    function enable_show_species_tab_action() {
      // clicking the species link to view the Species tab
      $("#show-species-tab").click(function(){
        $('#tabs a[data-target="#species"]').tab('show');
        return false;
      });
    };

    function enable_species_tree_scroll_action() {
      // scoll the species tree to the species level
      $("#d3-species-scroll-tree").click(function(){
        $('#d3-species-tree-tab').scrollLeft($('#d3-species-tree-tab svg').attr('width'));
      });
    };

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

var rnaSequenceView = function(upi) {
	this.upi = upi;
};

rnaSequenceView.prototype.initialize = function() {

	obj = this;

	load_xrefs();
	activate_tooltips();
	activate_literature_references();
	activate_species_tree();
  activate_abstract_buttons($('.abstract-btn'));
	enable_show_species_tab_action();
	enable_species_tree_scroll_action();

	function load_xrefs() {
      xref_loader = new xrefLoader(obj.upi);
      xref_loader.load_xrefs();
	};

	function activate_tooltips() {
      $('body').tooltip({
          selector: '.help',
          delay: { show: 200, hide: 100 }
      });
	};

	function activate_literature_references() {
      $(document).on('click', '.literature-refs-retrieve', function(){
          var $this = $(this);
          var accession = $this.data('accession');
          var target = $this.siblings('.literature-refs-content');

          insert_content = function(data) {
              var source = $("#handlebars-literature-reference-tmpl").html();
              var template = Handlebars.compile(source);
              var wrapper  = {refs: data};
              target.html(template(wrapper));
          };

          if ( target.html().length > 0 ) {
              target.slideToggle();
          } else {
            $.get('/api/v1/accession/' + accession + '/citations', function(data){
                insert_content(data);
                activate_abstract_buttons($this.siblings().find('.abstract-btn'));
                target.slideDown();
            });
          }
      });
	};

	function activate_species_tree() {
      var d3_species_tree = $('#d3-species-tree');
      if(!document.createElement('svg').getAttributeNS){
        d3_species_tree.html('Your browser does not support SVG');
      } else {
        $.ajax({
          url: "/rna/" + obj.upi + "/lineage",
          dataType: "json",
          success: function(data) {
            var tree = $('#d3-species-tree');
            tree.hide().html('');
            d3SpeciesTree(data, '#d3-species-tree');
            tree.fadeIn();
          },
          error: function() {
            var source = $("#handlebars-loading-error-tmpl").html();
            var msg = Handlebars.compile(source);
            d3_species_tree.hide().html(msg).fadeIn();
          }
        });
      }
    };

    function enable_show_species_tab_action() {
      // clicking the species link to view the Species tab
      $("#show-species-tab").click(function(){
        $('#tabs a[data-target="#species"]').tab('show');
        return false;
      });
    };

    function enable_species_tree_scroll_action() {
      // scoll the species tree to the species level
      $("#d3-species-scroll-tree").click(function(){
        $('#d3-species-tree-tab').scrollLeft($('#d3-species-tree-tab svg').attr('width'));
      });
    };

    function activate_abstract_buttons(target) {
        target.EuropePMCAbstracts({
          'target_class': '.abstract-text',
          'pubmed_id_data_attribute': 'pubmed-id',
          'msg': {
            'show_abstract': 'Show abstract',
            'hide_abstract': 'Hide abstract',
          }
        });
    };

};
<|endoftext|>


<commit_before>/*!
 * Module dependencies.
 */

var fs = require('fs-extra'),
	path = require('path'),
	_ = require('underscore'),
	moment = require('moment'),
	async = require('async'),
	util = require('util'),
	utils = require('keystone-utils'),
	super_ = require('../field');

/**
 * localfile FieldType Constructor
 * @extends Field
 * @api public
 */

function localfile(list, path, options) {
	this._underscoreMethods = ['format', 'uploadFile'];

	// event queues
	this._pre = {
		move: [] // Before file is moved into final destination
	};

	this._post = {
		move: [] // After file is moved into final destination
	};

	// TODO: implement filtering, usage disabled for now
	options.nofilter = true;

	// TODO: implement initial form, usage disabled for now
	if (options.initial) {
		throw new Error('Invalid Configuration\n\n' +
			'localfile fields (' + list.key + '.' + path + ') do not currently support being used as initial fields.\n');
	}

	localfile.super_.call(this, list, path, options);

	// validate destination dir
	if (!options.dest) {
		throw new Error('Invalid Configuration\n\n' +
			'localfile fields (' + list.key + '.' + path + ') require the "dest" option to be set.');
	}

	// Allow hook into before and after
	if (options.pre && options.pre.move) {
		this._pre.move = this._pre.move.concat(options.pre.move);
	}

	if (options.post && options.post.move) {
		this._post.move = this._post.move.concat(options.post.move);
	}
}

/*!
 * Inherit from Field
 */

util.inherits(localfile, super_);

/**
 * Allows you to add pre middleware after the field has been initialised
 *
 * @api public
 */

localfile.prototype.pre = function(event, fn) {
	if (!this._pre[event]) {
		throw new Error('localfile (' + this.list.key + '.' + this.path + ') error: localfile.pre()\n\n' +
			'Event ' + event + ' is not supported.\n');
	}
	this._pre[event].push(fn);
	return this;
};

/**
 * Allows you to add post middleware after the field has been initialised
 *
 * @api public
 */

localfile.prototype.post = function(event, fn) {
	if (!this._post[event]) {
		throw new Error('localfile (' + this.list.key + '.' + this.path + ') error: localfile.post()\n\n' +
			'Event ' + event + ' is not supported.\n');
	}
	this._post[event].push(fn);
	return this;
};

/**
 * Registers the field on the List's Mongoose Schema.
 *
 * @api public
 */

localfile.prototype.addToSchema = function() {

	var field = this,
		schema = this.list.schema;

	var paths = this.paths = {
		// fields
		filename:		this._path.append('.filename'),
		path:			this._path.append('.path'),
		size:			this._path.append('.size'),
		filetype:		this._path.append('.filetype'),
		// virtuals
		exists:			this._path.append('.exists'),
		href:			this._path.append('.href'),
		upload:			this._path.append('_upload'),
		action:			this._path.append('_action')
	};

	var schemaPaths = this._path.addTo({}, {
		filename:		String,
		path:			String,
		size:			Number,
		filetype:		String
	});

	schema.add(schemaPaths);

	// exists checks for a matching file at run-time
	var exists = function(item) {
		var filepath = item.get(paths.path),
			filename = item.get(paths.filename);

		if (!filepath || !filename) {
			return false;
		}

		return fs.existsSync(path.join(filepath, filename));
	};

	// The .exists virtual indicates whether a file is stored
	schema.virtual(paths.exists).get(function() {
		return schemaMethods.exists.apply(this);
	});

	// The .href virtual returns the public path of the file
	schema.virtual(paths.href).get(function() {
		return field.href.call(field, this);
	});

	// reset clears the value of the field
	var reset = function(item) {
		item.set(field.path, {
			filename: '',
			path: '',
			size: 0,
			filetype: ''
		});
	};

	var schemaMethods = {
		exists: function() {
			return exists(this);
		},
		/**
		 * Resets the value of the field
		 *
		 * @api public
		 */
		reset: function() {
			reset(this);
		},
		/**
		 * Deletes the file from localfile and resets the field
		 *
		 * @api public
		 */
		delete: function() {
			if (exists(this)) {
				fs.unlinkSync(path.join(this.get(paths.path), this.get(paths.filename)));
			}
			reset(this);
		}
	};

	_.each(schemaMethods, function(fn, key) {
		field.underscoreMethod(key, fn);
	});

	// expose a method on the field to call schema methods
	this.apply = function(item, method) {
		return schemaMethods[method].apply(item, Array.prototype.slice.call(arguments, 2));
	};

	this.bindUnderscoreMethods();
};

/**
 * Formats the field value
 *
 * Delegates to the options.format function if it exists.
 * @api public
 */

localfile.prototype.format = function(item) {
	if (this.hasFormatter()) {
		var file = item.get(this.path);
		file.href = this.href(item);
		return this.options.format.call(this, item, file);
	}
	return this.href(item);
};

/**
 * Detects the field have formatter function
 *
 * @api public
 */

localfile.prototype.hasFormatter = function() {
	return 'function' === typeof this.options.format;
};

/**
 * Return objects href
 *
 * @api public
 */

localfile.prototype.href = function(item) {
	if (this.options.prefix) {
		return this.options.prefix + '/' + item.get(this.paths.filename);
	}
	return path.join(item.get(this.paths.path), item.get(this.paths.filename));
};

/**
 * Detects whether the field has been modified
 *
 * @api public
 */

localfile.prototype.isModified = function(item) {
	return item.isModified(this.paths.path);
};

/**
 * Validates that a value for this field has been provided in a data object
 *
 * @api public
 */

localfile.prototype.validateInput = function(data) {
	// TODO - how should file field input be validated?
	return true;
};

/**
 * Updates the value for this field in the item from a data object
 *
 * @api public
 */

localfile.prototype.updateItem = function(item, data) {
	// TODO - direct updating of data (not via upload)
};

/**
 * Uploads the file for this field
 *
 * @api public
 */

localfile.prototype.uploadFile = function(item, file, update, callback) {

	var field = this,
		prefix = field.options.datePrefix ? moment().format(field.options.datePrefix) + '-' : '',
		name = prefix + file.name;

	if (field.options.allowedTypes && !_.contains(field.options.allowedTypes, file.type)){
		return callback(new Error('Unsupported File Type: '+file.type));
	}

	if ('function' === typeof update) {
		callback = update;
		update = false;
	}

	var doMove = function(callback) {

		if ('function' === typeof field.options.filename) {
			name = field.options.filename(item, name);
		}

		fs.move(file.path, path.join(field.options.dest, name), function(err) {

			if (err) return callback(err);

			var fileData = {
				filename: name,
				path: field.options.dest,
				size: file.size,
				filetype: file.type
			};

			if (update) {
				item.set(field.path, fileData);
			}

			callback(null, fileData);

		});
	};

	async.eachSeries(this._pre.move, function(fn, next) {
		fn(item, file, next);
	}, function(err) {

		if (err) return callback(err);

		doMove(function(err, fileData) {
			if (err) return callback(err);

			async.eachSeries(field._post.move, function(fn, next) {
				fn(item, file, fileData, next);
			}, function(err) {
				if (err) return callback(err);
				callback(null, fileData);
			});
		});

	});
};

/**
 * Returns a callback that handles a standard form submission for the field
 *
 * Expected form parts are
 * - `field.paths.action` in `req.body` (`clear` or `delete`)
 * - `field.paths.upload` in `req.files` (uploads the file to localfile)
 *
 * @api public
 */

localfile.prototype.getRequestHandler = function(item, req, paths, callback) {

	var field = this;

	if (utils.isFunction(paths)) {
		callback = paths;
		paths = field.paths;
	} else if (!paths) {
		paths = field.paths;
	}

	callback = callback || function() {};

	return function() {

		if (req.body) {
			var action = req.body[paths.action];

			if (/^(delete|reset)$/.test(action)) {
				field.apply(item, action);
			}
		}

		if (req.files && req.files[paths.upload] && req.files[paths.upload].size) {
			return field.uploadFile(item, req.files[paths.upload], true, callback);
		}

		return callback();

	};

};

/**
 * Immediately handles a standard form submission for the field (see `getRequestHandler()`)
 *
 * @api public
 */

localfile.prototype.handleRequest = function(item, req, paths, callback) {
	this.getRequestHandler(item, req, paths, callback)();
};

/*!
 * Export class
 */

exports = module.exports = localfile;
<commit_msg>Overwrite existing files by default in localfile<commit_after>/*!
 * Module dependencies.
 */

var fs = require('fs-extra'),
	path = require('path'),
	_ = require('underscore'),
	moment = require('moment'),
	async = require('async'),
	util = require('util'),
	utils = require('keystone-utils'),
	super_ = require('../field');

/**
 * localfile FieldType Constructor
 * @extends Field
 * @api public
 */

function localfile(list, path, options) {
	this._underscoreMethods = ['format', 'uploadFile'];

	// event queues
	this._pre = {
		move: [] // Before file is moved into final destination
	};

	this._post = {
		move: [] // After file is moved into final destination
	};

	// TODO: implement filtering, usage disabled for now
	options.nofilter = true;

	// TODO: implement initial form, usage disabled for now
	if (options.initial) {
		throw new Error('Invalid Configuration\n\n' +
			'localfile fields (' + list.key + '.' + path + ') do not currently support being used as initial fields.\n');
	}

	if (options.overwrite !== false) {
		options.overwrite = true;
	}

	localfile.super_.call(this, list, path, options);

	// validate destination dir
	if (!options.dest) {
		throw new Error('Invalid Configuration\n\n' +
			'localfile fields (' + list.key + '.' + path + ') require the "dest" option to be set.');
	}

	// Allow hook into before and after
	if (options.pre && options.pre.move) {
		this._pre.move = this._pre.move.concat(options.pre.move);
	}

	if (options.post && options.post.move) {
		this._post.move = this._post.move.concat(options.post.move);
	}
}

/*!
 * Inherit from Field
 */

util.inherits(localfile, super_);

/**
 * Allows you to add pre middleware after the field has been initialised
 *
 * @api public
 */

localfile.prototype.pre = function(event, fn) {
	if (!this._pre[event]) {
		throw new Error('localfile (' + this.list.key + '.' + this.path + ') error: localfile.pre()\n\n' +
			'Event ' + event + ' is not supported.\n');
	}
	this._pre[event].push(fn);
	return this;
};

/**
 * Allows you to add post middleware after the field has been initialised
 *
 * @api public
 */

localfile.prototype.post = function(event, fn) {
	if (!this._post[event]) {
		throw new Error('localfile (' + this.list.key + '.' + this.path + ') error: localfile.post()\n\n' +
			'Event ' + event + ' is not supported.\n');
	}
	this._post[event].push(fn);
	return this;
};

/**
 * Registers the field on the List's Mongoose Schema.
 *
 * @api public
 */

localfile.prototype.addToSchema = function() {

	var field = this,
		schema = this.list.schema;

	var paths = this.paths = {
		// fields
		filename:		this._path.append('.filename'),
		path:			this._path.append('.path'),
		size:			this._path.append('.size'),
		filetype:		this._path.append('.filetype'),
		// virtuals
		exists:			this._path.append('.exists'),
		href:			this._path.append('.href'),
		upload:			this._path.append('_upload'),
		action:			this._path.append('_action')
	};

	var schemaPaths = this._path.addTo({}, {
		filename:		String,
		path:			String,
		size:			Number,
		filetype:		String
	});

	schema.add(schemaPaths);

	// exists checks for a matching file at run-time
	var exists = function(item) {
		var filepath = item.get(paths.path),
			filename = item.get(paths.filename);

		if (!filepath || !filename) {
			return false;
		}

		return fs.existsSync(path.join(filepath, filename));
	};

	// The .exists virtual indicates whether a file is stored
	schema.virtual(paths.exists).get(function() {
		return schemaMethods.exists.apply(this);
	});

	// The .href virtual returns the public path of the file
	schema.virtual(paths.href).get(function() {
		return field.href.call(field, this);
	});

	// reset clears the value of the field
	var reset = function(item) {
		item.set(field.path, {
			filename: '',
			path: '',
			size: 0,
			filetype: ''
		});
	};

	var schemaMethods = {
		exists: function() {
			return exists(this);
		},
		/**
		 * Resets the value of the field
		 *
		 * @api public
		 */
		reset: function() {
			reset(this);
		},
		/**
		 * Deletes the file from localfile and resets the field
		 *
		 * @api public
		 */
		delete: function() {
			if (exists(this)) {
				fs.unlinkSync(path.join(this.get(paths.path), this.get(paths.filename)));
			}
			reset(this);
		}
	};

	_.each(schemaMethods, function(fn, key) {
		field.underscoreMethod(key, fn);
	});

	// expose a method on the field to call schema methods
	this.apply = function(item, method) {
		return schemaMethods[method].apply(item, Array.prototype.slice.call(arguments, 2));
	};

	this.bindUnderscoreMethods();
};

/**
 * Formats the field value
 *
 * Delegates to the options.format function if it exists.
 * @api public
 */

localfile.prototype.format = function(item) {
	if (this.hasFormatter()) {
		var file = item.get(this.path);
		file.href = this.href(item);
		return this.options.format.call(this, item, file);
	}
	return this.href(item);
};

/**
 * Detects the field have formatter function
 *
 * @api public
 */

localfile.prototype.hasFormatter = function() {
	return 'function' === typeof this.options.format;
};

/**
 * Return objects href
 *
 * @api public
 */

localfile.prototype.href = function(item) {
	if (this.options.prefix) {
		return this.options.prefix + '/' + item.get(this.paths.filename);
	}
	return path.join(item.get(this.paths.path), item.get(this.paths.filename));
};

/**
 * Detects whether the field has been modified
 *
 * @api public
 */

localfile.prototype.isModified = function(item) {
	return item.isModified(this.paths.path);
};

/**
 * Validates that a value for this field has been provided in a data object
 *
 * @api public
 */

localfile.prototype.validateInput = function(data) {
	// TODO - how should file field input be validated?
	return true;
};

/**
 * Updates the value for this field in the item from a data object
 *
 * @api public
 */

localfile.prototype.updateItem = function(item, data) {
	// TODO - direct updating of data (not via upload)
};

/**
 * Uploads the file for this field
 *
 * @api public
 */

localfile.prototype.uploadFile = function(item, file, update, callback) {

	var field = this,
		prefix = field.options.datePrefix ? moment().format(field.options.datePrefix) + '-' : '',
		name = prefix + file.name;

	if (field.options.allowedTypes && !_.contains(field.options.allowedTypes, file.type)){
		return callback(new Error('Unsupported File Type: '+file.type));
	}

	if ('function' === typeof update) {
		callback = update;
		update = false;
	}

	var doMove = function(callback) {

		if ('function' === typeof field.options.filename) {
			name = field.options.filename(item, name);
		}

		fs.move(file.path, path.join(field.options.dest, name), { clobber: field.options.overwrite }, function(err) {

			if (err) return callback(err);

			var fileData = {
				filename: name,
				path: field.options.dest,
				size: file.size,
				filetype: file.type
			};

			if (update) {
				item.set(field.path, fileData);
			}

			callback(null, fileData);

		});
	};

	async.eachSeries(this._pre.move, function(fn, next) {
		fn(item, file, next);
	}, function(err) {

		if (err) return callback(err);

		doMove(function(err, fileData) {
			if (err) return callback(err);

			async.eachSeries(field._post.move, function(fn, next) {
				fn(item, file, fileData, next);
			}, function(err) {
				if (err) return callback(err);
				callback(null, fileData);
			});
		});

	});
};

/**
 * Returns a callback that handles a standard form submission for the field
 *
 * Expected form parts are
 * - `field.paths.action` in `req.body` (`clear` or `delete`)
 * - `field.paths.upload` in `req.files` (uploads the file to localfile)
 *
 * @api public
 */

localfile.prototype.getRequestHandler = function(item, req, paths, callback) {

	var field = this;

	if (utils.isFunction(paths)) {
		callback = paths;
		paths = field.paths;
	} else if (!paths) {
		paths = field.paths;
	}

	callback = callback || function() {};

	return function() {

		if (req.body) {
			var action = req.body[paths.action];

			if (/^(delete|reset)$/.test(action)) {
				field.apply(item, action);
			}
		}

		if (req.files && req.files[paths.upload] && req.files[paths.upload].size) {
			return field.uploadFile(item, req.files[paths.upload], true, callback);
		}

		return callback();

	};

};

/**
 * Immediately handles a standard form submission for the field (see `getRequestHandler()`)
 *
 * @api public
 */

localfile.prototype.handleRequest = function(item, req, paths, callback) {
	this.getRequestHandler(item, req, paths, callback)();
};

/*!
 * Export class
 */

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


<commit_before>var fs = require('fs');
var shell = require('shelljs');

exports.specVersion = '1.1.0';

exports.updateFiles = function (params, cb) {
  // Read in our `setup.py`
  fs.readFile('setup.py', 'utf8', function handleFile (err, pythonSetup) {
    // If there is an error, callback with it
    if (err) {
      return cb(err);
    }

    // Otherwise, replace the semver and update the file
    var output = pythonSetup.replace(/version='\d+\.\d+\.\d+'/, 'version=\'' + params.version + '\'');
    fs.writeFile('setup.py', output, 'utf8', cb);
  });
};

exports.register = function (params, cb) {
  if (!shell.test('-f', '.pypi-private')) {
    shell.exec('python setup.py register');
  }

  // Callback
  process.nextTick(cb);
};

exports.publish = function (params, cb) {
  if (!shell.test('-f', '.pypi-private')) {
    // Build and upload the package
    shell.exec('python setup.py sdist --formats=gztar,zip upload');
  }

  // Callback
  process.nextTick(cb);
};
<commit_msg>Removed legacy specVersion export<commit_after>var fs = require('fs');
var shell = require('shelljs');

exports.updateFiles = function (params, cb) {
  // Read in our `setup.py`
  fs.readFile('setup.py', 'utf8', function handleFile (err, pythonSetup) {
    // If there is an error, callback with it
    if (err) {
      return cb(err);
    }

    // Otherwise, replace the semver and update the file
    var output = pythonSetup.replace(/version='\d+\.\d+\.\d+'/, 'version=\'' + params.version + '\'');
    fs.writeFile('setup.py', output, 'utf8', cb);
  });
};

exports.register = function (params, cb) {
  if (!shell.test('-f', '.pypi-private')) {
    shell.exec('python setup.py register');
  }

  // Callback
  process.nextTick(cb);
};

exports.publish = function (params, cb) {
  if (!shell.test('-f', '.pypi-private')) {
    // Build and upload the package
    shell.exec('python setup.py sdist --formats=gztar,zip upload');
  }

  // Callback
  process.nextTick(cb);
};
<|endoftext|>


<commit_before>// $Header: /cvsroot/tikiwiki/tiki/lib/freetag/freetag_ajax.js,v 1.16 2006-01-29 00:46:13 amette Exp $

//var maxRecords gets defined in the template !
var objectType = '';
var currentTag = '';
var filter = '';
var offset = 0;
var count = 0;
var selectedElement = false;

function browseToTag(tag) {
	resetOffset();
	listObjects(tag);
}

function setObjectType(type, button) {
	resetOffset();
	objectType = type;
	if (!selectedElement)
		selectedElement = document.getElementById('typeAll');
	selectedElement.className = 'linkbut';
	button = document.getElementById(button);
	button.className= 'linkbut highlight';
	selectedElement = button;
	listObjects(currentTag);
}

function setFilter(find) {
	resetOffset();
	filter = find;
	listObjects(currentTag);
}

function listObjects(tag) {
	currentTag = tag;
	var cp = new cpaint();
	cp.set_response_type('XML');
	//cp.set_debug(2);

	document.getElementById('ajaxLoading').style.display = 'block';

	cp.call('tiki-freetag_list_objects_ajax.php', 'list_objects', renderObjectList, tag, objectType, offset, filter);
}

function renderObjectList(result) {
	var objects = result.getElementsByTagName('object');

	if (!objects.length) {
		wipeList(0);
		document.getElementById('ajaxLoading').style.display = 'none';
		return;
	}

	var data = new Array();
	for (var i=0; i<objects.length; i++) {
		var obj = objects[i];
		var item = new Array();
		for (var j=0; j<obj.childNodes.length; j++) {
			item[obj.childNodes[j]['tagName']] = obj.childNodes[j]['textContent'];
		}
		data[i] = item;
	}

	for (var i=0; i<data.length; i++) {
		var item = data[i];
		document.getElementById('freetagObjectLink_' + (i) ).href = item['href'];
		document.getElementById('freetagObjectLink_' + (i) ).innerHTML = item['name'];
		document.getElementById('freetagObjectType_' + (i) ).innerHTML = item['type'];
		document.getElementById('freetagObjectDescription_' + (i) ).innerHTML = item['description'];
	}

	if (data.length < maxRecords) { // Need to wipe out the rest
		wipeList(data.length)
	}

	if (currentTag && document.getElementById('currentTag1')) {
		document.getElementById('currentTag1').innerHTML = currentTag;
	}
	if (currentTag && document.getElementById('currentTag2')) {
		document.getElementById('currentTag2').innerHTML = currentTag;
	}

	updatePageCount(result);
	document.getElementById('ajaxLoading').style.display = 'none';
}

/*
	Functions for pagination of results
*/

function setOffset(deltaOffset) {
	if (((offset + deltaOffset) < count) && ((offset + deltaOffset) >= 0)) {
		offset = offset + deltaOffset;
		listObjects(currentTag);
	}
}

function resetOffset() {
	offset = 0;
	document.getElementById('actual_page').innerHTML = 1;
}

function wipeList(start) {
	for (var i=start; i<maxRecords; i++) {
		document.getElementById('freetagObjectLink_' + (i) ).href = '';
		document.getElementById('freetagObjectLink_' + (i) ).innerHTML = '';
		document.getElementById('freetagObjectType_' + (i) ).innerHTML = '';
		document.getElementById('freetagObjectDescription_' + (i) ).innerHTML = '';
	}
}

function updatePageCount(result) {
	count = result.getElementsByTagName('cant').item(0).firstChild.data;
	var cant_pages = Math.ceil(count / maxRecords);
	var pageLink = '';
	document.getElementById('cant_pages').innerHTML = cant_pages;
	curPage = 1 + (offset / maxRecords);
	document.getElementById('actual_page').innerHTML = curPage;
	if (directPagination == 'y') {
		for (var i=0; i<cant_pages; i++) {
			pageLink += ''+(i+1)+' '+'';
		}
		document.getElementById('direct_pagination').innerHTML = pageLink;
	}
}
<commit_msg>ajax-pagination: Need to recalculate page-count also, when no results delivered and the page count is 1 not 0, when there are no items<commit_after>// $Header: /cvsroot/tikiwiki/tiki/lib/freetag/freetag_ajax.js,v 1.17 2006-01-29 01:04:41 amette Exp $

//var maxRecords gets defined in the template !
var objectType = '';
var currentTag = '';
var filter = '';
var offset = 0;
var count = 0;
var selectedElement = false;

function browseToTag(tag) {
	resetOffset();
	listObjects(tag);
}

function setObjectType(type, button) {
	resetOffset();
	objectType = type;
	if (!selectedElement)
		selectedElement = document.getElementById('typeAll');
	selectedElement.className = 'linkbut';
	button = document.getElementById(button);
	button.className= 'linkbut highlight';
	selectedElement = button;
	listObjects(currentTag);
}

function setFilter(find) {
	resetOffset();
	filter = find;
	listObjects(currentTag);
}

function listObjects(tag) {
	currentTag = tag;
	var cp = new cpaint();
	cp.set_response_type('XML');
	//cp.set_debug(2);

	document.getElementById('ajaxLoading').style.display = 'block';

	cp.call('tiki-freetag_list_objects_ajax.php', 'list_objects', renderObjectList, tag, objectType, offset, filter);
}

function renderObjectList(result) {
	var objects = result.getElementsByTagName('object');

	if (!objects.length) {
		wipeList(0);
		updatePageCount(result);
		document.getElementById('ajaxLoading').style.display = 'none';
		return;
	}

	var data = new Array();
	for (var i=0; i<objects.length; i++) {
		var obj = objects[i];
		var item = new Array();
		for (var j=0; j<obj.childNodes.length; j++) {
			item[obj.childNodes[j]['tagName']] = obj.childNodes[j]['textContent'];
		}
		data[i] = item;
	}

	for (var i=0; i<data.length; i++) {
		var item = data[i];
		document.getElementById('freetagObjectLink_' + (i) ).href = item['href'];
		document.getElementById('freetagObjectLink_' + (i) ).innerHTML = item['name'];
		document.getElementById('freetagObjectType_' + (i) ).innerHTML = item['type'];
		document.getElementById('freetagObjectDescription_' + (i) ).innerHTML = item['description'];
	}

	if (data.length < maxRecords) { // Need to wipe out the rest
		wipeList(data.length)
	}

	if (currentTag && document.getElementById('currentTag1')) {
		document.getElementById('currentTag1').innerHTML = currentTag;
	}
	if (currentTag && document.getElementById('currentTag2')) {
		document.getElementById('currentTag2').innerHTML = currentTag;
	}

	updatePageCount(result);
	document.getElementById('ajaxLoading').style.display = 'none';
}

/*
	Functions for pagination of results
*/

function setOffset(deltaOffset) {
	if (((offset + deltaOffset) < count) && ((offset + deltaOffset) >= 0)) {
		offset = offset + deltaOffset;
		listObjects(currentTag);
	}
}

function resetOffset() {
	offset = 0;
	document.getElementById('actual_page').innerHTML = 1;
}

function wipeList(start) {
	for (var i=start; i<maxRecords; i++) {
		document.getElementById('freetagObjectLink_' + (i) ).href = '';
		document.getElementById('freetagObjectLink_' + (i) ).innerHTML = '';
		document.getElementById('freetagObjectType_' + (i) ).innerHTML = '';
		document.getElementById('freetagObjectDescription_' + (i) ).innerHTML = '';
	}
}

function updatePageCount(result) {
	count = result.getElementsByTagName('cant').item(0).firstChild.data;
	var cant_pages = Math.ceil(count / maxRecords);
	if (cant_pages == 0) cant_pages = '1';
	document.getElementById('cant_pages').innerHTML = cant_pages;
	curPage = 1 + (offset / maxRecords);
	document.getElementById('actual_page').innerHTML = curPage;
	if (directPagination == 'y') {
		var pageLink = '';
		for (var i=0; i<cant_pages; i++) {
			pageLink += ''+(i+1)+' '+'';
		}
		document.getElementById('direct_pagination').innerHTML = pageLink;
	}
}
<|endoftext|>


<commit_before>var util = require("util");
var path = require("path");
var Q = require("q");
var _ = require("lodash");
var exec = require('child_process').exec;

var fs = require('graceful-fs');
var parse = require("../../parse");
var BaseGenerator = require("../page");
var stringUtils = require("../../utils/string");

var Generator = function() {
    BaseGenerator.apply(this, arguments);
};
util.inherits(Generator, BaseGenerator);

Generator.prototype.finish = function() {
    var that = this;

    return BaseGenerator.prototype.finish.apply(this)
    .then(function() {
        var d = Q.defer();
        var format = that.options.extension || path.extname(that.options.output).replace("\.", "") || "pdf";

        if (!that.options.cover && fs.existsSync(path.join(that.options.output, "cover.jpg"))) {
            that.options.cover = path.join(that.options.output, "cover.jpg");
        }

        var _options = {
            "--cover": that.options.cover,
            "--title": that.options.title,
            "--comments": that.options.description,
            "--authors": that.options.author,
            "--publisher": "GitBook",
            "--chapter": "descendant-or-self::*[contains(concat(' ', normalize-space(@class), ' '), ' book-chapter ')]",
            "--chapter-mark": "pagebreak",
            "--page-breaks-before": "/",
            "--level1-toc": "descendant-or-self::*[contains(concat(' ', normalize-space(@class), ' '), ' book-chapter-1 ')]",
            "--level2-toc": "descendant-or-self::*[contains(concat(' ', normalize-space(@class), ' '), ' book-chapter-2 ')]",
            "--level3-toc": "descendant-or-self::*[contains(concat(' ', normalize-space(@class), ' '), ' book-chapter-3 ')]",
            "--no-chapters-in-toc": true,
            "--max-levels": "1",
            "--breadth-first": true
        };

        if (format == "pdf") {
            var pdfOptions = that.options.pdf;

            _.extend(_options, {
                "--margin-left": String(pdfOptions.margin.left),
                "--margin-right": String(pdfOptions.margin.right),
                "--margin-top": String(pdfOptions.margin.top),
                "--margin-bottom": String(pdfOptions.margin.bottom),
                "--pdf-default-font-size": String(pdfOptions.fontSize),
                "--pdf-mono-font-size": String(pdfOptions.fontSize),
                "--paper-size": String(pdfOptions.paperSize),
                "--pdf-page-numbers": Boolean(pdfOptions.pageNumbers),
                "--pdf-header-template": String(pdfOptions.headerTemplate),
                "--pdf-footer-template": String(pdfOptions.footerTemplate)
            });

            if ('options' in pdfOptions) {
              _.extend(_options, pdfOptions.options);
              console.log('options', _options);
            }
        }

        var command = [
            "ebook-convert",
            path.join(that.options.output, "SUMMARY.html"),
            path.join(that.options.output, "index."+format),
            stringUtils.optionsToShellArgs(_options)
        ].join(" ");

        exec(command, function (error, stdout, stderr) {
            if (error) {
                if (error.code == 127) {
                    error.message = "Need to install ebook-convert from Calibre";
                } else {
                    error.message = error.message + " "+stdout;
                }
                return d.reject(error);
            }
            d.resolve();
        });

        return d.promise;
    });
};

module.exports = Generator;
<commit_msg>Add option to run ebook-convert with xvfb<commit_after>var util = require("util");
var path = require("path");
var Q = require("q");
var _ = require("lodash");
var exec = require('child_process').exec;

var fs = require('graceful-fs');
var parse = require("../../parse");
var BaseGenerator = require("../page");
var stringUtils = require("../../utils/string");

var Generator = function() {
    BaseGenerator.apply(this, arguments);
};
util.inherits(Generator, BaseGenerator);

Generator.prototype.finish = function() {
    var that = this;

    return BaseGenerator.prototype.finish.apply(this)
    .then(function() {
        var d = Q.defer();
        var format = that.options.extension || path.extname(that.options.output).replace("\.", "") || "pdf";

        if (!that.options.cover && fs.existsSync(path.join(that.options.output, "cover.jpg"))) {
            that.options.cover = path.join(that.options.output, "cover.jpg");
        }

        var _options = {
            "--cover": that.options.cover,
            "--title": that.options.title,
            "--comments": that.options.description,
            "--authors": that.options.author,
            "--publisher": "GitBook",
            "--chapter": "descendant-or-self::*[contains(concat(' ', normalize-space(@class), ' '), ' book-chapter ')]",
            "--chapter-mark": "pagebreak",
            "--page-breaks-before": "/",
            "--level1-toc": "descendant-or-self::*[contains(concat(' ', normalize-space(@class), ' '), ' book-chapter-1 ')]",
            "--level2-toc": "descendant-or-self::*[contains(concat(' ', normalize-space(@class), ' '), ' book-chapter-2 ')]",
            "--level3-toc": "descendant-or-self::*[contains(concat(' ', normalize-space(@class), ' '), ' book-chapter-3 ')]",
            "--no-chapters-in-toc": true,
            "--max-levels": "1",
            "--breadth-first": true
        };

        if (format == "pdf") {
            var pdfOptions = that.options.pdf;

            _.extend(_options, {
                "--margin-left": String(pdfOptions.margin.left),
                "--margin-right": String(pdfOptions.margin.right),
                "--margin-top": String(pdfOptions.margin.top),
                "--margin-bottom": String(pdfOptions.margin.bottom),
                "--pdf-default-font-size": String(pdfOptions.fontSize),
                "--pdf-mono-font-size": String(pdfOptions.fontSize),
                "--paper-size": String(pdfOptions.paperSize),
                "--pdf-page-numbers": Boolean(pdfOptions.pageNumbers),
                "--pdf-header-template": String(pdfOptions.headerTemplate),
                "--pdf-footer-template": String(pdfOptions.footerTemplate)
            });

            if ('options' in pdfOptions) {
              _.extend(_options, pdfOptions.options);
            }
        }

        var command = [
            "ebook-convert",
            path.join(that.options.output, "SUMMARY.html"),
            path.join(that.options.output, "index."+format),
            stringUtils.optionsToShellArgs(_options)
        ].join(" ");

        if (that.options.xvfb) {
          command = ["xvfb-run"].concat(command);
        }

        exec(command, function (error, stdout, stderr) {
            if (error) {
                if (error.code == 127) {
                    error.message = "Need to install ebook-convert from Calibre";
                } else {
                    error.message = error.message + " "+stdout;
                }
                return d.reject(error);
            }
            d.resolve();
        });

        return d.promise;
    });
};

module.exports = Generator;
<|endoftext|>


<commit_before>const { callEndpoint } = require('./callEndpoint');
const { forceArray, transformKey, transformObjectKeys } = require('./util/transformers');
const errors = require('./errors');

/**
 * remove a string pattern from a string
 *
 * @param {string} str string to remove pattern from
 * @param {string|regex} pattern pattern to remove
 * @return {string} string with the pattern removed
 */
const removeFromString = str => pattern => str.replace(pattern, '');

/**
 * Special key transformer for transformObjectKeys to strip "ns2:" from the beginning of keys,
 * such as 'ns2:ItemAttributes'
 *
 * @param {any} k
 */
const transformAttributeSetKey = k => transformKey(removeFromString(k)(/^ns2:/));

/**
 * Returns a list of products and their attributes, based on a list of ASIN, GCID, SellerSKU, UPC,
 * EAN, ISBN, or JAN values
 *
 * @param {Object} options see https://docs.developer.amazonservices.com/en_UK/products/Products_GetMatchingProductForId.html
 * @param {string} options.MarketplaceId Identifier for marketplace (see getMarketplaces)
 * @param {string} options.IdType Type of lookup to perform: ASIN, GCID, SellerSKU, UPC, EAN, ISBN, JAN
 * @param {string[]} options.IdList List of codes to perform lookup on
 * @public
 * @returns {Product[]}
 */
const getMatchingProductForId = async (options) => {
    const result = await callEndpoint('GetMatchingProductForId', options);
    if (result.Error) {
        throw new errors.ServiceError(result.Error.Message);
    }
    // for a single return, flattenResult will drop this to an object, which is not desireable
    // in this particular case.
    const products = forceArray(result);
    const ret = products.map((p) => {
        const type = String(p.$.IdType).toLowerCase();
        if (p.Error) {
            return { Error: p.Error, [`${type}`]: p.$.Id };
        }
        if (p.Products.Product.SalesRankings.SalesRank) {
            // eslint-disable-next-line no-param-reassign
            p.Products.Product.SalesRankings.SalesRank = forceArray(p.Products.Product.SalesRankings.SalesRank);
        }
        return {
            results: forceArray(transformObjectKeys(p.Products.Product, transformAttributeSetKey)),
            // results: p.Products.Product.map(x => {
            //     return {
            //         ...x,
            //         attributeSets: transformObjectKeys(x.AttributeSets, transformAttributeSetKey),
            //     };
            //     // console.warn("**************** x", x);
            //     // return x;
            // }),
            [`${type}`]: p.$.Id,
            idType: type,
            id: p.$.Id,
        };
    });
    return ret;
};

module.exports = {
    getMatchingProductForId,
};
<commit_msg>fix for when SalesRankings field is completely missing<commit_after>const { callEndpoint } = require('./callEndpoint');
const { forceArray, transformKey, transformObjectKeys } = require('./util/transformers');
const errors = require('./errors');

/**
 * remove a string pattern from a string
 *
 * @param {string} str string to remove pattern from
 * @param {string|regex} pattern pattern to remove
 * @return {string} string with the pattern removed
 */
const removeFromString = str => pattern => str.replace(pattern, '');

/**
 * Special key transformer for transformObjectKeys to strip "ns2:" from the beginning of keys,
 * such as 'ns2:ItemAttributes'
 *
 * @param {any} k
 */
const transformAttributeSetKey = k => transformKey(removeFromString(k)(/^ns2:/));

/**
 * Returns a list of products and their attributes, based on a list of ASIN, GCID, SellerSKU, UPC,
 * EAN, ISBN, or JAN values
 *
 * @param {Object} options see https://docs.developer.amazonservices.com/en_UK/products/Products_GetMatchingProductForId.html
 * @param {string} options.MarketplaceId Identifier for marketplace (see getMarketplaces)
 * @param {string} options.IdType Type of lookup to perform: ASIN, GCID, SellerSKU, UPC, EAN, ISBN, JAN
 * @param {string[]} options.IdList List of codes to perform lookup on
 * @public
 * @returns {Product[]}
 */
const getMatchingProductForId = async (options) => {
    const result = await callEndpoint('GetMatchingProductForId', options);
    if (result.Error) {
        throw new errors.ServiceError(result.Error.Message);
    }
    // for a single return, flattenResult will drop this to an object, which is not desireable
    // in this particular case.
    const products = forceArray(result);
    const ret = products.map((p) => {
        const type = String(p.$.IdType).toLowerCase();
        if (p.Error) {
            return { Error: p.Error, [`${type}`]: p.$.Id };
        }
        const { SalesRankings: rankings } = p.Products.Product;
        if (rankings && rankings.SalesRank) {
            // eslint-disable-next-line no-param-reassign
            p.Products.Product.SalesRankings.SalesRank = forceArray(rankings.SalesRank);
        }
        return {
            results: forceArray(transformObjectKeys(p.Products.Product, transformAttributeSetKey)),
            // results: p.Products.Product.map(x => {
            //     return {
            //         ...x,
            //         attributeSets: transformObjectKeys(x.AttributeSets, transformAttributeSetKey),
            //     };
            //     // console.warn("**************** x", x);
            //     // return x;
            // }),
            [`${type}`]: p.$.Id,
            idType: type,
            id: p.$.Id,
        };
    });
    return ret;
};

module.exports = {
    getMatchingProductForId,
};
<|endoftext|>


<commit_before>'use strict';

const net = require('net');

class Graphite {
    constructor(host, port) {
        this.options = {host, port};
        this.socket = null;
    }
    open() {
        if (!this.socket) {
            this.socket = net.connect(this.options);
            this.socket.on('close', () => {
                this.close();
            });
        }
    }
    close() {
        if (this.socket) {
            this.socket.destroy();
            this.socket = null;
        }
    }
    write(metric, value, timestamp = Date.now()) {
        timestamp = Math.floor(timestamp / 1000);
        this.open();
        this.socket.write(`${metric} ${value} ${timestamp}\n`);
    }
}

module.exports = Graphite;
<commit_msg>Add debug to Graphite<commit_after>'use strict';

const net = require('net');
const debug = require('./debug')('graphite');

class Graphite {
    constructor(host, port) {
        this.options = {host, port};
        this.socket = null;
    }
    open() {
        if (!this.socket) {
            this.socket = net.connect(this.options);
            this.socket.on('error', (err) => {
                debug.error(err);
                this.close();
            });
            this.socket.on('close', () => {
                this.close();
            });
        }
    }
    close() {
        if (this.socket) {
            this.socket.destroy();
            this.socket = null;
        }
    }
    write(metric, value, timestamp = Date.now()) {
        timestamp = Math.floor(timestamp / 1000);
        this.open();
        this.socket.write(`${metric} ${value} ${timestamp}\n`);
    }
}

module.exports = Graphite;
<|endoftext|>


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

module.exports = function(request, response, next){
  var filePath = request.zondajs.parsedURL.pathname;

  if(filePath == '/favicon.ico'){
    filePath = '/static/favicon.ico';
  }

  if(request.method === 'GET' && filePath.indexOf('/static/') == 0){
    filePath = '.' + filePath;

    path.exists(filePath, function(exists) {
      if (exists) {
        fs.readFile(filePath, function(error, content) {
          if(error) {
            response.writeHead(404);
            response.end();
          }else{
            response.writeHead(200, { 'Content-Type': mime.lookup(filePath) });
            response.end(content, 'utf-8');
          }
        });
      }else{
        response.writeHead(404);
        response.end();
      }
    });
  }else{
    next(request, response);
  }
};
<commit_msg>Moved from path.exists to fs.exists<commit_after>var fs = require('fs');
var mime = require('mime');

module.exports = function(request, response, next){
  var filePath = request.zondajs.parsedURL.pathname;

  if(filePath == '/favicon.ico'){
    filePath = '/static/favicon.ico';
  }

  if(request.method === 'GET' && filePath.indexOf('/static/') == 0){
    filePath = '.' + filePath;

    fs.exists(filePath, function(exists) {
      if (exists) {
        fs.readFile(filePath, function(error, content) {
          if(error) {
            response.writeHead(404);
            response.end();
          }else{
            response.writeHead(200, { 'Content-Type': mime.lookup(filePath) });
            response.end(content, 'utf-8');
          }
        });
      }else{
        response.writeHead(404);
        response.end();
      }
    });
  }else{
    next(request, response);
  }
};
<|endoftext|>