<commit_before>/*
This file is part of the Juju GUI, which lets users view and manage Juju
environments within a graphical interface (https://launchpad.net/juju-gui).
Copyright (C) 2017 Canonical Ltd.

This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License version 3, as published by
the Free Software Foundation.

This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranties of MERCHANTABILITY,
SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero
General Public License for more details.

You should have received a copy of the GNU Affero General Public License along
with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

'use strict';

YUI.add('account-payment-details-address', function() {

  juju.components.AccountPaymentDetailsAddress = React.createClass({
    displayName: 'AccountPaymentDetailsAddress',

    propTypes: {
      acl: React.PropTypes.object.isRequired,
      addAddress: React.PropTypes.func.isRequired,
      addNotification: React.PropTypes.func.isRequired,
      address: React.PropTypes.object.isRequired,
      close: React.PropTypes.func.isRequired,
      getCountries: React.PropTypes.func.isRequired,
      removeAddress: React.PropTypes.func.isRequired,
      showEdit: React.PropTypes.bool,
      updateAddress: React.PropTypes.func.isRequired,
      updated: React.PropTypes.func.isRequired,
      username: React.PropTypes.string.isRequired,
      validateForm: React.PropTypes.func.isRequired
    },

    getInitialState: function() {
      this.xhrs = [];
      return {};
    },

    componentWillUnmount: function() {
      this.xhrs.forEach((xhr) => {
        xhr && xhr.abort && xhr.abort();
      });
    },

    /**
      Update an address.

      @method _updateAddress
    */
    _updateAddress: function() {
      const valid = this.props.validateForm(['addressForm'], this.refs);;
      if (!valid) {
        return;
      }
      const address = this.refs.addressForm.getValue();
      const username = this.props.username;
      const xhr = this.props.updateAddress(
        username, this.props.address.id, address, error => {
          if (error) {
            const message = 'Could not update address';
            this.props.addNotification({
              title: message,
              message: `${message}: ${error}`,
              level: 'error'
            });
            console.error(message, error);
            return;
          }
          this.props.updated();
          this.props.close();
        });
      this.xhrs.push(xhr);
    },

    render: function() {
      const disabled = this.props.acl.isReadOnly();
      return (
        <juju.components.ExpandingRow
          classes={{
            'account-payment-details-address': true,
            'twelve-col': true
          }}
          clickable={false}
          expanded={this.props.showEdit}>
          <juju.components.AddressForm
            disabled={true}
            address={this.props.address}
            getCountries={this.props.getCountries} />

             <juju.components.AddressForm
               addNotification={this.props.addNotification}
               address={this.props.address}
               disabled={disabled}
               getCountries={this.props.getCountries}
               ref="addressForm"
               validateForm={this.props.validateForm} />

               <juju.components.GenericButton
                 action={this.props.close}
                 disabled={disabled}
                 type="inline-neutral"
                 title="Cancel" />
               <juju.components.GenericButton
                 action={this._updateAddress}
                 disabled={disabled}
                 type="inline-positive"
                 title="Update" />

        </juju.components.ExpandingRow>
      );
    }

  });

}, '', {
  requires: [
    'address-form',
    'expanding-row',
    'generic-button'
  ]
});
<commit_msg>Removed extra semicolon.<commit_after>/*
This file is part of the Juju GUI, which lets users view and manage Juju
environments within a graphical interface (https://launchpad.net/juju-gui).
Copyright (C) 2017 Canonical Ltd.

This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License version 3, as published by
the Free Software Foundation.

This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranties of MERCHANTABILITY,
SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero
General Public License for more details.

You should have received a copy of the GNU Affero General Public License along
with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

'use strict';

YUI.add('account-payment-details-address', function() {

  juju.components.AccountPaymentDetailsAddress = React.createClass({
    displayName: 'AccountPaymentDetailsAddress',

    propTypes: {
      acl: React.PropTypes.object.isRequired,
      addAddress: React.PropTypes.func.isRequired,
      addNotification: React.PropTypes.func.isRequired,
      address: React.PropTypes.object.isRequired,
      close: React.PropTypes.func.isRequired,
      getCountries: React.PropTypes.func.isRequired,
      removeAddress: React.PropTypes.func.isRequired,
      showEdit: React.PropTypes.bool,
      updateAddress: React.PropTypes.func.isRequired,
      updated: React.PropTypes.func.isRequired,
      username: React.PropTypes.string.isRequired,
      validateForm: React.PropTypes.func.isRequired
    },

    getInitialState: function() {
      this.xhrs = [];
      return {};
    },

    componentWillUnmount: function() {
      this.xhrs.forEach((xhr) => {
        xhr && xhr.abort && xhr.abort();
      });
    },

    /**
      Update an address.

      @method _updateAddress
    */
    _updateAddress: function() {
      const valid = this.props.validateForm(['addressForm'], this.refs);
      if (!valid) {
        return;
      }
      const address = this.refs.addressForm.getValue();
      const username = this.props.username;
      const xhr = this.props.updateAddress(
        username, this.props.address.id, address, error => {
          if (error) {
            const message = 'Could not update address';
            this.props.addNotification({
              title: message,
              message: `${message}: ${error}`,
              level: 'error'
            });
            console.error(message, error);
            return;
          }
          this.props.updated();
          this.props.close();
        });
      this.xhrs.push(xhr);
    },

    render: function() {
      const disabled = this.props.acl.isReadOnly();
      return (
        <juju.components.ExpandingRow
          classes={{
            'account-payment-details-address': true,
            'twelve-col': true
          }}
          clickable={false}
          expanded={this.props.showEdit}>
          <juju.components.AddressForm
            disabled={true}
            address={this.props.address}
            getCountries={this.props.getCountries} />

             <juju.components.AddressForm
               addNotification={this.props.addNotification}
               address={this.props.address}
               disabled={disabled}
               getCountries={this.props.getCountries}
               ref="addressForm"
               validateForm={this.props.validateForm} />

               <juju.components.GenericButton
                 action={this.props.close}
                 disabled={disabled}
                 type="inline-neutral"
                 title="Cancel" />
               <juju.components.GenericButton
                 action={this._updateAddress}
                 disabled={disabled}
                 type="inline-positive"
                 title="Update" />

        </juju.components.ExpandingRow>
      );
    }

  });

}, '', {
  requires: [
    'address-form',
    'expanding-row',
    'generic-button'
  ]
});
<|endoftext|>


<commit_before>

/**
 * @class Loads mno files and returns a PointcloudOctree
 * for a description of the mno binary file format, read mnoFileFormat.txt
 *
 * @author Markus Schuetz
 */
function POCLoader(){

}

/**
 * @return a point cloud octree with the root node data loaded.
 * loading of descendants happens asynchronously when they're needed
 *
 * @param file the xml mno file
 * @param loadingFinishedListener executed after loading the binary has been finished
 */
POCLoader.load = function load(file) {
	try{
		var pco = new PointcloudOctree();
		var xhr = new XMLHttpRequest();
		xhr.open('GET', file, false);
		xhr.send(null);
		if(xhr.status === 200 || xhr.status === 0){
			var fMno = JSON.parse(xhr.responseText);

			pco.octreeDir = file + "/../data";
			var pointAttributes = POCLoader.loadPointAttributes(fMno);
			pco.setPointAttributes(pointAttributes);

			{ // load Root
				var mRoot = new PointcloudOctreeNode("r", pco);
				var aabb = new AABB();
				aabb.setDimensionByMinMax(
						[ fMno.boundingBox.lx, fMno.boundingBox.ly, fMno.boundingBox.lz ],
						[ fMno.boundingBox.ux, fMno.boundingBox.uy, fMno.boundingBox.uz ]);
				mRoot.setAABB(aabb);
				mRoot.points = fMno.hierarchy[0][1];
				pco.rootNode = mRoot;
			}

			// load remaining hierarchy
			for( var i = 1; i < fMno.hierarchy.length; i++){
				var nodeName = fMno.hierarchy[i][0];
				var points = fMno.hierarchy[i][1];
				var mNode = new PointcloudOctreeNode(nodeName, pco);
				mNode.points = points;
				pco.rootNode.addChild(mNode);
				var childIndex = mNode.name.charAt(mNode.name.length-1);
				var childAABB = POCLoader.createChildAABB(mNode.parent.aabb, childIndex);
				mNode.setAABB(childAABB);
			}

		}

		var pcoNode = new PointcloudOctreeSceneNode(pco);
		return pcoNode;
	}catch(e){
//		Logger.error("loading failed: '" + file + "'");
//		Logger.error(e);
		console.log("loading failed: '" + file + "'");
		console.log(e);
	}
};

POCLoader.loadPointAttributes = function(mno){

	var fpa = mno.pointAttributes;
	var pa = new PointAttributes();

	for(var i = 0; i < fpa.length; i++){
		var pointAttribute = PointAttribute[fpa[i]];
		pa.add(pointAttribute);
	}

	return pa;
//	var fpa = mno.pointAttributes;
//	var pa = {
//		'numAttributes' : fpa.length,
//		'bytesPerPoint' : 0,
//		'attributes' : {}
//	};
//
//	for(var i = 0; i < fpa.length; i++){
//		var pointAttribute = PointAttributes[fpa[i]];
//		pa.attributes[i] = pointAttribute;
//		var bytes = pointAttribute.type.size * pointAttribute.numElements;
//		pa.bytesPerPoint += bytes;
//	}
//
//	return pa;
};

/**
 * creates an aabb that covers the area of the childnode at childIndex
 *
 * @param aabb aabb of the parent
 * @param childIndex index of the childs region
 * @returns {AABB}
 */
POCLoader.createChildAABB = function(aabb, childIndex){
	var min = aabb.objectSpaceMin;
	var max = aabb.objectSpaceMax;
	var caabb = new AABB();
	// (aabb.max - aabb.minPos) * 0.5
	var dHalfLength = V3.scale(V3.sub(max,min), 0.5);
	var xHalfLength = [ dHalfLength[0], 0, 0 ];
	var yHalfLength = [ 0, dHalfLength[1], 0 ];
	var zHalfLength = [ 0, 0, dHalfLength[2] ];

	{
		var cmin = min;
		// max = min + (aabb.max - aabb.min) * 0.5;
		var cmax = V3.add(min, dHalfLength);
		var caabb = new AABB();
		caabb.setDimensionByMinMax(cmin, cmax);
	}

	if (childIndex === 1) {
		var min = V3.add(caabb.min, zHalfLength);
		var max = V3.add(caabb.max, zHalfLength);
		caabb.setDimensionByMinMax(min, max);
		caabb.setColor([0.0, 0.0, 1.0, 1.0]);
	}else if (childIndex === 3) {
		var min = V3.add(V3.add(caabb.min, zHalfLength), yHalfLength);
		var max = V3.add(V3.add(caabb.max, zHalfLength), yHalfLength);
		caabb.setDimensionByMinMax(min, max);
		caabb.setColor([1.0, 1.0, 0.0, 1.0]);
	}else if (childIndex === 0) {
		caabb.setColor([1.0, 0.0, 0.0, 1.0]);
	}else if (childIndex === 2) {
		var min = V3.add(caabb.min, yHalfLength);
		var max = V3.add(caabb.max, yHalfLength);
		caabb.setDimensionByMinMax(min, max);
		caabb.setColor([0.0, 1.0, 0.0, 1.0]);
	}else if (childIndex === 5) {
		var min = V3.add(V3.add(caabb.min, zHalfLength), xHalfLength);
		var max = V3.add(V3.add(caabb.max, zHalfLength), xHalfLength);
		caabb.setDimensionByMinMax(min, max);
		caabb.setColor([1.0, 1.0, 1.0, 1.0]);
	}else if (childIndex === 7) {
		var min = V3.add(caabb.min, dHalfLength);
		var max = V3.add(caabb.max, dHalfLength);
		caabb.setDimensionByMinMax(min, max);
		caabb.setColor([0.0, 0.0, 0.0, 1.0]);
	}else if (childIndex === 4) {
		var min = V3.add(caabb.min, xHalfLength);
		var max = V3.add(caabb.max, xHalfLength);
		caabb.setDimensionByMinMax(min, max);
		caabb.setColor([1.0, 0.0, 1.0, 1.0]);
	}else if (childIndex === 6) {
		var min = V3.add(V3.add(caabb.min, xHalfLength), yHalfLength);
		var max = V3.add(V3.add(caabb.max, xHalfLength), yHalfLength);
		caabb.setDimensionByMinMax(min, max);
		caabb.setColor([0.0, 1.0, 1.0, 1.0]);
	}

	return caabb;
};

