<commit_before>/**
 * slider-easy is such a directive which generate a slider bar, and
 * helps developer select the desired value
 *
 * @param option[expression]
 *              start[number]: a number of start point
 *              end[number]: a number of end point
 *              handles[array]: init points. if you want a range returned, this
 *                              has to be set
 *              decimals[int]: the number you want to keep as decimal
 *              outFormatter[function]: the function used to format the text at
 *                                      hint area
 * @author Howard.Zuo
 * @date   Sep 19th, 2014
 *
 **/
(function(angular, document, window) {
    'use strict';

    var mod = angular.module('angular-slider-easy', []);

    var handle = '

';

    var defaults = {
        start: 0,
        end: 100,
        decimals: 0,
        outFormatter: function(value) {
            if (value.point) {
                return 'Point is: ' + value.point;
            } else {
                return 'Range is: ' + (value.end - value.start);
            }
        }
    };

    var _defaults = function(dest, src) {
        var dst = dest || {};
        if (!src || typeof src !== 'object') {
            return dst;
        }
        for (var i in src) {
            if (!dst[i] && typeof src[i] !== undefined & src[i] !== null) {
                dst[i] = src[i];
            }
        }
        return dst;
    };

    var isNumber = function(n) {
        return !isNaN(parseFloat(n)) && isFinite(n);
    };

    var isPositiveInt = function(n) {
        return n === parseInt(n) && n === Math.abs(n);
    };

    var validate = function(options) {
        if (!isNumber(options.start)) {
            throw new Error('start must be number');
        }
        if (!isNumber(options.end)) {
            throw new Error('end must be number');
        }
        if (!isPositiveInt(options.decimals)) {
            throw new Error('decimals must be +int');
        }
        if (options.handles && !isNumber(options.handles[0])) {
            throw new Error('init 0 must be number');
        }
        if (options.handles && options.handles[1] && !isNumber(options.handles[1])) {
            throw new Error('init 1 must be number');
        }
    };

    var getEvent = function(e) {
        if (e.touches && e.touches.length > 0) {
            return e.touches[0];
        }
        return e;
    };

    var preventDefault = function(e) {
        if (e.stopPropagation) {
            e.stopPropagation();
        }
        if (e.preventDefault) {
            e.preventDefault();
        }
    };

    var getMovement = function(element) {
        return parseInt(element.css('left'));
    };

    var getPoint = function(len, width, num) {
        return (num / len) * width;
    };

    var getValue = function(len, width, mov, decimals) {
        return ((mov / width) * len).toFixed(decimals);
    };

    var setHintPosition = function($hint, $handle0, $handle1) {
        var handle0 = getMovement($handle0);
        if (!$handle1) {
            $hint.css('left', (handle0 - 3 - $hint.prop('clientWidth') / 2) + 'px');
            return;
        }
        var handle1 = getMovement($handle1);
        var max = Math.max(handle0, handle1);
        var min = Math.min(handle0, handle1);
        $hint.css('left', ((max - min) / 2 + min - 3 - $hint.prop('clientWidth') / 2) + 'px');
    };

    var setValue = function(len, width, decimals, value, $handle0, $handle1) {
        if ($handle1) {
            setRange(len, width, decimals, value, $handle0, $handle1);
        } else {
            value.point = getValue(len, width, getMovement($handle0), decimals);
        }
    };

    var setOutput = function($scope, value, outFormatter) {
        $scope.output = outFormatter(value);
    };

    var setSelction = function($selection, $handle0, $handle1) {
        var handle0 = getMovement($handle0);
        var handle1 = getMovement($handle1);
        var max = Math.max(handle0, handle1);
        var min = Math.min(handle0, handle1);
        var wid = max - min;
        $selection.css('left', min + 'px').css('width', wid + 'px');
    };

    var setRange = function(len, width, decimals, value, $handle0, $handle1) {
        var handle0 = getMovement($handle0);
        var handle1 = getMovement($handle1);
        var max = Math.max(handle0, handle1);
        var min = Math.min(handle0, handle1);
        value.start = getValue(len, width, min, decimals);
        value.end = getValue(len, width, max, decimals);
    };

    var dir = function() {
        return {
            restrict: 'E',
            scope: {
                option: '=',
                value: '='
            },
            link: function($scope, element) {

                var $doc = angular.element(document);
                var $win = angular.element(window);

                var _options = _defaults($scope.option, defaults);

                validate(_options);

                if (!_options.handles) {
                    _options.handles = [];
                    _options.handles[0] = _options.start;
                }

                var $slider, $track, $hint, $selection;
                var len, width;
                var minPoint, maxPoint;
                var $handle0, $handle1;
                var initPoint0, initPoint1;

                var offset = 0;
                var activeHandle;
                var handlePos = {};

                var refresh = function() {
                    $slider = angular.element(element.children()[0]);
                    $track = angular.element($slider.children()[0]);
                    $hint = angular.element($slider.children()[1]);
                    $selection = angular.element($track.children()[0]);

                    len = _options.end - _options.start;
                    width = $slider.prop('clientWidth');

                    minPoint = getPoint(len, width, _options.start);
                    maxPoint = getPoint(len, width, _options.end);

                    if (!$handle0) {
                        $handle0 = angular.element(handle);
                        $track.append($handle0);
                        $handle0.attr('id', 'handle0');
                    }
                    initPoint0 = getPoint(len, width, _options.handles[0]);
                    if (typeof $scope.value.start !== 'undefined') {
                        $handle0.css('left', getPoint(len, width, $scope.value.start) + 'px');
                        handlePos.handle0 = getPoint(len, width, $scope.value.start);
                    } else if (typeof $scope.value.point !== 'undefined') {
                        $handle0.css('left', getPoint(len, width, $scope.value.point) + 'px');
                        handlePos.handle0 = getPoint(len, width, $scope.value.point);
                    } else {
                        $handle0.css('left', initPoint0 + 'px');
                        handlePos.handle0 = initPoint0;
                    }
                    setHintPosition($hint, $handle0);

                    if (_options.handles[1]) {
                        if (!$handle1) {
                            $handle1 = angular.element(handle);
                            $track.append($handle1);
                            $handle1.attr('id', 'handle1');
                        }
                        initPoint1 = getPoint(len, width, _options.handles[1]);
                        if (typeof $scope.value.end !== 'undefined') {
                            $handle1.css('left', getPoint(len, width, $scope.value.end) + 'px');
                            handlePos.handle1 = getPoint(len, width, $scope.value.end);
                        } else {
                            $handle1.css('left', initPoint1 + 'px');
                            handlePos.handle1 = initPoint1;
                        }
                        setHintPosition($hint, $handle0, $handle1);
                        setSelction($selection, $handle0, $handle1);
                    }
                    setValue(len, width, _options.decimals, $scope.value, $handle0, $handle1);
                    setOutput($scope, $scope.value, _options.outFormatter);
                };

                refresh();

                var move = function(event) {
                    var e = getEvent(event);
                    var movement = handlePos[activeHandle.attr('id')] + e.clientX - offset;
                    if (movement >= minPoint && movement <= maxPoint) {
                        activeHandle.css('left', movement + 'px');
                        if ($handle1) {
                            setSelction($selection, $handle0, $handle1);
                        }
                        setHintPosition($hint, $handle0, $handle1);
                        $scope.$apply(function() {
                            setValue(len, width, _options.decimals, $scope.value, $handle0, $handle1);
                            setOutput($scope, $scope.value, _options.outFormatter);
                        });
                    }
                    preventDefault(e);
                };

                var end = function(event) {
                    var e = getEvent(event);
                    offset = 0;
                    handlePos[activeHandle.attr('id')] = getMovement(activeHandle);
                    activeHandle = undefined;
                    $doc.off('mousemove touchmove', move);
                    $doc.off('mouseup touchend', end);
                    preventDefault(e);
                };

                var getStart = function(handle) {
                    return function(event) {
                        var e = getEvent(event);
                        activeHandle = handle;
                        offset = e.clientX;
                        $doc.on('mousemove touchmove', move);
                        $doc.on('mouseup touchend', end);
                        preventDefault(e);
                    };
                };

                var start0 = getStart($handle0);
                var start1 = getStart($handle1);

                $handle0.on('mousedown touchstart', start0);
                if ($handle1) {
                    $handle1.on('mousedown touchstart', start1);
                }

                $win.on('resize', refresh);

                $scope.$on('$destroy', function() {
                    $handle0.off('mousedown touchstart', start0);
                    if ($handle1) {
                        $handle1.off('mousedown touchstart', start1);
                    }
                    $doc.off('mousemove touchmove', move);
                    $doc.off('mouseup touchend', end);
                });
            },
            template: '

{{ output }}

'
        };
    };

    mod.directive('sliderEasy', [dir]);

}(angular, document, window));<commit_msg>fix issue #1<commit_after>/**
 * slider-easy is such a directive which generate a slider bar, and
 * helps developer select the desired value
 *
 * @param option[expression]
 *              start[number]: a number of start point
 *              end[number]: a number of end point
 *              handles[array]: init points. if you want a range returned, this
 *                              has to be set
 *              decimals[int]: the number you want to keep as decimal
 *              outFormatter[function]: the function used to format the text at
 *                                      hint area
 * @author Howard.Zuo
 * @date   Sep 19th, 2014
 *
 **/
