<commit_before>var Neuvol;
var game;
var FPS = 60;
var maxScore=0;
var HOLE_HEIGHT = 120;

var images = {};

var speed = function(fps){
	FPS = parseInt(fps);
}

var loadImages = function(sources, callback){
	var nb = 0;
	var loaded = 0;
	var imgs = {};
	for(var i in sources){
		nb++;
		imgs[i] = new Image();
		imgs[i].src = sources[i];
		imgs[i].onload = function(){
			loaded++;
			if(loaded == nb){
				callback(imgs);
			}
		}
	}
}

var Bird = function(json){
	this.x = 80;
	this.y = 250;
	this.width = 40;
	this.height = 30;

	this.alive = true;
	this.gravity = 0;
	this.velocity = 0.3;
	this.jump = -6;

	this.init(json);
}

Bird.prototype.init = function(json){
	for(var i in json){
		this[i] = json[i];
	}
}

Bird.prototype.flap = function(){
	this.gravity = this.jump;
}

Bird.prototype.update = function(){
	this.gravity += this.velocity;
	this.y += this.gravity;
}

Bird.prototype.isDead = function(height, pipes){
	if(this.y >= height || this.y + this.height <= 0){
		return true;
	}
	for(var i in pipes){
		if(!(
			this.x > pipes[i].x + pipes[i].width ||
			this.x + this.width < pipes[i].x ||
			this.y > pipes[i].y + pipes[i].height ||
			this.y + this.height < pipes[i].y
			)){
			return true;
	}
}
}

var Pipe = function(json){
	this.x = 0;
	this.y = 0;
	this.width = 50;
	this.height = 40;
	this.speed = 3;
	this.verticalSpeed = 0;

	this.init(json);
}

Pipe.prototype.init = function(json){
	for(var i in json){
		this[i] = json[i];
	}
}

Pipe.prototype.update = function(){
	this.x -= this.speed;

	var pipeBounceBuffer = 10;
	if (this.isTopPipe()) {
		this.height += this.verticalSpeed;

		if (this.height < pipeBounceBuffer || this.height > (game.height - HOLE_HEIGHT - pipeBounceBuffer)) {
			this.verticalSpeed *= -1;
		}
	} else {
		this.y += this.verticalSpeed;

		if (this.y < (pipeBounceBuffer + HOLE_HEIGHT) || this.y > (game.height - pipeBounceBuffer)) {
			this.verticalSpeed *= -1;
		}
	}
}

Pipe.prototype.isOut = function(){
	if(this.x + this.width < 0){
		return true;
	}
}

Pipe.prototype.isTopPipe = function(){
	return this.y === 0;
}

var Game = function(){
	this.pipes = [];
	this.birds = [];
	this.score = 0;
	this.canvas = document.querySelector("#flappy");
	this.ctx = this.canvas.getContext("2d");
	this.width = this.canvas.width;
	this.height = this.canvas.height;
	this.spawnInterval = 90;
	this.interval = 0;
	this.gen = [];
	this.alives = 0;
	this.generation = 0;
	this.backgroundSpeed = 0.5;
	this.backgroundx = 0;
    this.maxScore = 0;
}

Game.prototype.start = function(){
	this.interval = 0;
	this.score = 0;
	this.pipes = [];
	this.birds = [];

	this.gen = Neuvol.nextGeneration();
	for(var i in this.gen){
		var b = new Bird();
		this.birds.push(b)
	}
	this.generation++;
	this.alives = this.birds.length;
}

Game.prototype.update = function(){
	this.backgroundx += this.backgroundSpeed;
	var nextHoll = 0;
	if(this.birds.length > 0){
		for(var i = 0; i < this.pipes.length; i+=2){
			if(this.pipes[i].x + this.pipes[i].width > this.birds[0].x){
				nextHoll = this.pipes[i].height/this.height;
				break;
			}
		}
	}

	for(var i in this.birds){
		if(this.birds[i].alive){

			var inputs = [
			this.birds[i].y / this.height,
			nextHoll
			];

			var res = this.gen[i].compute(inputs);
			if(res > 0.5){
				this.birds[i].flap();
			}

			this.birds[i].update();
			if(this.birds[i].isDead(this.height, this.pipes)){
				this.birds[i].alive = false;
				this.alives--;
				//console.log(this.alives);
				Neuvol.networkScore(this.gen[i], this.score);
				if(this.isItEnd()){
					this.start();
				}
			}
		}
	}

	var deletedPipes = [];
	for(var i in this.pipes){
		this.pipes[i].update();
		if(this.pipes[i].isOut()){
			deletedPipes.push(i);
		}
	}

	var deltaIndex = 0;
	for(var i in deletedPipes){
		this.pipes.splice(deletedPipes[i] - deltaIndex, 1);
		deltaIndex++;
	}

	if(this.interval == 0){
		var deltaBord = 50;
		var pipeVerticalMoveSpeed = (Math.random() * 3);
		var hollPosition = Math.round(Math.random() * (this.height - deltaBord * 2 - HOLE_HEIGHT)) +  deltaBord;
		this.pipes.push(new Pipe({x:this.width, y:0, height:hollPosition, verticalSpeed: pipeVerticalMoveSpeed}));
		this.pipes.push(new Pipe({x:this.width, y:hollPosition+HOLE_HEIGHT, height:this.height, verticalSpeed: pipeVerticalMoveSpeed}));
	}

	this.interval++;
	if(this.interval == this.spawnInterval){
		this.interval = 0;
	}

	this.score++;
    this.maxScore = (this.score > this.maxScore) ? this.score : this.maxScore;
	var self = this;
	setTimeout(function(){
		self.update();
	}, 1000/FPS);

	this.display();
}

Game.prototype.isItEnd = function(){
	for(var i in this.birds){
		if(this.birds[i].alive){
			return false;
		}
	}
	return true;
}

Game.prototype.display = function(){
	this.ctx.clearRect(0, 0, this.width, this.height);
	for(var i = 0; i < Math.ceil(this.width / images.background.width) + 1; i++){
		this.ctx.drawImage(images.background, i * images.background.width - Math.floor(this.backgroundx%images.background.width), 0)
	}

	for(var i in this.pipes){
		if(i%2 == 0){
			this.ctx.drawImage(images.pipetop, this.pipes[i].x, this.pipes[i].y + this.pipes[i].height - images.pipetop.height, this.pipes[i].width, images.pipetop.height);
		}else{
			this.ctx.drawImage(images.pipebottom, this.pipes[i].x, this.pipes[i].y, this.pipes[i].width, images.pipetop.height);
		}
	}

	this.ctx.fillStyle = "#FFC600";
	this.ctx.strokeStyle = "#CE9E00";
	for(var i in this.birds){
		if(this.birds[i].alive){
			this.ctx.save();
 			this.ctx.translate(this.birds[i].x, this.birds[i].y);
 			this.ctx.translate(this.birds[i].width/2, this.birds[i].height/2);
 			this.ctx.rotate(Math.PI/2 * this.birds[i].gravity/20);
 			this.ctx.drawImage(images.bird, -this.birds[i].width, -this.birds[i].height/2, this.birds[i].width, this.birds[i].height);
 			this.ctx.restore();
		}
	}

	this.ctx.fillStyle = "white";
	this.ctx.font="20px Oswald, sans-serif";
	this.ctx.fillText("Score : "+ this.score, 10, 25);
	this.ctx.fillText("Max Score : "+this.maxScore, 10, 50);
	this.ctx.fillText("Generation : "+this.generation, 10, 75);
	this.ctx.fillText("Alive : "+this.alives+" / "+Neuvol.options.population, 10, 100);
}

window.onload = function(){
	var sprites = {
		bird:"./img/bird.png",
		background:"./img/background.png",
		pipetop:"./img/pipetop.png",
		pipebottom:"./img/pipebottom.png"
	}

	var start = function(){
		Neuvol = new Neuroevolution({
			population:50,
			network:[2, [2], 1],
		});
		game = new Game();
		game.start();
		setTimeout(function(){
			game.update();
		}, 1000/FPS);
	}

	loadImages(sprites, function(imgs){
		images = imgs;
		start();
	})

}
<commit_msg>What happens if we add more neurons?<commit_after>var Neuvol;
var game;
var FPS = 60;
var maxScore=0;
var HOLE_HEIGHT = 120;

var images = {};

var speed = function(fps){
	FPS = parseInt(fps);
}

var loadImages = function(sources, callback){
	var nb = 0;
	var loaded = 0;
	var imgs = {};
	for(var i in sources){
		nb++;
		imgs[i] = new Image();
		imgs[i].src = sources[i];
		imgs[i].onload = function(){
			loaded++;
			if(loaded == nb){
				callback(imgs);
			}
		}
	}
}

var Bird = function(json){
	this.x = 80;
	this.y = 250;
	this.width = 40;
	this.height = 30;

	this.alive = true;
	this.gravity = 0;
	this.velocity = 0.3;
	this.jump = -6;

	this.init(json);
}

Bird.prototype.init = function(json){
	for(var i in json){
		this[i] = json[i];
	}
}

Bird.prototype.flap = function(){
	this.gravity = this.jump;
}

Bird.prototype.update = function(){
	this.gravity += this.velocity;
	this.y += this.gravity;
}

Bird.prototype.isDead = function(height, pipes){
	if(this.y >= height || this.y + this.height <= 0){
		return true;
	}
	for(var i in pipes){
		if(!(
			this.x > pipes[i].x + pipes[i].width ||
			this.x + this.width < pipes[i].x ||
			this.y > pipes[i].y + pipes[i].height ||
			this.y + this.height < pipes[i].y
			)){
			return true;
	}
}
}

var Pipe = function(json){
	this.x = 0;
	this.y = 0;
	this.width = 50;
	this.height = 40;
	this.speed = 3;
	this.verticalSpeed = 0;

	this.init(json);
}

Pipe.prototype.init = function(json){
	for(var i in json){
		this[i] = json[i];
	}
}

Pipe.prototype.update = function(){
	this.x -= this.speed;

	var pipeBounceBuffer = 10;
	if (this.isTopPipe()) {
		this.height += this.verticalSpeed;

		if (this.height < pipeBounceBuffer || this.height > (game.height - HOLE_HEIGHT - pipeBounceBuffer)) {
			this.verticalSpeed *= -1;
		}
	} else {
		this.y += this.verticalSpeed;

		if (this.y < (pipeBounceBuffer + HOLE_HEIGHT) || this.y > (game.height - pipeBounceBuffer)) {
			this.verticalSpeed *= -1;
		}
	}
}

Pipe.prototype.isOut = function(){
	if(this.x + this.width < 0){
		return true;
	}
}

Pipe.prototype.isTopPipe = function(){
	return this.y === 0;
}

var Game = function(){
	this.pipes = [];
	this.birds = [];
	this.score = 0;
	this.canvas = document.querySelector("#flappy");
	this.ctx = this.canvas.getContext("2d");
	this.width = this.canvas.width;
	this.height = this.canvas.height;
	this.spawnInterval = 90;
	this.interval = 0;
	this.gen = [];
	this.alives = 0;
	this.generation = 0;
	this.backgroundSpeed = 0.5;
	this.backgroundx = 0;
    this.maxScore = 0;
}

Game.prototype.start = function(){
	this.interval = 0;
	this.score = 0;
	this.pipes = [];
	this.birds = [];

	this.gen = Neuvol.nextGeneration();
	for(var i in this.gen){
		var b = new Bird();
		this.birds.push(b)
	}
	this.generation++;
	this.alives = this.birds.length;
}

