<commit_before>const path = require('path');

const winston = require('winston');

const { getLogsPath } = require('./logs');

class Logger {
  constructor() {
    this.logger = winston.createLogger({
      level: 'info',
      format: winston.format.json(),
      defaultMeta: { application: 'hue-remote' },
      transports: [
        new winston.transports.File({
          filename: path.resolve(getLogsPath(), 'application.log')
        })
      ]
    });
  }
}

module.exports = Logger;
<commit_msg>added a singleton to the logger class<commit_after>/* eslint-disable max-classes-per-file */

const path = require('path');

const winston = require('winston');

const { getLogsPath } = require('./logs');

class Logger {
  constructor() {
    this.logger = winston.createLogger({
      level: 'info',
      format: winston.format.json(),
      defaultMeta: { application: 'hue-remote' },
      transports: [
        new winston.transports.File({
          filename: path.resolve(getLogsPath(), 'application.log')
        })
      ]
    });
  }
}

class Singleton {
  getInstance() {
    if (!Singleton.instance) {
      Singleton.instance = new Logger();
    }
  }
}

module.exports = Singleton;
<|endoftext|>


<commit_before>Ext.namespace('Kwc.Abstract.Image');
Kwc.Abstract.Image.DimensionWindow = Ext.extend(Ext.Window, {

    dimensions: null,
    value: null, //contains width, height, cropdata

    title: trlKwf('Image Size'),
    closeAction: 'close',
    modal: true,
    width: 850,
    height: 350,
    layout: 'fit',
    resizable: false,

    initComponent: function() {
        var radios = [];
        for (var i in this.dimensions) {
            radios.push({
                inputValue: i,
                boxLabel: Kwc.Abstract.Image.DimensionField.getDimensionString(this.dimensions, {dimension: i}),
                name: 'dimension',
                listeners: {
                    check: this._enableDisableFields,
                    scope: this
                }
            });
        }
        this._dimensionField = new Kwf.Form.RadioGroup({
            columns: 1,
            hideLabel: true,
            vertical: false,
            items: radios
        });
        this._widthField = new Ext.form.NumberField({
            fieldLabel: trlKwf('Width'),
            width: 50,
            enableKeyEvents: true,
            validateOnBlur: false,
            validationEvent: false,
            allowNegative: false
        });
        this._heightField = new Ext.form.NumberField({
            fieldLabel: trlKwf('Height'),
            width: 50,
            enableKeyEvents: true,
            validateOnBlur: false,
            validationEvent: false,
            allowNegative: false
        });

        this._widthField.on('blur', this._validateSizes, this);
        this._widthField.on('keyup', this._validateSizes, this);
        this._widthField.on('keyup', this._updateOutSize, this);
        this._heightField.on('blur', this._validateSizes, this);
        this._heightField.on('keyup', this._validateSizes, this);
        this._heightField.on('keyup', this._updateOutSize, this);
        this._dimensionField.on('change', this._validateSizes, this);
        this._dimensionField.on('change', this._resetCropRegion, this);

        // Has to be initialised before cropRegion because cropRegion needs dimensionValue
        if (this.value && this.value.dimension) {
            this._dimensionField.setValue(this.value.dimension);
            this._widthField.setValue(this.value.width);
            this._heightField.setValue(this.value.height);
        } else {
            for (var i in this.dimensions) {
                break;
            }
            this._dimensionField.setValue(i);
        }
        this._enableDisableFields();

        this._initCropRegion();

        this._configPane = new Ext.FormPanel({
            region: 'west',
            bodyStyle: 'padding: 10px',
            width: 250,
            items: [
                this._dimensionField,
                {
                    xtype: 'fieldset',
                    autoHeight: true,
                    title: trlKwf('Size'),
                    items: [
                        this._widthField,
                        this._heightField
                    ]
                }
            ]
        });

        this._cropPane = new Ext.Panel({
            region: 'center',
            layout: 'fit',
            width: 600,
            height: 200,
            items: [
                this._cropImage
            ]
        });

        this.items = new Ext.FormPanel({
            bodyStyle: 'padding: 10px',
            layout: 'border',
            items: [
                this._configPane,
                this._cropPane
            ]
        });
        this.buttons = [
            {
                text: trlKwf('OK'),
                handler: function() {
                    if (this._validateSizes()) {
                        this.value.cropData = this.cropData;
                        this.value = {
                            dimension: this._dimensionField.getValue(),
                            width: this._widthField.getValue(),
                            height: this._heightField.getValue(),
                            cropData: this.value.cropData
                        };
                        this.fireEvent('save', this.value);
                        this.close();
                    } else {
                        Ext.Msg.alert(trlKwf('Error'), trlKwf('Please fill the marked fields correctly.'));
                    }
                },
                scope: this
            },{
                text: trlKwf('Cancel'),
                handler: function() {
                    this.close();
                },
                scope: this
            }
        ];

        Kwc.Abstract.Image.DimensionWindow.superclass.initComponent.call(this);
        this._validateSizes();
    },

    _initCropRegion: function ()
    {
        var cropData = null;
        if (this._dimensionField.getValue() == this.value.dimension) {
            // load saved crop-values if not 0
            if (this.value.cropData && this.value.cropData.width > 0 && this.value.cropData.height > 0) {
                cropData = this.value.cropData;
            }
        }

        var outWidth = this._getWidth();
        var outHeight = this._getHeight();
        if (outWidth == -1 || outHeight == -1) {
            return;
        }

        var preserveRatio = this._getPreserveRatio();

        this._cropImage = new Kwc.Abstract.Image.CropImage({
            // call controller to create image with nice size to work with
            src: '/kwf/media/upload/download-handy?uploadId='+this.imageData.uploadId+'&hashKey='+this.imageData.hashKey,
            preserveRatio: preserveRatio,
            width: 500,
            height: 300,
            outWidth: outWidth,
            outHeight: outHeight,
            cropData: cropData
        });

        this._cropImage.on('changeCrop', function(cropImageElement, x) {
            this.cropData = x;
        }, this);
        this._cropImage.on('finishedLoading', function (dimensions) {
            this._cropPane.width = dimensions.width;
            this._cropPane.height = dimensions.height;
            this.setSize(250 + 18 + dimensions.width, dimensions.height + 73);
            //TODO handle image height smaller than dimensions-radios
        }, this);
    },

    _getPreserveRatio: function()
    {
        var preserveRatio = false;
        var outWidth = this._getWidth();
        var outHeight = this._getHeight();
        var dimension = this.dimensions[this._dimensionField.getValue()];
        if (dimension.cover == true && !(outWidth == 0 || outHeight == 0)) {
            preserveRatio = true;
        }
        return preserveRatio;
    },

    _getHeight: function ()
    {
        var outHeight = -1;
        var dimension = this.dimensions[this._dimensionField.getValue()];
        if (dimension.height == 'user' && this._heightField.getValue() != '') {
            outHeight = this._heightField.getValue();
        } else if (dimension.height >= 0) {
            outHeight = dimension.height;
        } else if (typeof dimension.height === 'undefined') {
            outHeight = 0;
        } else {
            Ext.Msg.alert(trlKwf('Error'), trlKwf('No height value was set'));
        }
        return outHeight;
    },

    _getWidth: function ()
    {
        var outWidth = -1;
        var dimension = this.dimensions[this._dimensionField.getValue()];
        if (dimension.width == 'user' && this._widthField.getValue() != '') {
            outWidth = this._widthField.getValue();
        } else if (dimension.width == 'contentWidth') {
            outWidth = 0;
        } else if (dimension.width >= 0) {
            outWidth = dimension.width;
        } else if (typeof dimension.width === 'undefined') {
            outWidth = 0;
        } else {
            Ext.Msg.alert(trlKwf('Error'), trlKwf('No width value was set'));
        }
        return outWidth;
    },

    _resetCropRegion: function (element, value)
    {
        var cropData = null;
        if (value.inputValue == this.value.dimension) {
            cropData = this.value.cropData;
        }
        this.value = {
            dimension: this._dimensionField.getValue(),
            width: this._widthField.getValue(),
            height: this._heightField.getValue(),
            cropData: cropData
        };
        var outWidth = this._getWidth();
        var outHeight = this._getHeight();
        if (outWidth == -1 || outHeight == -1) {
            return;
        }
        this._cropImage.outWidth = outWidth;
        this._cropImage.outHeight = outHeight;
        this._cropImage.setCropData(cropData, this._getPreserveRatio());
    },

    _validateSizes: function()
    {
        var dim = this._dimensionField.getValue();
        if (this._widthField.getValue() < 1 && this.dimensions[dim].width == 'user'
            && this._heightField.getValue() < 1 && this.dimensions[dim].height == 'user'
        ) {
            if (this._widthField.getValue() < 1) {
                this._widthField.markInvalid(trlKwf('Width or height must be higher than 0 when using crop or cover.'));
            }
            if (this._heightField.getValue() < 1) {
                this._heightField.markInvalid(trlKwf('Width or height must be higher than 0 when using crop or cover.'));
            }
            return false;
        }

        this._widthField.clearInvalid();
        this._heightField.clearInvalid();

        return true;
    },

    _updateOutSize: function()
    {
        var outWidth = this._widthField.getValue();
        var outHeight = this._heightField.getValue();
        var cropData = this._cropImage.getCropData();
        var preserveRatio = false;
        if (outWidth > 0 && outHeight > 0) {
            this._cropImage.outWidth = outWidth;
            this._cropImage.outHeight = outHeight;
            preserveRatio = true;
            cropData.height = outHeight * cropData.width / outWidth;
        }
        this._cropImage.setCropData(cropData, preserveRatio);
    },

    _enableDisableFields: function()
    {
        var dim = this.dimensions[this._dimensionField.getValue()];
        this._widthField.setDisabled(!(dim && dim.width == 'user'));
        this._heightField.setDisabled(!(dim && dim.height == 'user'));
    }
});