<commit_msg>fixed bug that occured with == to === replacement<commit_after>

/**
 * @class Loads mno files and returns a PointcloudOctree
 * for a description of the mno binary file format, read mnoFileFormat.txt
 *
 * @author Markus Schuetz
 */
function POCLoader(){

}

/**
 * @return a point cloud octree with the root node data loaded.
 * loading of descendants happens asynchronously when they're needed
 *
 * @param file the xml mno file
 * @param loadingFinishedListener executed after loading the binary has been finished
 */
POCLoader.load = function load(file) {
	try{
		var pco = new PointcloudOctree();
		var xhr = new XMLHttpRequest();
		xhr.open('GET', file, false);
		xhr.send(null);
		if(xhr.status === 200 || xhr.status === 0){
			var fMno = JSON.parse(xhr.responseText);

			pco.octreeDir = file + "/../data";
			var pointAttributes = POCLoader.loadPointAttributes(fMno);
			pco.setPointAttributes(pointAttributes);

			{ // load Root
				var mRoot = new PointcloudOctreeNode("r", pco);
				var aabb = new AABB();
				aabb.setDimensionByMinMax(
						[ fMno.boundingBox.lx, fMno.boundingBox.ly, fMno.boundingBox.lz ],
						[ fMno.boundingBox.ux, fMno.boundingBox.uy, fMno.boundingBox.uz ]);
				mRoot.setAABB(aabb);
				mRoot.points = fMno.hierarchy[0][1];
				pco.rootNode = mRoot;
			}

			// load remaining hierarchy
			for( var i = 1; i < fMno.hierarchy.length; i++){
				var nodeName = fMno.hierarchy[i][0];
				var points = fMno.hierarchy[i][1];
				var mNode = new PointcloudOctreeNode(nodeName, pco);
				mNode.points = points;
				pco.rootNode.addChild(mNode);
				var childIndex = parseInt(mNode.name.charAt(mNode.name.length-1));
				var childAABB = POCLoader.createChildAABB(mNode.parent.aabb, childIndex);
				mNode.setAABB(childAABB);
			}

		}

		var pcoNode = new PointcloudOctreeSceneNode(pco);
		return pcoNode;
	}catch(e){
//		Logger.error("loading failed: '" + file + "'");
//		Logger.error(e);
		console.log("loading failed: '" + file + "'");
		console.log(e);
	}
};

POCLoader.loadPointAttributes = function(mno){

	var fpa = mno.pointAttributes;
	var pa = new PointAttributes();

	for(var i = 0; i < fpa.length; i++){
		var pointAttribute = PointAttribute[fpa[i]];
		pa.add(pointAttribute);
	}

	return pa;
//	var fpa = mno.pointAttributes;
//	var pa = {
//		'numAttributes' : fpa.length,
//		'bytesPerPoint' : 0,
//		'attributes' : {}
//	};
//
//	for(var i = 0; i < fpa.length; i++){
//		var pointAttribute = PointAttributes[fpa[i]];
//		pa.attributes[i] = pointAttribute;
//		var bytes = pointAttribute.type.size * pointAttribute.numElements;
//		pa.bytesPerPoint += bytes;
//	}
//
//	return pa;
};

/**
 * creates an aabb that covers the area of the childnode at childIndex
 *
 * @param aabb aabb of the parent
 * @param childIndex index of the childs region
 * @returns {AABB}
 */
POCLoader.createChildAABB = function(aabb, childIndex){
	var min = aabb.objectSpaceMin;
	var max = aabb.objectSpaceMax;
	var caabb = new AABB();
	// (aabb.max - aabb.minPos) * 0.5
	var dHalfLength = V3.scale(V3.sub(max,min), 0.5);
	var xHalfLength = [ dHalfLength[0], 0, 0 ];
	var yHalfLength = [ 0, dHalfLength[1], 0 ];
	var zHalfLength = [ 0, 0, dHalfLength[2] ];

	{
		var cmin = min;
		// max = min + (aabb.max - aabb.min) * 0.5;
		var cmax = V3.add(min, dHalfLength);
		var caabb = new AABB();
		caabb.setDimensionByMinMax(cmin, cmax);
	}

	if (childIndex === 1) {
		var min = V3.add(caabb.min, zHalfLength);
		var max = V3.add(caabb.max, zHalfLength);
		caabb.setDimensionByMinMax(min, max);
		caabb.setColor([0.0, 0.0, 1.0, 1.0]);
	}else if (childIndex === 3) {
		var min = V3.add(V3.add(caabb.min, zHalfLength), yHalfLength);
		var max = V3.add(V3.add(caabb.max, zHalfLength), yHalfLength);
		caabb.setDimensionByMinMax(min, max);
		caabb.setColor([1.0, 1.0, 0.0, 1.0]);
	}else if (childIndex === 0) {
		caabb.setColor([1.0, 0.0, 0.0, 1.0]);
	}else if (childIndex === 2) {
		var min = V3.add(caabb.min, yHalfLength);
		var max = V3.add(caabb.max, yHalfLength);
		caabb.setDimensionByMinMax(min, max);
		caabb.setColor([0.0, 1.0, 0.0, 1.0]);
	}else if (childIndex === 5) {
		var min = V3.add(V3.add(caabb.min, zHalfLength), xHalfLength);
		var max = V3.add(V3.add(caabb.max, zHalfLength), xHalfLength);
		caabb.setDimensionByMinMax(min, max);
		caabb.setColor([1.0, 1.0, 1.0, 1.0]);
	}else if (childIndex === 7) {
		var min = V3.add(caabb.min, dHalfLength);
		var max = V3.add(caabb.max, dHalfLength);
		caabb.setDimensionByMinMax(min, max);
		caabb.setColor([0.0, 0.0, 0.0, 1.0]);
	}else if (childIndex === 4) {
		var min = V3.add(caabb.min, xHalfLength);
		var max = V3.add(caabb.max, xHalfLength);
		caabb.setDimensionByMinMax(min, max);
		caabb.setColor([1.0, 0.0, 1.0, 1.0]);
	}else if (childIndex === 6) {
		var min = V3.add(V3.add(caabb.min, xHalfLength), yHalfLength);
		var max = V3.add(V3.add(caabb.max, xHalfLength), yHalfLength);
		caabb.setDimensionByMinMax(min, max);
		caabb.setColor([0.0, 1.0, 1.0, 1.0]);
	}

	return caabb;
};

<|endoftext|>