(function(angular, document, window) {
    'use strict';

    var mod = angular.module('angular-slider-easy', []);

    var handle = '

';

    var defaults = {
        start: 0,
        end: 100,
        decimals: 0,
        outFormatter: function(value) {
            if (value.point) {
                return 'Point is: ' + value.point;
            } else {
                return 'Range is: ' + (value.end - value.start);
            }
        }
    };

    var _defaults = function(dest, src) {
        var dst = dest || {};
        if (!src || typeof src !== 'object') {
            return dst;
        }
        for (var i in src) {
            if (!dst[i] && typeof src[i] !== undefined & src[i] !== null) {
                dst[i] = src[i];
            }
        }
        return dst;
    };

    var isNumber = function(n) {
        return !isNaN(parseFloat(n)) && isFinite(n);
    };

    var isPositiveInt = function(n) {
        return n === parseInt(n) && n === Math.abs(n);
    };

    var validate = function(options) {
        if (!isNumber(options.start)) {
            throw new Error('start must be number');
        }
        if (!isNumber(options.end)) {
            throw new Error('end must be number');
        }
        if (!isPositiveInt(options.decimals)) {
            throw new Error('decimals must be +int');
        }
        if (options.handles && !isNumber(options.handles[0])) {
            throw new Error('init 0 must be number');
        }
        if (options.handles && options.handles[1] && !isNumber(options.handles[1])) {
            throw new Error('init 1 must be number');
        }
    };

    var getEvent = function(e) {
        if (e.touches && e.touches.length > 0) {
            return e.touches[0];
        }
        if (window.jQuery && window.jQuery.Event && e instanceof window.jQuery.Event && e.originalEvent.touches && e.originalEvent.touches.length > 0) {
            return e.originalEvent.touches[0];
        }
        return e;
    };

    var preventDefault = function(e) {
        if (e.stopPropagation) {
            e.stopPropagation();
        }
        if (e.preventDefault) {
            e.preventDefault();
        }
    };

    var getMovement = function(element) {
        return parseInt(element.css('left'));
    };

    var getPoint = function(len, width, num) {
        return (num / len) * width;
    };

    var getValue = function(len, width, mov, decimals) {
        return ((mov / width) * len).toFixed(decimals);
    };

    var setHintPosition = function($hint, $handle0, $handle1) {
        var handle0 = getMovement($handle0);
        if (!$handle1) {
            $hint.css('left', (handle0 - 3 - $hint.prop('clientWidth') / 2) + 'px');
            return;
        }
        var handle1 = getMovement($handle1);
        var max = Math.max(handle0, handle1);
        var min = Math.min(handle0, handle1);
        $hint.css('left', ((max - min) / 2 + min - 3 - $hint.prop('clientWidth') / 2) + 'px');
    };

    var setValue = function(len, width, decimals, value, $handle0, $handle1) {
        if ($handle1) {
            setRange(len, width, decimals, value, $handle0, $handle1);
        } else {
            value.point = getValue(len, width, getMovement($handle0), decimals);
        }
    };

    var setOutput = function($scope, value, outFormatter) {
        $scope.output = outFormatter(value);
    };

    var setSelction = function($selection, $handle0, $handle1) {
        var handle0 = getMovement($handle0);
        var handle1 = getMovement($handle1);
        var max = Math.max(handle0, handle1);
        var min = Math.min(handle0, handle1);
        var wid = max - min;
        $selection.css('left', min + 'px').css('width', wid + 'px');
    };

    var setRange = function(len, width, decimals, value, $handle0, $handle1) {
        var handle0 = getMovement($handle0);
        var handle1 = getMovement($handle1);
        var max = Math.max(handle0, handle1);
        var min = Math.min(handle0, handle1);
        value.start = getValue(len, width, min, decimals);
        value.end = getValue(len, width, max, decimals);
    };

    var dir = function() {
        return {
            restrict: 'E',
            scope: {
                option: '=',
                value: '='
            },
            link: function($scope, element) {

                var $doc = angular.element(document);
                var $win = angular.element(window);

                var _options = _defaults($scope.option, defaults);

                validate(_options);

                if (!_options.handles) {
                    _options.handles = [];
                    _options.handles[0] = _options.start;
                }

                var $slider, $track, $hint, $selection;
                var len, width;
                var minPoint, maxPoint;
                var $handle0, $handle1;
                var initPoint0, initPoint1;

                var offset = 0;
                var activeHandle;
                var handlePos = {};

                var refresh = function() {
                    $slider = angular.element(element.children()[0]);
                    $track = angular.element($slider.children()[0]);
                    $hint = angular.element($slider.children()[1]);
                    $selection = angular.element($track.children()[0]);

                    len = _options.end - _options.start;
                    width = $slider.prop('clientWidth');

                    minPoint = getPoint(len, width, _options.start);
                    maxPoint = getPoint(len, width, _options.end);

                    if (!$handle0) {
                        $handle0 = angular.element(handle);
                        $track.append($handle0);
                        $handle0.attr('id', 'handle0');
                    }
                    initPoint0 = getPoint(len, width, _options.handles[0]);
                    if (typeof $scope.value.start !== 'undefined') {
                        $handle0.css('left', getPoint(len, width, $scope.value.start) + 'px');
                        handlePos.handle0 = getPoint(len, width, $scope.value.start);
                    } else if (typeof $scope.value.point !== 'undefined') {
                        $handle0.css('left', getPoint(len, width, $scope.value.point) + 'px');
                        handlePos.handle0 = getPoint(len, width, $scope.value.point);
                    } else {
                        $handle0.css('left', initPoint0 + 'px');
                        handlePos.handle0 = initPoint0;
                    }
                    setHintPosition($hint, $handle0);

                    if (_options.handles[1]) {
                        if (!$handle1) {
                            $handle1 = angular.element(handle);
                            $track.append($handle1);
                            $handle1.attr('id', 'handle1');
                        }
                        initPoint1 = getPoint(len, width, _options.handles[1]);
                        if (typeof $scope.value.end !== 'undefined') {
                            $handle1.css('left', getPoint(len, width, $scope.value.end) + 'px');
                            handlePos.handle1 = getPoint(len, width, $scope.value.end);
                        } else {
                            $handle1.css('left', initPoint1 + 'px');
                            handlePos.handle1 = initPoint1;
                        }
                        setHintPosition($hint, $handle0, $handle1);
                        setSelction($selection, $handle0, $handle1);
                    }
                    setValue(len, width, _options.decimals, $scope.value, $handle0, $handle1);
                    setOutput($scope, $scope.value, _options.outFormatter);
                };

                refresh();

                var move = function(event) {
                    var e = getEvent(event);
                    var movement = handlePos[activeHandle.attr('id')] + e.clientX - offset;
                    if (movement >= minPoint && movement <= maxPoint) {
                        activeHandle.css('left', movement + 'px');
                        if ($handle1) {
                            setSelction($selection, $handle0, $handle1);
                        }
                        setHintPosition($hint, $handle0, $handle1);
                        $scope.$apply(function() {
                            setValue(len, width, _options.decimals, $scope.value, $handle0, $handle1);
                            setOutput($scope, $scope.value, _options.outFormatter);
                        });
                    }
                    preventDefault(e);
                };

                var end = function(event) {
                    var e = getEvent(event);
                    offset = 0;
                    handlePos[activeHandle.attr('id')] = getMovement(activeHandle);
                    activeHandle = undefined;
                    $doc.off('mousemove touchmove', move);
                    $doc.off('mouseup touchend', end);
                    preventDefault(e);
                };

                var getStart = function(handle) {
                    return function(event) {
                        var e = getEvent(event);
                        activeHandle = handle;
                        offset = e.clientX;
                        $doc.on('mousemove touchmove', move);
                        $doc.on('mouseup touchend', end);
                        preventDefault(e);
                    };
                };

                var start0 = getStart($handle0);
                var start1 = getStart($handle1);

                $handle0.on('mousedown touchstart', start0);
                if ($handle1) {
                    $handle1.on('mousedown touchstart', start1);
                }

                $win.on('resize', refresh);

                $scope.$on('$destroy', function() {
                    $handle0.off('mousedown touchstart', start0);
                    if ($handle1) {
                        $handle1.off('mousedown touchstart', start1);
                    }
                    $doc.off('mousemove touchmove', move);
                    $doc.off('mouseup touchend', end);
                });
            },
            template: '

{{ output }}

'
        };
    };

    mod.directive('sliderEasy', [dir]);

}(angular, document, window));
<|endoftext|>


<commit_before>/**
 * Created by max on 18.02.16.
 */
'use strict';

(function(){
    angular.module('dash').controller('dashboardController', dashController);
    dashController.$inject = ["$scope"];

    function dashController($scope){

        //$scope.currentTime = moment().format('Do MMM YYYY, h:mm:ss');

        setInterval(setCurrentTime, 1000);

        function setCurrentTime(){

            $scope.$apply(function(){
                $scope.currentTime = moment().format('Do MMM YYYY, h:mm:ss');
            });
        }

        function calcTimeToSunset(sunset){
             return  moment(sunset).calendar();
        }

        function calcTimeToSunrise(sunrise){
           return moment(sunrise).calendar();
        }

        var socket = io.connect('http://localhost:3000');

        socket.on('connect', function(data){
            console.log('connected to socket');
        });

        socket.on('traffic', function(trafficData){
            $scope.$apply(function(){
                $scope.trafficData = trafficData;
            });

        });

        socket.on('weather', function(weatherData){
            $scope.$apply(function(){
                var weather = JSON.parse(weatherData);
                $scope.weather = trimWeatherData(weather);
                $scope.sunset = calcTimeToSunset($scope.weather.sunset);
                $scope.sunrise = calcTimeToSunrise($scope.weather.sunrise);

                console.log($scope.weather);
            });
        });

        function trimWeatherData(res){

           return  { temp: 'Temp ' + res.main.temp + ' C',
                pressure: res.main.pressure,
                humidity: res.main.humidity,
                description : res.weather[0].description,
                icon : res.weather[0].icon,
                image: 'http://openweathermap.org/img/w/' + res.weather[0].icon +'.png',
                sunrise: res.sys.sunrise * 1000,
                sunset : res.sys.sunset * 1000,
                windspeed :  res.wind.speed + 'km/h'
            };
        }
    }
})();

//image hack
(function(){
    $(document).ready(function(){

        setImage();

        setInterval(setImage, 1000);

        setInterval(setHumidity, 1000);

    });

    function setImage(){
        var image_url = $('#weather_image_hidden').text();
        $('#weather_image').attr('src', image_url);
    }

    function setHumidity(){
        var humidity_value =   $('#humidity_bar').text();

        $('#humidity_bar').css("width", humidity_value + "%")
    }

})();<commit_msg>adjusted socket url<commit_after>/**
 * Created by max on 18.02.16.
 */
'use strict';

(function(){
    angular.module('dash').controller('dashboardController', dashController);
    dashController.$inject = ["$scope"];

    function dashController($scope){

        //$scope.currentTime = moment().format('Do MMM YYYY, h:mm:ss');

        setInterval(setCurrentTime, 1000);

        function setCurrentTime(){

            $scope.$apply(function(){
                $scope.currentTime = moment().format('Do MMM YYYY, h:mm:ss');
            });
        }

        function calcTimeToSunset(sunset){
             return  moment(sunset).calendar();
        }

        function calcTimeToSunrise(sunrise){
           return moment(sunrise).calendar();
        }

        var socket = io.connect('http://kimambo.de:3000');

        socket.on('connect', function(data){
            console.log('connected to socket');
        });

        socket.on('traffic', function(trafficData){
            $scope.$apply(function(){
                $scope.trafficData = trafficData;
            });

        });

        socket.on('weather', function(weatherData){
            $scope.$apply(function(){
                var weather = JSON.parse(weatherData);
                $scope.weather = trimWeatherData(weather);
                $scope.sunset = calcTimeToSunset($scope.weather.sunset);
                $scope.sunrise = calcTimeToSunrise($scope.weather.sunrise);

                console.log($scope.weather);
            });
        });

        function trimWeatherData(res){

           return  { temp: 'Temp ' + res.main.temp + ' C',
                pressure: res.main.pressure,
                humidity: res.main.humidity,
                description : res.weather[0].description,
                icon : res.weather[0].icon,
                image: 'http://openweathermap.org/img/w/' + res.weather[0].icon +'.png',
                sunrise: res.sys.sunrise * 1000,
                sunset : res.sys.sunset * 1000,
                windspeed :  res.wind.speed + 'km/h'
            };
        }
    }
})();

//image hack
(function(){
    $(document).ready(function(){

        setImage();

        setInterval(setImage, 1000);

        setInterval(setHumidity, 1000);

    });

    function setImage(){
        var image_url = $('#weather_image_hidden').text();
        $('#weather_image').attr('src', image_url);
    }

    function setHumidity(){
        var humidity_value =   $('#humidity_bar').text();

        $('#humidity_bar').css("width", humidity_value + "%")
    }

})();<|endoftext|>


<commit_before>if (typeof (require) != 'undefined') {
	var loader = require('../../../../node_modules/Butterfly-js/dist/butterfly.min.js').loader;
}

/**
 * Entry point of the game, contains some part of the game engine and deals with
 * the different entities
 */
