<commit_before>import React from 'react';
import RubikSquare from './../components/RubikSquare';
import ReactCountdownClock from 'react-countdown-clock';
import axios from 'axios';

export default class RubikSquaresContainer extends React.Component {

	constructor(props) {
		super(props);
		this.RUBIK_CONTAINER_SIZE = 16;
		this.ROW_LENGTH = Math.sqrt(this.RUBIK_CONTAINER_SIZE);
		this.startTime = Date.now(),this.endTime = 0;
		this.state = {
			squaresColors: this.randomSquareColors(),
			moves:0,
			isGameOver:false,
			timeUp:false,
			loginSuccessful: false,
			userName:''
		}
	}

	swap(src,trgt,array) {
		let temp = array[src];
		array[src] = array[trgt];
		array[trgt] = temp;
		return array;
	}

	isRowWiseOver(colorsArray){
			let color;
			for(let i=0;i < colorsArray.length; i++){
				if(i%this.ROW_LENGTH == 0){
					color = colorsArray[i];
				}
				else{
					if(color === colorsArray[i]) {
						continue;
					}
					else {
						return false;
					}
				}
			}
			return true;
	}

	isColumnWiseOver(colorsArray) {
		let color;
		for(let i= this.ROW_LENGTH;i < colorsArray.length; i++){
			  if(colorsArray[i] === colorsArray[i%this.ROW_LENGTH]) {
					continue;
				}
				else {
					return false;
				}
		}
		return true;
	}

	isGameOver(colorsArray){
		return this.isRowWiseOver(colorsArray) || this.isColumnWiseOver(colorsArray);
	}

	onSwipe(sourceIndex,targetIndex) {
		let swappedSquaresColors = this.swap(sourceIndex,targetIndex,this.state.squaresColors);

		this.setState({
			squaresColors:swappedSquaresColors,
			moves: ++this.state.moves,
			isGameOver: this.isGameOver(swappedSquaresColors)
		});
	}

	formRubikSquaresContainer(squareColors) {
		let squareBlocks = squareColors.map(function(color,i){
				return (<RubikSquare
					key={i}
					index={i}
					color={color}
					onSwipe={this.onSwipe.bind(this)}
				/>);
		}.bind(this));
		return squareBlocks;
	}

	randomColorPicker(colorsArray, colorsCountArray) {
		let randomColorCode= Math.floor(Math.random() * (colorsArray.length));
		let color = colorsArray[randomColorCode];
		colorsCountArray[randomColorCode]++;
		if(colorsCountArray[randomColorCode] == this.ROW_LENGTH){
			colorsArray.splice(randomColorCode,1);
			colorsCountArray.splice(randomColorCode,1);
		}
		return color;
	}

	randomSquareColors() {
		let squares = [];
		let colorsArray = ['#055994','#034003','#8c6804','#a20303'];
		let colorsCountArray = [0,0,0,0];
		for(let i=0;i<this.RUBIK_CONTAINER_SIZE;i++) {
			let color = this.randomColorPicker(colorsArray,colorsCountArray)
			squares.push(color);
		}
		return squares;
	}

	onTimeUp() {

		this.setState({timeUp:true})
	}

	postData() {
		this.endTime = Date.now();
		let totalTime = Math.floor((this.endTime - this.startTime)/1000);
		axios.post('http://sample-env.d8kzn4afvm.us-east-1.elasticbeanstalk.com/api/Rubiks', {
    			UserName: this.state.userName,
    			moves: this.state.moves,
    			timing: totalTime
  			})
  			.then(function (response) {
   				 console.log("successfully posted");
  			})

	}

	componentDidMount(){

	}

    startGame(){
        return (

					<ReactCountdownClock seconds={30}
										 color="#000"
										 size={100}
										 paused={this.state.isGameOver}
										 onComplete={this.onTimeUp.bind(this)}
					/>

                    {this.formRubikSquaresContainer(this.state.squaresColors)}

					moves: {this.state.moves}

                {this.state.isGameOver || this.state.timeUp ? this.postData() : false}
                {this.state.isGameOver ?
good job!!!
: false}
                {this.state.timeUp ?
time up!!!
: false}

        );
	}

    onStart(e) {
    	console.log('on start');
    	e.preventDefault();
    	this.setState({ loginSuccessful:true,userName: this.refs.userName.value});
    }

    userLogin() {
        /*return (

 Welcome to 2D Rubik's cube

 Swipe either horizontally or vertically and try to bring all colors to one place

 Please enter your user name and click button to start game

				<form onSubmit={this.onStart.bind(this)}>
					<input type="text" ref="userName" />
					<input type="submit" value="Lets Start the Game"/>
				</form>

        );*/
        return (

 Welcome to 2D Rubik's cube

 Swipe either horizontally or vertically and try to bring all colors to one place

 Please enter your user name and click button to start game

                    <form className="formContainer" onSubmit={this.onStart.bind(this)}>
                        <input className="formContainer-input" type="text" ref="userName" placeholder="Your name"/>
                        <input className='startGame' type="submit" value="Start the Game"/>
                    </form>

        );
    }

	render() {
		console.log(this.state);
		return this.state.loginSuccessful === true ? this.startGame() : this.userLogin()
	}
}
<commit_msg>updated rubik square container<commit_after>import React from 'react';
import RubikSquare from './../components/RubikSquare';
import ReactCountdownClock from 'react-countdown-clock';
import axios from 'axios';

export default class RubikSquaresContainer extends React.Component {

    constructor(props) {
        super(props);
        this.RUBIK_CONTAINER_SIZE = 16;
        this.ROW_LENGTH = Math.sqrt(this.RUBIK_CONTAINER_SIZE);
        this.startTime = 0, this.endTime = 0;
		this.winnerData = [],
        this.state = {
            squaresColors: this.randomSquareColors(),
            moves: 0,
            isGameOver: false,
            timeUp: false,
            loginSuccessful: false,
            userName: '',
		 results: '',
		 dataPosted:false,
		 viewButton: false,
		 buttonText:'View Results'
        }
	this.gameResults =this.gameResults.bind(this);
	this.viewFinalResults = this.viewFinalResults.bind(this);
	this.postData = this.postData.bind(this);
	this.postSuccess = this.postSuccess.bind(this);
	this.showViewResultsButton = this.showViewResultsButton.bind(this);
    }

    swap(src, trgt, array) {
        let temp = array[src];
        array[src] = array[trgt];
        array[trgt] = temp;
        return array;
    }

    isRowWiseOver(colorsArray) {
        let color;
        for (let i = 0; i < colorsArray.length; i++) {
            if (i % this.ROW_LENGTH == 0) {
                color = colorsArray[i];
            }
            else {
                if (color === colorsArray[i]) {
                    continue;
                }
                else {
                    return false;
                }
            }
        }
        return true;
    }

    isColumnWiseOver(colorsArray) {
        let color;
        for (let i = this.ROW_LENGTH; i < colorsArray.length; i++) {
            if (colorsArray[i] === colorsArray[i % this.ROW_LENGTH]) {
                continue;
            }
            else {
                return false;
            }
        }
        return true;
    }

    isGameOver(colorsArray) {
        return this.isRowWiseOver(colorsArray) || this.isColumnWiseOver(colorsArray);
    }

    onSwipe(sourceIndex, targetIndex) {
        let swappedSquaresColors = this.swap(sourceIndex, targetIndex, this.state.squaresColors);

        this.setState({
            squaresColors: swappedSquaresColors,
            moves: ++this.state.moves,
            isGameOver: this.isGameOver(swappedSquaresColors)
        });
    }

    formRubikSquaresContainer(squareColors) {
        let squareBlocks = squareColors.map(function (color, i) {
            return (<RubikSquare
                key={i}
                index={i}
                color={color}
                onSwipe={this.onSwipe.bind(this)}
            />);
        }.bind(this));
        return squareBlocks;
    }

    randomColorPicker(colorsArray, colorsCountArray) {
        let randomColorCode = Math.floor(Math.random() * (colorsArray.length));
        let color = colorsArray[randomColorCode];
        colorsCountArray[randomColorCode]++;
        if (colorsCountArray[randomColorCode] == this.ROW_LENGTH) {
            colorsArray.splice(randomColorCode, 1);
            colorsCountArray.splice(randomColorCode, 1);
        }
        return color;
    }

    randomSquareColors() {
        let squares = [];
        let colorsArray = ['red', 'green', 'yellow', 'blue'];
        let colorsCountArray = [0, 0, 0, 0];
        for (let i = 0; i < this.RUBIK_CONTAINER_SIZE; i++) {
            let color = this.randomColorPicker(colorsArray, colorsCountArray)
            squares.push(color);
        }
        return squares;
    }

    onTimeUp() {

        this.setState({timeUp: true})

	}

	postSuccess(){

      console.log("successfully posted");
		this.setState({
		dataPosted: true
	})
	}

	showViewResultsButton(){
		console.log("show view button ");

	}
    postData() {
        this.endTime = Date.now();
        let totalTime = Math.floor((this.endTime - this.state.startTime) / 1000);
		console.log("Start Time"+this.state.startTime);
		console.log("endTime"+this.endTime);
		console.log("totalTime"+totalTime);

        axios.post('http://sample-env.d8kzn4afvm.us-east-1.elasticbeanstalk.com/api/Rubiks', {
            UserName: this.state.userName,
            moves: this.state.moves,
            timing: totalTime
        })
            .then(this.postSuccess);

    }

    componentDidMount() {
	console.log('chaitanya');

    }

		gameResults(){
		console.log('onclick method');
				document.getElementById('viewDetails').disabled = true;
		setTimeout(
		    function(){
			console.log("Inside callback");
			clearInterval(timer);
			axios.get("http://sample-env.d8kzn4afvm.us-east-1.elasticbeanstalk.com/api/Rubiks?filter=%7B%22order%22%3A%5B%22timing%20ASC%22%2C%20%22moves%20ASC%22%5D%2C%20%22limit%22%3A%2010%7D",).then(response => {
						this.setState({
							results: response.data
						});

				});

		}.bind(this),30000);
		let secondsElapsed = 30;
		let timer = setInterval(() => {
			this.setState({buttonText: `Wait for ${secondsElapsed--} secs`});
		}, 1000);

	}

		viewFinalResults(){

		console.log("Inside the view results function");
		let truncatedResults = this.state.results ? this.state.results.slice(3) : [];

		return( truncatedResults.map((user, index) => {
		console.log(user);

				return (

 {index+4}

 {user.UserName}

 {user.moves}

 {user.timing}

				)
			  })
			  );

		}
		closeData(){var modal = document.getElementById("myModal");
			modal.style.display="none";

			}
	shoWFinalResults(){

			return (

		{this.gameResults}

		{this.state.results.length >1?

{this.state.results[1].UserName}

2

: null}
		{this.state.results.length >0?

{this.state.results[0].UserName}

1

: null}
			{this.state.results.length >2?

{this.state.results[2].UserName}

3

: null}

Positions Board

Rank

Name

Moves

Timing

				{this.viewFinalResults()}

			  );
	}

showButton(){

	return this.state.isGameOver || this.state.timeUp ?
<button onClick = {this.gameResults} className="resultsButton" id="viewDetails">{this.state.buttonText}</button>
: null;
}

    startGame() {
		console.log("this.state.startTime");
		console.log(this.state.startTime);
        return (

                    <ReactCountdownClock seconds={30}
                                         color="#000"
                                         size={100}
                                         paused={this.state.isGameOver}
                                         onComplete={this.onTimeUp.bind(this)}
                    />

                    {this.formRubikSquaresContainer(this.state.squaresColors)}

                    moves: {this.state.moves}

                {(this.state.isGameOver || this.state.timeUp ) && !this.state.dataPosted ? this.postData() : false}

                {this.state.isGameOver ?
good job!!!
 : false}
                {this.state.timeUp ?
time up!!!
 : false}
				{this.showButton()}

        );
    }

    onStart(e) {
        console.log('on start');
        console.log("startTime"+ this.startTime);
		e.preventDefault();
        this.setState({loginSuccessful: true, userName: this.refs.userName.value, startTime: Date.now()} );
    }