Ext.reg('kwc.image.dimensionwindow', Kwc.Abstract.Image.DimensionWindow);
<commit_msg>Remove fieldset for custom size (simplify design)<commit_after>Ext.namespace('Kwc.Abstract.Image');
Kwc.Abstract.Image.DimensionWindow = Ext.extend(Ext.Window, {

    dimensions: null,
    value: null, //contains width, height, cropdata

    title: trlKwf('Image Size'),
    closeAction: 'close',
    modal: true,
    width: 850,
    height: 350,
    layout: 'fit',
    resizable: false,

    initComponent: function() {
        var radios = [];
        for (var i in this.dimensions) {
            radios.push({
                inputValue: i,
                boxLabel: Kwc.Abstract.Image.DimensionField.getDimensionString(this.dimensions, {dimension: i}),
                name: 'dimension',
                listeners: {
                    check: this._enableDisableFields,
                    scope: this
                }
            });
        }
        this._dimensionField = new Kwf.Form.RadioGroup({
            columns: 1,
            hideLabel: true,
            vertical: false,
            items: radios
        });
        this._widthField = new Ext.form.NumberField({
            columnWidth: 0.45,
            enableKeyEvents: true,
            validateOnBlur: false,
            validationEvent: false,
            allowNegative: false
        });
        this._heightField = new Ext.form.NumberField({
            columnWidth: 0.45,
            enableKeyEvents: true,
            validateOnBlur: false,
            validationEvent: false,
            allowNegative: false
        });

        this._widthField.on('blur', this._validateSizes, this);
        this._widthField.on('keyup', this._validateSizes, this);
        this._widthField.on('keyup', this._updateOutSize, this);
        this._heightField.on('blur', this._validateSizes, this);
        this._heightField.on('keyup', this._validateSizes, this);
        this._heightField.on('keyup', this._updateOutSize, this);
        this._dimensionField.on('change', this._validateSizes, this);
        this._dimensionField.on('change', this._resetCropRegion, this);

        // Has to be initialised before cropRegion because cropRegion needs dimensionValue
        if (this.value && this.value.dimension) {
            this._dimensionField.setValue(this.value.dimension);
            this._widthField.setValue(this.value.width);
            this._heightField.setValue(this.value.height);
        } else {
            for (var i in this.dimensions) {
                break;
            }
            this._dimensionField.setValue(i);
        }
        this._enableDisableFields();

        this._initCropRegion();

        this._configPane = new Ext.FormPanel({
            region: 'west',
            bodyStyle: 'padding: 10px',
            width: 200,
            hideBorders: true,
            items: [
                this._dimensionField,
                {
                    xtype: 'panel',
                    layout: 'column',
                    hideBorders: true,
                    autoHeight: true,
                    items: [
                        this._widthField,
                        {
                            columnWidth: 0.1,
                            html: 'x',
                            style: 'line-height:20px;text-align:center;'
                        },
                        this._heightField
                    ]
                }
            ]
        });

        this._cropPane = new Ext.Panel({
            region: 'center',
            layout: 'fit',
            width: 600,
            height: 200,
            items: [
                this._cropImage
            ]
        });

        this.items = new Ext.FormPanel({
            bodyStyle: 'padding: 10px',
            layout: 'border',
            items: [
                this._configPane,
                this._cropPane
            ]
        });
        this.buttons = [
            {
                text: trlKwf('OK'),
                handler: function() {
                    if (this._validateSizes()) {
                        this.value.cropData = this.cropData;
                        this.value = {
                            dimension: this._dimensionField.getValue(),
                            width: this._widthField.getValue(),
                            height: this._heightField.getValue(),
                            cropData: this.value.cropData
                        };
                        this.fireEvent('save', this.value);
                        this.close();
                    } else {
                        Ext.Msg.alert(trlKwf('Error'), trlKwf('Please fill the marked fields correctly.'));
                    }
                },
                scope: this
            },{
                text: trlKwf('Cancel'),
                handler: function() {
                    this.close();
                },
                scope: this
            }
        ];

        Kwc.Abstract.Image.DimensionWindow.superclass.initComponent.call(this);
        this._validateSizes();
    },

    _initCropRegion: function ()
    {
        var cropData = null;
        if (this._dimensionField.getValue() == this.value.dimension) {
            // load saved crop-values if not 0
            if (this.value.cropData && this.value.cropData.width > 0 && this.value.cropData.height > 0) {
                cropData = this.value.cropData;
            }
        }

        var outWidth = this._getWidth();
        var outHeight = this._getHeight();
        if (outWidth == -1 || outHeight == -1) {
            return;
        }

        var preserveRatio = this._getPreserveRatio();

        this._cropImage = new Kwc.Abstract.Image.CropImage({
            // call controller to create image with nice size to work with
            src: '/kwf/media/upload/download-handy?uploadId='+this.imageData.uploadId+'&hashKey='+this.imageData.hashKey,
            preserveRatio: preserveRatio,
            width: 500,
            height: 300,
            outWidth: outWidth,
            outHeight: outHeight,
            cropData: cropData
        });

        this._cropImage.on('changeCrop', function(cropImageElement, x) {
            this.cropData = x;
        }, this);
        this._cropImage.on('finishedLoading', function (dimensions) {
            this._cropPane.width = dimensions.width;
            this._cropPane.height = dimensions.height;
            this.setSize(200 + 18 + dimensions.width, dimensions.height + 73);
            //TODO handle image height smaller than dimensions-radios
        }, this);
    },

    _getPreserveRatio: function()
    {
        var preserveRatio = false;
        var outWidth = this._getWidth();
        var outHeight = this._getHeight();
        var dimension = this.dimensions[this._dimensionField.getValue()];
        if (dimension.cover == true && !(outWidth == 0 || outHeight == 0)) {
            preserveRatio = true;
        }
        return preserveRatio;
    },

    _getHeight: function ()
    {
        var outHeight = -1;
        var dimension = this.dimensions[this._dimensionField.getValue()];
        if (dimension.height == 'user' && this._heightField.getValue() != '') {
            outHeight = this._heightField.getValue();
        } else if (dimension.height >= 0) {
            outHeight = dimension.height;
        } else if (typeof dimension.height === 'undefined') {
            outHeight = 0;
        } else {
            Ext.Msg.alert(trlKwf('Error'), trlKwf('No height value was set'));
        }
        return outHeight;
    },

    _getWidth: function ()
    {
        var outWidth = -1;
        var dimension = this.dimensions[this._dimensionField.getValue()];
        if (dimension.width == 'user' && this._widthField.getValue() != '') {
            outWidth = this._widthField.getValue();
        } else if (dimension.width == 'contentWidth') {
            outWidth = 0;
        } else if (dimension.width >= 0) {
            outWidth = dimension.width;
        } else if (typeof dimension.width === 'undefined') {
            outWidth = 0;
        } else {
            Ext.Msg.alert(trlKwf('Error'), trlKwf('No width value was set'));
        }
        return outWidth;
    },

    _resetCropRegion: function (element, value)
    {
        var cropData = null;
        if (value.inputValue == this.value.dimension) {
            cropData = this.value.cropData;
        }
        this.value = {
            dimension: this._dimensionField.getValue(),
            width: this._widthField.getValue(),
            height: this._heightField.getValue(),
            cropData: cropData
        };
        var outWidth = this._getWidth();
        var outHeight = this._getHeight();
        if (outWidth == -1 || outHeight == -1) {
            return;
        }
        this._cropImage.outWidth = outWidth;
        this._cropImage.outHeight = outHeight;
        this._cropImage.setCropData(cropData, this._getPreserveRatio());
    },

    _validateSizes: function()
    {
        var dim = this._dimensionField.getValue();
        if (this._widthField.getValue() < 1 && this.dimensions[dim].width == 'user'
            && this._heightField.getValue() < 1 && this.dimensions[dim].height == 'user'
        ) {
            if (this._widthField.getValue() < 1) {
                this._widthField.markInvalid(trlKwf('Width or height must be higher than 0 when using crop or cover.'));
            }
            if (this._heightField.getValue() < 1) {
                this._heightField.markInvalid(trlKwf('Width or height must be higher than 0 when using crop or cover.'));
            }
            return false;
        }

        this._widthField.clearInvalid();
        this._heightField.clearInvalid();

        return true;
    },

    _updateOutSize: function()
    {
        var outWidth = this._widthField.getValue();
        var outHeight = this._heightField.getValue();
        var cropData = this._cropImage.getCropData();
        var preserveRatio = false;
        if (outWidth > 0 && outHeight > 0) {
            this._cropImage.outWidth = outWidth;
            this._cropImage.outHeight = outHeight;
            preserveRatio = true;
            cropData.height = outHeight * cropData.width / outWidth;
        }
        this._cropImage.setCropData(cropData, preserveRatio);
    },

    _enableDisableFields: function()
    {
        var dim = this.dimensions[this._dimensionField.getValue()];
        this._widthField.setDisabled(!(dim && dim.width == 'user'));
        this._heightField.setDisabled(!(dim && dim.height == 'user'));
    }
});