<commit_before>/*
This file is part of the Juju GUI, which lets users view and manage Juju
environments within a graphical interface (https://launchpad.net/juju-gui).
Copyright (C) 2015 Canonical Ltd.

This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License version 3, as published by
the Free Software Foundation.

This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranties of MERCHANTABILITY,
SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero
General Public License for more details.

You should have received a copy of the GNU Affero General Public License along
with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

'use strict';

YUI.add('added-services-list', function() {

  juju.components.AddedServicesList = React.createClass({

    propTypes: {
      changeState: React.PropTypes.func.isRequired,
      findRelatedServices: React.PropTypes.func.isRequired,
      findUnrelatedServices: React.PropTypes.func.isRequired,
      getUnitStatusCounts: React.PropTypes.func.isRequired,
      hoverService: React.PropTypes.func.isRequired,
      hoveredId: React.PropTypes.oneOfType([
        React.PropTypes.string,
        React.PropTypes.bool
      ]),
      panToService: React.PropTypes.func.isRequired,
      services: React.PropTypes.object.isRequired,
      updateUnitFlags: React.PropTypes.func.isRequired
    },

    generateItemList: function(services) {
      var items = [];
      services.each((service) => {
        items.push(
          <juju.components.AddedServicesListItem
            // We use the 'name' instead of the 'id' here because when a
            // ghost service is added it uses the ghost id structure instead
            // of the final deployed service id structure and we want react
            // to treat them as the same record instead of re-rendering
            // when they key changes.
            key={service.get('name')}
            hovered={service.get('id') === this.props.hoveredId}
            changeState={this.props.changeState}
            getUnitStatusCounts={this.props.getUnitStatusCounts}
            ref={'AddedServicesListItem-' + service.get('id')}
            hoverService={this.props.hoverService}
            panToService={this.props.panToService}
            service={service} />);
      });
      return items;
    },

    render: function() {
      return (

            {this.generateItemList(this.props.services)}

      );
    }

  });

}, '0.1.0', { requires: [
  'added-services-list-item'
]});
<commit_msg>Update AddedServicesList component.<commit_after>/*
This file is part of the Juju GUI, which lets users view and manage Juju
environments within a graphical interface (https://launchpad.net/juju-gui).
Copyright (C) 2015 Canonical Ltd.

This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License version 3, as published by
the Free Software Foundation.

This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranties of MERCHANTABILITY,
SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero
General Public License for more details.

You should have received a copy of the GNU Affero General Public License along
with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

'use strict';

const AddedServicesList = React.createClass({

  propTypes: {
    changeState: React.PropTypes.func.isRequired,
    findRelatedServices: React.PropTypes.func.isRequired,
    findUnrelatedServices: React.PropTypes.func.isRequired,
    getUnitStatusCounts: React.PropTypes.func.isRequired,
    hoverService: React.PropTypes.func.isRequired,
    hoveredId: React.PropTypes.oneOfType([
      React.PropTypes.string,
      React.PropTypes.bool
    ]),
    panToService: React.PropTypes.func.isRequired,
    services: React.PropTypes.object.isRequired,
    updateUnitFlags: React.PropTypes.func.isRequired
  },

  generateItemList: function(services) {
    var items = [];
    services.each((service) => {
      items.push(
        <juju.components.AddedServicesListItem
          // We use the 'name' instead of the 'id' here because when a
          // ghost service is added it uses the ghost id structure instead
          // of the final deployed service id structure and we want react
          // to treat them as the same record instead of re-rendering
          // when they key changes.
          key={service.get('name')}
          hovered={service.get('id') === this.props.hoveredId}
          changeState={this.props.changeState}
          getUnitStatusCounts={this.props.getUnitStatusCounts}
          ref={'AddedServicesListItem-' + service.get('id')}
          hoverService={this.props.hoverService}
          panToService={this.props.panToService}
          service={service} />);
    });
    return items;
  },

  render: function() {
    return (

          {this.generateItemList(this.props.services)}

    );
  }

});

YUI.add('added-services-list', function() {
  juju.components.AddedServicesList = AddedServicesList;
}, '0.1.0', { requires: [
  'added-services-list-item'
]});
<|endoftext|>


<commit_before>define(function(require) {
  var $ = require('jquery')
  var DateFormat = require('./DateFormat')
  var DateRange = require('./DateRange')
  var DateTime = require('./DateTime')

  return function(container, calendarBody, executeCallback, locale, params, getElemDate, calendar, startDate,
                  endDate, calendarRange, setStartField, setEndField, formatDate, disabledDatesList) {
    var mouseDownDate = null
    var selection
    var oldSelection
    var Status = {
      CREATE_OR_RESIZE: 'create',
      MOVE            : 'move',
      NONE            : 'none'
    }
    var status = Status.NONE

    return {
      showInitialSelection: setRangeLabels,
      initEvents          : initEvents,
      addRangeLengthLabel : addRangeLengthLabel,
      addEndDateLabel     : addEndDateLabel,
      addDateClearingLabel: addDateClearingLabel,
      performTrigger      : performTrigger
    }

    function initEvents() {
      setInitialSelection()
      oldSelection = selection.clone()
      initRangeCalendarEvents(container, calendarBody.bodyTable)
      drawSelection()
    }

    function addRangeLengthLabel() {
      if($('.rangeLengthLabel', container).isEmpty()) {
        var rangeLengthContainer = $('

')
        $('.continuousCalendar', container).append(rangeLengthContainer)
      }
    }

    function addEndDateLabel(dateLabelContainer) { dateLabelContainer.append(' - ').append('') }

    function addDateClearingLabel() {
      if(params.allowClearDates) {
        var dateClearingLabel = $('').text(locale.clearRangeLabel)
        var dateClearingContainer = $('

').append(dateClearingLabel)
        $('.continuousCalendar', container).append(dateClearingContainer)
      }
    }

    function performTrigger() {
      container.data('calendarRange', selection)
      executeCallback(selection)
    }

    function setInitialSelection() {
      selection = startDate && endDate ? new DateRange(startDate, endDate) : DateRange.emptyRange()
      if (!selection.start && !selection.end) {
        $('span.separator', container).hide()
      }
    }

    function initRangeCalendarEvents(container, bodyTable) {
      $('span.rangeLengthLabel', container).text(locale.daysLabel(selection.days()))
      if (params.allowClearDates) {
        $('span.clearDates', container).click(clearRangeClick)
      }
      bodyTable.addClass(params.selectWeek ? 'weekRange' : 'freeRange')
      bodyTable.mousedown(mouseDown).mouseover(mouseMove).mouseup(mouseUp)
      disableTextSelection(bodyTable.get(0))
    }

    function mouseDown(event) {
      var elem = event.target
      var hasShiftKeyPressed = event.shiftKey
      if(isInstantSelection(elem, hasShiftKeyPressed)) {
        selection = instantSelection(elem, hasShiftKeyPressed)
      } else {
        status = Status.CREATE_OR_RESIZE
        mouseDownDate = getElemDate(elem)
        if(mouseDownDate.equalsOnlyDate(selection.end)) mouseDownDate = selection.start
        else if(mouseDownDate.equalsOnlyDate(selection.start)) mouseDownDate = selection.end
        else if(selection.hasDate(mouseDownDate)) status = Status.MOVE
        else if(enabledCell(elem)) startNewRange()
      }

      function enabledCell(elem) { return isDateCell(elem) && isEnabled(elem) }

      function isInstantSelection(elem, hasShiftKeyPressed) {
        if(params.selectWeek) return enabledCell(elem) || isWeekCell(elem)
        else return isWeekCell(elem) || isMonthCell(elem) || hasShiftKeyPressed

      }

      function instantSelection(elem, hasShiftKeyPressed) {
        if((params.selectWeek && enabledCell(elem)) || isWeekCell(elem)) {
          status = Status.NONE
          var firstDayOfWeek = getElemDate($(elem).parent().children('.date').get(0))
          return instantSelectWeek(firstDayOfWeek)
        } else if(isMonthCell(elem)) {
          status = Status.NONE
          var dayInMonth = getElemDate($(elem).siblings('.date').get(0))
          return new DateRange(dayInMonth.firstDateOfMonth(), dayInMonth.lastDateOfMonth(), locale)
        } else if(hasShiftKeyPressed) {
          if(selection.days() > 0 && enabledCell(elem)) {
            status = Status.NONE
            selection = selection.expandTo(getElemDate(elem))
            return selection
          }
        }
        return selection
      }

      function instantSelectWeek(firstDayOfWeek) {
        var firstDay = firstDayOfWeek
        var lastDay = firstDayOfWeek.plusDays(6)
        if(params.disableWeekends) {
          firstDay = firstDayOfWeek.withWeekday(DateTime.MONDAY)
          lastDay = firstDayOfWeek.withWeekday(DateTime.FRIDAY)
        }
        return new DateRange(firstDay, lastDay, locale).and(calendarRange)
      }
    }

    function startNewRange() { selection = new DateRange(mouseDownDate, mouseDownDate, locale) }

    function disableTextSelection(elem) {
      //Firefox
      $(elem).css('MozUserSelect', 'none')
      //IE
      $(elem).bind('selectstart', function() { return false })
      //Opera, etc.
      $(elem).mousedown(function() { return false })
    }

    function mouseMove(event) {
      if (status !== Status.NONE) {
        var date = getElemDate(event.target)
        var actions = {
          move:   function() {
            var deltaDays = mouseDownDate.distanceInDays(date)
            var movedSelection = selection.shiftDays(deltaDays).and(calendarRange)
            if (isPermittedRange(movedSelection)) {
              mouseDownDate = date
              selection = movedSelection
            }
          },
          create: function() {
            var newSelection = new DateRange(mouseDownDate, date, locale)
            if (isEnabled(event.target) && isPermittedRange(newSelection)) selection = newSelection
          }
        }
        actions[status]()
        drawSelection()
      }
    }

    function isPermittedRange(newSelection) { return newSelection.isPermittedRange(params.minimumRange, params.disableWeekends, calendarRange) }

    function mouseUp() {
      status = Status.NONE
      if(rangeHasDisabledDate()) selection = DateRange.emptyRange()
      drawSelection()
      afterSelection()
    }

    function clearRangeClick(event) {
      selection = DateRange.emptyRange()
      drawSelection()
      afterSelection()
    }

    function rangeHasDisabledDate() {
      for(var i = 0; i < disabledDatesList.length; i++) {
        if(selection.hasDate(new DateTime(disabledDatesList[i]))) return true
      }
      return false
    }

    function drawSelection() {
      selection = DateRange.rangeWithMinimumSize(selection, params.minimumRange, params.disableWeekends, calendarRange)
      drawSelectionBetweenDates(selection)
      $('span.rangeLengthLabel', container).text(locale.daysLabel(selection.days()))
    }

    function drawSelectionBetweenDates(range) {
      $('td.selected', container).removeClass('selected').removeClass('rangeStart').removeClass('rangeEnd').removeClass('invalidSelection')
      iterateAndToggleCells(range)
      oldSelection = range.clone()
    }

    function iterateAndToggleCells(range) {
      if (range.days() > 0) {
        var startIndex = index(range.start)
        var endIndex = index(range.end)
        for (var i = startIndex; i <= endIndex; i++)
          calendarBody.getDateCell(i).get(0).className = dateCellStyle(calendarBody.dateCellDates[i], range.start, range.end).join(' ')
        if (rangeHasDisabledDate()) $('td.selected', container).addClass('invalidSelection')
      }
      function index(date) { return calendarBody.dateCellMap[DateFormat.format(date, 'Ymd', locale)] }
    }

    function dateCellStyle(date, start, end) {
      var styleClass = [calendarBody.dateStyles(date)]
      if(date.equalsOnlyDate(end)) return styleClass.concat('selected rangeEnd')
      if(date.equalsOnlyDate(start)) return styleClass.concat('selected rangeStart')
      if(date.isBetweenDates(start, end)) return styleClass.concat('selected')
      return styleClass
    }

    function afterSelection() {
      if(rangeHasDisabledDate()) {
        selection = DateRange.emptyRange()
        // Flash invalidSelection styled cells when selection is expanded to minimum length
        setTimeout(function() { drawSelectionBetweenDates(selection) }, 200)
      }
      var formattedStart = formatDate(selection.start)
      var formattedEnd = formatDate(selection.end)
      container.data('calendarRange', selection)
      setStartField(formattedStart)
      setEndField(formattedEnd)
      setRangeLabels()
      if(params.selectWeek) calendar.close($('td.selected', container).first())
      executeCallback(selection)
    }

    function setRangeLabels() {
      if(!selection) setInitialSelection()

      if(selection.start && selection.end) {
        var format = locale.weekDateFormat
        $('span.startDateLabel', container).text(DateFormat.format(selection.start, format, locale))
        $('span.endDateLabel', container).text(DateFormat.format(selection.end, format, locale))
        $('span.separator, span.clearRangeLabel', container).show()
        $('span.startDateLabel', container).closest('.label').show()
      } else {
        if (!selection.start) {
          $('span.startDateLabel', container).empty()
          $('span.startDateLabel', container).closest('.label').hide()
        }
        if (!selection.end) {
          $('span.endDateLabel', container).empty()
        }
        $('span.separator, span.clearRangeLabel', container).hide()
      }
    }

    function isDateCell(elem) { return $(elem).closest('[date-cell-index]').hasClass('date') }

    function isWeekCell(elem) { return $(elem).hasClass('week') }

    function isMonthCell(elem) { return $(elem).hasClass('month') }

    function isEnabled(elem) { return !$(elem).hasClass('disabled') }
  }
})
<commit_msg>Show clear button only if range is set<commit_after>define(function(require) {
  var $ = require('jquery')
  var DateFormat = require('./DateFormat')
  var DateRange = require('./DateRange')
  var DateTime = require('./DateTime')

  return function(container, calendarBody, executeCallback, locale, params, getElemDate, calendar, startDate,
                  endDate, calendarRange, setStartField, setEndField, formatDate, disabledDatesList) {
    var mouseDownDate = null
    var selection
    var oldSelection
    var Status = {
      CREATE_OR_RESIZE: 'create',
      MOVE            : 'move',
      NONE            : 'none'
    }
    var status = Status.NONE

    return {
      showInitialSelection: setRangeLabels,
      initEvents          : initEvents,
      addRangeLengthLabel : addRangeLengthLabel,
      addEndDateLabel     : addEndDateLabel,
      addDateClearingLabel: addDateClearingLabel,
      performTrigger      : performTrigger
    }

    function initEvents() {
      setInitialSelection()
      oldSelection = selection.clone()
      initRangeCalendarEvents(container, calendarBody.bodyTable)
      drawSelection()
    }

    function addRangeLengthLabel() {
      if($('.rangeLengthLabel', container).isEmpty()) {
        var rangeLengthContainer = $('

')
        $('.continuousCalendar', container).append(rangeLengthContainer)
      }
    }

    function addEndDateLabel(dateLabelContainer) { dateLabelContainer.append(' - ').append('') }

    function addDateClearingLabel() {
      if(params.allowClearDates) {
        var dateClearingLabel = $('').text(locale.clearRangeLabel)
        var dateClearingContainer = $('

').append(dateClearingLabel)
        $('.continuousCalendar', container).append(dateClearingContainer)
      }
    }

    function performTrigger() {
      container.data('calendarRange', selection)
      executeCallback(selection)
    }

    function setInitialSelection() {
      selection = startDate && endDate ? new DateRange(startDate, endDate) : DateRange.emptyRange()
      if (!selection.start && !selection.end) {
        $('span.separator', container).hide()
      }
    }

    function initRangeCalendarEvents(container, bodyTable) {
      $('span.rangeLengthLabel', container).text(locale.daysLabel(selection.days()))
      if (params.allowClearDates) {
        $('span.clearDates', container).click(clearRangeClick)
      }
      bodyTable.addClass(params.selectWeek ? 'weekRange' : 'freeRange')
      bodyTable.mousedown(mouseDown).mouseover(mouseMove).mouseup(mouseUp)
      disableTextSelection(bodyTable.get(0))
    }

    function mouseDown(event) {
      var elem = event.target
      var hasShiftKeyPressed = event.shiftKey
      if(isInstantSelection(elem, hasShiftKeyPressed)) {
        selection = instantSelection(elem, hasShiftKeyPressed)
      } else {
        status = Status.CREATE_OR_RESIZE
        mouseDownDate = getElemDate(elem)
        if(mouseDownDate.equalsOnlyDate(selection.end)) mouseDownDate = selection.start
        else if(mouseDownDate.equalsOnlyDate(selection.start)) mouseDownDate = selection.end
        else if(selection.hasDate(mouseDownDate)) status = Status.MOVE
        else if(enabledCell(elem)) startNewRange()
      }

      function enabledCell(elem) { return isDateCell(elem) && isEnabled(elem) }

      function isInstantSelection(elem, hasShiftKeyPressed) {
        if(params.selectWeek) return enabledCell(elem) || isWeekCell(elem)
        else return isWeekCell(elem) || isMonthCell(elem) || hasShiftKeyPressed

      }

      function instantSelection(elem, hasShiftKeyPressed) {
        if((params.selectWeek && enabledCell(elem)) || isWeekCell(elem)) {
          status = Status.NONE
          var firstDayOfWeek = getElemDate($(elem).parent().children('.date').get(0))
          return instantSelectWeek(firstDayOfWeek)
        } else if(isMonthCell(elem)) {
          status = Status.NONE
          var dayInMonth = getElemDate($(elem).siblings('.date').get(0))
          return new DateRange(dayInMonth.firstDateOfMonth(), dayInMonth.lastDateOfMonth(), locale)
        } else if(hasShiftKeyPressed) {
          if(selection.days() > 0 && enabledCell(elem)) {
            status = Status.NONE
            selection = selection.expandTo(getElemDate(elem))
            return selection
          }
        }
        return selection
      }

      function instantSelectWeek(firstDayOfWeek) {
        var firstDay = firstDayOfWeek
        var lastDay = firstDayOfWeek.plusDays(6)
        if(params.disableWeekends) {
          firstDay = firstDayOfWeek.withWeekday(DateTime.MONDAY)
          lastDay = firstDayOfWeek.withWeekday(DateTime.FRIDAY)
        }
        return new DateRange(firstDay, lastDay, locale).and(calendarRange)
      }
    }

    function startNewRange() { selection = new DateRange(mouseDownDate, mouseDownDate, locale) }

    function disableTextSelection(elem) {
      //Firefox
      $(elem).css('MozUserSelect', 'none')
      //IE
      $(elem).bind('selectstart', function() { return false })
      //Opera, etc.
      $(elem).mousedown(function() { return false })
    }

    function mouseMove(event) {
      if (status !== Status.NONE) {
        var date = getElemDate(event.target)
        var actions = {
          move:   function() {
            var deltaDays = mouseDownDate.distanceInDays(date)
            var movedSelection = selection.shiftDays(deltaDays).and(calendarRange)
            if (isPermittedRange(movedSelection)) {
              mouseDownDate = date
              selection = movedSelection
            }
          },
          create: function() {
            var newSelection = new DateRange(mouseDownDate, date, locale)
            if (isEnabled(event.target) && isPermittedRange(newSelection)) selection = newSelection
          }
        }
        actions[status]()
        drawSelection()
      }
    }

    function isPermittedRange(newSelection) { return newSelection.isPermittedRange(params.minimumRange, params.disableWeekends, calendarRange) }

    function mouseUp() {
      status = Status.NONE
      if(rangeHasDisabledDate()) selection = DateRange.emptyRange()
      drawSelection()
      afterSelection()
    }

    function clearRangeClick(event) {
      selection = DateRange.emptyRange()
      drawSelection()
      afterSelection()
    }

    function rangeHasDisabledDate() {
      for(var i = 0; i < disabledDatesList.length; i++) {
        if(selection.hasDate(new DateTime(disabledDatesList[i]))) return true
      }
      return false
    }

    function drawSelection() {
      selection = DateRange.rangeWithMinimumSize(selection, params.minimumRange, params.disableWeekends, calendarRange)
      drawSelectionBetweenDates(selection)
      $('span.rangeLengthLabel', container).text(locale.daysLabel(selection.days()))
      var clearDates = $('span.clearDates', container)
      clearDates.toggle(selection.days() > 0)
    }

    function drawSelectionBetweenDates(range) {
      $('td.selected', container).removeClass('selected').removeClass('rangeStart').removeClass('rangeEnd').removeClass('invalidSelection')
      iterateAndToggleCells(range)
      oldSelection = range.clone()
    }

    function iterateAndToggleCells(range) {
      if (range.days() > 0) {
        var startIndex = index(range.start)
        var endIndex = index(range.end)
        for (var i = startIndex; i <= endIndex; i++)
          calendarBody.getDateCell(i).get(0).className = dateCellStyle(calendarBody.dateCellDates[i], range.start, range.end).join(' ')
        if (rangeHasDisabledDate()) $('td.selected', container).addClass('invalidSelection')
      }
      function index(date) { return calendarBody.dateCellMap[DateFormat.format(date, 'Ymd', locale)] }
    }

    function dateCellStyle(date, start, end) {
      var styleClass = [calendarBody.dateStyles(date)]
      if(date.equalsOnlyDate(end)) return styleClass.concat('selected rangeEnd')
      if(date.equalsOnlyDate(start)) return styleClass.concat('selected rangeStart')
      if(date.isBetweenDates(start, end)) return styleClass.concat('selected')
      return styleClass
    }

    function afterSelection() {
      if(rangeHasDisabledDate()) {
        selection = DateRange.emptyRange()
        // Flash invalidSelection styled cells when selection is expanded to minimum length
        setTimeout(function() { drawSelectionBetweenDates(selection) }, 200)
      }
      var formattedStart = formatDate(selection.start)
      var formattedEnd = formatDate(selection.end)
      container.data('calendarRange', selection)
      setStartField(formattedStart)
      setEndField(formattedEnd)
      setRangeLabels()
      if(params.selectWeek) calendar.close($('td.selected', container).first())
      executeCallback(selection)
    }

    function setRangeLabels() {
      if(!selection) setInitialSelection()

      if(selection.start && selection.end) {
        var format = locale.weekDateFormat
        $('span.startDateLabel', container).text(DateFormat.format(selection.start, format, locale))
        $('span.endDateLabel', container).text(DateFormat.format(selection.end, format, locale))
        $('span.separator, span.clearRangeLabel', container).show()
        $('span.startDateLabel', container).closest('.label').show()
      } else {
        if (!selection.start) {
          $('span.startDateLabel', container).empty()
          $('span.startDateLabel', container).closest('.label').hide()
        }
        if (!selection.end) {
          $('span.endDateLabel', container).empty()
        }
        $('span.separator, span.clearRangeLabel', container).hide()
      }
    }

    function isDateCell(elem) { return $(elem).closest('[date-cell-index]').hasClass('date') }

    function isWeekCell(elem) { return $(elem).hasClass('week') }

    function isMonthCell(elem) { return $(elem).hasClass('month') }

    function isEnabled(elem) { return !$(elem).hasClass('disabled') }
  }
})
<|endoftext|>


<commit_before>var cdb = require('cartodb.js');
var _ = require('underscore');
var ImportModel = require('./import_model');
var UploadModel = require('./upload_model');

/**
 *  Upload/import model
 *
 *  It takes the control of the upload and import,
 *  listening the change of any of these steps.
 *
 *  Steps:
 *  - upload
 *  - import
 *
 */