    userLogin() {
        return (

 Welcome to 2D Rubik's cube

 Swipe either horizontally or vertically and try to bring all colors to one place

 Please enter your user name and click button to start game

                    <form className="formContainer" onSubmit={this.onStart.bind(this)}>
                        <input className="formContainer-input" type="text" ref="userName" placeholder="Your name"/>
                        <input className='startGame' type="submit" value="Start the Game"/>
                    </form>

        );
    }

    render() {
	console.log('render');
        console.log(this.state.results);

        return (

		this.state.results ?  this.shoWFinalResults() : this.state.loginSuccessful === true ?this.startGame(): this.userLogin()
		);
    }
}<|endoftext|>


<commit_before>/*
 * Feedback arrows UX extension.
 * Shows two independent webgl models that should immitate spacenav movement.
 * Object should fade in and fade out on spacenav use.
 */
/*
 * Feedback arrows UX extension.
 * Shows two independent webgl models that should immitate spacenav movement.
 * Object should fade in and fade out on spacenav use.
 */

console.log('Loading Feedback arrows Extension: creating WS socket');

//Let's connect directly to websocket<->ROS bridge
var spacenavROS = new ROSLIB.Ros({
	url : 'ws://master:9090'
});

console.log('Loading Feedback arrows Extension: initializing ROS');

// Define topic object
var feedbackArrowsSpacenavListener = new ROSLIB.Topic({
	ros : spacenavROS,
	name : 'spacenav/twist',
	messageType : 'geometry_msgs/Twist',
	throttle_rate : 20
});

// we'll need a map function
Number.prototype.map = function ( in_min , in_max , out_min , out_max ) {
	  return ( this - in_min ) * ( out_max - out_min ) / ( in_max - in_min ) + out_min;
	}

var ringMultiplier = 0.1;
var arrowMultiplier = 0.1;
var spacenav_min = -350;
var spacenav_max = 350;

var arrows_min = -3;
var arrows_max = 3;

var arrowObjPosition = [ 0, 0, 0, 0, 0, 0 ];
var ringObjPosition = [ 0, 0, 0, 0, 0, 0 ];

// Subscribe to spacenav topic + ROS messages rate limiting
console.log('Loading Feedback arrows Extension: subscribing to spacenav topic');

//Let's normalize values with .map function ( in_min , in_max , out_min , out_max )

feedbackArrowsSpacenavListener.subscribe(function(msg) {
	this.msg = msg;
	if (this.msg.linear.x == 0 && this.msg.linear.y == 0
			&& this.msg.linear.z == 0 && this.msg.angular.x == 0
			&& this.msg.angular.y == 0 && this.msg.angular.z == 0)
		{
		/***
		 * - fade objects out
		 * - return to point 0
		 */
		for (var i = 0; i < arrowObjPosition.length; i++) {
			arrowObjPosition[i] = 0;
			ringObjPosition[i] = 0;
		}
		return;

	} else {
		/***
		 * - map spacenav values to threejs object coordinates
		 * - fade in
		 * - move objects
		 *
		 *	 ObjPosition =
		 *	 [
		 *	 0 : "go front right",
		 *	 1 : "go up (z)",
		 *	 2 : "go front left",
		 *	 3 : "rotate over y axis",
		 *	 4 : "rotate over center",
		 *	 5 : "rotate over x axis"
		 *	 ]
		 *
		 *	 rostopic echo /spacenav/twist:
		 *
		 *	 [
		 *	 "push then pull" : "linear z -350 => +350",
		 *	 "rotate from left to right" : "angular z: +350 => -350",
		 *	 "move backward then forward" : "linear x -350=>+350",
		 *	 "move left then right" : "linear y +350 => -350",
		 *	 "lean left then lean right" : "angular x -350 => +350",
		 *	 "lean forward then lean backward" : "angular y +350 => -350"
		 *	 ]
		 *
		 ***/

		this.msg.linear.x = this.msg.linear.x.map(spacenav_min, spacenav_max, arrows_min, arrows_max);
		this.msg.linear.y = this.msg.linear.y.map(spacenav_min, spacenav_max, arrows_min, arrows_max);
		this.msg.linear.z = this.msg.linear.z.map(spacenav_min, spacenav_max, arrows_min, arrows_max);
		this.msg.angular.x = this.msg.angular.x.map(spacenav_min, spacenav_max, arrows_min, arrows_max);
		this.msg.angular.y = this.msg.angular.y.map(spacenav_min, spacenav_max, arrows_min, arrows_max);
		this.msg.angular.z = this.msg.angular.z.map(spacenav_min, spacenav_max, arrows_min, arrows_max);

		// make object transparency proportional to the values
		ring_object.materials[0].opacity = Math.max(this.msg.linear.z,
				this.msg.angular.z, this.msg.angular.x, this.msg.angular.y)/100;
		// pull up , push down
		ringObjPosition[1] = this.msg.linear.z;
		// rotate (twist)
		ringObjPosition[4] = this.msg.angular.z;
		// lean forward and backward
		ringObjPosition[5] = this.msg.angular.x * -0.1;
		ringObjPosition[3] = this.msg.angular.y * -0.1;

	}

});

// Three.js part
var container, stats;
var camera, scene, renderer;
var mouseX = 0, mouseY = 0;

var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;

console.log("Arrows: before init");
init();
console.log("Arrows: after init");
console.log("Arrows: before animate");
animate();
console.log("Arrows: after animate");

function init() {
	container = document.createElement('div');
	container.id = 'feedback_arrows';
	document.body.appendChild(container);

	camera = new THREE.PerspectiveCamera(45, window.innerWidth
			/ window.innerHeight, 1, 2000);
	camera.position.x = 0;
	camera.position.y = 10;
	camera.position.z = 33;

	// scene

	scene = new THREE.Scene();

	var ambient = new THREE.AmbientLight(0x101030);
	scene.add(ambient);

	var directionalLight = new THREE.DirectionalLight(0xffeedd);
	directionalLight.position.set(0, 0, 1);
	scene.add(directionalLight);

	// texture

	var manager = new THREE.LoadingManager();
	manager.onProgress = function(item, loaded, total) {

		console.log(item, loaded, total);

	};

	var texture = new THREE.Texture();
	var imaginator = new Image();
	imaginator.src = "data:image/jpeg;base64,"
			+ "R0lGODlhkAGQAfAAAP///wAAACH5BAAAAAAAIf4Kc2NyaThlLmNvbQAsAAAAAJABkAEAAv6Ej6nL7Q+jnLTai7PevPsPhuJIluaJpurKtu4Lx/JM1/aN5/rO9/4PDAqHxKLxiEwql8ym8wmNSqfUqvWKzWq33K73Cw6Lx+Sy+YxOq9fstvsNj8vn9Lr9js/r9/y+/w8YKDhIWGh4iJiouMjY6PgIGSk5SVlpeYmZqbnJ2en5CRoqOkpaanqKmqq6ytrq+gobKztLW2t7i5uru8vb6/sLHCw8TFxsfIycrLzM3Oz8DB0tPU1dbX2Nna29zd3t/Q0eLj5OXm5+jp6uvs7e7v4OHy8/T19vf4+fr7/P3+//DzCgwIEECxo8iDChwoUMGzp8CDGixIkUK1q8iDGjxv6NHDt6/AgypMiRJEuaPIkypcqVLFu6fAkzpsyZNGvavIkzp86dPHv6/Ak0qNChRIsaPYo0qdKlTJs6fQo1qtSpVKtavYo1q9atXLt6/Qo2rNixZMuaPYs2rdq1bNu6fQs3rty5dOvavYs3r969fPv6/Qs4sODBhAsbPow4seLFjBs7fgw5suTJlCtbvow5s+bNnDt7/gw6tOjRpEubPo06terVrFu7fg07tuzZtGvbvo07t+7dvHv7/g08uPDhxIsbP448ufLlzJs7fw49uvTp1Ktbv449u/bt3Lt7/w4+vPjx5MubP48+vfr17Nu7fw8/vvz59Ovbv48/v/79/E/7+/8PYIACDkhggQYeiGCCCi7IYIMOPghhhBJOSGGFFl6IYYYabshhhx5+CGKIIo5IYokmnohiiiquyGKLLr4IY4wyzkhjjTbeiGOObRQAADs="
	texture.image = imaginator;
	texture.needsUpdate = true;
	// EOFD

	var arrows_loader = new THREE.OBJLoader(manager);
	arrows_loader.load(chrome.extension.getURL('models/arrow.obj'), function(
			arrow_object) {
		this.arrowObj = arrow_object;
		arrow_object.traverse(function(child) {
			if (child instanceof THREE.Mesh) {
				child.material.map = texture;
			}
		});
		scene.add(arrow_object);
	});

	var ring_loader = new THREE.OBJLoader(manager);
	ring_loader.load(chrome.extension.getURL('models/ring.obj'), function(
			ring_object) {
		this.ringObj = ring_object;
		ring_object.traverse(function(child) {
			if (child instanceof THREE.Mesh) {
				child.material.map = texture;
			}
		});
		scene.add(ring_object);
	});

	//

	// let's make transparent background
	renderer = new THREE.WebGLRenderer({
		alpha : true
	});
	renderer.setSize(window.innerWidth, window.innerHeight);
	container.appendChild(renderer.domElement);
	renderer.setClearColor(0x000000, 0);
	window.addEventListener('resize', onWindowResize, false);

}

// we need this for debug purposes
function onWindowResize() {
	windowHalfX = window.innerWidth / 2;
	windowHalfY = window.innerHeight / 2;
	camera.aspect = window.innerWidth / window.innerHeight;
	camera.updateProjectionMatrix();
	renderer.setSize(window.innerWidth, window.innerHeight);
}

//

function animate() {
	requestAnimationFrame(animate);
	render();
}

function render() {
	if (arrowObj) {
		arrowObj.position.x = arrowObjPosition[0];
		arrowObj.position.y = arrowObjPosition[1];
		arrowObj.position.z = arrowObjPosition[2];
		arrowObj.rotation.x = arrowObjPosition[3];
		arrowObj.rotation.y = arrowObjPosition[4];
		arrowObj.rotation.z = arrowObjPosition[5];
	}
	if (ringObj) {
		ringObj.position.x = ringObjPosition[0];
		ringObj.position.y = ringObjPosition[1];
		ringObj.position.z = ringObjPosition[2];
		ringObj.rotation.x = ringObjPosition[3];
		ringObj.rotation.y = ringObjPosition[4];
		ringObj.rotation.z = ringObjPosition[5];
	}
	camera.lookAt(scene.position);
	renderer.render(scene, camera);
}
<commit_msg>Fixed opacity error<commit_after>/*
 * Feedback arrows UX extension.
 * Shows two independent webgl models that should immitate spacenav movement.
 * Object should fade in and fade out on spacenav use.
 */
/*
 * Feedback arrows UX extension.
 * Shows two independent webgl models that should immitate spacenav movement.
 * Object should fade in and fade out on spacenav use.
 */

console.log('Loading Feedback arrows Extension: creating WS socket');

//Let's connect directly to websocket<->ROS bridge
var spacenavROS = new ROSLIB.Ros({
	url : 'ws://master:9090'
});

console.log('Loading Feedback arrows Extension: initializing ROS');

// Define topic object
var feedbackArrowsSpacenavListener = new ROSLIB.Topic({
	ros : spacenavROS,
	name : 'spacenav/twist',
	messageType : 'geometry_msgs/Twist',
	throttle_rate : 20
});

// we'll need a map function
Number.prototype.map = function ( in_min , in_max , out_min , out_max ) {
	  return ( this - in_min ) * ( out_max - out_min ) / ( in_max - in_min ) + out_min;
	}

var ringMultiplier = 0.1;
var arrowMultiplier = 0.1;
var spacenav_min = -350;
var spacenav_max = 350;

var arrows_min = -3;
var arrows_max = 3;

var arrowObjPosition = [ 0, 0, 0, 0, 0, 0 ];
var ringObjPosition = [ 0, 0, 0, 0, 0, 0 ];

// Subscribe to spacenav topic + ROS messages rate limiting
console.log('Loading Feedback arrows Extension: subscribing to spacenav topic');

