<commit_before>// partial of https://github.com/google/web-starter-kit/blob/master/gulpfile.js

'use strict';

// Include Gulp & Tools We'll Use
var gulp = require('gulp');
var browserSync = require('browser-sync');
var $ = require('gulp-load-plugins')();
var del = require('del');
var reload = browserSync.reload;

var path = {};

// if you want to generate special css,
// just run `gulp serve --p #{$projectName}`
// this use in 'css' task now. it will speedup compile speed
var projectName = '*';

path.srcDir = 'app';
path.distDir = '_dist';

gulp.task('css', function () {
  return gulp.src(path.srcDir + '/css/' + projectName + '.{styl,scss}')
    .pipe($.plumber({
        errorHandler: function (err) {
            console.log(err);
            this.emit('end');
        }
    }))
    .pipe($.if('*.styl', $.stylus()))
    .pipe($.if('*.scss', $.sass({
      outputStyle: "expanded"
    })))
    .pipe($.postcss([
      require('autoprefixer')({browsers: ['last 1 version']})
    ]))
    .pipe(gulp.dest(path.distDir + '/css/'))
});

gulp.task('js', function () {
  return gulp.src(path.srcDir + '/js/*.src.js')
    .pipe($.plumber())
    .pipe($.jshint())
    .pipe($.jshint.reporter('jshint-stylish'))
    .pipe($.babel())
    .pipe($.uglify())
    .pipe($.rename(function (path) {
      path.basename = path.basename.replace('.src', '.min');
    }))
    .pipe(gulp.dest(path.distDir + '/js/'))
});

gulp.task('html', function () {
  return gulp.src(path.srcDir + '/html/*.{html,jade}')
    .pipe($.plumber({
        errorHandler: function (err) {
            console.log(err);
            this.emit('end');
        }
    }))
    .pipe($.if('*.jade', $.jade()))
    .pipe(gulp.dest(path.distDir + '/html/'))
});

gulp.task('clean', del.bind(null, [path.distDir]));
gulp.task('clean:css', del.bind(null, [path.distDir + '/css']));

gulp.task('serve', function () {
  browserSync({
    browser: 'google-chrome',
    notify: false,
    ghostMode: {
      clicks: false,
      scroll: false,
      forms: false
    },
    scrollThrottle: 500,
    startPath: ($.util.env.p ? '_dist/html/' + $.util.env.p + '.html' : null),
    server: ''
  });
});

// Watch Files For Changes & Reload
gulp.task('dev', ['serve'], function () {
  projectName = $.util.env.p ? $.util.env.p : '*';
  // watch the folder to reload if files was change
  gulp.watch([path.srcDir + '/js/*.js'], ['js', reload]);
  gulp.watch([path.srcDir + '/css/*.{styl,scss}'], ['css', reload]);
  gulp.watch([path.srcDir + '/html/*.{html,jade}'], ['html', reload]);
});

// deploy dist folder to github branch gh-pages
gulp.task('deploy', function() {
  var name = $.util.env.p ? $.util.env.p : '**';
  return gulp.src(path.distDir + '/' + name + '/*')
    .pipe($.ghPages());
});

gulp.task('default', ['clean'], function () {
  gulp.start(['html', 'css', 'js']);
});
<commit_msg>為 js task 也加入 project 識別<commit_after>// partial of https://github.com/google/web-starter-kit/blob/master/gulpfile.js

'use strict';

// Include Gulp & Tools We'll Use
var gulp = require('gulp');
var browserSync = require('browser-sync');
var $ = require('gulp-load-plugins')();
var del = require('del');
var reload = browserSync.reload;

var path = {};

// if you want to generate special css,
// just run `gulp serve --p #{$projectName}`
// this use in 'css' task now. it will speedup compile speed
var projectName = '*';

path.srcDir = 'app';
path.distDir = '_dist';

gulp.task('css', function () {
  return gulp.src(path.srcDir + '/css/' + projectName + '.{styl,scss}')
    .pipe($.plumber({
        errorHandler: function (err) {
            console.log(err);
            this.emit('end');
        }
    }))
    .pipe($.if('*.styl', $.stylus()))
    .pipe($.if('*.scss', $.sass({
      outputStyle: "expanded"
    })))
    .pipe($.postcss([
      require('autoprefixer')({browsers: ['last 1 version']})
    ]))
    .pipe(gulp.dest(path.distDir + '/css/'))
});

gulp.task('js', function () {
  return gulp.src(path.srcDir + '/js/' + projectName + '.src.js')
    .pipe($.plumber())
    .pipe($.jshint())
    .pipe($.jshint.reporter('jshint-stylish'))
    .pipe($.babel())
    .pipe($.uglify())
    .pipe($.rename(function (path) {
      path.basename = path.basename.replace('.src', '.min');
    }))
    .pipe(gulp.dest(path.distDir + '/js/'))
});

gulp.task('html', function () {
  return gulp.src(path.srcDir + '/html/*.{html,jade}')
    .pipe($.plumber({
        errorHandler: function (err) {
            console.log(err);
            this.emit('end');
        }
    }))
    .pipe($.if('*.jade', $.jade()))
    .pipe(gulp.dest(path.distDir + '/html/'))
});

gulp.task('clean', del.bind(null, [path.distDir]));
gulp.task('clean:css', del.bind(null, [path.distDir + '/css']));

gulp.task('serve', function () {
  browserSync({
    browser: 'google-chrome',
    notify: false,
    ghostMode: {
      clicks: false,
      scroll: false,
      forms: false
    },
    scrollThrottle: 500,
    startPath: ($.util.env.p ? '_dist/html/' + $.util.env.p + '.html' : null),
    server: ''
  });
});

// Watch Files For Changes & Reload
gulp.task('dev', ['serve'], function () {
  projectName = $.util.env.p ? $.util.env.p : '*';
  // watch the folder to reload if files was change
  gulp.watch([path.srcDir + '/js/*.js'], ['js', reload]);
  gulp.watch([path.srcDir + '/css/*.{styl,scss}'], ['css', reload]);
  gulp.watch([path.srcDir + '/html/*.{html,jade}'], ['html', reload]);
});

// deploy dist folder to github branch gh-pages
gulp.task('deploy', function() {
  var name = $.util.env.p ? $.util.env.p : '**';
  return gulp.src(path.distDir + '/' + name + '/*')
    .pipe($.ghPages());
});

gulp.task('default', ['clean'], function () {
  gulp.start(['html', 'css', 'js']);
});
<|endoftext|>


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

var qs = require('querystring')
  , parse = require('url').parse
  , readFileSync = require('fs').readFileSync
  , crypto = require('crypto')
  , base64id = require('base64id')
  , transports = require('./transports')
  , EventEmitter = require('events').EventEmitter
  , Socket = require('./socket')
  , WebSocketServer = require('ws').Server
  , debug = require('debug')('engine');

/**
 * Module exports.
 */

module.exports = Server;

/**
 * Server constructor.
 *
 * @param {Object} options
 * @api public
 */

function Server(opts){
  this.clients = {};
  this.clientsCount = 0;

  opts = opts || {};
  this.pingTimeout = opts.pingTimeout || 60000;
  this.pingInterval = opts.pingInterval || 25000;
  this.upgradeTimeout = opts.upgradeTimeout || 10000;
  this.transports = opts.transports || Object.keys(transports);
  this.allowUpgrades = false !== opts.allowUpgrades;
  this.cookie = false !== opts.cookie ? (opts.cookie || 'io') : false;

  // initialize websocket server
  if (~this.transports.indexOf('websocket')) {
    this.ws = new WebSocketServer({ noServer: true, clientTracking: false });
  }
};

/**
 * Protocol errors mappings.
 */

Server.errors = {
  UNKNOWN_TRANSPORT: 0,
  UNKNOWN_SID: 1,
  BAD_HANDSHAKE_METHOD: 2
};

Server.errorMessages = {
  0: 'Transport unknown',
  1: 'Session ID unknown',
  2: 'Bad handshake method'
};

/**
 * Inherits from EventEmitter.
 */

Server.prototype.__proto__ = EventEmitter.prototype;

/**
 * Hash of open clients.
 *
 * @api public
 */

Server.prototype.clients;

/**
 * Returns a list of available transports for upgrade given a certain transport.
 *
 * @return {Array}
 * @api public
 */

Server.prototype.upgrades = function(transport){
  if (!this.allowUpgrades) return [];
  return transports[transport].upgradesTo || [];
};

/**
 * Verifies a request.
 *
 * @param {http.ServerRequest}
 * @return {Boolean} whether the request is valid
 * @api private
 */

Server.prototype.verify = function(req){
  // transport check
  var transport = req.query.transport;
  if (!~this.transports.indexOf(transport)) {
    debug('unknown transport "%s"', transport);
    return Server.errors.UNKNOWN_TRANSPORT;
  }

  // sid check
  if (req.query.sid) {
    return this.clients.hasOwnProperty(req.query.sid) ||
           Server.errors.UNKNOWN_SID;
  } else {
    // handshake is GET only
    return 'GET' == req.method ||
           Server.errors.BAD_HANDSHAKE_METHOD;
  }

  return true;
};

/**
 * Prepares a request by processing the query string.
 *
 * @api private
 */

Server.prototype.prepare = function(req){
  // try to leverage pre-existing `req.query` (e.g: from connect)
  if (!req.query) {
    req.query = ~req.url.indexOf('?') ? qs.parse(parse(req.url).query) : {};
  }
};

/**
 * Closes all clients.
 *
 * @api public
 */

Server.prototype.close = function(){
  debug('closing all open clients');
  for (var i in this.clients) {
    this.clients[i].close();
  }
  return this;
};

/**
 * Handles an Engine.IO HTTP request.
 *
 * @param {http.ServerRequest} request
 * @param {http.ServerResponse|http.OutgoingMessage} response
 * @api public
 */

Server.prototype.handleRequest = function(req, res){
  debug('handling "%s" http request "%s"', req.method, req.url);
  this.prepare(req);
  req.res = res;

  var code = this.verify(req);
  if (code !== true) {
    res.writeHead(400, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify({
      code: code,
      message: Server.errorMessages[code]
    }));
    return this;
  }

  if (req.query.sid) {
    debug('setting new request for existing client');
    this.clients[req.query.sid].transport.onRequest(req);
  } else {
    this.handshake(req.query.transport, req);
  }

  return this;
};

/**
 * Handshakes a new client.
 *
 * @param {String} transport name
 * @param {Object} request object
 * @api private
 */

Server.prototype.handshake = function(transport, req){
  var id = base64id.generateId();

  debug('handshaking client "%s"', id);

  var transport = new transports[transport](req);
  var socket = new Socket(id, this, transport);
  var self = this;

  if (false !== this.cookie) {
    transport.on('headers', function(headers){
      headers['Set-Cookie'] = self.cookie + '=' + id;
    });
  }

  transport.onRequest(req);

  this.clients[id] = socket;
  this.clientsCount++;
  this.emit('connection', socket);

  socket.once('close', function(){
    delete self.clients[id];
    self.clientsCount--;
  });
};

/**
 * Handles an Engine.IO HTTP Upgrade.
 *
 * @api public
 */