module.exports = cdb.core.Model.extend({

  defaults: {
    step: 'upload',
    state: ''
  },

  initialize: function(attrs, opts) {
    if (_.isEmpty(opts)) opts = {};
    this.user = opts && opts.user;
    this.upl = new UploadModel(opts.upload, { user: this.user });
    this.imp = new ImportModel(opts.import);
    this._initBinds();
    this._checkStatus();
  },

  _initBinds: function() {
    this.bind('change:import',  this._onImportChange, this);
    this.bind('change:upload',  this._onUploadChange, this);
    this.bind('change:id',      this._onIdChange, this);

    this.imp.bind('change', function() {
      this.trigger('change:import');
      this.trigger('change');
    }, this);
    this.upl.bind('change', function() {
      this.trigger('change:upload');
      this.trigger('change');
    }, this)
  },

  _destroyBinds: function() {
    this.upl.unbind(null, null, this);
    this.imp.unbind(null, null, this);
  },

  _onIdChange: function() {
    var item_queue_id = this.get('id');
    if (item_queue_id) this.imp.set('item_queue_id', item_queue_id);
    this.set('step', 'import');
  },

  _onUploadChange: function(m, i) {
    if (this.get('step') === "upload") {
      var item_queue_id = this.upl.get('item_queue_id');
      var state = this.upl.get('state');

      if (item_queue_id) this.set('id', item_queue_id);
      if (state) this.set('state', state);
    }
  },

  _onImportChange: function() {
    if (this.get('step') === "import") {
      var state = this.imp.get('state');
      if (state) this.set('state', state);
    }
  },

  _checkStatus: function() {
    if (!this.upl.isValid()) {
      // Upload is invalid so we need
      // checking init attributes
      this.trigger('change:upload');
      return;
    }

    if (this.upl.get('type') === 'file') {
      this.upl.upload();
    } else if (this.get('id')) {
      this.set('step', 'import');
      this.imp.set('item_queue_id', this.get('id'));
    } else if (!this.imp.get('item_queue_id') && this.upl.get('type') !== "") {
      this.set('step', 'import');
      this.imp.createImport(this.upl.toJSON());
    }
  },

  pause: function() {
    this.stopUpload();
    this.stopImport();
  },

  hasFailed: function() {
    var state = this.get('state');
    var step = this.get('step');

    return ( step === 'import' && state === 'failure' ) || ( step === 'upload' && state === 'error' );
  },

  hasCompleted: function() {
    return this.get('step') === "import" && this.imp && this.imp.get('state') === 'complete'
  },

  getError: function() {
    if (this.hasFailed()) {
      var step = this.get('step');
      return _.extend(
        {
          error_code: this[step === "upload" ? 'upl' : 'imp'].get('error_code'),
          item_queue_id: step === "import" ? this.imp.get('id') : ''
        }
        ,
        this[step === "upload" ? 'upl' : 'imp'].get('get_error_text')
      )
    }

    return {
      title: '',
      what_about: '',
      error_code: ''
    }
  },

  importedVis: function() {
    if (this.get('import').derived_visualization_id) {
      return this._getMapVis();
    } else {
      return this._getDatasetVis();
    }
  },

  _getMapVis: function() {
    var derivedVisId = this.imp.get('derived_visualization_id');

    if (!derivedVisId) {
      return false;
    }

    return this._createVis({
      type: 'derived',
      id: derivedVisId
    });
  },

  _getDatasetVis: function() {
    var tableName = this.imp.get('table_name');

    if (!tableName) {
      return false;
    }

    return this._createVis({
      type: 'table',
      table: {
        name: tableName
      }
    });
  },

  _createVis: function(attrs) {
    var vis = new cdb.admin.Visualization(attrs);
    vis.permission.owner = this.user;
    return vis;
  },

  stopUpload: function() {
    this.upl.stopUpload();
  },

  stopImport: function() {
    this.imp.destroyCheck();
  },

  get: function (attr) {
    if (attr === "upload") return this.upl.toJSON();
    if (attr === "import") return this.imp.toJSON();

    return cdb.core.Model.prototype.get.call(this, attr);
  },

  toJSON: function() {
    return {
      step: this.get('step'),
      id: this.get('id'),
      state: this.get('state'),
      upload: this.upl.toJSON(),
      import: this.imp.toJSON()
    }
  }

});
<commit_msg>Removed useless comment<commit_after>var cdb = require('cartodb.js');
var _ = require('underscore');
var ImportModel = require('./import_model');
var UploadModel = require('./upload_model');