Game.prototype.update = function(){
	this.backgroundx += this.backgroundSpeed;
	var nextHoll = 0;
	if(this.birds.length > 0){
		for(var i = 0; i < this.pipes.length; i+=2){
			if(this.pipes[i].x + this.pipes[i].width > this.birds[0].x){
				nextHoll = this.pipes[i].height/this.height;
				break;
			}
		}
	}

	for(var i in this.birds){
		if(this.birds[i].alive){

			var inputs = [
			this.birds[i].y / this.height,
			nextHoll
			];

			var res = this.gen[i].compute(inputs);
			if(res > 0.5){
				this.birds[i].flap();
			}

			this.birds[i].update();
			if(this.birds[i].isDead(this.height, this.pipes)){
				this.birds[i].alive = false;
				this.alives--;
				//console.log(this.alives);
				Neuvol.networkScore(this.gen[i], this.score);
				if(this.isItEnd()){
					this.start();
				}
			}
		}
	}

	var deletedPipes = [];
	for(var i in this.pipes){
		this.pipes[i].update();
		if(this.pipes[i].isOut()){
			deletedPipes.push(i);
		}
	}

	var deltaIndex = 0;
	for(var i in deletedPipes){
		this.pipes.splice(deletedPipes[i] - deltaIndex, 1);
		deltaIndex++;
	}

	if(this.interval == 0){
		var deltaBord = 50;
		var pipeVerticalMoveSpeed = (Math.random() * 3);
		var hollPosition = Math.round(Math.random() * (this.height - deltaBord * 2 - HOLE_HEIGHT)) +  deltaBord;
		this.pipes.push(new Pipe({x:this.width, y:0, height:hollPosition, verticalSpeed: pipeVerticalMoveSpeed}));
		this.pipes.push(new Pipe({x:this.width, y:hollPosition+HOLE_HEIGHT, height:this.height, verticalSpeed: pipeVerticalMoveSpeed}));
	}

	this.interval++;
	if(this.interval == this.spawnInterval){
		this.interval = 0;
	}

	this.score++;
    this.maxScore = (this.score > this.maxScore) ? this.score : this.maxScore;
	var self = this;
	setTimeout(function(){
		self.update();
	}, 1000/FPS);

	this.display();
}

Game.prototype.isItEnd = function(){
	for(var i in this.birds){
		if(this.birds[i].alive){
			return false;
		}
	}
	return true;
}

Game.prototype.display = function(){
	this.ctx.clearRect(0, 0, this.width, this.height);
	for(var i = 0; i < Math.ceil(this.width / images.background.width) + 1; i++){
		this.ctx.drawImage(images.background, i * images.background.width - Math.floor(this.backgroundx%images.background.width), 0)
	}

	for(var i in this.pipes){
		if(i%2 == 0){
			this.ctx.drawImage(images.pipetop, this.pipes[i].x, this.pipes[i].y + this.pipes[i].height - images.pipetop.height, this.pipes[i].width, images.pipetop.height);
		}else{
			this.ctx.drawImage(images.pipebottom, this.pipes[i].x, this.pipes[i].y, this.pipes[i].width, images.pipetop.height);
		}
	}

	this.ctx.fillStyle = "#FFC600";
	this.ctx.strokeStyle = "#CE9E00";
	for(var i in this.birds){
		if(this.birds[i].alive){
			this.ctx.save();
 			this.ctx.translate(this.birds[i].x, this.birds[i].y);
 			this.ctx.translate(this.birds[i].width/2, this.birds[i].height/2);
 			this.ctx.rotate(Math.PI/2 * this.birds[i].gravity/20);
 			this.ctx.drawImage(images.bird, -this.birds[i].width, -this.birds[i].height/2, this.birds[i].width, this.birds[i].height);
 			this.ctx.restore();
		}
	}

	this.ctx.fillStyle = "white";
	this.ctx.font="20px Oswald, sans-serif";
	this.ctx.fillText("Score : "+ this.score, 10, 25);
	this.ctx.fillText("Max Score : "+this.maxScore, 10, 50);
	this.ctx.fillText("Generation : "+this.generation, 10, 75);
	this.ctx.fillText("Alive : "+this.alives+" / "+Neuvol.options.population, 10, 100);
}

window.onload = function(){
	var sprites = {
		bird:"./img/bird.png",
		background:"./img/background.png",
		pipetop:"./img/pipetop.png",
		pipebottom:"./img/pipebottom.png"
	}

	var start = function(){
		Neuvol = new Neuroevolution({
			population:50,
			network:[2, [4], 1],
		});
		game = new Game();
		game.start();
		setTimeout(function(){
			game.update();
		}, 1000/FPS);
	}

	loadImages(sprites, function(imgs){
		images = imgs;
		start();
	})

}
<|endoftext|>


<commit_before>if(typeof widget_widget == 'undefined') {
    loadplugin('widget_widget');
}

var widget_famultibutton = $.extend({}, widget_widget, {
    widgetname : 'famultibutton',
    toggleOn : function(elem) {
        var device = elem.data('device');
        var cmd = [elem.data('cmd'), device, elem.data('set-on')].join(' ');
        setFhemStatus(cmd);
        if( device && typeof device != "undefined") {
            TOAST && $.toast(cmd);
        }
    },
    toggleOff : function(elem) {
        var device = elem.data('device');
        var cmd = [elem.data('cmd'), device, elem.data('set-off')].join(' ');
        setFhemStatus(cmd);
        if( device && typeof device != "undefined") {
            TOAST && $.toast(cmd);
        }
    },
    init_attr : function(elem) {
        elem.data('get',        elem.data('get') || 'STATE');
        elem.data('cmd',        elem.data('cmd') || 'set');
        elem.data('get-on',     elem.attr('data-get-on')    || elem.attr('data-on')     || 'on');
        elem.data('get-off',    elem.attr('data-get-off')   || elem.attr('data-off')    || 'off');
        elem.data('set-on',     elem.attr('data-set-on')    || elem.data('get-on'));
        elem.data('set-off',    elem.attr('data-set-off')   || elem.data('get-off'));
        elem.data('mode',       elem.data('mode')|| 'toggle');
        readings[elem.data('get')] = true;
    },
    init_ui : function(elem) {
        var base = this;
        elem.famultibutton({
            mode: elem.data('mode'),
            toggleOn: function() { base.toggleOn(elem) },
            toggleOff: function() { base.toggleOff(elem) },
        });
    },
    init: function () {
        var base = this;
        this.elements = $('div[data-type="'+this.widgetname+'"]');
        this.elements.each(function(index) {
            base.init_attr($(this));
            base.init_ui($(this));
        });
    },
    update: function (dev,par) {
        var deviceElements= this.elements.filter('div[data-device="'+dev+'"]');
        deviceElements.each(function(index) {
            if ( $(this).data('get')==par || par =='*') {
                var state = getDeviceValue( $(this), 'get' );
                if (state) {
                    var states=$(this).data('get-on');
                    if ( $.isArray(states)) {
                        var icons=$(this).data('icons');
                        var colors=$(this).data('on-colors');
                        if (icons && colors && states && icons.length == colors.length && icons.length == states.length ) {
                            var elm=$(this).children().last();
                            var idx=states.indexOf(state);
                            if (idx>-1){    elm.removeClass()
                                .addClass('fa fa-stack-1x')
                                .addClass(icons[idx])
                                .css( "color", colors[idx] );
                            }
                        }
                    } else {
                        if ( state == $(this).data('get-on') )
                            $(this).data('famultibutton').setOn();
                        else if ( state == $(this).data('get-off') )
                            $(this).data('famultibutton').setOff();
                        else if ( state.match(RegExp('^' + $(this).data('get-on') + '$')) )
                            $(this).data('famultibutton').setOn();
                        else if ( state.match(RegExp('^' + $(this).data('get-off') + '$')) )
                            $(this).data('famultibutton').setOff();
                        else if ( $(this).data('get-off')=='!on' && state != $(this).data('get-on') )
                            $(this).data('famultibutton').setOff();
                        else if ( $(this).data('get-on')=='!off' && state != $(this).data('get-off') )
                            $(this).data('famultibutton').setOn();
                    }
                }
            }
        });
    }
});<commit_msg>data-change-action<commit_after>if(typeof widget_widget == 'undefined') {
    loadplugin('widget_widget');
}

var widget_famultibutton = $.extend({}, widget_widget, {
    widgetname : 'famultibutton',
    toggleOn : function(elem) {
        var device = elem.data('device');
        var cmd = [elem.data('cmd'), device, elem.data('set-on')].join(' ');
        setFhemStatus(cmd);
        if( device && typeof device != "undefined") {
            TOAST && $.toast(cmd);
        }
    },
    toggleOff : function(elem) {
        var device = elem.data('device');
        var cmd = [elem.data('cmd'), device, elem.data('set-off')].join(' ');
        setFhemStatus(cmd);
        if( device && typeof device != "undefined") {
            TOAST && $.toast(cmd);
        }
    },
    init_attr : function(elem) {
        elem.data('get',        elem.data('get')        || 'STATE');
        elem.data('cmd',        elem.data('cmd')        || 'set');
        elem.data('get-on',     elem.data('get-on')     || 'on');
        elem.data('get-off',    elem.data('get-off')    || 'off');
        elem.data('set-on',     elem.data('set-on')     || elem.data('get-on'));
        elem.data('set-off',    elem.data('set-off')    || elem.data('get-off'));
        elem.data('mode',       elem.data('mode')       || 'toggle');
        readings[elem.data('get')] = true;
    },
    init_ui : function(elem) {
        var base = this;
        elem.famultibutton({
            mode: elem.data('mode'),
            toggleOn: function() { base.toggleOn(elem) },
            toggleOff: function() { base.toggleOff(elem) },
        });
        return elem;
    },
    init: function () {
        var base = this;
        this.elements = $('div[data-type="'+this.widgetname+'"]');
        this.elements.each(function(index) {
            base.init_attr($(this));
            base.init_ui($(this));
        });
    },
    update: function (dev,par) {
        var deviceElements= this.elements.filter('div[data-device="'+dev+'"]');
        deviceElements.each(function(index) {
            if ( $(this).data('get')==par || par =='*') {
                var state = getDeviceValue( $(this), 'get' );
                if(state && $(this).data('value') && state != $(this).data('value')) {
                    eval( $(this).data('change-action') );
                }
                if (state) {
                    var states=$(this).data('get-on');
                    if ( $.isArray(states)) {
                        var icons=$(this).data('icons');
                        var colors=$(this).data('on-colors');
                        if (icons && colors && states && icons.length == colors.length && icons.length == states.length ) {
                            var elm=$(this).children().last();
                            var idx=states.indexOf(state);
                            if (idx>-1){    elm.removeClass()
                                .addClass('fa fa-stack-1x')
                                .addClass(icons[idx])
                                .css( "color", colors[idx] );
                            }
                        }
                    } else {
                        if ( state == $(this).data('get-on') )
                            $(this).data('famultibutton').setOn();
                        else if ( state == $(this).data('get-off') )
                            $(this).data('famultibutton').setOff();
                        else if ( state.match(RegExp('^' + $(this).data('get-on') + '$')) )
                            $(this).data('famultibutton').setOn();
                        else if ( state.match(RegExp('^' + $(this).data('get-off') + '$')) )
                            $(this).data('famultibutton').setOff();
                        else if ( $(this).data('get-off')=='!on' && state != $(this).data('get-on') )
                            $(this).data('famultibutton').setOff();
                        else if ( $(this).data('get-on')=='!off' && state != $(this).data('get-off') )
                            $(this).data('famultibutton').setOn();
                    }
                }
                $(this).data('value', state);
            }
        });
    }
});
<|endoftext|>