Server.prototype.handleUpgrade = function(req, socket, head){
  this.prepare(req);

  if (this.verify(req) !== true) {
    socket.end();
    return;
  }

  // delegate to ws
  var self = this;
  this.ws.handleUpgrade(req, socket, head, function(conn){
    self.onWebSocket(req, conn);
  });
};

/**
 * Called upon a ws.io connection.
 *
 * @param {ws.Socket} websocket
 * @api private
 */

Server.prototype.onWebSocket = function(req, socket){
  if (!transports[req.query.transport].prototype.handlesUpgrades) {
    debug('transport doesnt handle upgraded requests');
    socket.close();
    return;
  }

  // get client id
  var id = req.query.sid;

  // keep a reference to the ws.Socket
  req.websocket = socket;

  if (id) {
    if (!this.clients[id]) {
      debug('upgrade attempt for closed client');
      socket.close();
    } else if (this.clients[id].upgraded) {
      debug('transport had already been upgraded');
      socket.close();
    } else {
      debug('upgrading existing transport');
      var transport = new transports[req.query.transport](req);
      this.clients[id].maybeUpgrade(transport);
    }
  } else {
    this.handshake(req.query.transport, req);
  }
};

/**
 * Handles a regular connection to watch for flash policy requests.
 *
 * @param {net.Stream} socket
 * @api private
 */

var policy = readFileSync(__dirname + '/transports/flashsocket.xml');

Server.prototype.handleSocket = function(socket){
  socket.on('data', function onData(data){
    // no need for buffering as node will discard subsequent packets
    // since they constitute a malformed HTTP request
    if (60 == data[0] && 23 == data.length) {
      var str = data.slice(0, 23).toString();
      if ('<policy-file-request/>\0' == str) {
        socket.end(policy);
      }
    }
    socket.removeListener('data', onData);
  });
};
<commit_msg>sending error on transport creation failure due to bad request<commit_after>
/**
 * Module dependencies.
 */

var qs = require('querystring')
  , parse = require('url').parse
  , readFileSync = require('fs').readFileSync
  , crypto = require('crypto')
  , base64id = require('base64id')
  , transports = require('./transports')
  , EventEmitter = require('events').EventEmitter
  , Socket = require('./socket')
  , WebSocketServer = require('ws').Server
  , debug = require('debug')('engine');

/**
 * Module exports.
 */

module.exports = Server;

/**
 * Server constructor.
 *
 * @param {Object} options
 * @api public
 */

function Server(opts){
  this.clients = {};
  this.clientsCount = 0;

  opts = opts || {};
  this.pingTimeout = opts.pingTimeout || 60000;
  this.pingInterval = opts.pingInterval || 25000;
  this.upgradeTimeout = opts.upgradeTimeout || 10000;
  this.transports = opts.transports || Object.keys(transports);
  this.allowUpgrades = false !== opts.allowUpgrades;
  this.cookie = false !== opts.cookie ? (opts.cookie || 'io') : false;

  // initialize websocket server
  if (~this.transports.indexOf('websocket')) {
    this.ws = new WebSocketServer({ noServer: true, clientTracking: false });
  }
};

/**
 * Protocol errors mappings.
 */

Server.errors = {
  UNKNOWN_TRANSPORT: 0,
  UNKNOWN_SID: 1,
  BAD_HANDSHAKE_METHOD: 2,
  BAD_REQUEST: 3
};

Server.errorMessages = {
  0: 'Transport unknown',
  1: 'Session ID unknown',
  2: 'Bad handshake method',
  3: 'Bad request'
};

/**
 * Inherits from EventEmitter.
 */

Server.prototype.__proto__ = EventEmitter.prototype;

/**
 * Hash of open clients.
 *
 * @api public
 */

Server.prototype.clients;

/**
 * Returns a list of available transports for upgrade given a certain transport.
 *
 * @return {Array}
 * @api public
 */

Server.prototype.upgrades = function(transport){
  if (!this.allowUpgrades) return [];
  return transports[transport].upgradesTo || [];
};

/**
 * Verifies a request.
 *
 * @param {http.ServerRequest}
 * @return {Boolean} whether the request is valid
 * @api private
 */

Server.prototype.verify = function(req){
  // transport check
  var transport = req.query.transport;
  if (!~this.transports.indexOf(transport)) {
    debug('unknown transport "%s"', transport);
    return Server.errors.UNKNOWN_TRANSPORT;
  }

  // sid check
  if (req.query.sid) {
    return this.clients.hasOwnProperty(req.query.sid) ||
           Server.errors.UNKNOWN_SID;
  } else {
    // handshake is GET only
    return 'GET' == req.method ||
           Server.errors.BAD_HANDSHAKE_METHOD;
  }

  return true;
};

/**
 * Prepares a request by processing the query string.
 *
 * @api private
 */

Server.prototype.prepare = function(req){
  // try to leverage pre-existing `req.query` (e.g: from connect)
  if (!req.query) {
    req.query = ~req.url.indexOf('?') ? qs.parse(parse(req.url).query) : {};
  }
};

/**
 * Closes all clients.
 *
 * @api public
 */

Server.prototype.close = function(){
  debug('closing all open clients');
  for (var i in this.clients) {
    this.clients[i].close();
  }
  return this;
};

/**
 * Handles an Engine.IO HTTP request.
 *
 * @param {http.ServerRequest} request
 * @param {http.ServerResponse|http.OutgoingMessage} response
 * @api public
 */

Server.prototype.handleRequest = function(req, res){
  debug('handling "%s" http request "%s"', req.method, req.url);
  var self = this;
  this.prepare(req);
  req.res = res;

  var code = this.verify(req);
  if (code !== true) {
    sendErrorMessage(res, code);
    return this;
  }

  if (req.query.sid) {
    debug('setting new request for existing client');
    this.clients[req.query.sid].transport.onRequest(req);
  } else {
    this.handshake(req.query.transport, req);
  }

  return this;
};

/**
 * Sends an Engine.IO Error Message
 *
 * @param {code} error code
 * @api private
 */

 function sendErrorMessage(res, code) {
    res.writeHead(400, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify({
      code: code,
      message: Server.errorMessages[code]
    }));
 }

/**
 * Handshakes a new client.
 *
 * @param {String} transport name
 * @param {Object} request object
 * @api private
 */

Server.prototype.handshake = function(transport, req){
  var id = base64id.generateId();

  debug('handshaking client "%s"', id);

  try {
    var transport = new transports[transport](req);
  }
  catch (e) {
    sendErrorMessage(req.res, Server.errors.BAD_REQUEST);
    return;
  }
  var socket = new Socket(id, this, transport);
  var self = this;

  if (false !== this.cookie) {
    transport.on('headers', function(headers){
      headers['Set-Cookie'] = self.cookie + '=' + id;
    });
  }

  transport.onRequest(req);

  this.clients[id] = socket;
  this.clientsCount++;
  this.emit('connection', socket);

  socket.once('close', function(){
    delete self.clients[id];
    self.clientsCount--;
  });
};

/**
 * Handles an Engine.IO HTTP Upgrade.
 *
 * @api public
 */

Server.prototype.handleUpgrade = function(req, socket, head){
  this.prepare(req);

  if (this.verify(req) !== true) {
    socket.end();
    return;
  }

  // delegate to ws
  var self = this;
  this.ws.handleUpgrade(req, socket, head, function(conn){
    self.onWebSocket(req, conn);
  });
};

/**
 * Called upon a ws.io connection.
 *
 * @param {ws.Socket} websocket
 * @api private
 */

Server.prototype.onWebSocket = function(req, socket){
  if (!transports[req.query.transport].prototype.handlesUpgrades) {
    debug('transport doesnt handle upgraded requests');
    socket.close();
    return;
  }

  // get client id
  var id = req.query.sid;

  // keep a reference to the ws.Socket
  req.websocket = socket;

  if (id) {
    if (!this.clients[id]) {
      debug('upgrade attempt for closed client');
      socket.close();
    } else if (this.clients[id].upgraded) {
      debug('transport had already been upgraded');
      socket.close();
    } else {
      debug('upgrading existing transport');
      var transport = new transports[req.query.transport](req);
      this.clients[id].maybeUpgrade(transport);
    }
  } else {
    this.handshake(req.query.transport, req);
  }
};

/**
 * Handles a regular connection to watch for flash policy requests.
 *
 * @param {net.Stream} socket
 * @api private
 */

var policy = readFileSync(__dirname + '/transports/flashsocket.xml');

Server.prototype.handleSocket = function(socket){
  socket.on('data', function onData(data){
    // no need for buffering as node will discard subsequent packets
    // since they constitute a malformed HTTP request
    if (60 == data[0] && 23 == data.length) {
      var str = data.slice(0, 23).toString();
      if ('<policy-file-request/>\0' == str) {
        socket.end(policy);
      }
    }
    socket.removeListener('data', onData);
  });
};
<|endoftext|>