//Let's normalize values with .map function ( in_min , in_max , out_min , out_max )

feedbackArrowsSpacenavListener.subscribe(function(msg) {
	this.msg = msg;
	if (this.msg.linear.x == 0 && this.msg.linear.y == 0
			&& this.msg.linear.z == 0 && this.msg.angular.x == 0
			&& this.msg.angular.y == 0 && this.msg.angular.z == 0)
		{
		/***
		 * - fade objects out
		 * - return to point 0
		 */
		if (ring_object && arrow_object ) {
		ring_object.materials[0].opacity = 1;
		arrow_object.materials[0].opacity = 1;
		}

		for (var i = 0; i < arrowObjPosition.length; i++) {
			arrowObjPosition[i] = 0;
			ringObjPosition[i] = 0;
		}
		return;

	} else {
		/***
		 * - map spacenav values to threejs object coordinates
		 * - fade in
		 * - move objects
		 *
		 *	 ObjPosition =
		 *	 [
		 *	 0 : "go front right",
		 *	 1 : "go up (z)",
		 *	 2 : "go front left",
		 *	 3 : "rotate over y axis",
		 *	 4 : "rotate over center",
		 *	 5 : "rotate over x axis"
		 *	 ]
		 *
		 *	 rostopic echo /spacenav/twist:
		 *
		 *	 [
		 *	 "push then pull" : "linear z -350 => +350",
		 *	 "rotate from left to right" : "angular z: +350 => -350",
		 *	 "move backward then forward" : "linear x -350=>+350",
		 *	 "move left then right" : "linear y +350 => -350",
		 *	 "lean left then lean right" : "angular x -350 => +350",
		 *	 "lean forward then lean backward" : "angular y +350 => -350"
		 *	 ]
		 *
		 ***/

		this.msg.linear.x = this.msg.linear.x.map(spacenav_min, spacenav_max, arrows_min, arrows_max);
		this.msg.linear.y = this.msg.linear.y.map(spacenav_min, spacenav_max, arrows_min, arrows_max);
		this.msg.linear.z = this.msg.linear.z.map(spacenav_min, spacenav_max, arrows_min, arrows_max);
		this.msg.angular.x = this.msg.angular.x.map(spacenav_min, spacenav_max, arrows_min, arrows_max);
		this.msg.angular.y = this.msg.angular.y.map(spacenav_min, spacenav_max, arrows_min, arrows_max);
		this.msg.angular.z = this.msg.angular.z.map(spacenav_min, spacenav_max, arrows_min, arrows_max);

		// make object transparency proportional to the values
		ring_object.materials[0].opacity = Math.max(this.msg.linear.z,
				this.msg.angular.z, this.msg.angular.x, this.msg.angular.y)/100;
		// pull up , push down
		ringObjPosition[1] = this.msg.linear.z;
		// rotate (twist)
		ringObjPosition[4] = this.msg.angular.z;
		// lean forward and backward
		ringObjPosition[5] = this.msg.angular.x * -0.1;
		ringObjPosition[3] = this.msg.angular.y * -0.1;

	}

});

// Three.js part
var container, stats;
var camera, scene, renderer;
var mouseX = 0, mouseY = 0;

var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;

console.log("Arrows: before init");
init();
console.log("Arrows: after init");
console.log("Arrows: before animate");
animate();
console.log("Arrows: after animate");

function init() {
	container = document.createElement('div');
	container.id = 'feedback_arrows';
	document.body.appendChild(container);

	camera = new THREE.PerspectiveCamera(45, window.innerWidth
			/ window.innerHeight, 1, 2000);
	camera.position.x = 0;
	camera.position.y = 10;
	camera.position.z = 33;

	// scene

	scene = new THREE.Scene();

	var ambient = new THREE.AmbientLight(0x101030);
	scene.add(ambient);

	var directionalLight = new THREE.DirectionalLight(0xffeedd);
	directionalLight.position.set(0, 0, 1);
	scene.add(directionalLight);

	// texture

	var manager = new THREE.LoadingManager();
	manager.onProgress = function(item, loaded, total) {

		console.log(item, loaded, total);

	};

	var texture = new THREE.Texture();
	var imaginator = new Image();
	imaginator.src = "data:image/jpeg;base64,"
			+ "R0lGODlhkAGQAfAAAP///wAAACH5BAAAAAAAIf4Kc2NyaThlLmNvbQAsAAAAAJABkAEAAv6Ej6nL7Q+jnLTai7PevPsPhuJIluaJpurKtu4Lx/JM1/aN5/rO9/4PDAqHxKLxiEwql8ym8wmNSqfUqvWKzWq33K73Cw6Lx+Sy+YxOq9fstvsNj8vn9Lr9js/r9/y+/w8YKDhIWGh4iJiouMjY6PgIGSk5SVlpeYmZqbnJ2en5CRoqOkpaanqKmqq6ytrq+gobKztLW2t7i5uru8vb6/sLHCw8TFxsfIycrLzM3Oz8DB0tPU1dbX2Nna29zd3t/Q0eLj5OXm5+jp6uvs7e7v4OHy8/T19vf4+fr7/P3+//DzCgwIEECxo8iDChwoUMGzp8CDGixIkUK1q8iDGjxv6NHDt6/AgypMiRJEuaPIkypcqVLFu6fAkzpsyZNGvavIkzp86dPHv6/Ak0qNChRIsaPYo0qdKlTJs6fQo1qtSpVKtavYo1q9atXLt6/Qo2rNixZMuaPYs2rdq1bNu6fQs3rty5dOvavYs3r969fPv6/Qs4sODBhAsbPow4seLFjBs7fgw5suTJlCtbvow5s+bNnDt7/gw6tOjRpEubPo06terVrFu7fg07tuzZtGvbvo07t+7dvHv7/g08uPDhxIsbP448ufLlzJs7fw49uvTp1Ktbv449u/bt3Lt7/w4+vPjx5MubP48+vfr17Nu7fw8/vvz59Ovbv48/v/79/E/7+/8PYIACDkhggQYeiGCCCi7IYIMOPghhhBJOSGGFFl6IYYYabshhhx5+CGKIIo5IYokmnohiiiquyGKLLr4IY4wyzkhjjTbeiGOObRQAADs="
	texture.image = imaginator;
	texture.needsUpdate = true;
	// EOFD

	var arrows_loader = new THREE.OBJLoader(manager);
	arrows_loader.load(chrome.extension.getURL('models/arrow.obj'), function(
			arrow_object) {
		this.arrowObj = arrow_object;
		arrow_object.traverse(function(child) {
			if (child instanceof THREE.Mesh) {
				child.material.map = texture;
			}
		});
		scene.add(arrow_object);
	});

	var ring_loader = new THREE.OBJLoader(manager);
	ring_loader.load(chrome.extension.getURL('models/ring.obj'), function(
			ring_object) {
		this.ringObj = ring_object;
		ring_object.traverse(function(child) {
			if (child instanceof THREE.Mesh) {
				child.material.map = texture;
			}
		});
		scene.add(ring_object);
	});

	//

	// let's make transparent background
	renderer = new THREE.WebGLRenderer({
		alpha : true
	});
	renderer.setSize(window.innerWidth, window.innerHeight);
	container.appendChild(renderer.domElement);
	renderer.setClearColor(0x000000, 0);
	window.addEventListener('resize', onWindowResize, false);

}

// we need this for debug purposes
function onWindowResize() {
	windowHalfX = window.innerWidth / 2;
	windowHalfY = window.innerHeight / 2;
	camera.aspect = window.innerWidth / window.innerHeight;
	camera.updateProjectionMatrix();
	renderer.setSize(window.innerWidth, window.innerHeight);
}

//

function animate() {
	requestAnimationFrame(animate);
	render();
}

function render() {
	if (arrowObj) {
		arrowObj.position.x = arrowObjPosition[0];
		arrowObj.position.y = arrowObjPosition[1];
		arrowObj.position.z = arrowObjPosition[2];
		arrowObj.rotation.x = arrowObjPosition[3];
		arrowObj.rotation.y = arrowObjPosition[4];
		arrowObj.rotation.z = arrowObjPosition[5];
	}
	if (ringObj) {
		ringObj.position.x = ringObjPosition[0];
		ringObj.position.y = ringObjPosition[1];
		ringObj.position.z = ringObjPosition[2];
		ringObj.rotation.x = ringObjPosition[3];
		ringObj.rotation.y = ringObjPosition[4];
		ringObj.rotation.z = ringObjPosition[5];
	}
	camera.lookAt(scene.position);
	renderer.render(scene, camera);
}
<|endoftext|>


<commit_before><commit_msg>Cron run<commit_after><|endoftext|>


<commit_before>// TODO:
// move typedWord from state to redux store, and possibly other
// state variables as well

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';

import TypingTest from '../components/typing-test';
import * as actions from '../actions/action-creators';

class TypingTestContainer extends Component {
  constructor() {
    super();
    this.start = this.start.bind(this);
    this.stop = this.stop.bind(this);
    this.calculateWPM = this.calculateWPM.bind(this);
    this.handleKeyPress = this.handleKeyPress.bind(this);

    this.state = {
      text: "this is test text the quick brown fox jumped over the lazy fox" +
      " second line of text begins here so and so testing one two three the" +
      " cat is free",
      words: [],
      typedWord: "", // The current word as typed by the user
      totalWords: 0,
      currentChar: 0,
      correctCharCount: 0,
      wrongCharCount: 0,
    };
  }

  componentDidMount() {
    this.props.setText(this.state.text);
    // Transform the text into on array of words
    this.setState({words: this.state.text.split(" ")});
    this.setState({ minutes: 1, seconds: 0 });
  }

  start() {
    if (!this.props.typingTest.finished)
      this.props.start(Date.now(), this.state.text);
  }

  stop() {
    this.props.stop(Date.now(), this.calculateWPM());
  }

  calculateWPM() {
    return 0;
  }

  handleKeyPress(e) {
    let {
      typedWord,
      totalWords,
      currentChar,
      correctCharCount,
      wrongCharCount } = this.state;

    // Get the word that's currently being typed
    const word = this.state.words[totalWords];

    if (e.key === "Tab")
      e.preventDefault();

    if (e.key === 'Shift' || e.key === 'Ctrl' || e.key === 'Alt')
      return;

    // Start when typing starts
    if (!this.props.typingTest.inProgress &&
      e.key !== 'Shift' &&
      e.key !== 'Tab')
      this.start();

    // Handle backspace
    if (e.key === 'Backspace') {
      // Already at the beginning of the current word?
      if (currentChar === 0)
        return;

      // Is this a correct char?
      if (this.state.typedWord[currentChar - 1] === word[currentChar - 1])
        correctCharCount--;
      else
        wrongCharCount--;

      currentChar--;
      typedWord = typedWord.slice(0, typedWord.length - 1);
    } else if (e.key === ' ' || e.key === 'Enter') {
      // If this was the last word, then stop the typing test,
      // otherwise move on to next word
      typedWord = "";
      totalWords++;
      currentChar = 0;
      if (totalWords === this.state.words.length)
        this.stop();
      else
        this.props.wordTyped();
    } else {
      // Handle other keys than backspace, space or enter
      if (e.key === word[currentChar])
        correctCharCount++;
      else
        wrongCharCount++;

      currentChar++;
      typedWord += e.key;

      // Stop if all the text was typed (the last character being correct)
      if (this.state.totalWords === this.state.words.length - 1 &&
        typedWord.length === word.length &&
        typedWord.slice(-1) === word.slice(-1)) {

        this.stop();
      }
    }
    this.setState({
      correctCharCount,
      wrongCharCount,
      currentChar,
      typedWord,
      totalWords,
    });
  }

  render() {
    return(
      <TypingTest
        text={this.props.typingTest.text}
        typedWord={this.state.typedWord}
        line={this.props.typingTest.currentLineNum}
        lineLength={60}
        onKeyPress={this.handleKeyPress}/>
    );
  }
}

function mapStateToProps(state) {
  return { typingTest: state.typingTest };
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators(actions, dispatch);
}

export default connect(mapStateToProps, mapDispatchToProps)(TypingTestContainer);
<commit_msg>Don't allow typing at all when test is finished<commit_after>// TODO:
// move typedWord from state to redux store, and possibly other
// state variables as well

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';