<commit_before>let path = require('path');
let cors = require('cors');

module.exports = function(app) {
    app.use(cors());
    // app.use('/', function (req, res) { res.json({message:'ok'})});
    app.use('/api/v1/auth', require('./auth'));
};<commit_msg>Build gc-orders-server from commit 855bd30 on branch master<commit_after>'use strict';

let path = require('path');
let cors = require('cors');

module.exports = function(app) {
    app.use(cors());
    // app.use('/', function (req, res) { res.json({message:'ok'})});
    app.use('/api/v1/auth', require('./auth'));
};<|endoftext|>


<commit_before>import React from 'react'
import classes from './Participant.scss'
import SpacedInfo from 'components/SpacedInfo'
import StackedInfo from 'components/StackedInfo'
import LinkInfo from 'components/LinkInfo'
import { personalInfoFields, linkFields } from 'extensions/participantUtils'
import { dehumanize, humanize } from 'extensions/stringUtils'

class Participant extends React.Component {

  constructor () {
    super()
    this.state = {personalInfo: [], linkInfo: []}
  }

  static propTypes = {
    participant: React.PropTypes.object.isRequired,
    person: React.PropTypes.object.isRequired
  }

  componentDidMount () {
    this.updateState(this.props)
  }

  componentWillReceiveProps (nextProps) {
    this.updateState(nextProps)
  }

  updateState (props) {
    const personalInfo = personalInfoFields.map(field => this.getInfo(field, props))
    const linkInfo = linkFields.map(field => this.getInfo(field, props))
    this.setState({personalInfo: this.filterInfo(personalInfo),
      linkInfo: this.filterInfo(linkInfo)})
  }

  getInfo (field, props) {
    const key = dehumanize(field)
    let description = props.person[key]
    if (description == null) {
      description = props.participant[key]
    }
    return {title: field, description: description}
  }

  /* eslint eqeqeq: 0 */

  filterInfo (info) {
    return info.filter(info => info['description'] != null && info['description'] != '')
  }

  renderList (title, list) {
    if (list.length > 0) {
      return (

            {title}:  {list}

      )
    }
  }

  render () {
    return (

            {humanize(`${this.props.person['first_name']} ${this.props.person['last_name']}`)}

          <SpacedInfo titles={this.state.personalInfo.map(info => info['title'])}
            descriptions={this.state.personalInfo.map(info => info['description'])} />

        {/*

 More Info

          {this.renderList('Dietary Restrictions', this.props.person['dietary_restrictions'].join(', '))}
          {this.renderList('Skills', this.props.participant['skills'].join(', '))}
          {Object.keys(this.state.linkInfo).length > 0 ? (
            <LinkInfo titles={this.state.linkInfo.map(info => info['title'])}
              links={this.state.linkInfo.map(info => info['description'])} />
          ) : null}

        */}

 Custom Questions

          {Object.keys(this.props.participant['custom']).length > 0 ? (
            <StackedInfo text={this.props.participant['custom']} />
          ) : null}

    )
  }
}

export default Participant
<commit_msg>removed dietary from display<commit_after>import React from 'react'
import classes from './Participant.scss'
import SpacedInfo from 'components/SpacedInfo'
import StackedInfo from 'components/StackedInfo'
import LinkInfo from 'components/LinkInfo'
import { personalInfoFields, linkFields } from 'extensions/participantUtils'
import { dehumanize, humanize } from 'extensions/stringUtils'

class Participant extends React.Component {

  constructor () {
    super()
    this.state = {personalInfo: [], linkInfo: []}
  }

  static propTypes = {
    participant: React.PropTypes.object.isRequired,
    person: React.PropTypes.object.isRequired
  }

  componentDidMount () {
    this.updateState(this.props)
  }

  componentWillReceiveProps (nextProps) {
    this.updateState(nextProps)
  }

  updateState (props) {
    const personalInfo = personalInfoFields.map(field => this.getInfo(field, props))
    const linkInfo = linkFields.map(field => this.getInfo(field, props))
    this.setState({personalInfo: this.filterInfo(personalInfo),
      linkInfo: this.filterInfo(linkInfo)})
  }

  getInfo (field, props) {
    const key = dehumanize(field)
    let description = props.person[key]
    if (description == null) {
      description = props.participant[key]
    }
    return {title: field, description: description}
  }

  /* eslint eqeqeq: 0 */

  filterInfo (info) {
    return info.filter(info => info['description'] != null && info['description'] != '')
  }

  renderList (title, list) {
    if (list.length > 0) {
      return (

            {title}:  {list}

      )
    }
  }

  render () {
    return (

            {humanize(`${this.props.person['first_name']} ${this.props.person['last_name']}`)}

          <SpacedInfo titles={this.state.personalInfo.map(info => info['title'])}
            descriptions={this.state.personalInfo.map(info => info['description'])} />

 More Info

          {/* {this.renderList('Dietary Restrictions', this.props.person['dietary_restrictions'].join(', '))} */}
          {this.renderList('Skills', this.props.participant['skills'].join(', '))}
          {Object.keys(this.state.linkInfo).length > 0 ? (
            <LinkInfo titles={this.state.linkInfo.map(info => info['title'])}
              links={this.state.linkInfo.map(info => info['description'])} />
          ) : null}

 Custom Questions

          {Object.keys(this.props.participant['custom']).length > 0 ? (
            <StackedInfo text={this.props.participant['custom']} />
          ) : null}

    )
  }
}

export default Participant
<|endoftext|>