<commit_before>
function createShareLinkDisplay(share_link){
	var current_link = document.createElement("div");
	current_link.share_link = share_link;
	var keyDiv = document.createElement("div");
	//keyDiv.className = "input-group";
	var keyLabel = document.createElement("label");
	keyLabel.innerHTML = "ShareLinkKey";
	keyDiv.appendChild(keyLabel);
	var keyInput = document.createElement("input");
	current_link.keyInput = keyInput;
	keyInput.className = "form-control";
	keyInput.id = "sharelinkkey";
	keyInput.type = "text";
	keyDiv.appendChild(keyInput);
	keyLabel.setAttribute("for", "sharelinkkey");

	current_link.appendChild(keyDiv);

	var shareLinkTypeDiv = document.createElement("div");
	//shareLinkTypeDiv.className = "input-group";
	var shareLinkTypeLabel = document.createElement("label");
	shareLinkTypeLabel.innerHTML = "Share Link Type";
	shareLinkTypeDiv.appendChild(shareLinkTypeLabel);
	var shareLinkTypeSelect = document.createElement("select");
	shareLinkTypeSelect.id = "sharelinktypeselect";
	shareLinkTypeSelect.className = "form-control";
	current_link.shareLinkTypeSelect = shareLinkTypeSelect;
	shareLinkTypeLabel.setAttribute("for", "sharelinktypeselect");
	var shareLinkType = [ "key", "authenticated", "restricted"];
	for (var i=0; i<shareLinkType.length; i++){
		var option = document.createElement("option");
		option.value = shareLinkType[i];
		option.innerHTML = shareLinkType[i];
		shareLinkTypeSelect.appendChild(option);
	}
	shareLinkTypeSelect.onchange = function(event){
		for (var i=0; i < shareLinkTypeSelect.options.length; i++){
			var option = shareLinkTypeSelect.options[i];
			if (option.selected){
				document.getElementById("share_link_" + option.value).style.display="";
			}else{
				document.getElementById("share_link_" + option.value).style.display="none";
			}
		}
		updateSelect(shareLinkTypeSelect);
	}
	shareLinkTypeDiv.appendChild(shareLinkTypeSelect);
	createSelect(shareLinkTypeSelect);

	current_link.appendChild(shareLinkTypeDiv);
	var shareLinkSpecificDiv = document.createElement("div");
	var shareLinkDivKey = document.createElement("div");
	shareLinkDivKey.id = "share_link_key";
	shareLinkSpecificDiv.appendChild(shareLinkDivKey);
	var shareLinkDivAuthenticated = document.createElement("div");
	shareLinkDivAuthenticated.style.display="none";
	shareLinkDivAuthenticated.id = "share_link_authenticated";
	shareLinkSpecificDiv.appendChild(shareLinkDivAuthenticated);

	var shareLinkDivRestricted = document.createElement("div");
	shareLinkDivRestricted.style.display="none";
	shareLinkSpecificDiv.appendChild(shareLinkDivRestricted);
	shareLinkDivRestricted.id = "share_link_restricted";

	//Add the list of users added to this share link
	var usersUl = document.createElement("ul");
	shareLinkDivRestricted.appendChild(usersUl);

	//Share Restricted requires listing the users..
	var searchTimer = null;
	var searchUsersDiv = document.createElement("div");
	var searchUsersSpan = document.createElement("span");
	searchUsersDiv.appendChild(searchUsersSpan);
	var searchUsersInput = document.createElement("input");
	searchUsersSpan.appendChild(searchUsersInput);
	searchUsersInput.type = "list";
	searchUsersInput.setAttribute("list", "searchUserResults");
	var buttonPlus = document.createElement("button");
	buttonPlus.className = "btn btn-default w-expand-info";
	var iButtonPlus = document.createElement("i");
	iButtonPlus.className = "icon-plus";
	buttonPlus.appendChild(iButtonPlus);
	buttonPlus.onclick = function(event){
		//TODO add user to user list
		event.stopPropagation();
	}
	searchUsersSpan.appendChild(buttonPlus);

	var searchUsersResponse = document.createElement("datalist");
	searchUsersResponse.id = "searchUserResults";
	searchUsersSpan.appendChild(searchUsersResponse);
	searchUsersInput.onkeyup = function(){
		clearTimeout(searchTimer);
		searchTimer = setTimeout(
			function(){
				sendRequest(
					{
						url:"auths/list_users?search=" + searchUsersInput.value,
						method:"GET",
						onSuccess: function(result){
							searchUsersResponse.innerHTML = "";
							for(var i=0; i < result.length; i++){
								var label = document.createElement("option");
								label.value = result[i].name + "(" + result[i].id +")";
								searchUsersResponse.appendChild(label);
							}
						}
					}
				);
			},
			300);
	}
	shareLinkDivRestricted.appendChild(searchUsersDiv);
	var selectedUsers = document.createElement("div");
	shareLinkDivRestricted.appendChild(selectedUsers);

	current_link.appendChild(shareLinkSpecificDiv);
	current_link.update = function(share_link){
		current_link.share_link = share_link;
		if (share_link){
			keyInput.value = share_link.key;
		}else{
			keyInput.value = "";
		}
		usersUl.innerHTML = "";
		if (null != share_link && "restricted" == share_link.type){
			for(var i=0; i < share_link.user_list.length; i++){
				var userLi = document.createElement("li");
				userLi.innerHTML = share_link.user_list[i];
				usersUl.appendChild(userLi);
			}
		}
	}
	if (null != share_link){
		current_link.update(share_link);
	}
	return current_link;
}

function sharePopup(element, result){
	var share_links = [];
	if (null != result){
		share_links = result.share_link.list.output.share_links;
	}
	var current_share_link = null;
	var current_link = null;
	PopupClass.show({
		title: "Share " + element.name,
		data: share_links,
		message: function(self){
			var content_div = document.createElement("form");
			content_div.className = "content";
			content_div.id = "share_link_content";

			//if (0 != share_links.length){

				var selectShareLinks = document.createElement("select");
				selectShareLinks.className = "selectpicker form-control";
				selectShareLinks.setAttribute("data-style", "btn-primary");
				content_div.appendChild(selectShareLinks);

				//Update the select object this will deal with mobile cases to.
				createSelect(selectShareLinks);

				if (0 != share_links.length){
					current_link = share_links[0];
				}
				self.refresh = function(){
					selectShareLinks.innerHTML = "";
					var option;
					for(var i=0; i < share_links.length; i++){

						option = document.createElement("option");
						option.value = share_links[i].name?share_links[i].name:share_links[i].key;

						option.share_link = share_links[i];
						if (null != current_link && current_link.key == option.share_link.key){
							option.setAttribute("selected", true);
						}
						option.innerHTML = option.value;
						selectShareLinks.appendChild(option);
					}
					option = document.createElement("option");
					option.value = option.innerHTML = "New Share Link";
					if (null == current_link){
						option.setAttribute("selected", true);
					}
					selectShareLinks.appendChild(option);

					selectShareLinks.onchange = function(event){
						for (var i=0; i < selectShareLinks.options.length; i++){
							var option = selectShareLinks.options[i];
							if (option.selected){
								current_link = option.share_link;
								self.refresh();
								break;
							}
						}
					}
					current_share_link.update(current_link);
					var button = self.getButton("updateCreateId")[0];
					if (current_link){
						button.innerHTML = "Update";
					}else{
						button.innerHTML = "Create";
					}
					updateSelect(selectShareLinks);
				}
			//}
			current_share_link = createShareLinkDisplay(current_link);
			self.refresh();

			content_div.appendChild(current_share_link);
			return content_div;
		},
		onshown: function(self){
			//Call the ToolBoxUpdate method so that all the select elements are displayed correctly
			ToolBoxUpdate();
		},
		buttons: [
			{
				label: "Close",
				action: function(self){
					self.close();
				}
			},{
				id: "updateCreateId",
				cssClass:"btn-primary",
				label: current_link?"Update":"Create",
				action: function(self){
					var cmd = null == current_share_link.share_link ? sendCommandShareLinkCreate:sendCommandShareLinkUpdate;
					var share_link = {
						share_link:{
							path: current_folder.path +"/" + element.name,
							type: current_share_link.shareLinkTypeSelect.selectedOptions[0].value
						}
					}
					if ("restricted" == current_share_link.shareLinkTypeSelect.selectedOptions[0].value){
						//Add the users that have access to this share link
					}
					cmd(
						share_link,
						{poll: true},
						function(result){
							console.log(result);
							if (0 == result.state.status){
								if (result.name == "share_link.create"){
									share_links.push(result.share_link.create.output.share_link);
									current_link = result.share_link.create.output.share_link;
								}
								self.refresh();
							}
							//Else notify of an error...
						}
					);
				}
			}
		]
	});

}
<commit_msg>[shareminatorfrontend] share.js: add type parameter<commit_after>
function createShareLinkDisplay(share_link){
	var current_link = document.createElement("div");
	current_link.share_link = share_link;
	var keyDiv = document.createElement("div");
	//keyDiv.className = "input-group";
	var keyLabel = document.createElement("label");
	keyLabel.innerHTML = "ShareLinkKey";
	keyDiv.appendChild(keyLabel);
	var keyInput = document.createElement("input");
	current_link.keyInput = keyInput;
	keyInput.className = "form-control";
	keyInput.id = "sharelinkkey";
	keyInput.type = "text";
	keyDiv.appendChild(keyInput);
	keyLabel.setAttribute("for", "sharelinkkey");

	current_link.appendChild(keyDiv);

	var shareLinkTypeDiv = document.createElement("div");
	//shareLinkTypeDiv.className = "input-group";
	var shareLinkTypeLabel = document.createElement("label");
	shareLinkTypeLabel.innerHTML = "Share Link Type";
	shareLinkTypeDiv.appendChild(shareLinkTypeLabel);
	var shareLinkTypeSelect = document.createElement("select");
	shareLinkTypeSelect.id = "sharelinktypeselect";
	shareLinkTypeSelect.className = "form-control";
	current_link.shareLinkTypeSelect = shareLinkTypeSelect;
	shareLinkTypeLabel.setAttribute("for", "sharelinktypeselect");
	var shareLinkType = [{key:"key", value:EnumShareLinkType.EnumShareByKey},
	{key:"authenticated", value:EnumShareLinkType.EnumAuthenticated},
	{key:"restricted", value:EnumShareLinkType.EnumRestricted}];
	for (var i=0; i<shareLinkType.length; i++){
		var option = document.createElement("option");
		option.value = shareLinkType[i].value;
		option.innerHTML = shareLinkType[i].key;
		shareLinkTypeSelect.appendChild(option);
	}
	shareLinkTypeSelect.onchange = function(event){
		for (var i=0; i < shareLinkTypeSelect.options.length; i++){
			var option = shareLinkTypeSelect.options[i];
			if (option.selected){
				document.getElementById("share_link_" + option.value).style.display="";
			}else{
				document.getElementById("share_link_" + option.value).style.display="none";
			}
		}
		updateSelect(shareLinkTypeSelect);
	}
	shareLinkTypeDiv.appendChild(shareLinkTypeSelect);
	createSelect(shareLinkTypeSelect);

	current_link.appendChild(shareLinkTypeDiv);
	var shareLinkSpecificDiv = document.createElement("div");
	var shareLinkDivKey = document.createElement("div");
	shareLinkDivKey.id = "share_link_key";
	shareLinkSpecificDiv.appendChild(shareLinkDivKey);
	var shareLinkDivAuthenticated = document.createElement("div");
	shareLinkDivAuthenticated.style.display="none";
	shareLinkDivAuthenticated.id = "share_link_authenticated";
	shareLinkSpecificDiv.appendChild(shareLinkDivAuthenticated);

	var shareLinkDivRestricted = document.createElement("div");
	shareLinkDivRestricted.style.display="none";
	shareLinkSpecificDiv.appendChild(shareLinkDivRestricted);
	shareLinkDivRestricted.id = "share_link_restricted";

	//Add the list of users added to this share link
	var usersUl = document.createElement("ul");
	shareLinkDivRestricted.appendChild(usersUl);

	//Share Restricted requires listing the users..
	var searchTimer = null;
	var searchUsersDiv = document.createElement("div");
	var searchUsersSpan = document.createElement("span");
	searchUsersDiv.appendChild(searchUsersSpan);
	var searchUsersInput = document.createElement("input");
	searchUsersSpan.appendChild(searchUsersInput);
	searchUsersInput.type = "list";
	searchUsersInput.setAttribute("list", "searchUserResults");
	var buttonPlus = document.createElement("button");
	buttonPlus.className = "btn btn-default w-expand-info";
	var iButtonPlus = document.createElement("i");
	iButtonPlus.className = "icon-plus";
	buttonPlus.appendChild(iButtonPlus);
	buttonPlus.onclick = function(event){
		//TODO add user to user list
		event.stopPropagation();
	}
	searchUsersSpan.appendChild(buttonPlus);

	var searchUsersResponse = document.createElement("datalist");
	searchUsersResponse.id = "searchUserResults";
	searchUsersSpan.appendChild(searchUsersResponse);
	searchUsersInput.onkeyup = function(){
		clearTimeout(searchTimer);
		searchTimer = setTimeout(
			function(){
				sendRequest(
					{
						url:"auths/list_users?search=" + searchUsersInput.value,
						method:"GET",
						onSuccess: function(result){
							searchUsersResponse.innerHTML = "";
							for(var i=0; i < result.length; i++){
								var label = document.createElement("option");
								label.value = result[i].name + "(" + result[i].id +")";
								searchUsersResponse.appendChild(label);
							}
						}
					}
				);
			},
			300);
	}
	shareLinkDivRestricted.appendChild(searchUsersDiv);
	var selectedUsers = document.createElement("div");
	shareLinkDivRestricted.appendChild(selectedUsers);

	current_link.appendChild(shareLinkSpecificDiv);
	current_link.update = function(share_link){
		current_link.share_link = share_link;
		if (share_link){
			keyInput.value = share_link.key;
		}else{
			keyInput.value = "";
		}
		usersUl.innerHTML = "";
		if (null != share_link && "restricted" == share_link.type){
			for(var i=0; i < share_link.user_list.length; i++){
				var userLi = document.createElement("li");
				userLi.innerHTML = share_link.user_list[i];
				usersUl.appendChild(userLi);
			}
		}
	}
	if (null != share_link){
		current_link.update(share_link);
	}
	return current_link;
}

