<commit_before>import React, { Component, PropTypes } from 'react';
import bowser from 'bowser';
import classNames from 'classnames';
import THREE from 'three';
import TWEEN from 'tween.js';
import Stats from 'stats.js';
import lodashThrottle from 'lodash/throttle';
import lodashIsEqual from 'lodash/isEqual';

import { makeRadiansPositive, randomWithRange, simplifyAngle } from '../../businessLogic/mathHelpers';
import { averageRGB,
         currentColorInTween,
         getColorFromPosition,
         mergeTopAndBottomColors,
         randomRGB } from '../../businessLogic/threeHelpers';

import './orthofloat.scss';

export default class Orthofloat extends Component {
    constructor(props) {
        super(props);

        this.state = {
            windowHeight: window.innerHeight,
            windowWidth: window.innerWidth
        };
    }

    componentWillMount() {
        this.setVendorPrefix();
        this.stripeWidth = 25;
        this.tweenLength = 2000;
    }

    componentDidMount() {
        this.initializeScene();

        this.windowResizeFunc = lodashThrottle(() => this.onWindowResize(), 16.667);
        window.addEventListener('resize', this.windowResizeFunc);
    }

    componentWillReceiveProps(nextProps) {
        if (!lodashIsEqual(nextProps.bottomColor, this.props.bottomColor)
            || !lodashIsEqual(nextProps.topColor, this.props.topColor)) {
            this.changeColors(nextProps.topColor, nextProps.bottomColor);
        }
    }

    componentWillUnmount() {
        window.removeEventListener('resize', this.windowResizeFunc);
    }

    changeColors(nextTopColor, nextBottomColor) {
        const { randomShapeMaterialBottom, randomShapeMaterialTop, randomShapeMaterialMid } = this;
        const oldColors = mergeTopAndBottomColors(this.props.topColor, this.props.bottomColor);
        const newColors = mergeTopAndBottomColors(nextTopColor, nextBottomColor);

        const tween = new TWEEN.Tween(oldColors)
            .to(newColors, this.tweenLength)
            .easing(TWEEN.Easing.Quadratic.Out)
            .onUpdate(function() {
                randomShapeMaterialBottom.color = currentColorInTween(this, 'bottom');
                randomShapeMaterialTop.color = currentColorInTween(this, 'top');

                randomShapeMaterialMid.color = averageRGB(
                    randomShapeMaterialBottom.color,
                    randomShapeMaterialTop.color
                );
            })
            .start();
    }

    initializeScene() {
        this.scene = new THREE.Scene();

        this.initializeCamera();
        this.initializeMeshes();
        this.initializeLights();
        this.initializeRenderer();

        if (this.props.initializeWithStats) {
            this.initializeStats();
        }

        this.renderAnimation();
    }

    initializeCamera() {
        const { windowHeight, windowWidth } = this.state;
        this.camFactor = 16;
        this.camera = new THREE.OrthographicCamera(
            windowWidth / - this.camFactor,
            windowWidth / this.camFactor,
            windowHeight / this.camFactor,
            windowHeight / - this.camFactor,
            -200,
            500
        );
        this.camera.position.x = 120;
        this.camera.lookAt(this.scene.position);
    }

    initializeMeshes() {
        this.meshSize = 2.5;
        this.initializeRandomShapes();
        this.initializeTetrahedrons();
    }

    initializeRandomShapes() {
        const { bottomColor, topColor } = this.props;
        const threeTopColor = new THREE.Color(topColor.r, topColor.g, topColor.b);
        const threeBottomColor = new THREE.Color(bottomColor.r, bottomColor.g, bottomColor.b);
        this.randomShapeMaterialTop = new THREE.MeshBasicMaterial({ color: threeTopColor });
        this.randomShapeMaterialBottom = new THREE.MeshBasicMaterial({ color: threeBottomColor });
        const averageColor = averageRGB(this.randomShapeMaterialTop.color, this.randomShapeMaterialBottom.color);
        this.randomShapeMaterialMid = new THREE.MeshBasicMaterial({
            color: new THREE.Color(averageColor.r, averageColor.g, averageColor.b)
        });
        this.randomShapes = [];
        for (let i = 0; i < 53; i++) {
            let shape;
            switch (i % 5) {
                case 0:
                    shape = new THREE.Mesh(this.generateRandomGeometry(), this.randomShapeMaterialTop);
                    break;
                case 1:
                    shape = new THREE.Mesh(this.generateRandomGeometry(), this.randomShapeMaterialBottom);
                    break;
                case 2:
                    shape = new THREE.Mesh(this.generateRandomGeometry(), this.randomShapeMaterialMid);
                    break;
                case 3:
                    shape = new THREE.Mesh(
                        this.generateRandomGeometry(),
                        new THREE.MeshBasicMaterial({ color: threeTopColor })
                    );
                    shape.colorTopToBottom = true;
                    break;
                case 4:
                default:
                    shape = new THREE.Mesh(
                        this.generateRandomGeometry(),
                        new THREE.MeshBasicMaterial({ color: threeBottomColor })
                    );
                    shape.colorBottomToTop = true;
            }
            this.setMeshInSpace(shape);
            this.randomShapes.push(shape);
            this.scene.add(shape);
        }
    }

    generateRandomGeometry() {
        const meshSize = randomWithRange(0.25, 2) * this.meshSize;
        const cylRadius = randomWithRange(meshSize / 2, meshSize);

        switch (Math.floor(Math.random() * 11)) {
            case 10:
                return new THREE.TorusKnotGeometry(
                    meshSize, meshSize / 3, 32, 12, randomWithRange(1, 7), randomWithRange(1, 10)
                );
            case 9:
                return new THREE.TorusGeometry(
                    meshSize, meshSize / 4, 16, 16, randomWithRange(Math.PI / 2, Math.PI * 3)
                );
            case 8:
                return new THREE.SphereGeometry(
                    meshSize,
                    16,
                    16,
                    0,
                    randomWithRange(Math.PI / 2, Math.PI * 3),
                    0,
                    randomWithRange(Math.PI / 2, Math.PI)
                );
            case 7:
                return new THREE.RingGeometry(
                    meshSize / 2, meshSize, 16, 1, 0, randomWithRange(Math.PI / 2, Math.PI * 3)
                );
            case 6:
                return new THREE.PlaneGeometry(meshSize, meshSize, 1, 1);
            case 5:
                return new THREE.OctahedronGeometry(meshSize, 0);
            case 4:
                return new THREE.IcosahedronGeometry(meshSize, 0);
            case 3:
                return new THREE.DodecahedronGeometry(meshSize, 0);
            case 2:
                return new THREE.CylinderGeometry(
                    cylRadius,
                    cylRadius,
                    randomWithRange(meshSize / 2, meshSize * 1.5),
                    16,
                    1,
                    Math.random() < 0.5,
                    0,
                    randomWithRange(Math.PI / 2, Math.PI * 3)
                );
            case 1:
                return new THREE.CircleGeometry(meshSize, 16);
            case 0:
            default:
                return new THREE.BoxGeometry(meshSize, meshSize, meshSize);
        }
    }

    initializeTetrahedrons() {
        const tetraGeometry = new THREE.TetrahedronGeometry(this.meshSize);
        const color = new THREE.Color(0xff6ba9);
        const tetraMaterial = new THREE.MeshBasicMaterial({color});
        this.tetras = [];
        for (let i = 0; i < 50; i++) {
            const tetra = new THREE.Mesh(tetraGeometry, tetraMaterial);
            this.setMeshInSpace(tetra);
            this.tetras.push(tetra);
            this.scene.add(tetra);
        }
    }

    setMeshInSpace(mesh) {
        const { windowHeight, windowWidth } = this.state;
        mesh.position.x = randomWithRange(windowWidth / 16, windowWidth / -16);
        mesh.position.y = randomWithRange(windowHeight / 16, windowHeight / -16);
        mesh.position.z = randomWithRange(windowWidth / 16, windowWidth / -16);
        mesh.rotation.set(randomWithRange(0, Math.PI), randomWithRange(0, Math.PI), randomWithRange(0, Math.PI));
        mesh.rotationSpeed = {
            x: randomWithRange(-0.01, 0.01),
            y: randomWithRange(-0.01, 0.01),
            z: randomWithRange(-0.01, 0.01)
        };

        this.assignMeshVelocities(mesh);
    }

    assignMeshVelocities(mesh) {
        mesh.xVelocity = randomWithRange(-0.01, 0.01);
        mesh.yVelocity = randomWithRange(0.03, 0.1);
        mesh.zVelocity = randomWithRange(-0.01, 0.01);
    }

    initializeLights() {
        const directionalLight = new THREE.DirectionalLight( 0xffffff, 0.7 );
        directionalLight.position.set(60, 60, 60);
        this.scene.add(directionalLight);

        const ambientLight = new THREE.AmbientLight(0x4B4B4B);
        this.scene.add(ambientLight);
    }

    initializeRenderer() {
        const { windowHeight, windowWidth } = this.state;
        this.renderer = new THREE.WebGLRenderer({ alpha: true });
        this.renderer.setSize(windowWidth, windowHeight);

        this.el.appendChild(this.renderer.domElement);
        this.renderer.render(this.scene, this.camera);
    }

    initializeStats() {
        this.stats = new Stats();
        this.el.appendChild(this.stats.dom);
    }

    setVendorPrefix() {
        if (bowser.webkit) {
            this.vendorPrefix = '-webkit-';
        } else if (bowser.firefox) {
            this.vendorPrefix = '-moz-';
        } else if (bowser.opera) {
            this.vendorPrefix = '-o-';
        } else {
            this.vendorPrefix = '';
        }
    }

    onWindowResize() {
        const windowHeight = window.innerHeight,
              windowWidth = window.innerWidth;

        this.setState({ windowHeight, windowWidth });

        this.renderer.setSize(windowWidth, windowHeight);

        this.camera.left = windowWidth / -this.camFactor;
        this.camera.right = windowWidth / this.camFactor;
        this.camera.top = windowHeight / this.camFactor;
        this.camera.bottom = windowHeight / -this.camFactor;
        this.camera.updateProjectionMatrix();
    }

    moveCamera(angle) {
        const { camera, scene } = this;
        const oldAngle = { angle: makeRadiansPositive(Math.atan2(camera.position.z, camera.position.x)) };
        const newAngle = { angle: simplifyAngle(angle) * (Math.PI / 180) };

        const tween = new TWEEN.Tween(oldAngle)
            .to(newAngle, this.tweenLength)
            .easing(TWEEN.Easing.Quadratic.Out)
            .onUpdate(function() {
                camera.position.x = 120 * Math.cos(this.angle);
                camera.position.z = 120 * Math.sin(this.angle);
                camera.lookAt(scene.position);
            })
            .start();
    }

    renderAnimation() {
        if (this.stats && this.props.showStats) {
            this.stats.begin();
        }

        const { windowHeight, windowWidth } = this.state;
        const { topColor, bottomColor } = this.props;

        for (let mesh of this.randomShapes) {
            // if shape is above top of window
            if (mesh.position.y > (windowHeight / 16 + this.meshSize * 4)) {
                mesh.geometry = this.generateRandomGeometry();
                this.repositionMeshToBottom(mesh);
            }

            this.moveMesh(mesh);

            if (mesh.colorTopToBottom) {
                mesh.material.color = getColorFromPosition(mesh.position.y, windowHeight, topColor, bottomColor);
            } else if (mesh.colorBottomToTop) {
                mesh.material.color = getColorFromPosition(mesh.position.y, windowHeight, bottomColor, topColor);
            }
        }

        for (let mesh of this.tetras) {
            // if shape is above top of window
            if (mesh.position.y > (windowHeight / 16 + this.meshSize * 4)) {
                this.repositionMeshToBottom(mesh);
            }

            this.moveMesh(mesh);
        }

        TWEEN.update();
        this.renderer.render(this.scene, this.camera);

        if (this.stats && this.props.showStats) {
            this.stats.end();
        }

        requestAnimationFrame(() => this.renderAnimation());
    }