loader.executeModule('main',
'B', 'Engine', 'Canvas', 'Entities', 'GameEntities', 'Physics', 'Utils', 'data', 'Controls', 'Level', 'GUI',
function (B, Engine, canvas, Entities, GameEntities, Physics, Utils, data, Controls, Level, GUI) {
	var ball,
		paddle,
		bricks = [],
		remainingBricks,
		// position of the mouse in the canvas, taking in account the scroll
		// and position of the canvas in the page
		mouseX,
		mouseY,
		urlParams = Utils.getUrlParams(window.location.search);

	const DEBUG = urlParams.debug || NO_DEBUG;

	const PADDLE_WIDTH = 100;
	const PADDLE_THICKNESS = 10;
	const BALL_RADIUS = 10;
	const BALL_SPEED_X = 5;
	const BALL_SPEED_Y = 7;

	Engine.addCallback('resetLevel', function () {
		// Set the number of remaining bricks to destroy
		remainingBricks = Engine.getLevel().counts[data.states.ACTIVE];
	});

	Engine.init(
		document.getElementById('game-canvas'),
		Engine.OPTION_USE_MOUSE,
		function () {
			// Init the ball
			var startCell = Engine.getLevel().getCoordinatesCenterCell(data.maps[0].start[0], data.maps[0].start[1]);
			ball = new GameEntities.Ball(startCell[0], startCell[1], BALL_RADIUS, BALL_SPEED_X, BALL_SPEED_Y);
			// Init the paddle at the middle of the game view, 100px above the bottom
			paddle = new GameEntities.Paddle(
				(canvas.width() - PADDLE_WIDTH) / 2, canvas.height() - 100,
				PADDLE_WIDTH,
				PADDLE_THICKNESS
			);
			Engine.addDrawable(ball);
			Engine.addDrawable(paddle);
		}
	);

	Engine.addCallback('win', function () {
		ball.reset();
	});

	Engine.addCallback('lose', function () {
		ball.reset();
	});

	Engine.addCallback('mouseMoved', function (mouseX, mouseY) {
		// @TODO move that in the paddle logic
		if (mouseX > PADDLE_WIDTH / 2 && mouseX < canvas.width() - PADDLE_WIDTH / 2) {
			paddle.updatePosition(
				Math.min(
					Math.max(
						0,
						mouseX - PADDLE_WIDTH / 2
					),
					canvas.width() - PADDLE_WIDTH / 2
				)
			);
		}

		if (DEBUG) {
			ball.x = mouseX;
			ball.y = mouseY;
			ball.speedX = BALL_SPEED_X;
			ball.speedY = BALL_SPEED_Y * -1;
		}
	});

	Engine.addCallback('gameFinishedScreen', function () {
		canvas.drawText('You won the game!', canvas.width() / 2 - 50, 200, 'white');
		canvas.drawText('Click to restart', canvas.width() / 2 - 45, 400, 'white');
	});

	Engine.addCallback('levelFinishedScreen', function () {
		canvas.drawText('Level finished', canvas.width() / 2 - 40, 200, 'white');
		canvas.drawText('Click to continue', canvas.width() / 2 - 45, 400, 'white');
	});

	/**
	 * Method to update the game state and the objects's position
	 */
	Engine.addCallback('moveAll', function () {
		// Update the ball position
		ball.updatePosition();

		/* Ball and edges collision*/
		var wallBounded = Physics.sphereBounceAgainstInnerRectangle(ball, {x: 0, y: 0, w: canvas.width(), h: canvas.height()});
		if (wallBounded == 'down') {
			ball.reset();
			console.log('fire lost');
			B.Events.fire('lost');
		}
		/* End of Ball and edges collision*/

		/* Ball and active brick collision */
		var brick,
			brickSide,
			brickTopBot,
			ballGridCellCol = Math.floor(ball.x / Engine.getLevel().gridCellWidth),
			ballGridCellRow = Math.floor(ball.y / Engine.getLevel().gridCellHeight)
			ballOldGridCellCol = Math.floor((ball.x - ball.speedX) / Engine.getLevel().gridCellWidth),
			ballOldGridCellRow = Math.floor((ball.y - ball.speedY) / Engine.getLevel().gridCellHeight);

		brick = Engine.getLevel().getCell(
			ballGridCellCol,
			ballGridCellRow
		);

		// if the ball is on an active brick
		if (0 <= ballGridCellCol && ballGridCellCol < Engine.getLevel().width
			&& 0 <= ballGridCellRow && ballGridCellRow < Engine.getLevel().height
			&& brick.state == data.states.ACTIVE
		) {
			// brick next to the current one, according to ball's old position
			brickSide = Engine.getLevel().getCell(ballOldGridCellCol, ballGridCellRow);
			brickSide = brickSide && brickSide.state == data.states.ACTIVE && brickSide || undefined;

			// brick under or above to the current one, according to ball's old position
			brickTopBot = Engine.getLevel().getCell(ballGridCellCol, ballOldGridCellRow);
			brickTopBot = brickTopBot && brickTopBot.state == data.states.ACTIVE && brickTopBot || undefined;

			Physics.sphereBounceAgainstGridRectangle(ball, brick, brickSide, brickTopBot);

			brick.changeStateAndTexture(data.states.INACTIVE, data.resources[brick.state].resource);
			remainingBricks--;

			if (remainingBricks == 0) {
				console.log('win');
				B.Events.fire('win');
				return;
			}
		}
		/* End of Ball and active brick collision */

		/* Ball and paddle collision */
		// if the ball is colliding with the paddle
		if (Physics.sphereCollidesWithRectangle(ball, paddle)) {
			ball.speedY *= -1;

			var centerPaddleX = paddle.x + paddle.w / 2,
				distFromPaddleCenter = ball.x - centerPaddleX;

			ball.speedX = distFromPaddleCenter * 0.35;
		}
		/* Ball and paddle collision */
	});
});
<commit_msg>BRICK-BREAKER - missing comma added<commit_after>if (typeof (require) != 'undefined') {
	var loader = require('../../../../node_modules/Butterfly-js/dist/butterfly.min.js').loader;
}

/**
 * Entry point of the game, contains some part of the game engine and deals with
 * the different entities
 */
loader.executeModule('main',
'B', 'Engine', 'Canvas', 'Entities', 'GameEntities', 'Physics', 'Utils', 'data', 'Controls', 'Level', 'GUI',
function (B, Engine, canvas, Entities, GameEntities, Physics, Utils, data, Controls, Level, GUI) {
	var ball,
		paddle,
		bricks = [],
		remainingBricks,
		// position of the mouse in the canvas, taking in account the scroll
		// and position of the canvas in the page
		mouseX,
		mouseY,
		urlParams = Utils.getUrlParams(window.location.search);

	const DEBUG = urlParams.debug || NO_DEBUG;

	const PADDLE_WIDTH = 100;
	const PADDLE_THICKNESS = 10;
	const BALL_RADIUS = 10;
	const BALL_SPEED_X = 5;
	const BALL_SPEED_Y = 7;

	Engine.addCallback('resetLevel', function () {
		// Set the number of remaining bricks to destroy
		remainingBricks = Engine.getLevel().counts[data.states.ACTIVE];
	});

	Engine.init(
		document.getElementById('game-canvas'),
		Engine.OPTION_USE_MOUSE,
		function () {
			// Init the ball
			var startCell = Engine.getLevel().getCoordinatesCenterCell(data.maps[0].start[0], data.maps[0].start[1]);
			ball = new GameEntities.Ball(startCell[0], startCell[1], BALL_RADIUS, BALL_SPEED_X, BALL_SPEED_Y);
			// Init the paddle at the middle of the game view, 100px above the bottom
			paddle = new GameEntities.Paddle(
				(canvas.width() - PADDLE_WIDTH) / 2, canvas.height() - 100,
				PADDLE_WIDTH,
				PADDLE_THICKNESS
			);
			Engine.addDrawable(ball);
			Engine.addDrawable(paddle);
		}
	);

	Engine.addCallback('win', function () {
		ball.reset();
	});

	Engine.addCallback('lose', function () {
		ball.reset();
	});

	Engine.addCallback('mouseMoved', function (mouseX, mouseY) {
		// @TODO move that in the paddle logic
		if (mouseX > PADDLE_WIDTH / 2 && mouseX < canvas.width() - PADDLE_WIDTH / 2) {
			paddle.updatePosition(
				Math.min(
					Math.max(
						0,
						mouseX - PADDLE_WIDTH / 2
					),
					canvas.width() - PADDLE_WIDTH / 2
				)
			);
		}

		if (DEBUG) {
			ball.x = mouseX;
			ball.y = mouseY;
			ball.speedX = BALL_SPEED_X;
			ball.speedY = BALL_SPEED_Y * -1;
		}
	});

	Engine.addCallback('gameFinishedScreen', function () {
		canvas.drawText('You won the game!', canvas.width() / 2 - 50, 200, 'white');
		canvas.drawText('Click to restart', canvas.width() / 2 - 45, 400, 'white');
	});

	Engine.addCallback('levelFinishedScreen', function () {
		canvas.drawText('Level finished', canvas.width() / 2 - 40, 200, 'white');
		canvas.drawText('Click to continue', canvas.width() / 2 - 45, 400, 'white');
	});

	/**
	 * Method to update the game state and the objects's position
	 */
	Engine.addCallback('moveAll', function () {
		// Update the ball position
		ball.updatePosition();

		/* Ball and edges collision*/
		var wallBounded = Physics.sphereBounceAgainstInnerRectangle(ball, {x: 0, y: 0, w: canvas.width(), h: canvas.height()});
		if (wallBounded == 'down') {
			ball.reset();
			console.log('fire lost');
			B.Events.fire('lost');
		}
		/* End of Ball and edges collision*/

		/* Ball and active brick collision */
		var brick,
			brickSide,
			brickTopBot,
			ballGridCellCol = Math.floor(ball.x / Engine.getLevel().gridCellWidth),
			ballGridCellRow = Math.floor(ball.y / Engine.getLevel().gridCellHeight),
			ballOldGridCellCol = Math.floor((ball.x - ball.speedX) / Engine.getLevel().gridCellWidth),
			ballOldGridCellRow = Math.floor((ball.y - ball.speedY) / Engine.getLevel().gridCellHeight);

		brick = Engine.getLevel().getCell(
			ballGridCellCol,
			ballGridCellRow
		);

		// if the ball is on an active brick
		if (0 <= ballGridCellCol && ballGridCellCol < Engine.getLevel().width
			&& 0 <= ballGridCellRow && ballGridCellRow < Engine.getLevel().height
			&& brick.state == data.states.ACTIVE
		) {
			// brick next to the current one, according to ball's old position
			brickSide = Engine.getLevel().getCell(ballOldGridCellCol, ballGridCellRow);
			brickSide = brickSide && brickSide.state == data.states.ACTIVE && brickSide || undefined;

			// brick under or above to the current one, according to ball's old position
			brickTopBot = Engine.getLevel().getCell(ballGridCellCol, ballOldGridCellRow);
			brickTopBot = brickTopBot && brickTopBot.state == data.states.ACTIVE && brickTopBot || undefined;

			Physics.sphereBounceAgainstGridRectangle(ball, brick, brickSide, brickTopBot);

			brick.changeStateAndTexture(data.states.INACTIVE, data.resources[brick.state].resource);
			remainingBricks--;

			if (remainingBricks == 0) {
				console.log('win');
				B.Events.fire('win');
				return;
			}
		}
		/* End of Ball and active brick collision */

		/* Ball and paddle collision */
		// if the ball is colliding with the paddle
		if (Physics.sphereCollidesWithRectangle(ball, paddle)) {
			ball.speedY *= -1;

			var centerPaddleX = paddle.x + paddle.w / 2,
				distFromPaddleCenter = ball.x - centerPaddleX;

			ball.speedX = distFromPaddleCenter * 0.35;
		}
		/* Ball and paddle collision */
	});
});
<|endoftext|>