/**
 *  Upload/import model
 *
 *  It takes the control of the upload and import,
 *  listening the change of any of these steps.
 *
 *  Steps:
 *  - upload
 *  - import
 *
 */

module.exports = cdb.core.Model.extend({

  defaults: {
    step: 'upload',
    state: ''
  },

  initialize: function(attrs, opts) {
    if (_.isEmpty(opts)) opts = {};
    this.user = opts && opts.user;
    this.upl = new UploadModel(opts.upload, { user: this.user });
    this.imp = new ImportModel(opts.import);
    this._initBinds();
    this._checkStatus();
  },

  _initBinds: function() {
    this.bind('change:import',  this._onImportChange, this);
    this.bind('change:upload',  this._onUploadChange, this);
    this.bind('change:id',      this._onIdChange, this);

    this.imp.bind('change', function() {
      this.trigger('change:import');
      this.trigger('change');
    }, this);
    this.upl.bind('change', function() {
      this.trigger('change:upload');
      this.trigger('change');
    }, this)
  },

  _destroyBinds: function() {
    this.upl.unbind(null, null, this);
    this.imp.unbind(null, null, this);
  },

  _onIdChange: function() {
    var item_queue_id = this.get('id');
    if (item_queue_id) this.imp.set('item_queue_id', item_queue_id);
    this.set('step', 'import');
  },

  _onUploadChange: function(m, i) {
    if (this.get('step') === "upload") {
      var item_queue_id = this.upl.get('item_queue_id');
      var state = this.upl.get('state');

      if (item_queue_id) this.set('id', item_queue_id);
      if (state) this.set('state', state);
    }
  },

  _onImportChange: function() {
    if (this.get('step') === "import") {
      var state = this.imp.get('state');
      if (state) this.set('state', state);
    }
  },

  _checkStatus: function() {
    if (!this.upl.isValid()) {
      this.trigger('change:upload');
      return;
    }

    if (this.upl.get('type') === 'file') {
      this.upl.upload();
    } else if (this.get('id')) {
      this.set('step', 'import');
      this.imp.set('item_queue_id', this.get('id'));
    } else if (!this.imp.get('item_queue_id') && this.upl.get('type') !== "") {
      this.set('step', 'import');
      this.imp.createImport(this.upl.toJSON());
    }
  },

  pause: function() {
    this.stopUpload();
    this.stopImport();
  },

  hasFailed: function() {
    var state = this.get('state');
    var step = this.get('step');

    return ( step === 'import' && state === 'failure' ) || ( step === 'upload' && state === 'error' );
  },

  hasCompleted: function() {
    return this.get('step') === "import" && this.imp && this.imp.get('state') === 'complete'
  },

  getError: function() {
    if (this.hasFailed()) {
      var step = this.get('step');
      return _.extend(
        {
          error_code: this[step === "upload" ? 'upl' : 'imp'].get('error_code'),
          item_queue_id: step === "import" ? this.imp.get('id') : ''
        }
        ,
        this[step === "upload" ? 'upl' : 'imp'].get('get_error_text')
      )
    }

    return {
      title: '',
      what_about: '',
      error_code: ''
    }
  },

  importedVis: function() {
    if (this.get('import').derived_visualization_id) {
      return this._getMapVis();
    } else {
      return this._getDatasetVis();
    }
  },

  _getMapVis: function() {
    var derivedVisId = this.imp.get('derived_visualization_id');

    if (!derivedVisId) {
      return false;
    }

    return this._createVis({
      type: 'derived',
      id: derivedVisId
    });
  },

  _getDatasetVis: function() {
    var tableName = this.imp.get('table_name');

    if (!tableName) {
      return false;
    }

    return this._createVis({
      type: 'table',
      table: {
        name: tableName
      }
    });
  },

  _createVis: function(attrs) {
    var vis = new cdb.admin.Visualization(attrs);
    vis.permission.owner = this.user;
    return vis;
  },

  stopUpload: function() {
    this.upl.stopUpload();
  },

  stopImport: function() {
    this.imp.destroyCheck();
  },

  get: function (attr) {
    if (attr === "upload") return this.upl.toJSON();
    if (attr === "import") return this.imp.toJSON();

    return cdb.core.Model.prototype.get.call(this, attr);
  },

  toJSON: function() {
    return {
      step: this.get('step'),
      id: this.get('id'),
      state: this.get('state'),
      upload: this.upl.toJSON(),
      import: this.imp.toJSON()
    }
  }

});
<|endoftext|>


<commit_before>function initTypeProtoI(a, b, c){} //IGNORE
function initTypeProto(a,b,c,d){}//IGNORE
function initType(a,b){}//IGNORE
function Basic(x){}//IGNORE
function ArraySequence(x){}//IGNORE
function Comprehension(x){}//IGNORE
function Exception(x){}//IGNORE
function String$(x){}//IGNORE
var Container,$finished,empty,larger,smaller,exports;//IGNORE

function Iterable(wat) {
    return wat;
}
initTypeProtoI(Iterable, 'ceylon.language::Iterable', $init$ContainerWithFirstElement());
function $init$Iterable() { return Iterable; }
var Iterable$proto=Iterable.$$.prototype;
Iterable$proto.getEmpty = function() {
    return this.getIterator().next() === $finished;
}
Iterable$proto.getFirst = function() {
    var e = this.getIterator().next();
    return e === $finished ? null : e;
}
Iterable$proto.getRest = function() {
    return this.skipping(1);
}
Iterable$proto.getSequence = function() {
    var a = [];
    var iter = this.getIterator();
    var next;
    while ((next = iter.next()) !== $finished) {
        a.push(next);
    }
    return ArraySequence(a, this.$$targs$$);
}
Iterable$proto.$map = function(mapper) {
    var iter = this;
    return Comprehension(function() {
        var it = iter.getIterator();
        return function() {
            var e = it.next();
            if(e !== $finished) {return mapper(e);}
            return $finished;
        }
    });
}
Iterable$proto.$filter = function(select) {
    var iter = this;
    return Comprehension(function() {
        var it = iter.getIterator();
        return function() {
            do {
                var e = it.next();
            } while ((e !== $finished) && !select(e));
            return e;
        }
    });
}
Iterable$proto.fold = function(ini, accum) {
    var r = ini;
    var iter = this.getIterator();
    var e; while ((e = iter.next()) !== $finished) {
        r = accum(r, e);
    }
    return r;
}
Iterable$proto.find = function(select) {
    var iter = this.getIterator();
    var e; while ((e = iter.next()) !== $finished) {
        if (select(e)) {
            return e;
        }
    }
    return null;
}
Iterable$proto.findLast = function(select) {
    var iter = this.getIterator();
    var last = null;
    var e; while ((e = iter.next()) !== $finished) {
        if (select(e)) {
            last = e;
        }
    }
    return last;
}
Iterable$proto.$sort = function(/*Callable<Comparison?,Element,Element>*/comparing) {
    var a = [];
    var iter = this.getIterator();
    var e; while ((e = iter.next()) !== $finished) {
        a.push(e);
    }
    a.sort(function(x,y) {
        var r = comparing(x,y);
        if (r === larger) return 1;
        if (r === smaller) return -1;
        return 0;
    });
    return ArraySequence(a, this.$$targs$$);
}
Iterable$proto.any = function(/*Callable<Boolean,Element>*/selecting) {
    var iter = this.getIterator();
    var e; while ((e = iter.next()) !== $finished) {
        if (selecting(e)) {
            return true;
        }
    }
    return false;
}
Iterable$proto.$every = function(/*Callable<Boolean,Element>*/selecting) {
    var iter = this.getIterator();
    var e; while ((e = iter.next()) !== $finished) {
        if (!selecting(e)) {
            return false;
        }
    }
    return true;
}
Iterable$proto.skipping = function(skip) {
    function skip$iter(iter,skip){
        var $cmp$=new skip$iter.$$;
        Basic($cmp$);
        $cmp$.iter=iter;
        $cmp$.skip=skip;
        $cmp$.getIterator=function(){
            var iter = this.iter.getIterator();
            for (var i=0; i < this.skip; i++) {
                iter.next();
            }
            return iter;
        };
        return $cmp$;
    }
    initTypeProto(skip$iter, 'ceylon.language::SkipIterable', Basic, Iterable);
    return skip$iter(this,skip);
}
Iterable$proto.taking = function(take) {
    if (take <= 0) return empty;
    var iter = this;
    return Comprehension(function() {
        var it = iter.getIterator();
        var i = 0;
        return function() {
            if (i >= take) {return $finished;}
            ++i;
            return it.next();
        }
    });
}
Iterable$proto.by = function(step) {
    if (step == 1) return this;
    if (step < 1) throw Exception(String$("Step must be positive"));
    var iter = this;
    return Comprehension(function() {
        var it = iter.getIterator();
        return function() {
            var e = it.next();
            for (var i=1; i<step && (it.next()!==$finished); i++);
            return e;
        }
    });
}
Iterable$proto.count = function(sel) {
    var c = 0;
    var iter = this.getIterator();
    var e; while ((e = iter.next()) !== $finished) {
        if (sel(e)) c++;
    }
    return c;
}
Iterable$proto.getCoalesced = function() {
    var iter = this;
    return Comprehension(function() {
        var it = iter.getIterator();
        return function() {
            var e;
            while ((e = it.next()) === null);
            return e;
        }
    });
}
Iterable$proto.getIndexed = function() {
    var iter = this;
    return Comprehension(function() {
        var it = iter.getIterator();
        var idx = 0;
        return function() {
            var e;
            while ((e = it.next()) === null) {idx++;}
            return e === $finished ? e : Entry(idx++, e);
        }
    });
}
Iterable$proto.getLast = function() {
    var iter = this.getIterator();
    var l=null;
    var e; while ((e = iter.next()) !== $finished) {
        l=e;
    }
    return l;
}
Iterable$proto.collect = function(collecting) {
    return this.$map(collecting).getSequence();
}
Iterable$proto.select = function(selecting) {
    return this.$filter(selecting).getSequence();
}
Iterable$proto.group = function(grouping, $$$mptypes) {
    var map = HashMap();
    var it = this.getIterator();
    var elem;
    var newSeq = ArraySequence([], this.$$targs$$);
    while ((elem=it.next()) !== $finished) {
        var key = grouping(elem);
        var seq = map.put(Entry(key, newSeq, [$$$mptypes[0], {t:Sequence, a:this.$$targs$$}]), true);
        if (seq === null) {
            seq = newSeq;
            newSeq = ArraySequence([], this.$$targs$$);
        }
        seq.push(elem);
    }
    return map;
}