    repositionMeshToBottom(mesh) {
        const { windowHeight, windowWidth } = this.state;
        // put it below the bottom of the window and give it a random z position
        mesh.position.y -= (windowHeight / 8 + this.meshSize * 8);
        mesh.position.z = randomWithRange(windowWidth / 16, windowWidth / -16);

        // give it new velocities
        this.assignMeshVelocities(mesh);

        // give the mesh new rotation speeds
        for (let axis of ['x', 'y', 'z']) {
            mesh.rotationSpeed[axis] = randomWithRange(-0.01, 0.01);
        }
    }

    moveMesh(mesh) {
        const { windowHeight, windowWidth } = this.state;

        // rotate the mesh around its axes
        for (let axis of ['x', 'y', 'z']) {
            mesh.position[axis] += mesh[`${axis}Velocity`]; // translate the mesh
            mesh.rotation[axis] += mesh.rotationSpeed[axis]; // rotate the mesh
        }
    }

    render() {
        const { showStats, topColor, bottomColor } = this.props;
        const { windowHeight, windowWidth } = this.state;
        const className = classNames('orthofloat-wrapper', { 'show-stats': showStats });
        const topColorStyle = (new THREE.Color(topColor.r, topColor.g, topColor.b)).getStyle();
        const bottomColorStyle = (new THREE.Color(bottomColor.r, bottomColor.g, bottomColor.b)).getStyle();
        const wrapperStyle = {
            backgroundImage: `${this.vendorPrefix}linear-gradient(${topColorStyle}, ${bottomColorStyle})`
        };

        // stripes
        const stripeStyle = {
            width: `${this.stripeWidth}px`,
            marginRight: `${this.stripeWidth}px`,
            backgroundImage: `${this.vendorPrefix}linear-gradient(${bottomColorStyle}, ${topColorStyle})`
        };
        const numOfStripes = Math.ceil(windowWidth / (this.stripeWidth * 2));
        let stripes = [];
        for (let i = 0; i < numOfStripes; i++) {
            stripes.push(
);
        }

        return (

 this.el = c}>

                    {stripes}

        );
    }
}

Orthofloat.propTypes = {
    bottomColor: PropTypes.shape({
        r: PropTypes.number.isRequired,
        g: PropTypes.number.isRequired,
        b: PropTypes.number.isRequired
    }),
    topColor: PropTypes.shape({
        r: PropTypes.number.isRequired,
        g: PropTypes.number.isRequired,
        b: PropTypes.number.isRequired
    }),
    initializeWithStats: PropTypes.bool,
    showStats: PropTypes.bool
};

Orthofloat.defaultProps = {
    bottomColor: randomRGB(),
    topColor: randomRGB(),
    initializeWithStats: false,
    showStats: false
};<commit_msg>set background image when orthofloat mounts<commit_after>import React, { Component, PropTypes } from 'react';
import bowser from 'bowser';
import classNames from 'classnames';
import THREE from 'three';
import TWEEN from 'tween.js';
import Stats from 'stats.js';
import lodashThrottle from 'lodash/throttle';
import lodashIsEqual from 'lodash/isEqual';

import { makeRadiansPositive, randomWithRange, simplifyAngle } from '../../businessLogic/mathHelpers';
import { averageRGB,
         currentColorInTween,
         getColorFromPosition,
         mergeTopAndBottomColors,
         randomRGB } from '../../businessLogic/threeHelpers';

import './orthofloat.scss';

export default class Orthofloat extends Component {
    constructor(props) {
        super(props);

        this.state = {
            windowHeight: window.innerHeight,
            windowWidth: window.innerWidth
        };
    }

    componentWillMount() {
        this.setVendorPrefix();
        this.stripeWidth = 25;
        this.tweenLength = 2000;
    }

    componentDidMount() {
        this.initializeScene();
        this.initializeBackground();

        this.windowResizeFunc = lodashThrottle(() => this.onWindowResize(), 16.667);
        window.addEventListener('resize', this.windowResizeFunc);
    }

    componentWillReceiveProps(nextProps) {
        if (!lodashIsEqual(nextProps.bottomColor, this.props.bottomColor)
            || !lodashIsEqual(nextProps.topColor, this.props.topColor)) {
            this.changeColors(nextProps.topColor, nextProps.bottomColor);
        }
    }

    componentWillUnmount() {
        window.removeEventListener('resize', this.windowResizeFunc);
    }

    initializeBackground() {
        const { topColor, bottomColor } = this.props;
        const topColorStyle = (new THREE.Color(topColor.r, topColor.g, topColor.b)).getStyle();
        const bottomColorStyle = (new THREE.Color(bottomColor.r, bottomColor.g, bottomColor.b)).getStyle();

        this.setBackgroundColor(null, topColorStyle, bottomColorStyle);
    }

    setBackgroundColor(stripeDivs, topColorStyle, bottomColorStyle) {
        this.el.style.backgroundImage = `${this.vendorPrefix}linear-gradient(${topColorStyle}, ${bottomColorStyle})`;
    }

    changeColors(nextTopColor, nextBottomColor) {
        const { randomShapeMaterialBottom, randomShapeMaterialTop, randomShapeMaterialMid } = this;
        const oldColors = mergeTopAndBottomColors(this.props.topColor, this.props.bottomColor);
        const newColors = mergeTopAndBottomColors(nextTopColor, nextBottomColor);

        const tween = new TWEEN.Tween(oldColors)
            .to(newColors, this.tweenLength)
            .easing(TWEEN.Easing.Quadratic.Out)
            .onUpdate(function() {
                randomShapeMaterialBottom.color = currentColorInTween(this, 'bottom');
                randomShapeMaterialTop.color = currentColorInTween(this, 'top');

                randomShapeMaterialMid.color = averageRGB(
                    randomShapeMaterialBottom.color,
                    randomShapeMaterialTop.color
                );
            })
            .start();
    }

    initializeScene() {
        this.scene = new THREE.Scene();

        this.initializeCamera();
        this.initializeMeshes();
        this.initializeLights();
        this.initializeRenderer();

        if (this.props.initializeWithStats) {
            this.initializeStats();
        }

        this.renderAnimation();
    }

    initializeCamera() {
        const { windowHeight, windowWidth } = this.state;
        this.camFactor = 16;
        this.camera = new THREE.OrthographicCamera(
            windowWidth / - this.camFactor,
            windowWidth / this.camFactor,
            windowHeight / this.camFactor,
            windowHeight / - this.camFactor,
            -200,
            500
        );
        this.camera.position.x = 120;
        this.camera.lookAt(this.scene.position);
    }

    initializeMeshes() {
        this.meshSize = 2.5;
        this.initializeRandomShapes();
        this.initializeTetrahedrons();
    }

    initializeRandomShapes() {
        const { bottomColor, topColor } = this.props;
        const threeTopColor = new THREE.Color(topColor.r, topColor.g, topColor.b);
        const threeBottomColor = new THREE.Color(bottomColor.r, bottomColor.g, bottomColor.b);
        this.randomShapeMaterialTop = new THREE.MeshBasicMaterial({ color: threeTopColor });
        this.randomShapeMaterialBottom = new THREE.MeshBasicMaterial({ color: threeBottomColor });
        const averageColor = averageRGB(this.randomShapeMaterialTop.color, this.randomShapeMaterialBottom.color);
        this.randomShapeMaterialMid = new THREE.MeshBasicMaterial({
            color: new THREE.Color(averageColor.r, averageColor.g, averageColor.b)
        });
        this.randomShapes = [];
        for (let i = 0; i < 53; i++) {
            let shape;
            switch (i % 5) {
                case 0:
                    shape = new THREE.Mesh(this.generateRandomGeometry(), this.randomShapeMaterialTop);
                    break;
                case 1:
                    shape = new THREE.Mesh(this.generateRandomGeometry(), this.randomShapeMaterialBottom);
                    break;
                case 2:
                    shape = new THREE.Mesh(this.generateRandomGeometry(), this.randomShapeMaterialMid);
                    break;
                case 3:
                    shape = new THREE.Mesh(
                        this.generateRandomGeometry(),
                        new THREE.MeshBasicMaterial({ color: threeTopColor })
                    );
                    shape.colorTopToBottom = true;
                    break;
                case 4:
                default:
                    shape = new THREE.Mesh(
                        this.generateRandomGeometry(),
                        new THREE.MeshBasicMaterial({ color: threeBottomColor })
                    );
                    shape.colorBottomToTop = true;
            }
            this.setMeshInSpace(shape);
            this.randomShapes.push(shape);
            this.scene.add(shape);
        }
    }

    generateRandomGeometry() {
        const meshSize = randomWithRange(0.25, 2) * this.meshSize;
        const cylRadius = randomWithRange(meshSize / 2, meshSize);

        switch (Math.floor(Math.random() * 11)) {
            case 10:
                return new THREE.TorusKnotGeometry(
                    meshSize, meshSize / 3, 32, 12, randomWithRange(1, 7), randomWithRange(1, 10)
                );
            case 9:
                return new THREE.TorusGeometry(
                    meshSize, meshSize / 4, 16, 16, randomWithRange(Math.PI / 2, Math.PI * 3)
                );
            case 8:
                return new THREE.SphereGeometry(
                    meshSize,
                    16,
                    16,
                    0,
                    randomWithRange(Math.PI / 2, Math.PI * 3),
                    0,
                    randomWithRange(Math.PI / 2, Math.PI)
                );
            case 7:
                return new THREE.RingGeometry(
                    meshSize / 2, meshSize, 16, 1, 0, randomWithRange(Math.PI / 2, Math.PI * 3)
                );
            case 6:
                return new THREE.PlaneGeometry(meshSize, meshSize, 1, 1);
            case 5:
                return new THREE.OctahedronGeometry(meshSize, 0);
            case 4:
                return new THREE.IcosahedronGeometry(meshSize, 0);
            case 3:
                return new THREE.DodecahedronGeometry(meshSize, 0);
            case 2:
                return new THREE.CylinderGeometry(
                    cylRadius,
                    cylRadius,
                    randomWithRange(meshSize / 2, meshSize * 1.5),
                    16,
                    1,
                    Math.random() < 0.5,
                    0,
                    randomWithRange(Math.PI / 2, Math.PI * 3)
                );
            case 1:
                return new THREE.CircleGeometry(meshSize, 16);
            case 0:
            default:
                return new THREE.BoxGeometry(meshSize, meshSize, meshSize);
        }
    }

    initializeTetrahedrons() {
        const tetraGeometry = new THREE.TetrahedronGeometry(this.meshSize);
        const color = new THREE.Color(0xff6ba9);
        const tetraMaterial = new THREE.MeshBasicMaterial({color});
        this.tetras = [];
        for (let i = 0; i < 50; i++) {
            const tetra = new THREE.Mesh(tetraGeometry, tetraMaterial);
            this.setMeshInSpace(tetra);
            this.tetras.push(tetra);
            this.scene.add(tetra);
        }
    }

    setMeshInSpace(mesh) {
        const { windowHeight, windowWidth } = this.state;
        mesh.position.x = randomWithRange(windowWidth / 16, windowWidth / -16);
        mesh.position.y = randomWithRange(windowHeight / 16, windowHeight / -16);
        mesh.position.z = randomWithRange(windowWidth / 16, windowWidth / -16);
        mesh.rotation.set(randomWithRange(0, Math.PI), randomWithRange(0, Math.PI), randomWithRange(0, Math.PI));
        mesh.rotationSpeed = {
            x: randomWithRange(-0.01, 0.01),
            y: randomWithRange(-0.01, 0.01),
            z: randomWithRange(-0.01, 0.01)
        };

        this.assignMeshVelocities(mesh);
    }

    assignMeshVelocities(mesh) {
        mesh.xVelocity = randomWithRange(-0.01, 0.01);
        mesh.yVelocity = randomWithRange(0.03, 0.1);
        mesh.zVelocity = randomWithRange(-0.01, 0.01);
    }

    initializeLights() {
        const directionalLight = new THREE.DirectionalLight( 0xffffff, 0.7 );
        directionalLight.position.set(60, 60, 60);
        this.scene.add(directionalLight);

        const ambientLight = new THREE.AmbientLight(0x4B4B4B);
        this.scene.add(ambientLight);
    }