<commit_before>/*
 * grunt-contrib-symlink
 * https://github.com/gruntjs/grunt-contrib-symlink
 *
 * Copyright (c) 2014 Grunt Team
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function(grunt) {

  var fs = require('fs');
  var path = require('path');

  grunt.registerMultiTask('symlink', 'Create symbolic links.', function() {
    var nowrite = grunt.option('no-write');
    var linkCount = 0;

    // default options
    var options = this.options({
      overwrite: false
    });

    // overwrite options from CLI
    options.overwrite = grunt.option('overwrite') || options.overwrite;

    this.files.forEach(function(f) {
      var srcpath = f.src[0];
      var destpath = f.dest;
      if (!grunt.file.exists(srcpath)) {
        grunt.log.warn('Source file "' + srcpath + '" not found.');
        return;
      } else if (grunt.file.exists(destpath)) {
        if (!options.overwrite) {
          grunt.log.warn('Destination ' + destpath + ' already exists.');
          return;
        }
        grunt.file.delete(destpath);
      }
      // Strip any trailing slashes.
      destpath = destpath.replace(/[\\\/]$/, '');
      // The destdir is the location in which the symlink will be created.
      var destdir = path.join(destpath, '..');
      // If the dest path is relative, create a proper relative symlink path.
      if (!grunt.file.isPathAbsolute(srcpath)) {
        srcpath = path.relative(destdir, srcpath) || '.';
      }
      // Create any necessary interim directories.
      grunt.file.mkdir(destdir);
      // The symlink mode is determined automatically.
      var mode = grunt.file.isDir(f.src[0]) ? 'dir' : 'file';
      grunt.verbose.write((nowrite ? 'Not actually linking ' : 'Linking ') + '(' + mode + ') ' + destpath + ' -> ' + srcpath + '...');
      try {
        if (!nowrite) {
          fs.symlinkSync(srcpath, destpath, mode);
        }
        grunt.verbose.ok();
      } catch(e) {
        grunt.verbose.error();
        grunt.log.error(e);
        grunt.fail.warn('Failed to create symlink: ' + '(' + mode + ') ' + destpath + ' -> ' + srcpath + '.');
      }
      linkCount++;
    });
    grunt.log.ok('Created ' + linkCount + ' symbolic links.');
  });

};
<commit_msg>Adding option to force "outside working directory" warning<commit_after>/*
 * grunt-contrib-symlink
 * https://github.com/gruntjs/grunt-contrib-symlink
 *
 * Copyright (c) 2014 Grunt Team
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function(grunt) {

  var fs = require('fs');
  var path = require('path');

  grunt.registerMultiTask('symlink', 'Create symbolic links.', function() {
    var nowrite = grunt.option('no-write');
    var linkCount = 0;

    // default options
    var options = this.options({
      overwrite: false,
      force: false
    });

    // overwrite options from CLI
    options.overwrite = grunt.option('overwrite') || options.overwrite;

    // force options from CLI
    options.force = grunt.option('force') || options.force;

    this.files.forEach(function(f) {
      var srcpath = f.src[0];
      var destpath = f.dest;
      if (!grunt.file.exists(srcpath)) {
        grunt.log.warn('Source file "' + srcpath + '" not found.');
        return;
      } else if (grunt.file.exists(destpath)) {
        if (!options.overwrite) {
          grunt.log.warn('Destination ' + destpath + ' already exists.');
          return;
        }
        grunt.file.delete(destpath, {force: options.force});
      }
      // Strip any trailing slashes.
      destpath = destpath.replace(/[\\\/]$/, '');
      // The destdir is the location in which the symlink will be created.
      var destdir = path.join(destpath, '..');
      // If the dest path is relative, create a proper relative symlink path.
      if (!grunt.file.isPathAbsolute(srcpath)) {
        srcpath = path.relative(destdir, srcpath) || '.';
      }
      // Create any necessary interim directories.
      grunt.file.mkdir(destdir);
      // The symlink mode is determined automatically.
      var mode = grunt.file.isDir(f.src[0]) ? 'dir' : 'file';
      grunt.verbose.write((nowrite ? 'Not actually linking ' : 'Linking ') + '(' + mode + ') ' + destpath + ' -> ' + srcpath + '...');
      try {
        if (!nowrite) {
          fs.symlinkSync(srcpath, destpath, mode);
        }
        grunt.verbose.ok();
      } catch(e) {
        grunt.verbose.error();
        grunt.log.error(e);
        grunt.fail.warn('Failed to create symlink: ' + '(' + mode + ') ' + destpath + ' -> ' + srcpath + '.');
      }
      linkCount++;
    });
    grunt.log.ok('Created ' + linkCount + ' symbolic links.');
  });

};
<|endoftext|>


<commit_before>const PropTypes = require('prop-types');
/**
 * Copyright (c) 2017-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

const React = require('react')

const SocialFooter = props => (

Social

        {props.config.projectName}

    {props.config.twitterUsername && (

        <a
          href={`https://twitter.com/${props.config.twitterUsername}`}
          className="twitter-follow-button">
          Follow @{props.config.twitterUsername}

    )}
    {props.config.facebookAppId && (

    )}

);

SocialFooter.propTypes = {
  config: PropTypes.object,
};

class Footer extends React.Component {
  docUrl(doc, language) {
    const baseUrl = this.props.config.baseUrl
    return baseUrl + 'docs/' + (language ? language + '/' : '') + doc
  }

  pageUrl(doc, language) {
    const baseUrl = this.props.config.baseUrl
    return baseUrl + (language ? language + '/' : '') + doc
  }

  render() {
    const currentYear = new Date().getFullYear()
    return (

            {this.props.config.footerIcon && (

            )}

Docs

              Getting Started

              Usage

            Other

Community

              User Showcase

              Stack Overflow

            Project Chat
            Donate
            Blog

          <SocialFooter config={this.props.config} />

{this.props.config.copyright}

    )
  }
}

module.exports = Footer
<commit_msg>- Shortened hashtag list for tweet button<commit_after>const PropTypes = require('prop-types');
/**
 * Copyright (c) 2017-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

const React = require('react')

const SocialFooter = props => (

Social

        {props.config.projectName}

    {props.config.twitterUsername && (

        <a
          href={`https://twitter.com/${props.config.twitterUsername}`}
          className="twitter-follow-button">
          Follow @{props.config.twitterUsername}

    )}
    {props.config.facebookAppId && (

    )}

);

SocialFooter.propTypes = {
  config: PropTypes.object,
};

class Footer extends React.Component {
  docUrl(doc, language) {
    const baseUrl = this.props.config.baseUrl
    return baseUrl + 'docs/' + (language ? language + '/' : '') + doc
  }

  pageUrl(doc, language) {
    const baseUrl = this.props.config.baseUrl
    return baseUrl + (language ? language + '/' : '') + doc
  }

  render() {
    const currentYear = new Date().getFullYear()
    return (

            {this.props.config.footerIcon && (

            )}

Docs

              Getting Started

              Usage

            Other

Community

              User Showcase

              Stack Overflow

            Project Chat
            Donate
            Blog

          <SocialFooter config={this.props.config} />

{this.props.config.copyright}

    )
  }
}

module.exports = Footer
<|endoftext|>


<commit_before>var EventEmitter = require('events').EventEmitter
  , Slide = require('../../../src/remark/models/slide')
  , SlideView = require('../../../src/remark/views/slideView')
  , utils = require('../../../src/remark/utils')
  ;

describe('SlideView', function () {
  var slideshow = {
        getHighlightStyle: function () { return 'default'; }
      , getSlides: function () { return []; }
      }
    , scaler = {
        dimensions: {width: 10, height: 10}
      }
    ;

  describe('background', function () {
    it('should be set from background slide property', function () {
      var slide = new Slide(1, {
            source: '',
            properties: {'background-image': 'url(image.jpg)'}
          })
        , slideView = new SlideView(new EventEmitter(), slideshow, scaler, slide)
        ;

        slideView.contentElement.style.backgroundImage.should.equal('url(image.jpg)');
    });
  });

  describe('classes', function () {
    it('should contain "content" class by default', function () {
      var slide = new Slide(1, {source: ''})
        , slideView = new SlideView(new EventEmitter(), slideshow, scaler, slide)
        , classes = utils.getClasses(slideView.contentElement)
        ;

      classes.should.include('remark-slide-content');
    });

    it('should contain additional classes from slide properties', function () {
      var slide = new Slide(1, {
            source: '',
            properties: {'class': 'middle, center'}
          })
        , slideView = new SlideView(new EventEmitter(), slideshow, scaler, slide)
        , classes = utils.getClasses(slideView.contentElement)
        ;

      classes.should.include('remark-slide-content');
      classes.should.include('middle');
      classes.should.include('center');
    });
  });

  describe('empty paragraph removal', function () {
    it('should have empty paragraphs removed', function () {
      var slide = new Slide(1, {source: '<p> </p>'})
        , slideView = new SlideView(new EventEmitter(), slideshow, scaler, slide);

      slideView.contentElement.innerHTML.should.not.include('

');
    });
  });

  describe('show slide', function () {
    it('should set the slide visible', function () {
      var slide = new Slide(1, {source: ''})
        , slideView = new SlideView(new EventEmitter(), slideshow, scaler, slide)
        ;

        slideView.show();

        var classes = utils.getClasses(slideView.containerElement);
        classes.should.include('remark-visible');
        classes.should.not.include('remark-fading');
    });

    it('should remove any fading element', function () {
      var slide = new Slide(1, {source: ''})
        , slideView = new SlideView(new EventEmitter(), slideshow, scaler, slide)
        ;
        utils.addClass(slideView.containerElement, 'remark-fading');

        slideView.show();

        var classes = utils.getClasses(slideView.containerElement);
        classes.should.include('remark-visible');
        classes.should.not.include('remark-fading');
    });
  });

  describe('hide slide', function () {
    it('should mark the slide as fading', function () {
      var slide = new Slide(1, {source: ''})
        , slideView = new SlideView(new EventEmitter(), slideshow, scaler, slide)
        ;
        utils.addClass(slideView.containerElement, 'remark-visible');

        slideView.hide();

        var classes = utils.getClasses(slideView.containerElement);
        classes.should.not.include('remark-visible');
        classes.should.include('remark-fading');
    });
  });

});
<commit_msg>Use regexp match to allow absolute image path.<commit_after>var EventEmitter = require('events').EventEmitter
  , Slide = require('../../../src/remark/models/slide')
  , SlideView = require('../../../src/remark/views/slideView')
  , utils = require('../../../src/remark/utils')
  ;

describe('SlideView', function () {
  var slideshow = {
        getHighlightStyle: function () { return 'default'; }
      , getSlides: function () { return []; }
      }
    , scaler = {
        dimensions: {width: 10, height: 10}
      }
    ;

  describe('background', function () {
    it('should be set from background slide property', function () {
      var slide = new Slide(1, {
            source: '',
            properties: {'background-image': 'url(image.jpg)'}
          })
        , slideView = new SlideView(new EventEmitter(), slideshow, scaler, slide)
        ;

        slideView.contentElement.style.backgroundImage.should.match(/^url\(.*image\.jpg\)$/);
    });
  });

  describe('classes', function () {
    it('should contain "content" class by default', function () {
      var slide = new Slide(1, {source: ''})
        , slideView = new SlideView(new EventEmitter(), slideshow, scaler, slide)
        , classes = utils.getClasses(slideView.contentElement)
        ;

      classes.should.include('remark-slide-content');
    });

    it('should contain additional classes from slide properties', function () {
      var slide = new Slide(1, {
            source: '',
            properties: {'class': 'middle, center'}
          })
        , slideView = new SlideView(new EventEmitter(), slideshow, scaler, slide)
        , classes = utils.getClasses(slideView.contentElement)
        ;

      classes.should.include('remark-slide-content');
      classes.should.include('middle');
      classes.should.include('center');
    });
  });

  describe('empty paragraph removal', function () {
    it('should have empty paragraphs removed', function () {
      var slide = new Slide(1, {source: '<p> </p>'})
        , slideView = new SlideView(new EventEmitter(), slideshow, scaler, slide);

      slideView.contentElement.innerHTML.should.not.include('

');
    });
  });

  describe('show slide', function () {
    it('should set the slide visible', function () {
      var slide = new Slide(1, {source: ''})
        , slideView = new SlideView(new EventEmitter(), slideshow, scaler, slide)
        ;

        slideView.show();

        var classes = utils.getClasses(slideView.containerElement);
        classes.should.include('remark-visible');
        classes.should.not.include('remark-fading');
    });

    it('should remove any fading element', function () {
      var slide = new Slide(1, {source: ''})
        , slideView = new SlideView(new EventEmitter(), slideshow, scaler, slide)
        ;
        utils.addClass(slideView.containerElement, 'remark-fading');

        slideView.show();

        var classes = utils.getClasses(slideView.containerElement);
        classes.should.include('remark-visible');
        classes.should.not.include('remark-fading');
    });
  });

  describe('hide slide', function () {
    it('should mark the slide as fading', function () {
      var slide = new Slide(1, {source: ''})
        , slideView = new SlideView(new EventEmitter(), slideshow, scaler, slide)
        ;
        utils.addClass(slideView.containerElement, 'remark-visible');

        slideView.hide();

        var classes = utils.getClasses(slideView.containerElement);
        classes.should.not.include('remark-visible');
        classes.should.include('remark-fading');
    });
  });

});
<|endoftext|>


<commit_before>/**
 * HTTP Server Settings
 * (sails.config.http)
 *
 * Configuration for the underlying HTTP server in Sails.
 * Only applies to HTTP requests (not WebSockets)
 *
 * For more information on configuration, check out:
 * http://sailsjs.org/#!/documentation/reference/sails.config/sails.config.http.html
 */

module.exports.http = {

  /****************************************************************************
  *                                                                           *
  * Express middleware to use for every Sails request. To add custom          *
  * middleware to the mix, add a function to the middleware config object and *
  * add its key to the "order" array. The $custom key is reserved for         *
  * backwards-compatibility with Sails v0.9.x apps that use the               *
  * `customMiddleware` config option.                                         *
  *                                                                           *
  ****************************************************************************/

  // middleware: {

  /***************************************************************************
  *                                                                          *
  * The order in which middleware should be run for HTTP request. (the Sails *
  * router is invoked by the "router" middleware below.)                     *
  *                                                                          *
  ***************************************************************************/

    // order: [
    //   'startRequestTimer',
    //   'cookieParser',
    //   'session',
    //   'myRequestLogger',
    //   'bodyParser',
    //   'handleBodyParserError',
    //   'compress',
    //   'methodOverride',
    //   'poweredBy',
    //   '$custom',
    //   'router',
    //   'www',
    //   'favicon',
    //   '404',
    //   '500'
    // ],

  /****************************************************************************
  *                                                                           *
  * Example custom middleware; logs each request to the console.              *
  *                                                                           *
  ****************************************************************************/

    // myRequestLogger: function (req, res, next) {
    //     console.log("Requested :: ", req.method, req.url);
    //     return next();
    // }

  /***************************************************************************
  *                                                                          *
  * The body parser that will handle incoming multipart HTTP requests. By    *
  * default as of v0.10, Sails uses                                          *
  * [skipper](http://github.com/balderdashy/skipper). See                    *
  * http://www.senchalabs.org/connect/multipart.html for other options.      *
  *                                                                          *
  ***************************************************************************/

    // bodyParser: require('skipper')

  // },

  /***************************************************************************
  *                                                                          *
  * The number of seconds to cache flat files on disk being served by        *
  * Express static middleware (by default, these files are in `.tmp/public`) *
  *                                                                          *
  * The HTTP static cache is only active in a 'production' environment,      *
  * since that's the only time Express will cache flat-files.                *
  *                                                                          *
  ***************************************************************************/

  // cache: 31557600000
};
<commit_msg>Update "bodyParser" example and uncomment "middleware" property for clarity<commit_after>/**
 * HTTP Server Settings
 * (sails.config.http)
 *
 * Configuration for the underlying HTTP server in Sails.
 * Only applies to HTTP requests (not WebSockets)
 *
 * For more information on configuration, check out:
 * http://sailsjs.org/#!/documentation/reference/sails.config/sails.config.http.html
 */