Ext.reg('kwc.image.dimensionwindow', Kwc.Abstract.Image.DimensionWindow);
<|endoftext|>


<commit_before>'use strict';

var log = log4javascript.getLogger("periscopeController-logger");

angular.module('uluwatuControllers').controller('periscopeController', ['$scope', '$rootScope', '$filter', 'PeriscopeCluster', 'MetricAlert',
    'TimeAlert', 'ScalingPolicy', 'Cluster', 'PeriscopeClusterState', 'PeriscopeClusterScalingConfiguration', 'MetricDefinitions', 'PeriscopeClusterScalingHistory', 'ErrorHandler',
    function($scope, $rootScope, $filter, PeriscopeCluster, MetricAlert, TimeAlert, ScalingPolicy, Cluster, PeriscopeClusterState,
        PeriscopeClusterScalingConfiguration, MetricDefinitions, PeriscopeClusterScalingHistory, ErrorHandler) {
        $rootScope.periscopeClusters = PeriscopeCluster.query();
        $scope.alerts = [];
        $scope.policies = {};
        $scope.scalingConfiguration = {};
        $scope.scalingAction = {};
        $scope.alert = {};
        $scope.scalingHistory = {};
        $scope.metricBasedAlarm = true;
        $scope.timeBasedAlarm = false;
        $scope.actPeriscopeCluster = undefined;
        $scope.alertDefinitions = [];
        resetAlarmForms();
        resetScalingActionForm();

        $rootScope.$watch('activeCluster', function(uluCluster, oldUluCluster) {
            if (uluCluster.cluster != undefined && uluCluster.cluster.ambariServerIp != undefined) {
                var periCluster = selectPeriscopeClusterByAmbariIp(uluCluster.cluster.ambariServerIp);
                if (isSelectedUluClusterEqualsPeriClusterAndRunning(periCluster)) {
                    setActivePeriClusterWithResources(periCluster);
                } else {
                    disableAutoScalingPolicies();
                }
            } else {
                disableAutoScalingPolicies();
            }
        }, false);

        $rootScope.$watch("activeCluster.cluster.status == 'AVAILABLE' && activeCluster.status == 'AVAILABLE'", function(newValue, oldValue) {
            if ($rootScope.activeCluster.cluster != undefined && $rootScope.activeCluster.cluster.ambariServerIp != undefined) {
                var periCluster = selectPeriscopeClusterByAmbariIp($rootScope.activeCluster.cluster.ambariServerIp);
                if (newValue && !oldValue && isSelectedUluClusterEqualsPeriClusterAndRunning(periCluster)) {
                    setActivePeriClusterWithResources(periCluster);
                }
            }
        });

        function isSelectedUluClusterEqualsPeriClusterAndRunning(periCluster) {
            return periCluster != undefined && $rootScope.activeCluster.cluster.ambariServerIp != undefined && $rootScope.activeCluster.cluster.ambariServerIp == periCluster.host && periCluster.state == 'RUNNING';
        }

        function setActivePeriClusterWithResources(periscopeCluster) {
            $scope.actPeriscopeCluster = periscopeCluster;
            $scope.autoScalingSLAPoliciesEnabled = true;
            if ($rootScope.activeCluster.cluster.status == 'AVAILABLE' && $rootScope.activeCluster.status == 'AVAILABLE') {
                getAlertDefinitions(periscopeCluster.id);
                getAlarms(periscopeCluster.id);
                getScalingConfigurations(periscopeCluster.id);
                getScalingHistory(periscopeCluster.id);
                getScalingPolicies(periscopeCluster.id);
            }
        }

        function disableAutoScalingPolicies() {
            $scope.actPeriscopeCluster = undefined;
            $scope.autoScalingSLAPoliciesEnabled = false;
        }

        function getAlertDefinitions(id) {
            $scope.alertDefinitions = [];
            MetricDefinitions.query({
                id: id
            }, function(success) {
                success.forEach(function(el) {
                    $scope.alertDefinitions.push(el);
                });
            });
        }

        function getAlarms(id) {
            $scope.alerts = [];
            MetricAlert.query({
                id: id
            }, function(success) {
                success.forEach(function(el) {
                    $scope.alerts.push(el);
                });
            });
            TimeAlert.query({
                id: id
            }, function(success) {
                success.forEach(function(el) {
                    $scope.alerts.push(el);
                });
            });
        }

        function getScalingConfigurations(id) {
            PeriscopeClusterScalingConfiguration.get({
                id: id
            }, function(success) {
                $scope.scalingConfiguration = success;
            });
        }

        function getScalingHistory(id) {
            PeriscopeClusterScalingHistory.query({
                id: id
            }, function(success) {
                angular.forEach(success, function(item) {
                    item.eventTimestampAsFloat = item.timestamp;
                    item.timestamp = new Date(item.timestamp).toLocaleString();
                });
                $scope.scalingHistory = success;
                $scope.pagination = {
                    currentPage: 1,
                    itemsPerPage: 10,
                    totalItems: $scope.scalingHistory.length
                }
            }, function(error) {
                console.log(error);
            });
        }

        $scope.$watch('scalingHistory', function() {
            if ($scope.scalingHistory != null) {
                paginateScalingHistory();
            }
        });

        $scope.$watch('pagination.currentPage + pagination.itemsPerPage', function() {
            if ($scope.scalingHistory != null) {
                paginateScalingHistory();
            }
        });

        function paginateScalingHistory() {
            if ($scope.pagination != null && $scope.scalingHistory.length > 0) {
                $scope.pagination.totalItems = $scope.scalingHistory.length;
                var begin = (($scope.pagination.currentPage - 1) * $scope.pagination.itemsPerPage),
                    end = begin + $scope.pagination.itemsPerPage;
                $scope.filteredScalingHistory = $scope.scalingHistory.slice(begin, end);
            } else {
                $scope.filteredScalingHistory = [];
            }
        }

        function getScalingPolicies(id) {
            ScalingPolicy.query({
                id: id
            }, function(policies) {
                $scope.policies = policies;
                resetScalingActionForm();
            });
        }

        $scope.enableAutoScaling = function() {
            var uluCluster = $rootScope.activeCluster;
            var periCluster = $filter('filter')($rootScope.periscopeClusters, function(value, index) {
                return value.stackId == uluCluster.id;
            }, true)[0];
            if (periCluster == undefined) {
                createPeriscopeCluster(uluCluster);
            } else if (periCluster.state == 'SUSPENDED') {
                startPeriscopeCluster(uluCluster);
            }
        }

        $scope.disableAutoScaling = function() {
            var uluCluster = $rootScope.activeCluster;
            var periCluster = $filter('filter')($rootScope.periscopeClusters, function(value, index) {
                return value.stackId == uluCluster.id;
            }, true)[0];
            var periscopeClusterStatus = {
                'state': 'SUSPENDED'
            };
            PeriscopeClusterState.save({
                id: periCluster.id
            }, periscopeClusterStatus, function(success) {
                periCluster.state = 'SUSPENDED';
                disableAutoScalingPolicies();
            }, function(error) {
                $scope.showError($rootScope.msg.peri_cluster_update_failed + ": " + ErrorHandler.handleError(error));
            });
        }

        $scope.activateMetricAlertCreationForm = function(isMetricAlert) {
            $scope.metricBasedAlarm = isMetricAlert;
            $scope.timeBasedAlarm = !isMetricAlert;
            resetAlarmForms();
        }

        $scope.createAlert = function() {
            if ($scope.actPeriscopeCluster != undefined) {
                var periClusterId = $scope.actPeriscopeCluster.id;
                if ($scope.metricBasedAlarm) {
                    MetricAlert.save({
                        id: periClusterId
                    }, $scope.alert, createAlarmSuccessHandler, createAlarmErrorHandler);
                } else {
                    TimeAlert.save({
                        id: periClusterId
                    }, $scope.alert, createAlarmSuccessHandler, createAlarmErrorHandler);
                }
            }
        }

        function createAlarmSuccessHandler(success) {
            $scope.alerts.push(success);
            $scope.metricBasedAlertForm.$setPristine();
            $scope.timeBasedAlertForm.$setPristine();
            resetAlarmForms();
            angular.element(document.querySelector('#panel-create-periscope-alert-btn')).click();
        }

        function createAlarmErrorHandler(error) {
            $scope.showErrorMessage($rootScope.msg.alarm_creation_failed + ": " + ErrorHandler.handleError(error));
        }

        function resetAlarmForms() {
            $scope.alert = {}
            if ($scope.timeBasedAlarm) {
                $scope.alert.timeZone = 'Etc/GMT';
            }
        }

        $scope.deleteAlarm = function(alert) {
            if ($scope.actPeriscopeCluster != undefined) {
                if (alert.alertDefinition != undefined) {
                    MetricAlert.delete({
                        id: $scope.actPeriscopeCluster.id,
                        alertId: alert.id
                    }, function(success) {
                        deleteAlarmSuccessHandler(success, alert, $scope.actPeriscopeCluster.id)
                    }, deleteAlarmErrorHandler);
                } else {
                    TimeAlert.delete({
                        id: $scope.actPeriscopeCluster.id,
                        alertId: alert.id
                    }, function(success) {
                        deleteAlarmSuccessHandler(success, alert, $scope.actPeriscopeCluster.id)
                    }, deleteAlarmErrorHandler);
                }
            }
        }

        function deleteAlarmSuccessHandler(success, alarm, periClusterId) {
            $scope.alerts = $filter('filter')($scope.alerts, function(value, index) {
                return value.id != alarm.id;
            }, true);
            getScalingPolicies(periClusterId);
        }

        function deleteAlarmErrorHandler(error) {
            $scope.showErrorMessage($rootScope.msg.alarm_delete_failed + ": " + ErrorHandler.handleError(error));
        }

        function selectPeriscopeClusterByAmbariIp(ambariServerIp) {
            var periCluster = undefined;
            var periClusters = $filter('filter')($rootScope.periscopeClusters, function(value, index) {
                return value.host == ambariServerIp;
            }, true);
            if (periClusters != undefined && periClusters.length > 0) {
                periCluster = periClusters[0];
            }
            return periCluster;
        }

        $scope.updateScalingConfiguration = function() {
            if ($scope.actPeriscopeCluster != undefined) {
                PeriscopeClusterScalingConfiguration.save({
                    id: $scope.actPeriscopeCluster.id
                }, $scope.scalingConfiguration, function(success) {
                    $scope.scalingConfiguration = success;
                }, function(error) {
                    $scope.showErrorMessage($rootScope.msg.peri_cluster_update_failed + ": " + ErrorHandler.handleError(error));
                });
            }
        }

        $scope.createPolicy = function() {
            if ($scope.actPeriscopeCluster != undefined) {
                ScalingPolicy.save({
                    id: $scope.actPeriscopeCluster.id
                }, $scope.scalingAction.policy, function(success) {
                    angular.element(document.querySelector('#create-policy-collapse-btn')).click();
                    getScalingPolicies($scope.actPeriscopeCluster.id);
                    $scope.policyForm.$setPristine();
                    resetScalingActionForm();
                });
            }
        }

        function resetScalingActionForm() {
            $scope.scalingAction = {};
            $scope.scalingAction.policy = {};
            $scope.scalingAction.policy.adjustmentType = "NODE_COUNT";
        }

        $scope.deletePolicy = function(policy) {
            if ($scope.actPeriscopeCluster != undefined) {
                ScalingPolicy.delete({
                    id: $scope.actPeriscopeCluster.id,
                    policyId: policy.id
                }, function(success) {
                    $scope.policies = $filter('filter')($scope.policies, function(value, index) {
                        return value.id != policy.id;
                    }, true);
                }, function(error) {
                    $scope.showErrorMessage($rootScope.msg.scaling_policy_delete_failed + ": " + ErrorHandler.handleError(error));
                });
            }
        }

        $scope.$on('DELETE_PERISCOPE_CLUSTER', function(event, stackId) {
            var periCluster = $filter('filter')($rootScope.periscopeClusters, function(value, index) {
                return value.stackId == stackId;
            }, true)[0];
            if (periCluster != undefined) {
                PeriscopeCluster.delete({
                    id: periCluster.id
                }, function(success) {
                    $rootScope.periscopeClusters = $filter('filter')($rootScope.periscopeClusters, function(value, index) {
                        return value.id != periCluster.id;
                    });
                }, function(error) {
                    $scope.showErrorMessage($rootScope.msg.peri_cluster_delete_failed + ": " + ErrorHandler.handleError(error));
                });
            }
        });

        $scope.$on('START_PERISCOPE_CLUSTER', function(event, uluwatuCluster, message) {
            if (message.indexOf("Cluster started successfully") > -1) {
                startPeriscopeCluster(uluwatuCluster);
            }
        });

        function startPeriscopeCluster(uluCluster) {
            Cluster.get({
                id: uluCluster.id
            }, function(cluster) {
                if (cluster.status == 'AVAILABLE') {
                    var periCluster = $filter('filter')($rootScope.periscopeClusters, function(value, index) {
                        return value.stackId == uluCluster.id;
                    }, true)[0];
                    if (periCluster != undefined) {
                        //update ambari ip after start
                        var ambariJson = createAmbariJsonFromUluwatuCluster(uluCluster);
                        PeriscopeCluster.update({
                            id: periCluster.id
                        }, ambariJson, function(success) {
                            periCluster.host = uluCluster.cluster.ambariServerIp;
                            //set state to RUNNING
                            var periscopeClusterStatus = {
                                'state': 'RUNNING'
                            };
                            PeriscopeClusterState.save({
                                id: periCluster.id
                            }, periscopeClusterStatus, function(success) {
                                periCluster.state = 'RUNNING';
                                if (isSelectedUluClusterEqualsPeriClusterAndRunning(periCluster)) {
                                    setActivePeriClusterWithResources(periCluster);
                                }
                            }, function(error) {
                                $scope.showErrorMessage($rootScope.msg.peri_cluster_start_failed + ": " + ErrorHandler.handleError(error));
                            });

                        }, function(error) {
                            $scope.showErrorMessage($rootScope.msg.peri_cluster_start_failed + ": " + ErrorHandler.handleError(error));
                        });
                    }
                }
            });
        }

        function createPeriscopeCluster(uluCluster) {
            Cluster.get({
                id: uluCluster.id
            }, function(cluster) {
                if (cluster.status == 'AVAILABLE') {
                    var ambariJson = createAmbariJsonFromUluwatuCluster(uluCluster);
                    PeriscopeCluster.save(ambariJson, function(periCluster) {
                        $rootScope.periscopeClusters.push(periCluster);
                        var periCluster = selectPeriscopeClusterByAmbariIp(uluCluster.cluster.ambariServerIp);
                        if (isSelectedUluClusterEqualsPeriClusterAndRunning(periCluster)) {
                            setActivePeriClusterWithResources(periCluster);
                        }
                    }, function(error) {
                        $scope.showErrorMessage($rootScope.msg.peri_cluster_creation_failed + ": " + ErrorHandler.handleError(error));
                    });
                } else {
                    $scope.showWarningMessage($rootScope.msg.cluster_not_available_yet);
                }
            }, function(error) {
                $scope.showWarningMessage($rootScope.msg.cluster_not_available_yet);
            });
        }

        $scope.timeZoneOrderGetter = function(mapEntry) {
            var result = 0;
            if (mapEntry.key != undefined && mapEntry.key != 'Etc/GMT') {
                result = parseInt(mapEntry.key.replace("Etc/GMT", ""));
            }
            return result;
        }

        function createAmbariJsonFromUluwatuCluster(uluCluster) {
            return {
                'host': uluCluster.cluster.ambariServerIp,
                'port': uluCluster.gatewayPort,
                'user': uluCluster.cluster.userName,
                'pass': uluCluster.cluster.password
            };
        }
    }
]);<commit_msg>CLOUD-59184 avoid duplicated alarmas<commit_after>'use strict';