import TypingTest from '../components/typing-test';
import * as actions from '../actions/action-creators';

class TypingTestContainer extends Component {
  constructor() {
    super();
    this.start = this.start.bind(this);
    this.stop = this.stop.bind(this);
    this.calculateWPM = this.calculateWPM.bind(this);
    this.handleKeyPress = this.handleKeyPress.bind(this);

    this.state = {
      text: "this is test text the quick brown fox jumped over the lazy fox" +
      " second line of text begins here so and so testing one two three the" +
      " cat is free",
      words: [],
      typedWord: "", // The current word as typed by the user
      totalWords: 0,
      currentChar: 0,
      correctCharCount: 0,
      wrongCharCount: 0,
    };
  }

  componentDidMount() {
    this.props.setText(this.state.text);
    // Transform the text into on array of words
    this.setState({words: this.state.text.split(" ")});
    this.setState({ minutes: 1, seconds: 0 });
  }

  start() {
    this.props.start(Date.now(), this.state.text);
  }

  stop() {
    this.props.stop(Date.now(), this.calculateWPM());
  }

  calculateWPM() {
    return 0;
  }

  handleKeyPress(e) {
    if (this.props.typingTest.finished)
      return;

    let {
      typedWord,
      totalWords,
      currentChar,
      correctCharCount,
      wrongCharCount } = this.state;

    // Get the word that's currently being typed
    const word = this.state.words[totalWords];

    if (e.key === "Tab")
      e.preventDefault();

    if (e.key === 'Shift' || e.key === 'Ctrl' || e.key === 'Alt')
      return;

    // Start when typing starts
    if (!this.props.typingTest.inProgress &&
      e.key !== 'Shift' &&
      e.key !== 'Tab')
      this.start();

    // Handle backspace
    if (e.key === 'Backspace') {
      // Already at the beginning of the current word?
      if (currentChar === 0)
        return;

      // Is this a correct char?
      if (this.state.typedWord[currentChar - 1] === word[currentChar - 1])
        correctCharCount--;
      else
        wrongCharCount--;

      currentChar--;
      typedWord = typedWord.slice(0, typedWord.length - 1);
    } else if (e.key === ' ' || e.key === 'Enter') {
      // If this was the last word, then stop the typing test,
      // otherwise move on to next word
      typedWord = "";
      totalWords++;
      currentChar = 0;
      if (totalWords === this.state.words.length)
        this.stop();
      else
        this.props.wordTyped();
    } else {
      // Handle other keys than backspace, space or enter
      if (e.key === word[currentChar])
        correctCharCount++;
      else
        wrongCharCount++;

      currentChar++;
      typedWord += e.key;

      // Stop if all the text was typed (the last character being correct)
      if (this.state.totalWords === this.state.words.length - 1 &&
        typedWord.length === word.length &&
        typedWord.slice(-1) === word.slice(-1)) {

          this.stop();
        }
    }
    this.setState({
      correctCharCount,
      wrongCharCount,
      currentChar,
      typedWord,
      totalWords,
    });
  }

  render() {
    return(
      <TypingTest
        text={this.props.typingTest.text}
        typedWord={this.state.typedWord}
        line={this.props.typingTest.currentLineNum}
        lineLength={60}
        onKeyPress={this.handleKeyPress}/>
    );
  }
}

function mapStateToProps(state) {
  return { typingTest: state.typingTest };
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators(actions, dispatch);
}

export default connect(mapStateToProps, mapDispatchToProps)(TypingTestContainer);
<|endoftext|>


<commit_before>/*
Copyright 2015 OpenMarket Ltd

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

'use strict';

var React = require("react");
var MatrixClientPeg = require("../../MatrixClientPeg");
var Modal = require("../../Modal");
var ComponentBroker = require('../../ComponentBroker');
var ErrorDialog = ComponentBroker.get("organisms/ErrorDialog");

var INITIAL_LOAD_NUM_MEMBERS = 50;

module.exports = {
    getInitialState: function() {
        var members = this.roomMembers(INITIAL_LOAD_NUM_MEMBERS);
        return {
            memberDict: members
        };
    },

    componentWillMount: function() {
        var cli = MatrixClientPeg.get();
        cli.on("RoomState.members", this.onRoomStateMember);
    },

    componentWillUnmount: function() {
        if (MatrixClientPeg.get()) {
            MatrixClientPeg.get().removeListener("RoomState.members", this.onRoomStateMember);
            MatrixClientPeg.get().removeListener("User.presence", this.userPresenceFn);
        }
    },

    componentDidMount: function() {
        var self = this;
        setTimeout(function() {
            if (!self.isMounted()) return;
            self.setState({
                memberDict: self.roomMembers()
            });
        }, 50);

        // Attach a SINGLE listener for global presence changes then locate the
        // member tile and re-render it. This is more efficient than every tile
        // evar attaching their own listener.
        function updateUserState(event, user) {
            var tile = self.refs[user.userId];
            if (tile) {
                tile.forceUpdate();
            }
        }
        MatrixClientPeg.get().on("User.presence", updateUserState);
        this.userPresenceFn = updateUserState;
    },
    // Remember to set 'key' on a MemberList to the ID of the room it's for
    /*componentWillReceiveProps: function(newProps) {
    },*/

    onRoomStateMember: function(ev, state, member) {
        var members = this.roomMembers();
        this.setState({
            memberDict: members
        });
    },

    onInvite: function(inputText) {
        var self = this;
        // sanity check the input
        inputText = inputText.trim(); // react requires es5-shim so we know trim() exists
        if (inputText[0] !== '@' || inputText.indexOf(":") === -1) {
            console.error("Bad user ID to invite: %s", inputText);
            Modal.createDialog(ErrorDialog, {
                title: "Invite Error",
                description: "Malformed user ID. Should look like '@localpart:domain'"
            });
            return;
        }
        self.setState({
            inviting: true
        });
        console.log("Invite %s to %s", inputText, this.props.roomId);
        MatrixClientPeg.get().invite(this.props.roomId, inputText).done(
        function(res) {
            console.log("Invited");
            self.setState({
                inviting: false
            });
        }, function(err) {
            console.error("Failed to invite: %s", JSON.stringify(err));
            Modal.createDialog(ErrorDialog, {
                title: "Server error whilst inviting",
                description: err.message
            });
            self.setState({
                inviting: false
            });
        });
    },

    roomMembers: function(limit) {
        if (!this.props.roomId) return {};
        var cli = MatrixClientPeg.get();
        var room = cli.getRoom(this.props.roomId);
        if (!room) return {};
        var all_members = room.currentState.members;
        var all_user_ids = Object.keys(all_members);

        all_user_ids.sort(function(userIdA, userIdB) {
            var userA = all_members[userIdA].user;
            var userB = all_members[userIdB].user;

            var latA = userA ? userA.lastActiveAgo || Number.MAX_VALUE : Number.MAX_VALUE;
            var latB = userB ? userB.lastActiveAgo || Number.MAX_VALUE : Number.MAX_VALUE;

            return latA - latB;
        });

        var to_display = {};
        var count = 0;
        for (var i = 0; i < all_user_ids.length && (limit === undefined || count < limit); ++i) {
            var user_id = all_user_ids[i];
            var m = all_members[user_id];

            if (m.membership == 'join' || m.membership == 'invite') {
                to_display[user_id] = m;
                ++count;
            }
        }
        return to_display;
    }
};

<commit_msg>Bugfix: Accepting an invite no longer results in a stale membership list.<commit_after>/*
Copyright 2015 OpenMarket Ltd

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

'use strict';

var React = require("react");
var MatrixClientPeg = require("../../MatrixClientPeg");
var Modal = require("../../Modal");
var ComponentBroker = require('../../ComponentBroker');
var ErrorDialog = ComponentBroker.get("organisms/ErrorDialog");

var INITIAL_LOAD_NUM_MEMBERS = 50;

module.exports = {
    getInitialState: function() {
        var members = this.roomMembers(INITIAL_LOAD_NUM_MEMBERS);
        return {
            memberDict: members
        };
    },

    componentWillMount: function() {
        var cli = MatrixClientPeg.get();
        cli.on("RoomState.members", this.onRoomStateMember);
        cli.on("Room", this.onRoom); // invites
    },

    componentWillUnmount: function() {
        if (MatrixClientPeg.get()) {
            MatrixClientPeg.get().removeListener("Room", this.onRoom);
            MatrixClientPeg.get().removeListener("RoomState.members", this.onRoomStateMember);
            MatrixClientPeg.get().removeListener("User.presence", this.userPresenceFn);
        }
    },

    componentDidMount: function() {
        var self = this;
        setTimeout(function() {
            if (!self.isMounted()) return;
            self.setState({
                memberDict: self.roomMembers()
            });
        }, 50);

        // Attach a SINGLE listener for global presence changes then locate the
        // member tile and re-render it. This is more efficient than every tile
        // evar attaching their own listener.
        function updateUserState(event, user) {
            var tile = self.refs[user.userId];
            if (tile) {
                tile.forceUpdate();
            }
        }
        MatrixClientPeg.get().on("User.presence", updateUserState);
        this.userPresenceFn = updateUserState;
    },
    // Remember to set 'key' on a MemberList to the ID of the room it's for
    /*componentWillReceiveProps: function(newProps) {
    },*/

    onRoom: function(room) {
        if (room.roomId !== this.props.roomId) {
            return;
        }
        // We listen for room events because when we accept an invite
        // we need to wait till the room is fully populated with state
        // before refreshing the member list else we get a stale list.
        this._updateList();
    },

    onRoomStateMember: function(ev, state, member) {
        this._updateList();
    },

    _updateList: function() {
        var members = this.roomMembers();
        this.setState({
            memberDict: members
        });
    },

    onInvite: function(inputText) {
        var self = this;
        // sanity check the input
        inputText = inputText.trim(); // react requires es5-shim so we know trim() exists
        if (inputText[0] !== '@' || inputText.indexOf(":") === -1) {
            console.error("Bad user ID to invite: %s", inputText);
            Modal.createDialog(ErrorDialog, {
                title: "Invite Error",
                description: "Malformed user ID. Should look like '@localpart:domain'"
            });
            return;
        }
        self.setState({
            inviting: true
        });
        console.log("Invite %s to %s", inputText, this.props.roomId);
        MatrixClientPeg.get().invite(this.props.roomId, inputText).done(
        function(res) {
            console.log("Invited");
            self.setState({
                inviting: false
            });
        }, function(err) {
            console.error("Failed to invite: %s", JSON.stringify(err));
            Modal.createDialog(ErrorDialog, {
                title: "Server error whilst inviting",
                description: err.message
            });
            self.setState({
                inviting: false
            });
        });
    },

    roomMembers: function(limit) {
        if (!this.props.roomId) return {};
        var cli = MatrixClientPeg.get();
        var room = cli.getRoom(this.props.roomId);
        if (!room) return {};
        var all_members = room.currentState.members;
        var all_user_ids = Object.keys(all_members);

        all_user_ids.sort(function(userIdA, userIdB) {
            var userA = all_members[userIdA].user;
            var userB = all_members[userIdB].user;

            var latA = userA ? userA.lastActiveAgo || Number.MAX_VALUE : Number.MAX_VALUE;
            var latB = userB ? userB.lastActiveAgo || Number.MAX_VALUE : Number.MAX_VALUE;

            return latA - latB;
        });

        var to_display = {};
        var count = 0;
        for (var i = 0; i < all_user_ids.length && (limit === undefined || count < limit); ++i) {
            var user_id = all_user_ids[i];
            var m = all_members[user_id];

            if (m.membership == 'join' || m.membership == 'invite') {
                to_display[user_id] = m;
                ++count;
            }
        }
        return to_display;
    }
};

<|endoftext|>


<commit_before>import React from 'react'
import { Link } from 'gatsby'
import Helmet from 'react-helmet'
import styled from 'styled-components'
import { Text } from 'rebass'
import Header from '../components/Header'
import { Title, Subtitle } from '../components/Typography'
import { themeHover } from '../utils/styles'

const HaikuLink = styled(Link)`
  ${themeHover};
`