    initializeRenderer() {
        const { windowHeight, windowWidth } = this.state;
        this.renderer = new THREE.WebGLRenderer({ alpha: true });
        this.renderer.setSize(windowWidth, windowHeight);

        this.el.appendChild(this.renderer.domElement);
        this.renderer.render(this.scene, this.camera);
    }

    initializeStats() {
        this.stats = new Stats();
        this.el.appendChild(this.stats.dom);
    }

    setVendorPrefix() {
        if (bowser.webkit) {
            this.vendorPrefix = '-webkit-';
        } else if (bowser.firefox) {
            this.vendorPrefix = '-moz-';
        } else if (bowser.opera) {
            this.vendorPrefix = '-o-';
        } else {
            this.vendorPrefix = '';
        }
    }

    onWindowResize() {
        const windowHeight = window.innerHeight,
              windowWidth = window.innerWidth;

        this.setState({ windowHeight, windowWidth });

        this.renderer.setSize(windowWidth, windowHeight);

        this.camera.left = windowWidth / -this.camFactor;
        this.camera.right = windowWidth / this.camFactor;
        this.camera.top = windowHeight / this.camFactor;
        this.camera.bottom = windowHeight / -this.camFactor;
        this.camera.updateProjectionMatrix();
    }

    moveCamera(angle) {
        const { camera, scene } = this;
        const oldAngle = { angle: makeRadiansPositive(Math.atan2(camera.position.z, camera.position.x)) };
        const newAngle = { angle: simplifyAngle(angle) * (Math.PI / 180) };

        const tween = new TWEEN.Tween(oldAngle)
            .to(newAngle, this.tweenLength)
            .easing(TWEEN.Easing.Quadratic.Out)
            .onUpdate(function() {
                camera.position.x = 120 * Math.cos(this.angle);
                camera.position.z = 120 * Math.sin(this.angle);
                camera.lookAt(scene.position);
            })
            .start();
    }

    renderAnimation() {
        if (this.stats && this.props.showStats) {
            this.stats.begin();
        }

        const { windowHeight, windowWidth } = this.state;
        const { topColor, bottomColor } = this.props;

        for (let mesh of this.randomShapes) {
            // if shape is above top of window
            if (mesh.position.y > (windowHeight / 16 + this.meshSize * 4)) {
                mesh.geometry = this.generateRandomGeometry();
                this.repositionMeshToBottom(mesh);
            }

            this.moveMesh(mesh);

            if (mesh.colorTopToBottom) {
                mesh.material.color = getColorFromPosition(mesh.position.y, windowHeight, topColor, bottomColor);
            } else if (mesh.colorBottomToTop) {
                mesh.material.color = getColorFromPosition(mesh.position.y, windowHeight, bottomColor, topColor);
            }
        }

        for (let mesh of this.tetras) {
            // if shape is above top of window
            if (mesh.position.y > (windowHeight / 16 + this.meshSize * 4)) {
                this.repositionMeshToBottom(mesh);
            }

            this.moveMesh(mesh);
        }

        TWEEN.update();
        this.renderer.render(this.scene, this.camera);

        if (this.stats && this.props.showStats) {
            this.stats.end();
        }

        requestAnimationFrame(() => this.renderAnimation());
    }

    repositionMeshToBottom(mesh) {
        const { windowHeight, windowWidth } = this.state;
        // put it below the bottom of the window and give it a random z position
        mesh.position.y -= (windowHeight / 8 + this.meshSize * 8);
        mesh.position.z = randomWithRange(windowWidth / 16, windowWidth / -16);

        // give it new velocities
        this.assignMeshVelocities(mesh);

        // give the mesh new rotation speeds
        for (let axis of ['x', 'y', 'z']) {
            mesh.rotationSpeed[axis] = randomWithRange(-0.01, 0.01);
        }
    }

    moveMesh(mesh) {
        const { windowHeight, windowWidth } = this.state;

        // rotate the mesh around its axes
        for (let axis of ['x', 'y', 'z']) {
            mesh.position[axis] += mesh[`${axis}Velocity`]; // translate the mesh
            mesh.rotation[axis] += mesh.rotationSpeed[axis]; // rotate the mesh
        }
    }

    render() {
        const { showStats, topColor, bottomColor } = this.props;
        const { windowHeight, windowWidth } = this.state;
        const className = classNames('orthofloat-wrapper', { 'show-stats': showStats });
        const topColorStyle = (new THREE.Color(topColor.r, topColor.g, topColor.b)).getStyle();
        const bottomColorStyle = (new THREE.Color(bottomColor.r, bottomColor.g, bottomColor.b)).getStyle();

        // stripes
        const stripeStyle = {
            width: `${this.stripeWidth}px`,
            marginRight: `${this.stripeWidth}px`,
            backgroundImage: `${this.vendorPrefix}linear-gradient(${bottomColorStyle}, ${topColorStyle})`
        };
        const numOfStripes = Math.ceil(windowWidth / (this.stripeWidth * 2));
        let stripes = [];
        for (let i = 0; i < numOfStripes; i++) {
            stripes.push(
);
        }

        return (

 this.el = c}>

                    {stripes}

        );
    }
}

Orthofloat.propTypes = {
    bottomColor: PropTypes.shape({
        r: PropTypes.number.isRequired,
        g: PropTypes.number.isRequired,
        b: PropTypes.number.isRequired
    }),
    topColor: PropTypes.shape({
        r: PropTypes.number.isRequired,
        g: PropTypes.number.isRequired,
        b: PropTypes.number.isRequired
    }),
    initializeWithStats: PropTypes.bool,
    showStats: PropTypes.bool
};

Orthofloat.defaultProps = {
    bottomColor: randomRGB(),
    topColor: randomRGB(),
    initializeWithStats: false,
    showStats: false
};<|endoftext|>


<commit_before>// @flow
import * as React from 'react'

import TextField from '@material-ui/core/TextField'
import Button from '@material-ui/core/Button'
import List from '@material-ui/core/List'
import ListItem from '@material-ui/core/ListItem'
import Typography from '@material-ui/core/Typography'

import SearchIcon from '@material-ui/icons/Search'
import StarIcon from '@material-ui/icons/Star'
import RadioCheckedIcon from '@material-ui/icons/RadioButtonChecked'
import RadioUnCheckedIcon from '@material-ui/icons/RadioButtonUnchecked'

import styled from 'styled-components'
import type { Tag } from '../../types'

export type Props = {
  tags: Tag[],
  searchSubmit: Function,
}

type State = {
  qText: string,
  tagText: string,
}

const Wrapper = styled.div`
  padding: 10px;
`

const Inputs = styled.div`
  width: 70%;
`

const Row = styled.div`
  display: flex;
  justify-content: space-between;
`

const IconWrap = styled.div`
  margin: 15px auto;
  width: 2em;
`

class Component extends React.Component<Props, State> {
  constructor(props: Props) {
    super(props)
    this.state = {
      qText: '',
      tagText: '',
    }
  }
  render() {
    const { props, state } = this
    const filteredTags = props.tags.filter(
      tag => tag.name.indexOf(state.tagText) !== -1,
    )
    return (
      <Wrapper>
        <Row>
          <Inputs>
            <Row>
              <IconWrap>
                <SearchIcon />
              </IconWrap>
              <TextField
                label="キーワード・作品・キャラ"
                onChange={e => {
                  this.setState({ qText: e.target.value })
                }}
              />
            </Row>
            <Row>
              <IconWrap>
                <StarIcon />
              </IconWrap>
              <TextField
                label="タグ"
                onChange={e => {
                  this.setState({ tagText: e.target.value })
                }}
              />
            </Row>
          </Inputs>
          <Button
            color="primary"
            variant="contained"
            style={{ margin: 5, height: 50, width: 50 }}
            onClick={() => {
              props.searchSubmit(state.qText, state.tagText)
            }}
          >
            検索
          </Button>
        </Row>

タグ数:{props.tags.length}

絞り込み:{filteredTags.length}

        <List>
          {filteredTags.map(tag => {
            // HACKME
            const selected = tag.name === state.tagText
            return (
              <ListItem
                key={tag.id}
                onClick={() => {
                  this.setState({ tagText: selected ? '' : tag.name })
                }}
              >

                    <Typography variant="body1">{tag.name}</Typography>
                    <Typography variant="body2">
                      ({tag.taggingsCount})
                    </Typography>

                    {selected ? <RadioCheckedIcon /> : <RadioUnCheckedIcon />}

              </ListItem>
            )
          })}
        </List>
      </Wrapper>
    )
  }
}

export default Component
<commit_msg>Fix ref<commit_after>// @flow
import * as React from 'react'

import TextField from '@material-ui/core/TextField'
import Button from '@material-ui/core/Button'
import List from '@material-ui/core/List'
import ListItem from '@material-ui/core/ListItem'
import Typography from '@material-ui/core/Typography'

import SearchIcon from '@material-ui/icons/Search'
import StarIcon from '@material-ui/icons/Star'
import RadioCheckedIcon from '@material-ui/icons/RadioButtonChecked'
import RadioUnCheckedIcon from '@material-ui/icons/RadioButtonUnchecked'

import styled from 'styled-components'
import type { Tag } from '../../types'

export type Props = {
  tags: Tag[],
  searchSubmit: Function,
}

type State = {
  qText: string,
  tagText: string,
}

const Wrapper = styled.div`
  padding: 10px;
`

const Inputs = styled.div`
  width: 70%;
`

const Row = styled.div`
  display: flex;
  justify-content: space-between;
`

const IconWrap = styled.div`
  margin: 15px auto;
  width: 2em;
`

class Component extends React.Component<Props, State> {
  searchRef: ?HTMLInputElement

  state = {
    qText: '',
    tagText: '',
  }

  render() {
    const { props, state } = this
    const filteredTags = props.tags.filter(
      tag => tag.name.indexOf(state.tagText) !== -1,
    )
    return (
      <Wrapper>
        <Row>
          <Inputs>
            <Row>
              <IconWrap>
                <SearchIcon />
              </IconWrap>
              <TextField
                label="キーワード・作品・キャラ"
                InputLabelProps={{
                  shrink: true,
                }}
                onChange={e => {
                  this.setState({ qText: e.target.value })
                }}
              />
            </Row>
            <Row>
              <IconWrap>
                <StarIcon />
              </IconWrap>
              <TextField
                label="タグ"
                inputRef={r => {
                  this.searchRef = r
                }}
                InputLabelProps={{
                  shrink: true,
                }}
                onChange={e => {
                  this.setState({ tagText: e.target.value })
                }}
              />
            </Row>
          </Inputs>
          <Button
            color="primary"
            variant="contained"
            style={{ margin: 5, height: 50, width: 50 }}
            onClick={() => {
              props.searchSubmit(state.qText, state.tagText)
            }}
          >
            検索
          </Button>
        </Row>

タグ数:{props.tags.length}

絞り込み:{filteredTags.length}

        <List>
          {filteredTags.map(tag => {
            // HACKME
            const selected = tag.name === state.tagText
            return (
              <ListItem
                key={tag.id}
                onClick={() => {
                  const tagText = selected ? '' : tag.name
                  this.setState({ tagText })
                  if (this.searchRef) {
                    this.searchRef.value = tagText
                  }
                }}
              >

                    <Typography variant="body1">{tag.name}</Typography>
                    <Typography variant="body2">
                      ({tag.taggingsCount})
                    </Typography>

                    {selected ? <RadioCheckedIcon /> : <RadioUnCheckedIcon />}

              </ListItem>
            )
          })}
        </List>
      </Wrapper>
    )
  }
}

export default Component
<|endoftext|>


<commit_before>let d3 = require('d3');
let queue = require('./Queue');

require('./cordChart.less');

export default class CordChart {
    constructor(element) {
        this.element = element;
    }