var log = log4javascript.getLogger("periscopeController-logger");

angular.module('uluwatuControllers').controller('periscopeController', ['$scope', '$rootScope', '$filter', 'PeriscopeCluster', 'MetricAlert',
    'TimeAlert', 'ScalingPolicy', 'Cluster', 'PeriscopeClusterState', 'PeriscopeClusterScalingConfiguration', 'MetricDefinitions', 'PeriscopeClusterScalingHistory', 'ErrorHandler',
    function($scope, $rootScope, $filter, PeriscopeCluster, MetricAlert, TimeAlert, ScalingPolicy, Cluster, PeriscopeClusterState,
        PeriscopeClusterScalingConfiguration, MetricDefinitions, PeriscopeClusterScalingHistory, ErrorHandler) {
        $rootScope.periscopeClusters = PeriscopeCluster.query();
        $scope.alerts = [];
        $scope.policies = {};
        $scope.scalingConfiguration = {};
        $scope.scalingAction = {};
        $scope.alert = {};
        $scope.scalingHistory = {};
        $scope.metricBasedAlarm = true;
        $scope.timeBasedAlarm = false;
        $scope.actPeriscopeCluster = undefined;
        $scope.alertDefinitions = [];
        resetAlarmForms();
        resetScalingActionForm();

        $rootScope.$watch("activeCluster || activeCluster.cluster.status == 'AVAILABLE' && activeCluster.status == 'AVAILABLE'", function(uluCluster, oldUluCluster) {
            if (uluCluster.cluster != undefined && uluCluster.cluster.ambariServerIp != undefined) {
                var periCluster = selectPeriscopeClusterByAmbariIp(uluCluster.cluster.ambariServerIp);
                if (isSelectedUluClusterEqualsPeriClusterAndRunning(periCluster)) {
                    setActivePeriClusterWithResources(periCluster);
                } else {
                    disableAutoScalingPolicies();
                }
            } else {
                disableAutoScalingPolicies();
            }
        }, false);

        function isSelectedUluClusterEqualsPeriClusterAndRunning(periCluster) {
            return periCluster != undefined && $rootScope.activeCluster.cluster.ambariServerIp != undefined && $rootScope.activeCluster.cluster.ambariServerIp == periCluster.host && periCluster.state == 'RUNNING';
        }

        function setActivePeriClusterWithResources(periscopeCluster) {
            $scope.actPeriscopeCluster = periscopeCluster;
            $scope.autoScalingSLAPoliciesEnabled = true;
            if ($rootScope.activeCluster.cluster.status == 'AVAILABLE' && $rootScope.activeCluster.status == 'AVAILABLE') {
                getAlertDefinitions(periscopeCluster.id);
                getAlarms(periscopeCluster.id);
                getScalingConfigurations(periscopeCluster.id);
                getScalingHistory(periscopeCluster.id);
                getScalingPolicies(periscopeCluster.id);
            }
        }

        function disableAutoScalingPolicies() {
            $scope.actPeriscopeCluster = undefined;
            $scope.autoScalingSLAPoliciesEnabled = false;
        }

        function getAlertDefinitions(id) {
            $scope.alertDefinitions = [];
            MetricDefinitions.query({
                id: id
            }, function(success) {
                success.forEach(function(el) {
                    $scope.alertDefinitions.push(el);
                });
            });
        }

        function getAlarms(id) {
            $scope.alerts = [];
            MetricAlert.query({
                id: id
            }, function(success) {
                success.forEach(function(el) {
                    $scope.alerts.push(el);
                });
            });
            TimeAlert.query({
                id: id
            }, function(success) {
                success.forEach(function(el) {
                    $scope.alerts.push(el);
                });
            });
        }

        function getScalingConfigurations(id) {
            PeriscopeClusterScalingConfiguration.get({
                id: id
            }, function(success) {
                $scope.scalingConfiguration = success;
            });
        }

        function getScalingHistory(id) {
            PeriscopeClusterScalingHistory.query({
                id: id
            }, function(success) {
                angular.forEach(success, function(item) {
                    item.eventTimestampAsFloat = item.timestamp;
                    item.timestamp = new Date(item.timestamp).toLocaleString();
                });
                $scope.scalingHistory = success;
                $scope.pagination = {
                    currentPage: 1,
                    itemsPerPage: 10,
                    totalItems: $scope.scalingHistory.length
                }
            }, function(error) {
                console.log(error);
            });
        }

        $scope.$watch('scalingHistory', function() {
            if ($scope.scalingHistory != null) {
                paginateScalingHistory();
            }
        });

        $scope.$watch('pagination.currentPage + pagination.itemsPerPage', function() {
            if ($scope.scalingHistory != null) {
                paginateScalingHistory();
            }
        });

        function paginateScalingHistory() {
            if ($scope.pagination != null && $scope.scalingHistory.length > 0) {
                $scope.pagination.totalItems = $scope.scalingHistory.length;
                var begin = (($scope.pagination.currentPage - 1) * $scope.pagination.itemsPerPage),
                    end = begin + $scope.pagination.itemsPerPage;
                $scope.filteredScalingHistory = $scope.scalingHistory.slice(begin, end);
            } else {
                $scope.filteredScalingHistory = [];
            }
        }

        function getScalingPolicies(id) {
            ScalingPolicy.query({
                id: id
            }, function(policies) {
                $scope.policies = policies;
                resetScalingActionForm();
            });
        }

        $scope.enableAutoScaling = function() {
            var uluCluster = $rootScope.activeCluster;
            var periCluster = $filter('filter')($rootScope.periscopeClusters, function(value, index) {
                return value.stackId == uluCluster.id;
            }, true)[0];
            if (periCluster == undefined) {
                createPeriscopeCluster(uluCluster);
            } else if (periCluster.state == 'SUSPENDED') {
                startPeriscopeCluster(uluCluster);
            }
        }

        $scope.disableAutoScaling = function() {
            var uluCluster = $rootScope.activeCluster;
            var periCluster = $filter('filter')($rootScope.periscopeClusters, function(value, index) {
                return value.stackId == uluCluster.id;
            }, true)[0];
            var periscopeClusterStatus = {
                'state': 'SUSPENDED'
            };
            PeriscopeClusterState.save({
                id: periCluster.id
            }, periscopeClusterStatus, function(success) {
                periCluster.state = 'SUSPENDED';
                disableAutoScalingPolicies();
            }, function(error) {
                $scope.showError($rootScope.msg.peri_cluster_update_failed + ": " + ErrorHandler.handleError(error));
            });
        }

        $scope.activateMetricAlertCreationForm = function(isMetricAlert) {
            $scope.metricBasedAlarm = isMetricAlert;
            $scope.timeBasedAlarm = !isMetricAlert;
            resetAlarmForms();
        }

        $scope.createAlert = function() {
            if ($scope.actPeriscopeCluster != undefined) {
                var periClusterId = $scope.actPeriscopeCluster.id;
                if ($scope.metricBasedAlarm) {
                    MetricAlert.save({
                        id: periClusterId
                    }, $scope.alert, createAlarmSuccessHandler, createAlarmErrorHandler);
                } else {
                    TimeAlert.save({
                        id: periClusterId
                    }, $scope.alert, createAlarmSuccessHandler, createAlarmErrorHandler);
                }
            }
        }

        function createAlarmSuccessHandler(success) {
            $scope.alerts.push(success);
            $scope.metricBasedAlertForm.$setPristine();
            $scope.timeBasedAlertForm.$setPristine();
            resetAlarmForms();
            angular.element(document.querySelector('#panel-create-periscope-alert-btn')).click();
        }

        function createAlarmErrorHandler(error) {
            $scope.showErrorMessage($rootScope.msg.alarm_creation_failed + ": " + ErrorHandler.handleError(error));
        }

        function resetAlarmForms() {
            $scope.alert = {}
            if ($scope.timeBasedAlarm) {
                $scope.alert.timeZone = 'Etc/GMT';
            }
        }

        $scope.deleteAlarm = function(alert) {
            if ($scope.actPeriscopeCluster != undefined) {
                if (alert.alertDefinition != undefined) {
                    MetricAlert.delete({
                        id: $scope.actPeriscopeCluster.id,
                        alertId: alert.id
                    }, function(success) {
                        deleteAlarmSuccessHandler(success, alert, $scope.actPeriscopeCluster.id)
                    }, deleteAlarmErrorHandler);
                } else {
                    TimeAlert.delete({
                        id: $scope.actPeriscopeCluster.id,
                        alertId: alert.id
                    }, function(success) {
                        deleteAlarmSuccessHandler(success, alert, $scope.actPeriscopeCluster.id)
                    }, deleteAlarmErrorHandler);
                }
            }
        }

        function deleteAlarmSuccessHandler(success, alarm, periClusterId) {
            $scope.alerts = $filter('filter')($scope.alerts, function(value, index) {
                return value.id != alarm.id;
            }, true);
            getScalingPolicies(periClusterId);
        }

        function deleteAlarmErrorHandler(error) {
            $scope.showErrorMessage($rootScope.msg.alarm_delete_failed + ": " + ErrorHandler.handleError(error));
        }

        function selectPeriscopeClusterByAmbariIp(ambariServerIp) {
            var periCluster = undefined;
            var periClusters = $filter('filter')($rootScope.periscopeClusters, function(value, index) {
                return value.host == ambariServerIp;
            }, true);
            if (periClusters != undefined && periClusters.length > 0) {
                periCluster = periClusters[0];
            }
            return periCluster;
        }

        $scope.updateScalingConfiguration = function() {
            if ($scope.actPeriscopeCluster != undefined) {
                PeriscopeClusterScalingConfiguration.save({
                    id: $scope.actPeriscopeCluster.id
                }, $scope.scalingConfiguration, function(success) {
                    $scope.scalingConfiguration = success;
                }, function(error) {
                    $scope.showErrorMessage($rootScope.msg.peri_cluster_update_failed + ": " + ErrorHandler.handleError(error));
                });
            }
        }

        $scope.createPolicy = function() {
            if ($scope.actPeriscopeCluster != undefined) {
                ScalingPolicy.save({
                    id: $scope.actPeriscopeCluster.id
                }, $scope.scalingAction.policy, function(success) {
                    angular.element(document.querySelector('#create-policy-collapse-btn')).click();
                    getScalingPolicies($scope.actPeriscopeCluster.id);
                    $scope.policyForm.$setPristine();
                    resetScalingActionForm();
                });
            }
        }

        function resetScalingActionForm() {
            $scope.scalingAction = {};
            $scope.scalingAction.policy = {};
            $scope.scalingAction.policy.adjustmentType = "NODE_COUNT";
        }

        $scope.deletePolicy = function(policy) {
            if ($scope.actPeriscopeCluster != undefined) {
                ScalingPolicy.delete({
                    id: $scope.actPeriscopeCluster.id,
                    policyId: policy.id
                }, function(success) {
                    $scope.policies = $filter('filter')($scope.policies, function(value, index) {
                        return value.id != policy.id;
                    }, true);
                }, function(error) {
                    $scope.showErrorMessage($rootScope.msg.scaling_policy_delete_failed + ": " + ErrorHandler.handleError(error));
                });
            }
        }

        $scope.$on('DELETE_PERISCOPE_CLUSTER', function(event, stackId) {
            var periCluster = $filter('filter')($rootScope.periscopeClusters, function(value, index) {
                return value.stackId == stackId;
            }, true)[0];
            if (periCluster != undefined) {
                PeriscopeCluster.delete({
                    id: periCluster.id
                }, function(success) {
                    $rootScope.periscopeClusters = $filter('filter')($rootScope.periscopeClusters, function(value, index) {
                        return value.id != periCluster.id;
                    });
                }, function(error) {
                    $scope.showErrorMessage($rootScope.msg.peri_cluster_delete_failed + ": " + ErrorHandler.handleError(error));
                });
            }
        });

        $scope.$on('START_PERISCOPE_CLUSTER', function(event, uluwatuCluster, message) {
            if (message.indexOf("Cluster started successfully") > -1) {
                startPeriscopeCluster(uluwatuCluster);
            }
        });

        function startPeriscopeCluster(uluCluster) {
            Cluster.get({
                id: uluCluster.id
            }, function(cluster) {
                if (cluster.status == 'AVAILABLE') {
                    var periCluster = $filter('filter')($rootScope.periscopeClusters, function(value, index) {
                        return value.stackId == uluCluster.id;
                    }, true)[0];
                    if (periCluster != undefined) {
                        //update ambari ip after start
                        var ambariJson = createAmbariJsonFromUluwatuCluster(uluCluster);
                        PeriscopeCluster.update({
                            id: periCluster.id
                        }, ambariJson, function(success) {
                            periCluster.host = uluCluster.cluster.ambariServerIp;
                            //set state to RUNNING
                            var periscopeClusterStatus = {
                                'state': 'RUNNING'
                            };
                            PeriscopeClusterState.save({
                                id: periCluster.id
                            }, periscopeClusterStatus, function(success) {
                                periCluster.state = 'RUNNING';
                                if (isSelectedUluClusterEqualsPeriClusterAndRunning(periCluster)) {
                                    setActivePeriClusterWithResources(periCluster);
                                }
                            }, function(error) {
                                $scope.showErrorMessage($rootScope.msg.peri_cluster_start_failed + ": " + ErrorHandler.handleError(error));
                            });

                        }, function(error) {
                            $scope.showErrorMessage($rootScope.msg.peri_cluster_start_failed + ": " + ErrorHandler.handleError(error));
                        });
                    }
                }
            });
        }

        function createPeriscopeCluster(uluCluster) {
            Cluster.get({
                id: uluCluster.id
            }, function(cluster) {
                if (cluster.status == 'AVAILABLE') {
                    var ambariJson = createAmbariJsonFromUluwatuCluster(uluCluster);
                    PeriscopeCluster.save(ambariJson, function(periCluster) {
                        $rootScope.periscopeClusters.push(periCluster);
                        var periCluster = selectPeriscopeClusterByAmbariIp(uluCluster.cluster.ambariServerIp);
                        if (isSelectedUluClusterEqualsPeriClusterAndRunning(periCluster)) {
                            setActivePeriClusterWithResources(periCluster);
                        }
                    }, function(error) {
                        $scope.showErrorMessage($rootScope.msg.peri_cluster_creation_failed + ": " + ErrorHandler.handleError(error));
                    });
                } else {
                    $scope.showWarningMessage($rootScope.msg.cluster_not_available_yet);
                }
            }, function(error) {
                $scope.showWarningMessage($rootScope.msg.cluster_not_available_yet);
            });
        }

        $scope.timeZoneOrderGetter = function(mapEntry) {
            var result = 0;
            if (mapEntry.key != undefined && mapEntry.key != 'Etc/GMT') {
                result = parseInt(mapEntry.key.replace("Etc/GMT", ""));
            }
            return result;
        }

        function createAmbariJsonFromUluwatuCluster(uluCluster) {
            return {
                'host': uluCluster.cluster.ambariServerIp,
                'port': uluCluster.gatewayPort,
                'user': uluCluster.cluster.userName,
                'pass': uluCluster.cluster.password
            };
        }
    }
]);<|endoftext|>