const errorPage = () => (
  <>
    <Helmet>
      <title>I goofed it.</title>
    </Helmet>

        <Title>Error 404</Title>

        <Subtitle>Requested Page Not Found</Subtitle>

        {/* have to ugily do this because somewhere whitespace gets removed */}
        <Text
          as="pre"
          fontSize={[2, 3]}
          fontFamily="monospace"
          lineHeight="title"
        >
          “
          <HaikuLink to="/">Click here to go home</HaikuLink>
          ”

           Is over-used and boring,

           But at least it’s clear.

        </Text>

  </>
)

export default errorPage
<commit_msg>:twisted_rightwards_arrows: merge master into develop<commit_after>import React from 'react'
import { Link } from 'gatsby'
import Helmet from 'react-helmet'
import styled from 'styled-components'
import { Text } from 'rebass'
import Header from '../components/Header'
import { Title, Subtitle } from '../components/Typography'
import { themeHover } from '../utils/styles'

const HaikuLink = styled(Link)`
  ${themeHover};
`

const errorPage = () => (
  <>
    <Helmet>
      <title>I goofed it.</title>
    </Helmet>

        <Title>Error 404</Title>

        <Subtitle>Requested Page Not Found</Subtitle>

        {/* have to ugily do this because somewhere whitespace gets removed */}
        <Text
          as="pre"
          fontSize={[2, 3]}
          fontFamily="monospace"
          lineHeight="title"
        >
          “
          <HaikuLink to="/">Click here to go home</HaikuLink>
          ”

           is over-used and boring,

           but at least it’s clear.

        </Text>

  </>
)

export default errorPage
<|endoftext|>


<commit_before>module.exports = function () {

  var babelPreprocessor = file => require('babel').transform(file.content, {sourceMap: true});
  return {
    files: [
      {pattern: 'jspm_packages/system.js', instrument: false},
      {pattern: 'config.js', instrument: false},

      {pattern: 'src/*.js', load: false}
    ],
    tests: [
      {pattern: 'test/*Spec.js', load: false}
    ],

    preprocessors: {
      'test/*.js': babelPreprocessor,
      'src/*.js': babelPreprocessor
    },

    middleware: (app, express) => {
      app.use('/jspm_packages', express.static(require('path').join(__dirname, 'jspm_packages')));
    },

    setup: function (wallaby) {
      wallaby.delayStart();

      var promises = [];
      for (var i = 0, len = wallaby.tests.length; i < len; i++) {
        promises.push(System['import'](wallaby.tests[i].replace(/\.js$/, '')));
      }

      Promise.all(promises).then(function () {
        wallaby.start();
      }).catch(function (e) { setTimeout(function (){ throw e; }, 0); });
    }
  };
};
<commit_msg>Changed preprocessor to compiler<commit_after>module.exports = function (wallaby) {

  return {
    files: [
      {pattern: 'jspm_packages/system.js', instrument: false},
      {pattern: 'config.js', instrument: false},

      {pattern: 'src/*.js', load: false}
    ],
    tests: [
      {pattern: 'test/*Spec.js', load: false}
    ],

    compilers: {
      '**/*.js': wallaby.compilers.babel()
    },

    middleware: (app, express) => {
      app.use('/jspm_packages', express.static(require('path').join(__dirname, 'jspm_packages')));
    },

    setup: function (wallaby) {
      wallaby.delayStart();

      var promises = [];
      for (var i = 0, len = wallaby.tests.length; i < len; i++) {
        promises.push(System['import'](wallaby.tests[i].replace(/\.js$/, '')));
      }

      Promise.all(promises).then(function () {
        wallaby.start();
      }).catch(function (e) { setTimeout(function (){ throw e; }, 0); });
    }
  };
};
<|endoftext|>


<commit_before>"use strict";

module.exports = () => ({
	debug: true,
	testFramework: "jasmine",
	files: ["src/**/*.ts"],
	tests: ["test/*.spec.ts"],
	env: {
		type: "node"
	}
});
<commit_msg>test: remove Wallaby config<commit_after><|endoftext|>


<commit_before>module.exports = function(wallaby) {
  return {
    files: [
      { pattern: 'test/**/*.spec.js', ignore: true },
      'src/**/*.js*',
      'test/getTestDeps.js'
    ],
    tests: [
      { pattern: 'node_modules/*', ignore: true, instrument: false },
      { pattern: 'test/react/**/*.spec.js', ignore: true, instrument: false },
      'test/**/*.spec.js*',
    ],
    compilers: {
      '**/*.js': wallaby.compilers.babel({
        babel: require('babel-core'),
      }),
    },
    env: {
      type: 'node'
    },
    testFramework: 'jest'
  }
}
<commit_msg>Delete wallaby.js<commit_after><|endoftext|>


<commit_before>'use strict';

const Path = require('path');
const Hapi = require('@hapi/hapi');
const Inert = require('@hapi/inert');

const init = async () => {
    // create the [formerly] Walmart Labs Hapi Server
    const server = Hapi.server({
      port: process.env.PORT || 8000,
      host: 'localhost'
    });

    await server.register(Inert);

    // serve up all static content in public folder
    server.route({
      method: 'GET',
      path: '/{path*}',
      handler: {
        directory: {
          path: './public',
          listing: false
        }
      }
    });

    server.route({
      method: 'GET',
      path: '/greeting',
      handler: (request, h) => {
        return 'Hi World!';
      }
    });

    await server.start();
    console.log(`=> Mullet Stack running at: ${server.info.uri}`);
};

process.on('unhandledRejection', (err) => {

    console.log(err);
    process.exit(1);
});

init();
<commit_msg>[bug] fix lint issues<commit_after>'use strict';

const Hapi = require('@hapi/hapi');
const Inert = require('@hapi/inert');

const init = async () => {
    // create the [formerly] Walmart Labs Hapi Server
    const server = Hapi.server({
      port: process.env.PORT || 8000,
      host: 'localhost'
    });

    await server.register(Inert);

    // serve up all static content in public folder
    server.route({
      method: 'GET',
      path: '/{path*}',
      handler: {
        directory: {
          path: './public',
          listing: false
        }
      }
    });

    server.route({
      method: 'GET',
      path: '/greeting',
      handler: (request, h) => {
        return 'Hi World!';
      }
    });

    await server.start();
    console.log(`=> Mullet Stack running at: ${server.info.uri}`);
};

process.on('unhandledRejection', (err) => {

    console.log(err);
    process.exit(1);
});

init();
<|endoftext|>


<commit_before>'use strict';

define(['knockout', 'ko-data-source', 'stringifyable'], function (ko, dataSource, stringifyable) {
    return function (args) {
        var entriesPromiser = args.entries;
        var idProperty = args.id || 'id';
        var observableProperties = args.properties;
        var numericProperties = args.numericProperties || [];

        var idSelector = function (e) { return e[idProperty]; };
        var observableStateTransitioner = new (dataSource.DefaultObservableStateTransitioner.bind.apply(dataSource.DefaultObservableStateTransitioner, observableProperties));

        var clientSideDatSourceFactory = function () {
            var observables = new dataSource.ObservableEntries(idSelector, observableStateTransitioner);
            var clientSideDataSource = new dataSource.ClientSideDataSource(idSelector, observables);

            entriesPromiser().then(function (entries) {
                clientSideDataSource.addEntries(entries);
            });

            return clientSideDataSource;
        };

        clientSideDatSourceFactory.remote = function (options) {
            var entries = [];
            entriesPromiser().then(function (es) {
                // well.. this ain't pretty
                entries = es;
                Array.prototype.slice.call(document.querySelectorAll('.ko-grid')).forEach(function (grid) {
                    ko.contextFor(grid).grid.data.predicates.valueHasMutated();
                });
            });

            options = options || {};
            var io = options.io || {
                    logRequest: function (r) { window.console.log('Mock Server Request: ', r); },
                    logResponse: function (r) { window.console.log('Mock Server Response: ', r); }
                };

            var observables = new dataSource.ObservableEntries(idSelector, observableStateTransitioner);
            return new dataSource.ServerSideDataSource(idSelector, observables, {
                issue: function (query) {
                    io.logRequest(JSON.stringify({
                        predicate: query.predicate,
                        comparator: query.comparator,
                        offset: query.offset,
                        limit: query.limit,
                    }, stringifyable.stringifyReplacer, '  '));

                    return new Promise(function (resolve) {
                        window.setTimeout(function () {
                            var matching = entries.filter(query.predicate);
                            matching.sort(query.comparator);
                            var clipped = matching.slice(query.offset, query.offset + query.limit);

                            var result = {
                                unfilteredSize: entries.length,
                                filteredSize: matching.length,
                                values: clipped
                            };

                            if (options.computeStatistics) {
                                var statistics = {};
                                numericProperties.forEach(function (p) {
                                    statistics[p] = {'minimum': Number.POSITIVE_INFINITY, 'maximum': Number.NEGATIVE_INFINITY, 'sum': 0}
                                });
                                matching.forEach(function (e) {
                                    numericProperties.forEach(function (p) {
                                        var propertyStatistics = statistics[p];
                                        var v = e[p];
                                        propertyStatistics['minimum'] = Math.min(propertyStatistics['minimum'], v);
                                        propertyStatistics['maximum'] = Math.max(propertyStatistics['maximum'], v);
                                        propertyStatistics['sum'] += v;
                                    });
                                });

                                result.statistics = statistics;
                            }

                            io.logResponse(JSON.stringify(result, stringifyable.stringifyReplacer, '  '));

                            result.values = dataSource.streams.streamArray(clipped);
                            resolve(result);
                        }, options.latency || 500);
                    });
                }
            });
        };

        return clientSideDatSourceFactory;
    };
});
<commit_msg>`Number.POSITIVE_INFINITY` is turned into the string `'Number.POSITIVE_INFINITY'` so it does not show up as `null`.<commit_after>'use strict';

define(['knockout', 'ko-data-source', 'stringifyable'], function (ko, dataSource, stringifyable) {
    var stringifyReplacer = function (key, value) {
        if (value === Number.POSITIVE_INFINITY)
            return 'Number.POSITIVE_INFINITY';

        return stringifyable.stringifyReplacer(key, value);
    };

    return function (args) {
        var entriesPromiser = args.entries;
        var idProperty = args.id || 'id';
        var observableProperties = args.properties;
        var numericProperties = args.numericProperties || [];

        var idSelector = function (e) { return e[idProperty]; };
        var observableStateTransitioner = new (dataSource.DefaultObservableStateTransitioner.bind.apply(dataSource.DefaultObservableStateTransitioner, observableProperties));

        var clientSideDatSourceFactory = function () {
            var observables = new dataSource.ObservableEntries(idSelector, observableStateTransitioner);
            var clientSideDataSource = new dataSource.ClientSideDataSource(idSelector, observables);

            entriesPromiser().then(function (entries) {
                clientSideDataSource.addEntries(entries);
            });

            return clientSideDataSource;
        };

        clientSideDatSourceFactory.remote = function (options) {
            var entries = [];
            entriesPromiser().then(function (es) {
                // well.. this ain't pretty
                entries = es;
                Array.prototype.slice.call(document.querySelectorAll('.ko-grid')).forEach(function (grid) {
                    ko.contextFor(grid).grid.data.predicates.valueHasMutated();
                });
            });

            options = options || {};
            var io = options.io || {
                    logRequest: function (r) { window.console.log('Mock Server Request: ', r); },
                    logResponse: function (r) { window.console.log('Mock Server Response: ', r); }
                };

            var observables = new dataSource.ObservableEntries(idSelector, observableStateTransitioner);
            var querier = {
                issue: function (query) {
                    io.logRequest(JSON.stringify({
                        predicate: query.predicate,
                        comparator: query.comparator,
                        offset: query.offset,
                        limit: query.limit,
                    }, stringifyReplacer, '  '));

                    return new Promise(function (resolve) {
                        window.setTimeout(function () {
                            var matching = entries.filter(query.predicate);
                            matching.sort(query.comparator);
                            var clipped = matching.slice(query.offset, query.offset + query.limit);

                            var result = {
                                unfilteredSize: entries.length,
                                filteredSize: matching.length,
                                values: clipped
                            };

                            if (options.computeStatistics) {
                                var statistics = {};
                                numericProperties.forEach(function (p) {
                                    statistics[p] = {'minimum': Number.POSITIVE_INFINITY, 'maximum': Number.NEGATIVE_INFINITY, 'sum': 0}
                                });
                                matching.forEach(function (e) {
                                    numericProperties.forEach(function (p) {
                                        var propertyStatistics = statistics[p];
                                        var v = e[p];
                                        propertyStatistics['minimum'] = Math.min(propertyStatistics['minimum'], v);
                                        propertyStatistics['maximum'] = Math.max(propertyStatistics['maximum'], v);
                                        propertyStatistics['sum'] += v;
                                    });
                                });

                                result.statistics = statistics;
                            }

                            io.logResponse(JSON.stringify(result, stringifyReplacer, '  '));

                            result.values = dataSource.streams.streamArray(clipped);
                            resolve(result);
                        }, options.latency || 500);
                    });
                }
            };
            return new dataSource.ServerSideDataSource(idSelector, querier, observables);
        };

        return clientSideDatSourceFactory;
    };
});
<|endoftext|>