<commit_before>const fileName = 'storage-files/poof.json';
var fs = require('fs');
var poofoff = false;
var poofs = JSON.parse(fs.readFileSync(fileName));

function randomColor () {
	var colors = ['9900f2', '4ca2ff', '4cff55', 'e87f00', 'd30007', '8e8080', 'd8b00d', '01776a', '0c4787', '0c870e', '8e892c',
		'5b5931', '660c60', '9e5a99', 'c43873', '39bf39', '7c5cd6', '76d65c', '38c9c9', '2300af', '1daf00'
	];
	return colors[Math.floor(Math.random() * colors.length)];
}

exports.commands = {
	lolol: function (target, room, user) {
		poofs.map(function (msg) { if (!msg.match(/\(user\)/)) return '(user) ' + msg;});

		fs.writeFileSync('storage-files/poof.json', JSON.stringify(poofs, null, 1));
	},
	poofhelp: function (target, room, user) {
		if (!this.canBroadcast()) return;
		this.sendReplyBox('-/poof - Leaves a random message in the chat and disconnects the user from the server.
' +
			'-/cpoof Message - Leaves a custom message in the chat and disconnects the user from the server. Requires %, @, # or ~
' +
			'-/addpoof Message - Adds a poof message into the list of possible poofs. Adding "(user)" into a poof message replaces "(user)" with that user\'s name. Requires ~
' +
			'-/togglepoof - Enables/Disables poofs.' +
			'-/pooflist - Displays the list of all poof messages.'
		);
	},

	d: 'poof',
	poof: function (target, room, user) {
		if (!this.canTalk()) return;
		if (poofoff) return this.sendReply("Poofs are currently disabled.");
		var message = poofs[Math.floor(Math.random() * poofs.length)].replace(/\(user\)/g, Tools.escapeHTML(user.name));
		this.add('|html|~~ ' + message + ' ~~');
		user.disconnectAll();
	},

	custompoof: 'cpoof',
	cpoof: function (target, room, user) {
		if (!this.canTalk()) return;
		if (poofoff) return this.sendReply("Poofs are currently disabled.");
		if (!target || !target.trim()) return this.parse('/poof');
		if (!target.match(/\(user\)/)) target = Tools.escapeHTML(user.name) + ' ' + target;
		else target = target.replace(/\(user\)/, Tools.escapeHTML(user.name));
		this.add('|html|~~ ' + target.trim() + ' ~~');
		this.disconnectAll();
	},

	addpoof: function (target, room, user) {
		if (!this.can('hotpatch')) return false;
		if (!target) return this.parse('/addpoofhelp');
		if (poofs.map(toId).indexOf(toId(target)) > -1) return this.sendReply('That poof message already exists!');
		if (target.length > 100) return this.sendReply('Poof messages can only contain a maximum of 100 characters.');
		if (!target.match(/\(user\)/)) target = '(user) ' + target;
		poofs.push(target.trim());
		fs.writeFileSync(fileName, JSON.stringify(poofs, null, 1));
		return this.sendReply('|html|"' + target + '" has been added to the list of poof messages.');
	},

	switchpoof: 'togglepoof',
	tpoof: 'togglepoof',
	togglepoof: function (target, room, user) {
		if (!this.can('hotpatch')) return false;
		poofoff = !poofoff;
		this.sendReply('Poofs have been ' + (poofoff ? 'disabled' : 'enabled') + '.');
	},

	pooflist: function (target, room, user) {
		var list = '|html|Poof message list
';
		poofs.forEach(function (msg) {
			list += '"' + msg + '"';
			if (user.can('hotpatch')) list += '<button name = "send" value = "/deletepoof ' + msg + '" style = "font-size: 7pt;">Delete</button>';
			list += '
';
		});
		this.popupReply(list);
	},

	deletepoof: function (target, room, user) {
		if (!target || !target.trim()) return this.sendReply('|html|/deletepoof Message - Deletes the selected message from the list of poofs.');
		if (!target.match(/\(user\)/)) target = '(user) ' + target;
		var pos = poofs.map(toId).indexOf(toId(target));
		if (pos === -1) return this.sendReply('That poof message doesn\'t exist.');
		this.popupReply('|html|The poof message "' + poofs[pos] + '" has been deleted.');
		poofs.splice(pos, 1);
		fs.writeFileSync(fileName, JSON.stringify(poofs, null, 1));
	}
};
<commit_msg>Update poof.js<commit_after>const fileName = 'storage-files/poof.json';
var fs = require('fs');
var poofoff = false;
var poofs = JSON.parse(fs.readFileSync(fileName));

function randomColor () {
	var colors = ['9900f2', '4ca2ff', '4cff55', 'e87f00', 'd30007', '8e8080', 'd8b00d', '01776a', '0c4787', '0c870e', '8e892c',
		'5b5931', '660c60', '9e5a99', 'c43873', '39bf39', '7c5cd6', '76d65c', '38c9c9', '2300af', '1daf00'
	];
	return colors[Math.floor(Math.random() * colors.length)];
}

exports.commands = {
	poofhelp: function (target, room, user) {
		if (!this.canBroadcast()) return;
		this.sendReplyBox('-/poof - Leaves a random message in the chat and disconnects the user from the server.
' +
			'-/cpoof Message - Leaves a custom message in the chat and disconnects the user from the server. Requires %, @, # or ~
' +
			'-/addpoof Message - Adds a poof message into the list of possible poofs. Adding "(user)" into a poof message replaces "(user)" with that user\'s name. Requires ~
' +
			'-/togglepoof - Enables/Disables poofs.' +
			'-/pooflist - Displays the list of all poof messages.'
		);
	},

	d: 'poof',
	poof: function (target, room, user) {
		if (!this.canTalk()) return;
		if (poofoff) return this.sendReply("Poofs are currently disabled.");
		var message = poofs[Math.floor(Math.random() * poofs.length)];
		if (message.match(/\(user\)/)) message = message.replace(/\(user\)/g, Tools.escapeHTML(user.name));
		else message = Tools.escapeHTML(user.name) + ' ' + message;
		this.add('|html|~~ ' + message + ' ~~');
		user.disconnectAll();
	},

	custompoof: 'cpoof',
	cpoof: function (target, room, user) {
		if (!this.canTalk()) return;
		if (poofoff) return this.sendReply("Poofs are currently disabled.");
		if (!target || !target.trim()) return this.parse('/poof');
		if (!target.match(/\(user\)/)) target = Tools.escapeHTML(user.name) + ' ' + target;
		else target = target.replace(/\(user\)/, Tools.escapeHTML(user.name));
		this.add('|html|~~ ' + target.trim() + ' ~~');
		this.disconnectAll();
	},

	addpoof: function (target, room, user) {
		if (!this.can('hotpatch')) return false;
		if (!target) return this.parse('/addpoofhelp');
		if (poofs.map(toId).indexOf(toId(target)) > -1) return this.sendReply('That poof message already exists!');
		if (target.length > 100) return this.sendReply('Poof messages can only contain a maximum of 100 characters.');
		if (!target.match(/\(user\)/)) target = '(user) ' + target;
		poofs.push(target.trim());
		fs.writeFileSync(fileName, JSON.stringify(poofs, null, 1));
		return this.sendReply('|html|"' + target + '" has been added to the list of poof messages.');
	},

	switchpoof: 'togglepoof',
	tpoof: 'togglepoof',
	togglepoof: function (target, room, user) {
		if (!this.can('hotpatch')) return false;
		poofoff = !poofoff;
		this.sendReply('Poofs have been ' + (poofoff ? 'disabled' : 'enabled') + '.');
	},

	pooflist: function (target, room, user) {
		var list = '|html|Poof message list
';
		poofs.forEach(function (msg) {
			list += '"' + msg + '"';
			if (user.can('hotpatch')) list += '<button name = "send" value = "/deletepoof ' + msg + '" style = "font-size: 7pt;">Delete</button>';
			list += '
';
		});
		this.popupReply(list);
	},

	deletepoof: function (target, room, user) {
		if (!target || !target.trim()) return this.sendReply('|html|/deletepoof Message - Deletes the selected message from the list of poofs.');
		if (!target.match(/\(user\)/)) target = '(user) ' + target;
		var pos = poofs.map(toId).indexOf(toId(target));
		if (pos === -1) return this.sendReply('That poof message doesn\'t exist.');
		this.popupReply('|html|The poof message "' + poofs[pos] + '" has been deleted.');
		poofs.splice(pos, 1);
		fs.writeFileSync(fileName, JSON.stringify(poofs, null, 1));
	}
};
<|endoftext|>


<commit_before>var config = require('./lib/readConfig.js').readCmdOptions();

// Now using the official Amazon Web Services SDK for Javascript
var AWS = require("aws-sdk");

// We'll use the Cloudwatch API
var cloudwatch = new AWS.CloudWatch(config.awsCredentials);

// get the graphite prefix from the metrics config or use cloudwatch as default
var graphitePrefix = config.metricsConfig.carbonNameSpacePrefix || 'cloudwatch';

// use legacy format, defaulting to false
var useLegacyFormat = config.metricsConfig.legacyFormat;

// pulling all of lodash for _.sortBy(), does it matter? Do we even need to sort?
var _ = require('lodash');

// TODO: do we need both those libraries, do we need any?
var dateFormat = require('dateformat');
require('./lib/date');

// number of minutes of recent data to query
var interval = 3;

// Between now and 11 minutes ago
var now = new Date();
var then = (interval).minutes().ago();
var end_time = dateFormat(now, "isoUtcDateTime");
var start_time = dateFormat(then, "isoUtcDateTime");

// We used to use this when looking at Billing metrics
// if ( metric.Namespace.match(/Billing/) ) {
//     then.setHours(then.getHours() - 30)
// }
// if ( metric.Namespace.match(/Billing/) ) {
//     options["Period"] = '28800'
// }

var metrics = config.metricsConfig.metrics;

getAllELBNames(getELBMetrics);
getAllRDSInstanceNames(getRDSMetrics);
getAllElasticCacheNames(getElasticCacheMetrics);

for (var index in metrics) {
    printMetric(metrics[index], start_time, end_time);
}

function printMetric(metric, get_start_time, get_end_time) {

    var getMetricStatistics_param = metric;

    getMetricStatistics_param.StartTime = get_start_time;
    getMetricStatistics_param.EndTime = get_end_time;

    cloudwatch.getMetricStatistics(getMetricStatistics_param, function (err, data) {
        if (err) {
            console.error(err, err.stack); // an error occurred
            console.error("on:\n" + JSON.stringify(getMetricStatistics_param, null, 2));
        }
        else {
            formatter = useLegacyFormat ? legacyFormat : newFormat;
            console.log( formatter(metric, data).join("\n"));
        }
    });
}

// Takes the orig query and the response and formats the response as an array of strings
function newFormat(query, data) {
    var dimension_prefix = _.map(query.Dimensions, function(dim) {
        return dim.Name + '_' + dim.Value;
    }).join('.');

    return _.map(data.Datapoints, function(point) {
        var name = query.Namespace.replace("/", ".");
        name += '.' + dimension_prefix;
        name += '.' + query.MetricName;
        var value = point[query['Statistics']];
        var time = parseInt(new Date(point.Timestamp).getTime() / 1000.0);
        return name + ' ' + value + ' ' + time;
    });
}