<commit_before>/* Help configure the state-base ui.router */
(function() {
  'use strict';

  angular.module('blocks.router')
    .provider('routerHelper', routerHelperProvider);

  /** @ngInject */
  function routerHelperProvider($locationProvider, $stateProvider, $urlRouterProvider, $injector) {
    /* jshint validthis:true */
    var config = {
      docTitle: undefined,
      resolveAlways: {}
    };

    var provider = {
      configure: configure,
      $get: RouterHelper
    };

    $locationProvider.html5Mode(true);

    return provider;

    function configure(cfg) {
      angular.extend(config, cfg);
    }

    /** @ngInject */
    function RouterHelper($location, $rootScope, $state, logger) {
      var handlingStateChangeError = false;
      var hasOtherwise = false;
      var stateCounts = {
        errors: 0,
        changes: 0
      };

      var service = {
        configureStates: configureStates,
        getStates: getStates,
        stateCounts: stateCounts
      };

      init();

      return service;

      function configureStates(states, otherwisePath) {
        angular.forEach(states, buildState);

        if (otherwisePath && !hasOtherwise) {
          hasOtherwise = true;
          $urlRouterProvider.otherwise(otherwisePath);
        }

        function buildState(stateConfig, state) {
          stateConfig.resolve = angular.extend(stateConfig.resolve || {}, config.resolveAlways);
          $stateProvider.state(state, stateConfig);
        }
      }

      function init() {
        // Route cancellation:
        // On routing error, go to the dashboard.
        // Provide an exit clause if it tries to do it twice.
        $rootScope.$on('$stateChangeError', handleRoutingErrors);
        $rootScope.$on('$stateChangeSuccess', updateTitle);
        // Hack in redirect to default children
        // Discussions: https://github.com/angular-ui/ui-router/issues/1235
        // https://github.com/angular-ui/ui-router/issues/27
        $rootScope.$on('$stateChangeStart', redirectTo);
      }

      function getStates() {
        return $state.get();
      }

      // Private

      function handleRoutingErrors(event, toState, toParams, fromState, fromParams, error) {
        var destination;
        var msg;

        if (handlingStateChangeError) {
          return;
        }
        stateCounts.errors++;
        handlingStateChangeError = true;
        destination = (toState && (toState.title ? __(toState.title) : (toState.name || toState.loadedTemplateUrl))) || 'unknown target';
        msg = 'Error routing to ' + destination + '. '
          + (error.data || '') + '.
' + (error.statusText || '')
          + ': ' + (error.status || '');
        logger.warning(msg, [toState]);
        $location.path('/');
      }

      function updateTitle(event, toState) {
        stateCounts.changes++;
        handlingStateChangeError = false;
        $rootScope.title = config.docTitle + ' ' + (toState.title ? __(toState.title) : ''); // data bind to <title>
      }

      function redirectTo(event, toState, toParams) {
        var redirect = toState.redirectTo;
        var newState;

        if (redirect) {
          if (angular.isString(redirect)) {
            event.preventDefault();
            $state.go(redirect, toParams);
          } else {
            newState = $injector.invoke(redirect, null, {toState: toState, toParams: toParams});
            if (newState) {
              if (angular.isString(newState)) {
                event.preventDefault();
                $state.go(newState);
              } else if (newState.state) {
                event.preventDefault();
                $state.go(newState.state, newState.params);
              }
            }
          }
        }
      }
    }
  }
})();
<commit_msg>Log the actual error on stateChangeError<commit_after>/* Help configure the state-base ui.router */
(function() {
  'use strict';

  angular.module('blocks.router')
    .provider('routerHelper', routerHelperProvider);

  /** @ngInject */
  function routerHelperProvider($locationProvider, $stateProvider, $urlRouterProvider, $injector) {
    /* jshint validthis:true */
    var config = {
      docTitle: undefined,
      resolveAlways: {}
    };

    var provider = {
      configure: configure,
      $get: RouterHelper
    };

    $locationProvider.html5Mode(true);

    return provider;

    function configure(cfg) {
      angular.extend(config, cfg);
    }

    /** @ngInject */
    function RouterHelper($location, $rootScope, $state, logger) {
      var handlingStateChangeError = false;
      var hasOtherwise = false;
      var stateCounts = {
        errors: 0,
        changes: 0
      };

      var service = {
        configureStates: configureStates,
        getStates: getStates,
        stateCounts: stateCounts
      };

      init();

      return service;

      function configureStates(states, otherwisePath) {
        angular.forEach(states, buildState);

        if (otherwisePath && !hasOtherwise) {
          hasOtherwise = true;
          $urlRouterProvider.otherwise(otherwisePath);
        }

        function buildState(stateConfig, state) {
          stateConfig.resolve = angular.extend(stateConfig.resolve || {}, config.resolveAlways);
          $stateProvider.state(state, stateConfig);
        }
      }

      function init() {
        // Route cancellation:
        // On routing error, go to the dashboard.
        // Provide an exit clause if it tries to do it twice.
        $rootScope.$on('$stateChangeError', handleRoutingErrors);
        $rootScope.$on('$stateChangeSuccess', updateTitle);
        // Hack in redirect to default children
        // Discussions: https://github.com/angular-ui/ui-router/issues/1235
        // https://github.com/angular-ui/ui-router/issues/27
        $rootScope.$on('$stateChangeStart', redirectTo);
      }

      function getStates() {
        return $state.get();
      }

      // Private

      function handleRoutingErrors(event, toState, toParams, fromState, fromParams, error) {
        var destination;
        var msg;

        if (handlingStateChangeError) {
          return;
        }
        stateCounts.errors++;
        handlingStateChangeError = true;
        destination = (toState && (toState.title ? __(toState.title) : (toState.name || toState.loadedTemplateUrl))) || 'unknown target';
        msg = 'Error routing to ' + destination + '. '
          + (error.data || '') + '.
' + (error.statusText || '')
          + ': ' + (error.status || '');
        logger.warning(msg, [toState, error]);
        $location.path('/');
      }

      function updateTitle(event, toState) {
        stateCounts.changes++;
        handlingStateChangeError = false;
        $rootScope.title = config.docTitle + ' ' + (toState.title ? __(toState.title) : ''); // data bind to <title>
      }

      function redirectTo(event, toState, toParams) {
        var redirect = toState.redirectTo;
        var newState;

        if (redirect) {
          if (angular.isString(redirect)) {
            event.preventDefault();
            $state.go(redirect, toParams);
          } else {
            newState = $injector.invoke(redirect, null, {toState: toState, toParams: toParams});
            if (newState) {
              if (angular.isString(newState)) {
                event.preventDefault();
                $state.go(newState);
              } else if (newState.state) {
                event.preventDefault();
                $state.go(newState.state, newState.params);
              }
            }
          }
        }
      }
    }
  }
})();
<|endoftext|>