module.exports.http = {

  /****************************************************************************
  *                                                                           *
  * Express middleware to use for every Sails request. To add custom          *
  * middleware to the mix, add a function to the middleware config object and *
  * add its key to the "order" array. The $custom key is reserved for         *
  * backwards-compatibility with Sails v0.9.x apps that use the               *
  * `customMiddleware` config option.                                         *
  *                                                                           *
  ****************************************************************************/

  middleware: {

  /***************************************************************************
  *                                                                          *
  * The order in which middleware should be run for HTTP request. (the Sails *
  * router is invoked by the "router" middleware below.)                     *
  *                                                                          *
  ***************************************************************************/

    // order: [
    //   'startRequestTimer',
    //   'cookieParser',
    //   'session',
    //   'myRequestLogger',
    //   'bodyParser',
    //   'handleBodyParserError',
    //   'compress',
    //   'methodOverride',
    //   'poweredBy',
    //   '$custom',
    //   'router',
    //   'www',
    //   'favicon',
    //   '404',
    //   '500'
    // ],

  /****************************************************************************
  *                                                                           *
  * Example custom middleware; logs each request to the console.              *
  *                                                                           *
  ****************************************************************************/

    // myRequestLogger: function (req, res, next) {
    //     console.log("Requested :: ", req.method, req.url);
    //     return next();
    // }

  /***************************************************************************
  *                                                                          *
  * The body parser that will handle incoming multipart HTTP requests. By    *
  * default as of v0.10, Sails uses                                          *
  * [skipper](http://github.com/balderdashy/skipper). See                    *
  * http://www.senchalabs.org/connect/multipart.html for other options.      *
  *                                                                          *
  * Note that Sails uses an internal instance of Skipper by default; to      *
  * override it and specify more options, make sure to "npm install skipper" *
  * in your project first.  You can also specify a different body parser or  *
  * a custom function with req, res and next parameters (just like any other *
  * middleware function).                                                    *
  *                                                                          *
  ***************************************************************************/

    // bodyParser: require('skipper')({strict: true})

  },

  /***************************************************************************
  *                                                                          *
  * The number of seconds to cache flat files on disk being served by        *
  * Express static middleware (by default, these files are in `.tmp/public`) *
  *                                                                          *
  * The HTTP static cache is only active in a 'production' environment,      *
  * since that's the only time Express will cache flat-files.                *
  *                                                                          *
  ***************************************************************************/

  // cache: 31557600000
};
<|endoftext|>


<commit_before>var _ = require('underscore'),
    spawn = require('child_process').spawn,
    Game = require('../engine/game.js').Game;

function Runner() {
    function Runner(commands) {
        this.gameResult = "";
        this.commands = commands;
        this.n_survivors = 0;
        this.n_ready = 0;
    }
}

Runner.prototype.runGame = function (done) {
    var game = new Game();
    game.initialize(4);
    this.n_survivors = 4;

    var ais = [];
    for (var i = 0; i < 4; i++) {
        ais.push({
            process: spawn('python', ['engine/' + (i == 0 ? 'ai-tle' : 'ai') + '.py']),
            command: [],
            ready: false,
            expired: false,
            TO: null,
            id: i
        });
    }

    var self = this;
    _.each(ais, function (ai) {
        ai.process.stdout.on('data', function (data) {
            console.log("AI" + ai.id + ">>" + 'stdout: ' + data);
            if (ai.expired)
                return;
            ai.command = data.toString().trim().split(' ');
            ai.ready = true;
            self.n_ready += 1;
            clearTimeout(ai.TO);
            onReady.call(self, game, ais, done);
        });

        ai.process.stderr.on('data', function (data) {
            console.log("AI" + ai.id + ">>" + 'stderr: ' + data);
        });

        ai.process.on('close', function (code) {
            console.log("AI" + ai.id + ">>" + 'child process exited with code ' + code);
        });
    });

    doTurn.call(this, game, ais, done);
};

function onReady(game, ais, done) {
    if (this.n_ready == this.n_survivors) {
        console.log('Turn ended');
        var commands = _.map(ais, function (ai) {
            return ai.expired ? "" : ai.command;
        });

        game.processTurn(commands);
        this.gameResult += game.getStatus();

        doTurn.call(this, game, ais, done);
    }
}

function doTurn(game, ais, done) {
    this.n_ready = 0;
    if (game.isFinished()) {
        _.each(ais, function (ai) {
            if (!ai.expired)
                ai.process.stdin.write('-1\n');
        });

        this.gameResult += game.getRanking();
        done();
    } else {
        var self = this;
        _.each(ais, function (ai) {
            if (ai.expired)
                return;
            ai.ready = false;
            ai.process.stdin.write(game.getStatusForAI(ai.id));
            console.log("AI" + ai.id + ">>" + 'writing 1 to stdin, waiting for stdout');

            var TO = setTimeout(function () {
                console.log("AI" + ai.id + ">>" + 'killing due to TLE');
                ai.expired = true;

                self.n_survivors -= 1;
                ai.process.kill('SIGINT');
                onReady.call(self, game, ais, done);
            }, 1000);
            ai.TO = TO;
        });
    }
};

exports.Runner = Runner;
<commit_msg>Added some documentation to Runner<commit_after>var _ = require('underscore'),
    spawn = require('child_process').spawn,
    Game = require('../engine/game.js').Game;

/**
 *
 * @param commands
 * @constructor
 */
function Runner(commands) {
    this.gameResult = "";
    this.commands = commands;
    this.n_survivors = 0;
    this.n_ready = 0;
}

/**
 * Sets up game, and runs it till completion
 * @param done
 */
Runner.prototype.runGame = function (done) {
    var game = new Game();
    game.initialize(4);
    this.n_survivors = 4;

    var ais = [];
    for (var i = 0; i < 4; i++) {
        ais.push({
            process: spawn('python', ['engine/' + (i == 0 ? 'ai-tle' : 'ai') + '.py']),
            command: [],
            ready: false,
            expired: false,
            TO: null,
            id: i
        });
    }

    var self = this;
    _.each(ais, function (ai) {
        ai.process.stdout.on('data', function (data) {
            console.log("AI" + ai.id + ">>" + 'stdout: ' + data);
            if (ai.expired)
                return;
            ai.command = data.toString().trim().split(' ');
            ai.ready = true;
            self.n_ready += 1;
            clearTimeout(ai.TO);
            onReady.call(self, game, ais, done);
        });

        ai.process.stderr.on('data', function (data) {
            console.log("AI" + ai.id + ">>" + 'stderr: ' + data);
        });

        ai.process.on('close', function (code) {
            console.log("AI" + ai.id + ">>" + 'child process exited with code ' + code);
        });
    });

    doTurn.call(this, game, ais, done);
};

/**
 * Post-turn handling, and set up of new turn processing
 * @param game
 * @param ais
 * @param done
 */
function onReady(game, ais, done) {
    if (this.n_ready == this.n_survivors) {
        console.log('Turn ended');
        var commands = _.map(ais, function (ai) {
            return ai.expired ? "" : ai.command;
        });

        game.processTurn(commands);
        this.gameResult += game.getStatus();

        doTurn.call(this, game, ais, done);
    }
}

/**
 * Processes a turn
 * @param game
 * @param ais
 * @param done
 */
function doTurn(game, ais, done) {
    this.n_ready = 0;
    if (game.isFinished()) {
        _.each(ais, function (ai) {
            if (!ai.expired)
                ai.process.stdin.write('-1\n');
        });

        this.gameResult += game.getRanking();
        done();
    } else {
        var self = this;
        _.each(ais, function (ai) {
            if (ai.expired)
                return;
            ai.ready = false;
            ai.process.stdin.write(game.getStatusForAI(ai.id));
            console.log("AI" + ai.id + ">>" + 'writing 1 to stdin, waiting for stdout');

            var TO = setTimeout(function () {
                console.log("AI" + ai.id + ">>" + 'killing due to TLE');
                ai.expired = true;

                self.n_survivors -= 1;
                ai.process.kill('SIGINT');
                onReady.call(self, game, ais, done);
            }, 1000);
            ai.TO = TO;
        });
    }
};

exports.Runner = Runner;
<|endoftext|>


<commit_before>import { Element as PolymerElement } from '/node_modules/@polymer/polymer/polymer-element.js'
import ReduxMixin from '../../reduxStore.js'
import { uuidV1 } from '../../../libs/abcq/uuid.js'
import { addAnimation } from '../../actions/index.js'
import { getAnimationsSorted } from '../../selectors/index.js'
import '../animation-bee/index.js'

/*
 * Handle a list of animations
 */
class AnimationManager extends ReduxMixin(PolymerElement) {
  static get properties() {
    return {
      animations: {
        type: Array,
        statePath: getAnimationsSorted
      }
    }
  }

  handleSubmit(e) {
    // Prevent sending data to server
    e.preventDefault()

    const id = uuidV1()

    this.dispatch(addAnimation({
      id,
      keyframes: {},
      duration: this.duration,
      name: this.name
    }))
  }

  handleName(e) {
    this.name = e.target.value
  }

  handleDuration(e) {
    this.duration = e.target.value
  }

  static get template() {
    return `

      <form on-submit="handleSubmit">
        Name
        <input name="name" type="text" on-change="handleName" required></input>

        Duration
        <input name="duration" type="number" min="0" on-change="handleDuration" required></input>

        <button type="submit">Add animation</button>
      </form>

        <template is="dom-repeat" items="{{animations}}" as="animation">

            <animation-bee
              index$="[[index]]"
              name="[[animation.name]]"
              duration="[[animation.duration]]"
              keyframes="[[animation.keyframes]]""></animation-bee>

        </template>

    `
  }
}

customElements.define('animation-manager', AnimationManager)
<commit_msg>feat(animation-manager): Add multiple animations<commit_after>import { Element as PolymerElement } from '/node_modules/@polymer/polymer/polymer-element.js'
import ReduxMixin from '../../reduxStore.js'
import { uuidV1 } from '../../../libs/abcq/uuid.js'
import { addAnimation } from '../../actions/index.js'
import { getAnimationsSorted } from '../../selectors/index.js'
import '../animation-bee/index.js'

/*
 * Handle a list of animations
 */
class AnimationManager extends ReduxMixin(PolymerElement) {
  static get properties() {
    return {
      animations: {
        type: Array,
        statePath: 'animationManager'
      }
    }
  }

  handleSubmit(e) {
    // Prevent sending data to server
    e.preventDefault()

    // Get data out of the form
    const data = new FormData(e.target)

    const duration = parseInt(data.get('duration'), 10)
    const name = data.get('name')
    const amount = parseInt(data.get('amount'), 10)

    // Amount was not specified, so we just add one fixture
    if (isNaN(amount)) {
      this.dispatch(addAnimation({
        id: uuidV1(),
        keyframes: {},
        duration,
        name
      }))

    // Add multiple animations specified by amount
    } else {

      // Add multiple animations
      for (let i = 0; i < amount; i++) {
        const animationIndex = i + 1

        // @TODO: Allow default keyframes than only modvColor
        const keyframes = {
          0: { modvColor: animationIndex },
          1: { modvColor: animationIndex }
        }

        this.dispatch(addAnimation({
          id: uuidV1(),
          keyframes,
          duration,
          name: `${name}${animationIndex}`
        }))
      }
    }

  }

  static get template() {
    return `

      <form on-submit="handleSubmit">
        Name
        <input name="name" type="text" required></input>

        Duration
        <input name="duration" type="number" min="0" required></input>

        Amount
        <input name="amount" type="number" min="1" max="512"></input>

        <button type="submit">Add</button>
      </form>

        <template is="dom-repeat" items="{{animations}}" as="animation">

            <animation-bee
              index$="[[index]]"
              name="[[animation.name]]"
              duration="[[animation.duration]]"
              keyframes="[[animation.keyframes]]""></animation-bee>

        </template>

    `
  }
}

customElements.define('animation-manager', AnimationManager)
<|endoftext|>


<commit_before>var krbb = {
    root: 'https://raw.githubusercontent.com/fish-ball/krbb-plugins/master/upload-photo'
};

// Ȱ jQuery 滻
$('body').append('');