<commit_before>import { monad_apply, chain, mjoin, pointMaker, equalMaker, stringMaker, valueOf } from '../data_structure_util';

function Validation(val) {
    return Object.create(validation, {
        _value: {
            value: val
        }
    });
}

Validation.of = function _of(val) {
    return Validation(val);
};

/**
 * @sig
 * @description d
 * @param {Object} f - a
 * @return {boolean} - b
 */
Validation.is = f => validation.isPrototypeOf(f);

var validation = {
    map: function _map(fn) {
        return this.of(fn(this.value));
    },
    of: pointMaker(Validation),
    valueOf: valueOf,
    toString: stringMaker('Validation'),
    factory: Validation
};

/**
 * @sig
 * @description d
 * @return {boolean} - a
 */
validation.equals = equalMaker(validation);

/**
 * @sig
 * @description Since the constant functor does not represent a disjunction, the Validation's
 * bimap function property behaves just as its map function property. It is merely here as a
 * convenience so that swapping out functors/monads does not break an application that is
 * relying on its existence.
 * @type {function}
 * @param {function} f - a
 * @param {function} g - b
 * @return {validation} - c
 */
validation.bimap = validation.map;

validation.chain = chain;
validation.mjoin = mjoin;
validation.apply = monad_apply;

//Since FantasyLand is the defacto standard for JavaScript algebraic data structures, and I want to maintain
//compliance with the standard, a .constructor property must be on the container delegators. In this case, its
//just an alias for the true .factory property, which points to the delegator factory. I am isolating this from
//the actual delegator itself as it encourages poor JavaScript development patterns and ... the myth of Javascript
//classes and inheritance. I do not recommend using the .constructor property at all since that just encourages
//FantasyLand and others to continue either not learning how JavaScript actually works, or refusing to use it
//as it was intended... you know, like Douglas Crockford and his "good parts", which is really just another
//way of saying: "your too dumb to understand how JavaScript works, and I either don't know myself, or don't
//care to know, so just stick with what I tell you to use."
validation.constructor = validation.factory;

export { Validation, validation };<commit_msg>develop: added refactored equals to validation data structure<commit_after>import { monad_apply, chain, mjoin, pointMaker, equals, stringMaker, valueOf } from '../data_structure_util';

function Validation(val) {
    return Object.create(validation, {
        _value: {
            value: val
        }
    });
}

Validation.of = function _of(val) {
    return Validation(val);
};

/**
 * @sig
 * @description d
 * @param {Object} f - a
 * @return {boolean} - b
 */
Validation.is = f => validation.isPrototypeOf(f);

var validation = {
    map: function _map(fn) {
        return this.of(fn(this.value));
    },
    of: pointMaker(Validation),
    valueOf: valueOf,
    equals: equals,
    toString: stringMaker('Validation'),
    factory: Validation
};

/**
 * @signature
 * @description Since the constant functor does not represent a disjunction, the Validation's
 * bimap function property behaves just as its map function property. It is merely here as a
 * convenience so that swapping out functors/monads does not break an application that is
 * relying on its existence.
 * @type {function}
 * @param {function} f - a
 * @param {function} g - b
 * @return {validation} - c
 */
validation.bimap = validation.map;

validation.chain = chain;
validation.mjoin = mjoin;
validation.apply = monad_apply;

//Since FantasyLand is the defacto standard for JavaScript algebraic data structures, and I want to maintain
//compliance with the standard, a .constructor property must be on the container delegators. In this case, its
//just an alias for the true .factory property, which points to the delegator factory. I am isolating this from
//the actual delegator itself as it encourages poor JavaScript development patterns and ... the myth of Javascript
//classes and inheritance. I do not recommend using the .constructor property at all since that just encourages
//FantasyLand and others to continue either not learning how JavaScript actually works, or refusing to use it
//as it was intended... you know, like Douglas Crockford and his "good parts", which is really just another
//way of saying: "your too dumb to understand how JavaScript works, and I either don't know myself, or don't
//care to know, so just stick with what I tell you to use."
validation.constructor = validation.factory;

export { Validation, validation };<|endoftext|>


<commit_before>var Tinkerforge = require('tinkerforge');

var config_json = require(require('os-homedir')() + '/.tf_config.json');

var HOST = config_json.host;
var PORT = parseInt(config_json.port);

var BARO = config_json.baro;
var HUMI = config_json.humi;
var LIGHT = config_json.light;

var ipcon = new Tinkerforge.IPConnection();
var al = new Tinkerforge.BrickletAmbientLight(LIGHT, ipcon);
var b = new Tinkerforge.BrickletBarometer(BARO, ipcon);
var h = new Tinkerforge.BrickletHumidity(HUMI, ipcon);

function tfinit() {
  /* istanbul ignore next */
  ipcon.connect(HOST, PORT,
    function(error) {
      if (error === 11) {
        console.log('Error: ALREADY CONNECTED');
      } else if (error === 12) {
        console.log('Error: NOT CONNECTED');
      } else if (error === 13) {
        console.log('Error: CONNECT FAILED');
      } else if (error === 21) {
        console.log('Error: INVALID FUNCTION ID');
      } else if (error === 31) {
        console.log('Error: TIMEOUT');
      } else if (error === 41) {
        console.log('Error: INVALID PARAMETER');
      } else if (error === 42) {
        console.log('Error: FUNCTION NOT SUPPORTED');
      } else {
        console.log('Error: UNKNOWN ERROR');
      }
      process.exit(1);
    }
  );
}

function tfdata() {
  /* istanbul ignore next */
  h.getHumidity(
    function(humidity) {
      var rh = humidity / 10;
      console.log('Relative Humidity: ' + rh + ' %RH');
    },
    function(error) {
      console.log('Relative Humidity: ' + 'Error ' + error);
    }
  );
  /* istanbul ignore next */
  b.getAirPressure(
    function(air_pressure) {
      var ap = air_pressure / 1000;
      console.log('Air pressure:      ' + ap + ' mbar');
    },
    function(error) {
      console.log('Air pressure: ' + 'Error ' + error);
    }
  );
  /* istanbul ignore next */
  b.getChipTemperature(
    function(temperature) {
      var temp = temperature / 100;
      console.log('Temperature:       ' + temp + ' \u00B0C');
    },
    function(error) {
      console.log('Temperature: ' + 'Error ' + error);
    }
  );
  /* istanbul ignore next */
  al.getIlluminance(
    function(illuminance) {
      var ilu = illuminance / 10;
      console.log('Illuminance:       ' + ilu + ' Lux');
    },
    function(error) {
      process.stdout.write('Illuminance: ' + 'Error ' + error);
    }
  );
}

function tfsimple() {
  tfinit();
  console.log("");
  ipcon.on(Tinkerforge.IPConnection.CALLBACK_CONNECTED,
    function(connectReason) {
      tfdata();
    }
  );
  setTimeout(function() {
    console.log("");
    process.exit();
  }, 500);
}

function tflive() {
  tfinit();
  end();
  var async = require('async');
  var WAIT = parseInt(config_json.wait);
  async.whilst(
    function() {
      return true;
    },
    function(callback) {

      console.log('\033[2J');
      tfdata();

      setTimeout(callback, WAIT);
    },
    function(err) {
      console.log("ERROR: " + err);
      process.exit();
    }
  );
}

function end() {
  process.stdin.on('data',
    function(data) {
      ipcon.disconnect();
      process.exit(0);
    }
  );
}

exports.tfsimple = tfsimple;
exports.tflive = tflive;
<commit_msg>:arrow_up: coverage<commit_after>var Tinkerforge = require('tinkerforge');

var config_json = require(require('os-homedir')() + '/.tf_config.json');

var HOST = config_json.host;
var PORT = parseInt(config_json.port);

var BARO = config_json.baro;
var HUMI = config_json.humi;
var LIGHT = config_json.light;

var ipcon = new Tinkerforge.IPConnection();
var al = new Tinkerforge.BrickletAmbientLight(LIGHT, ipcon);
var b = new Tinkerforge.BrickletBarometer(BARO, ipcon);
var h = new Tinkerforge.BrickletHumidity(HUMI, ipcon);

function tfinit() {
  /* istanbul ignore next */
  ipcon.connect(HOST, PORT,
    function(error) {
      if (error === 11) {
        console.log('Error: ALREADY CONNECTED');
      } else if (error === 12) {
        console.log('Error: NOT CONNECTED');
      } else if (error === 13) {
        console.log('Error: CONNECT FAILED');
      } else if (error === 21) {
        console.log('Error: INVALID FUNCTION ID');
      } else if (error === 31) {
        console.log('Error: TIMEOUT');
      } else if (error === 41) {
        console.log('Error: INVALID PARAMETER');
      } else if (error === 42) {
        console.log('Error: FUNCTION NOT SUPPORTED');
      } else {
        console.log('Error: UNKNOWN ERROR');
      }
      process.exit(1);
    }
  );
}
/* istanbul ignore next */
function tfdata() {
  h.getHumidity(
    function(humidity) {
      var rh = humidity / 10;
      console.log('Relative Humidity: ' + rh + ' %RH');
    },
    function(error) {
      console.log('Relative Humidity: ' + 'Error ' + error);
    }
  );
  b.getAirPressure(
    function(air_pressure) {
      var ap = air_pressure / 1000;
      console.log('Air pressure:      ' + ap + ' mbar');
    },
    function(error) {
      console.log('Air pressure: ' + 'Error ' + error);
    }
  );
  b.getChipTemperature(
    function(temperature) {
      var temp = temperature / 100;
      console.log('Temperature:       ' + temp + ' \u00B0C');
    },
    function(error) {
      console.log('Temperature: ' + 'Error ' + error);
    }
  );
  al.getIlluminance(
    function(illuminance) {
      var ilu = illuminance / 10;
      console.log('Illuminance:       ' + ilu + ' Lux');
    },
    function(error) {
      process.stdout.write('Illuminance: ' + 'Error ' + error);
    }
  );
}
/* istanbul ignore next */
function tfsimple() {
  tfinit();
  console.log("");
  ipcon.on(Tinkerforge.IPConnection.CALLBACK_CONNECTED,
    function(connectReason) {
      tfdata();
    }
  );
  setTimeout(function() {
    console.log("");
    process.exit();
  }, 500);
}
/* istanbul ignore next */
function tflive() {
  tfinit();
  end();
  var async = require('async');
  var WAIT = parseInt(config_json.wait);
  async.whilst(
    function() {
      return true;
    },
    function(callback) {

      console.log('\033[2J');
      tfdata();

      setTimeout(callback, WAIT);
    },
    function(err) {
      console.log("ERROR: " + err);
      process.exit();
    }
  );
}
/* istanbul ignore next */
function end() {
  process.stdin.on('data',
    function(data) {
      ipcon.disconnect();
      process.exit(0);
    }
  );
}

exports.tfsimple = tfsimple;
exports.tflive = tflive;
<|endoftext|>


<commit_before>/**
 * System configuration for Angular 2 samples
 * Adjust as necessary for your application needs.
 */