    render(model) {
        var matrix = [
            [11975, 5871, 8916, 2868],
            [1951, 10048, 2060, 6171],
            [8010, 16145, 8090, 8045],
            [1013, 990, 940, 6907]
        ];

        var chord = d3.layout.chord()
            .padding(.05)
            .sortSubgroups(d3.descending)
            .matrix(matrix);

        var width = 960,
            height = 500,
            innerRadius = Math.min(width, height) * .41,
            outerRadius = innerRadius * 1.1;

        var fill = d3.scale.ordinal()
            .domain(d3.range(4))
            .range(["#000000", "#FFDD89", "#957244", "#F26223"]);

        var svg = d3.select(this.element).append("svg")
            .attr("width", width)
            .attr("height", height)
            .append("g")
            .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");

        svg.append("g").selectAll("path")
            .data(chord.groups)
            .enter().append("path")
            .style("fill", function (d) {
                return fill(d.index);
            })
            .style("stroke", function (d) {
                return fill(d.index);
            })
            .attr("d", d3.svg.arc().innerRadius(innerRadius).outerRadius(outerRadius))
            .on("mouseover", fade(.1))
            .on("mouseout", fade(1));

        var ticks = svg.append("g").selectAll("g")
            .data(chord.groups)
            .enter().append("g").selectAll("g")
            .data(groupTicks)
            .enter().append("g")
            .attr("transform", function (d) {
                return "rotate(" + (d.angle * 180 / Math.PI - 90) + ")"
                    + "translate(" + outerRadius + ",0)";
            });

        ticks.append("line")
            .attr("x1", 1)
            .attr("y1", 0)
            .attr("x2", 5)
            .attr("y2", 0)
            .style("stroke", "#000");

        ticks.append("text")
            .attr("x", 8)
            .attr("dy", ".35em")
            .attr("transform", function (d) {
                return d.angle > Math.PI ? "rotate(180)translate(-16)" : null;
            })
            .style("text-anchor", function (d) {
                return d.angle > Math.PI ? "end" : null;
            })
            .text(function (d) {
                return d.label;
            });

        svg.append("g")
            .attr("class", "chord")
            .selectAll("path")
            .data(chord.chords)
            .enter().append("path")
            .attr("d", d3.svg.chord().radius(innerRadius))
            .style("fill", function (d) {
                return fill(d.target.index);
            })
            .style("opacity", 1);

// Returns an array of tick angles and labels, given a group.
        function groupTicks(d) {
            var k = (d.endAngle - d.startAngle) / d.value;
            return d3.range(0, d.value, 1000).map(function (v, i) {
                return {
                    angle: v * k + d.startAngle,
                    label: i % 5 ? null : v / 1000 + "k"
                };
            });
        }

// Returns an event handler for fading a given chord group.
        function fade(opacity) {
            return function (g, i) {
                svg.selectAll(".chord path")
                    .filter(function (d) {
                        return d.source.index != i && d.target.index != i;
                    })
                    .transition()
                    .style("opacity", opacity);
            };
        }

    }
}<commit_msg>it works!<commit_after>let d3 = require('d3');
let queue = require('./Queue');
let Colors = require('./../../constants/Colors');

require('./cordChart.less');

export default class CordChart {
    constructor(element) {
        this.element = element;
    }

    render(model) {
        var matrix = [
            [11975, 5871, 8916, 2868],
            [1951, 10048, 2060, 6171],
            [8010, 16145, 8090, 8045],
            [1013, 990, 940, 6907]
        ];

        var chord = d3.layout.chord()
            .padding(.05)
            .sortSubgroups(d3.descending)
            .matrix(matrix);

        var width = 960,
            height = 500,
            innerRadius = Math.min(width, height) * .41,
            outerRadius = innerRadius * 1.1;

        var svg = d3.select(this.element).append("svg")
            .attr("width", width)
            .attr("height", height)
            .append("g")
            .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");

        let group = svg.append("g").selectAll("path")
            .data(chord.groups)
            .enter().append("g")
            .attr("class", "group")
            .on("mouseover", fade(.1))
            .on("mouseout", fade(1));

        group.append("path")
            .style("fill", function (d) {
                return Colors.getColor(d.index);
            })
            .style("stroke", function (d) {
                return Colors.getColor(d.index);
            })
            .attr("id", function(d) { return "group" + d.index; })
            .attr("d", d3.svg.arc().innerRadius(innerRadius).outerRadius(outerRadius));

        group.append("title").text(function(d, i) {
            return'DUPA';
        });

        group.append("svg:text")
            .attr("x", 6)
            .attr("dy", 15)
            //.filter(function(d) { return d.value > 110; })
            .append("svg:textPath")
            .attr("xlink:href", function(d) { return "#group" + d.index; })
            .text(function(d) { return 'asasasas'; });

        //
        //
        //var ticks = svg.append("g").selectAll("g")
        //    .data(chord.groups)
        //    .enter().append("g").selectAll("g")
        //    .data(groupTicks)
        //    .enter().append("g")
        //    .attr("transform", function (d) {
        //        return "rotate(" + (d.angle * 180 / Math.PI - 90) + ")"
        //            + "translate(" + outerRadius + ",0)";
        //    });
        //
        //ticks.append("line")
        //    .attr("x1", 1)
        //    .attr("y1", 0)
        //    .attr("x2", 5)
        //    .attr("y2", 0)
        //    .style("stroke", "#000");
        //
        //ticks.append("text")
        //    .attr("x", 8)
        //    .attr("dy", ".35em")
        //    .attr("transform", function (d) {
        //        return d.angle > Math.PI ? "rotate(180)translate(-16)" : null;
        //    })
        //    .style("text-anchor", function (d) {
        //        return d.angle > Math.PI ? "end" : null;
        //    })
        //    .text(function (d) {
        //        return d.label;
        //    });

        svg.append("g")
            .attr("class", "chord")
            .selectAll("path")
            .data(chord.chords)
            .enter().append("path")
            .attr("d", d3.svg.chord().radius(innerRadius))
            .style("fill", function (d) {
                return Colors.getColor(d.target.index);
            })
            .style("opacity", 1);

// Returns an array of tick angles and labels, given a group.
        function groupTicks(d) {
            var k = (d.endAngle - d.startAngle) / d.value;
            return d3.range(0, d.value, 1000).map(function (v, i) {
                return {
                    angle: v * k + d.startAngle,
                    label: i % 5 ? null : v / 1000 + "k"
                };
            });
        }

// Returns an event handler for fading a given chord group.
        function fade(opacity) {
            return function (g, i) {
                svg.selectAll(".chord path")
                    .filter(function (d) {
                        return d.source.index != i && d.target.index != i;
                    })
                    .transition()
                    .style("opacity", opacity);
            };
        }

    }
}<|endoftext|>


<commit_before>import React from 'react';
import ReactDOM from 'react-dom';

export default class ContentEditable extends React.Component {
  static propTypes = {
    html: React.PropTypes.string,
    onChange: React.PropTypes.func,
    autoFocus: React.PropTypes.bool,
  };

  componentDidMount() {
    if (this.props.autoFocus && typeof window.orientation !== 'undefined') {
      // We use orientation as a proxy for devices with an on-screen keyboard.
      // They don't respond well to auto-focusing, so disabling it for now.
      ReactDOM.findDOMNode(this).focus();
    }
  }

  shouldComponentUpdate(nextProps) {
    return nextProps.html !== ReactDOM.findDOMNode(this).innerHTML;
  }

  componentDidUpdate() {
    if (this.props.html !== ReactDOM.findDOMNode(this).innerHTML) {
      ReactDOM.findDOMNode(this).innerHTML = this.props.html;
    }
  }

  emitChange = () => {
    const html = ReactDOM.findDOMNode(this).innerHTML;
    if (this.props.onChange && html !== this.lastHtml) {
      this.props.onChange({
        target: {
          value: html,
        },
      });
    }
    this.lastHtml = html;
  };

  render() {
    return (

    );
  }
}
<commit_msg>I give up<commit_after>import React from 'react';
import ReactDOM from 'react-dom';

export default class ContentEditable extends React.Component {
  static propTypes = {
    html: React.PropTypes.string,
    onChange: React.PropTypes.func,
    autoFocus: React.PropTypes.bool,
  };

  componentDidMount() {
    if (this.props.autoFocus && (typeof window.orientation) === 'undefined') {
      // We use orientation as a proxy for devices with an on-screen keyboard.
      // They don't respond well to auto-focusing, so disabling it for now.
      ReactDOM.findDOMNode(this).focus();
    }
  }

  shouldComponentUpdate(nextProps) {
    return nextProps.html !== ReactDOM.findDOMNode(this).innerHTML;
  }

  componentDidUpdate() {
    if (this.props.html !== ReactDOM.findDOMNode(this).innerHTML) {
      ReactDOM.findDOMNode(this).innerHTML = this.props.html;
    }
  }

  emitChange = () => {
    const html = ReactDOM.findDOMNode(this).innerHTML;
    if (this.props.onChange && html !== this.lastHtml) {
      this.props.onChange({
        target: {
          value: html,
        },
      });
    }
    this.lastHtml = html;
  };

  render() {
    return (

    );
  }
}
<|endoftext|>


<commit_before>const WebSocket = require('ws');
const gpio = require('rpi-gpio');
var async = require('async');

const wss = new WebSocket.Server({ port: 8080 });

var power = false;
var mute = false;

const pinConfig = {
    power: 18,
    mute: 17
}

wss.on('connection', function connection(ws) {
    gpio.setMode(gpio.MODE_BCM);

    ws.on('message', function incoming(message) {
        if (message == 'powerToggle') {
            power = !power;

            async.parallel([
                function (callback) {
                    gpio.setup(pinConfig.power, gpio.DIR_OUT, callback)
                },
                function (callback) {
                    gpio.setup(pinConfig.mute, gpio.DIR_OUT, callback)
                },
            ], function (err, results) {
                console.log('Pins set up');
                async.series([
                    function (callback) {
                        delayedWrite(pinConfig.mute, true, callback);
                    },
                    function (callback) {
                        delayedWrite(pinConfig.power, power, callback, 0);
                    }
                ], function (err, results) {
                    if (err) {
                        console.error(err);
                    }
                    else {
                        console.log(`Powered ${power ? on : off}`);
                    }
                });
            });
        }

        if (message == 'muteToggle') {
            mute = !mute;

            writePin(pinConfig.mute, mute);
        }
    });

    ws.on('close', function exit(code, reason) {
        gpio.destroy(function () {
            console.log(`Closing connection: ${code} : ${reason}`)
        });
    });

    ws.send('connected to DeskPi');
});

function delayedWrite(pin, value, callback, delay = 250) {
    setTimeout(function () {
        gpio.write(pin, value, callback);
    }, delay);
}
<commit_msg>Trying something else<commit_after>const WebSocket = require('ws');
const gpio = require('rpi-gpio');
var async = require('async');

const wss = new WebSocket.Server({ port: 8080 });

var power = false;
var mute = false;

const pinConfig = {
    power: 18,
    mute: 17
}

wss.on('connection', function connection(ws) {
    gpio.setMode(gpio.MODE_BCM);

    async.parallel([
                function (callback) {
                    gpio.setup(pinConfig.power, gpio.DIR_OUT, callback)
                },
                function (callback) {
                    gpio.setup(pinConfig.mute, gpio.DIR_OUT, callback)
                },
            ], function (err, results) {
                console.log('Pins set up');
                async.series([
                    function (callback) {
                        delayedWrite(pinConfig.mute, true, callback);
                    },
                    function (callback) {
                        delayedWrite(pinConfig.power, power, callback, 0);
                    }
                ], function (err, results) {
                    if (err) {
                        console.error(err);
                    }
                    else {
                        console.log(`Powered ${power ? on : off}`);
                    }
                });
            });

    ws.on('message', function incoming(message) {
        if (message == 'powerToggle') {
            power = !power;

        }

        if (message == 'muteToggle') {
            mute = !mute;

            writePin(pinConfig.mute, mute);
        }
    });

    ws.on('close', function exit(code, reason) {
        gpio.destroy(function () {
            console.log(`Closing connection: ${code} : ${reason}`)
        });
    });

    ws.send('connected to DeskPi');
});

function delayedWrite(pin, value, callback, delay = 250) {
    setTimeout(function () {
        gpio.write(pin, value, callback);
    }, delay);
}
<|endoftext|>


<commit_before>'use strict';

var gulp = require('gulp');
var _ = require('lodash');