var jqLoaded = setInterval(function() {
    var version = jQuery.fn.jquery;
    console.log(version);
    if(version == '2.0.0') {
        clearInterval(jqLoaded);
        main();
    }
}, 50);

var main = function() {

    // -----------------------------------
    //
    // -----------------------------------

    $.watch = function(fnCase) {
        return $.Deferred(function(dfd) {
            var itv = setInterval(function() {
                var obj = fnCase();
                if(obj) {
                    clearInterval(itv);
                    dfd.resolve(obj);
                }
            }, 50);
        }).promise();
    };

    // jquery.formdata.js
    (function(c){"function"===typeof define&&define.amd?define(["jquery"],c):c("undefined"!=typeof jQuery?jQuery:window.Zepto)})(function(c){var l=window.TextEncoder?function(c){c=(new TextEncoder("utf8")).encode(c);for(var a="",d=0;d<c.length;++d)a+=String.fromCharCode(c[d]);return a}:function(c){return eval("'"+encodeURI(c).replace(/%/gm,"\\x")+"'")};c.ajaxFormData=function(f,a){"object"==typeof f&&(a=f,f=void 0);a=a||{};a.url=a.url||f||"";a.method=a.method||"post";var d=jQuery.ajaxSetup({},a);if("object"!==typeof d.data||!/^(GET|HEAD|OPTIONS|TRACE)$/.test(d.type))return c.ajax(d);var p=d.data,g="----JQBoundary"+btoa(Math.random().toString()).substr(0,12),m=[],e="",n=function(h,b){if(b instanceof File||b instanceof Blob)m.push(c.Deferred(function(c){var a=new FileReader;a.onload=function(a){a=a.target.result;var d=b.name&&l(b.name)||"blob";e+="--"+g+'\r\nContent-Disposition: form-data; name="'+h+'"; filename="'+d+'"\r\nContent-Type: '+(b.type||"application/octet-stream")+"\r\n\r\n"+a+"\r\n";c.resolve()};a.readAsBinaryString(b)}).promise());else if(/^data:image\/\w+;base64,/.test(b)){var a=b.search(";base64,"),d=b.substr(5,a-5),a=atob(b.substr(a+8));e+="--"+g+'\r\nContent-Disposition: form-data; name="'+h+'"; filename="blob"\r\nContent-Type: '+d+"\r\n\r\n"+a+"\r\n"}else"string"==typeof b||"number"==typeof b?e+="--"+g+'\r\nContent-Disposition: form-data; name="'+h+'"\r\n\r\n'+l(b.toString())+"\r\n":"boolean"===typeof b?b&&(e+="--"+g+'\r\nContent-Disposition: form-data; name="'+h+'"\r\n\r\non\r\n'):alert("jQuery.formdata: Post field type not supported,\nignore the field ["+h+"].")};c.each(p,function(a,b){b instanceof Array||b instanceof FileList?/\[]$/.test(a)?c.each(b,function(){n(a,this)}):alert("jQuery.formdata: an array field must have a `[]` suffix.\nignore the field ["+a+"]."):n(a,b)});return c.when.apply(c,m).then(function(){e+="--"+g+"--\r\n";var a;a:{a=e;for(var b=[],f,k=0;k<a.length;++k){f=a.charCodeAt(k);if(255<f){alert("Char code range out of 8 bit, parse error!");a=[];break a}b.push(a.charCodeAt(k))}a=new Uint8Array(b)}e=a.buffer;d.data=e;d.processData=!1;d.contentType="multipart/form-data; boundary="+g;return c.ajax(d)})}});

    // file to url
    var getFileURL = function(file) {
        var URL = window.URL || window.webkitURL;
        if(!URL) {
            alert('ֿ֧ͻͼƬ');
            return false;
        }
        return imgURL = URL.createObjectURL(file);
    };

    // -----------------------------------
    //              ִнű
    // -----------------------------------

    var galleries = [];
    var files = [];
    var $body = $('body');

    $.watch(function() {
        return $.ajaxFormData;
    }).then(function() {
        //menuonclick('BookList','2206768');
        OpenWinUpload('ϴͼƬ','ͼƬ',{menuid:2206768,cateid:0,type:2});
        return $.watch(function() {
            return $(document.frame1.document).find('#xc_sel').children().length;
        });
    }).then(function() {
        $(document.frame1.document).find('#xc_sel').children().each(function() {
            galleries.push([$(this).html(), $(this).val()]);
        });
        $('head').append('<link rel="stylesheet" type="text/css" href="'+krbb.root+'/style.css" />');
        $body.html(
            '
׽ͨͼƬϴǿ v0.1.0
' +
            '' +
            '    ѡ᣺' +
            '    <select id="gallery"></select>' +
            '    ѡͼƬ' +
            '    <input id="fileUpload" style="display: none;" type="file" name="images" multiple accept="image/*" />' +
            '' +
            '
' +
            '

' +
            '
ϴ
' +
            '
'
        );
        $.each(galleries, function() {
            $('#gallery').append('<option value="'+this[1]+'">'+this[0]+'</option>')
        });
        var $images = $('#images');
        var $upload = $('#fileUpload').change(function() {
            files = [];
            $.each($upload[0].files, function() {
                files.push(this);
                $images.append(
                    '
' +
                    '  ' +
                    '
'
                );
            });
        });
        var fileSizeText = function(sz) {
            var e = Math.pow(10, parseInt(Math.log10(sz))-2);
            sz = Math.round(sz/e)*e;
            if (sz < 1000) return sz + 'B';
            else if(sz < 1e6) return sz/1e3 + 'KB';
            else if(sz < 1e9) return sz/1e6 + 'MB';
            else return sz/1e9+ 'GB';
        };
        var doUpload = function() {
            if(files.length == 0) return;
            var file = files.shift();
            return $.getJSON('http://www.krbb.cn/NewWebSite/Manage/js/uploadify3.2/getcode.ashx?OperateType=1&time='+Math.random()).then(function(obj) {
                var code = obj.code;
                var gallery_id = $('#gallery').val();
                var filename = file.name;
                $images.find('li:first').append('

0%

');
                return $.ajaxFormData({
                    url: '/newwebsite/manage/js/uploadify3.2/Upload.ashx',
                    xhr: function() {
                        var xhr = $.ajaxSettings.xhr();
                        //ϴȵĻص
                        xhr.upload.addEventListener('progress', function(evt) {
                            if (evt.lengthComputable) {
                                var percentComplete = evt.loaded / evt.total;
                                $('#progress').html(
                                    '
' + parseInt(percentComplete*100)+'%
' +
                                    '
'+fileSizeText(evt.loaded)+'/'+fileSizeText(evt.total)+'
'
                                );
                            }
                        }, false);
                        return xhr;
                    },
                    data: {
                        Filename: filename,
                        Paras: gallery_id + '\t' + filename,
                        OperateType: 1,
                        CheckCode: code,
                        Filedata: file,
                        Upload: 'Submit Query'
                    }
                });
            }).then(function() {
                $images.find('li:first').fadeOut().detach();
            }).then(doUpload);
        };
        $('#submit').click(function() {
            doUpload();
        });

    });

};<commit_msg>加入 GitHub Pages<commit_after>var krbb = {
    root: 'https://fish-ball.github.io/krbb-plugins/upload-photo'
};

// Ȱ jQuery 滻
$('body').append('');

var jqLoaded = setInterval(function() {
    var version = jQuery.fn.jquery;
    console.log(version);
    if(version == '2.0.0') {
        clearInterval(jqLoaded);
        main();
    }
}, 50);

var main = function() {

    // -----------------------------------
    //
    // -----------------------------------

    $.watch = function(fnCase) {
        return $.Deferred(function(dfd) {
            var itv = setInterval(function() {
                var obj = fnCase();
                if(obj) {
                    clearInterval(itv);
                    dfd.resolve(obj);
                }
            }, 50);
        }).promise();
    };

    // jquery.formdata.js
    (function(c){"function"===typeof define&&define.amd?define(["jquery"],c):c("undefined"!=typeof jQuery?jQuery:window.Zepto)})(function(c){var l=window.TextEncoder?function(c){c=(new TextEncoder("utf8")).encode(c);for(var a="",d=0;d<c.length;++d)a+=String.fromCharCode(c[d]);return a}:function(c){return eval("'"+encodeURI(c).replace(/%/gm,"\\x")+"'")};c.ajaxFormData=function(f,a){"object"==typeof f&&(a=f,f=void 0);a=a||{};a.url=a.url||f||"";a.method=a.method||"post";var d=jQuery.ajaxSetup({},a);if("object"!==typeof d.data||!/^(GET|HEAD|OPTIONS|TRACE)$/.test(d.type))return c.ajax(d);var p=d.data,g="----JQBoundary"+btoa(Math.random().toString()).substr(0,12),m=[],e="",n=function(h,b){if(b instanceof File||b instanceof Blob)m.push(c.Deferred(function(c){var a=new FileReader;a.onload=function(a){a=a.target.result;var d=b.name&&l(b.name)||"blob";e+="--"+g+'\r\nContent-Disposition: form-data; name="'+h+'"; filename="'+d+'"\r\nContent-Type: '+(b.type||"application/octet-stream")+"\r\n\r\n"+a+"\r\n";c.resolve()};a.readAsBinaryString(b)}).promise());else if(/^data:image\/\w+;base64,/.test(b)){var a=b.search(";base64,"),d=b.substr(5,a-5),a=atob(b.substr(a+8));e+="--"+g+'\r\nContent-Disposition: form-data; name="'+h+'"; filename="blob"\r\nContent-Type: '+d+"\r\n\r\n"+a+"\r\n"}else"string"==typeof b||"number"==typeof b?e+="--"+g+'\r\nContent-Disposition: form-data; name="'+h+'"\r\n\r\n'+l(b.toString())+"\r\n":"boolean"===typeof b?b&&(e+="--"+g+'\r\nContent-Disposition: form-data; name="'+h+'"\r\n\r\non\r\n'):alert("jQuery.formdata: Post field type not supported,\nignore the field ["+h+"].")};c.each(p,function(a,b){b instanceof Array||b instanceof FileList?/\[]$/.test(a)?c.each(b,function(){n(a,this)}):alert("jQuery.formdata: an array field must have a `[]` suffix.\nignore the field ["+a+"]."):n(a,b)});return c.when.apply(c,m).then(function(){e+="--"+g+"--\r\n";var a;a:{a=e;for(var b=[],f,k=0;k<a.length;++k){f=a.charCodeAt(k);if(255<f){alert("Char code range out of 8 bit, parse error!");a=[];break a}b.push(a.charCodeAt(k))}a=new Uint8Array(b)}e=a.buffer;d.data=e;d.processData=!1;d.contentType="multipart/form-data; boundary="+g;return c.ajax(d)})}});

    // file to url
    var getFileURL = function(file) {
        var URL = window.URL || window.webkitURL;
        if(!URL) {
            alert('ֿ֧ͻͼƬ');
            return false;
        }
        return imgURL = URL.createObjectURL(file);
    };

    // -----------------------------------
    //              ִнű
    // -----------------------------------

    var galleries = [];
    var files = [];
    var $body = $('body');

    $.watch(function() {
        return $.ajaxFormData;
    }).then(function() {
        //menuonclick('BookList','2206768');
        OpenWinUpload('ϴͼƬ','ͼƬ',{menuid:2206768,cateid:0,type:2});
        return $.watch(function() {
            return $(document.frame1.document).find('#xc_sel').children().length;
        });
    }).then(function() {
        $(document.frame1.document).find('#xc_sel').children().each(function() {
            galleries.push([$(this).html(), $(this).val()]);
        });
        $('head').append('<link rel="stylesheet" type="text/css" href="'+krbb.root+'/style.css" />');
        $body.html(
            '
׽ͨͼƬϴǿ v0.1.0
' +
            '' +
            '    ѡ᣺' +
            '    <select id="gallery"></select>' +
            '    ѡͼƬ' +
            '    <input id="fileUpload" style="display: none;" type="file" name="images" multiple accept="image/*" />' +
            '' +
            '
' +
            '

' +
            '
ϴ
' +
            '
'
        );
        $.each(galleries, function() {
            $('#gallery').append('<option value="'+this[1]+'">'+this[0]+'</option>')
        });
        var $images = $('#images');
        var $upload = $('#fileUpload').change(function() {
            files = [];
            $.each($upload[0].files, function() {
                files.push(this);
                $images.append(
                    '
' +
                    '  ' +
                    '
'
                );
            });
        });
        var fileSizeText = function(sz) {
            var e = Math.pow(10, parseInt(Math.log10(sz))-2);
            sz = Math.round(sz/e)*e;
            if (sz < 1000) return sz + 'B';
            else if(sz < 1e6) return sz/1e3 + 'KB';
            else if(sz < 1e9) return sz/1e6 + 'MB';
            else return sz/1e9+ 'GB';
        };
        var doUpload = function() {
            if(files.length == 0) return;
            var file = files.shift();
            return $.getJSON('http://www.krbb.cn/NewWebSite/Manage/js/uploadify3.2/getcode.ashx?OperateType=1&time='+Math.random()).then(function(obj) {
                var code = obj.code;
                var gallery_id = $('#gallery').val();
                var filename = file.name;
                $images.find('li:first').append('

0%

');
                return $.ajaxFormData({
                    url: '/newwebsite/manage/js/uploadify3.2/Upload.ashx',
                    xhr: function() {
                        var xhr = $.ajaxSettings.xhr();
                        //ϴȵĻص
                        xhr.upload.addEventListener('progress', function(evt) {
                            if (evt.lengthComputable) {
                                var percentComplete = evt.loaded / evt.total;
                                $('#progress').html(
                                    '
' + parseInt(percentComplete*100)+'%
' +
                                    '
'+fileSizeText(evt.loaded)+'/'+fileSizeText(evt.total)+'
'
                                );
                            }
                        }, false);
                        return xhr;
                    },
                    data: {
                        Filename: filename,
                        Paras: gallery_id + '\t' + filename,
                        OperateType: 1,
                        CheckCode: code,
                        Filedata: file,
                        Upload: 'Submit Query'
                    }
                });
            }).then(function() {
                $images.find('li:first').fadeOut().detach();
            }).then(doUpload);
        };
        $('#submit').click(function() {
            doUpload();
        });

    });

};<|endoftext|>


<commit_before>'use strict';

KylinApp.controller('CubeSchemaCtrl', function ($scope, QueryService, UserService, ProjectService, AuthenticationService) {
    //~ Define metadata & class
    $scope.capacities = ['SMALL', 'MEDIUM', 'LARGE'];
    $scope.cubePartitionTypes = ['APPEND', 'UPDATE_INSERT'];
    $scope.projects = [];
    $scope.newDimension = null;
    $scope.newMeasure = null;

    $scope.wizardSteps = [
        {title: 'Cube Info', src: 'partials/cubeDesigner/info.html', isComplete: false},
        {title: 'Dimensions', src: 'partials/cubeDesigner/dimensions.html', isComplete: false},
        {title: 'Measures', src: 'partials/cubeDesigner/measures.html', isComplete: false},
        {title: 'Filter', src: 'partials/cubeDesigner/filter.html', isComplete: false},
        {title: 'Refresh Setting', src: 'partials/cubeDesigner/incremental.html', isComplete: false}
    ];
    if (UserService.hasRole("ROLE_ADMIN")) {
            $scope.wizardSteps.push({title: 'Advanced Setting', src: 'partials/cubeDesigner/advanced_settings.html', isComplete: false});
    }
    $scope.wizardSteps.push({title: 'Overview', src: 'partials/cubeDesigner/overview.html', isComplete: false});

    $scope.curStep = $scope.wizardSteps[0];

    var Dimension = {
        createNew: function () {
            var dimension = {
                "id": "",
                "name": "",
                "table": "",
                "column": "",
                "datatype": "",
                "derived": [],
                "join": {
                    "type": "",
                    "primary_key": [],
                    "foreign_key": []
                },
                "hierarchy": [],
                "status": {
                    "joinCount": 1,
                    "hierarchyCount": 1,
                    "useHierarchy": false,
                    "useJoin": false
                }
            };

            return dimension;
        }
    };

    var Measure = {
        createNew: function () {
            var measure = {
                "id": "",
                "name": "",
                "function": {
                    "expression": "",
                    "returntype": "",
                    "parameter": {
                        "type": "",
                        "value": ""
                    }
                }
            };

            return measure;
        }
    };

    // ~ init
    if (!$scope.state) {
        $scope.state = {mode: "view"};
    }

    $scope.$watch('cube.detail', function (newValue, oldValue) {
        if (newValue) {
            $scope.cubeMetaFrame = newValue;
        }
    });

    $scope.$watch('cubeMetaFrame', function (newValue, oldValue) {
        if (newValue && !newValue.project) {
            initProject();
            generateCubeStatus($scope.cubeMetaFrame);
        }
    });

    // ~ public methods
    $scope.filterProj = function(project){
        return $scope.userService.hasRole('ROLE_ADMIN') || $scope.hasPermission(project,$scope.permissions.ADMINISTRATION.mask);
    }

    $scope.addNewDimension = function (dimension) {
        $scope.newDimension = (!!dimension)? dimension: Dimension.createNew();
        if(!$scope.newDimension.join){
            $scope.newDimension.join = { "type": "","primary_key": [],"foreign_key": []}
        }
        if($scope.newDimension.status&&$scope.newDimension.status.useJoin||$scope.newDimension.join.foreign_key.length!=0){
            $scope.newDimension.status.useJoin = true;
        }
    }

    $scope.clearNewDimension = function () {
        $scope.newDimension = null;
    }

    $scope.saveNewDimension = function () {
        if($scope.editFlag.dimensionEdited=="init"){
            $scope.editFlag.dimensionEdited = false;
        }else{
            $scope.editFlag.dimensionEdited=!$scope.editFlag.dimensionEdited;
        }

        if ($scope.cubeMetaFrame.dimensions.indexOf($scope.newDimension) === -1) {
            $scope.cubeMetaFrame.dimensions.push($scope.newDimension);
        }
        $scope.newDimension = null;
    }

    $scope.addNewMeasure = function (measure) {
        $scope.newMeasure = (!!measure)? measure:Measure.createNew();
    }

    $scope.clearNewMeasure = function () {
        $scope.newMeasure = null;
    }

    $scope.saveNewMeasure = function () {
        if ($scope.cubeMetaFrame.measures.indexOf($scope.newMeasure) === -1) {
            $scope.cubeMetaFrame.measures.push($scope.newMeasure);
        }
        $scope.newMeasure = null;
    }

    $scope.addNewRowkeyColumn = function () {
        $scope.cubeMetaFrame.rowkey.rowkey_columns.push({
            "column": "",
            "length": 0,
            "dictionary": "true",
            "mandatory": false
        });
    }

    $scope.addNewAggregationGroup = function () {
        $scope.cubeMetaFrame.rowkey.aggregation_groups.push([]);
    }

    $scope.refreshAggregationGroup = function (list, index, aggregation_groups) {
        if (aggregation_groups) {
            list[index] = aggregation_groups;
        }
    }

    $scope.addNewHierarchy = function (dimension) {
        if (!dimension.hierarchy) {
            dimension.hierarchy = [];
        }
        dimension.hierarchy.push({
            "level": (dimension.hierarchy.length + 1),
            "column": undefined
        });
    }

    $scope.addNewDerived = function (dimension) {
        if(!dimension.derived){
            dimension.derived = [];
        }
        dimension.derived.push("");
    }

    $scope.toggleJoin = function (dimension,$event) {
        if (dimension.join&&dimension.join.type!='') {
            if(!confirm('Delete the join relation?')){
                $event.preventDefault();
                return;
            }else{
                delete dimension.join;
            }
        }
        else {
            dimension.join = dimension.join==undefined?{}:dimension.join;
            dimension.join.type = 'left';
        }
    }

    $scope.toggleHierarchy = function (dimension) {
        if (dimension.status.useHierarchy) {
            dimension.hierarchy = [];
        }
    }

    $scope.removeElement = function (arr, element) {
        var index = arr.indexOf(element);
        if (index > -1) {
            arr.splice(index, 1);
        }
    }

    $scope.removeDimension = function (arr, element) {
        var index = arr.indexOf(element);
        if (index > -1) {
            arr.splice(index, 1);
            if($scope.editFlag.dimensionEdited=="init"){
                $scope.editFlag.dimensionEdited = false;
            }else{
                $scope.editFlag.dimensionEdited=!$scope.editFlag.dimensionEdited;
            }
        }
    }

    $scope.open = function ($event) {
        $event.preventDefault();
        $event.stopPropagation();

        $scope.opened = true;
    };

    $scope.preView = function () {
        var stepIndex = $scope.wizardSteps.indexOf($scope.curStep);
        if (stepIndex >= 1) {
            $scope.curStep.isComplete = false;
            $scope.curStep = $scope.wizardSteps[stepIndex - 1];
        }
    }

    $scope.nextView = function () {
        var stepIndex = $scope.wizardSteps.indexOf($scope.curStep);
        if (stepIndex < ($scope.wizardSteps.length - 1)) {
            $scope.curStep.isComplete = true;
            $scope.curStep = $scope.wizardSteps[stepIndex + 1];

            AuthenticationService.ping(function (data) {
                UserService.setCurUser(data);
            });
        }
    }

    $scope.getJoinToolTip = function (dimension) {
        var tooltip = "";

        if (dimension.join) {
            angular.forEach(dimension.join.primary_key, function (pk, index) {
                tooltip += (pk + " = " + dimension.join.foreign_key[index] + "
");
            });
        }

        return tooltip;
    }

    // ~ private methods
    function initProject() {
        ProjectService.list({}, function (projects) {
            $scope.projects = projects;

            var cubeName = (!!$scope.routeParams.cubeName)? $scope.routeParams.cubeName:$scope.state.cubeName;
            if (cubeName) {
                var projName = null;
                angular.forEach($scope.projects, function (project, index) {
                    angular.forEach(project.cubes, function (cube, index) {
                        if (!projName && cube === cubeName.toUpperCase()) {
                            projName = project.name;
                        }
                    });
                });

                $scope.cubeMetaFrame.project = projName;
            }

            angular.forEach($scope.projects, function (project, index) {
                $scope.listAccess(project, 'ProjectInstance');
            });
        });
    }

    function generateCubeStatus(cubeMeta) {
        angular.forEach(cubeMeta.dimensions, function (dimension, index) {
            dimension.status = {};
            if (dimension.hierarchy) {
                dimension.status.useHierarchy = true;
                dimension.status.joinCount = (!!dimension.join.primary_key) ? dimension.join.primary_key.length : 0;
                dimension.status.hierarchyCount = (!!dimension.hierarchy) ? dimension.hierarchy.length : 0;
            }
        });
    }
});
<commit_msg>enhance cubeEdit init func<commit_after>'use strict';

KylinApp.controller('CubeSchemaCtrl', function ($scope, QueryService, UserService, ProjectService, AuthenticationService) {
    //~ Define metadata & class
    $scope.capacities = ['SMALL', 'MEDIUM', 'LARGE'];
    $scope.cubePartitionTypes = ['APPEND', 'UPDATE_INSERT'];
    $scope.projects = [];
    $scope.newDimension = null;
    $scope.newMeasure = null;

    $scope.wizardSteps = [
        {title: 'Cube Info', src: 'partials/cubeDesigner/info.html', isComplete: false},
        {title: 'Dimensions', src: 'partials/cubeDesigner/dimensions.html', isComplete: false},
        {title: 'Measures', src: 'partials/cubeDesigner/measures.html', isComplete: false},
        {title: 'Filter', src: 'partials/cubeDesigner/filter.html', isComplete: false},
        {title: 'Refresh Setting', src: 'partials/cubeDesigner/incremental.html', isComplete: false}
    ];
    if (UserService.hasRole("ROLE_ADMIN")) {
            $scope.wizardSteps.push({title: 'Advanced Setting', src: 'partials/cubeDesigner/advanced_settings.html', isComplete: false});
    }
    $scope.wizardSteps.push({title: 'Overview', src: 'partials/cubeDesigner/overview.html', isComplete: false});

    $scope.curStep = $scope.wizardSteps[0];

    var Dimension = {
        createNew: function () {
            var dimension = {
                "id": "",
                "name": "",
                "table": "",
                "column": "",
                "datatype": "",
                "derived": [],
                "join": {
                    "type": "",
                    "primary_key": [],
                    "foreign_key": []
                },
                "hierarchy": [],
                "status": {
                    "joinCount": 1,
                    "hierarchyCount": 1,
                    "useHierarchy": false,
                    "useJoin": false
                }
            };

            return dimension;
        }
    };

    var Measure = {
        createNew: function () {
            var measure = {
                "id": "",
                "name": "",
                "function": {
                    "expression": "",
                    "returntype": "",
                    "parameter": {
                        "type": "",
                        "value": ""
                    }
                }
            };

            return measure;
        }
    };

    // ~ init
    if (!$scope.state) {
        $scope.state = {mode: "view"};
    }

    $scope.$watch('cube.detail', function (newValue, oldValue) {
        if (newValue) {
            $scope.cubeMetaFrame = newValue;
        }
    });

    $scope.$watch('cubeMetaFrame', function (newValue, oldValue) {
        if ($scope.cubeMode=="editExistCube"&&newValue && !newValue.project) {
            initProject();
            generateCubeStatus($scope.cubeMetaFrame);
        }
    });

    // ~ public methods
    $scope.filterProj = function(project){
        return $scope.userService.hasRole('ROLE_ADMIN') || $scope.hasPermission(project,$scope.permissions.ADMINISTRATION.mask);
    }

    $scope.addNewDimension = function (dimension) {
        $scope.newDimension = (!!dimension)? dimension: Dimension.createNew();
        if(!$scope.newDimension.join){
            $scope.newDimension.join = { "type": "","primary_key": [],"foreign_key": []}
        }
        if($scope.newDimension.status&&$scope.newDimension.status.useJoin||$scope.newDimension.join.foreign_key.length!=0){
            $scope.newDimension.status.useJoin = true;
        }
    }

    $scope.clearNewDimension = function () {
        $scope.newDimension = null;
    }

    $scope.saveNewDimension = function () {
        if($scope.editFlag.dimensionEdited=="init"){
            $scope.editFlag.dimensionEdited = false;
        }else{
            $scope.editFlag.dimensionEdited=!$scope.editFlag.dimensionEdited;
        }

        if ($scope.cubeMetaFrame.dimensions.indexOf($scope.newDimension) === -1) {
            $scope.cubeMetaFrame.dimensions.push($scope.newDimension);
        }
        $scope.newDimension = null;
    }

    $scope.addNewMeasure = function (measure) {
        $scope.newMeasure = (!!measure)? measure:Measure.createNew();
    }

    $scope.clearNewMeasure = function () {
        $scope.newMeasure = null;
    }

    $scope.saveNewMeasure = function () {
        if ($scope.cubeMetaFrame.measures.indexOf($scope.newMeasure) === -1) {
            $scope.cubeMetaFrame.measures.push($scope.newMeasure);
        }
        $scope.newMeasure = null;
    }

    $scope.addNewRowkeyColumn = function () {
        $scope.cubeMetaFrame.rowkey.rowkey_columns.push({
            "column": "",
            "length": 0,
            "dictionary": "true",
            "mandatory": false
        });
    }

    $scope.addNewAggregationGroup = function () {
        $scope.cubeMetaFrame.rowkey.aggregation_groups.push([]);
    }

    $scope.refreshAggregationGroup = function (list, index, aggregation_groups) {
        if (aggregation_groups) {
            list[index] = aggregation_groups;
        }
    }

    $scope.addNewHierarchy = function (dimension) {
        if (!dimension.hierarchy) {
            dimension.hierarchy = [];
        }
        dimension.hierarchy.push({
            "level": (dimension.hierarchy.length + 1),
            "column": undefined
        });
    }

    $scope.addNewDerived = function (dimension) {
        if(!dimension.derived){
            dimension.derived = [];
        }
        dimension.derived.push("");
    }

    $scope.toggleJoin = function (dimension,$event) {
        if (dimension.join&&dimension.join.type!='') {
            if(!confirm('Delete the join relation?')){
                $event.preventDefault();
                return;
            }else{
                delete dimension.join;
            }
        }
        else {
            dimension.join = dimension.join==undefined?{}:dimension.join;
            dimension.join.type = 'left';
        }
    }

    $scope.toggleHierarchy = function (dimension) {
        if (dimension.status.useHierarchy) {
            dimension.hierarchy = [];
        }
    }

    $scope.removeElement = function (arr, element) {
        var index = arr.indexOf(element);
        if (index > -1) {
            arr.splice(index, 1);
        }
    }

    $scope.removeDimension = function (arr, element) {
        var index = arr.indexOf(element);
        if (index > -1) {
            arr.splice(index, 1);
            if($scope.editFlag.dimensionEdited=="init"){
                $scope.editFlag.dimensionEdited = false;
            }else{
                $scope.editFlag.dimensionEdited=!$scope.editFlag.dimensionEdited;
            }
        }
    }

    $scope.open = function ($event) {
        $event.preventDefault();
        $event.stopPropagation();

        $scope.opened = true;
    };

    $scope.preView = function () {
        var stepIndex = $scope.wizardSteps.indexOf($scope.curStep);
        if (stepIndex >= 1) {
            $scope.curStep.isComplete = false;
            $scope.curStep = $scope.wizardSteps[stepIndex - 1];
        }
    }

    $scope.nextView = function () {
        var stepIndex = $scope.wizardSteps.indexOf($scope.curStep);
        if (stepIndex < ($scope.wizardSteps.length - 1)) {
            $scope.curStep.isComplete = true;
            $scope.curStep = $scope.wizardSteps[stepIndex + 1];

            AuthenticationService.ping(function (data) {
                UserService.setCurUser(data);
            });
        }
    }

    $scope.getJoinToolTip = function (dimension) {
        var tooltip = "";

        if (dimension.join) {
            angular.forEach(dimension.join.primary_key, function (pk, index) {
                tooltip += (pk + " = " + dimension.join.foreign_key[index] + "
");
            });
        }

        return tooltip;
    }

    // ~ private methods
    function initProject() {
        ProjectService.list({}, function (projects) {
            $scope.projects = projects;

            var cubeName = (!!$scope.routeParams.cubeName)? $scope.routeParams.cubeName:$scope.state.cubeName;
            if (cubeName) {
                var projName = null;
                angular.forEach($scope.projects, function (project, index) {
                    angular.forEach(project.cubes, function (cube, index) {
                        if (!projName && cube === cubeName.toUpperCase()) {
                            projName = project.name;
                        }
                    });
                });

                $scope.cubeMetaFrame.project = projName;
            }

            angular.forEach($scope.projects, function (project, index) {
                $scope.listAccess(project, 'ProjectInstance');
            });
        });
    }

    function generateCubeStatus(cubeMeta) {
        angular.forEach(cubeMeta.dimensions, function (dimension, index) {
            dimension.status = {};
            if (dimension.hierarchy) {
                dimension.status.useHierarchy = true;
                dimension.status.joinCount = (!!dimension.join.primary_key) ? dimension.join.primary_key.length : 0;
                dimension.status.hierarchyCount = (!!dimension.hierarchy) ? dimension.hierarchy.length : 0;
            }
        });
    }
});
<|endoftext|>


<commit_before>import { expect } from 'chai';
import { childOf } from '../../../../src/notebook/kernel/messaging';

const Rx = require('rxjs/Rx');

describe('childOf', () => {
  it('filters messages that have the same parent', () => {
    return Rx.Observable.from([
      {parent_header: {msg_id: '100'}},
      {parent_header: {msg_id: '100'}},
      {parent_header: {msg_id: '200'}},
      {parent_header: {msg_id: '300'}},
      {parent_header: {msg_id: '100'}},
    ])
    .childOf({header: {msg_id: '100'}})
    .count()
    .toPromise()
    .then(val => {
      expect(val).to.equal(3);
    });
  });
});

describe('ofMessageType', () => {
  it('filters messages of type requested', () => {
    const requested = Rx.Observable.from([
      {header: {msg_type: 'a'}},
      {header: {msg_type: 'd'}},
      {header: {msg_type: 'b'}},
      {header: {msg_type: 'a'}},
      {header: {msg_type: 'd'}},
    ])
    .ofMessageType(['a', 'd'])
    .do(val => {
      expect(val.header.msg_type === 'a' || val.header.msg_type === 'd')
    })
    .pluck('header', 'msg_type')
    .count()
    .toPromise()
    .then(val => {
      expect(val).to.equal(4);
    });
  });
});
<commit_msg>Fix path in messaging-spec after rename<commit_after>import { expect } from 'chai';
import { childOf } from '../../../src/notebook/kernel/messaging';

const Rx = require('rxjs/Rx');

describe('childOf', () => {
  it('filters messages that have the same parent', () => {
    return Rx.Observable.from([
      {parent_header: {msg_id: '100'}},
      {parent_header: {msg_id: '100'}},
      {parent_header: {msg_id: '200'}},
      {parent_header: {msg_id: '300'}},
      {parent_header: {msg_id: '100'}},
    ])
    .childOf({header: {msg_id: '100'}})
    .count()
    .toPromise()
    .then(val => {
      expect(val).to.equal(3);
    });
  });
});

describe('ofMessageType', () => {
  it('filters messages of type requested', () => {
    const requested = Rx.Observable.from([
      {header: {msg_type: 'a'}},
      {header: {msg_type: 'd'}},
      {header: {msg_type: 'b'}},
      {header: {msg_type: 'a'}},
      {header: {msg_type: 'd'}},
    ])
    .ofMessageType(['a', 'd'])
    .do(val => {
      expect(val.header.msg_type === 'a' || val.header.msg_type === 'd')
    })
    .pluck('header', 'msg_type')
    .count()
    .toPromise()
    .then(val => {
      expect(val).to.equal(4);
    });
  });
});
<|endoftext|>