// Takes the orig query and the response and formats the response as an array of strings
// according to old style of cloudwatch2graphite.
function legacyFormat(query, data) {

    // the legacy format is to only use the dimension Values in the prefix
    var dimension_prefix = _.map(query.Dimensions, function(dim) {
        return dim.Value;
    }).join('.');

    return _.map(data.Datapoints, function(point) {
        var name = query.Namespace.replace("/", ".");
        name += '.' + dimension_prefix;
        name += '.' + query.MetricName;
        name += '.' + query['Statistics'];
        name += '.' + query['Unit'];
        var value = point[query['Statistics']];
        var time = parseInt(new Date(point.Timestamp).getTime() / 1000.0);
        return graphitePrefix + '.' + name.toLowerCase() + ' ' + value + ' ' + time;
    });
}

// returns a hash with all details needed for an cloudwatch metrics query
function buildMetricQuery(namespace, name, unit, statistics, dimensions, period) {
    return {
        'Namespace': namespace,
        'MetricName': name,
        'Unit' : unit,
        'Statistics': [statistics],
        'Dimensions' : dimensions,
        'Period' : period || 60,
    }
}

// executes callback with array of names of all ELBs
function getAllELBNames(callback) {
    var elb = new AWS.ELB(config.awsCredentials);
    elb.describeLoadBalancers({}, function(err, data) {
        if (err) {
            console.log(err);
            callback([]);
        }
        callback(_.pluck(data.LoadBalancerDescriptions, 'LoadBalancerName'));
    });
}

// takes array of ELB names and gets a variety metrics
function getELBMetrics(elbs) {
    for (index in elbs) {
        var elb = elbs[index];
        var dimensions = [ { "Name" : 'LoadBalancerName', "Value" : elb} ];
        printMetric(buildMetricQuery('AWS/ELB', 'Latency', 'Seconds', 'Average', dimensions), start_time, end_time);
        printMetric(buildMetricQuery('AWS/ELB', 'HealthyHostCount', 'Count', 'Average', dimensions), start_time, end_time);
        printMetric(buildMetricQuery('AWS/ELB', 'UnHealthyHostCount', 'Count', 'Average', dimensions), start_time, end_time);
        printMetric(buildMetricQuery('AWS/ELB', 'HTTPCode_Backend_2XX', 'Count', 'Sum', dimensions), start_time, end_time);
        printMetric(buildMetricQuery('AWS/ELB', 'HTTPCode_Backend_3XX', 'Count', 'Sum', dimensions), start_time, end_time);
        printMetric(buildMetricQuery('AWS/ELB', 'HTTPCode_Backend_4XX', 'Count', 'Sum', dimensions), start_time, end_time);
        printMetric(buildMetricQuery('AWS/ELB', 'HTTPCode_Backend_5XX', 'Count', 'Sum', dimensions), start_time, end_time);
        printMetric(buildMetricQuery('AWS/ELB', 'HTTPCode_ELB_4XX', 'Count', 'Sum', dimensions), start_time, end_time);
        printMetric(buildMetricQuery('AWS/ELB', 'HTTPCode_ELB_5XX', 'Count', 'Sum', dimensions), start_time, end_time);
    }
}

// executes callback with array of names of all RDS db instances
function getAllRDSInstanceNames(callback) {
    var rds = new AWS.RDS(config.awsCredentials);
    rds.describeDBInstances({}, function(err, data) {
        if (err) {
            console.log(err);
            callback([]);
        }
        callback(_.pluck(data.DBInstances, 'DBInstanceIdentifier'));
    });
}

// takes array of RDS db instance names and gets a variety metrics
function getRDSMetrics(instances) {
    for (index in instances) {
        var instance = instances[index];
        var dimensions = [ { "Name" : 'DBInstanceIdentifier', "Value" : instance} ];
        printMetric(buildMetricQuery('AWS/RDS', 'CPUUtilization', 'Percent', 'Average', dimensions), start_time, end_time);
        printMetric(buildMetricQuery('AWS/RDS', 'DatabaseConnections', 'Count', 'Average', dimensions), start_time, end_time);
    }
}

// executes callback with array of hashes of that include ElastiCache CacheClusterId and CacheNodeId
function getAllElasticCacheNames(callback) {
    var ec = new AWS.ElastiCache(config.awsCredentials);
    ec.describeCacheClusters({ ShowCacheNodeInfo: true}, function(err, data) {
        if (err) {
            console.log(err);
            callback([]);
        }
        var nodes = _.map(data.CacheClusters, function(value, key) {
            return [{'Name':'CacheClusterId', 'Value':value.CacheClusterId},
                    {'Name':'CacheNodeId', 'Value':value.CacheNodes[0].CacheNodeId}];
        });
        callback(nodes);
    });
}

// takes array of hashes of ElastiCache CacheClusterId and CacheNodeId and gets a variety metrics
function getElasticCacheMetrics(nodes) {
    for (index in nodes) {
        var node = nodes[index];
        printMetric(buildMetricQuery('AWS/ElastiCache', 'CPUUtilization', 'Percent', 'Average', node), start_time, end_time);
      byte_metrics = ['UnusedMemory', 'FreeableMemory', 'NetworkBytesIn', 'NetworkBytesOut'];
        for (index in byte_metrics) {
            printMetric(buildMetricQuery('AWS/ElastiCache', byte_metrics[index], 'Bytes', 'Average', node), start_time, end_time);
        }
      count_metrics = ['CurrConnections', 'CurrItems', 'Evictions', 'Reclaimed', 'GetHits', 'CacheHits',
                       'GetMisses', 'CacheMisses', 'GetTypeCmds', 'SetTypeCmds', 'CmdGet', 'CmdSet', 'DeleteHits', 'DeleteMisses', 'NewItems', 'NewConnections' ];
        for (index in count_metrics) {
            printMetric(buildMetricQuery('AWS/ElastiCache', count_metrics[index], 'Count', 'Average', node), start_time, end_time);
        }
    }
}
<commit_msg>start making metrics configurable<commit_after>var config = require('./lib/readConfig.js').readCmdOptions();

// Now using the official Amazon Web Services SDK for Javascript
var AWS = require("aws-sdk");

// We'll use the Cloudwatch API
var cloudwatch = new AWS.CloudWatch(config.awsCredentials);

// get the graphite prefix from the metrics config or use cloudwatch as default
var graphitePrefix = config.metricsConfig.carbonNameSpacePrefix || 'cloudwatch';

// use legacy format, defaulting to false
var useLegacyFormat = config.metricsConfig.legacyFormat;

// pulling all of lodash for _.sortBy(), does it matter? Do we even need to sort?
var _ = require('lodash');

// TODO: do we need both those libraries, do we need any?
var dateFormat = require('dateformat');
require('./lib/date');

// number of minutes of recent data to query
var interval = 3;

// Between now and 11 minutes ago
var now = new Date();
var then = (interval).minutes().ago();
var end_time = dateFormat(now, "isoUtcDateTime");
var start_time = dateFormat(then, "isoUtcDateTime");

// We used to use this when looking at Billing metrics
// if ( metric.Namespace.match(/Billing/) ) {
//     then.setHours(then.getHours() - 30)
// }
// if ( metric.Namespace.match(/Billing/) ) {
//     options["Period"] = '28800'
// }

var metrics = config.metricsConfig.metrics;

getAllELBNames(getELBMetrics);
getAllRDSInstanceNames(getRDSMetrics);

//TODO: read this from config
var elasticCacheMetrics = {
  byteMetrics: [
    'UnusedMemory', 'FreeableMemory', 'NetworkBytesIn', 'NetworkBytesOut'
  ],
  countMetrics: [
    'CurrConnections', 'CurrItems', 'Evictions', 'Reclaimed', 'GetHits', 'CacheHits',
    'GetMisses', 'CacheMisses', 'GetTypeCmds', 'SetTypeCmds', 'CmdGet', 'CmdSet', 'DeleteHits',
    'DeleteMisses', 'NewItems', 'NewConnections'
  ]
};

getAllElasticCacheNames(function(nodes) {
  getElasticCacheMetrics(nodes, elasticCacheMetrics);
});

for (var index in metrics) {
    printMetric(metrics[index], start_time, end_time);
}

function printMetric(metric, get_start_time, get_end_time) {

    var getMetricStatistics_param = metric;

    getMetricStatistics_param.StartTime = get_start_time;
    getMetricStatistics_param.EndTime = get_end_time;

    cloudwatch.getMetricStatistics(getMetricStatistics_param, function (err, data) {
        if (err) {
            console.error(err, err.stack); // an error occurred
            console.error("on:\n" + JSON.stringify(getMetricStatistics_param, null, 2));
        }
        else {
            formatter = useLegacyFormat ? legacyFormat : newFormat;
            console.log( formatter(metric, data).join("\n"));
        }
    });
}

// Takes the orig query and the response and formats the response as an array of strings
function newFormat(query, data) {
    var dimension_prefix = _.map(query.Dimensions, function(dim) {
        return dim.Name + '_' + dim.Value;
    }).join('.');

    return _.map(data.Datapoints, function(point) {
        var name = query.Namespace.replace("/", ".");
        name += '.' + dimension_prefix;
        name += '.' + query.MetricName;
        var value = point[query['Statistics']];
        var time = parseInt(new Date(point.Timestamp).getTime() / 1000.0);
        return name + ' ' + value + ' ' + time;
    });
}

// Takes the orig query and the response and formats the response as an array of strings
// according to old style of cloudwatch2graphite.
function legacyFormat(query, data) {

    // the legacy format is to only use the dimension Values in the prefix
    var dimension_prefix = _.map(query.Dimensions, function(dim) {
        return dim.Value;
    }).join('.');

    return _.map(data.Datapoints, function(point) {
        var name = query.Namespace.replace("/", ".");
        name += '.' + dimension_prefix;
        name += '.' + query.MetricName;
        name += '.' + query['Statistics'];
        name += '.' + query['Unit'];
        var value = point[query['Statistics']];
        var time = parseInt(new Date(point.Timestamp).getTime() / 1000.0);
        return graphitePrefix + '.' + name.toLowerCase() + ' ' + value + ' ' + time;
    });
}

// returns a hash with all details needed for an cloudwatch metrics query
function buildMetricQuery(namespace, name, unit, statistics, dimensions, period) {
    return {
        'Namespace': namespace,
        'MetricName': name,
        'Unit' : unit,
        'Statistics': [statistics],
        'Dimensions' : dimensions,
        'Period' : period || 60,
    }
}

// executes callback with array of names of all ELBs
function getAllELBNames(callback) {
    var elb = new AWS.ELB(config.awsCredentials);
    elb.describeLoadBalancers({}, function(err, data) {
        if (err) {
            console.log(err);
            callback([]);
        }
        callback(_.pluck(data.LoadBalancerDescriptions, 'LoadBalancerName'));
    });
}