<commit_before>if(typeof langs == "undefined") {
    var langs = {};
}

//Turkish language
langs.tr = {
    'ikaeasy_link': 'https://www.facebook.com/ikariam.easy',
    'movements':{
        all: 'hepsi',
        transport: 'transport',
        plunder: 'plunder',
        blockade: 'blockade',
        deployarmy: 'birimleri terhis et',
        deployfleet: 'deploy fleet',
        defend: 'savun',
        defend_port: 'limanı savun',
        occupy: 'işgal',
        trade: 'ticaret'
    },
    'char_day': 'd',
    'char_hour': 'h',
    'char_minute': 'm',
    'char_second': 's',
    'WillBeFullIn': 'Tamamlanması için:',
    'per_day': "Her gün",
    'per_week': "Her hafta",
    'per_month': "Her ay",
    'left': "Kalan",
    'hours': "saat",
    'days': "gün",
    'months': "ay",
    'years': "yıl",
    'MessagePlaceholder': "CTRL ye tıkla ve mesajı göndermek için Enter a tıkla",
    'ConfirmDowngrade': "Binayı yıkmak için onayla",
    'Circular_message': "Herkese mesaj gönder",
    'Ally_members': "ittifak",
    'Attack_All': "Hepsi",
    'Attack_Half': "Yarısı",
    'Attack_Nothing': "Hiçbiri",
    'Required': "Gerekli:",
    'Next_Level': "Sonraki Seviye: ",
    'Messages': "Mesajlar",
    'Agora': "Agora",
    'Treaty': "Antlaşma",
    'Alliance': "Board",
    'Transport': "Kaynakları taşı!",
    'Send_General_Log': "Send log to ally",
    'Send_General_Log_Header': "Attacks on alliance members",

    'options': {
        'transport': {
            'header': 'Transporting options type',
            'original': 'GameForge',
            'ikaeasy': 'IkaEasy'
        },
        'movement_tabs': {
            'header': 'Movement tabs',
            'enable': 'aktif',
            'disable': 'pasif'
        },
        'gold_per_hour': {
            'header': 'Gold сonsumption',
            'enable': 'aktif',
            'disable': 'pasif'
        },
        'island_ap': {
            'header': 'Action points on island view',
            'enable': 'akttif',
            'disable': 'pasif'
        },
        'development': {
            'overview': "IkaEasy ticari olmayan ve açık kaynak kodlu bir projedir. Yardım etmek ister misin? GitHub aracılığı ile katkıda bulunabilir, Facebook aracılığıyla ise hataları bildirebilir veya özellikleri önerebilirsiniz.
Ikariam Easy geliştirmek çok zaman alır, hafta sonları, iş çıkışları ve tabikide geceler. Eğer isterseniz bir teşekkür edebilir veya uyanık kalmam için bana bir kahve ısmarlayabilirsiniz :)

 Eklentiyi IkaEasy V2 ile değiştirip güncellemeleri daha erken alabilirsiniz!"
        }
    },

    'ikalogs': {
        'save_log': 'Save log',
        'analyze': 'Analyze',
        'each': 'Her seferinde',
        'help_bw': 'Seperate individual rounds with a comma, or a range of rounds with a dash.',

        'get_info': 'Getting data',
        'get_round': 'Getting log',
        'saving': 'Saving log',

        'saving_success': 'log başarıyla kaydedildi.',
        'open_report': 'Open log',

        'saving_failed': 'log kaydedilemedi',
        'repeat': 'Tekrar deneyin',

        'auth': {
            'not_logged': 'Ikalogs oturumunuz açık değil'
        },

        'types': {
            'full': 'Full log',
            'short': 'Short log',
            'last': 'Son raund',
            'each': 'Her N raund',
            'between': 'Specific raund'
        }
    },

    'Transporter': 'Nakliyat'
};
<commit_msg>little changes 2<commit_after>if(typeof langs == "undefined") {
    var langs = {};
}