function sharePopup(element, result){
	var share_links = [];
	if (null != result){
		share_links = result.share_link.list.output.share_links;
	}
	var current_share_link = null;
	var current_link = null;
	PopupClass.show({
		title: "Share " + element.name,
		data: share_links,
		message: function(self){
			var content_div = document.createElement("form");
			content_div.className = "content";
			content_div.id = "share_link_content";

			//if (0 != share_links.length){

				var selectShareLinks = document.createElement("select");
				selectShareLinks.className = "selectpicker form-control";
				selectShareLinks.setAttribute("data-style", "btn-primary");
				content_div.appendChild(selectShareLinks);

				//Update the select object this will deal with mobile cases to.
				createSelect(selectShareLinks);

				if (0 != share_links.length){
					current_link = share_links[0];
				}
				self.refresh = function(){
					selectShareLinks.innerHTML = "";
					var option;
					for(var i=0; i < share_links.length; i++){

						option = document.createElement("option");
						option.value = share_links[i].name?share_links[i].name:share_links[i].key;

						option.share_link = share_links[i];
						if (null != current_link && current_link.key == option.share_link.key){
							option.setAttribute("selected", true);
						}
						option.innerHTML = option.value;
						selectShareLinks.appendChild(option);
					}
					option = document.createElement("option");
					option.value = option.innerHTML = "New Share Link";
					if (null == current_link){
						option.setAttribute("selected", true);
					}
					selectShareLinks.appendChild(option);

					selectShareLinks.onchange = function(event){
						for (var i=0; i < selectShareLinks.options.length; i++){
							var option = selectShareLinks.options[i];
							if (option.selected){
								current_link = option.share_link;
								self.refresh();
								break;
							}
						}
					}
					current_share_link.update(current_link);
					var button = self.getButton("updateCreateId")[0];
					if (current_link){
						button.innerHTML = "Update";
					}else{
						button.innerHTML = "Create";
					}
					updateSelect(selectShareLinks);
				}
			//}
			current_share_link = createShareLinkDisplay(current_link);
			self.refresh();

			content_div.appendChild(current_share_link);
			return content_div;
		},
		onshown: function(self){
			//Call the ToolBoxUpdate method so that all the select elements are displayed correctly
			ToolBoxUpdate();
		},
		buttons: [
			{
				label: "Close",
				action: function(self){
					self.close();
				}
			},{
				id: "updateCreateId",
				cssClass:"btn-primary",
				label: current_link?"Update":"Create",
				action: function(self){
					var cmd = null == current_share_link.share_link ? sendCommandShareLinkCreate:sendCommandShareLinkUpdate;
					var share_link = {
						share_link:{
							path: current_folder.path +"/" + element.name,
							type: parseInt(current_share_link.shareLinkTypeSelect.selectedOptions[0].value)
						}
					}
					if (EnumShareLinkType.EnumRestricted == parseInt(current_share_link.shareLinkTypeSelect.selectedOptions[0].value)){
						//Add the users that have access to this share link
					}
					cmd(
						share_link,
						{poll: true},
						function(result){
							console.log(result);
							if (0 == result.state.status){
								if (result.name == "share_link.create"){
									share_links.push(result.share_link.create.output.share_link);
									current_link = result.share_link.create.output.share_link;
								}
								self.refresh();
							}
							//Else notify of an error...
						}
					);
				}
			}
		]
	});

}
<|endoftext|>


<commit_before>const chalk = require('chalk')

const Match = require('./lib/Match')

const players = require('require-smart')('./players')

const TAG = 'server'
async function startup(){
  console.info(TAG, chalk.yellow('startup'))

  let match = new Match({
    vision: {
      PORT: 10002,
    },
    robots: {
      red: {visionId: 1, radioId: 1, class: players.Attacker}
    },
  })

  await match.init()
}

process.on('unhandledRejection', (e) => {
  console.error('Unhandled Rejection')
  console.error(e.stack)
  process.exit(1)
})

startup()

// async initSocket() {
//   this.socket = new SocketIo(...)
//   // Wait be ready
//   await this.socket.ready()

//   // Bind to vision events
//   this.vision.on('detection', detection => {
//     this.socket.broadcast({type: 'detection', detection})
//   })

//   // Bind to state change events
//   this.state.on('change', change => {
//     this.socket.broadcast({type: 'state', state})
//   })

//   // Update state
//   this.socket.on('set:state', data => {
//     this.state.setState(data)
//   })
// }

<commit_msg>add settings<commit_after>const chalk = require('chalk')

const Match = require('./lib/Match')

const players = require('require-smart')('./players')

const PORT = process.env.PORT || 10002
const HOST = process.env.HOST || '224.5.23.2'

const TAG = 'server'
async function startup(){
  console.info(TAG, chalk.yellow('startup'))

  let match = new Match({
    vision: { PORT, HOST },
    robots: {
      red: {visionId: 1, radioId: 1, class: players.Attacker}
    },
  })

  await match.init()

  // match.vision.on('data', console.log)

  console.log('Listening in:', PORT)
}

process.on('unhandledRejection', (e) => {
  console.error('Unhandled Rejection')
  console.error(e.stack)
  process.exit(1)
})

startup()

// async initSocket() {
//   this.socket = new SocketIo(...)
//   // Wait be ready
//   await this.socket.ready()

//   // Bind to vision events
//   this.vision.on('detection', detection => {
//     this.socket.broadcast({type: 'detection', detection})
//   })

//   // Bind to state change events
//   this.state.on('change', change => {
//     this.socket.broadcast({type: 'state', state})
//   })

//   // Update state
//   this.socket.on('set:state', data => {
//     this.state.setState(data)
//   })
// }

<|endoftext|>


<commit_before>
/**
 * This file is dependent on gulp which automate tasks.
 *Author : # Collins

 */
const gulp = require('gulp'),
    less = require('gulp-less'),
    livereload = require('gulp-livereload'),
    cleanCSS = require('gulp-clean-css'),
    jshint = require('gulp-jshint');
    //coveralls = require('gulp-coveralls');

const browserSync1 = require("browser-sync").create();
const browserSync2 = require("browser-sync").create();
const browserSync = require("browser-sync").create();

gulp.task("default", ["front","test"]);

gulp.task('css', function() {
  gulp.src('public/design/css/*.css')
    .pipe(cleanCSS())
    .pipe(gulp.dest('css'))
    .pipe(livereload(".public/index.html"));
});

gulp.task('watch', function() {
  livereload.listen();
  gulp.watch('public/design/css/*.css', ['css']);
});

// A task that ensures the javascript task is complete before
// reloading browsers
gulp.task('js-watch', ['js'], function (done) {
    browserSync.reload();
    done();
});

gulp.task('front', function () {

    browserSync1.init({
        server : {
            baseDir: "./public"
        },
        port : 3002,
        ui: {
            port:3070
        }
    });
    // tracks html,js and css changes
    // I have used to allow reload
    gulp.watch("./public/**/*.{html,js,css}").on("change", browserSync1.reload);
});

gulp.task("test", function () {
  //.pipe(coveralls());

    browserSync2.init({
        server: {
          baseDir: ["./public/src/", "./jasmine"]},
          port: 3080,
          ui: {
              port: 3090
          }
      //}
    });

    gulp.watch('./jasmine/spec/*.js').on("change",browserSync2.reload);
    gulp.watch("./public/src/*.js").on("change", browserSync2.reload);
});
// end tasks<commit_msg>change to babel for es6<commit_after><|endoftext|>


<commit_before>var xmpp        = require('node-xmpp');

// Loading all modules needed
var Logger              = require('../modules/logger');
var Router              = require('../modules/router').Router;
var RecipientOffline    = require('../modules/offline');
var Roster              = require('../modules/roster');
var Websocket           = require('../modules/websocket');

// Loading non -xmpp libraries
var User = require('../lib/users.js').User;

exports.run = function(config) {
    // Creates the server.
    var c2s = new xmpp.C2SServer(config);
    c2s.router = new Router(c2s); // Using the right Router.
    var s2s = new xmpp.Router();

    // S2S plugged to C2S.
    s2s.register(config.domain, function(stanza) {
        c2s.router.route(stanza);
    });
    c2s.s2s = s2s;

    // Configure the mods at the server level!
    Logger.configure(c2s, s2s);
    RecipientOffline.configure(c2s, s2s);
    Websocket.configure(c2s, s2s);
    Roster.configure(c2s, s2s);

    // On Connect event. When a client connects.
    c2s.on("connect", function(client) {
        client.addMixin(Logger.mod);
        client.addMixin(RecipientOffline.mod);
        client.addMixin(Roster.mod);

        // Allows the developer to authenticate users against anything they want.
        client.on("authenticate", function(opts, cb) {
            User.find(opts.jid, function(user) {
                if(!user) {
                    cb(new Error("No such user"));
                }
                else if(user.auth(opts.password)) {
                    cb();
                }
                else {
                    user.token_auth(opts.password, function(result) {
                        if(result)
                            cb();
                        else
                            cb(new Error("Wrong password"));
                    });
                }
            });
        });

        // Allows the developer to register the jid against anything they want
        client.on("register", function(opts, cb) {
            cb(false, {code: "406", type: "cancel", text: "denied"});
        });

        // When the user is online, let's register the route. there could be other things involed here... like presence!
        client.on('online', function() {
            c2s.router.registerRoute(client.jid, client);
        });

        // When the user is offline, we remove him from the router.
        client.on('end', function() {
            if(client.jid) {
                // We may not have a jid just yet if the client never connected before
                c2s.router.unregisterRoute(client.jid, client);
            }
        });

        // this callback is called when the client sends a stanza.
        client.on('stanza', function(stanza) {
            c2s.router.route(stanza, client);  // Let's send the stanza to the router and let the router decide what to do with it.
        });
    });

    // On Disconnect event. When a client disconnects
    c2s.on("disconnect", function(client) {
        // Not much to do for now.
        client.logger.info("Client disconnected");
    });
}

<commit_msg>Revert "plugging S2S back into C2S"<commit_after>var xmpp        = require('node-xmpp');

// Loading all modules needed
var Logger              = require('../modules/logger');
var Router              = require('../modules/router').Router;
var RecipientOffline    = require('../modules/offline');
var SoftwareVersion     = require('../modules/software_version');
var Presence            = require('../modules/presence');
var Roster              = require('../modules/roster');
var DiscoInfo           = require('../modules/disco_info');
var VCard               = require('../modules/vcard');
var Websocket           = require('../modules/websocket');

// Loading non -xmpp libraries
var User = require('../lib/users.js').User;