exports.Iterable=Iterable;

Iterable$proto.chain = function(other) {
    return ChainedIterable(this, other);
}
exports.Iterable=Iterable;

function ChainedIterable(first, second, chained) {
    if (chained===undefined) {chained = new ChainedIterable.$$;}
    Basic(chained);
    chained.first = first;
    chained.second = second;
    return chained;
}
initTypeProto(ChainedIterable, "ceylon.language::ChainedIterable",
        Basic, Iterable);
var ChainedIterable$proto = ChainedIterable.$$.prototype;
ChainedIterable$proto.getIterator = function() {
    return ChainedIterator(this.first, this.second);
}

function toTuple(iterable) {
  var seq = iterable.getSequence();
  return Tuple(seq.getFirst(), seq.getRest().getSequence(), seq.$$targs$$);
}
exports.toTuple=toTuple;
<commit_msg>Add reified generics for #156<commit_after>function initTypeProtoI(a, b, c){} //IGNORE
function initTypeProto(a,b,c,d){}//IGNORE
function initType(a,b){}//IGNORE
function Basic(x){}//IGNORE
function ArraySequence(x){}//IGNORE
function Comprehension(x){}//IGNORE
function Exception(x){}//IGNORE
function String$(x){}//IGNORE
var Container,$finished,empty,larger,smaller,exports;//IGNORE

function Iterable(wat) {
    return wat;
}
initTypeProtoI(Iterable, 'ceylon.language::Iterable', $init$ContainerWithFirstElement());
function $init$Iterable() { return Iterable; }
var Iterable$proto=Iterable.$$.prototype;
Iterable$proto.getEmpty = function() {
    return this.getIterator().next() === $finished;
}
Iterable$proto.getFirst = function() {
    var e = this.getIterator().next();
    return e === $finished ? null : e;
}
Iterable$proto.getRest = function() {
    return this.skipping(1);
}
Iterable$proto.getSequence = function() {
    var a = [];
    var iter = this.getIterator();
    var next;
    while ((next = iter.next()) !== $finished) {
        a.push(next);
    }
    return ArraySequence(a, this.$$targs$$);
}
Iterable$proto.$map = function(mapper) {
    var iter = this;
    return Comprehension(function() {
        var it = iter.getIterator();
        return function() {
            var e = it.next();
            if(e !== $finished) {return mapper(e);}
            return $finished;
        }
    });
}
Iterable$proto.$filter = function(select) {
    var iter = this;
    return Comprehension(function() {
        var it = iter.getIterator();
        return function() {
            do {
                var e = it.next();
            } while ((e !== $finished) && !select(e));
            return e;
        }
    });
}
Iterable$proto.fold = function(ini, accum) {
    var r = ini;
    var iter = this.getIterator();
    var e; while ((e = iter.next()) !== $finished) {
        r = accum(r, e);
    }
    return r;
}
Iterable$proto.find = function(select) {
    var iter = this.getIterator();
    var e; while ((e = iter.next()) !== $finished) {
        if (select(e)) {
            return e;
        }
    }
    return null;
}
Iterable$proto.findLast = function(select) {
    var iter = this.getIterator();
    var last = null;
    var e; while ((e = iter.next()) !== $finished) {
        if (select(e)) {
            last = e;
        }
    }
    return last;
}
Iterable$proto.$sort = function(/*Callable<Comparison?,Element,Element>*/comparing) {
    var a = [];
    var iter = this.getIterator();
    var e; while ((e = iter.next()) !== $finished) {
        a.push(e);
    }
    a.sort(function(x,y) {
        var r = comparing(x,y);
        if (r === larger) return 1;
        if (r === smaller) return -1;
        return 0;
    });
    return ArraySequence(a, this.$$targs$$);
}
Iterable$proto.any = function(/*Callable<Boolean,Element>*/selecting) {
    var iter = this.getIterator();
    var e; while ((e = iter.next()) !== $finished) {
        if (selecting(e)) {
            return true;
        }
    }
    return false;
}
Iterable$proto.$every = function(/*Callable<Boolean,Element>*/selecting) {
    var iter = this.getIterator();
    var e; while ((e = iter.next()) !== $finished) {
        if (!selecting(e)) {
            return false;
        }
    }
    return true;
}
Iterable$proto.skipping = function(skip) {
    function skip$iter(iter,skip){
        var $cmp$=new skip$iter.$$;
        Basic($cmp$);
        $cmp$.iter=iter;
        $cmp$.skip=skip;
        $cmp$.getIterator=function(){
            var iter = this.iter.getIterator();
            for (var i=0; i < this.skip; i++) {
                iter.next();
            }
            return iter;
        };
        return $cmp$;
    }
    initTypeProto(skip$iter, 'ceylon.language::SkipIterable', Basic, Iterable);
    return skip$iter(this,skip);
}
Iterable$proto.taking = function(take) {
    if (take <= 0) return empty;
    var iter = this;
    return Comprehension(function() {
        var it = iter.getIterator();
        var i = 0;
        return function() {
            if (i >= take) {return $finished;}
            ++i;
            return it.next();
        }
    });
}
Iterable$proto.by = function(step) {
    if (step == 1) return this;
    if (step < 1) throw Exception(String$("Step must be positive"));
    var iter = this;
    return Comprehension(function() {
        var it = iter.getIterator();
        return function() {
            var e = it.next();
            for (var i=1; i<step && (it.next()!==$finished); i++);
            return e;
        }
    });
}
Iterable$proto.count = function(sel) {
    var c = 0;
    var iter = this.getIterator();
    var e; while ((e = iter.next()) !== $finished) {
        if (sel(e)) c++;
    }
    return c;
}
Iterable$proto.getCoalesced = function() {
    var iter = this;
    return Comprehension(function() {
        var it = iter.getIterator();
        return function() {
            var e;
            while ((e = it.next()) === null);
            return e;
        }
    });
}
Iterable$proto.getIndexed = function() {
    var iter = this;
    return Comprehension(function() {
        var it = iter.getIterator();
        var idx = 0;
        return function() {
            var e;
            while ((e = it.next()) === null) {idx++;}
            return e === $finished ? e : Entry(idx++, e);
        }
    });
}
Iterable$proto.getLast = function() {
    var iter = this.getIterator();
    var l=null;
    var e; while ((e = iter.next()) !== $finished) {
        l=e;
    }
    return l;
}
Iterable$proto.collect = function(collecting) {
    return this.$map(collecting).getSequence();
}
Iterable$proto.select = function(selecting) {
    return this.$filter(selecting).getSequence();
}
Iterable$proto.group = function(grouping, $$$mptypes) {
    var map = HashMap();
    var it = this.getIterator();
    var elem;
    var newSeq = ArraySequence([], this.$$targs$$);
    while ((elem=it.next()) !== $finished) {
        var key = grouping(elem);
        var seq = map.put(Entry(key, newSeq, [$$$mptypes[0], {t:Sequence, a:this.$$targs$$}]), true);
        if (seq === null) {
            seq = newSeq;
            newSeq = ArraySequence([], this.$$targs$$);
        }
        seq.push(elem);
    }
    return map;
}
Iterable$proto.chain = function(other, $$$mptypes) {
    return ChainedIterable(this, other, [this.$$targs$$[0], $$$mptypes[0]]);
}
Iterable$proto.getSize = function() {
    return this.count(function() { return true; });
}
exports.Iterable=Iterable;

function ChainedIterable(first, second, $$targs$$, chained) {
    if (chained===undefined) {chained = new ChainedIterable.$$;}
    Basic(chained);
    chained.first = first;
    chained.second = second;
    chained.$$targs$$=$$targs$$;
    return chained;
}
initTypeProto(ChainedIterable, "ceylon.language::ChainedIterable",
        Basic, Iterable);
var ChainedIterable$proto = ChainedIterable.$$.prototype;
ChainedIterable$proto.getIterator = function() {
    return ChainedIterator(this.first, this.second);
}

function toTuple(iterable) {
  var seq = iterable.getSequence();
  return Tuple(seq.getFirst(), seq.getRest().getSequence(),
    [seq.$$targs$$[0], seq.$$targs$$[0], {t:Sequential, a:seq.$$targs$$}]);
}
exports.toTuple=toTuple;
<|endoftext|>