// takes array of ELB names and gets a variety metrics
function getELBMetrics(elbs) {
    for (index in elbs) {
        var elb = elbs[index];
        var dimensions = [ { "Name" : 'LoadBalancerName', "Value" : elb} ];
        printMetric(buildMetricQuery('AWS/ELB', 'Latency', 'Seconds', 'Average', dimensions), start_time, end_time);
        printMetric(buildMetricQuery('AWS/ELB', 'HealthyHostCount', 'Count', 'Average', dimensions), start_time, end_time);
        printMetric(buildMetricQuery('AWS/ELB', 'UnHealthyHostCount', 'Count', 'Average', dimensions), start_time, end_time);
        printMetric(buildMetricQuery('AWS/ELB', 'HTTPCode_Backend_2XX', 'Count', 'Sum', dimensions), start_time, end_time);
        printMetric(buildMetricQuery('AWS/ELB', 'HTTPCode_Backend_3XX', 'Count', 'Sum', dimensions), start_time, end_time);
        printMetric(buildMetricQuery('AWS/ELB', 'HTTPCode_Backend_4XX', 'Count', 'Sum', dimensions), start_time, end_time);
        printMetric(buildMetricQuery('AWS/ELB', 'HTTPCode_Backend_5XX', 'Count', 'Sum', dimensions), start_time, end_time);
        printMetric(buildMetricQuery('AWS/ELB', 'HTTPCode_ELB_4XX', 'Count', 'Sum', dimensions), start_time, end_time);
        printMetric(buildMetricQuery('AWS/ELB', 'HTTPCode_ELB_5XX', 'Count', 'Sum', dimensions), start_time, end_time);
    }
}

// executes callback with array of names of all RDS db instances
function getAllRDSInstanceNames(callback) {
    var rds = new AWS.RDS(config.awsCredentials);
    rds.describeDBInstances({}, function(err, data) {
        if (err) {
            console.log(err);
            callback([]);
        }
        callback(_.pluck(data.DBInstances, 'DBInstanceIdentifier'));
    });
}

// takes array of RDS db instance names and gets a variety metrics
function getRDSMetrics(instances) {
    for (index in instances) {
        var instance = instances[index];
        var dimensions = [ { "Name" : 'DBInstanceIdentifier', "Value" : instance} ];
        printMetric(buildMetricQuery('AWS/RDS', 'CPUUtilization', 'Percent', 'Average', dimensions), start_time, end_time);
        printMetric(buildMetricQuery('AWS/RDS', 'DatabaseConnections', 'Count', 'Average', dimensions), start_time, end_time);
    }
}

// executes callback with array of hashes of that include ElastiCache CacheClusterId and CacheNodeId
function getAllElasticCacheNames(callback) {
    var ec = new AWS.ElastiCache(config.awsCredentials);
    ec.describeCacheClusters({ ShowCacheNodeInfo: true}, function(err, data) {
        if (err) {
            console.log(err);
            callback([]);
        }
        var nodes = _.map(data.CacheClusters, function(value, key) {
            return [{'Name':'CacheClusterId', 'Value':value.CacheClusterId},
                    {'Name':'CacheNodeId', 'Value':value.CacheNodes[0].CacheNodeId}];
        });
        callback(nodes);
    });
}

// takes array of hashes of ElastiCache CacheClusterId and CacheNodeId and gets a variety metrics
function getElasticCacheMetrics(nodes, elasticCacheMetrics) {
    for (index in nodes) {
        var node = nodes[index];

        printMetric(buildMetricQuery('AWS/ElastiCache', 'CPUUtilization', 'Percent', 'Average', node), start_time, end_time);

        elasticCacheMetrics.byteMetrics.forEach(function(metric) {
            printMetric(buildMetricQuery('AWS/ElastiCache', metric, 'Bytes', 'Average', node), start_time, end_time);
        });

        elasticCacheMetrics.countMetrics.forEach(function(metric) {
            printMetric(buildMetricQuery('AWS/ElastiCache', metric, 'Count', 'Average', node), start_time, end_time);
        });
    }
}
<|endoftext|>


<commit_before>var AWS = require("aws-sdk");
var fs = require("fs");
var c = require("child_process");
const exec = require("child_process").exec;

exports.myHandler = function(event, context, callback) {
  exec("ls; cp tmobile.mp4 /tmp/", (error, stdout, stderr) => {
    console.log(`${stdout}`);
    console.log(`${stderr}`);

    if (error !== null) {
      console.log(`exec error: ${error}`);
      callback("ERROR!");
    }

    exec("tar xf ffmpeg.tar.xz -C /tmp/; cd /tmp/; ls; ./ffmpeg-3.4-64bit-static/ffmpeg -i tmobile.mp4 -ss 00:00:14.435 -vframes 1 out.png; ls", (error, stdout, stderr) => {
        console.log(`${stdout}`);
        console.log(`${stderr}`);
        callback(null, "OK, responsive");
        if (error !== null) {
          console.log(`exec error: ${error}`);
          callback("ERROR!");
        }
      })

  });
};
<commit_msg>Changed ClipR_Thumbnailer: Add sample file<commit_after>var AWS = require("aws-sdk");
var fs = require("fs");
var c = require("child_process");
const exec = require("child_process").exec;
var s3 = new AWS.S3();

exports.myHandler = function(event, context, callback) {
  exec("ls; cp tmobile.mp4 /tmp/", (error, stdout, stderr) => {
    console.log(`${stdout}`);
    console.log(`${stderr}`);

    if (error !== null) {
      console.log(`exec error: ${error}`);
      callback("ERROR!");
    }

    exec("tar xf ffmpeg.tar.xz -C /tmp/; cd /tmp/; ls; ./ffmpeg-3.4-64bit-static/ffmpeg -i tmobile.mp4 -ss 00:00:14.435 -vframes 1 out.png; ls; ", (error, stdout, stderr) => {
        console.log(`${stdout}`);
        console.log(`${stderr}`);

        fs.readFile('/tmp/out.png', function (err, data) {
            if (err) {
              var resp = {
              "statusCode": 400,
              "body": JSON.stringify({"msg":"Error Reading Zipped Module", "err":err.message})
              }
              callback(null,resp);
                throw err;
            }

            var s3params = {Bucket: 'clipr-videos', Key: 'out.png', Body: data};
            s3.upload(s3params, function(err, data) {
            if(err) {
              var resp = {
                  "statusCode": 400,
                  "body": JSON.stringify({"msg":"Error Saving Code", "err":err.message})
              }
              callback(null,resp);
            }

          });

          });

        if (error !== null) {
          console.log(`exec error: ${error}`);
          callback("ERROR!");
        }

      })

  });
};
<|endoftext|>


<commit_before>CollectionAPI = function(options) {
  var self = this;

  self._url = Npm.require('url');
  self._querystring = Npm.require('querystring');
  self._fiber = Npm.require('fibers');
  self._collections = {};
  self.options = {
    apiPath: 'collectionapi',
    standAlone: false,
    sslEnabled: false,
    listenPort: 3005,
    listenHost: undefined,
    authToken: undefined,
    privateKeyFile: 'privatekey.pem',
    certificateFile: 'certificate.pem'
  };
  _.extend(self.options, options || {});
};

CollectionAPI.prototype.addCollection = function(collection, path, options) {
  var self = this;

  var collectionOptions = {};
  collectionOptions[path] = {
    collection: collection,
    options: options || {}
  };
  _.extend(self._collections, collectionOptions);
};

CollectionAPI.prototype.start = function() {
  var self = this;
  var httpServer, httpOptions, scheme;

  var startupMessage = 'Collection API v' + self.version;

  if (self.options.standAlone === true) {
    if (self.options.sslEnabled === true) {
      scheme = 'https://';
      httpServer = Npm.require('https');
      var fs = Npm.require('fs');

      httpOptions = {
        key: fs.readFileSync(self.options.privateKeyFile),
        cert: fs.readFileSync(self.options.certificateFile)
      };
    } else {
      scheme = 'http://';
      httpServer = Npm.require('http');
    }

    self._httpServer = httpServer.createServer(httpOptions);
    self._httpServer.addListener('request', function(request, response) { new CollectionAPI._requestListener(self, request, response); });
    self._httpServer.listen(self.options.listenPort, self.options.listenHost);
    console.log(startupMessage + ' running as a stand-alone server on ' +  scheme + (self.options.listenHost || 'localhost') + ':' + self.options.listenPort + '/' + (self.options.apiPath || ''));
  } else {

    RoutePolicy.declare('/' + this.options.apiPath + '/', 'network');

    WebApp.connectHandlers.use(function(req, res, next) {
      if (req.url.split('/')[1] !== self.options.apiPath) {
        next();
        return;
      }
      self._fiber(function () {
        new CollectionAPI._requestListener(self, req, res);
      }).run();
    });

    console.log(startupMessage + ' running at /' + this.options.apiPath);
  }
};

CollectionAPI.prototype._collectionOptions = function(requestPath) {
  var self = this;
  return self._collections[requestPath.collectionPath] ? self._collections[requestPath.collectionPath].options : undefined;
};

CollectionAPI._requestListener = function (server, request, response) {
  var self = this;

  self._server = server;
  self._request = request;
  self._response = response;

  self._requestUrl = self._server._url.parse(self._request.url);

  // Check for the X-Auth-Token header or auth-token in the query string
  self._requestAuthToken = self._request.headers['x-auth-token'] ? self._request.headers['x-auth-token'] : self._server._querystring.parse(self._requestUrl.query)['auth-token'];

  var requestPath;
  if (self._server.options.standAlone === true && ! self._server.options.apiPath) {
    requestPath = self._requestUrl.pathname.split('/').slice(1,3);
  } else {
    requestPath = self._requestUrl.pathname.split('/').slice(2,4);
  }

  self._requestPath = {
    collectionPath: requestPath[0],
    collectionId: requestPath[1]
  };

  self._requestCollection = self._server._collections[self._requestPath.collectionPath] ? self._server._collections[self._requestPath.collectionPath].collection : undefined;

  if (!self._authenticate()) {
    return self._unauthorizedResponse('Invalid/Missing Auth Token');
  }

  if (!self._requestCollection) {
    return self._notFoundResponse('Collection Object Not Found');
  }

  return self._handleRequest();
};

CollectionAPI._requestListener.prototype._authenticate = function() {
  var self = this;
  var collectionOptions = self._server._collectionOptions(self._requestPath);

  // Check the collection's auth token
  if (collectionOptions && collectionOptions.authToken) {
    return self._requestAuthToken === collectionOptions.authToken;
  }

  // Check the global auth token
  if (self._server.options.authToken) {
    return self._requestAuthToken === self._server.options.authToken;
  }

  return true;
};

CollectionAPI._requestListener.prototype._handleRequest = function() {
  var self = this;

  if (!self._requestMethodAllowed(self._request.method)) {
    return self._notSupportedResponse();
  }

  switch (self._request.method) {
    case 'GET':
      return self._getRequest();
    case 'POST':
      return self._postRequest();
    case 'PUT':
      return self._putRequest();
    case 'DELETE':
      return self._deleteRequest();
    default:
      return self._notSupportedResponse();
  }
};

CollectionAPI._requestListener.prototype._requestMethodAllowed = function (method) {
  var self = this;
  var collectionOptions = self._server._collectionOptions(self._requestPath);

  if (collectionOptions && collectionOptions.methods) {
    return _.indexOf(collectionOptions.methods, method) >= 0;
  }

  return true;
};

CollectionAPI._requestListener.prototype._beforeHandling = function (method) {
  var self = this;
  var collectionOptions = self._server._collectionOptions(self._requestPath);

  if (collectionOptions && collectionOptions.before && collectionOptions.before[method] &&  _.isFunction(collectionOptions.before[method])) {
    return collectionOptions.before[method].apply(self, _.rest(arguments));
  }

  return true;
}