var config = require('./_config.js');
var paths = config.paths;

var karma = require('karma').server;

var karmaConf = {
  browsers: ['PhantomJS'],
  frameworks: ['mocha'],
  preprocessors: {},
  files: [
    paths.tmp + "/js/main.js",
    './node_modules/should/should.min.js',
    paths.test + '/**/*.spec.js'
  ],
  reporters: ['mocha', 'osx', 'coverage']
};

karmaConf.preprocessors[paths.tmp + '/js/main.js'] = ['coverage'];

gulp.task('test', function (done) {
  karma.start(karmaConf, done);
});

gulp.task('test:once', function () {
  karma.start(_.assign({}, karmaConf, { singleRun: true }));
});

<commit_msg>Updae ci test task to also build project.<commit_after>'use strict';

var gulp = require('gulp');
var _ = require('lodash');

var config = require('./_config.js');
var paths = config.paths;

var karma = require('karma').server;

var karmaConf = {
  browsers: ['PhantomJS'],
  frameworks: ['mocha'],
  preprocessors: {},
  files: [
    paths.tmp + "/js/main.js",
    './node_modules/should/should.min.js',
    paths.test + '/**/*.spec.js'
  ],
  reporters: ['mocha', 'osx', 'coverage']
};

karmaConf.preprocessors[paths.tmp + '/js/main.js'] = ['coverage'];

gulp.task('test', function (done) {
  karma.start(karmaConf, done);
});

gulp.task('test:once', ['build'], function () {
  karma.start(_.assign({}, karmaConf, { singleRun: true }));
});

<|endoftext|>


<commit_before>function mouseoverColumn(d, i) {

    d3.selectAll(".connection, .combination rect, .setSize")
    //    .style("opacity", .3)
    .style("stroke", "white")

    d3.selectAll(".connection.diagonal").filter(function (dd, ii) {
        return ii == i;
    })
        .style("opacity", 1)
        .style("stroke", "black")

    d3.selectAll(".combination").selectAll("rect").filter(function (dd, ii) {
        return ii == i;
    })
        .style("opacity", 1)
        .style("stroke", "black")

    d3.selectAll(".connection.vertical").filter(function (dd, ii) {
        return ii == i;
    })
        .style("opacity", 1)
        .style("stroke", "black")

    d3.selectAll(".setSize").filter(function (dd, ii) {
        return ii == i;
    })
        .style("opacity", 1)
        .style("stroke", "black")
}

function mouseoutColumn(d, i) {

    d3.selectAll(".connection, .combination rect, .setSize")
        .style("opacity", 1)
        .style("stroke", "white")

}

function mouseoverRow(d, i) {

    // plot Venn diagram with highlighting of selected subset

    console.log(d);
    if ( d.data.type === 'SUBSET_TYPE') {
        plotVenn( "#venn-vis", 50, [ d.data ] );
    }

    if ( d.data.type === 'GROUP_TYPE') {
        plotVenn( "#venn-vis", 50, d.data.subSets );
    }

    d3.selectAll(".row .backgroundRect")
        .style("stroke",
            function(dd){
                if (d.id == dd.id) return "black";
                else null;
            })
}

function mouseoutRow(d, i) {

    // plot Venn diagram without highlighting
    plotVenn( "#venn-vis", 50 );

    d3.selectAll(".row .backgroundRect")
        .style("stroke",null)
}

function mouseoverCell(d, i) {

    mouseoverColumn(d, i);
    mouseoverRow(d3.select(this).node().parentNode.parentNode.__data__, 1)

}

function mouseoutCell(d, i) {

    mouseoutColumn(d, i);
    mouseoutRow(d, 1)

}<commit_msg>Removed console log output.<commit_after>function mouseoverColumn(d, i) {

    d3.selectAll(".connection, .combination rect, .setSize")
    //    .style("opacity", .3)
    .style("stroke", "white")

    d3.selectAll(".connection.diagonal").filter(function (dd, ii) {
        return ii == i;
    })
        .style("opacity", 1)
        .style("stroke", "black")

    d3.selectAll(".combination").selectAll("rect").filter(function (dd, ii) {
        return ii == i;
    })
        .style("opacity", 1)
        .style("stroke", "black")

    d3.selectAll(".connection.vertical").filter(function (dd, ii) {
        return ii == i;
    })
        .style("opacity", 1)
        .style("stroke", "black")

    d3.selectAll(".setSize").filter(function (dd, ii) {
        return ii == i;
    })
        .style("opacity", 1)
        .style("stroke", "black")
}

function mouseoutColumn(d, i) {

    d3.selectAll(".connection, .combination rect, .setSize")
        .style("opacity", 1)
        .style("stroke", "white")

}

function mouseoverRow(d, i) {

    // plot Venn diagram with highlighting of selected subset
    if ( d.data.type === 'SUBSET_TYPE') {
        plotVenn( "#venn-vis", 50, [ d.data ] );
    }

    if ( d.data.type === 'GROUP_TYPE') {
        plotVenn( "#venn-vis", 50, d.data.subSets );
    }

    d3.selectAll(".row .backgroundRect")
        .style("stroke",
            function(dd){
                if (d.id == dd.id) return "black";
                else null;
            })
}

function mouseoutRow(d, i) {

    // plot Venn diagram without highlighting
    plotVenn( "#venn-vis", 50 );

    d3.selectAll(".row .backgroundRect")
        .style("stroke",null)
}

function mouseoverCell(d, i) {

    mouseoverColumn(d, i);
    mouseoverRow(d3.select(this).node().parentNode.parentNode.__data__, 1)

}

function mouseoutCell(d, i) {

    mouseoutColumn(d, i);
    mouseoutRow(d, 1)

}<|endoftext|>


<commit_before>var JS_GAME = {};

JS_GAME.game = (function () {
  var isKeyDown = [];
  var context;
  var userData = [];
  var enemies = [];
  var frameLength = 1;// in milliseconds
  var socket;
  var connected = false;
  var user = "";
  var pass = "";
  var windowWidth = $(window).innerWidth();
  var windowHeight = $(window).innerHeight();

  function init() {
    user = document.getElementById("loginInfo").user.value;
    pass = document.getElementById("loginInfo").pass.value;
    if (user.indexOf(",") >= 0 || user.indexOf(":") >= 0){
      document.getElementById("loginInfo").user.value = "INVALID INPUT";
      return;
    }

    $("#user").blur();
    $("#pass").blur();
    $("#loginInfo").remove();

    socket = new WebSocket("ws:167.88.120.57:38734");

    socket.onopen = function() {
      connected = true;
      socket.send("login:" + user + "," + pass);
    };

socket.onmessage = function(message) {
  if (message.data.indexOf("pos") == 0){
  userData = message.data.split(":")[1].split(",");

} else if (message.data.indexOf("dat") == 0){
  enemies = message.data.split(":")[1].split(",");
}
};

socket.onclose = function() {
  window.location.reload(false);
};

socket.onerror = function() {
};

document.body.innerHTML = "";
for (i = 0; i < 256; i++){
  isKeyDown[i] = false;
}
$('body').append('<canvas id="GameCanvas">');
var canvasElement = $('#GameCanvas');
canvasElement.select().focus().click();
canvasElement.attr('width', windowWidth);
canvasElement.attr('height', windowHeight);
canvasElement.arrt('tabIndex', 1);
document.getElementById("GameCanvas").focus();
var canvas = canvasElement[0];
window.addEventListener( "keydown", keyPress, false);
window.addEventListener( "keyup", keyRelease, false);
context = canvas.getContext('2d');
gameLoop();
}

function gameLoop() {
  var keyData = "";
  for (i = 0; i < 256; i++){
    keyData += isKeyDown[i] ? 1 : 0;
  }
  try {
    socket.send("keys:" + keyData);
  } catch (err) {
  }
  context.clearRect(0, 0, windowWidth, windowHeight);
  //draw enemies
  for (i = 0; i < enemies.length; i += 4){
  context.fillStyle = enemies[i+2];
  context.fillRect(enemies[i], enemies[i+1], 30, 50);
  }
  //draw player
  context.fillStyle = userData[2];
  context.fillRect(userData[0], userData[1], 30, 50);
  //draw enemy names
  for (i = 0; i < enemies.length; i += 4){
  context.fillStyle = enemies[i+2];
  context.fillText(enemies[i+3],(enemies[i] - (context.measureText(enemies[i+3]).width / 2)) + 15,enemies[i+1] - 5);
  }
  //draw player name
  context.fillStyle = userData[2];
  context.font = "15px Arial";
  context.fillText(userData[3],(userData[0] - (context.measureText(userData[3]).width / 2)) + 15,userData[1] - 5);

  setTimeout(gameLoop, frameLength);
}

function keyPress(e){
  isKeyDown[e.keyCode] = true;
}
function keyRelease(e){
  isKeyDown[e.keyCode] = false;
}
function isKeyPressed(c){
  return isKeyDown[c.charCodeAt(0)];
}

return {
  init: init
};
})();

$(document).ready(function() {
  $("#loginInfo").submit(function(event){
    event.preventDefault();
    JS_GAME.game.init();
    return false;
  });
});
<commit_msg>I don't even<commit_after>var JS_GAME = {};

JS_GAME.game = (function () {
  var isKeyDown = [];
  var context;
  var userData = [];
  var enemies = [];
  var frameLength = 1;// in milliseconds
  var socket;
  var connected = false;
  var user = "";
  var pass = "";
  var windowWidth = $(window).innerWidth();
  var windowHeight = $(window).innerHeight();

  function init() {
    user = document.getElementById("loginInfo").user.value;
    pass = document.getElementById("loginInfo").pass.value;
    if (user.indexOf(",") >= 0 || user.indexOf(":") >= 0){
      document.getElementById("loginInfo").user.value = "INVALID INPUT";
      return;
    }

    $("#user").blur();
    $("#pass").blur();
    $("#loginInfo").remove();

    socket = new WebSocket("ws:167.88.120.57:38734");

    socket.onopen = function() {
      connected = true;
      socket.send("login:" + user + "," + pass);
    };

socket.onmessage = function(message) {
  if (message.data.indexOf("pos") == 0){
  userData = message.data.split(":")[1].split(",");

} else if (message.data.indexOf("dat") == 0){
  enemies = message.data.split(":")[1].split(",");
}
};

socket.onclose = function() {
  window.location.reload(false);
};

socket.onerror = function() {
};

document.body.innerHTML = "";
for (i = 0; i < 256; i++){
  isKeyDown[i] = false;
}
$('body').append('<canvas id="GameCanvas">');
var canvasElement = $('#GameCanvas');
canvasElement.attr('width', windowWidth);
canvasElement.attr('height', windowHeight);
canvasElement.attr('tabIndex', 1);
canvasElement.select().focus().click();

var canvas = canvasElement[0];

window.addEventListener( "keydown", keyPress, false);
window.addEventListener( "keyup", keyRelease, false);
context = canvas.getContext('2d');
gameLoop();
}

function gameLoop() {
  var keyData = "";
  for (i = 0; i < 256; i++){
    keyData += isKeyDown[i] ? 1 : 0;
  }
  try {
    socket.send("keys:" + keyData);
  } catch (err) {
  }
  context.clearRect(0, 0, windowWidth, windowHeight);
  //draw enemies
  for (i = 0; i < enemies.length; i += 4){
  context.fillStyle = enemies[i+2];
  context.fillRect(enemies[i], enemies[i+1], 30, 50);
  }
  //draw player
  context.fillStyle = userData[2];
  context.fillRect(userData[0], userData[1], 30, 50);
  //draw enemy names
  for (i = 0; i < enemies.length; i += 4){
  context.fillStyle = enemies[i+2];
  context.fillText(enemies[i+3],(enemies[i] - (context.measureText(enemies[i+3]).width / 2)) + 15,enemies[i+1] - 5);
  }
  //draw player name
  context.fillStyle = userData[2];
  context.font = "15px Arial";
  context.fillText(userData[3],(userData[0] - (context.measureText(userData[3]).width / 2)) + 15,userData[1] - 5);

  setTimeout(gameLoop, frameLength);
}

function keyPress(e){
  isKeyDown[e.keyCode] = true;
}
function keyRelease(e){
  isKeyDown[e.keyCode] = false;
}
function isKeyPressed(c){
  return isKeyDown[c.charCodeAt(0)];
}

return {
  init: init
};
})();