exports.run = function(config) {

    // That's the way you add mods to a given server.
    SoftwareVersion.name = "Node XMPP server example";
    SoftwareVersion.version = "0.0.0.1";
    SoftwareVersion.os = "Unknown";

    // Creates the server.
    var c2s = new xmpp.C2SServer(config);
    c2s.router = new Router(c2s); // Using the right Router.
    var s2s = new xmpp.Router();

    // Configure the mods at the server level!
    Logger.configure(c2s, s2s);
    RecipientOffline.configure(c2s, s2s);
    SoftwareVersion.configure(c2s, s2s);
    Presence.configure(c2s, s2s);
    Roster.configure(c2s, s2s);
    DiscoInfo.configure(c2s, s2s);
    VCard.configure(c2s, s2s);
    Websocket.configure(c2s, s2s);

    // On Connect event. When a client connects.
    c2s.on("connect", function(client) {
        client.addMixin(Logger.mod);
        client.addMixin(RecipientOffline.mod);
        client.addMixin(SoftwareVersion.mod);
        client.addMixin(Presence.mod);
        client.addMixin(Roster.mod);
        client.addMixin(DiscoInfo.mod);
        client.addMixin(VCard.mod);

        // Allows the developer to authenticate users against anything they want.
        client.on("authenticate", function(opts, cb) {
            User.find(opts.jid, function(user) {
                if (user && user.attrs.password === opts.password)
                    cb();
                else
                    cb(new Error("Authentication failure"));
            });
        });

        // Allows the developer to register the jid against anything they want
        client.on("register", function(opts, cb) {
            User.register(opts.jid, opts.password, {
                success: function() {
                    cb(true);
                },
                error: function() {
                    var err = new Error("conflict");
                    err.code = 409;
                    err.type = "cancel";
                    cb(err);
                }
            });
        });

        // When the user is online, let's register the route. there could be other things involed here... like presence!
        client.on('online', function() {
            c2s.router.registerRoute(client.jid, client);
        });

        // When the user is offline, we remove him from the router.
        client.on('end', function() {
            if(client.jid) {
                // We may not have a jid just yet if the client never connected before
                c2s.router.unregisterRoute(client.jid, client);
            }
        });

        // this callback is called when the client sends a stanza.
        client.on('stanza', function(stanza) {
            c2s.router.route(stanza, client);  // Let's send the stanza to the router and let the router decide what to do with it.
        });
    });

    // On Disconnect event. When a client disconnects
    c2s.on("disconnect", function(client) {

    });
}

<|endoftext|>


<commit_before>// dimensions of the SVG viewport
var w = 600;
var h = 400;
var r = 3;

// TODO change domain and range according to some configuration

// scale for the second Chern number
var c2 = d3.scale.linear()
  .domain([-20, 80])
  .range([0, w]);

// scale for the first Chern number
var c12 = d3.scale.linear()
  .domain([-30, 60])
  .range([h, 0]);

// axis for the second Chern number
var c2Axis = d3.svg.axis()
  .scale(c2);

// axis for the first Chern number
var c12Axis = d3.svg.axis()
  .scale(c12)
  .orient("left");

// scale for the Kodaira dimension
var kodaira = d3.scale.ordinal()
  .domain([-1, 0, 1, 2])
  .range(["kodaira-infty", "kodaira-0", "kodaira-1", "kodaira-2"]);

// all the pairs (c_2,c_1^2) corresponding to a minimal projective surface
var points = []

// projective plane
points.push([3, 9, -1]);

// minimal surfaces of Kodaira dimension 0
points.push([0, 0, 0]); // abelian and hyperelliptic surfaces
points.push([12, 0, 0]); // Enriques surfaces
points.push([24, 0, 0]); // K3 surfaces

for (var i2 = c2.domain()[0]; i2 < c2.domain()[1]; i2++) {
  for (var i12 = c12.domain()[0]; i12 < c12.domain()[1]; i12++) {
    // ruled surfaces
    var positivity = (i2 <= 4) && (i12 <= 8);
    var congruence = (i2 % 4 == 0) && (i12 % 8 == 0) && (i12 == i2 * 2);
    if (congruence && positivity)
      points.push([i2, i12, -1]);

    // minimal surface of Kodaira dimension 1
    var congruence = ((i12 + i2) % 12 == 0);
    var positivity = (i12 == 0) && (i2 >= 0);
    if (congruence && positivity)
      points.push([i2, i12, 1]);

    // minimal surface of general type
    var congruence = ((i12 + i2) % 12 == 0);
    var positivity = (i12 >= 0) && (i2 >= 0) && ((i12 > 0) || (i2 > 0));
    var BMY = (i12 <= (3 * i2));
    var noether = ((5 * i12 - i2 + 36) >= 0);

    if (congruence && positivity && BMY && noether)
      points.push([i2, i12, 2]);
  }
}

var svg = d3.select("body")
  .append("svg")
  .attr("width", w)
  .attr("height", h);

// all the minimal nodes
svg.selectAll("circle")
  .data(points)
  .enter()
  .append("circle")
  .attr("cx", function(d) { return c2(d[0]); })
  .attr("cy", function(d) { return c12(d[1]); })
  .attr("r", function(d) { return r; })
  .attr("class", function(d) { return kodaira(d[2]); })

// horizontal axis
svg.append("g")
  .attr("class", "axis")
  .attr("transform", "translate(0," + c12(0) + ")")
  .call(c2Axis);

// vertical axis
svg.append("g")
  .attr("class", "axis")
  .attr("transform", "translate(" + c2(0) + ",0)")
  .call(c12Axis);

// improve origin: remove double 0
svg.selectAll(".axis g text")
  .filter(function(d) { return d == 0 })
  .style("opacity", function(d, i) { if (i != 0) return 0; })
  .attr("dx", function(d, i) { if (i == 0) return "-10px"; })

// draw Noether inequality (hardcoded constants...)
svg.append("line")
  .attr("x1", c2(36))
  .attr("x2", c2(86))
  .attr("y1", c12(0))
  .attr("y2", c12(10))
  .attr("class", "axis");
svg.append("text")
  .attr("x", c2(65))
  .attr("y", c12(2))
  .attr("text-anchor", "middle")
  .attr("transform", "rotate(-7, " + c2(65) + ", " + c12(2) + ")")
  .text("Noether inequality");

// draw the BMY inequality (hardcoded constants...)
svg.append("line")
  .attr("x1", c2(0))
  .attr("x2", c2(20))
  .attr("y1", c12(0))
  .attr("y2", c12(60))
  .attr("class", "axis");
svg.append("text")
  .attr("x", c2(10))
  .attr("y", c12(35))
  .attr("text-anchor", "middle")
  .attr("transform", "rotate(-66, " + c2(10) + ", " + c12(35) + ")")
  .text("Bogomolov-Miyaoka-Yau inequality");

// assign click event to points
d3.selectAll("circle").on("click", clickedPoint);