CollectionAPI._requestListener.prototype._getRequest = function(fromPutRequest) {
  var self = this;

  self._server._fiber(function() {

    try {
      // TODO: A better way to do this?
      var collection_result = self._requestPath.collectionId !== undefined ? self._requestCollection.find(self._requestPath.collectionId) : self._requestCollection.find();

      var records = [];
      collection_result.forEach(function(record) {
        records.push(record);
      });

      if(!self._beforeHandling('GET',  self._requestPath.collectionId, records)) {
        if (fromPutRequest) {
          return records.length ? self._noContentResponse() : self._notFoundResponse('No Record(s) Found');
        }
        return self._rejectedResponse("Could not get that collection/object.");
      }

      records = _.compact(records);

      if (records.length === 0) {
        return self._notFoundResponse('No Record(s) Found');
      }

      return self._okResponse(JSON.stringify(records));

    } catch (e) {
      return self._internalServerErrorResponse(e);
    }

  }).run();

};

CollectionAPI._requestListener.prototype._putRequest = function() {
  var self = this;

  if (! self._requestPath.collectionId) {
    return self._notFoundResponse('Missing _id');
  }

  var requestData = '';

  self._request.on('data', function(chunk) {
    requestData += chunk.toString();
  });

  self._request.on('end', function() {
    self._server._fiber(function() {
      try {
        var obj = JSON.parse(requestData);

        if(!self._beforeHandling('PUT', self._requestPath.collectionId, self._requestCollection.findOne(self._requestPath.collectionId), obj)) {
          return self._rejectedResponse("Could not put that object.");
        }
        self._requestCollection.update(self._requestPath.collectionId, obj);
      } catch (e) {
        return self._internalServerErrorResponse(e);
      }
      return self._getRequest('fromPutRequest');
    }).run();
  });

};

CollectionAPI._requestListener.prototype._deleteRequest = function() {
  var self = this;

  if (! self._requestPath.collectionId) {
    return self._notFoundResponse('Missing _id');
  }

  self._server._fiber(function() {
    try {
      if(!self._beforeHandling('DELETE', self._requestPath.collectionId, self._requestCollection.findOne(self._requestPath.collectionId))) {
        return self._rejectedResponse("Could not delete that object.");
      }
      self._requestCollection.remove(self._requestPath.collectionId);
    } catch (e) {
      return self._internalServerErrorResponse(e);
    }
    return self._okResponse('');
  }).run();
};

CollectionAPI._requestListener.prototype._postRequest = function() {
  var self = this;
  var requestData = '';

  self._request.on('data', function(chunk) {
    requestData += chunk.toString();
  });

  self._request.on('end', function() {
    self._server._fiber(function() {
      try {
        var obj = JSON.parse(requestData);

        if(!self._beforeHandling('POST', obj)) {
          return self._rejectedResponse("Could not post that object.");
        }
        self._requestPath.collectionId = self._requestCollection.insert(obj);
      } catch (e) {
        return self._internalServerErrorResponse(e);
      }
      return self._createdResponse(JSON.stringify({_id: self._requestPath.collectionId}));
    }).run();
  });
};

CollectionAPI._requestListener.prototype._okResponse = function(body) {
  var self = this;
  self._sendResponse(200, body);
};

CollectionAPI._requestListener.prototype._createdResponse = function(body) {
  var self = this;
  self._sendResponse(201, body);
};

CollectionAPI._requestListener.prototype._noContentResponse = function() {
  var self = this;
  self._sendResponse(204, '');
};

CollectionAPI._requestListener.prototype._notSupportedResponse = function() {
  var self = this;
  self._sendResponse(501, '');
};

CollectionAPI._requestListener.prototype._unauthorizedResponse = function(body) {
  var self = this;
  self._sendResponse(401, JSON.stringify({message: body.toString()}));
};

CollectionAPI._requestListener.prototype._notFoundResponse = function(body) {
  var self = this;
  self._sendResponse(404, JSON.stringify({message: body.toString()}));
};

CollectionAPI._requestListener.prototype._rejectedResponse= function(body) {
  var self = this;
  self._sendResponse(409, JSON.stringify({message: body.toString()}));
};

CollectionAPI._requestListener.prototype._internalServerErrorResponse = function(body) {
  var self = this;
  self._sendResponse(500, JSON.stringify({error: body.toString()}));
};

CollectionAPI._requestListener.prototype._sendResponse = function(statusCode, body) {
  var self = this;
  self._response.statusCode = statusCode;
  self._response.setHeader('Content-Length', Buffer.byteLength(body, 'utf8'));
  self._response.setHeader('Content-Type', 'application/json');
  self._response.write(body);
  self._response.end();
};
<commit_msg>fix indent, remove tab<commit_after>CollectionAPI = function(options) {
  var self = this;

  self._url = Npm.require('url');
  self._querystring = Npm.require('querystring');
  self._fiber = Npm.require('fibers');
  self._collections = {};
  self.options = {
    apiPath: 'collectionapi',
    standAlone: false,
    sslEnabled: false,
    listenPort: 3005,
    listenHost: undefined,
    authToken: undefined,
    privateKeyFile: 'privatekey.pem',
    certificateFile: 'certificate.pem'
  };
  _.extend(self.options, options || {});
};

CollectionAPI.prototype.addCollection = function(collection, path, options) {
  var self = this;

  var collectionOptions = {};
  collectionOptions[path] = {
    collection: collection,
    options: options || {}
  };
  _.extend(self._collections, collectionOptions);
};

CollectionAPI.prototype.start = function() {
  var self = this;
  var httpServer, httpOptions, scheme;

  var startupMessage = 'Collection API v' + self.version;

  if (self.options.standAlone === true) {
    if (self.options.sslEnabled === true) {
      scheme = 'https://';
      httpServer = Npm.require('https');
      var fs = Npm.require('fs');

      httpOptions = {
        key: fs.readFileSync(self.options.privateKeyFile),
        cert: fs.readFileSync(self.options.certificateFile)
      };
    } else {
      scheme = 'http://';
      httpServer = Npm.require('http');
    }

    self._httpServer = httpServer.createServer(httpOptions);
    self._httpServer.addListener('request', function(request, response) { new CollectionAPI._requestListener(self, request, response); });
    self._httpServer.listen(self.options.listenPort, self.options.listenHost);
    console.log(startupMessage + ' running as a stand-alone server on ' +  scheme + (self.options.listenHost || 'localhost') + ':' + self.options.listenPort + '/' + (self.options.apiPath || ''));
  } else {

    RoutePolicy.declare('/' + this.options.apiPath + '/', 'network');

    WebApp.connectHandlers.use(function(req, res, next) {
      if (req.url.split('/')[1] !== self.options.apiPath) {
        next();
        return;
      }
      self._fiber(function () {
        new CollectionAPI._requestListener(self, req, res);
      }).run();
    });

    console.log(startupMessage + ' running at /' + this.options.apiPath);
  }
};

CollectionAPI.prototype._collectionOptions = function(requestPath) {
  var self = this;
  return self._collections[requestPath.collectionPath] ? self._collections[requestPath.collectionPath].options : undefined;
};

CollectionAPI._requestListener = function (server, request, response) {
  var self = this;

  self._server = server;
  self._request = request;
  self._response = response;

  self._requestUrl = self._server._url.parse(self._request.url);

  // Check for the X-Auth-Token header or auth-token in the query string
  self._requestAuthToken = self._request.headers['x-auth-token'] ? self._request.headers['x-auth-token'] : self._server._querystring.parse(self._requestUrl.query)['auth-token'];

  var requestPath;
  if (self._server.options.standAlone === true && ! self._server.options.apiPath) {
    requestPath = self._requestUrl.pathname.split('/').slice(1,3);
  } else {
    requestPath = self._requestUrl.pathname.split('/').slice(2,4);
  }

  self._requestPath = {
    collectionPath: requestPath[0],
    collectionId: requestPath[1]
  };

  self._requestCollection = self._server._collections[self._requestPath.collectionPath] ? self._server._collections[self._requestPath.collectionPath].collection : undefined;

  if (!self._authenticate()) {
    return self._unauthorizedResponse('Invalid/Missing Auth Token');
  }

  if (!self._requestCollection) {
    return self._notFoundResponse('Collection Object Not Found');
  }

  return self._handleRequest();
};

CollectionAPI._requestListener.prototype._authenticate = function() {
  var self = this;
  var collectionOptions = self._server._collectionOptions(self._requestPath);

  // Check the collection's auth token
  if (collectionOptions && collectionOptions.authToken) {
    return self._requestAuthToken === collectionOptions.authToken;
  }

  // Check the global auth token
  if (self._server.options.authToken) {
    return self._requestAuthToken === self._server.options.authToken;
  }

  return true;
};

CollectionAPI._requestListener.prototype._handleRequest = function() {
  var self = this;

  if (!self._requestMethodAllowed(self._request.method)) {
    return self._notSupportedResponse();
  }

  switch (self._request.method) {
    case 'GET':
      return self._getRequest();
    case 'POST':
      return self._postRequest();
    case 'PUT':
      return self._putRequest();
    case 'DELETE':
      return self._deleteRequest();
    default:
      return self._notSupportedResponse();
  }
};

CollectionAPI._requestListener.prototype._requestMethodAllowed = function (method) {
  var self = this;
  var collectionOptions = self._server._collectionOptions(self._requestPath);

  if (collectionOptions && collectionOptions.methods) {
    return _.indexOf(collectionOptions.methods, method) >= 0;
  }

  return true;
};

CollectionAPI._requestListener.prototype._beforeHandling = function (method) {
  var self = this;
  var collectionOptions = self._server._collectionOptions(self._requestPath);

  if (collectionOptions && collectionOptions.before && collectionOptions.before[method] &&  _.isFunction(collectionOptions.before[method])) {
    return collectionOptions.before[method].apply(self, _.rest(arguments));
  }

  return true;
}

CollectionAPI._requestListener.prototype._getRequest = function(fromPutRequest) {
  var self = this;

  self._server._fiber(function() {

    try {
      // TODO: A better way to do this?
      var collection_result = self._requestPath.collectionId !== undefined ? self._requestCollection.find(self._requestPath.collectionId) : self._requestCollection.find();

      var records = [];
      collection_result.forEach(function(record) {
        records.push(record);
      });

      if(!self._beforeHandling('GET',  self._requestPath.collectionId, records)) {
        if (fromPutRequest) {
          return records.length ? self._noContentResponse() : self._notFoundResponse('No Record(s) Found');
        }
        return self._rejectedResponse("Could not get that collection/object.");
      }

      records = _.compact(records);

      if (records.length === 0) {
        return self._notFoundResponse('No Record(s) Found');
      }

      return self._okResponse(JSON.stringify(records));

    } catch (e) {
      return self._internalServerErrorResponse(e);
    }

  }).run();

};

CollectionAPI._requestListener.prototype._putRequest = function() {
  var self = this;

  if (! self._requestPath.collectionId) {
    return self._notFoundResponse('Missing _id');
  }

  var requestData = '';

  self._request.on('data', function(chunk) {
    requestData += chunk.toString();
  });

  self._request.on('end', function() {
    self._server._fiber(function() {
      try {
        var obj = JSON.parse(requestData);

        if(!self._beforeHandling('PUT', self._requestPath.collectionId, self._requestCollection.findOne(self._requestPath.collectionId), obj)) {
          return self._rejectedResponse("Could not put that object.");
        }
        self._requestCollection.update(self._requestPath.collectionId, obj);
      } catch (e) {
        return self._internalServerErrorResponse(e);
      }
      return self._getRequest('fromPutRequest');
    }).run();
  });

};