$(document).ready(function() {
  $("#loginInfo").submit(function(event){
    event.preventDefault();
    JS_GAME.game.init();
    return false;
  });
});
<|endoftext|>


<commit_before>var JS_GAME = {};

JS_GAME.game = (function () {
  var isKeyDown = [];
  var context;
  var userData = [];
  var enemies = [];
  var enemyStride = 7;
  var frameLength = 1;// in milliseconds
  var socket;
  var connected = false;
  var user = "";
  var pass = "";
  var windowWidth = $(window).innerWidth();
  var windowHeight = $(window).innerHeight();
  var textures = new Object();

  function init() {
  	document.documentElement.style.overflow = 'hidden';  // firefox, chrome
    document.body.scroll = "no"; // ie only

    user = document.getElementById("loginInfo").user.value;
    pass = document.getElementById("loginInfo").pass.value;
    if (user.indexOf(",") >= 0 || user.indexOf(":") >= 0){
      document.getElementById("loginInfo").user.value = "INVALID INPUT";
      return;
    }

    socket = new WebSocket("ws:167.88.120.57:38734");

    socket.onopen = function() {
      connected = true;
      socket.send("login:" + user + "," + pass);
    };

    socket.onmessage = function(message) {
      if (message.data.indexOf("pos") == 0){
        userData = message.data.split(":")[1].split(",");
        for (i = 0; i < 4; i++) {
          userData[i] = Number(userData[i]);
        }
      } else if (message.data.indexOf("dat") == 0){
        enemies = message.data.split(":")[1].split(",");
        enemyStride = Number(message.data.split(":")[0].replace("dat", ""));
      }
    };

    socket.onclose = function() {
      window.location.reload(false);
    };

    socket.onerror = function() {

    };

    $("body").empty();

    for (i = 0; i < 256; i++){
      isKeyDown[i] = false;
    }
    $('body').append('<canvas id="GameCanvas">');
    canvasElement = $('#GameCanvas');
    canvasElement.attr({
      width: windowWidth / 2,
      height: windowHeight / 2,
      style: "width: " + windowWidth + "px; height: " + windowHeight + "px;",
      tabIndex: 0,
      onblur: clearInput,
    }).focus();
    window.onblur = clearInput;

    var canvas = canvasElement[0];

    window.addEventListener( "keydown", keyPress, false);
    window.addEventListener( "keyup", keyRelease, false);
    context = canvas.getContext('2d');
    context.globalCompositeOperation = "normal";
    gameLoop();

    $(window).resize(function() {
      windowWidth = $(window).innerWidth();
      windowHeight = $(window).innerHeight();

      canvasElement.attr({
        width: windowWidth / 2,
        height: windowHeight / 2,
        style: "width: " + windowWidth + "px; height: " + windowHeight + "px;"
      });
    });
  }

  function gameLoop() {
    var keyData = "";
    for (i = 0; i < 256; i++){
      keyData += isKeyDown[i] ? 1 : 0;
    }
    try {
      socket.send("keys:" + keyData);
    } catch (err) {
    }
    context.clearRect(0, 0, windowWidth, windowHeight);
    context.fillStyle = "#FFFFFF"
    context.fillRect(0, 0, windowWidth, windowHeight);
    //draw BG
    for (a = -2; a < 3; a++){
    	for (b = -2; b < 3; b++){
    		context.drawImage(getImage("BG"), (gPIVX(0) % 1000) + (1000 * a), (gPIVY(0) % 1000) + (1000 * b), 1000, 1000);
    	}
    }
    //draw enemies
    for (i = 0; i < enemies.length; i += enemyStride){
      context.fillStyle = enemies[i+4];
      context.drawImage(getImageMasked("player", enemies[i+4]),gPIVX(enemies[i]), gPIVY(enemies[i+1]), enemies[i+2], enemies[i+3]);
    }

    //draw enemy names
    for (i = 0; i < enemies.length; i += enemyStride){
      context.fillStyle = enemies[i+4];
      context.fillText(enemies[i+5],(gPIVX(enemies[i]) - (context.measureText(enemies[i+5]).width / 2)) + 15,gPIVY(enemies[i+1]) - 5);
    }

    //draw player name
    //context.fillStyle = userData[4];
    //context.font = "15px Arial";
    //context.fillText(userData[5],(gPIVX(userData[0]) - (context.measureText(userData[5]).width / 2)) + 15,gPIVY(userData[1]) - 5);

    setTimeout(gameLoop, frameLength);
  }

  function gPIVX(x){
    //getPositionInViewportX
    var ret = new Object();
    return ((x - (userData[0] + (userData[2] / 2))) + (windowWidth / 2.0));
  }
  function gPIVY(y){
    //getPositionInViewportY
    return ((y - (userData[1] + (userData[3] / 2))) + (windowHeight / 2.0));
  }

  function clearInput(){
    for (i = 0; i < 256; i++){
      isKeyDown[i] = false;
    }
  }

  function keyPress(e){
    e.preventDefault();
    isKeyDown[e.keyCode] = true;
    return false;
  }
  function keyRelease(e){
    e.preventDefault();
    isKeyDown[e.keyCode] = false;
  }
  function isKeyPressed(c){
    return isKeyDown[c.charCodeAt(0)];
  }

  function getImageData(image){
    var tempCanv = document.createElement('canvas');
    tempCanv.width = image.width;
    tempCanv.height = image.height;
    var tempCTX = tempCanv.getContext('2d');
    tempCTX.drawImage(image, 0, 0, image.width, image.height);
    return tempCTX.getImageData(0, 0, image.width, image.height);
  }

  function getImage(name){
  	if ((name) in textures){
  		return textures[name];
  	} else {
  		textures[name] = new Image;
  		textures[name].src = 'http://monolc.com/FellJS/res/' + name + '.png';
  		return textures[name];
  	}
  }
  function getImageMasked(name, color){
  	if ((name + "-mask" + color) in textures){
  		return textures[name + "-mask" + color];
  	}
    var image = getImage(name);
    var mask = getImage(name + "-mask");
    if (image.width == 0 || image.height == 0 || mask.width == 0 || mask.height == 0){
      return new Image();
    }
    var maskData = getImageData(mask);
    var regex = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i;
    var colorRGBS = regex.exec(color);
    console.log(color + "|" + colorRGBS[0] + "|" + colorRGBS[1] + "|" + colorRGBS[2] + "|" + colorRGBS[3]);
    var colorRGB = [];
    for (i = 0; i < 3; i++){
      colorRGB[i] = parseInt(colorRGBS[i+1], 16);
    }
    for (i = 0; i < maskData.data.length; i+=4){
      maskData.data[i] =  colorRGB[0];
      maskData.data[i+1] =  colorRGB[1];
      maskData.data[i+2] =  colorRGB[2];
    }
    var tempCanv = document.createElement('canvas');
    tempCanv.width = image.width;
    tempCanv.height = image.height;
    var tempCTX=tempCanv.getContext("2d");
    tempCTX.drawImage(image,0,0,image.width, image.height);
    tempCTX.putImageData(maskData, 0, 0)
    var ret = new Image();
    ret.src = tempCanv.toDataURL("image/png");
    textures[name + "-mask" + color] = ret;
    return ret;
  }

  return {
    init: init
  };
})();

$(document).ready(function() {
  $("#loginInfo").submit(function(e){
    e.preventDefault();
    JS_GAME.game.init();
    return false;
  });
});
<commit_msg>scaling fix<commit_after>var JS_GAME = {};

JS_GAME.game = (function () {
  var isKeyDown = [];
  var context;
  var userData = [];
  var enemies = [];
  var enemyStride = 7;
  var frameLength = 1;// in milliseconds
  var socket;
  var connected = false;
  var user = "";
  var pass = "";
  var windowWidth = $(window).innerWidth();
  var windowHeight = $(window).innerHeight();
  var canvasWidth = windowWidth / 2;
  var canvasHeight = windowHeight / 2;
  var textures = new Object();

  function init() {
  	document.documentElement.style.overflow = 'hidden';  // firefox, chrome
    document.body.scroll = "no"; // ie only

    user = document.getElementById("loginInfo").user.value;
    pass = document.getElementById("loginInfo").pass.value;
    if (user.indexOf(",") >= 0 || user.indexOf(":") >= 0){
      document.getElementById("loginInfo").user.value = "INVALID INPUT";
      return;
    }

    socket = new WebSocket("ws:167.88.120.57:38734");

    socket.onopen = function() {
      connected = true;
      socket.send("login:" + user + "," + pass);
    };

    socket.onmessage = function(message) {
      if (message.data.indexOf("pos") == 0){
        userData = message.data.split(":")[1].split(",");
        for (i = 0; i < 4; i++) {
          userData[i] = Number(userData[i]);
        }
      } else if (message.data.indexOf("dat") == 0){
        enemies = message.data.split(":")[1].split(",");
        enemyStride = Number(message.data.split(":")[0].replace("dat", ""));
      }
    };

    socket.onclose = function() {
      window.location.reload(false);
    };

    socket.onerror = function() {

    };

    $("body").empty();

    for (i = 0; i < 256; i++){
      isKeyDown[i] = false;
    }
    $('body').append('<canvas id="GameCanvas">');
    canvasElement = $('#GameCanvas');
    canvasElement.attr({
      width: canvasWidth,
      height: canvasHeight,
      style: "width: " + windowWidth + "px; height: " + windowHeight + "px;",
      tabIndex: 0,
      onblur: clearInput,
    }).focus();
    window.onblur = clearInput;

    var canvas = canvasElement[0];

    window.addEventListener( "keydown", keyPress, false);
    window.addEventListener( "keyup", keyRelease, false);
    context = canvas.getContext('2d');
    context.globalCompositeOperation = "normal";
    gameLoop();

    $(window).resize(function() {
      windowWidth = $(window).innerWidth();
      windowHeight = $(window).innerHeight();
      canvasWidth = windowWidth / 2;
      canvasHeight = windowHeight / 2;

      canvasElement.attr({
        width: canvasWidth,
        height: canvasHeight,
        style: "width: " + windowWidth + "px; height: " + windowHeight + "px;"
      });
    });
  }

  function gameLoop() {
    var keyData = "";
    for (i = 0; i < 256; i++){
      keyData += isKeyDown[i] ? 1 : 0;
    }
    try {
      socket.send("keys:" + keyData);
    } catch (err) {
    }
    context.clearRect(0, 0, windowWidth, windowHeight);
    context.fillStyle = "#FFFFFF"
    context.fillRect(0, 0, windowWidth, windowHeight);
    //draw BG
    for (a = -2; a < 3; a++){
    	for (b = -2; b < 3; b++){
    		context.drawImage(getImage("BG"), (gPIVX(0) % 1000) + (1000 * a), (gPIVY(0) % 1000) + (1000 * b), 1000, 1000);
    	}
    }
    //draw enemies
    for (i = 0; i < enemies.length; i += enemyStride){
      context.fillStyle = enemies[i+4];
      context.drawImage(getImageMasked("player", enemies[i+4]),gPIVX(enemies[i]), gPIVY(enemies[i+1]), enemies[i+2], enemies[i+3]);
    }

    //draw enemy names
    for (i = 0; i < enemies.length; i += enemyStride){
      context.fillStyle = enemies[i+4];
      context.fillText(enemies[i+5],(gPIVX(enemies[i]) - (context.measureText(enemies[i+5]).width / 2)) + 15,gPIVY(enemies[i+1]) - 5);
    }

    //draw player name
    //context.fillStyle = userData[4];
    //context.font = "15px Arial";
    //context.fillText(userData[5],(gPIVX(userData[0]) - (context.measureText(userData[5]).width / 2)) + 15,gPIVY(userData[1]) - 5);

    setTimeout(gameLoop, frameLength);
  }

  function gPIVX(x){
    //getPositionInViewportX
    var ret = new Object();
    return ((x - (userData[0] + (userData[2] / 2))) + (canvasWidth / 2.0));
  }
  function gPIVY(y){
    //getPositionInViewportY
    return ((y - (userData[1] + (userData[3] / 2))) + (canvasHeight / 2.0));
  }

  function clearInput(){
    for (i = 0; i < 256; i++){
      isKeyDown[i] = false;
    }
  }

  function keyPress(e){
    e.preventDefault();
    isKeyDown[e.keyCode] = true;
    return false;
  }
  function keyRelease(e){
    e.preventDefault();
    isKeyDown[e.keyCode] = false;
  }
  function isKeyPressed(c){
    return isKeyDown[c.charCodeAt(0)];
  }

  function getImageData(image){
    var tempCanv = document.createElement('canvas');
    tempCanv.width = image.width;
    tempCanv.height = image.height;
    var tempCTX = tempCanv.getContext('2d');
    tempCTX.drawImage(image, 0, 0, image.width, image.height);
    return tempCTX.getImageData(0, 0, image.width, image.height);
  }

  function getImage(name){
  	if ((name) in textures){
  		return textures[name];
  	} else {
  		textures[name] = new Image;
  		textures[name].src = 'http://monolc.com/FellJS/res/' + name + '.png';
  		return textures[name];
  	}
  }
  function getImageMasked(name, color){
  	if ((name + "-mask" + color) in textures){
  		return textures[name + "-mask" + color];
  	}
    var image = getImage(name);
    var mask = getImage(name + "-mask");
    if (image.width == 0 || image.height == 0 || mask.width == 0 || mask.height == 0){
      return new Image();
    }
    var maskData = getImageData(mask);
    var regex = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i;
    var colorRGBS = regex.exec(color);
    console.log(color + "|" + colorRGBS[0] + "|" + colorRGBS[1] + "|" + colorRGBS[2] + "|" + colorRGBS[3]);
    var colorRGB = [];
    for (i = 0; i < 3; i++){
      colorRGB[i] = parseInt(colorRGBS[i+1], 16);
    }
    for (i = 0; i < maskData.data.length; i+=4){
      maskData.data[i] =  colorRGB[0];
      maskData.data[i+1] =  colorRGB[1];
      maskData.data[i+2] =  colorRGB[2];
    }
    var tempCanv = document.createElement('canvas');
    tempCanv.width = image.width;
    tempCanv.height = image.height;
    var tempCTX=tempCanv.getContext("2d");
    tempCTX.drawImage(image,0,0,image.width, image.height);
    tempCTX.putImageData(maskData, 0, 0)
    var ret = new Image();
    ret.src = tempCanv.toDataURL("image/png");
    textures[name + "-mask" + color] = ret;
    return ret;
  }

  return {
    init: init
  };
})();