//Turkish language
langs.tr = {
    'ikaeasy_link': 'http://ikariam-easy.com',
    'movements':{
        all: 'hepsi',
        transport: 'nakliye',
        plunder: 'yağma',
        blockade: 'abluka',
        deployarmy: 'birimleri terhis et',
        deployfleet: 'filoyu dağıt',
        defend: 'savun',
        defend_port: 'limanı savun',
        occupy: 'işgal',
        trade: 'ticaret'
    },
    'char_day': 'd',
    'char_hour': 'h',
    'char_minute': 'm',
    'char_second': 's',
    'WillBeFullIn': 'Tamamlanması için:',
    'per_day': "Her gün",
    'per_week': "Her hafta",
    'per_month': "Her ay",
    'left': "Kalan",
    'hours': "saat",
    'days': "gün",
    'months': "ay",
    'years': "yıl",
    'MessagePlaceholder': "CTRL ye tıkla ve mesajı göndermek için Enter a tıkla",
    'ConfirmDowngrade': "Binayı yıkmak için onayla",
    'Circular_message': "Herkese mesaj gönder",
    'Ally_members': "ittifak",
    'Attack_All': "Hepsi",
    'Attack_Half': "Yarısı",
    'Attack_Nothing': "Hiçbiri",
    'Required': "Gerekli:",
    'Next_Level': "Sonraki Seviye: ",
    'Messages': "Mesajlar",
    'Agora': "Agora",
    'Treaty': "Antlaşma",
    'Alliance': "Board",
    'Transport': "Kaynakları taşı!",
    'Send_General_Log': "İttifağa log gönder",
    'Send_General_Log_Header': "Attacks on alliance members",

    'options': {
        'transport': {
            'header': 'Nakliye taşıma tipi',
            'original': 'GameForge',
            'ikaeasy': 'IkaEasy'
        },
        'movement_tabs': {
            'header': 'Movement tabs',
            'enable': 'aktif',
            'disable': 'pasif'
        },
        'gold_per_hour': {
            'header': 'Altın Durumu',
            'enable': 'aktif',
            'disable': 'pasif'
        },
        'island_ap': {
            'header': 'Ada görünümünde Aksiyon Puanı',
            'enable': 'akttif',
            'disable': 'pasif'
        },
        'development': {
            'overview': "IkaEasy ticari olmayan ve açık kaynak kodlu bir projedir. Yardım etmek ister misin? GitHub aracılığı ile katkıda bulunabilir, Facebook aracılığıyla ise hataları bildirebilir veya özellikleri önerebilirsiniz.
Ikariam Easy geliştirmek çok zaman alır, hafta sonları, iş çıkışları ve tabikide geceler. Eğer isterseniz bir teşekkür edebilir veya uyanık kalmam için bana bir kahve ısmarlayabilirsiniz :)

 Eklentiyi IkaEasy V2 ile değiştirip güncellemeleri daha erken alabilirsiniz!"
        }
    },

    'ikalogs': {
        'save_log': 'Save log',
        'analyze': 'Analyze',
        'each': 'Her seferinde',
        'help_bw': 'Seperate individual rounds with a comma, or a range of rounds with a dash.',

        'get_info': 'Getting data',
        'get_round': 'Getting log',
        'saving': 'Saving log',

        'saving_success': 'log başarıyla kaydedildi.',
        'open_report': 'Open log',

        'saving_failed': 'log kaydedilemedi',
        'repeat': 'Tekrar deneyin',

        'auth': {
            'not_logged': 'Ikalogs oturumunuz açık değil'
        },

        'types': {
            'full': 'Full log',
            'short': 'Short log',
            'last': 'Son raund',
            'each': 'Her N raund',
            'between': 'Spesifik raund'
        }
    },

    'Transporter': 'Nakliyat'
};
<|endoftext|>


<commit_before>import intersect from './intersect';

/**
 * Appends a new point to the lasso
 *
 * @param {*} lasso the lasso in pixel space
 * @param {*} x the x coordinate in pixel space
 * @param {*} y the y coordinate in pixel space
 * @param {*} minDist the minimum distance, in pixels, that thenew point needs to be apart from the last point
 * @returns a new array containing the lasso with the new point
 */
export function lassoAppend(lasso, x, y, minDist = 5) {
  const last = lasso[lasso.length - 1];

  // Add point to lasso if distance to last point exceed minDist or its the first point
  if (last === undefined || Math.sqrt(((last[0] - x) ** 2) + ((last[1] - y) ** 2)) > minDist) {
    lasso.push([x, y]);

    return [...lasso];
  }

  return lasso;
}

/**
 * Generates a svg path command which draws a lasso
 *
 * @param {*} lasso the lasso in pixel space in the form [[x,y], [x,y], ...]
 * @returns the svg path command that draws the lasso
 */
export function lassoPath(lasso) {
  let svg = '';
  for (const [i, [x, y]] of lasso.entries()) {
    svg += i === 0
      ? `M ${x},${y} `
      : i === lasso.length - 1
        ? ' Z'
        : `L ${x},${y} `;
  }

  return svg;
}

/**
 * Inverts the lasso from pixel space to an array of vega scenegraph tuples
 *
 * @param {*} data the dataset
 * @param {*} pixelLasso the lasso in pixel space, [[x,y], [x,y], ...]
 *
 * @returns an array of vega scenegraph tuples
 */