(function(global) {
  // map tells the System loader where to look for things
  var map = {
    'app':                        'app', // 'site',
    '@angular':                   'assets/lib/@angular',
    'angular2-in-memory-web-api': 'assets/lib/angular2-in-memory-web-api',
    'rxjs':                       'assets/lib/rxjs',
    'partials':                   'templates/partials',
    'css'                      'assets/css'
  };
  // packages tells the System loader how to load when no filename and/or no extension
  var packages = {
    'app':                        { main: 'main.js',  defaultExtension: 'js' },
    'rxjs':                       { defaultExtension: 'js' },
    'angular2-in-memory-web-api': { main: 'index.js', defaultExtension: 'js' },
  };
  var ngPackageNames = [
    'common',
    'compiler',
    'core',
    'forms',
    'http',
    'platform-browser',
    'platform-browser-dynamic',
    'router',
    'router-deprecated',
    'upgrade',
  ];
  // Individual files (~300 requests):
  function packIndex(pkgName) {
    packages['@angular/'+pkgName] = { main: 'index.js', defaultExtension: 'js' };
  }
  // Bundled (~40 requests):
  function packUmd(pkgName) {
    packages['@angular/'+pkgName] = { main: 'bundles/' + pkgName + '.umd.js', defaultExtension: 'js' };
  }
  // Most environments should use UMD; some (Karma) need the individual index files
  var setPackageConfig = System.packageWithIndex ? packIndex : packUmd;
  // Add package entries for angular packages
  ngPackageNames.forEach(setPackageConfig);
  var config = {
    map: map,
    packages: packages
  };
  System.config(config);
})(this);

<commit_msg>Update systemjs.config.js<commit_after>/**
 * System configuration for Angular 2 samples
 * Adjust as necessary for your application needs.
 */
(function(global) {
  // map tells the System loader where to look for things
  var map = {
    'app':                        'app', // 'site',
    '@angular':                   'assets/lib/@angular',
    'angular2-in-memory-web-api': 'assets/lib/angular2-in-memory-web-api',
    'rxjs':                       'assets/lib/rxjs',
    'partials':                   'templates/partials',
    'assets'                      'assets'
  };
  // packages tells the System loader how to load when no filename and/or no extension
  var packages = {
    'app':                        { main: 'main.js',  defaultExtension: 'js' },
    'rxjs':                       { defaultExtension: 'js' },
    'angular2-in-memory-web-api': { main: 'index.js', defaultExtension: 'js' },
  };
  var ngPackageNames = [
    'common',
    'compiler',
    'core',
    'forms',
    'http',
    'platform-browser',
    'platform-browser-dynamic',
    'router',
    'router-deprecated',
    'upgrade',
  ];
  // Individual files (~300 requests):
  function packIndex(pkgName) {
    packages['@angular/'+pkgName] = { main: 'index.js', defaultExtension: 'js' };
  }
  // Bundled (~40 requests):
  function packUmd(pkgName) {
    packages['@angular/'+pkgName] = { main: 'bundles/' + pkgName + '.umd.js', defaultExtension: 'js' };
  }
  // Most environments should use UMD; some (Karma) need the individual index files
  var setPackageConfig = System.packageWithIndex ? packIndex : packUmd;
  // Add package entries for angular packages
  ngPackageNames.forEach(setPackageConfig);
  var config = {
    map: map,
    packages: packages
  };
  System.config(config);
})(this);

<|endoftext|>


<commit_before>var http     = require('http'),
    fs       = require('fs'),
    path     = require('path'),
    spawn    = require('child_process').spawn,
    express  = require('express'),
    pod      = require('../lib/api'),
    ghURL    = require('parse-github-url'),
    app      = express()

// late def, wait until pod is ready
var conf

// middlewares
var reloadConf = function (req, res, next) {
    conf = pod.reloadConfig()
    next()
}

var auth = express.basicAuth(function (user, pass) {
    var u = conf.web.username || 'admin',
        p = conf.web.password || 'admin'
    return user === u && pass === p
})

app.configure(function(){
    app.set('views', __dirname + '/views')
    app.set('view engine', 'ejs')
    app.use(express.favicon())
    app.use(reloadConf)
    app.use(app.router)
    app.use(express.static(path.join(__dirname, 'static')))
})

app.get('/', auth, function (req, res) {
    pod.listApps(function (err, list) {
        if (err) return res.end(err)
        res.render('index', {
            apps: list
        })
    })
})

app.get('/json', auth, function (req, res) {
    pod.listApps(function (err, list) {
        if (err) return res.end(err)
        res.json(list)
    })
})

app.post('/hooks/:appid', express.bodyParser(), function (req, res) {
    var appid = req.params.appid,
        payload = JSON.stringify(req.body),
        app = conf.apps[appid]

    try {
        payload = JSON.parse(payload)
    } catch (e) {
        return res.end(e.toString())
    }

    if (app && verify(req, app, payload)) {
        executeHook(appid, app, payload, function () {
            res.end()
        })
    } else {
        res.end()
    }
})

// listen when API is ready
pod.once('ready', function () {
    // load config first
    conf = pod.getConfig()
    // conditional open up jsonp based on config
    if (conf.web.jsonp === true) {
        app.get('/jsonp', function (req, res) {
            pod.listApps(function (err, list) {
                if (err) return res.end(err)
                res.jsonp(list)
            })
        })
    }
    app.listen(process.env.PORT || 19999)
})

// Helpers
function verify (req, app, payload) {
    // not even a remote app
    if (!app.remote) return
    // check repo match

    var repo = payload.repository

    // console.error(repo.links.html.href)

    if (/bitbucket\.org/.test(repo.links.html.href)) {
        console.log('\nreceived webhook request from: ' + repo.links.html.href)
    } else {
        console.log('\nreceived webhook request from: ' + repo.url)
    }

    var repoURL = repo.links.html.href ? repo.links.html.href : repo.url

    if (ghURL(repoURL).repopath !== ghURL(app.remote).repopath) {
        console.log('aborted.')
        return
    }

    var commit

    // support bitbucket webhooks payload structure
    if (/bitbucket\.org/.test(repoURL)) {
        commit = payload.push.changes[0].new

        commit.message = commit.target.message
    } else {
        // use gitlab's payload structure if detected
        commit = payload.head_commit ? payload.head_commit :
            payload.commits[payload.commits.length - 1];
    }

    // skip it with [pod skip] message
    console.log('commit message: ' + commit.message)
    if (/\[pod skip\]/.test(commit.message)) {
        console.log('aborted.')
        return
    }
    // check branch match
    var ref = commit.name ? commit.name : payload.ref

    var branch = ref.replace('refs/heads/', ''),
        expected = app.branch || 'master'
    console.log('expected branch: ' + expected + ', got branch: ' + branch)
    if (branch !== expected) {
        console.log('aborted.')
        return
    }
    return true
}

function executeHook (appid, app, payload, cb) {

    // set a response timeout to avoid GitHub webhooks
    // hanging up due to long build times
    var responded = false
    function respond (err) {
        if (!responded) {
            responded = true
            cb(err)
        }
    }
    setTimeout(respond, 3000)

    fs.readFile(path.resolve(__dirname, '../hooks/post-receive'), 'utf-8', function (err, template) {
        if (err) return respond(err)
        var hookPath = conf.root + '/temphook.sh',
            hook = template
                .replace(/\{\{pod_dir\}\}/g, conf.root)
                .replace(/\{\{app\}\}/g, appid)
        if (app.branch) {
            hook = hook.replace('origin/master', 'origin/' + app.branch)
        }
        fs.writeFile(hookPath, hook, function (err) {
            if (err) return respond(err)
            fs.chmod(hookPath, '0777', function (err) {
                if (err) return respond(err)
                console.log('excuting github webhook for ' + appid + '...')
                var child = spawn('bash', [hookPath])
                child.stdout.pipe(process.stdout)
                child.stderr.pipe(process.stderr)
                child.on('exit', function (code) {
                    fs.unlink(hookPath, respond)
                })
            })
        })
    })
}
<commit_msg>Fixed issue with Github webhooks failing due to a non-existent path. All tests pass.<commit_after>var http     = require('http'),
    fs       = require('fs'),
    path     = require('path'),
    spawn    = require('child_process').spawn,
    express  = require('express'),
    pod      = require('../lib/api'),
    ghURL    = require('parse-github-url'),
    app      = express()

// late def, wait until pod is ready
var conf

// middlewares
var reloadConf = function (req, res, next) {
    conf = pod.reloadConfig()
    next()
}

var auth = express.basicAuth(function (user, pass) {
    var u = conf.web.username || 'admin',
        p = conf.web.password || 'admin'
    return user === u && pass === p
})

app.configure(function(){
    app.set('views', __dirname + '/views')
    app.set('view engine', 'ejs')
    app.use(express.favicon())
    app.use(reloadConf)
    app.use(app.router)
    app.use(express.static(path.join(__dirname, 'static')))
})

app.get('/', auth, function (req, res) {
    pod.listApps(function (err, list) {
        if (err) return res.end(err)
        res.render('index', {
            apps: list
        })
    })
})

app.get('/json', auth, function (req, res) {
    pod.listApps(function (err, list) {
        if (err) return res.end(err)
        res.json(list)
    })
})

app.post('/hooks/:appid', express.bodyParser(), function (req, res) {
    var appid = req.params.appid,
        payload = JSON.stringify(req.body),
        app = conf.apps[appid]

    try {
        payload = JSON.parse(payload)
    } catch (e) {
        return res.end(e.toString())
    }

    if (app && verify(req, app, payload)) {
        executeHook(appid, app, payload, function () {
            res.end()
        })
    } else {
        res.end()
    }
})

// listen when API is ready
pod.once('ready', function () {
    // load config first
    conf = pod.getConfig()
    // conditional open up jsonp based on config
    if (conf.web.jsonp === true) {
        app.get('/jsonp', function (req, res) {
            pod.listApps(function (err, list) {
                if (err) return res.end(err)
                res.jsonp(list)
            })
        })
    }
    app.listen(process.env.PORT || 19999)
})

// Helpers
function verify (req, app, payload) {
    // not even a remote app
    if (!app.remote) return
    // check repo match

    var repo = payload.repository
    var repoURL

    if (repo.links && /bitbucket\.org/.test(repo.links.html.href)) {
        console.log('\nreceived webhook request from: ' + repo.links.html.href)

        repoURL = repo.links.html.href
    } else {
        console.log('\nreceived webhook request from: ' + repo.url)

        repoURL = repo.url
    }

    if (!repoURL) return

    if (ghURL(repoURL).repopath !== ghURL(app.remote).repopath) {
        console.log('aborted.')
        return
    }

    var commit

    // support bitbucket webhooks payload structure
    if (/bitbucket\.org/.test(repoURL)) {
        commit = payload.push.changes[0].new

        commit.message = commit.target.message
    } else {
        // use gitlab's payload structure if detected
        commit = payload.head_commit ? payload.head_commit :
            payload.commits[payload.commits.length - 1];
    }

    if (!commit) return

    // skip it with [pod skip] message
    console.log('commit message: ' + commit.message)
    if (/\[pod skip\]/.test(commit.message)) {
        console.log('aborted.')
        return
    }
    // check branch match
    var ref = commit.name ? commit.name : payload.ref

    if (!ref) return

    var branch = ref.replace('refs/heads/', ''),
        expected = app.branch || 'master'
    console.log('expected branch: ' + expected + ', got branch: ' + branch)
    if (branch !== expected) {
        console.log('aborted.')
        return
    }
    return true
}

function executeHook (appid, app, payload, cb) {

    // set a response timeout to avoid GitHub webhooks
    // hanging up due to long build times
    var responded = false
    function respond (err) {
        if (!responded) {
            responded = true
            cb(err)
        }
    }
    setTimeout(respond, 3000)

    fs.readFile(path.resolve(__dirname, '../hooks/post-receive'), 'utf-8', function (err, template) {
        if (err) return respond(err)
        var hookPath = conf.root + '/temphook.sh',
            hook = template
                .replace(/\{\{pod_dir\}\}/g, conf.root)
                .replace(/\{\{app\}\}/g, appid)
        if (app.branch) {
            hook = hook.replace('origin/master', 'origin/' + app.branch)
        }
        fs.writeFile(hookPath, hook, function (err) {
            if (err) return respond(err)
            fs.chmod(hookPath, '0777', function (err) {
                if (err) return respond(err)
                console.log('excuting github webhook for ' + appid + '...')
                var child = spawn('bash', [hookPath])
                child.stdout.pipe(process.stdout)
                child.stderr.pipe(process.stderr)
                child.on('exit', function (code) {
                    fs.unlink(hookPath, respond)
                })
            })
        })
    })
}
<|endoftext|>