<commit_before>/*
 * Copyright 2017 Banco Bilbao Vizcaya Argentaria, S.A.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var OperationsUtils = (function() {
  'use strict';

  var stateMapping = {
    Ok: 0,
    Warn: 1,
    Error: 2
  };

  var eventMap = {};

  return {

    checkOperationMetricsToSendEvent : function(emitter, stats, config){
      var metricName = '';
      var thresholds = '';
      var description = '';
      var state;
      var color;

      var responseTimeAlertingLevels = {
        warning: config.responseTimeAlertingLevelWarning,
        error: config.responseTimeAlertingLevelError
      };
      var errorsRateAlertingLevels = {
        warning: config.errorsRateAlertingLevelWarning,
        error: config.errorsRateAlertingLevelError
      };
      var availabilityRateAlertingLevels = {
        warning: config.availabilityRateAlertingLevelWarning,
        error: config.availabilityRateAlertingLevelError
      };
      var responseTimeState = OperationsUtils.getMetricState(stats.responseTime, responseTimeAlertingLevels);
      var errorsRateState = OperationsUtils.getMetricState(stats.errorsRate, errorsRateAlertingLevels);
      var availabilityRateState = OperationsUtils.getMetricStateInverse(stats.availabilityRate, availabilityRateAlertingLevels, true);

      if(errorsRateState == stateMapping.Ok && responseTimeState == stateMapping.Ok && availabilityRateState == stateMapping.Ok){

        if(eventMap[emitter]){
          metricName = 'Errors rate, response time & availability rate';
          description = 'Values have returned below the thresholds (' + errorsRateAlertingLevels.warning + ', ' + responseTimeAlertingLevels.warning + ', ' + availabilityRateAlertingLevels.warning + ' )';
          state = Math.max(errorsRateState, responseTimeState, availabilityRateState);
          color = state == stateMapping.Error ? 'red' : state == stateMapping.Warn ? 'yellow' : 'blue';

          OperationsUtils.sendEvent(emitter, metricName, description, color);
        }

      } else {

        if(availabilityRateState == stateMapping.Warn || availabilityRateState == stateMapping.Error){
          metricName = 'Availability rate';
          thresholds = availabilityRateState == stateMapping.Warn ? availabilityRateAlertingLevels.warning : availabilityRateAlertingLevels.error;
          description = 'Less than the threshold (' + thresholds + ')';
        } else if(errorsRateState == stateMapping.Warn || errorsRateState == stateMapping.Error){
          metricName = 'Errors rate';
          thresholds = errorsRateState == stateMapping.Warn ? errorsRateAlertingLevels.warning : errorsRateAlertingLevels.error;
          description = 'Greater than the threshold (' + thresholds + ')';
        } else if(responseTimeState == stateMapping.Warn || responseTimeState == stateMapping.Error){
          metricName = metricName === '' ? 'Response time' : metricName + ' and response time';
          thresholds = thresholds === '' ? '' : thresholds + ' and ';
          thresholds = thresholds + (responseTimeState == stateMapping.Warn ? responseTimeAlertingLevels.warning : responseTimeAlertingLevels.error);
          description = 'Greater than the threshold (' + thresholds + ')';
        }

        state = Math.max(errorsRateState, responseTimeState, availabilityRateState);
        color = state == stateMapping.Error ? 'red' : state == stateMapping.Warn ? 'yellow' : 'blue';

        OperationsUtils.sendEvent(emitter, metricName, description, color);
      }
    },

    getMetricState: function(metric, metricRateAlertingLevels){
      return metric === undefined || metric <= metricRateAlertingLevels.warning ? stateMapping.Ok
              : metric <= metricRateAlertingLevels.error ? stateMapping.Warn
              : stateMapping.Error;
    },

    getMetricStateInverse: function(metric, metricRateAlertingLevels){
      return metric === undefined || metric >= metricRateAlertingLevels.warning ? stateMapping.Ok
              : metric >= metricRateAlertingLevels.error ? stateMapping.Warn
              : stateMapping.Error;
    },

    getComponentState: function(metrics, responseTimeAlertingLevels, errorsRateAlertingLevels, availabilityRateAlertingLevels){
      return Math.max(OperationsUtils.getMetricState(metrics.responseTime, responseTimeAlertingLevels), OperationsUtils.getMetricState(metrics.errorsRate, errorsRateAlertingLevels), OperationsUtils.getMetricStateInverse(metrics.availabilityRate, availabilityRateAlertingLevels));
    },

    getStats: function (metrics, infraCost) {
      var metricsMap = {};

      metrics.forEach(function(metric) {
        if(metricsMap[metric.name] === undefined) {
          metricsMap[metric.name] = {
            oneDayValue: 0,
            oneDaySampleSize: 0,
            sevenDaysValue: 0,
            sevenDaysSampleSize: 0,
            tendency: undefined
          };
        }

        metricsMap[metric.name].oneDayValue = metric.oneDayValue ? metricsMap[metric.name].oneDayValue + parseFloat(metric.oneDayValue) : parseFloat(metricsMap[metric.name].oneDayValue);
        metricsMap[metric.name].oneDaySampleSize = metric.oneDaySampleSize ? metricsMap[metric.name].oneDaySampleSize + parseInt(metric.oneDaySampleSize) : parseInt(metricsMap[metric.name].oneDaySampleSize);
        metricsMap[metric.name].sevenDaysValue = metric.sevenDaysValue ? metricsMap[metric.name].sevenDaysValue + parseFloat(metric.sevenDaysValue) : parseFloat(metricsMap[metric.name].sevenDaysValue);
        metricsMap[metric.name].sevenDaysSampleSize = metric.sevenDaysSampleSize ? metricsMap[metric.name].sevenDaysSampleSize + parseInt(metric.sevenDaysSampleSize) : parseInt(metricsMap[metric.name].sevenDaysSampleSize);
      });

      for (var metric in metricsMap) {
        var tendencyChange = metricsMap[metric].oneDaySampleSize ? Utils.getPercentageDifference(metricsMap[metric].sevenDaysValue / metricsMap[metric].sevenDaysSampleSize || 0, metricsMap[metric].oneDayValue / metricsMap[metric].oneDaySampleSize || 0) : undefined;
        if(tendencyChange !== undefined) {
          if(metric === 'errorsNumber' || metric === 'responseTime' || metric === 'infrastructureCost' ) {
            metricsMap[metric].tendency = tendencyChange < -10 ? 'threedown-green' : tendencyChange < -5 ? 'twodown-green' : tendencyChange < -1 ? 'onedown-green' : tendencyChange > 10 ? 'threeup-red' : tendencyChange > 5 ? 'twoup-red' : tendencyChange > 1 ? 'oneup-red' : 'eq';
          } else {
            metricsMap[metric].tendency = tendencyChange < -10 ? 'threedown' : tendencyChange < -5 ? 'twodown' : tendencyChange < -1 ? 'onedown' : tendencyChange > 10 ? 'threeup' : tendencyChange > 5 ? 'twoup' : tendencyChange > 1 ? 'oneup' : 'eq';
          }
        }
      }

      var stats = {
        requestsNumber: metricsMap.requestsNumber && metricsMap.requestsNumber.oneDaySampleSize > 0 ? metricsMap.requestsNumber.oneDayValue : undefined,
        requestsNumberTendency: metricsMap.requestsNumber && metricsMap.requestsNumber.oneDaySampleSize > 0 ? metricsMap.requestsNumber.tendency : undefined,
        errorsRate: metricsMap.errorsNumber && metricsMap.requestsNumber && metricsMap.requestsNumber.oneDayValue > 0 ? parseFloat((100 * metricsMap.errorsNumber.oneDayValue / metricsMap.requestsNumber.oneDayValue || 0).toFixed(2)) : undefined,
        errorsRateTendency: metricsMap.errorsNumber && metricsMap.errorsNumber.oneDaySampleSize > 0 ? metricsMap.errorsNumber.tendency : undefined,
        availabilityRate: metricsMap.availabilityRate && metricsMap.availabilityRate.oneDaySampleSize > 0 ? parseFloat((metricsMap.availabilityRate.oneDayValue / metricsMap.availabilityRate.oneDaySampleSize).toFixed(2)) : undefined,
        availabilityRateTendency: metricsMap.availabilityRate &&  metricsMap.availabilityRate.oneDaySampleSize > 0 ? metricsMap.availabilityRate.tendency : undefined,
        responseTime: metricsMap.responseTime && metricsMap.responseTime.oneDaySampleSize > 0 ? parseFloat((metricsMap.responseTime.oneDayValue / metricsMap.responseTime.oneDaySampleSize).toFixed(2)) : undefined,
        responseTimeTendency: metricsMap.responseTime && metricsMap.responseTime.oneDaySampleSize > 0 ? metricsMap.responseTime.tendency : undefined,
        infraCost: infraCost && metricsMap.infrastructureCost ? parseFloat(metricsMap.infrastructureCost.oneDayValue.toFixed(2)) : undefined,
        infraCostTendency: infraCost && metricsMap.infrastructureCost ? metricsMap.infrastructureCost.tendency : undefined
      };

      return Object.values(stats).some(function(metric) {
        return metric !== undefined;
      }) ? stats : undefined;
    },

    getMetricsGroupByViewId: function(metrics, config) {
      var metricsMap = {};
      var metricsGroup = [];

      metrics.forEach(function(metric) {
        if(!metricsMap[metric.viewId]) {
          metricsMap[metric.viewId] = new Array(metric);
        } else {
          metricsMap[metric.viewId].push(metric);
        }
      });

      for (var viewId in metricsMap) {
        var stats = OperationsUtils.getStats(metricsMap[viewId], config.infraCost);

        if(stats) {
          metricsGroup.push(JSON.stringify({
            stats: stats,
            viewId: viewId,
            responseTimeAlertingLevelWarning: config.responseTimeAlertingLevelWarning,
            responseTimeAlertingLevelError: config.responseTimeAlertingLevelError,
            errorsRateAlertingLevelWarning: config.errorsRateAlertingLevelWarning,
            errorsRateAlertingLevelError: config.errorsRateAlertingLevelError,
            availabilityRateAlertingLevelWarning: config.availabilityRateAlertingLevelWarning,
            availabilityRateAlertingLevelError: config.availabilityRateAlertingLevelError
          }));
        }
      }

      return metricsGroup;
    },

    sendEvent: function(emitter, metricName, description, color){
      var event =  {
        detail: {
          emitter: emitter,
          title: metricName,
          dashboard: Utils.getDashboardId(),
          description: emitter + ' - ' + description,
          date: new Date(),
          url: '',
          color: color
        }
      };
      if(!eventMap[emitter] || eventMap[emitter].title !== event.detail.title || eventMap[emitter].description !== event.detail.description || eventMap[emitter].color !== event.detail.color) {
        eventMap[emitter] = {
          emitter: event.detail.title,
          title: event.detail.title,
          description: event.detail.description,
          color: event.detail.color
        };
        document.dispatchEvent(new CustomEvent('HeadsUp', event));
      }
    }

  };

})();
<commit_msg>feat(operations): sort operations resources by id<commit_after>/*
 * Copyright 2017 Banco Bilbao Vizcaya Argentaria, S.A.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var OperationsUtils = (function() {
  'use strict';

  var stateMapping = {
    Ok: 0,
    Warn: 1,
    Error: 2
  };

  var eventMap = {};

  return {

    checkOperationMetricsToSendEvent : function(emitter, stats, config){
      var metricName = '';
      var thresholds = '';
      var description = '';
      var state;
      var color;

      var responseTimeAlertingLevels = {
        warning: config.responseTimeAlertingLevelWarning,
        error: config.responseTimeAlertingLevelError
      };
      var errorsRateAlertingLevels = {
        warning: config.errorsRateAlertingLevelWarning,
        error: config.errorsRateAlertingLevelError
      };
      var availabilityRateAlertingLevels = {
        warning: config.availabilityRateAlertingLevelWarning,
        error: config.availabilityRateAlertingLevelError
      };
      var responseTimeState = OperationsUtils.getMetricState(stats.responseTime, responseTimeAlertingLevels);
      var errorsRateState = OperationsUtils.getMetricState(stats.errorsRate, errorsRateAlertingLevels);
      var availabilityRateState = OperationsUtils.getMetricStateInverse(stats.availabilityRate, availabilityRateAlertingLevels, true);

      if(errorsRateState == stateMapping.Ok && responseTimeState == stateMapping.Ok && availabilityRateState == stateMapping.Ok){

        if(eventMap[emitter]){
          metricName = 'Errors rate, response time & availability rate';
          description = 'Values have returned below the thresholds (' + errorsRateAlertingLevels.warning + ', ' + responseTimeAlertingLevels.warning + ', ' + availabilityRateAlertingLevels.warning + ' )';
          state = Math.max(errorsRateState, responseTimeState, availabilityRateState);
          color = state == stateMapping.Error ? 'red' : state == stateMapping.Warn ? 'yellow' : 'blue';

          OperationsUtils.sendEvent(emitter, metricName, description, color);
        }

      } else {

        if(availabilityRateState == stateMapping.Warn || availabilityRateState == stateMapping.Error){
          metricName = 'Availability rate';
          thresholds = availabilityRateState == stateMapping.Warn ? availabilityRateAlertingLevels.warning : availabilityRateAlertingLevels.error;
          description = 'Less than the threshold (' + thresholds + ')';
        } else if(errorsRateState == stateMapping.Warn || errorsRateState == stateMapping.Error){
          metricName = 'Errors rate';
          thresholds = errorsRateState == stateMapping.Warn ? errorsRateAlertingLevels.warning : errorsRateAlertingLevels.error;
          description = 'Greater than the threshold (' + thresholds + ')';
        } else if(responseTimeState == stateMapping.Warn || responseTimeState == stateMapping.Error){
          metricName = metricName === '' ? 'Response time' : metricName + ' and response time';
          thresholds = thresholds === '' ? '' : thresholds + ' and ';
          thresholds = thresholds + (responseTimeState == stateMapping.Warn ? responseTimeAlertingLevels.warning : responseTimeAlertingLevels.error);
          description = 'Greater than the threshold (' + thresholds + ')';
        }

        state = Math.max(errorsRateState, responseTimeState, availabilityRateState);
        color = state == stateMapping.Error ? 'red' : state == stateMapping.Warn ? 'yellow' : 'blue';

        OperationsUtils.sendEvent(emitter, metricName, description, color);
      }
    },

    getMetricState: function(metric, metricRateAlertingLevels){
      return metric === undefined || metric <= metricRateAlertingLevels.warning ? stateMapping.Ok
              : metric <= metricRateAlertingLevels.error ? stateMapping.Warn
              : stateMapping.Error;
    },

    getMetricStateInverse: function(metric, metricRateAlertingLevels){
      return metric === undefined || metric >= metricRateAlertingLevels.warning ? stateMapping.Ok
              : metric >= metricRateAlertingLevels.error ? stateMapping.Warn
              : stateMapping.Error;
    },

    getComponentState: function(metrics, responseTimeAlertingLevels, errorsRateAlertingLevels, availabilityRateAlertingLevels){
      return Math.max(OperationsUtils.getMetricState(metrics.responseTime, responseTimeAlertingLevels), OperationsUtils.getMetricState(metrics.errorsRate, errorsRateAlertingLevels), OperationsUtils.getMetricStateInverse(metrics.availabilityRate, availabilityRateAlertingLevels));
    },

    getStats: function (metrics, infraCost) {
      var metricsMap = {};

      metrics.forEach(function(metric) {
        if(metricsMap[metric.name] === undefined) {
          metricsMap[metric.name] = {
            oneDayValue: 0,
            oneDaySampleSize: 0,
            sevenDaysValue: 0,
            sevenDaysSampleSize: 0,
            tendency: undefined
          };
        }

        metricsMap[metric.name].oneDayValue = metric.oneDayValue ? metricsMap[metric.name].oneDayValue + parseFloat(metric.oneDayValue) : parseFloat(metricsMap[metric.name].oneDayValue);
        metricsMap[metric.name].oneDaySampleSize = metric.oneDaySampleSize ? metricsMap[metric.name].oneDaySampleSize + parseInt(metric.oneDaySampleSize) : parseInt(metricsMap[metric.name].oneDaySampleSize);
        metricsMap[metric.name].sevenDaysValue = metric.sevenDaysValue ? metricsMap[metric.name].sevenDaysValue + parseFloat(metric.sevenDaysValue) : parseFloat(metricsMap[metric.name].sevenDaysValue);
        metricsMap[metric.name].sevenDaysSampleSize = metric.sevenDaysSampleSize ? metricsMap[metric.name].sevenDaysSampleSize + parseInt(metric.sevenDaysSampleSize) : parseInt(metricsMap[metric.name].sevenDaysSampleSize);
      });

      for (var metric in metricsMap) {
        var tendencyChange = metricsMap[metric].oneDaySampleSize ? Utils.getPercentageDifference(metricsMap[metric].sevenDaysValue / metricsMap[metric].sevenDaysSampleSize || 0, metricsMap[metric].oneDayValue / metricsMap[metric].oneDaySampleSize || 0) : undefined;
        if(tendencyChange !== undefined) {
          if(metric === 'errorsNumber' || metric === 'responseTime' || metric === 'infrastructureCost' ) {
            metricsMap[metric].tendency = tendencyChange < -10 ? 'threedown-green' : tendencyChange < -5 ? 'twodown-green' : tendencyChange < -1 ? 'onedown-green' : tendencyChange > 10 ? 'threeup-red' : tendencyChange > 5 ? 'twoup-red' : tendencyChange > 1 ? 'oneup-red' : 'eq';
          } else {
            metricsMap[metric].tendency = tendencyChange < -10 ? 'threedown' : tendencyChange < -5 ? 'twodown' : tendencyChange < -1 ? 'onedown' : tendencyChange > 10 ? 'threeup' : tendencyChange > 5 ? 'twoup' : tendencyChange > 1 ? 'oneup' : 'eq';
          }
        }
      }

      var stats = {
        requestsNumber: metricsMap.requestsNumber && metricsMap.requestsNumber.oneDaySampleSize > 0 ? metricsMap.requestsNumber.oneDayValue : undefined,
        requestsNumberTendency: metricsMap.requestsNumber && metricsMap.requestsNumber.oneDaySampleSize > 0 ? metricsMap.requestsNumber.tendency : undefined,
        errorsRate: metricsMap.errorsNumber && metricsMap.requestsNumber && metricsMap.requestsNumber.oneDayValue > 0 ? parseFloat((100 * metricsMap.errorsNumber.oneDayValue / metricsMap.requestsNumber.oneDayValue || 0).toFixed(2)) : undefined,
        errorsRateTendency: metricsMap.errorsNumber && metricsMap.errorsNumber.oneDaySampleSize > 0 ? metricsMap.errorsNumber.tendency : undefined,
        availabilityRate: metricsMap.availabilityRate && metricsMap.availabilityRate.oneDaySampleSize > 0 ? parseFloat((metricsMap.availabilityRate.oneDayValue / metricsMap.availabilityRate.oneDaySampleSize).toFixed(2)) : undefined,
        availabilityRateTendency: metricsMap.availabilityRate &&  metricsMap.availabilityRate.oneDaySampleSize > 0 ? metricsMap.availabilityRate.tendency : undefined,
        responseTime: metricsMap.responseTime && metricsMap.responseTime.oneDaySampleSize > 0 ? parseFloat((metricsMap.responseTime.oneDayValue / metricsMap.responseTime.oneDaySampleSize).toFixed(2)) : undefined,
        responseTimeTendency: metricsMap.responseTime && metricsMap.responseTime.oneDaySampleSize > 0 ? metricsMap.responseTime.tendency : undefined,
        infraCost: infraCost && metricsMap.infrastructureCost ? parseFloat(metricsMap.infrastructureCost.oneDayValue.toFixed(2)) : undefined,
        infraCostTendency: infraCost && metricsMap.infrastructureCost ? metricsMap.infrastructureCost.tendency : undefined
      };

      return Object.values(stats).some(function(metric) {
        return metric !== undefined;
      }) ? stats : undefined;
    },

    getMetricsGroupByViewId: function(metrics, config) {
      var metricsMap = {};
      var metricsGroup = [];

      metrics.forEach(function(metric) {
        if(!metricsMap[metric.viewId]) {
          metricsMap[metric.viewId] = new Array(metric);
        } else {
          metricsMap[metric.viewId].push(metric);
        }
      });

      for (var viewId in metricsMap) {
        var stats = OperationsUtils.getStats(metricsMap[viewId], config.infraCost);

        if(stats) {
          metricsGroup.push({
            stats: stats,
            viewId: viewId,
            responseTimeAlertingLevelWarning: config.responseTimeAlertingLevelWarning,
            responseTimeAlertingLevelError: config.responseTimeAlertingLevelError,
            errorsRateAlertingLevelWarning: config.errorsRateAlertingLevelWarning,
            errorsRateAlertingLevelError: config.errorsRateAlertingLevelError,
            availabilityRateAlertingLevelWarning: config.availabilityRateAlertingLevelWarning,
            availabilityRateAlertingLevelError: config.availabilityRateAlertingLevelError
          });
        }
      }

      return metricsGroup
        .sort(function(m1, m2) {
          var id1 = m1.viewId.toUpperCase(); // ignore upper and lowercase
          var id2 = m2.viewId.toUpperCase(); // ignore upper and lowercase
          if (id1 < id2) {
            return -1;
          }
          if (id1 > id2) {
            return 1;
          }
          return 0;
        })
        .map(function(metric) {
          return JSON.stringify(metric);
        });
    },

    sendEvent: function(emitter, metricName, description, color){
      var event =  {
        detail: {
          emitter: emitter,
          title: metricName,
          dashboard: Utils.getDashboardId(),
          description: emitter + ' - ' + description,
          date: new Date(),
          url: '',
          color: color
        }
      };
      if(!eventMap[emitter] || eventMap[emitter].title !== event.detail.title || eventMap[emitter].description !== event.detail.description || eventMap[emitter].color !== event.detail.color) {
        eventMap[emitter] = {
          emitter: event.detail.title,
          title: event.detail.title,
          description: event.detail.description,
          color: event.detail.color
        };
        document.dispatchEvent(new CustomEvent('HeadsUp', event));
      }
    }

  };

})();
<|endoftext|>


<commit_before>module.exports = callback => {
    var proxy = {
        enable: false,
        server: {
            http: process.env.HTTP_PROXY || '',
            https: process.env.HTTPS_PROXY || '',
            ftp: '',
            socks: ''
        }
    }

    proxy.enable = Object.keys(proxy.server).map(k => proxy.server[k]).join('').length > 0
    return callback(null, proxy)
}
<commit_msg>Fix: Add support for FTP_PROXY and SOCKS_PROXY env on linux<commit_after>module.exports = callback => {
    var proxy = {
        enable: false,
        server: {
            http: process.env.HTTP_PROXY || '',
            https: process.env.HTTPS_PROXY || '',
            ftp: process.env.FTP_PROXY || '',
            socks: process.env.SOCKS_PROXY || ''
        }
    }

    proxy.enable = Object.keys(proxy.server).map(k => proxy.server[k]).join('').length > 0
    return callback(null, proxy)
}
<|endoftext|>