$(document).ready(function() {
  $("#loginInfo").submit(function(e){
    e.preventDefault();
    JS_GAME.game.init();
    return false;
  });
});
<|endoftext|>


<commit_before>var JS_GAME = {};

JS_GAME.game = (function () {
  var isKeyDown = [];
  var context;
  var userData = [];
  var enemies = [];
  var frameLength = 1;// in milliseconds
  var socket;
  var connected = false;
  var user = "";
  var pass = "";

  function init() {
    user = document.getElementById("loginInfo").user.value;
    pass = document.getElementById("loginInfo").pass.value;
    $("#user").blur();
    $("#pass").blur();
    $("#loginInfo").remove();
    if (user.indexOf(",") >= 0 || user.indexOf(":") >= 0){
      document.getElementById("loginInfo").user.value = "INVALID INPUT";
      return;
    }
    socket = new WebSocket("ws:167.88.120.57:38734");

    socket.onopen = function() {
      connected = true;
      socket.send("login:" + user + "," + pass);
    };

socket.onmessage = function(message) {
  if (message.data.indexOf("pos") == 0){
  userData = message.data.split(":")[1].split(",");

} else if (message.data.indexOf("dat") == 0){
  enemies = message.data.split(":")[1].split(",");
}
};

socket.onclose = function() {
  window.location.reload(false);
};

socket.onerror = function() {
};

document.body.innerHTML = "";
for (i = 0; i < 256; i++){
  isKeyDown[i] = false;
}
$('body').append('<canvas id="GameCanvas">');
var $canvas = $('#GameCanvas');
$canvas.select().focus().click();
$canvas.attr('width', $(window).innerWidth());
$canvas.attr('height', $(window).innerHeight());
$canvas.arrt('tabIndex', 1);
$canvas.focus();
var canvas = $canvas[0];
window.addEventListener( "keydown", keyPress, false);
window.addEventListener( "keyup", keyRelease, false);
context = canvas.getContext('2d');
gameLoop();
}

function gameLoop() {
  var keyData = "";
  for (i = 0; i < 256; i++){
    keyData += isKeyDown[i] ? 1 : 0;
  }
  try {
    socket.send("keys:" + keyData);
  } catch (err) {
  }
  context.clearRect(0, 0, document.body.clientWidth, document.body.clientHeight);
  //draw enemies
  for (i = 0; i < enemies.length; i += 4){
  context.fillStyle = enemies[i+2];
  context.fillRect(enemies[i], enemies[i+1], 30, 50);
  }
  //draw player
  context.fillStyle = userData[2];
  context.fillRect(userData[0], userData[1], 30, 50);
  //draw enemy names
  for (i = 0; i < enemies.length; i += 4){
  context.fillStyle = enemies[i+2];
  context.fillText(enemies[i+3],(enemies[i] - (context.measureText(enemies[i+3]).width / 2)) + 15,enemies[i+1] - 5);
  }
  //draw player name
  context.fillStyle = userData[2];
  context.font = "15px Arial";
  context.fillText(userData[3],(userData[0] - (context.measureText(userData[3]).width / 2)) + 15,userData[1] - 5);

  setTimeout(gameLoop, frameLength);
}

function keyPress(e){
  isKeyDown[e.keyCode] = true;
}
function keyRelease(e){
  isKeyDown[e.keyCode] = false;
}
function isKeyPressed(c){
  return isKeyDown[c.charCodeAt(0)];
}

return {
  init: init
};
})();

$(document).ready(function() {
  $("#loginInfo").submit(function(event){
    event.preventDefault();
    JS_GAME.game.init();
    return false;
  });
});
<commit_msg>Revet more!<commit_after>var JS_GAME = {};

JS_GAME.game = (function () {
  var isKeyDown = [];
  var context;
  var userData = [];
  var enemies = [];
  var frameLength = 1;// in milliseconds
  var socket;
  var connected = false;
  var user = "";
  var pass = "";

  function init() {
    user = document.getElementById("loginInfo").user.value;
    pass = document.getElementById("loginInfo").pass.value;
    $("#user").blur();
    $("#pass").blur();
    $("#loginInfo").remove();
    if (user.indexOf(",") >= 0 || user.indexOf(":") >= 0){
      document.getElementById("loginInfo").user.value = "INVALID INPUT";
      return;
    }
    socket = new WebSocket("ws:167.88.120.57:38734");

    socket.onopen = function() {
      connected = true;
      socket.send("login:" + user + "," + pass);
    };

socket.onmessage = function(message) {
  if (message.data.indexOf("pos") == 0){
  userData = message.data.split(":")[1].split(",");

} else if (message.data.indexOf("dat") == 0){
  enemies = message.data.split(":")[1].split(",");
}
};

socket.onclose = function() {
  window.location.reload(false);
};

socket.onerror = function() {
};

document.body.innerHTML = "";
for (i = 0; i < 256; i++){
  isKeyDown[i] = false;
}
$('body').append('<canvas id="GameCanvas">');
var $canvas = $('#GameCanvas');
$canvas.select().focus().click();
$canvas.attr('width', $(window).innerWidth());
$canvas.attr('height', $(window).innerHeight());
$canvas.arrt('tabIndex', 1);
document.getElementById("GameCanvas").focus();
var canvas = $canvas[0];
window.addEventListener( "keydown", keyPress, false);
window.addEventListener( "keyup", keyRelease, false);
context = canvas.getContext('2d');
gameLoop();
}

function gameLoop() {
  var keyData = "";
  for (i = 0; i < 256; i++){
    keyData += isKeyDown[i] ? 1 : 0;
  }
  try {
    socket.send("keys:" + keyData);
  } catch (err) {
  }
  context.clearRect(0, 0, document.body.clientWidth, document.body.clientHeight);
  //draw enemies
  for (i = 0; i < enemies.length; i += 4){
  context.fillStyle = enemies[i+2];
  context.fillRect(enemies[i], enemies[i+1], 30, 50);
  }
  //draw player
  context.fillStyle = userData[2];
  context.fillRect(userData[0], userData[1], 30, 50);
  //draw enemy names
  for (i = 0; i < enemies.length; i += 4){
  context.fillStyle = enemies[i+2];
  context.fillText(enemies[i+3],(enemies[i] - (context.measureText(enemies[i+3]).width / 2)) + 15,enemies[i+1] - 5);
  }
  //draw player name
  context.fillStyle = userData[2];
  context.font = "15px Arial";
  context.fillText(userData[3],(userData[0] - (context.measureText(userData[3]).width / 2)) + 15,userData[1] - 5);

  setTimeout(gameLoop, frameLength);
}

function keyPress(e){
  isKeyDown[e.keyCode] = true;
}
function keyRelease(e){
  isKeyDown[e.keyCode] = false;
}
function isKeyPressed(c){
  return isKeyDown[c.charCodeAt(0)];
}

return {
  init: init
};
})();

$(document).ready(function() {
  $("#loginInfo").submit(function(event){
    event.preventDefault();
    JS_GAME.game.init();
    return false;
  });
});
<|endoftext|>


<commit_before>
var intervalInSeconds = 30;
var interval = intervalInSeconds * 1000;
var newMessages = new Array();

function loadNewMessagesTicker() {
    var sinceId = $(".message:first-child > input[name=id]").val();

    $.get("/api/messagesSince/" + sinceId, function (messages) {
        if (messages.length > 0) {
            newMessages = messages;
            $("#show-new-btn").text("Show " + newMessages.length + " new messages");
            $("#show-new-btn").show();
        }
    });

    setTimeout(loadNewMessagesTicker, interval);
}

function loadOlderMessages() {
    var maxId = $(".message:last-child > input[name=id]").val();

    $.get("/api/messagesUntil/" + maxId, function (messages) {
        for (var i = 0; i < messages.length; i++) {
            var message = messages[i];
            var html = formatMessage(message);
            $("#message-stream").append(html);
        }
        $("#load-more-btn").show();
    });
}

function formatMessage(message) {
    var created = convertToDate(message.Created);

    var html =
        "
" +
        "<input type='hidden' name='id' value='" + message.Id + "'/>" +
        "<input type='hidden' name='created' value='" + created + "'/>" +
        "" +
        "
" +
        "" + message.User.Name + "" +
        "" + created + "" +
        "
" +
        "
" + message.Text + "
" +
        "
";
    return html;
}

function convertToDate(value) {
    var a = /\/Date\((\d*)\)\//.exec(value);
    return new Date(+a[1]);
}

$(function () {

    $("#show-new-btn").hide();

    /* ---------------------
     * Load initial messages
     * ---------------------*/

    $.get("/api/messages", function (messages) {
        for (var i = 0; i < messages.length; i++) {
            var message = messages[i];
            var html = formatMessage(message);
            $("#message-stream").append(html);
        }
    });

    /* ---------------------
     * Poll messages
     * ---------------------*/

    setTimeout(loadNewMessagesTicker, interval);

    /* ---------------------
     * Register Button events
     * ---------------------*/

    $("#load-more-btn").click(function (event) {
        event.preventDefault();
        $(this).hide();
        loadOlderMessages();
    });

    $("#show-new-btn").click(function (event) {
        event.preventDefault();
        for (var i = 0; i < newMessages.length; i++) {
            var message = newMessages[i];
            var html = formatMessage(message);
            $("#message-stream").prepend(html);
        }
        $(this).hide();
    });
});<commit_msg>Hacking correct JS behaviour together.<commit_after>
var intervalInSeconds = 10;
var interval = intervalInSeconds * 1000;
var newMessages = new Array();
var messageIds = new Array();