<commit_before>var Lang = A.Lang,
	UA = A.UA,
	getClassName = A.getClassName,

	NAME = 'video',

	CSS_VIDEO = getClassName(NAME),
	CSS_VIDEO_NODE = getClassName(NAME, 'node'),

	DEFAULT_PLAYER_PATH = A.config.base + 'aui-video/assets/player.swf',

	DOC = A.config.doc,

	TPL_VIDEO = '<video id="{0}" width="100%" height="100%" controls="controls" class="' + CSS_VIDEO_NODE + '"></video>',
	TPL_VIDEO_FALLBACK = '

';

var Video = A.Component.create(
	{
		NAME: NAME,

		ATTRS: {
			url: {
				value: ''
			},
			ogvUrl: {
				value: ''
			},
			swfUrl: {
				value: DEFAULT_PLAYER_PATH
			},
			poster: {
				value: ''
			},
			fixedAttributes: {
				value: {}
			},
			flashVars: {
				value: {}
			},
			render: {
				value: true
			}
		},

		BIND_UI_ATTRS: ['url', 'poster', 'ogvUrl', 'swfUrl', 'fixedAttributes', 'flashVars'],
		SYNC_UI_ATTRS: ['url', 'poster', 'ogvUrl'],

		prototype: {
			renderUI: function () {
				var instance = this;

				instance._renderVideoTask = A.debounce(instance._renderVideo, 1, instance);
				instance._renderSwfTask = A.debounce(instance._renderSwf, 1, instance);

				instance._renderVideo(!instance.get('ogvUrl'));
			},

			bindUI: function () {
				var instance = this;

				instance.publish(
					'videoReady',
					{
						fireOnce: true
					}
				);
			},

			_createSource: function(type) {
				var instance = this;

				var sourceNode = new A.Node(DOC.createElement('source'));

				sourceNode.attr('type', type);

				return sourceNode;
			},

			_renderSwf: function () {
				var instance = this;

				var swfUrl = instance.get('swfUrl');

				if (swfUrl) {
					var videoUrl = instance.get('url');
					var posterUrl = instance.get('poster');
					var flashVars = instance.get('flashVars');

					A.mix(
						flashVars,
						{
							controls: true,
							src: videoUrl,
							poster: posterUrl
						}
					);

					var flashVarString = A.QueryString.stringify(flashVars);

					if (instance._swfId) {
						instance._video.removeChild(A.one('#' + instance._swfId));
					}
					else {
						instance._swfId = A.guid();
					}

					var tplObj = '<object id="' + instance._swfId + '" ';

					if (UA.ie) {
						tplObj += 'classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" ';
					}
					else {
						tplObj += 'type="application/x-shockwave-flash" data="' + swfUrl + '" ';
					}

					tplObj += 'height="100%" width="100%">';

					if (UA.ie) {
						tplObj += '<param name="movie" value="' + swfUrl + '"/>';
					}

					var fixedAttributes = instance.get('fixedAttributes');

					for (var i in fixedAttributes) {
						tplObj += '<param name="' + i + '" value="' + fixedAttributes[i] + '" />';
					}

					if (flashVarString) {
						tplObj += '<param name="flashVars" value="' + flashVarString + '" />';
					}

					if (posterUrl != '') {
						tplObj += '';
					}

					tplObj += '</object>';

					instance._video.append(tplObj);
				}
			},

			_renderVideo: function(fallback) {
				var instance = this;

				var tpl = TPL_VIDEO;

				if (UA.gecko && fallback) {
					tpl = TPL_VIDEO_FALLBACK;
				}

				var tplObj = Lang.sub(tpl, [A.guid()]);

				var video = A.Node.create(tplObj);

				instance.get('contentBox').append(video);

				instance._video = video;
			},

			_uiSetFixedAttributes: function (val) {
				var instance = this;

				instance._renderSwfTask();
			},

			_uiSetFlashVars: function (val) {
				var instance = this;

				instance._renderSwfTask();
			},

			_uiSetOgvUrl: function (val) {
				var instance = this;

				if (UA.gecko) {
					var video = instance._video;

					var usingVideo = instance._usingVideo();

					if ((!val && usingVideo) || (val && !usingVideo)) {
						video.remove(true);

						instance._renderVideoTask(!val);
					}

					if (!val) {
						instance._renderSwfTask();
					}
					else {
						var sourceOgv = instance._sourceOgv;

						if (!sourceOgv) {
							sourceOgv = instance._createSource('video/ogg; codecs="theora, vorbis"');

							video.append(sourceOgv);

							instance._sourceOgv = sourceOgv;
						}

						sourceOgv.attr('src', val);
					}
				}
			},

			_uiSetPoster: function (val) {
				var instance = this;

				var video = instance._video;

				if (instance._usingVideo()) {
					video.setAttribute('poster', val);
				}

				instance._renderSwfTask();
			},

			_uiSetSwfUrl: function (val) {
				var instance = this;

				instance._renderSwfTask();
			},

			_uiSetUrl: function (val) {
				var instance = this;

				var ogvUrl = instance.get('ogvUrl');
				var video = instance._video;

				var sourceMp4 = instance._sourceMp4;

				if (UA.gecko && !instance._usingVideo()) {
					if (sourceMp4 != null) {
						sourceMp4.remove(true);

						instance._sourceMp4 = null;
					}
				}
				else
				{
					if (video || !ogvUrl) {
						if (!sourceMp4) {
							sourceMp4 = instance._createSource('video/mp4;');

							video.append(sourceMp4);

							instance._sourceMp4 = sourceMp4;
						}

						sourceMp4.attr('src', val);
					}
				}

				instance._renderSwfTask();
			},

			_usingVideo: function() {
				var instance = this;

				return (instance._video.get('nodeName').toLowerCase() == 'video');
			}
		}
	}
);

A.Video = Video;<commit_msg>AUI-573 - create source element for Ogg in case of Opera<commit_after>var Lang = A.Lang,
	UA = A.UA,
	getClassName = A.getClassName,

	NAME = 'video',

	CSS_VIDEO = getClassName(NAME),
	CSS_VIDEO_NODE = getClassName(NAME, 'node'),

	DEFAULT_PLAYER_PATH = A.config.base + 'aui-video/assets/player.swf',

	DOC = A.config.doc,

	TPL_VIDEO = '<video id="{0}" width="100%" height="100%" controls="controls" class="' + CSS_VIDEO_NODE + '"></video>',
	TPL_VIDEO_FALLBACK = '

';

var Video = A.Component.create(
	{
		NAME: NAME,

		ATTRS: {
			url: {
				value: ''
			},
			ogvUrl: {
				value: ''
			},
			swfUrl: {
				value: DEFAULT_PLAYER_PATH
			},
			poster: {
				value: ''
			},
			fixedAttributes: {
				value: {}
			},
			flashVars: {
				value: {}
			},
			render: {
				value: true
			}
		},

		BIND_UI_ATTRS: ['url', 'poster', 'ogvUrl', 'swfUrl', 'fixedAttributes', 'flashVars'],
		SYNC_UI_ATTRS: ['url', 'poster', 'ogvUrl'],

		prototype: {
			renderUI: function () {
				var instance = this;

				instance._renderVideoTask = A.debounce(instance._renderVideo, 1, instance);
				instance._renderSwfTask = A.debounce(instance._renderSwf, 1, instance);

				instance._renderVideo(!instance.get('ogvUrl'));
			},

			bindUI: function () {
				var instance = this;

				instance.publish(
					'videoReady',
					{
						fireOnce: true
					}
				);
			},

			_createSource: function(type) {
				var instance = this;

				var sourceNode = new A.Node(DOC.createElement('source'));

				sourceNode.attr('type', type);

				return sourceNode;
			},

			_renderSwf: function () {
				var instance = this;

				var swfUrl = instance.get('swfUrl');

				if (swfUrl) {
					var videoUrl = instance.get('url');
					var posterUrl = instance.get('poster');
					var flashVars = instance.get('flashVars');

					A.mix(
						flashVars,
						{
							controls: true,
							src: videoUrl,
							poster: posterUrl
						}
					);

					var flashVarString = A.QueryString.stringify(flashVars);

					if (instance._swfId) {
						instance._video.removeChild(A.one('#' + instance._swfId));
					}
					else {
						instance._swfId = A.guid();
					}

					var tplObj = '<object id="' + instance._swfId + '" ';

					if (UA.ie) {
						tplObj += 'classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" ';
					}
					else {
						tplObj += 'type="application/x-shockwave-flash" data="' + swfUrl + '" ';
					}

					tplObj += 'height="100%" width="100%">';

					if (UA.ie) {
						tplObj += '<param name="movie" value="' + swfUrl + '"/>';
					}

					var fixedAttributes = instance.get('fixedAttributes');

					for (var i in fixedAttributes) {
						tplObj += '<param name="' + i + '" value="' + fixedAttributes[i] + '" />';
					}

					if (flashVarString) {
						tplObj += '<param name="flashVars" value="' + flashVarString + '" />';
					}

					if (posterUrl != '') {
						tplObj += '';
					}

					tplObj += '</object>';

					instance._video.append(tplObj);
				}
			},

			_renderVideo: function(fallback) {
				var instance = this;

				var tpl = TPL_VIDEO;

				if (UA.gecko && fallback) {
					tpl = TPL_VIDEO_FALLBACK;
				}

				var tplObj = Lang.sub(tpl, [A.guid()]);

				var video = A.Node.create(tplObj);

				instance.get('contentBox').append(video);

				instance._video = video;
			},

			_uiSetFixedAttributes: function (val) {
				var instance = this;

				instance._renderSwfTask();
			},

			_uiSetFlashVars: function (val) {
				var instance = this;

				instance._renderSwfTask();
			},

			_uiSetOgvUrl: function (val) {
				var instance = this;

				if (UA.gecko || UA.opera) {
					var video = instance._video;

					var usingVideo = instance._usingVideo();

					if ((!val && usingVideo) || (val && !usingVideo)) {
						video.remove(true);

						instance._renderVideoTask(!val);
					}

					if (!val) {
						instance._renderSwfTask();
					}
					else {
						var sourceOgv = instance._sourceOgv;

						if (!sourceOgv) {
							sourceOgv = instance._createSource('video/ogg; codecs="theora, vorbis"');

							video.append(sourceOgv);

							instance._sourceOgv = sourceOgv;
						}

						sourceOgv.attr('src', val);
					}
				}
			},

			_uiSetPoster: function (val) {
				var instance = this;

				var video = instance._video;

				if (instance._usingVideo()) {
					video.setAttribute('poster', val);
				}

				instance._renderSwfTask();
			},

			_uiSetSwfUrl: function (val) {
				var instance = this;

				instance._renderSwfTask();
			},

			_uiSetUrl: function (val) {
				var instance = this;

				var ogvUrl = instance.get('ogvUrl');
				var video = instance._video;

				var sourceMp4 = instance._sourceMp4;

				if (UA.gecko && !instance._usingVideo()) {
					if (sourceMp4 != null) {
						sourceMp4.remove(true);

						instance._sourceMp4 = null;
					}
				}
				else
				{
					if (video || !ogvUrl) {
						if (!sourceMp4) {
							sourceMp4 = instance._createSource('video/mp4;');

							video.append(sourceMp4);

							instance._sourceMp4 = sourceMp4;
						}

						sourceMp4.attr('src', val);
					}
				}

				instance._renderSwfTask();
			},

			_usingVideo: function() {
				var instance = this;

				return (instance._video.get('nodeName').toLowerCase() == 'video');
			}
		}
	}
);

A.Video = Video;<|endoftext|>