CollectionAPI._requestListener.prototype._deleteRequest = function() {
  var self = this;

  if (! self._requestPath.collectionId) {
    return self._notFoundResponse('Missing _id');
  }

  self._server._fiber(function() {
    try {
      if(!self._beforeHandling('DELETE', self._requestPath.collectionId, self._requestCollection.findOne(self._requestPath.collectionId))) {
        return self._rejectedResponse("Could not delete that object.");
      }
      self._requestCollection.remove(self._requestPath.collectionId);
    } catch (e) {
      return self._internalServerErrorResponse(e);
    }
    return self._okResponse('');
  }).run();
};

CollectionAPI._requestListener.prototype._postRequest = function() {
  var self = this;
  var requestData = '';

  self._request.on('data', function(chunk) {
    requestData += chunk.toString();
  });

  self._request.on('end', function() {
    self._server._fiber(function() {
      try {
        var obj = JSON.parse(requestData);

        if(!self._beforeHandling('POST', obj)) {
          return self._rejectedResponse("Could not post that object.");
        }
        self._requestPath.collectionId = self._requestCollection.insert(obj);
      } catch (e) {
        return self._internalServerErrorResponse(e);
      }
      return self._createdResponse(JSON.stringify({_id: self._requestPath.collectionId}));
    }).run();
  });
};

CollectionAPI._requestListener.prototype._okResponse = function(body) {
  var self = this;
  self._sendResponse(200, body);
};

CollectionAPI._requestListener.prototype._createdResponse = function(body) {
  var self = this;
  self._sendResponse(201, body);
};

CollectionAPI._requestListener.prototype._noContentResponse = function() {
  var self = this;
  self._sendResponse(204, '');
};

CollectionAPI._requestListener.prototype._notSupportedResponse = function() {
  var self = this;
  self._sendResponse(501, '');
};

CollectionAPI._requestListener.prototype._unauthorizedResponse = function(body) {
  var self = this;
  self._sendResponse(401, JSON.stringify({message: body.toString()}));
};

CollectionAPI._requestListener.prototype._notFoundResponse = function(body) {
  var self = this;
  self._sendResponse(404, JSON.stringify({message: body.toString()}));
};

CollectionAPI._requestListener.prototype._rejectedResponse= function(body) {
  var self = this;
  self._sendResponse(409, JSON.stringify({message: body.toString()}));
};

CollectionAPI._requestListener.prototype._internalServerErrorResponse = function(body) {
  var self = this;
  self._sendResponse(500, JSON.stringify({error: body.toString()}));
};

CollectionAPI._requestListener.prototype._sendResponse = function(statusCode, body) {
  var self = this;
  self._response.statusCode = statusCode;
  self._response.setHeader('Content-Length', Buffer.byteLength(body, 'utf8'));
  self._response.setHeader('Content-Type', 'application/json');
  self._response.write(body);
  self._response.end();
};
<|endoftext|>


<commit_before>//Dependencies.
var CoreStore = require('../CoreStore');
var buildDefinition = require('./definition');
/**
 * Class standing for the reference store.
 */
class ReferenceStore extends CoreStore {
  constructor(conf){
    conf = conf || {};
    conf.definition = conf.definition || buildDefinition();
    super(conf);
  }
}

module.exports = ReferenceStore;
<commit_msg>[reference] Store add method to load references.<commit_after>//Dependencies.
var CoreStore = require('../CoreStore');
var buildDefinition = require('./definition');
/**
 * Class standing for the reference store.
 */
class ReferenceStore extends CoreStore {

  constructor(conf){
    conf = conf || {};
    conf.definition = conf.definition || buildDefinition();
    super(conf);
  }
  getReference(names){
    var refs = {};
    names.map((name)=>{
      if(this.data.has(name)){
        refs[name] = this.data.get(name);
      }
    });
    return {references: this.data.toJS()};
  }
  setReference(){}

}

module.exports = ReferenceStore;
<|endoftext|>


<commit_before>#!/usr/bin/env node
var app=require("express")(),
    http=require("http").Server(app),
    io=require("socket.io")(http),
    child_process=require("child_process"),
    shlex=require("shell-quote").parse;

var HTTPPORT=8012;

var conn=null,ai=new AI(),ai2=new AI();

function AI(){
	var proc=null;
	var cmd=null;
	var buf=null;
	var lines=[];
	var lineslisteners=[];

	this.reset=function(){
		console.log("AI_STOP\n");
		if(proc)proc.kill("SIGTERM");
		proc=null;
		cmd=null;
		buf=null;
		lines=[];
		lineslisteners=[];
	}

	this.start=function(command){
		this.reset();
		cmd=command;
		var lexed=shlex(cmd);
		console.log( process.env.PATH );
		console.log("starting");
		proc=child_process.spawn(lexed[0],lexed.slice(1),{stdio:["pipe","pipe","inherit"]});
		console.log("AI_START");
		var self=this;
		proc.on("error",function(err){
			if(err){
				if(conn)conn.emit("alert",err.message);
				console.log(err);
				self.reset();
				return;
			}
		});
		proc.stdout.on("data",function(data){
			console.log("AI_OUT: "+String(data).replace(/\n$/,""));
			var idx;
			buf+=data;
			idx=buf.indexOf("\n");
			while(idx!=-1){
				lines.push(buf.slice(0,idx));
				buf=buf.slice(idx+1);
				idx=buf.indexOf("\n");
			}
			while(lines.length&&lineslisteners.length){
				lineslisteners.shift()(lines.shift());
			}
		});
		buf="";
	}

	this.writeln=function(text){
		console.log("AI_IN: "+text);
		proc.stdin.write(text+"\n");
	}

	this.getline=function(){
		var line;
		if(lines.length){
			line=lines.shift();
			conn.emit("ailine",line);
			console.log(" sent: "+line);
		} else lineslisteners.push(function(line){
			conn.emit("ailine",line);
			console.log(" sent: "+line);
		});
	}

	this.status=function(){
		if(proc==null)conn.emit("aistatus","Not running");
		else conn.emit("aistatus","Running: "+cmd);
	}
}

app.get('/style.css', function(req, res) {
	res.sendFile(__dirname + "/style.css");
});
app.get('/client.js', function(req, res) {
	res.sendFile(__dirname + "/client.js");
});

app.get("/",function(req,res){
	res.sendFile(__dirname+"/index.html");
});
var aiVsAi=false;
var turn=0;
io.on("connection",function(_conn){
	if(conn!=null){
		_conn.emit("alert","Another connection already active!");
		_conn.emit("jseval","window.close();");
		_conn.disconnect(true);
		return;
	}
	console.log("(connect)");
	conn=_conn;
	conn.on("disconnect",function(){
		console.log("(disconnect)");
		conn.disconnect(); //just to be sure
		conn=null;
		ai.reset();
		if(aiVsAi)ai2.reset();
	});
	conn.on("aistart2",function(cmd,cmd2){
		ai.start(cmd);
		ai2.start(cmd2);
		aiVsAi=true;
		turn=0;
	});
	conn.on("aistart",function(cmd){
		if(aiVsAi)ai.reset();
		ai.start(cmd);
		aiVsAi=false;
	});
	conn.on("aistop",function(){
		ai.reset();
		if(aiVsAi)ai2.reset();
	});
	conn.on("aiwriteln",function(text){
		if(!aiVsAi)ai.writeln(text);
		else{
			if(turn==0)ai.writeln(text);
			else ai2.writeln(text);
		}
	});
	conn.on("aigetline",function(){
		if(aiVsAi){
			if(turn==0)ai.getline();
			else ai2.getline();
			turn=!turn;
		}else{
			ai.getline();
		}
	});
	conn.on("aistatus",function(){
		ai.status();
	});
});

http.listen(HTTPPORT,function(){
	console.log("Listening on http://localhost:"+HTTPPORT);
});
<commit_msg>Removed random path print<commit_after>#!/usr/bin/env node
var app=require("express")(),
    http=require("http").Server(app),
    io=require("socket.io")(http),
    child_process=require("child_process"),
    shlex=require("shell-quote").parse;

var HTTPPORT=8012;

var conn=null,ai=new AI(),ai2=new AI();

function AI(){
	var proc=null;
	var cmd=null;
	var buf=null;
	var lines=[];
	var lineslisteners=[];

	this.reset=function(){
		console.log("AI_STOP\n");
		if(proc)proc.kill("SIGTERM");
		proc=null;
		cmd=null;
		buf=null;
		lines=[];
		lineslisteners=[];
	}

	this.start=function(command){
		this.reset();
		cmd=command;
		var lexed=shlex(cmd);
		console.log("starting");
		proc=child_process.spawn(lexed[0],lexed.slice(1),{stdio:["pipe","pipe","inherit"]});
		console.log("AI_START");
		var self=this;
		proc.on("error",function(err){
			if(err){
				if(conn)conn.emit("alert",err.message);
				console.log(err);
				self.reset();
				return;
			}
		});
		proc.stdout.on("data",function(data){
			console.log("AI_OUT: "+String(data).replace(/\n$/,""));
			var idx;
			buf+=data;
			idx=buf.indexOf("\n");
			while(idx!=-1){
				lines.push(buf.slice(0,idx));
				buf=buf.slice(idx+1);
				idx=buf.indexOf("\n");
			}
			while(lines.length&&lineslisteners.length){
				lineslisteners.shift()(lines.shift());
			}
		});
		buf="";
	}

	this.writeln=function(text){
		console.log("AI_IN: "+text);
		proc.stdin.write(text+"\n");
	}

	this.getline=function(){
		var line;
		if(lines.length){
			line=lines.shift();
			conn.emit("ailine",line);
			console.log(" sent: "+line);
		} else lineslisteners.push(function(line){
			conn.emit("ailine",line);
			console.log(" sent: "+line);
		});
	}

	this.status=function(){
		if(proc==null)conn.emit("aistatus","Not running");
		else conn.emit("aistatus","Running: "+cmd);
	}
}

app.get('/style.css', function(req, res) {
	res.sendFile(__dirname + "/style.css");
});
app.get('/client.js', function(req, res) {
	res.sendFile(__dirname + "/client.js");
});

app.get("/",function(req,res){
	res.sendFile(__dirname+"/index.html");
});
var aiVsAi=false;
var turn=0;
io.on("connection",function(_conn){
	if(conn!=null){
		_conn.emit("alert","Another connection already active!");
		_conn.emit("jseval","window.close();");
		_conn.disconnect(true);
		return;
	}
	console.log("(connect)");
	conn=_conn;
	conn.on("disconnect",function(){
		console.log("(disconnect)");
		conn.disconnect(); //just to be sure
		conn=null;
		ai.reset();
		if(aiVsAi)ai2.reset();
	});
	conn.on("aistart2",function(cmd,cmd2){
		ai.start(cmd);
		ai2.start(cmd2);
		aiVsAi=true;
		turn=0;
	});
	conn.on("aistart",function(cmd){
		if(aiVsAi)ai.reset();
		ai.start(cmd);
		aiVsAi=false;
	});
	conn.on("aistop",function(){
		ai.reset();
		if(aiVsAi)ai2.reset();
	});
	conn.on("aiwriteln",function(text){
		if(!aiVsAi)ai.writeln(text);
		else{
			if(turn==0)ai.writeln(text);
			else ai2.writeln(text);
		}
	});
	conn.on("aigetline",function(){
		if(aiVsAi){
			if(turn==0)ai.getline();
			else ai2.getline();
			turn=!turn;
		}else{
			ai.getline();
		}
	});
	conn.on("aistatus",function(){
		ai.status();
	});
});

http.listen(HTTPPORT,function(){
	console.log("Listening on http://localhost:"+HTTPPORT);
});
<|endoftext|>