function loadNewMessagesTicker() {
    var sinceId = messageIds[0];

    $.get("/api/messagesSince/" + sinceId, function (messages) {
        if (messages.length > 0) {
            for (var i = messages.length - 1; i >= 0; i--) {
                var message = messages[i];

                if ($.inArray(message.Id, messageIds) === -1) {
                    newMessages.unshift(message);
                    messageIds.unshift(message.Id);
                }
            }

            if (newMessages.length > 0) {
                $("#show-new-btn").text("Show " + newMessages.length + " new messages");
                $("#show-new-btn").show();
            }
        }
    });

    setTimeout(loadNewMessagesTicker, interval);
}

function loadOlderMessages() {
    var maxId = $(".message:last-child > input[name=id]").val();

    $.get("/api/messagesUntil/" + maxId, function (messages) {
        // skipping the first message, because it is a duplicate
        for (var i = 1; i < messages.length; i++) {
            var message = messages[i];
            var html = formatMessage(message);
            $("#message-stream").append(html);
        }
        $("#load-more-btn").show();
    });
}

function formatMessage(message) {
    var created = convertToDate(message.Created);

    var html =
        "
" +
        "<input type='hidden' name='id' value='" + message.Id + "'/>" +
        "<input type='hidden' name='created' value='" + created + "'/>" +
        "" +
        "
" +
        "" + message.User.Name + "" +
        "" + created.toString().replace(" GMT+0000 (GMT Standard Time)", "") + "" +
        "
" +
        "
" + message.Text + "
" +
        "
";
    return html;
}

function convertToDate(value) {
    var a = /\/Date\((\d*)\)\//.exec(value);
    return new Date(+a[1]);
}

$(function () {

    $("#show-new-btn").hide();

    $.get("/api/messages", function (messages) {
        for (var i = 0; i < messages.length; i++) {
            var message = messages[i];
            var html = formatMessage(message);
            $("#message-stream").append(html);
            messageIds.push(message.Id);
        }

        setTimeout(loadNewMessagesTicker, interval);
    });

    $("#load-more-btn").click(function (event) {
        event.preventDefault();
        $(this).hide();
        loadOlderMessages();
    });

    $("#show-new-btn").click(function (event) {
        event.preventDefault();
        for (var i = newMessages.length - 1; i >= 0; i--) {
            var message = newMessages[i];
            var html = formatMessage(message);
            $("#message-stream").prepend(html);
            newMessages.splice(i, 1);
        }
        $(this).hide();
    });
});<|endoftext|>


<commit_before><commit_msg>shoot me<commit_after><|endoftext|>


<commit_before><commit_msg>Deleted file<commit_after><|endoftext|>


<commit_before>/**
 *
 */

VK.init({
	apiId : 1755175
});

var WRONG_TEXT = 'Something goes wrong. Enter valid post address.';

var grp = '';
var us = '';
var grpAvatar = '';

var obj = [];
var parsed = [0, 0];

var grCount = 0;
var grOffset = 0;

var sexArray;
var manpos = [];
var sexCountArray = [0,0,0];
var wompos = [];
var onopos = [];
var wArray = [];
var mArray = [];
var m = 0;
var w = 0;

function getGroupInfo(groupId) {// ??? 2nd main funtion

	VK.api("groups.getById", {
		'group_id' : Math.abs(groupId),
		'fields' : 'members_count,photo_100'
	}, function(data) {
		if (data.error) {
			errorMSG('Error in data. Wrong group data.')
		} else {
			for (var i = 0; i < data.response.length; i++) {
				grp = data.response[i].name;
				us = data.response[i].members_count;
				grpAvatar = data.response[i].photo_100;

				obj[0] = grp;
				obj[1] = us;
				obj[2] = grpAvatar;

			}
			groupViewChanges(getGroupData());
			//UI changes
			getGroupMembers(getParsedInfo(),0);
		}
	});

}

function getGroupMembers(objTargets, offset) {
	var aboutPost = objTargets;
	// 0-group, 1-item_post
	var code = '';
	code = 'var c=0;var co=100;var p=[];var i=0;var o=' + offset + ';var u=[];' + 'while(i!=10) {var li=API.likes.getList({"type":"post","owner_id":' + aboutPost[0] + ',"item_id":' + aboutPost[1] + ',"filter":"likes","friends_only":0,"offset":o,"count":co});'
	+ 'c=li.count;u=u+API.users.get({"user_ids":li.users,"fields":"sex"})@.sex;i=i+1;o=o+co;}'
	+ 'return {"count":c,"sex":u};';

	VK.api('execute', {'code' : code,}, function(data) {
		if (data.response.error) {
			errorMSG('Wrong: Group Member');
			console.log("error");
		} else {

			document.getElementById("m_members").innerHTML = 'Count: ' + data.response.count + ' members.' + " L: " + data.response.sex.length;
			document.getElementById("pCaption").innerHTML = '

'+data.response.sex.length;
			var dtd = data.response.sex;
			var cM = data.response.count;
			sexArray = dtd;//JSON.parse("["+data.response.sex+"]");
			//put different in array.
			for (var i = 0; i < sexArray.length; i++) {// 1 man 2 woman
				if (sexArray[i] == 1) {
					sexCountArray[1]++;
					manpos.push(i);
				}
				if (sexArray[i] == 2){
					sexCountArray[2]++;
					wompos.push(i);
				}
				if (sexArray[i] == 0){
					sexCountArray[0]++;
					onopos.push(i);
				}
			}

			console.log("0: "+sexCountArray[0]);
			console.log("1: "+sexCountArray[1]);
			console.log("2: "+sexCountArray[2]);

			console.log("sArray: "+sexArray.length);
		}
	});
}

function getGroupData() {//data for groupName,groupMembersCount, avatar.
	return obj;
}

function getParsedInfo() {//getting obj {groupID, postID}
	return parsed;
}

function waiting() {//maybe wait some time
	var se = 0;
	var t = setTimeout(function() {
		if (se > 1) {
			waiting();
			console.log('waits ----------------------------------');
			se = 0;
		}
		se++;
	}, 500);
}

function groupViewChanges(obj) {//changes UI view
	var a = obj;
	document.getElementById('groupName').innerHTML = 'Name: ' + a[0];
	document.getElementById('members_count').innerHTML = 'Count: ' + a[1];
	document.getElementById('av').src = a[2];
}

function parseLink() {// main function for parse link from text area.
	var link = String(document.getElementById('post').value);

	if (link != '' && (link.match('vk.com') == 'vk.com') && (link.match('wall-') == 'wall-')) {

		if (link.indexOf('=wall') != -1) {
			var adr = link.substring(link.indexOf('=wall') + 5, link.length);
			var p = adr.split('_');
			if ((p[0] === undefined) && (p[1] === undefined)) {
				errorMSG('Wrong: group or post or both');
			} else {
				if ((/\d+/.test(p[0])) && (/\d+/.test(p[1]))) {
					parsed[0] = p[0];
					parsed[1] = p[1];
					getGroupInfo(parsed[0]);
				}

			}
		} else {
			errorMSG('Wrong: not wall post');
		}
	} else {
		errorMSG('Wrong: not vk.com');
	}
}

function clearadress() {// clear text area
	document.getElementById('post').value = '';
}

function errorMSG(msg) {// shows error messages in main text area
	document.getElementById('post').value = msg;
	var t = setTimeout(clearadress, 1000);
}<commit_msg>ans fix<commit_after>/**
 *
 */

VK.init({
	apiId : 1755175
});

var WRONG_TEXT = 'Something goes wrong. Enter valid post address.';

var grp = '';
var us = '';
var grpAvatar = '';

var obj = [];
var parsed = [0, 0];

var grCount = 0;
var grOffset = 0;

var sexArray;
var manpos = [];
var sexCountArray = [0,0,0];
var wompos = [];
var onopos = [];
var wArray = [];
var mArray = [];
var m = 0;
var w = 0;

function getGroupInfo(groupId) {// ??? 2nd main funtion

	VK.api("groups.getById", {
		'group_id' : Math.abs(groupId),
		'fields' : 'members_count,photo_100'
	}, function(data) {
		if (data.error) {
			errorMSG('Error in data. Wrong group data.')
		} else {
			for (var i = 0; i < data.response.length; i++) {
				grp = data.response[i].name;
				us = data.response[i].members_count;
				grpAvatar = data.response[i].photo_100;

				obj[0] = grp;
				obj[1] = us;
				obj[2] = grpAvatar;

			}
			groupViewChanges(getGroupData());
			//UI changes
			getGroupMembers(getParsedInfo(),0);
		}
	});

}

function getGroupMembers(objTargets, offset) {
	var aboutPost = objTargets;
	// 0-group, 1-item_post
	var code = '';
	code = 'var c=0;var co=100;var p=[];var i=0;var o=' + offset + ';var u=[];' + 'while(i!=10) {var li=API.likes.getList({"type":"post","owner_id":' + aboutPost[0] + ',"item_id":' + aboutPost[1] + ',"filter":"likes","friends_only":0,"offset":o,"count":co});'
	+ 'c=li.count;u=u+API.users.get({"user_ids":li.users,"fields":"sex"})@.sex;i=i+1;o=o+co;}'
	+ 'return {"count":c,"sex":u};';

	VK.api('execute', {'code' : code,}, function(data) {
		if (data.response.error) {
			errorMSG('Wrong: Group Member');
			console.log("error");
		} else {

			document.getElementById("m_members").innerHTML = 'Count: ' + data.response.count + ' members.' + " L: " + data.response.sex.length;

			var dtd = data.response.sex;
			var cM = data.response.count;
			sexArray = dtd;//JSON.parse("["+data.response.sex+"]");
			document.getElementById("pCaption").innerHTML = '

'+data.response.sex.length;
			//put different in array.
			for (var i = 0; i < sexArray.length; i++) {// 1 man 2 woman
				if (sexArray[i] == 1) {
					sexCountArray[1]++;
					manpos.push(i);
				}
				if (sexArray[i] == 2){
					sexCountArray[2]++;
					wompos.push(i);
				}
				if (sexArray[i] == 0){
					sexCountArray[0]++;
					onopos.push(i);
				}
			}

			console.log("0: "+sexCountArray[0]);
			console.log("1: "+sexCountArray[1]);
			console.log("2: "+sexCountArray[2]);

			console.log("sArray: "+sexArray.length);
		}
	});
}

function getGroupData() {//data for groupName,groupMembersCount, avatar.
	return obj;
}

function getParsedInfo() {//getting obj {groupID, postID}
	return parsed;
}

function waiting() {//maybe wait some time
	var se = 0;
	var t = setTimeout(function() {
		if (se > 1) {
			waiting();
			console.log('waits ----------------------------------');
			se = 0;
		}
		se++;
	}, 500);
}

function groupViewChanges(obj) {//changes UI view
	var a = obj;
	document.getElementById('groupName').innerHTML = 'Name: ' + a[0];
	document.getElementById('members_count').innerHTML = 'Count: ' + a[1];
	document.getElementById('av').src = a[2];
}

function parseLink() {// main function for parse link from text area.
	var link = String(document.getElementById('post').value);

	if (link != '' && (link.match('vk.com') == 'vk.com') && (link.match('wall-') == 'wall-')) {

		if (link.indexOf('=wall') != -1) {
			var adr = link.substring(link.indexOf('=wall') + 5, link.length);
			var p = adr.split('_');
			if ((p[0] === undefined) && (p[1] === undefined)) {
				errorMSG('Wrong: group or post or both');
			} else {
				if ((/\d+/.test(p[0])) && (/\d+/.test(p[1]))) {
					parsed[0] = p[0];
					parsed[1] = p[1];
					getGroupInfo(parsed[0]);
				}

			}
		} else {
			errorMSG('Wrong: not wall post');
		}
	} else {
		errorMSG('Wrong: not vk.com');
	}
}

function clearadress() {// clear text area
	document.getElementById('post').value = '';
}

function errorMSG(msg) {// shows error messages in main text area
	document.getElementById('post').value = msg;
	var t = setTimeout(clearadress, 1000);
}<|endoftext|>