export function intersectLasso(markname, pixelLasso) {
  const tuples = [];

  const bounds = {
    left: Number.MAX_SAFE_INTEGER,
    right: Number.MIN_SAFE_INTEGER,
    top: Number.MAX_SAFE_INTEGER,
    bottom: Number.MIN_SAFE_INTEGER
  };

  // Get bounding box around lasso
  for (const [px, py] of pixelLasso) {
    if (px < bounds.left) bounds.left = px;
    if (px > bounds.right) bounds.right = px;
    if (py < bounds.top) bounds.top = py;
    if (py > bounds.bottom) bounds.bottom = py;
  }

  const intersection = intersect([[bounds.left, bounds.top], [bounds.right, bounds.bottom]],
    { markname },
    this.context.dataflow.scenegraph().root);

  // Check every point against the lasso
  for (const tuple of intersection) {
    if (pointInPolygon([tuple.x, tuple.y], pixelLasso)) {
      tuples.push(tuple);
    }
  }

  return tuples;
}

/**
 * Performs a test if a point is inside a polygon based on the idea from
 * https://wrf.ecse.rpi.edu/Research/Short_Notes/pnpoly.html
 *
 * This method will not need the same start/end point since it wraps around the edges of the array
 *
 * @param {*} test a point to test against
 * @param {*} polygon a polygon in the form [[x,y], [x,y], ...]
 * @returns true if the point lies inside the polygon, false otherwise
 */
function pointInPolygon(test, polygon) {
  const [testx, testy] = test;
  var intersections = 0;

  for (var i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {
    const [prevX, prevY] = polygon[j];
    const [x, y] = polygon[i];

    // count intersections
    if (((y > testy) != (prevY > testy)) && (testx < (prevX - x) * (testy - y) / (prevY - y) + x)) {
      intersections++;
    }
  }

  // point is in polygon if intersection count is odd
  return intersections & 1;
}<commit_msg>Update packages/vega-functions/src/functions/lasso.js<commit_after>import intersect from './intersect';

/**
 * Appends a new point to the lasso
 *
 * @param {*} lasso the lasso in pixel space
 * @param {*} x the x coordinate in pixel space
 * @param {*} y the y coordinate in pixel space
 * @param {*} minDist the minimum distance, in pixels, that thenew point needs to be apart from the last point
 * @returns a new array containing the lasso with the new point
 */
export function lassoAppend(lasso, x, y, minDist = 5) {
  const last = lasso[lasso.length - 1];

  // Add point to lasso if distance to last point exceed minDist or its the first point
  if (last === undefined || Math.sqrt(((last[0] - x) ** 2) + ((last[1] - y) ** 2)) > minDist) {
    lasso.push([x, y]);

    return [...lasso];
  }

  return lasso;
}

/**
 * Generates a svg path command which draws a lasso
 *
 * @param {*} lasso the lasso in pixel space in the form [[x,y], [x,y], ...]
 * @returns the svg path command that draws the lasso
 */
export function lassoPath(lasso) {
  let svg = '';
  for (const [i, [x, y]] of lasso.entries()) {
    svg += i === 0
      ? `M ${x},${y} `
      : i === lasso.length - 1
        ? ' Z'
        : `L ${x},${y} `;
  }

  return svg;
}

/**
 * Inverts the lasso from pixel space to an array of vega scenegraph tuples
 *
 * @param {*} data the dataset
 * @param {*} pixelLasso the lasso in pixel space, [[x,y], [x,y], ...]
 *
 * @returns an array of vega scenegraph tuples
 */
export function intersectLasso(markname, pixelLasso) {

  const bounds = {
    left: Number.MAX_SAFE_INTEGER,
    right: Number.MIN_SAFE_INTEGER,
    top: Number.MAX_SAFE_INTEGER,
    bottom: Number.MIN_SAFE_INTEGER
  };

  // Get bounding box around lasso
  for (const [px, py] of pixelLasso) {
    if (px < bounds.left) bounds.left = px;
    if (px > bounds.right) bounds.right = px;
    if (py < bounds.top) bounds.top = py;
    if (py > bounds.bottom) bounds.bottom = py;
  }

  const intersection = intersect([[bounds.left, bounds.top], [bounds.right, bounds.bottom]],
    { markname },
    this.context.dataflow.scenegraph().root);

  // Check every point against the lasso
  for (const tuple of intersection) {
    if (pointInPolygon([tuple.x, tuple.y], pixelLasso)) {
      tuples.push(tuple);
    }
  }

  return tuples;
}

/**
 * Performs a test if a point is inside a polygon based on the idea from
 * https://wrf.ecse.rpi.edu/Research/Short_Notes/pnpoly.html
 *
 * This method will not need the same start/end point since it wraps around the edges of the array
 *
 * @param {*} test a point to test against
 * @param {*} polygon a polygon in the form [[x,y], [x,y], ...]
 * @returns true if the point lies inside the polygon, false otherwise
 */
function pointInPolygon(test, polygon) {
  const [testx, testy] = test;
  var intersections = 0;

  for (var i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {
    const [prevX, prevY] = polygon[j];
    const [x, y] = polygon[i];

    // count intersections
    if (((y > testy) != (prevY > testy)) && (testx < (prevX - x) * (testy - y) / (prevY - y) + x)) {
      intersections++;
    }
  }

  // point is in polygon if intersection count is odd
  return intersections & 1;
}<|endoftext|>


<commit_before>var start;
var end;
var range;

module("date range default behavior", {
  setup: resetRange
});

test("creates dange of three days", function() {
  equals(range.start, start);
  equals(range.end, end);
  equals(range.days(), 3);
  ok(!range.hasDate(new Date('09/9/2009')));
  ok(range.hasDate(new Date('09/10/2009')));
  ok(range.hasDate(new Date('09/11/2009')));
  ok(range.hasDate(new Date('09/12/2009')));
  ok(!range.hasDate(new Date('09/13/2009')));
});

test("range is movable", function() {
  range.shiftDays(2);
  equals(range.start.getDate(), 12);
  equals(range.end.getDate(), 12 + 2);
});

test("range is expandable", function() {
  range.expandTo(new Date('09/15/2009'));
  equals(range.days(), 6);
});

test("two ranges can do interception", function() {
  var range2 = new DateRange(new Date('09/11/2009'), new Date('09/19/2009'));
  equals(range.and(range2).days(), 2);
  range2 = new DateRange(new Date('09/16/2009'), new Date('09/19/2009'));
  equals(range.and(range2).days(), 0);
});

module("date range with time behavior", {
  setup: resetRange
});

test("date range can have times", function() {
  range.setTimes('10:00', '14:30');
  equals(range.days(), 2);
  equals(range.hours(), 4);
  equals(range.minutes(), 30);
  equals(range.toString(DATE_LOCALE_FI), "2 Päivää 4,5 tuntia");
  range.setTimes('17:00', '16:00');
  equals(range.days(), 1);
  equals(range.hours(), 23);
  equals(range.minutes(), 0);
});

test("one day range with start time after end time is not valid", function() {
  ok(range.isValid());
  range.start = new Date('09/13/2009');
  ok(!range.isValid());
  range.start = new Date('09/12/2009');
  ok(range.isValid());
  range.setTimes('15:00', '14:30');
  ok(!range.isValid());
  range.setTimes('15:00', '15:00');
  ok(range.isValid());
  range.setTimes('15:00', '15:30');
  ok(range.isValid());
});

function resetRange() {
  start = new Date('09/10/2009');
  end = new Date('09/12/2009');
  range = new DateRange(end, start);
}<commit_msg>fixed daterange test<commit_after>var start;
var end;
var range;

module("date range default behavior", {
  setup: resetRange
});

test("creates dange of three days", function() {
  equals(range.start, start);
  equals(range.end, end);
  equals(range.days(), 3);
  ok(!range.hasDate(new Date('09/9/2009')));
  ok(range.hasDate(new Date('09/10/2009')));
  ok(range.hasDate(new Date('09/11/2009')));
  ok(range.hasDate(new Date('09/12/2009')));
  ok(!range.hasDate(new Date('09/13/2009')));
});

test("range is movable", function() {
  range.shiftDays(2);
  equals(range.start.getDate(), 12);
  equals(range.end.getDate(), 12 + 2);
});

test("range is expandable", function() {
  range.expandTo(new Date('09/15/2009'));
  equals(range.days(), 6);
});

test("two ranges can do interception", function() {
  var range2 = new DateRange(new Date('09/11/2009'), new Date('09/19/2009'));
  equals(range.and(range2).days(), 2);
  range2 = new DateRange(new Date('09/16/2009'), new Date('09/19/2009'));
  equals(range.and(range2).days(), 0);
});

module("date range with time behavior", {
  setup: resetRange
});

test("date range can have times", function() {
  range.setTimes('10:00', '14:30');
  equals(range.days(), 2);
  equals(range.hours(), 4);
  equals(range.minutes(), 30);
  DATE_LOCALE_EN.init();
  equals(range.toString(), "2 Days 4,5 hours");
  range.setTimes('17:00', '16:00');
  equals(range.days(), 1);
  equals(range.hours(), 23);
  equals(range.minutes(), 0);
});

test("one day range with start time after end time is not valid", function() {
  ok(range.isValid());
  range.start = new Date('09/13/2009');
  ok(!range.isValid());
  range.start = new Date('09/12/2009');
  ok(range.isValid());
  range.setTimes('15:00', '14:30');
  ok(!range.isValid());
  range.setTimes('15:00', '15:00');
  ok(range.isValid());
  range.setTimes('15:00', '15:30');
  ok(range.isValid());
});

function resetRange() {
  start = new Date('09/10/2009');
  end = new Date('09/12/2009');
  range = new DateRange(end, start);
}<|endoftext|>