function clickedPoint(point) {
  // only act when the clicked node is active (i.e. has the correct Kodaira dimension)
  if (!d3.select(this).classed("inactive")) {
    // make all nodes inactive
    d3.selectAll("circle").classed("active", false);

    // make this node active
    d3.select(this).classed("active", true);

    // remove candidates
    clearCandidates();

    // reset the Hodge diamond
    setInactive();

    // add the coordinates to the legend in the fieldset
    $("fieldset#candidates legend").html("Candidates
for $\\mathrm{c}_2=" + point[0] + "$, $\\mathrm{c}_1^2=" + point[1] + "$");
    MathJax.Hub.Queue(["Typeset", MathJax.Hub]);

    // look for surfaces with the correct invariants
    for (var i = 0; i < surfaces.length; i++) {
      if (surfaces[i].c2 == point[0] && surfaces[i].c12 == point[1] && surfaces[i].kodaira == point[2])
        addCandidateSurface(surfaces[i]);
    }

    // check whether we have found surfaces, otherwise display a message
    if ($("fieldset#candidates ol li").length == 0)
      $("fieldset#candidates").prepend("
No surfaces known with these invariants, sorry.");
  }
}
<commit_msg>Improved axes and added axis labels<commit_after>// dimensions of the SVG viewport
var w = 600;
var h = 400;
var r = 3;

// TODO change domain and range according to some configuration

// scale for the second Chern number
var c2 = d3.scale.linear()
  .domain([-20, 80])
  .range([0, w]);

// scale for the first Chern number
var c12 = d3.scale.linear()
  .domain([-30, 60])
  .range([h, 0]);

// axis for the second Chern number
var c2Axis = d3.svg.axis()
  .tickValues([-10, 0, 10, 20, 30, 40, 50, 60, 70])
  .scale(c2);

// axis for the first Chern number
var c12Axis = d3.svg.axis()
  .scale(c12)
  .tickValues([-20, -10, 0, 10, 20, 30, 40, 50])
  .orient("left");

// scale for the Kodaira dimension
var kodaira = d3.scale.ordinal()
  .domain([-1, 0, 1, 2])
  .range(["kodaira-infty", "kodaira-0", "kodaira-1", "kodaira-2"]);

// all the pairs (c_2,c_1^2) corresponding to a minimal projective surface
var points = []

// projective plane
points.push([3, 9, -1]);

// minimal surfaces of Kodaira dimension 0
points.push([0, 0, 0]); // abelian and hyperelliptic surfaces
points.push([12, 0, 0]); // Enriques surfaces
points.push([24, 0, 0]); // K3 surfaces

for (var i2 = c2.domain()[0]; i2 < c2.domain()[1]; i2++) {
  for (var i12 = c12.domain()[0]; i12 < c12.domain()[1]; i12++) {
    // ruled surfaces
    var positivity = (i2 <= 4) && (i12 <= 8);
    var congruence = (i2 % 4 == 0) && (i12 % 8 == 0) && (i12 == i2 * 2);
    if (congruence && positivity)
      points.push([i2, i12, -1]);

    // minimal surface of Kodaira dimension 1
    var congruence = ((i12 + i2) % 12 == 0);
    var positivity = (i12 == 0) && (i2 >= 0);
    if (congruence && positivity)
      points.push([i2, i12, 1]);

    // minimal surface of general type
    var congruence = ((i12 + i2) % 12 == 0);
    var positivity = (i12 >= 0) && (i2 >= 0) && ((i12 > 0) || (i2 > 0));
    var BMY = (i12 <= (3 * i2));
    var noether = ((5 * i12 - i2 + 36) >= 0);

    if (congruence && positivity && BMY && noether)
      points.push([i2, i12, 2]);
  }
}

var svg = d3.select("body")
  .append("svg")
  .attr("width", w)
  .attr("height", h);

// all the minimal nodes
svg.selectAll("circle")
  .data(points)
  .enter()
  .append("circle")
  .attr("cx", function(d) { return c2(d[0]); })
  .attr("cy", function(d) { return c12(d[1]); })
  .attr("r", function(d) { return r; })
  .attr("class", function(d) { return kodaira(d[2]); })

// horizontal axis
svg.append("g")
  .attr("class", "axis")
  .attr("transform", "translate(0," + c12(0) + ")")
  .call(c2Axis);
svg.append("text")
  .attr("x", c2(-18))
  .attr("y", c12(2))
  .text("c2"); // TODO MathJax inside SVG seems to be a challenge...

// vertical axis
svg.append("g")
  .attr("class", "axis")
  .attr("transform", "translate(" + c2(0) + ",0)")
  .call(c12Axis);
svg.append("text")
  .attr("x", c2(1))
  .attr("y", c12(-28))
  .text("c12"); // TODO MathJax inside SVG seems to be a challenge...

// improve origin: remove double 0
svg.selectAll(".axis g text")
  .filter(function(d) { return d == 0 })
  .style("opacity", function(d, i) { if (i != 0) return 0; })
  .attr("dx", function(d, i) { if (i == 0) return "-10px"; })

// draw Noether inequality (hardcoded constants...)
svg.append("line")
  .attr("x1", c2(36))
  .attr("x2", c2(86))
  .attr("y1", c12(0))
  .attr("y2", c12(10))
  .attr("class", "axis");
svg.append("text")
  .attr("x", c2(65))
  .attr("y", c12(2))
  .attr("text-anchor", "middle")
  .attr("transform", "rotate(-7, " + c2(65) + ", " + c12(2) + ")")
  .text("Noether inequality");

// draw the BMY inequality (hardcoded constants...)
svg.append("line")
  .attr("x1", c2(0))
  .attr("x2", c2(20))
  .attr("y1", c12(0))
  .attr("y2", c12(60))
  .attr("class", "axis");
svg.append("text")
  .attr("x", c2(10))
  .attr("y", c12(35))
  .attr("text-anchor", "middle")
  .attr("transform", "rotate(-66, " + c2(10) + ", " + c12(35) + ")")
  .text("Bogomolov-Miyaoka-Yau inequality");

// assign click event to points
d3.selectAll("circle").on("click", clickedPoint);

function clickedPoint(point) {
  // only act when the clicked node is active (i.e. has the correct Kodaira dimension)
  if (!d3.select(this).classed("inactive")) {
    // make all nodes inactive
    d3.selectAll("circle").classed("active", false);

    // make this node active
    d3.select(this).classed("active", true);

    // remove candidates
    clearCandidates();

    // reset the Hodge diamond
    setInactive();

    // add the coordinates to the legend in the fieldset
    $("fieldset#candidates legend").html("Candidates
for $\\mathrm{c}_2=" + point[0] + "$, $\\mathrm{c}_1^2=" + point[1] + "$");
    MathJax.Hub.Queue(["Typeset", MathJax.Hub]);

    // look for surfaces with the correct invariants
    for (var i = 0; i < surfaces.length; i++) {
      if (surfaces[i].c2 == point[0] && surfaces[i].c12 == point[1] && surfaces[i].kodaira == point[2])
        addCandidateSurface(surfaces[i]);
    }

    // check whether we have found surfaces, otherwise display a message
    if ($("fieldset#candidates ol li").length == 0)
      $("fieldset#candidates").prepend("
No surfaces known with these invariants, sorry.");
  }
}
<|endoftext|>


<commit_before>/* server.js: run this with Node.js in the publish/ folder to start your server.
 * Copyright (c) 2011 Jan Keromnes, Thaddee Tyl. All rights reserved.
 * Code covered by the LGPL license. */

// Import the Camp
var Camp = require ('./lib/camp.js');

// Templating demo
Camp.handle('/template.html', function (data, path) {
  var map = {
     title: data.title || 'Success',
     enc: data.enc || 'utf-8',
     info: data.info || 'This document has been templated!'
  };
  return map;
});

// Doctor demo
var replies = ['Ok.', 'Oh⁉', 'Is that so?', 'How interesting!',
               'Hm…', 'What do you mean?', 'So say we all.'];
Camp.add('doctor', function (data) {
  replies.push (data.text);
  return { reply: replies [ Math.floor ( Math.random() * replies.length ) ] };
});

// Chat demo
Camp.add('talk', function(data) {
    Camp.Server.emit('incoming', data);
});
Camp.add('all', function() {
  return function incoming(data){
    return data;
  };
});

// Not found demo
Camp.notfound(/.*/, function (data, path) {
  path[0] = '/404.html';
});

// Let's rock'n'roll!
Camp.Server.start (80);
<commit_msg>Explanatory comment to help understand templates.<commit_after>/* server.js: run this with Node.js in the publish/ folder to start your server.
 * Copyright (c) 2011 Jan Keromnes, Thaddee Tyl. All rights reserved.
 * Code covered by the LGPL license. */

// Import the Camp
var Camp = require ('./lib/camp.js');

// Templating demo
Camp.handle('/template.html', function (data, path) {
  var map = {    // Try http://localhost/template.html?title=Hello&info=[Redacted].
     title: data.title || 'Success',
     enc: data.enc || 'utf-8',
     info: data.info || 'This document has been templated!'
  };
  return map;
});

// Doctor demo
var replies = ['Ok.', 'Oh⁉', 'Is that so?', 'How interesting!',
               'Hm…', 'What do you mean?', 'So say we all.'];
Camp.add('doctor', function (data) {
  replies.push (data.text);
  return { reply: replies [ Math.floor ( Math.random() * replies.length ) ] };
});

// Chat demo
Camp.add('talk', function(data) {
    Camp.Server.emit('incoming', data);
});
Camp.add('all', function() {
  return function incoming(data){
    return data;
  };
});

// Not found demo
Camp.notfound(/.*/, function (data, path) {
  path[0] = '/404.html';
});

// Let's rock'n'roll!
Camp.Server.start (80);
<|endoftext|>


<commit_before>const {series, watch, src, dest, parallel} = require('gulp');
const pump = require('pump');
const path = require('path');
const releaseUtils = require('@tryghost/release-utils');
const inquirer = require('inquirer');

// gulp plugins and utils
const livereload = require('gulp-livereload');
const postcss = require('gulp-postcss');
const zip = require('gulp-zip');
const concat = require('gulp-concat');
const uglify = require('gulp-uglify');
const beeper = require('beeper');
const fs = require('fs');

// postcss plugins
const autoprefixer = require('autoprefixer');
const colorFunction = require('postcss-color-mod-function');
const cssnano = require('cssnano');
const easyimport = require('postcss-easy-import');

const REPO = 'TryGhost/Casper';
const REPO_READONLY = 'TryGhost/Casper';
const CHANGELOG_PATH = path.join(process.cwd(), '.', 'changelog.md');

function serve(done) {
    livereload.listen();
    done();
}

const handleError = (done) => {
    return function (err) {
        if (err) {
            beeper();
        }
        return done(err);
    };
};

function hbs(done) {
    pump([
        src(['*.hbs', 'partials/**/*.hbs']),
        livereload()
    ], handleError(done));
}

function css(done) {
    pump([
        src('assets/css/*.css', {sourcemaps: true}),
        postcss([
            easyimport,
            colorFunction(),
            autoprefixer(),
            cssnano()
        ]),
        dest('assets/built/', {sourcemaps: '.'}),
        livereload()
    ], handleError(done));
}

function js(done) {
    pump([
        src([
            // pull in lib files first so our own code can depend on it
            'assets/js/lib/*.js',
            'assets/js/*.js'
        ], {sourcemaps: true}),
        concat('casper.js'),
        uglify(),
        dest('assets/built/', {sourcemaps: '.'}),
        livereload()
    ], handleError(done));
}

function zipper(done) {
    const filename = require('./package.json').name + '.zip';

    pump([
        src([
            '**',
            '!node_modules', '!node_modules/**',
            '!dist', '!dist/**',
            '!yarn-error.log'
        ]),
        zip(filename),
        dest('dist/')
    ], handleError(done));
}

const cssWatcher = () => watch('assets/css/**', css);
const hbsWatcher = () => watch(['*.hbs', 'partials/**/*.hbs'], hbs);
const watcher = parallel(cssWatcher, hbsWatcher);
const build = series(css, js);

exports.build = build;
exports.zip = series(build, zipper);
exports.default = series(build, serve, watcher);

exports.release = () => {
    // @NOTE: https://yarnpkg.com/lang/en/docs/cli/version/
    // require(./package.json) can run into caching issues, this re-reads from file everytime on release
    var packageJSON = JSON.parse(fs.readFileSync('./package.json'));
    const newVersion = packageJSON.version;

    if (!newVersion || newVersion === '') {
        console.log(`Invalid version: ${newVersion}`);
        return;
    }

    console.log(`\nCreating release for ${newVersion}...`);

    let config;
    try {
        config = require('./config');
    } catch (err) {
        config = null;
    }

    if (!config || !config.github || !config.github.token) {
        console.log('Please copy config.example.json and configure Github token.');
        return;
    }

    let compatibleWithGhost;

    return inquirer.prompt([{
        type: 'input',
        name: 'compatibleWithGhost',
        message: 'Which version of Ghost is it compatible with?',
        default: '3.0.0'
    }])
    .then(result => {
        compatibleWithGhost = result.compatibleWithGhost;
        return Promise.resolve();
    })
    .then(() => releaseUtils.releases.get({
        userAgent: 'Casper',
        uri: `https://api.github.com/repos/${REPO_READONLY}/releases`
    }))
    .then((response) => {
        if (!response || !response.length) {
            console.log('No releases found. Skipping...');
            return;
        }

        let previousVersion = response[0].tag_name || response[0].name;
        console.log(`Previous version: ${previousVersion}`);
        return Promise.resolve(previousVersion);
    })
    .then((previousVersion) => {
        const changelog = new releaseUtils.Changelog({
            changelogPath: CHANGELOG_PATH,
            folder: path.join(process.cwd(), '.')
        });

        changelog
            .write({
                githubRepoPath: `https://github.com/${REPO}`,
                lastVersion: previousVersion
            })
            .sort()
            .clean();

        return Promise.resolve();
    })
    .then(() => releaseUtils.releases.create({
        draft: true,
        preRelease: false,
        tagName: newVersion,
        releaseName: newVersion,
        userAgent: 'Casper',
        uri: `https://api.github.com/repos/${REPO}/releases`,
        github: {
            token: config.github.token
        },
        content: [`**Compatible with Ghost ≥ ${compatibleWithGhost}**\n\n`],
        changelogPath: CHANGELOG_PATH
    }))
    .then((response) => {
        console.log(`\nRelease draft generated: ${response.releaseUrl}\n`);
        return Promise.resolve();
    })
    .catch((err) => {
        console.error(err);
        process.exit(1);
    });
};
<commit_msg>Removed the need for config.json when releasing<commit_after>const {series, watch, src, dest, parallel} = require('gulp');
const pump = require('pump');
const path = require('path');
const releaseUtils = require('@tryghost/release-utils');
const inquirer = require('inquirer');

// gulp plugins and utils
const livereload = require('gulp-livereload');
const postcss = require('gulp-postcss');
const zip = require('gulp-zip');
const concat = require('gulp-concat');
const uglify = require('gulp-uglify');
const beeper = require('beeper');
const fs = require('fs');

// postcss plugins
const autoprefixer = require('autoprefixer');
const colorFunction = require('postcss-color-mod-function');
const cssnano = require('cssnano');
const easyimport = require('postcss-easy-import');

const REPO = 'TryGhost/Casper';
const REPO_READONLY = 'TryGhost/Casper';
const CHANGELOG_PATH = path.join(process.cwd(), '.', 'changelog.md');

function serve(done) {
    livereload.listen();
    done();
}

const handleError = (done) => {
    return function (err) {
        if (err) {
            beeper();
        }
        return done(err);
    };
};

function hbs(done) {
    pump([
        src(['*.hbs', 'partials/**/*.hbs']),
        livereload()
    ], handleError(done));
}

function css(done) {
    pump([
        src('assets/css/*.css', {sourcemaps: true}),
        postcss([
            easyimport,
            colorFunction(),
            autoprefixer(),
            cssnano()
        ]),
        dest('assets/built/', {sourcemaps: '.'}),
        livereload()
    ], handleError(done));
}

function js(done) {
    pump([
        src([
            // pull in lib files first so our own code can depend on it
            'assets/js/lib/*.js',
            'assets/js/*.js'
        ], {sourcemaps: true}),
        concat('casper.js'),
        uglify(),
        dest('assets/built/', {sourcemaps: '.'}),
        livereload()
    ], handleError(done));
}

function zipper(done) {
    const filename = require('./package.json').name + '.zip';

    pump([
        src([
            '**',
            '!node_modules', '!node_modules/**',
            '!dist', '!dist/**',
            '!yarn-error.log'
        ]),
        zip(filename),
        dest('dist/')
    ], handleError(done));
}

const cssWatcher = () => watch('assets/css/**', css);
const hbsWatcher = () => watch(['*.hbs', 'partials/**/*.hbs'], hbs);
const watcher = parallel(cssWatcher, hbsWatcher);
const build = series(css, js);

exports.build = build;
exports.zip = series(build, zipper);
exports.default = series(build, serve, watcher);

exports.release = async () => {
    // @NOTE: https://yarnpkg.com/lang/en/docs/cli/version/
    // require(./package.json) can run into caching issues, this re-reads from file everytime on release
    let packageJSON = JSON.parse(fs.readFileSync('./package.json'));
    const newVersion = packageJSON.version;

    if (!newVersion || newVersion === '') {
        console.log(`Invalid version: ${newVersion}`);
        return;
    }

    console.log(`\nCreating release for ${newVersion}...`);

    const githubToken = process.env.GST_TOKEN;

    if (githubToken) {
        console.log('Please configure your environment with a Github token located in GST_TOKEN');
        return;
    }

    try {
        const result = await inquirer.prompt([{
            type: 'input',
            name: 'compatibleWithGhost',
            message: 'Which version of Ghost is it compatible with?',
            default: '3.0.0'
        }]);

        const compatibleWithGhost = result.compatibleWithGhost;

        const releasesResponse = await releaseUtils.releases.get({
            userAgent: 'Casper',
            uri: `https://api.github.com/repos/${REPO_READONLY}/releases`
        });

        if (!releasesResponse || !releasesResponse) {
            console.log('No releases found. Skipping...');
            return;
        }

        let previousVersion = releasesResponse[0].tag_name || releasesResponse[0].name;
        console.log(`Previous version: ${previousVersion}`);

        const changelog = new releaseUtils.Changelog({
            changelogPath: CHANGELOG_PATH,
            folder: path.join(process.cwd(), '.')
        });

        changelog
            .write({
                githubRepoPath: `https://github.com/${REPO}`,
                lastVersion: previousVersion
            })
            .sort()
            .clean();

        const newReleaseResponse = await releaseUtils.releases.create({
            draft: true,
            preRelease: false,
            tagName: newVersion,
            releaseName: newVersion,
            userAgent: 'Casper',
            uri: `https://api.github.com/repos/${REPO}/releases`,
            github: {
                token: githubToken
            },
            content: [`**Compatible with Ghost ≥ ${compatibleWithGhost}**\n\n`],
            changelogPath: CHANGELOG_PATH
        });
        console.log(`\nRelease draft generated: ${newReleaseResponse.releaseUrl}\n`);
    } catch (err) {
        console.error(err);
        process.exit(1);
    }
};
<|endoftext|>


<commit_before>var on_dragstart = function(event) {
  var id = event.target.getAttribute('id');
  event.originalEvent.dataTransfer.setData("text/plain", id);
}

var on_dragover = function(event) {
  event.preventDefault();
}

var on_drop = function(event) {
  event.preventDefault();
  var id      = event.originalEvent.dataTransfer.getData("text/plain");
  var task    = document.getElementById(id);
  var target  = $(event.target);

  drop_task(target, task);
}

var create_task = function(list, task_name, id) {
  task = $('<li/>').html(task_name)
          .prop('id', id)
          .prop('draggable', true)
          .addClass('task');

  task.bind('dragstart', on_dragstart);
  list.append(task);
}

var generate_sample_tasks = function(lists) {
  for (i = 1; i <= lists.length; i++) {
    list = $(lists[i - 1]);

    for (j = 1; j < 4; j ++) {
      task_id   = i + '.' + j;
      task_name = 'Task ' + task_id;
      create_task(list, task_name, task_id);
    }
  }
}

var drop_task = function(target, task) {
  var tag = target.prop('tagName').toLowerCase()
  if (tag == 'ul')
    target.append(task);

  if (tag == 'li')
    target.after(task);
}

var generate_sample_list = function(id, index) {
  list    = $('<ul />')
  header  = $('<li />').html('List ' + index).addClass('header')

  list.bind('dragover', on_dragover);
  list.bind('drop', on_drop);
  list.append(header);
  $('#' + lists_id).append(list);
}

var lists_id = 'lists'
for (i = 0; i < 3; i++)
  generate_sample_list(lists_id, i + 1);

var lists = $('#' + lists_id).children();
generate_sample_tasks(lists);

<commit_msg>Cosmetic changes<commit_after>var on_dragstart = function(event) {
  var id = event.target.getAttribute('id');
  event.originalEvent.dataTransfer.setData("text/plain", id);
}

var on_dragover = function(event) {
  event.preventDefault();
}

var on_drop = function(event) {
  event.preventDefault();
  var id      = event.originalEvent.dataTransfer.getData("text/plain");
  var task    = document.getElementById(id);
  var target  = $(event.target);

  drop_task(target, task);
}

var create_task = function(list, task_name, id) {
  task = $('<li/>').html(task_name)
          .prop('id', id)
          .prop('draggable', true)
          .addClass('task');

  task.bind('dragstart', on_dragstart);
  list.append(task);
}

var generate_sample_tasks = function(lists) {
  var tasks_per_list = 5;
  for (i = 0; i < lists.length; i++) {
    list = $(lists[i]);

    for (j = 0; j < tasks_per_list; j ++) {
      task_id   = (i + 1) + '.' + (j + 1);
      task_name = 'Task ' + task_id;
      create_task(list, task_name, task_id);
    }
  }
}

var drop_task = function(target, task) {
  var tag = target.prop('tagName').toLowerCase()
  if (tag == 'ul')
    target.append(task);

  if (tag == 'li')
    target.after(task);
}

var generate_sample_list = function(id, index) {
  list    = $('<ul />')
  header  = $('<li />').html('List ' + index).addClass('header')

  list.bind('dragover', on_dragover);
  list.bind('drop', on_drop);
  list.append(header);
  $('#' + lists_id).append(list);
}

var lists_id = 'lists'
for (i = 0; i < 3; i++)
  generate_sample_list(lists_id, i + 1);

var lists = $('#' + lists_id).children();
generate_sample_tasks(lists);

<|endoftext|>


<commit_before>require('habitat').load();
var Path = require('path');

var Hapi = require('hapi');
var Good = require('good');

var httpRequest = require('request');

var server = new Hapi.Server();
server.connection({
  host: process.env.HOST,
  port: process.env.PORT
});

server.route([
  {
     method: 'GET',
     path: '/{params*}',
     handler: {
       directory: {
         path: Path.join(__dirname, 'public')
       }
     }
  }, {
    method: 'POST',
    path: '/api/signup',
    handler: function(request, reply) {
      var payload = request.payload || {};
      var mailingList = !!payload['signup-mailing'];
      if (mailingList) {
        httpRequest({
          url: 'https://sendto.mozilla.org/page/signup/EOYFR2014-donor',
          method: "POST",
          form: {
            'opt_in': '1',
            email: payload.email
          }
        }, function(err, httpResponse, body) {
          if (err) {
            return console.error('signup failed:', err);
          }
        });
      }
      httpRequest({
        url: 'https://sendto.mozilla.org/page/s/test-signup',
        method: "POST",
        form: {
          firstname: payload.firstname,
          lastname: payload.lastname,
          country: payload.country,
          email: payload.email,
          'custom-3586': payload['privacy-checkbox']
        }
      }, function(err, httpResponse, body) {
        if (err) {
          return console.error('signature failed:', err);
        }
        reply.redirect("/data-retention/thank-you/");
      });
    }
  }
]);

server.register({
  register: Good,
  options: {
    reporters: [{
      reporter: require('good-console'),
      events: {
        response: '*',
        log: '*'
      }
    }]
  }
}, function (err) {
  if (err) {
    throw err;
  }

  server.start(function () {
    server.log('info', 'Server running at: ' + server.info.uri);
  });
});
<commit_msg>Redirect to current petition<commit_after>require('habitat').load();
var Path = require('path');

var Hapi = require('hapi');
var Good = require('good');

var httpRequest = require('request');

var server = new Hapi.Server();
server.connection({
  host: process.env.HOST,
  port: process.env.PORT
});

server.route([
  {
     method: 'GET',
     path: '/{params*}',
     handler: {
       directory: {
         path: Path.join(__dirname, 'public')
       }
     }
  }, {
    method: 'POST',
    path: '/api/signup',
    handler: function(request, reply) {
      var payload = request.payload || {};
      var mailingList = !!payload['signup-mailing'];
      if (mailingList) {
        httpRequest({
          url: 'https://sendto.mozilla.org/page/signup/EOYFR2014-donor',
          method: "POST",
          form: {
            'opt_in': '1',
            email: payload.email
          }
        }, function(err, httpResponse, body) {
          if (err) {
            return console.error('signup failed:', err);
          }
        });
      }
      httpRequest({
        url: 'https://sendto.mozilla.org/page/s/test-signup',
        method: "POST",
        form: {
          firstname: payload.firstname,
          lastname: payload.lastname,
          country: payload.country,
          email: payload.email,
          'custom-3586': payload['privacy-checkbox']
        }
      }, function(err, httpResponse, body) {
        if (err) {
          return console.error('signature failed:', err);
        }
        reply.redirect("/data-retention/thank-you/");
      });
    }
  }
]);

// This will catch all 404s and redirect them to root URL
// with preserving the pathname for client-side to handle.
server.ext('onPreResponse', function(request, reply) {
  if(request.response.output && [403, 404].indexOf(request.response.output.statusCode) >= 0) {
    return reply.redirect('/data-retention');
  }
  return reply.continue();
});

server.register({
  register: Good,
  options: {
    reporters: [{
      reporter: require('good-console'),
      events: {
        response: '*',
        log: '*'
      }
    }]
  }
}, function (err) {
  if (err) {
    throw err;
  }

  server.start(function () {
    server.log('info', 'Server running at: ' + server.info.uri);
  });
});
<|endoftext|>


<commit_before>const gulp = require('gulp');
const { series, parallel } = gulp;
const glob = require('glob');
const shell = cmd => require('child_process').execSync(cmd, { stdio: [0, 1, 2] });
const del = require('del');
const source = require('vinyl-source-stream');
const buffer = require('vinyl-buffer');
const $ = require('gulp-load-plugins')();
const browserify = require('browserify');
const tsify = require('tsify');
const minify = require('gulp-uglify/composer')(require('uglify-es'), console);
const Server = require('karma').Server;

const pkg = require('./package.json');
const config = {
  browsers: ['Chrome', 'Firefox'].concat((os => {
    switch (os) {
      case 'Windows_NT':
        return ['Edge'];
      case 'Darwin':
        return [];
     default:
        return [];
    }
  })(require('os').type())),
  ts: {
    dist: {
      src: [
        '*.ts'
      ],
      dest: 'dist'
    },
    test: {
      src: [
        '*.ts',
        'src/**/*.ts',
        'test/**/*.ts'
      ],
      dest: 'dist'
    }
  },
  site: {
    js: './gh-pages/assets/js/lib',
  },
  banner: [
    `/*! ${pkg.name} v${pkg.version} ${pkg.repository.url} | (c) 2012, ${pkg.author} | ${pkg.license} License */`,
    ''
  ].join('\n'),
  module: `
(function (root, factory) {
  if (typeof define === 'function' && define.amd) {
      define([], factory);
  } else if (typeof module === 'object' && module.exports) {
      module.exports = factory();
  } else {
      //root.returnExports = factory();
  }
}(typeof self !== 'undefined' ? self : this, function () {
  return require('${pkg.name}');
}));
`,
  clean: [
    'dist',
    'gh-pages/assets/*/**/lib',
  ]
};

function compile(src, watch = false) {
  let done = true;
  const b = browserify(Object.values(src).map(p => glob.sync(p)), {
    cache: {},
    packageCache: {},
  })
    .require(`./index.ts`, { expose: pkg.name })
    .plugin(tsify, { global: true, ...require('./tsconfig.json').compilerOptions });
  return bundle();

  function bundle() {
    console.time('bundle');
    return b
      .bundle()
      .on("error", err => done = console.log(err + '') || watch)
      .pipe(source(`${pkg.name}.js`))
      .pipe(buffer())
      .pipe($.derequire())
      .once('finish', () => console.timeEnd('bundle'))
      .once("finish", () => done || process.exit(1))
      .pipe($.footer(config.module));
  }
}

gulp.task('ts:dev', () =>
  gulp.watch(config.ts.test.src, { ignoreInitial: false }, () =>
    compile(config.ts.test.src, true)
      .pipe($.rename({ extname: '.test.js' }))
      .pipe(gulp.dest(config.ts.test.dest))));

gulp.task('ts:test', () =>
  compile(config.ts.test.src)
    .pipe($.rename({ extname: '.test.js' }))
    .pipe(gulp.dest(config.ts.test.dest)));

gulp.task('ts:dist', () =>
  compile(config.ts.dist.src)
    .pipe($.unassert())
    .pipe($.header(config.banner))
    .pipe(gulp.dest(config.ts.dist.dest))
    .pipe(gulp.dest(config.site.js))
    .pipe($.rename({ extname: '.min.js' }))
    .pipe(minify({ output: { comments: /^!/ } }))
    .pipe(gulp.dest(config.ts.dist.dest)));

gulp.task('ts:view', () =>
  gulp.watch(config.ts.dist.src, { ignoreInitial: false }, () =>
    compile(config.ts.dist.src, true)
      .pipe($.unassert())
      .pipe($.header(config.banner))
      .pipe(gulp.dest(config.site.js))));

gulp.task('karma:dev', done =>
  void new Server({
    configFile: __dirname + '/karma.conf.js',
    browsers: config.browsers,
    preprocessors: {
      'dist/*.js': ['espower']
    },
    singleRun: false
  }, done).start());

gulp.task('karma:test', done =>
  void new Server({
    configFile: __dirname + '/karma.conf.js',
    browsers: config.browsers,
    preprocessors: {
      'dist/*.js': ['coverage', 'espower']
    },
    reporters: ['dots', 'coverage'],
    concurrency: 1,
    singleRun: true
  }, done).start());

gulp.task('karma:ci', done =>
  void new Server({
    configFile: __dirname + '/karma.conf.js',
    browsers: config.browsers,
    preprocessors: {
      'dist/*.js': ['coverage', 'espower']
    },
    reporters: ['dots', 'coverage', 'coveralls'],
    concurrency: 1,
    singleRun: true
  }, done).start());

gulp.task('clean', () =>
  del(config.clean));

gulp.task('install', done => {
  shell('npm i --no-shrinkwrap');
  done();
});

gulp.task('update', done => {
  shell('bundle update');
  shell('ncu -ux del');
  shell('npm i -DE typescript@next --no-shrinkwrap');
  shell('npm i --no-shrinkwrap');
  done();
});

gulp.task('dev',
  series(
    'clean',
    parallel(
      'ts:dev',
      'karma:dev',
    )));

gulp.task('test',
  series(
    'clean',
    series(
      'ts:test',
      'karma:test',
      'ts:dist',
    )));

gulp.task('dist',
  series(
    'clean',
    series(
      'ts:dist',
    )));

gulp.task('view',
  series(
    'clean',
    () =>
      shell([
        'concurrently',
        '"gulp dev"',
        '"gulp ts:view"',
        '"bundle exec jekyll serve -s ./gh-pages -d ./gh-pages/_site --incremental"'
      ].join(' ')),
  ));

gulp.task('ci',
  series(
    'clean',
    series(
      'ts:test',
      'karma:ci',
      'karma:ci',
      'karma:ci',
      'dist',
    )));
<commit_msg>refactor: refactoring<commit_after>const gulp = require('gulp');
const { series, parallel } = gulp;
const glob = require('glob');
const shell = cmd => require('child_process').execSync(cmd, { stdio: [0, 1, 2] });
const del = require('del');
const source = require('vinyl-source-stream');
const buffer = require('vinyl-buffer');
const $ = require('gulp-load-plugins')();
const browserify = require('browserify');
const tsify = require('tsify');
const minify = require('gulp-uglify/composer')(require('uglify-es'), console);
const Server = require('karma').Server;

const pkg = require('./package.json');
const config = {
  browsers: ['Chrome', 'Firefox'].concat((os => {
    switch (os) {
      case 'Windows_NT':
        return ['Edge'];
      case 'Darwin':
        return [];
     default:
        return [];
    }
  })(require('os').type())),
  ts: {
    dist: {
      src: [
        '*.ts'
      ],
      dest: 'dist'
    },
    test: {
      src: [
        '*.ts',
        'src/**/*.ts',
        'test/**/*.ts'
      ],
      dest: 'dist'
    }
  },
  site: {
    js: './gh-pages/assets/js/lib',
  },
  banner: [
    `/*! ${pkg.name} v${pkg.version} ${pkg.repository.url} | (c) 2012, ${pkg.author} | ${pkg.license} License */`,
    ''
  ].join('\n'),
  module: `
(function (root, factory) {
  if (typeof define === 'function' && define.amd) {
      define([], factory);
  } else if (typeof module === 'object' && module.exports) {
      module.exports = factory();
  } else {
      //root.returnExports = factory();
  }
}(typeof self !== 'undefined' ? self : this, function () {
  return require('${pkg.name}');
}));
`,
  clean: [
    'dist',
    'gh-pages/assets/*/**/lib',
  ]
};

function compile(src, watch = false) {
  let done = true;
  const b = browserify(Object.values(src).map(p => glob.sync(p)), {
    cache: {},
    packageCache: {},
  })
    .require(`./index.ts`, { expose: pkg.name })
    .plugin(tsify, { global: true, ...require('./tsconfig.json').compilerOptions });
  return bundle();

  function bundle() {
    console.time('bundle');
    return b
      .bundle()
      .on("error", err => done = console.log(err + '') || watch)
      .pipe(source(`${pkg.name}.js`))
      .pipe(buffer())
      .pipe($.derequire())
      .once('finish', () => console.timeEnd('bundle'))
      .once("finish", () => done || process.exit(1))
      .pipe($.footer(config.module));
  }
}

gulp.task('ts:dev', () =>
  gulp.watch(config.ts.test.src, { ignoreInitial: false }, () =>
    compile(config.ts.test.src, true)
      .pipe($.rename({ extname: '.test.js' }))
      .pipe(gulp.dest(config.ts.test.dest))));

gulp.task('ts:test', () =>
  compile(config.ts.test.src)
    .pipe($.rename({ extname: '.test.js' }))
    .pipe(gulp.dest(config.ts.test.dest)));

gulp.task('ts:dist', () =>
  compile(config.ts.dist.src)
    .pipe($.unassert())
    .pipe($.header(config.banner))
    .pipe(gulp.dest(config.ts.dist.dest))
    .pipe(gulp.dest(config.site.js))
    .pipe($.rename({ extname: '.min.js' }))
    .pipe(minify({ output: { comments: /^!/ } }))
    .pipe(gulp.dest(config.ts.dist.dest)));

gulp.task('ts:view', () =>
  gulp.watch(config.ts.dist.src, { ignoreInitial: false }, () =>
    compile(config.ts.dist.src, true)
      .pipe($.unassert())
      .pipe($.header(config.banner))
      .pipe(gulp.dest(config.site.js))));

gulp.task('karma:dev', done =>
  void new Server({
    configFile: __dirname + '/karma.conf.js',
    browsers: config.browsers,
    preprocessors: {
      'dist/*.js': ['espower']
    },
    singleRun: false
  }, done).start());

gulp.task('karma:test', done =>
  void new Server({
    configFile: __dirname + '/karma.conf.js',
    browsers: config.browsers,
    preprocessors: {
      'dist/*.js': ['coverage', 'espower']
    },
    reporters: ['dots', 'coverage'],
    concurrency: 1,
    singleRun: true
  }, done).start());

gulp.task('karma:ci', done =>
  void new Server({
    configFile: __dirname + '/karma.conf.js',
    browsers: config.browsers,
    preprocessors: {
      'dist/*.js': ['coverage', 'espower']
    },
    reporters: ['dots', 'coverage', 'coveralls'],
    concurrency: 1,
    singleRun: true
  }, done).start());

gulp.task('clean', () =>
  del(config.clean));

gulp.task('install', done => {
  shell('npm i --no-shrinkwrap');
  done();
});

gulp.task('update', done => {
  shell('bundle update');
  shell('ncu -ux del');
  shell('ncu -ut typescript');
  shell('npm i --no-shrinkwrap');
  done();
});

gulp.task('dev',
  series(
    'clean',
    parallel(
      'ts:dev',
      'karma:dev',
    )));

gulp.task('test',
  series(
    'clean',
    series(
      'ts:test',
      'karma:test',
      'ts:dist',
    )));

gulp.task('dist',
  series(
    'clean',
    series(
      'ts:dist',
    )));

gulp.task('view',
  series(
    'clean',
    () =>
      shell([
        'concurrently',
        '"gulp dev"',
        '"gulp ts:view"',
        '"bundle exec jekyll serve -s ./gh-pages -d ./gh-pages/_site --incremental"'
      ].join(' ')),
  ));

gulp.task('ci',
  series(
    'clean',
    series(
      'ts:test',
      'karma:ci',
      'karma:ci',
      'karma:ci',
      'dist',
    )));
<|endoftext|>