<commit_before>(function () {

  angular.module('settings', []).directive('settingsPage', function () {
    return {
      restrict: 'E',
      templateUrl: 'app/frontend/view/content/settings-page.html',

      controller: function ($scope) {
        this.showSettingsPage = false;
        this.hidePage = true;
        this.fonts = [
          'Comic Sans MS',
          'Ubuntu',
          'Droid Sans',
          'Roboto'
        ];
        this.selectedRepository = null;
        this.globalGitConfigs = {
          'user.name': '',
          'user.email': ''
        };

        this.hideSettingsPage = function () {
          this.showSettingsPage = false;

          setTimeout(function () {
            this.hidePage = true;
            applyScope($scope);
          }.bind(this), 500);
        };

        this.getGlobalGitConfigs = function () {
          GIT.getGlobalConfigs(function (err, configs) {

            if (err) {
              alert(err.message);
            } else {
              this.globalGitConfigs = configs;
            }
          }.bind(this));
        };

        $scope.$root.showSettingsPage = function () {
          this.hidePage = false;

          setTimeout(function () {
            this.showSettingsPage = true;
            applyScope($scope);
          }.bind(this), 200);
        }.bind(this);

        // Attemp to get the global git configs on load the application
        this.getGlobalGitConfigs();

        this.changeGitCofigs = function (global, event) {
          var username,
            email,
            repositoryPath;

          if (global) {
            username = this.globalGitConfigs['user.name'];
            email = this.globalGitConfigs['user.email'];
          } else {
            username = this.localGitConfigs['user.name'];
            email = this.localGitConfigs['user.email'];
            repositoryPath = this.selectedRepository.path;
          }

          event.target.setAttribute('disabled', true);

          GIT.alterGitConfig(repositoryPath, {
            global: global,
            username: username,
            email: email,
            callback: function (err) {

              if (err) {
                alert(err);
              }

              event.target.removeAttribute('disabled');
            }
          });
        };

        $scope.$on('repositorychanged', function (event, repository) {
          this.selectedRepository = repository;
          this.selectedRepository.usingSSH = false;

          GIT.listRemotes(repository.path, function (err, remotesList) {

            if (err) {
              alert(err.message);
            } else {
              var GitUrlParse = require('./node_modules/git-url-parse'),
                repoSettings = GitUrlParse(remotesList.origin.push);

              if (repoSettings.protocol == 'ssh') {
                this.selectedRepository.usingSSH = true;
              }
            }
          }.bind(this));

          this.getGlobalGitConfigs();

          GIT.getLocalConfigs(this.selectedRepository.path, function (err, configs) {

            if (err) {
              this.localGitConfigs = {
                'user.name': '',
                'user.email': ''
              };
              alert(err.message);
            } else {
              this.localGitConfigs = configs;
            }
          }.bind(this));

        }.bind(this));

        $scope.$on('removedRepository', function () {
          this.selectedRepository = null;
        }.bind(this));
      },

      controllerAs: 'settingsCtrl'
    };
  });
})();
<commit_msg>:bug: Fixed isSsh to fresh created repositories<commit_after>(function () {

  angular.module('settings', []).directive('settingsPage', function () {
    return {
      restrict: 'E',
      templateUrl: 'app/frontend/view/content/settings-page.html',

      controller: function ($scope) {
        this.showSettingsPage = false;
        this.hidePage = true;
        this.fonts = [
          'Comic Sans MS',
          'Ubuntu',
          'Droid Sans',
          'Roboto'
        ];
        this.selectedRepository = null;
        this.globalGitConfigs = {
          'user.name': '',
          'user.email': ''
        };

        this.hideSettingsPage = function () {
          this.showSettingsPage = false;

          setTimeout(function () {
            this.hidePage = true;
            applyScope($scope);
          }.bind(this), 500);
        };

        this.getGlobalGitConfigs = function () {
          GIT.getGlobalConfigs(function (err, configs) {

            if (err) {
              alert(err.message);
            } else {
              this.globalGitConfigs = configs;
            }
          }.bind(this));
        };

        $scope.$root.showSettingsPage = function () {
          this.hidePage = false;

          setTimeout(function () {
            this.showSettingsPage = true;
            applyScope($scope);
          }.bind(this), 200);
        }.bind(this);

        // Attemp to get the global git configs on load the application
        this.getGlobalGitConfigs();

        this.changeGitCofigs = function (global, event) {
          var username,
            email,
            repositoryPath;

          if (global) {
            username = this.globalGitConfigs['user.name'];
            email = this.globalGitConfigs['user.email'];
          } else {
            username = this.localGitConfigs['user.name'];
            email = this.localGitConfigs['user.email'];
            repositoryPath = this.selectedRepository.path;
          }

          event.target.setAttribute('disabled', true);

          GIT.alterGitConfig(repositoryPath, {
            global: global,
            username: username,
            email: email,
            callback: function (err) {

              if (err) {
                alert(err);
              }

              event.target.removeAttribute('disabled');
            }
          });
        };

        $scope.$on('repositorychanged', function (event, repository) {
          this.selectedRepository = repository;
          this.selectedRepository.usingSSH = false;

          GIT.listRemotes(repository.path, function (err, remotesList) {

            if (err) {
              alert(err.message);
            } else if (remotesList.origin) {
              var GitUrlParse = require('git-url-parse'),
                repoSettings = GitUrlParse(remotesList.origin.push);

              if (repoSettings.protocol == 'ssh') {
                this.selectedRepository.usingSSH = true;
              }
            }
          }.bind(this));

          this.getGlobalGitConfigs();

          GIT.getLocalConfigs(this.selectedRepository.path, function (err, configs) {

            if (err) {
              this.localGitConfigs = {
                'user.name': '',
                'user.email': ''
              };
              alert(err.message);
            } else {
              this.localGitConfigs = configs;
            }
          }.bind(this));

        }.bind(this));

        $scope.$on('removedRepository', function () {
          this.selectedRepository = null;
        }.bind(this));
      },

      controllerAs: 'settingsCtrl'
    };
  });
})();
<|endoftext|>


<commit_before>/*global Hammer*/
import Ember from 'ember';
import camelize from 'ember-allpurpose/string/dasherized-to-camel';
import capitalize from 'ember-allpurpose/string/capitalize-word';

const {
  Service,
  set: set,
  RSVP
  } = Ember;

const {
  Promise
  } = RSVP;

export default Service.extend({

  _recognizers: null,

  retrieve(names) {
    let promises = names.map((name) => { return this.lookupRecognizer(name); });
    return RSVP.all(promises);
  },

  makeRecognizer(name, details) {

    let eventName = details.includeEvents ? camelize(name).toLowerCase() : details.recognizer;
    let gesture = capitalize(details.recognizer);

    let options = details.options || {};
    options.event = eventName;

    let Recognizer = new Hammer[gesture](options);
    this.registerRecognizer(name, Recognizer);

    if (details.include) {
      let included = details.include.map((name) => {
        return this.lookupRecognizer(name);
      });

      RSVP.all(included).then((recognizers) => {
        Recognizer.recognizeWith(recognizers);
      });

    }

    if (details.exclude) {
      let excluded = details.exclude.map((name) => {
        return this.lookupRecognizer(name);
      });

      RSVP.all(excluded).then((recognizers) => {
        Recognizer.requireFailure(recognizers);
      });

    }

    return Recognizer;

  },

  lookupRecognizer(name) {
    return new Promise((resolve, reject) => {
      let recognizer = this.get(`_recognizers.${name}`);
      if (recognizer) {
        resolve(recognizer);
        return;
      }

      let path = `ember-gesture:recognizers/${name}`;
      let details = this.container.lookupFactory(path);
      if (details) {
        resolve(this.makeRecognizer(name, details));
        return;
      }

      reject(`ember-gestures/recognizers/${name} was not found. You can scaffold this recognizer with 'ember g recognizer ${name}'`);

    });
  },

  registerRecognizer(name, Recognizer) {
    let registry = this.get('_recognizers');
    set(registry, name, Recognizer);
  },

  init() {
    this._super();
    this.set('_recognizers', {});
  }

});
<commit_msg>explicit eventName API<commit_after>/*global Hammer*/
import Ember from 'ember';
import camelize from 'ember-allpurpose/string/dasherized-to-camel';
import capitalize from 'ember-allpurpose/string/capitalize-word';

const {
  Service,
  set,
  RSVP
} = Ember;

const {
  Promise  // jshint ignore:line
} = RSVP;

export default Service.extend({

  _recognizers: null,

  retrieve(names) {
    let promises = names.map((name) => { return this.lookupRecognizer(name); });
    return RSVP.all(promises);
  },

  makeRecognizer(name, details) {
    const eventName = details.eventName || camelize(name).toLowerCase();
    const gesture = capitalize(details.recognizer);

    const options = details.options || {};
    options.event = eventName;

    const Recognizer = new Hammer[gesture](options);
    this.registerRecognizer(name, Recognizer);

    if (details.include) {
      let included = details.include.map((name) => {
        return this.lookupRecognizer(name);
      });

      RSVP.all(included).then((recognizers) => {
        Recognizer.recognizeWith(recognizers);
      });

    }

    if (details.exclude) {
      let excluded = details.exclude.map((name) => {
        return this.lookupRecognizer(name);
      });

      RSVP.all(excluded).then((recognizers) => {
        Recognizer.requireFailure(recognizers);
      });

    }

    return Recognizer;

  },

  lookupRecognizer(name) {
    return new Promise((resolve, reject) => {
      let recognizer = this.get(`_recognizers.${name}`);
      if (recognizer) {
        resolve(recognizer);
        return;
      }

      let path = `ember-gesture:recognizers/${name}`;
      let details = this.container.lookupFactory(path);
      if (details) {
        resolve(this.makeRecognizer(name, details));
        return;
      }

      reject(`ember-gestures/recognizers/${name} was not found. You can scaffold this recognizer with 'ember g recognizer ${name}'`);

    });
  },

  registerRecognizer(name, Recognizer) {
    let registry = this.get('_recognizers');
    set(registry, name, Recognizer);
  },

  init() {
    this._super();
    this.set('_recognizers', {});
  }

});
<|endoftext|>


<commit_before>var helper = require(__dirname+'/test-helper');
var client = helper.client();

test("empty query message handling", function() {
  client.query("");
  assert.emits(client, 'drain', function() {
    client.end.bind(client);
  })
});
<commit_msg>fix test failure<commit_after>var helper = require(__dirname+'/test-helper');
var client = helper.client();

test("empty query message handling", function() {
  assert.emits(client, 'drain', function() {
    client.end();
  });
  client.query("");
});
<|endoftext|>


<commit_before>"use strict";

function randomIntInc (low, high) {
    return Math.floor(Math.random() * (high - low + 1) + low);
}

var firebase = require('firebase');
firebase.initializeApp({
  serviceAccount: "../credentials.json",
  databaseURL: "https://sgdq-backend.firebaseio.com"
});
var data_ref = firebase.database().ref("data");

var start = new Date("9:30:00 July 3, 2016")
var end   = new Date("21:18:00 July 9, 2016")

var payload = {}
var i = 0, v = 10000;
while(start < end) {
    start.setMinutes(start.getMinutes() + 1)
    // console.log(start)
    i = i + randomIntInc(0, 1000)
    v = v + randomIntInc(-100, 100);
    payload[start.getTime()] = {
        m: i,
        d: 2,
        v: v,
    }
}

data_ref.set(payload).then(function(){
    process.exit();
});<commit_msg>Extras test data<commit_after>"use strict";

function randomIntInc (low, high) {
    return Math.floor(Math.random() * (high - low + 1) + low);
}

var firebase = require('firebase');
firebase.initializeApp({
  serviceAccount: "../credentials.json",
  databaseURL: "https://sgdq-backend.firebaseio.com"
});
var data_ref = firebase.database().ref("data");
var extras_ref = firebase.database().ref("extras");

var start = new Date("9:30:00 July 3, 2016")
var end   = new Date("21:18:00 July 9, 2016")

var payload = {}
var extrasPayload = {}
var i = 0, v = 10000;
while(start < end) {
    start.setMinutes(start.getMinutes() + 1)
    // console.log(start)
    i = i + randomIntInc(0, 1000)
    v = v + randomIntInc(-100, 100);
    payload[start.getTime()] = {
        m: i,
        d: 2,
        v: v,
    }
    extrasPayload[start.getTime()] = {
        t: randomIntInc(120, 460),
        e: randomIntInc(150, 1550),
        c: randomIntInc(250, 1250)
    }
}

data_ref.set(payload).then(function(){
    console.log("Data payload done.");
    extras_ref.set(extrasPayload).then(function() {
        console.log("Extras payload done.");
        process.exit();
    });
});<|endoftext|>


<commit_before>define(function () {
	function meta (data) {
		var ext = data["extends"],
			mixin = data.mixin;
		if (ext) {
			data["extends"] = get(ext);
		}
		if (mixin) {
			data.mixin = get(mixin);
		}
		return data;
	}

	function get (key) {
		var value;
		if (isIdentifier(key)) {
			try {
				value = globalEval(key);
			} catch (ignore) {}
		}
		if (isUndefined(value)) {
			try {
				value = require(key);
			} catch (ignore) {}
		}
		if (isUndefined(value)) {
			throw "Unable to get the value of "+ key;
		}
	}

	function isUndefined (value) {
		return typeof value === "undefined";
	}

	isIdentifier.identifier = /^(?!(?:\.|$))(?:(?:\.(?!$))?[_$a-zA-Z]+[_$a-zA-Z0-9]*)+$/;

	function isIdentifier (key) {
		return isIdentifier.identifier.test(key);
	}

	function globalEval (key) {
		var getter = new Function("return "+ key +";");
		return getter();
	}

	meta({
		"entity": "module",
		"description": "Runtime shim for meta()",
		"export": "function"
	});

	meta({
		"entity": "function",
		"name": "meta",
		"arguments": [{
			"name": "data",
			"type": "object",
			"description": "Must be written as valid JSON including quoted key names. This allows meta to be extracted and parsed by documentation systems."
		}],
		"return": {
			"type": "object",
			"description": "The data the was passed in"
		}
	});

	return meta;
});
<commit_msg>returning value from get<commit_after>define(function () {
	function meta (data) {
		var ext = data["extends"],
			mixin = data.mixin;
		if (ext) {
			data["extends"] = get(ext);
		}
		if (mixin) {
			data.mixin = get(mixin);
		}
		return data;
	}

	function get (key) {
		var value;
		if (isIdentifier(key)) {
			try {
				value = globalEval(key);
			} catch (ignore) {}
		}
		if (isUndefined(value)) {
			try {
				value = require(key);
			} catch (ignore) {}
		}
		if (isUndefined(value)) {
			throw "Unable to get the value of "+ key;
		}
		return value;
	}

	function isUndefined (value) {
		return typeof value === "undefined";
	}

	isIdentifier.identifier = /^(?!(?:\.|$))(?:(?:\.(?!$))?[_$a-zA-Z]+[_$a-zA-Z0-9]*)+$/;

	function isIdentifier (key) {
		return isIdentifier.identifier.test(key);
	}

	function globalEval (key) {
		var getter = new Function("return "+ key +";");
		return getter();
	}

	meta({
		"entity": "module",
		"description": "Runtime shim for meta()",
		"export": "function"
	});

	meta({
		"entity": "function",
		"name": "meta",
		"arguments": [{
			"name": "data",
			"type": "object",
			"description": "Must be written as valid JSON including quoted key names. This allows meta to be extracted and parsed by documentation systems."
		}],
		"return": {
			"type": "object",
			"description": "The data the was passed in"
		}
	});

	return meta;
});
<|endoftext|>


<commit_before>/**
 * Binding Core Module Class
 * @class Core.Module.Binding
 * @author Jerome Vial, Bruno Santos
 */
(function(root, factory) {
	if (typeof define === 'function' && define.amd) {
		define([], factory);
	} else if (typeof exports === 'object') {
		module.exports = factory();
	} else {
		root.returnExports = factory();
	}
}(this, function() {

	var _log = __debug('core:module-binding').defineLevel();

	if (typeof define !== 'function') {
		Class = require('primish');
		Events = require('primish/emitter');
	}

	var exports = new Class({

		Implements: [Events],

		options: {
			api: {
				emit: 'trigger'
			}
		},

		/**
		 * Initialize
		 * @return {void}
		 */
		initialize: function() {
			_log.debug('initialize binding');

			var self = this;

			this.addEvent('initReady', function() {
				self._initBinding.bind(this)();
			});
		},

		/**
		 * Events communication controller
		 * Event bindings
		 * @return {Object}
		 */
		_initBinding: function(binding) {
			binding = binding || this.options.controller || this.options.binding;

			this.binding = this.binding || {};

			_log.debug('_initBinding', this.options.name, binding);

			if (!binding) {
				_log.debug('missing binding options');
				return;
			}

			if (!binding._list) {
				this._bindObject(binding);
				return;
			}

			var list = binding._list;

			//_log.debug(list, binding);

			for (var i = 0; list.length > i; i++) {
				var bind = binding[list[i]];
				this.binding = this.binding || {};

				this._bindObject(bind);
			}

			if (this.fireEvent) {
				this.fireEvent('bindingsReady');
			} else if (this.trigger) {
				this.trigger('bindingsReady');
			}

			return this.binding;
		},

		/**
		 * Bind an object
		 * @param  {Object} obj obj whit key and value to be bound
		 * @return {void}
		 */
		_bindObject: function(obj) {
			//_log.debug('_bindObject', obj);

			for (var key in obj) {
				if (!obj.hasOwnProperty(key)) {
					continue;
				}
				var value = obj[key];

				if (typeof value !== 'object') {
					this._bindkey(key, value);
				} else {
					this._bindList(key, value);
				}
			}
		},

		/**
		 * Bind a list of events to a specific object
		 * @param  {string} key Object path that will listen
		 * @param  {Array} values List if values to bind
		 * @return {void}
		 */
		_bindList: function(key, values) {
			//_log.debug('_bindList', key, values);

			for (var i = 0; i < values.length; i++) {
				this._bindkey(key, values[i]);
			}
		},

		/**
		 * Bind to object path
		 * get the event,
		 * get the reference to the last key of the first object,
		 * check if there is a event or a mehtod to bind
		 * @param  {string} key Object path that will listen
		 * @param  {string} val Object path to be bound
		 * @return {void}
		 */
		_bindkey: function(key, val) {
			//_log.debug('_bindkey', key, val);

			var eventKeys = key.split('.');
			var ev = eventKeys[eventKeys.length - 1];
			eventKeys.pop();
			var listenerCtx = this._path(eventKeys.join('.'));

			//handle obj
			var obj = this._getObj(listenerCtx, val);
			if (obj) {
				for (var newCtx in obj) {
					if (!obj.hasOwnProperty(newCtx)) {
						continue;
					}
					var newKey = eventKeys.join('.') + '.' + newCtx + '.' + ev;
					//_log.debug('_bindkey', newKey, val);
					this._bindkey(newKey, val);
				}
				return;
			}

			//handle args
			var args;
			if (typeof val === 'object') {
				for (var k in val) {
					if (!val.hasOwnProperty(k)) {
						continue;
					}
					break;
				}
				args = this._processKeyObj(k, val);
				val = k;
			}

			var valKeys = val.split('.');

			//Check if it's an event
			if (valKeys[valKeys.length - 2] === this.options.api.emit) {
				var emit = valKeys[valKeys.length - 1];
				this._bindEvent(listenerCtx, ev, emit, val);
			} else {
				this._bindMethod(listenerCtx, ev, val, args);
			}
		},

		/**
		 * Process Key Obj
		 * @param  {string} key
		 * @param  {Object} val
		 * @return {Object}
		 */
		_processKeyObj: function(key, val) {
			//_log.debug('_processKeyObj', key, val);

			var args = val[key];

			for (var i = 0; i < args.length; i++) {
				var arg = args[i];

				if (arg.split('.')[0] === 'this') {
					arg = arg.split('.');
					arg.shift();
					args[i] = this._path(arg.join('.'));
				}
			}

			return args;
		},

		/**
		 * Listen to the given event and trigger another
		 * @param  {Object} listenerCtx Object to listen
		 * @param  {string} ev Event that will be listened
		 * @param  {string} emit Event that will be emitted
		 * @param  {string} val Method path to be bound
		 * @return {void}
		 */
		_bindEvent: function(listenerCtx, ev, emit, val) {
			//_log.debug('_bindEvent', listenerCtx, ev, emit, val);

			var emitter = this.options.api.emit;

			var valKeys = val.split('.');
			var save = valKeys[valKeys.length - 1];
			valKeys.splice(-2, 2);
			var boundCtx = this._path(valKeys.join('.'));

			//handle obj
			var obj = this._getObj(boundCtx, val);
			if (obj) {
				for (var newCtx in obj) {
					if (!obj.hasOwnProperty(newCtx)) {
						continue;
					}
					var newKey = valKeys.join('.') + '.' + newCtx + '.' + emitter + '.' + save;
					//_log.debug('_bindEvent', newKey);
					this._bindEvent(listenerCtx, ev, emit, newKey);
				}
				return;
			}

			if (listenerCtx && listenerCtx.addEvent && boundCtx && boundCtx.fireEvent) {
				//_log.debug('bind val', val);
				listenerCtx.addEvent(ev, boundCtx.fireEvent.bind(boundCtx, emit));
				// keep track of the binding
				this.binding[ev] = event;
			} else if (listenerCtx && listenerCtx.on && boundCtx && boundCtx.fireEvent) {
				this.binding[ev] = event;
				listenerCtx.on(ev, boundCtx.fireEvent.bind(boundCtx, emit));
			} else {
				_log.warn('missing context or method', listenerCtx, val, this);
			}
		},

		/**
		 * Listen to the given event and bind to the given method
		 * @param  {Object} listenerCtx Object to listen
		 * @param  {string} ev Event that will be listened
		 * @param  {string} val Method path to be bound
		 * @return {void}
		 */
		_bindMethod: function(listenerCtx, ev, val, args) {
			//_log.debug('_bindMethod', listenerCtx, ev, val);
			var method = this._path(val);

			var valKeys = val.split('.');
			valKeys.pop();
			var boundCtx = this._path(valKeys.join('.'));

			//handle obj
			var obj = this._getObj(boundCtx, val);
			if (obj) {
				for (var newCtx in obj) {
					if (!obj.hasOwnProperty(newCtx)) {
						continue;
					}
					var newKey = valKeys.slice(0, 2).join('.');
					newKey = val.replace(newKey, newKey + '.' + newCtx);
					//_log.debug('_bindMethod', newKey);
					this._bindMethod(listenerCtx, ev, newKey, args);
				}
				return;
			}

			if (listenerCtx && listenerCtx.addEvent && method) {
				if (args) {
					listenerCtx.addEvent(ev, method.bind(boundCtx, args));
				} else {
					listenerCtx.addEvent(ev, method.bind(boundCtx));
				}
				// keep track of the binding
				this.binding[ev] = method;
			} else if (listenerCtx && listenerCtx.on && method) {
				this.binding[ev] = method;
				listenerCtx.on(ev, method.bind(boundCtx));
			} else {
				_log.warn('missing context or method', listenerCtx, val, this);
			}
		},

		/**
		 * Return the last reference to a object
		 * @param  {string} str Object path for example key1.key2.key3
		 * @return {Object}
		 */
		_path: function(str) {
			//_log.debug('_path', str);
			if (!str) {
				return this;
			} else if (!str.match(/\./)) {
				return this[str];
			}

			var last;

			var keys = str.split('.');
			for (var i = 0, l = keys.length; i < l; i++) {
				var key = keys[i];

				last = last || this;
				last = last[key];
			}

			return last;
		},

		_getObj: function(ctx, str) {

			if (ctx && ctx.constructor && ctx.constructor.name === 'Object') {
				for (var first in ctx) {
					if (!ctx.hasOwnProperty(first)) {
						continue;
					}
					break;
				}
				if (str.indexOf(first) !== -1) {
					return;
				}
				//_log.debug('_getObj', str, ctx, first);
				return ctx;
			}
		},

	});

	return exports;

}));
<commit_msg>fix globals<commit_after>/**
 * Binding Core Module Class
 * @class Core.Module.Binding
 * @author Jerome Vial, Bruno Santos
 */
(function(root, factory) {
	if (typeof define === 'function' && define.amd) {
		define([], factory);
	} else if (typeof exports === 'object') {
		module.exports = factory();
	} else {
		root.returnExports = factory();
	}
}(this, function() {

	var _log = __debug('core:module-binding').defineLevel();

	if (typeof define !== 'function') {
		Class = require('primish');
		Events = require('primish/emitter');
	}

	var exports = new Class({

		Implements: [Events],

		options: {
			api: {
				emit: 'trigger'
			}
		},

		/**
		 * Initialize
		 * @return {void}
		 */
		initialize: function() {
			_log.debug('initialize binding');

			var self = this;

			this.addEvent('initReady', function() {
				self._initBinding.bind(this)();
			});
		},

		/**
		 * Events communication controller
		 * Event bindings
		 * @return {Object}
		 */
		_initBinding: function(binding) {
			binding = binding || this.options.controller || this.options.binding;

			this.binding = this.binding || {};

			_log.debug('_initBinding', this.options.name, binding);

			if (!binding) {
				_log.debug('missing binding options');
				return;
			}

			if (!binding._list) {
				this._bindObject(binding);
				return;
			}

			var list = binding._list;

			//_log.debug(list, binding);

			for (var i = 0; list.length > i; i++) {
				var bind = binding[list[i]];
				this.binding = this.binding || {};

				this._bindObject(bind);
			}

			if (this.fireEvent) {
				this.fireEvent('bindingsReady');
			} else if (this.trigger) {
				this.trigger('bindingsReady');
			}

			return this.binding;
		},

		/**
		 * Bind an object
		 * @param  {Object} obj obj whit key and value to be bound
		 * @return {void}
		 */
		_bindObject: function(obj) {
			//_log.debug('_bindObject', obj);

			for (var key in obj) {
				if (!obj.hasOwnProperty(key)) {
					continue;
				}
				var value = obj[key];

				if (typeof value !== 'object') {
					this._bindkey(key, value);
				} else {
					this._bindList(key, value);
				}
			}
		},

		/**
		 * Bind a list of events to a specific object
		 * @param  {string} key Object path that will listen
		 * @param  {Array} values List if values to bind
		 * @return {void}
		 */
		_bindList: function(key, values) {
			//_log.debug('_bindList', key, values);

			for (var i = 0; i < values.length; i++) {
				this._bindkey(key, values[i]);
			}
		},

		/**
		 * Bind to object path
		 * get the event,
		 * get the reference to the last key of the first object,
		 * check if there is a event or a mehtod to bind
		 * @param  {string} key Object path that will listen
		 * @param  {string} val Object path to be bound
		 * @return {void}
		 */
		_bindkey: function(key, val) {
			//_log.debug('_bindkey', key, val);

			var eventKeys = key.split('.');
			var ev = eventKeys[eventKeys.length - 1];
			eventKeys.pop();
			var listenerCtx = this._path(eventKeys.join('.'));

			//handle obj
			var obj = this._getObj(listenerCtx, val);
			if (obj) {
				for (var newCtx in obj) {
					if (!obj.hasOwnProperty(newCtx)) {
						continue;
					}
					var newKey = eventKeys.join('.') + '.' + newCtx + '.' + ev;
					//_log.debug('_bindkey', newKey, val);
					this._bindkey(newKey, val);
				}
				return;
			}

			//handle args
			var args;
			if (typeof val === 'object') {
				for (var k in val) {
					if (!val.hasOwnProperty(k)) {
						continue;
					}
					break;
				}
				args = this._processKeyObj(k, val);
				val = k;
			}

			var valKeys = val.split('.');

			//Check if it's an event
			if (valKeys[valKeys.length - 2] === this.options.api.emit) {
				var emit = valKeys[valKeys.length - 1];
				this._bindEvent(listenerCtx, ev, emit, val);
			} else {
				this._bindMethod(listenerCtx, ev, val, args);
			}
		},

		/**
		 * Process Key Obj
		 * @param  {string} key
		 * @param  {Object} val
		 * @return {Object}
		 */
		_processKeyObj: function(key, val) {
			//_log.debug('_processKeyObj', key, val);

			var args = val[key];

			for (var i = 0; i < args.length; i++) {
				var arg = args[i];

				if (arg.split('.')[0] === 'this') {
					arg = arg.split('.');
					arg.shift();
					args[i] = this._path(arg.join('.'));
				}
			}

			return args;
		},

		/**
		 * Listen to the given event and trigger another
		 * @param  {Object} listenerCtx Object to listen
		 * @param  {string} ev Event that will be listened
		 * @param  {string} emit Event that will be emitted
		 * @param  {string} val Method path to be bound
		 * @return {void}
		 */
		_bindEvent: function(listenerCtx, ev, emit, val) {
			//_log.debug('_bindEvent', listenerCtx, ev, emit, val);

			var emitter = this.options.api.emit;

			var valKeys = val.split('.');
			var save = valKeys[valKeys.length - 1];
			valKeys.splice(-2, 2);
			var boundCtx = this._path(valKeys.join('.'));

			//handle obj
			var obj = this._getObj(boundCtx, val);
			if (obj) {
				for (var newCtx in obj) {
					if (!obj.hasOwnProperty(newCtx)) {
						continue;
					}
					var newKey = valKeys.join('.') + '.' + newCtx + '.' + emitter + '.' + save;
					//_log.debug('_bindEvent', newKey);
					this._bindEvent(listenerCtx, ev, emit, newKey);
				}
				return;
			}

			if (listenerCtx && listenerCtx.addEvent && boundCtx && boundCtx.fireEvent) {
				//_log.debug('bind val', val);
				listenerCtx.addEvent(ev, boundCtx.fireEvent.bind(boundCtx, emit));
				// keep track of the binding
				//this.binding[ev] = event;
			} else if (listenerCtx && listenerCtx.on && boundCtx && boundCtx.fireEvent) {
				//this.binding[ev] = event;
				listenerCtx.on(ev, boundCtx.fireEvent.bind(boundCtx, emit));
			} else {
				_log.warn('missing context or method', listenerCtx, val, this);
			}
		},

		/**
		 * Listen to the given event and bind to the given method
		 * @param  {Object} listenerCtx Object to listen
		 * @param  {string} ev Event that will be listened
		 * @param  {string} val Method path to be bound
		 * @return {void}
		 */
		_bindMethod: function(listenerCtx, ev, val, args) {
			//_log.debug('_bindMethod', listenerCtx, ev, val);
			var method = this._path(val);

			var valKeys = val.split('.');
			valKeys.pop();
			var boundCtx = this._path(valKeys.join('.'));

			//handle obj
			var obj = this._getObj(boundCtx, val);
			if (obj) {
				for (var newCtx in obj) {
					if (!obj.hasOwnProperty(newCtx)) {
						continue;
					}
					var newKey = valKeys.slice(0, 2).join('.');
					newKey = val.replace(newKey, newKey + '.' + newCtx);
					//_log.debug('_bindMethod', newKey);
					this._bindMethod(listenerCtx, ev, newKey, args);
				}
				return;
			}

			if (listenerCtx && listenerCtx.addEvent && method) {
				if (args) {
					listenerCtx.addEvent(ev, method.bind(boundCtx, args));
				} else {
					listenerCtx.addEvent(ev, method.bind(boundCtx));
				}
				// keep track of the binding
				this.binding[ev] = method;
			} else if (listenerCtx && listenerCtx.on && method) {
				this.binding[ev] = method;
				listenerCtx.on(ev, method.bind(boundCtx));
			} else {
				_log.warn('missing context or method', listenerCtx, val, this);
			}
		},

		/**
		 * Return the last reference to a object
		 * @param  {string} str Object path for example key1.key2.key3
		 * @return {Object}
		 */
		_path: function(str) {
			//_log.debug('_path', str);
			if (!str) {
				return this;
			} else if (!str.match(/\./)) {
				return this[str];
			}

			var last;

			var keys = str.split('.');
			for (var i = 0, l = keys.length; i < l; i++) {
				var key = keys[i];

				last = last || this;
				last = last[key];
			}

			return last;
		},

		_getObj: function(ctx, str) {

			if (ctx && ctx.constructor && ctx.constructor.name === 'Object') {
				for (var first in ctx) {
					if (!ctx.hasOwnProperty(first)) {
						continue;
					}
					break;
				}
				if (str.indexOf(first) !== -1) {
					return;
				}
				//_log.debug('_getObj', str, ctx, first);
				return ctx;
			}
		},

	});

	return exports;

}));
<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';

import AppBar from '@material-ui/core/AppBar';
import Toolbar from '@material-ui/core/Toolbar';
import Typography from '@material-ui/core/Typography';
import Paper from '@material-ui/core/Paper';
import Grid from '@material-ui/core/Grid';
import Button from '@material-ui/core/Button';
import TextField from '@material-ui/core/TextField';
import Tooltip from '@material-ui/core/Tooltip';
import IconButton from '@material-ui/core/IconButton';
import { withStyles } from '@material-ui/core/styles';
import SearchIcon from '@material-ui/icons/Search';
import RefreshIcon from '@material-ui/icons/Refresh';
import Container from '@material-ui/core/Container';
import Divider from '@material-ui/core/Divider'
//import Chart from './Chart';
import moment from 'moment'

import Card from '@material-ui/core/Card';
import CardActions from '@material-ui/core/CardActions';
import CardContent from '@material-ui/core/CardContent';

import DashboardCard from '../components/dashboard/card'
import Title from '../components/dashboard/title';
import Progress from '../shared/Progress'

import HeatMap from '../components/charts/heatMap'
import Pie from '../components/charts/pie'
import Count from '../components/charts/count'

import {DASHBOARD} from "../graphql/queries"
import graphql from '../graphql/client'

import {setCurrentSection} from '../actions/navigation'
import { withRouter } from 'react-router-dom'
import Content from '../components/Content'
import { connect } from 'react-redux'

const styles = theme => ({
  paperll: {
    maxWidth: 936,
    //marginTop: '2em',
    //marginBottom: '2em',
    margin: 'auto',
    //overflow: 'hidden',
    //marginBottom: 20,
  },
  searchBar: {
    borderBottom: '1px solid rgba(0, 0, 0, 0.12)',
  },
  searchInput: {
    fontSize: theme.typography.fontSize,
  },
  block: {
    display: 'block',
  },
  addUser: {
    marginRight: theme.spacing(1),
  },
  contentWrapper: {
    margin: '40px 16px',
  },
  card: {
    minWidth: 275,
  },
  bullet: {
    display: 'inline-block',
    margin: '0 2px',
    transform: 'scale(0.8)',
  },
  title: {
    fontSize: 14,
  },
  pos: {
    marginBottom: 12,
  },

  content: {
    flexGrow: 1,
    height: '100vh',
    //overflow: 'auto',
  },
  container: {
    paddingTop: theme.spacing(4),
    paddingBottom: theme.spacing(4),
  },
  paper: {
    padding: theme.spacing(2),
    display: 'flex',
    overflow: 'auto',
    flexDirection: 'column',
  },
  fixedHeight: {
    height: 240,
  },

});

function Dashboard(props) {
  const { classes, app, dispatch } = props;

  React.useEffect(()=>{
    dispatch(
      setCurrentSection("Dashboard")
    )
  }, [])

  const initialData =  {
    loading: true,
    from: moment().add(-1, 'week'),
    to: moment(), //.add(-1, 'day')
  }

  const [dashboard, setDashboard] = React.useState(initialData)

  const bull = •;
  const fixedHeightPaper = clsx(classes.paper, classes.fixedHeight);

  return (
    <Content>

        <Container maxWidth="lg" className={classes.container}>
          <Grid container spacing={3}>
            {/* Chart */}

            <Grid item xs={12} md={12} lg={12}>

              <DashboardCard title={"Integrated blocks"}>
                <DashboardItem
                  chartType={"app_packages"}
                  dashboard={dashboard}
                  app={app}
                  label={I18n.t('dashboasrd.user_country')}
                  kind={'app_packages'}
                  classes={classes}
                  styles={{}}
                />
              </DashboardCard>

            </Grid>

            <Grid item xs={6} md={3}>
              <Paper className={classes.paper}>
                <DashboardItem
                  chartType={"count"}
                  dashboard={dashboard}
                  app={app}
                  kind={"first_response_time"}
                  label={I18n.t('dashboard.response_avg')}
                  appendLabel={"Hrs"}
                />
              </Paper>
            </Grid>

            <Grid item xs={6} md={3}>
              <Paper className={classes.paper}>
                <DashboardItem
                  chartType={"count"}
                  dashboard={dashboard}
                  app={app}
                  kind={"opened_conversations"}
                  label={I18n.t('dashboard.new_conversations')}
                  appendLabel={""}
                />
              </Paper>
            </Grid>

            <Grid item xs={6} md={3}>
              <Paper className={classes.paper}>
                <DashboardItem
                  chartType={"count"}
                  dashboard={dashboard}
                  app={app}
                  kind={"solved_conversations"}
                  label={I18n.t('dashboard.resolutions')}
                  appendLabel={""}
                />
              </Paper>
            </Grid>

            <Grid item xs={6} md={3}>
              <Paper className={classes.paper}>
                <DashboardItem
                  chartType={"count"}
                  dashboard={dashboard}
                  app={app}
                  kind={"incoming_messages"}
                  label={I18n.t('dashboard.incoming_messages')}
                  appendLabel={""}
                />
              </Paper>
            </Grid>

            <Grid item xs={12} md={8} lg={9}>
              <Paper className={fixedHeightPaper}>
                {/*<Chart />*/}
                <Title>Visit activity</Title>
                 <DashboardItem
                    chartType={"heatMap"}
                    dashboard={dashboard}
                    app={app}
                    kind={"visits"}
                  />
              </Paper>
            </Grid>
            {/* Recent Deposits */}
            <Grid item xs={12} md={4} lg={3}>
              <Paper className={fixedHeightPaper}>
                <DashboardCard title={"Users browser"}>

                  <DashboardItem
                    chartType={"pie"}
                    dashboard={dashboard}
                    app={app}
                    label={I18n.t('dashboasrd.browser')}
                    kind={'browser'}
                  />

                </DashboardCard>

              </Paper>
            </Grid>

            <Grid item xs={12} md={4} lg={3}>
              <Paper className={classes.paper}>
              <DashboardCard title={"Lead Os"}>
                  <DashboardItem
                    chartType={"pie"}
                    dashboard={dashboard}
                    app={app}
                    label={I18n.t('dashboasrd.lead_os')}
                    kind={'lead_os'}
                  />
                </DashboardCard>
              </Paper>
            </Grid>

            <Grid item xs={12} md={4} lg={3}>
              <Paper className={classes.paper}>
              <DashboardCard title={"User Os"}>
                  <DashboardItem
                    chartType={"pie"}
                    dashboard={dashboard}
                    app={app}
                    label={I18n.t('dashboasrd.user_os')}
                    kind={'user_os'}
                  />
                </DashboardCard>
              </Paper>
            </Grid>

            <Grid item xs={12} md={4} lg={3}>
              <Paper className={classes.paper}>
              <DashboardCard title={"User country"}>
                  <DashboardItem
                    chartType={"pie"}
                    dashboard={dashboard}
                    app={app}
                    label={I18n.t('dashboasrd.user_country')}
                    kind={'user_country'}
                  />
                </DashboardCard>
              </Paper>
            </Grid>

          </Grid>
        </Container>
        {/*<MadeWithLove />*/}

    </Content>
  );
}

function DashboardItem(
  {
    app,
    kind,
    dashboard,
    chartType,
    label,
    appendLabel,
    classes,
    styles
  }){

  const [data, setData] = React.useState([])
  const [loading, setLoading] = React.useState(true)

  React.useEffect(()=>{
    getData()}
  , [])

  function getData(){

    graphql(DASHBOARD, {
      appKey: app.key,
      range: {
          from: dashboard.from,
          to: dashboard.to
        },
        kind: kind
      }, {
      success: (data)=>{
        setData(data.app.dashboard)
        setLoading(false)
      },
      error: (err)=>{
        setLoading(false)
        debugger
      }
    })
  }

  function renderChart(){
    switch (chartType) {
      case "heatMap":
        return <HeatMap
          data={data}
          from={dashboard.from}
          to={dashboard.to}
        />

      case "pie":
        return  <Pie
          data={data}
          from={dashboard.from}
          to={dashboard.to}
        />
      case "count":
        return  <Count
          data={data}
          from={dashboard.from}
          to={dashboard.to}
          label={label}
          appendLabel={appendLabel}
        />
      case "app_packages":
        return <DashboardAppPackages
                data={data}
                dashboard={dashboard}
                classes={classes}
               />
      default:
        return
no chart type
;
    }
  }

  return (

      {
        loading && <Progress/>
      }
      {
        !loading && renderChart()
      }

  )
}

function DashboardAppPackages(props){
  const packages  = props.data
  return (

      {
        packages && packages.map((o)=>(
          <DashboardAppPackage
            package={o}
            dashboard={props.dashboard}
            classes={props.classes}
          />
        ))
      }

  )
}

function DashboardAppPackage(props){
  const dashboard = props.dashboard
  const pkg  = props.package
  const data = pkg.data
  const classes = props.classes

  return (
    <Paper className={classes.paper}>

    <Grid container spacing={3}>
      <Grid item>

      </Grid>

      <Grid item>
        <Typography variant="h5">
          {pkg.name}: {data.title}
        </Typography>

        <Typography variant="overline">
          {data.subtitle}
        </Typography>
      </Grid>
    </Grid>

    <Divider/>

      <Grid container spacing={3}>

        {
          data.values && data.values.map((v)=>{
            return <Grid item>

                        <Count
                          data={v.value}
                          from={dashboard.from}
                          to={dashboard.to}
                          label={v.label}
                          subtitle={`${v.value2}`}
                          //appendLabel={appendLabel}
                        />

                    </Grid>
          })
        }

      </Grid>
    </Paper>
  )
}

Dashboard.propTypes = {
  classes: PropTypes.object.isRequired,
};

function mapStateToProps(state) {

  const { auth, app } = state
  const { loading, isAuthenticated } = auth

  return {
    app,
    loading,
    isAuthenticated
  }
}

export default withRouter(connect(mapStateToProps)(withStyles(styles)(Dashboard)))<commit_msg>Update Dashboard.js<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';

import AppBar from '@material-ui/core/AppBar';
import Toolbar from '@material-ui/core/Toolbar';
import Typography from '@material-ui/core/Typography';
import Paper from '@material-ui/core/Paper';
import Grid from '@material-ui/core/Grid';
import Button from '@material-ui/core/Button';
import TextField from '@material-ui/core/TextField';
import Tooltip from '@material-ui/core/Tooltip';
import IconButton from '@material-ui/core/IconButton';
import { withStyles } from '@material-ui/core/styles';
import SearchIcon from '@material-ui/icons/Search';
import RefreshIcon from '@material-ui/icons/Refresh';
import Container from '@material-ui/core/Container';
import Divider from '@material-ui/core/Divider'
//import Chart from './Chart';
import moment from 'moment'

import Card from '@material-ui/core/Card';
import CardActions from '@material-ui/core/CardActions';
import CardContent from '@material-ui/core/CardContent';

import DashboardCard from '../components/dashboard/card'
import Title from '../components/dashboard/title';
import Progress from '../shared/Progress'

import HeatMap from '../components/charts/heatMap'
import Pie from '../components/charts/pie'
import Count from '../components/charts/count'

import {DASHBOARD} from "../graphql/queries"
import graphql from '../graphql/client'

import {setCurrentSection} from '../actions/navigation'
import { withRouter } from 'react-router-dom'
import Content from '../components/Content'
import { connect } from 'react-redux'

const styles = theme => ({
  paperll: {
    maxWidth: 936,
    //marginTop: '2em',
    //marginBottom: '2em',
    margin: 'auto',
    //overflow: 'hidden',
    //marginBottom: 20,
  },
  searchBar: {
    borderBottom: '1px solid rgba(0, 0, 0, 0.12)',
  },
  searchInput: {
    fontSize: theme.typography.fontSize,
  },
  block: {
    display: 'block',
  },
  addUser: {
    marginRight: theme.spacing(1),
  },
  contentWrapper: {
    margin: '40px 16px',
  },
  card: {
    minWidth: 275,
  },
  bullet: {
    display: 'inline-block',
    margin: '0 2px',
    transform: 'scale(0.8)',
  },
  title: {
    fontSize: 14,
  },
  pos: {
    marginBottom: 12,
  },

  content: {
    flexGrow: 1,
    height: '100vh',
    //overflow: 'auto',
  },
  container: {
    paddingTop: theme.spacing(4),
    paddingBottom: theme.spacing(4),
  },
  paper: {
    padding: theme.spacing(2),
    display: 'flex',
    overflow: 'auto',
    flexDirection: 'column',
  },
  fixedHeight: {
    height: 240,
  },

});

function Dashboard(props) {
  const { classes, app, dispatch } = props;

  React.useEffect(()=>{
    dispatch(
      setCurrentSection("Dashboard")
    )
  }, [])

  const initialData =  {
    loading: true,
    from: moment().add(-1, 'week'),
    to: moment(), //.add(-1, 'day')
  }

  const [dashboard, setDashboard] = React.useState(initialData)

  const bull = •;
  const fixedHeightPaper = clsx(classes.paper, classes.fixedHeight);

  return (
    <Content>

        <Container maxWidth="lg" className={classes.container}>
          <Grid container spacing={3}>
            {/* Chart */}

            <Grid item xs={12} md={12} lg={12}>

              <DashboardItem
                chartType={"app_packages"}
                dashboard={dashboard}
                app={app}
                label={I18n.t('dashboasrd.user_country')}
                kind={'app_packages'}
                classes={classes}
                styles={{}}
              />

            </Grid>

            <Grid item xs={6} md={3}>
              <Paper className={classes.paper}>
                <DashboardItem
                  chartType={"count"}
                  dashboard={dashboard}
                  app={app}
                  kind={"first_response_time"}
                  label={I18n.t('dashboard.response_avg')}
                  appendLabel={"Hrs"}
                />
              </Paper>
            </Grid>

            <Grid item xs={6} md={3}>
              <Paper className={classes.paper}>
                <DashboardItem
                  chartType={"count"}
                  dashboard={dashboard}
                  app={app}
                  kind={"opened_conversations"}
                  label={I18n.t('dashboard.new_conversations')}
                  appendLabel={""}
                />
              </Paper>
            </Grid>

            <Grid item xs={6} md={3}>
              <Paper className={classes.paper}>
                <DashboardItem
                  chartType={"count"}
                  dashboard={dashboard}
                  app={app}
                  kind={"solved_conversations"}
                  label={I18n.t('dashboard.resolutions')}
                  appendLabel={""}
                />
              </Paper>
            </Grid>

            <Grid item xs={6} md={3}>
              <Paper className={classes.paper}>
                <DashboardItem
                  chartType={"count"}
                  dashboard={dashboard}
                  app={app}
                  kind={"incoming_messages"}
                  label={I18n.t('dashboard.incoming_messages')}
                  appendLabel={""}
                />
              </Paper>
            </Grid>

            <Grid item xs={12} md={8} lg={9}>
              <Paper className={fixedHeightPaper}>
                {/*<Chart />*/}
                <Title>Visit activity</Title>
                 <DashboardItem
                    chartType={"heatMap"}
                    dashboard={dashboard}
                    app={app}
                    kind={"visits"}
                  />
              </Paper>
            </Grid>
            {/* Recent Deposits */}
            <Grid item xs={12} md={4} lg={3}>
              <Paper className={fixedHeightPaper}>
                <DashboardCard title={"Users browser"}>

                  <DashboardItem
                    chartType={"pie"}
                    dashboard={dashboard}
                    app={app}
                    label={I18n.t('dashboasrd.browser')}
                    kind={'browser'}
                  />

                </DashboardCard>

              </Paper>
            </Grid>

            <Grid item xs={12} md={4} lg={3}>
              <Paper className={classes.paper}>
              <DashboardCard title={"Lead Os"}>
                  <DashboardItem
                    chartType={"pie"}
                    dashboard={dashboard}
                    app={app}
                    label={I18n.t('dashboasrd.lead_os')}
                    kind={'lead_os'}
                  />
                </DashboardCard>
              </Paper>
            </Grid>

            <Grid item xs={12} md={4} lg={3}>
              <Paper className={classes.paper}>
              <DashboardCard title={"User Os"}>
                  <DashboardItem
                    chartType={"pie"}
                    dashboard={dashboard}
                    app={app}
                    label={I18n.t('dashboasrd.user_os')}
                    kind={'user_os'}
                  />
                </DashboardCard>
              </Paper>
            </Grid>

            <Grid item xs={12} md={4} lg={3}>
              <Paper className={classes.paper}>
              <DashboardCard title={"User country"}>
                  <DashboardItem
                    chartType={"pie"}
                    dashboard={dashboard}
                    app={app}
                    label={I18n.t('dashboasrd.user_country')}
                    kind={'user_country'}
                  />
                </DashboardCard>
              </Paper>
            </Grid>

          </Grid>
        </Container>
        {/*<MadeWithLove />*/}

    </Content>
  );
}

function DashboardItem(
  {
    app,
    kind,
    dashboard,
    chartType,
    label,
    appendLabel,
    classes,
    styles
  }){

  const [data, setData] = React.useState([])
  const [loading, setLoading] = React.useState(true)

  React.useEffect(()=>{
    getData()}
  , [])

  function getData(){

    graphql(DASHBOARD, {
      appKey: app.key,
      range: {
          from: dashboard.from,
          to: dashboard.to
        },
        kind: kind
      }, {
      success: (data)=>{
        setData(data.app.dashboard)
        setLoading(false)
      },
      error: (err)=>{
        setLoading(false)
        debugger
      }
    })
  }

  function renderChart(){
    switch (chartType) {
      case "heatMap":
        return <HeatMap
          data={data}
          from={dashboard.from}
          to={dashboard.to}
        />

      case "pie":
        return  <Pie
          data={data}
          from={dashboard.from}
          to={dashboard.to}
        />
      case "count":
        return  <Count
          data={data}
          from={dashboard.from}
          to={dashboard.to}
          label={label}
          appendLabel={appendLabel}
        />
      case "app_packages":
        return <DashboardAppPackages
                data={data}
                dashboard={dashboard}
                classes={classes}
               />
      default:
        return
no chart type
;
    }
  }

  return (

      {
        loading && <Progress/>
      }
      {
        !loading && renderChart()
      }

  )
}

function DashboardAppPackages(props){
  const packages  = props.data
  return (

      {
        packages && packages.map((o)=>(
          <DashboardAppPackage
            package={o}
            dashboard={props.dashboard}
            classes={props.classes}
          />
        ))
      }

  )
}

function DashboardAppPackage(props){
  const dashboard = props.dashboard
  const pkg  = props.package
  const data = pkg.data
  const classes = props.classes

  return (
    <Paper className={classes.paper}>

    <Grid container spacing={3}>
      <Grid item>

      </Grid>

      <Grid item>
        <Typography variant="h5">
          {pkg.name}: {data.title}
        </Typography>

        <Typography variant="overline">
          {data.subtitle}
        </Typography>
      </Grid>
    </Grid>

    <Divider/>

      <Grid container spacing={3}>

        {
          data.values && data.values.map((v)=>{
            return <Grid item>

                        <Count
                          data={v.value}
                          from={dashboard.from}
                          to={dashboard.to}
                          label={v.label}
                          subtitle={`${v.value2}`}
                          //appendLabel={appendLabel}
                        />

                    </Grid>
          })
        }

      </Grid>
    </Paper>
  )
}

Dashboard.propTypes = {
  classes: PropTypes.object.isRequired,
};

function mapStateToProps(state) {

  const { auth, app } = state
  const { loading, isAuthenticated } = auth

  return {
    app,
    loading,
    isAuthenticated
  }
}

export default withRouter(connect(mapStateToProps)(withStyles(styles)(Dashboard)))<|endoftext|>


<commit_before>'use strict';

var stream = require('../../lib' + (process.env.COVERAGE || '') + '/stream/streams.js'),
    genlex = require('../../lib' + (process.env.COVERAGE || '') + '/genlex/genlex.js');

/*
  ======== A Handy Little Nodeunit Reference ========
  https://github.com/caolan/nodeunit

  Test methods:
    test.expect(numAssertions)
    test.done()
  Test assertions:
    test.ok(value, [message])
    test.equal(actual, expected, [message])
    test.notEqual(actual, expected, [message])
    test.deepEqual(actual, expected, [message])
    test.notDeepEqual(actual, expected, [message])
    test.strictEqual(actual, expected, [message])
    test.notStrictEqual(actual, expected, [message])
    test.throws(block, [error], [message])
    test.doesNotThrow(block, [error], [message])
    test.ifError(value)
*/

exports['genlex'] = {
  setUp: function(done) {
    done();
  },

  'expect (space) to be accepted': function(test) {
    test.expect(1);
    // tests here
    test.equal(genlex.generator([]).space().parse(stream.ofString(" "),0).isAccepted(),
               true,
               'should be accepted.');
    test.done();
  },

  'expect (meta space) to be accepted': function(test) {
    test.expect(1);
    // tests here
    test.equal(genlex.generator([]).space().parse(stream.ofString("\t"),0).isAccepted(),
               true,
               'should be accepted.');
    test.done();
  },

  'expect (spaces) to be accepted': function(test) {
    test.expect(1);
    // tests here
    test.equal(genlex.generator([]).spaces().parse(stream.ofString(" \n  "),0).isAccepted(),
               true,
               'should be accepted.');
    test.done();
  },

  'expect (spaces) to be skipped': function(test) {
    test.expect(1);
    // tests here
    test.equal(genlex.generator([]).spaces().parse(stream.ofString(" \n "),0).offset,
               3,
               'should be skipped.');
    test.done();
  },

  'expect (keyword) to be accepted': function(test) {
    test.expect(1);
    // tests here
    var factory = genlex.factory(
        function (s) { return s; },
        null,
        null,
        null,
        null
    );

    test.equal(genlex.generator(['<-', '->']).keyword(factory).parse(stream.ofString("a->b"),1).isAccepted(),
               true,
               'should be accepted.');
    test.done();
  },

  'expect (keyword) to return ->': function(test) {
    test.expect(1);
    // tests here
    var factory = genlex.factory(
        function (s) { return s; },
        null,
        null,
        null,
        null
    );

    test.equal(genlex.generator(['<-', '->']).keyword(factory).parse(stream.ofString("a->b"),1).value,
               '->',
               'should be accepted.');
    test.done();
  },

  'expect (ident) to be accepted': function(test) {
    test.expect(1);
    // tests here
    var factory = genlex.factory(
        null,
        function (s) { return s; },
        null,
        null,
        null
    );

    test.equal(genlex.generator([]).ident(factory).parse(stream.ofString("smith "),0).isAccepted(),
               true,
               'should be accepted.');
    test.done();
  },

  'expect (ident) to return smith': function(test) {
    test.expect(1);
    // tests here
    var factory = genlex.factory(
        null,
        function (s) { return s; },
        null,
        null,
        null
    );

    test.equal(genlex.generator([]).ident(factory).parse(stream.ofString("smith "),0).value,
               'smith',
               'should be smith.');
    test.done();
  },

  'expect (number) to be accepted': function(test) {
    test.expect(1);
    // tests here
    var factory = genlex.factory(
        null,
        null,
        function (s) { return s; },
        null,
        null
    );

    test.equal(genlex.generator([]).number(factory).parse(stream.ofString('42'),0).isAccepted(),
               true,
               'should be accepted.');
    test.done();
  },

  'expect (number) to return 42': function(test) {
    test.expect(1);
    // tests here
    var factory = genlex.factory(
        null,
        null,
        function (s) { return s; },
        null,
        null
    );

    test.equal(genlex.generator([]).number(factory).parse(stream.ofString('42'),0).value,
               42,
               'should be 42.');
    test.done();
  },

  'expect (string) to be accepted': function(test) {
    test.expect(1);
    // tests here
    var factory = genlex.factory(
        null,
        null,
        null,
        function (s) { return s; },
        null
    );

    test.equal(genlex.generator([]).string(factory).parse(stream.ofString('"smith"'),0).isAccepted(),
               true,
               'should be accepted.');
    test.done();
  },

  'expect (string) to return smith': function(test) {
    test.expect(1);
    // tests here
    var factory = genlex.factory(
        null,
        null,
        null,
        function (s) { return s; },
        null
    );

    test.equal(genlex.generator([]).string(factory).parse(stream.ofString('"smith"'),0).value,
               'smith',
               'should be smith.');
    test.done();
  },

  'expect (char) to be accepted': function(test) {
    test.expect(1);
    // tests here
    var factory = genlex.factory(
        null,
        null,
        null,
        null,
        function (s) { return s; }
    );

    test.equal(genlex.generator([]).char(factory).parse(stream.ofString("'s'"),0).isAccepted(),
               true,
               'should be accepted.');
    test.done();
  },

  'expect (char) to return j': function(test) {
    test.expect(1);
    // tests here
    var factory = genlex.factory(
        null,
        null,
        null,
        null,
        function (s) { return s; }
     );

    test.equal(genlex.generator([]).char(factory).parse(stream.ofString("'s'"),0).value,
               's',
               'should be s.');
    test.done();
  },

  'expect (token) to return keyword': function(test) {
    test.expect(1);
    // tests here
    var factory = genlex.factory(
        function (s) { return s; },
        null,
        null,
        null,
        null
    );

    test.equal(genlex.generator(['<-']).token(factory).parse(stream.ofString("a<-b"),1).value,
               '<-',
               'should be <-.');
    test.done();
  },

  'expect (token) to return ident': function(test) {
    test.expect(1);
    // tests here
    var factory = genlex.factory(
        null,
        function (s) { return s; },
        null,
        null,
        null
    );

    test.equal(genlex.generator(['<-']).token(factory).parse(stream.ofString("hello"),0).value,
               'hello',
               'should be hello.');
    test.done();
  },

  'expect (token) to return number': function(test) {
    test.expect(1);
    // tests here
    var factory = genlex.factory(
        null,
        null,
        function (s) { return s; },
        null,
        null
    );

    test.equal(genlex.generator(['<-']).token(factory).parse(stream.ofString("123"),0).value,
               123,
               'should be 123.');
    test.done();
  },

  'expect (token) to return string': function(test) {
    test.expect(1);
    // tests here
    var factory = genlex.factory(
        null,
        null,
        null,
        function (s) { return s; },
        null
    );

    test.equal(genlex.generator(['<-']).token(factory).parse(stream.ofString('"123"'),0).value,
               "123",
               'should be 123.');
    test.done();
  },

  'expect (token) to return char': function(test) {
    test.expect(1);
    // tests here
    var factory = genlex.factory(
        null,
        null,
        null,
        null,
        function (s) { return s; }
    );

    test.equal(genlex.generator(['<-']).token(factory).parse(stream.ofString("'a'"),0).value,
               "a",
               'should be a.');
    test.done();
  },

  'expect (tokens) to return ["a","->","b"]': function(test) {
    test.expect(1);
    // tests here
    var factory = genlex.factory(
        function (s) { return s; },
        function (s) { return s; },
        function (s) { return s; },
        function (s) { return s; },
        function (s) { return s; }
    );

    test.deepEqual(genlex.generator(['->']).tokens(factory).parse(stream.ofString("a -> b"),0).value,
                   ["a","->","b"],
                   'should be [a,->,b].');
    test.done();
  },
};
    <commit_msg>Cover genlex literal error case<commit_after>'use strict';

var stream = require('../../lib' + (process.env.COVERAGE || '') + '/stream/streams.js'),
    genlex = require('../../lib' + (process.env.COVERAGE || '') + '/genlex/genlex.js');

/*
  ======== A Handy Little Nodeunit Reference ========
  https://github.com/caolan/nodeunit

  Test methods:
    test.expect(numAssertions)
    test.done()
  Test assertions:
    test.ok(value, [message])
    test.equal(actual, expected, [message])
    test.notEqual(actual, expected, [message])
    test.deepEqual(actual, expected, [message])
    test.notDeepEqual(actual, expected, [message])
    test.strictEqual(actual, expected, [message])
    test.notStrictEqual(actual, expected, [message])
    test.throws(block, [error], [message])
    test.doesNotThrow(block, [error], [message])
    test.ifError(value)
*/

exports['genlex'] = {
  setUp: function(done) {
    done();
  },

  'expect (space) to be accepted': function(test) {
    test.expect(1);
    // tests here
    test.equal(genlex.generator([]).space().parse(stream.ofString(" "),0).isAccepted(),
               true,
               'should be accepted.');
    test.done();
  },

  'expect (meta space) to be accepted': function(test) {
    test.expect(1);
    // tests here
    test.equal(genlex.generator([]).space().parse(stream.ofString("\t"),0).isAccepted(),
               true,
               'should be accepted.');
    test.done();
  },

  'expect (spaces) to be accepted': function(test) {
    test.expect(1);
    // tests here
    test.equal(genlex.generator([]).spaces().parse(stream.ofString(" \n  "),0).isAccepted(),
               true,
               'should be accepted.');
    test.done();
  },

  'expect (spaces) to be skipped': function(test) {
    test.expect(1);
    // tests here
    test.equal(genlex.generator([]).spaces().parse(stream.ofString(" \n "),0).offset,
               3,
               'should be skipped.');
    test.done();
  },

  'expect (keyword) to be accepted': function(test) {
    test.expect(1);
    // tests here
    var factory = genlex.factory(
        function (s) { return s; },
        null,
        null,
        null,
        null
    );

    test.equal(genlex.generator(['<-', '->']).keyword(factory).parse(stream.ofString("a->b"),1).isAccepted(),
               true,
               'should be accepted.');
    test.done();
  },

  'expect (keyword) to return ->': function(test) {
    test.expect(1);
    // tests here
    var factory = genlex.factory(
        function (s) { return s; },
        null,
        null,
        null,
        null
    );

    test.equal(genlex.generator(['<-', '->']).keyword(factory).parse(stream.ofString("a->b"),1).value,
               '->',
               'should be accepted.');
    test.done();
  },

  'expect (keyword) to be rejected': function(test) {
    test.expect(1);
    // tests here
    var factory = genlex.factory(
        function (s) { return s; },
        null,
        null,
        null,
        null
    );

    test.equal(genlex.generator([]).keyword(factory).parse(stream.ofString("->"),1).isAccepted(),
               false,
               'should be rejected.');
    test.done();
  },

  'expect (ident) to be accepted': function(test) {
    test.expect(1);
    // tests here
    var factory = genlex.factory(
        null,
        function (s) { return s; },
        null,
        null,
        null
    );

    test.equal(genlex.generator([]).ident(factory).parse(stream.ofString("smith "),0).isAccepted(),
               true,
               'should be accepted.');
    test.done();
  },

  'expect (ident) to return smith': function(test) {
    test.expect(1);
    // tests here
    var factory = genlex.factory(
        null,
        function (s) { return s; },
        null,
        null,
        null
    );

    test.equal(genlex.generator([]).ident(factory).parse(stream.ofString("smith "),0).value,
               'smith',
               'should be smith.');
    test.done();
  },

  'expect (number) to be accepted': function(test) {
    test.expect(1);
    // tests here
    var factory = genlex.factory(
        null,
        null,
        function (s) { return s; },
        null,
        null
    );

    test.equal(genlex.generator([]).number(factory).parse(stream.ofString('42'),0).isAccepted(),
               true,
               'should be accepted.');
    test.done();
  },

  'expect (number) to return 42': function(test) {
    test.expect(1);
    // tests here
    var factory = genlex.factory(
        null,
        null,
        function (s) { return s; },
        null,
        null
    );

    test.equal(genlex.generator([]).number(factory).parse(stream.ofString('42'),0).value,
               42,
               'should be 42.');
    test.done();
  },

  'expect (string) to be accepted': function(test) {
    test.expect(1);
    // tests here
    var factory = genlex.factory(
        null,
        null,
        null,
        function (s) { return s; },
        null
    );

    test.equal(genlex.generator([]).string(factory).parse(stream.ofString('"smith"'),0).isAccepted(),
               true,
               'should be accepted.');
    test.done();
  },

  'expect (string) to return smith': function(test) {
    test.expect(1);
    // tests here
    var factory = genlex.factory(
        null,
        null,
        null,
        function (s) { return s; },
        null
    );

    test.equal(genlex.generator([]).string(factory).parse(stream.ofString('"smith"'),0).value,
               'smith',
               'should be smith.');
    test.done();
  },

  'expect (char) to be accepted': function(test) {
    test.expect(1);
    // tests here
    var factory = genlex.factory(
        null,
        null,
        null,
        null,
        function (s) { return s; }
    );

    test.equal(genlex.generator([]).char(factory).parse(stream.ofString("'s'"),0).isAccepted(),
               true,
               'should be accepted.');
    test.done();
  },

  'expect (char) to return j': function(test) {
    test.expect(1);
    // tests here
    var factory = genlex.factory(
        null,
        null,
        null,
        null,
        function (s) { return s; }
     );

    test.equal(genlex.generator([]).char(factory).parse(stream.ofString("'s'"),0).value,
               's',
               'should be s.');
    test.done();
  },

  'expect (token) to return keyword': function(test) {
    test.expect(1);
    // tests here
    var factory = genlex.factory(
        function (s) { return s; },
        null,
        null,
        null,
        null
    );

    test.equal(genlex.generator(['<-']).token(factory).parse(stream.ofString("a<-b"),1).value,
               '<-',
               'should be <-.');
    test.done();
  },

  'expect (token) to return ident': function(test) {
    test.expect(1);
    // tests here
    var factory = genlex.factory(
        null,
        function (s) { return s; },
        null,
        null,
        null
    );

    test.equal(genlex.generator(['<-']).token(factory).parse(stream.ofString("hello"),0).value,
               'hello',
               'should be hello.');
    test.done();
  },

  'expect (token) to return number': function(test) {
    test.expect(1);
    // tests here
    var factory = genlex.factory(
        null,
        null,
        function (s) { return s; },
        null,
        null
    );

    test.equal(genlex.generator(['<-']).token(factory).parse(stream.ofString("123"),0).value,
               123,
               'should be 123.');
    test.done();
  },

  'expect (token) to return string': function(test) {
    test.expect(1);
    // tests here
    var factory = genlex.factory(
        null,
        null,
        null,
        function (s) { return s; },
        null
    );

    test.equal(genlex.generator(['<-']).token(factory).parse(stream.ofString('"123"'),0).value,
               "123",
               'should be 123.');
    test.done();
  },

  'expect (token) to return char': function(test) {
    test.expect(1);
    // tests here
    var factory = genlex.factory(
        null,
        null,
        null,
        null,
        function (s) { return s; }
    );

    test.equal(genlex.generator(['<-']).token(factory).parse(stream.ofString("'a'"),0).value,
               "a",
               'should be a.');
    test.done();
  },

  'expect (tokens) to return ["a","->","b"]': function(test) {
    test.expect(1);
    // tests here
    var factory = genlex.factory(
        function (s) { return s; },
        function (s) { return s; },
        function (s) { return s; },
        function (s) { return s; },
        function (s) { return s; }
    );

    test.deepEqual(genlex.generator(['->']).tokens(factory).parse(stream.ofString("a -> b"),0).value,
                   ["a","->","b"],
                   'should be [a,->,b].');
    test.done();
  },
};
    <|endoftext|>


<commit_before>#!/usr/bin/env node

var fs = require('fs');
var path = require('path');
var argv = process.argv;
var Carmen = require('../index.js');
var termops = require('../lib/util/termops.js');
var Queue = require('../queue');
var f = argv[2];

if (!f) {
    console.warn('Usage: carmen-analyze.js <file>');
    process.exit(1);
}
if (!fs.existsSync(f)) {
    console.warn('File %s does not exist.', f);
    process.exit(1);
}

console.log('Analyzing %s ...', f);

var s = Carmen.auto(f);
var carmen = new Carmen({ s: s });

carmen.analyze(s, function(err, stats) {
    if (err) throw err;
    console.log('term <=> phrase index');
    console.log('---------------------');
    for (var key in stats.term) {
        var val = stats.term[key];
        if (key === 'maxes') {
            console.log('- %s:', key);
            val.forEach(function(entry, i) {
                console.log('  %s. %s (%s) %s', i+1, entry[0], entry[1], entry[2]);
            });
        } else {
            console.log('- %s: %s', key, val);
        }
    }

    console.log('');

    console.log('phrase <=> grid index');
    console.log('--------------------');
    for (var key in stats.grid) {
        var val = stats.grid[key];
        if (key === 'maxes') {
            console.log('- %s:', key);
            val.forEach(function(entry, i) {
                console.log('  %s. %s (%s) %s', i+1, entry[0], entry[1], entry[2]);
            });
        } else {
            console.log('- %s: %s', key, val);
        }
    }
});

<commit_msg>Remove bad require.<commit_after>#!/usr/bin/env node

var fs = require('fs');
var path = require('path');
var argv = process.argv;
var Carmen = require('../index.js');
var termops = require('../lib/util/termops.js');
var f = argv[2];

if (!f) {
    console.warn('Usage: carmen-analyze.js <file>');
    process.exit(1);
}
if (!fs.existsSync(f)) {
    console.warn('File %s does not exist.', f);
    process.exit(1);
}

console.log('Analyzing %s ...', f);

var s = Carmen.auto(f);
var carmen = new Carmen({ s: s });

carmen.analyze(s, function(err, stats) {
    if (err) throw err;
    console.log('term <=> phrase index');
    console.log('---------------------');
    for (var key in stats.term) {
        var val = stats.term[key];
        if (key === 'maxes') {
            console.log('- %s:', key);
            val.forEach(function(entry, i) {
                console.log('  %s. %s (%s) %s', i+1, entry[0], entry[1], entry[2]);
            });
        } else {
            console.log('- %s: %s', key, val);
        }
    }

    console.log('');

    console.log('phrase <=> grid index');
    console.log('--------------------');
    for (var key in stats.grid) {
        var val = stats.grid[key];
        if (key === 'maxes') {
            console.log('- %s:', key);
            val.forEach(function(entry, i) {
                console.log('  %s. %s (%s) %s', i+1, entry[0], entry[1], entry[2]);
            });
        } else {
            console.log('- %s: %s', key, val);
        }
    }
});

<|endoftext|>


<commit_before>define([
        './Cartesian3',
        './Check',
        './defaultValue',
        './defined',
        './freezeObject',
        './Math',
        './scaleToGeodeticSurface'
    ], function(
        Cartesian3,
        Check,
        defaultValue,
        defined,
        freezeObject,
        CesiumMath,
        scaleToGeodeticSurface) {
    'use strict';

    /**
     * A position defined by longitude, latitude, and height.
     * @alias Cartographic
     * @constructor
     *
     * @param {Number} [longitude=0.0] The longitude, in radians.
     * @param {Number} [latitude=0.0] The latitude, in radians.
     * @param {Number} [height=0.0] The height, in meters, above the ellipsoid.
     *
     * @see Ellipsoid
     */
    function Cartographic(longitude, latitude, height) {
        /**
         * The longitude, in radians.
         * @type {Number}
         * @default 0.0
         */
        this.longitude = defaultValue(longitude, 0.0);

        /**
         * The latitude, in radians.
         * @type {Number}
         * @default 0.0
         */
        this.latitude = defaultValue(latitude, 0.0);

        /**
         * The height, in meters, above the ellipsoid.
         * @type {Number}
         * @default 0.0
         */
        this.height = defaultValue(height, 0.0);
    }

    /**
     * Creates a new Cartographic instance from longitude and latitude
     * specified in radians.
     *
     * @param {Number} longitude The longitude, in radians.
     * @param {Number} latitude The latitude, in radians.
     * @param {Number} [height=0.0] The height, in meters, above the ellipsoid.
     * @param {Cartographic} [result] The object onto which to store the result.
     * @returns {Cartographic} The modified result parameter or a new Cartographic instance if one was not provided.
     */
    Cartographic.fromRadians = function(longitude, latitude, height, result) {
        //>>includeStart('debug', pragmas.debug);
        Check.typeOf.number('longitude', longitude);
        Check.typeOf.number('latitude', latitude);
        //>>includeEnd('debug');

        height = defaultValue(height, 0.0);

        if (!defined(result)) {
            return new Cartographic(longitude, latitude, height);
        }

        result.longitude = longitude;
        result.latitude = latitude;
        result.height = height;
        return result;
    };

    /**
     * Creates a new Cartographic instance from longitude and latitude
     * specified in degrees.  The values in the resulting object will
     * be in radians.
     *
     * @param {Number} longitude The longitude, in degrees.
     * @param {Number} latitude The latitude, in degrees.
     * @param {Number} [height=0.0] The height, in meters, above the ellipsoid.
     * @param {Cartographic} [result] The object onto which to store the result.
     * @returns {Cartographic} The modified result parameter or a new Cartographic instance if one was not provided.
     */
    Cartographic.fromDegrees = function(longitude, latitude, height, result) {
        //>>includeStart('debug', pragmas.debug);
        Check.typeOf.number('longitude', longitude);
        Check.typeOf.number('latitude', latitude);
        //>>includeEnd('debug');
        longitude = CesiumMath.toRadians(longitude);
        latitude = CesiumMath.toRadians(latitude);

        return Cartographic.fromRadians(longitude, latitude, height, result);
    };

    var cartesianToCartographicN = new Cartesian3();
    var cartesianToCartographicP = new Cartesian3();
    var cartesianToCartographicH = new Cartesian3();
    var wgs84OneOverRadii = new Cartesian3(1.0 / 6378137.0, 1.0 / 6378137.0, 1.0 / 6356752.3142451793);
    var wgs84OneOverRadiiSquared = new Cartesian3(1.0 / (6378137.0 * 6378137.0), 1.0 / (6378137.0 * 6378137.0), 1.0 / (6356752.3142451793 * 6356752.3142451793));
    var wgs84CenterToleranceSquared = CesiumMath.EPSILON1;

    /**
     * Creates a new Cartographic instance from a Cartesian position. The values in the
     * resulting object will be in radians.
     *
     * @param {Cartesian3} cartesian The Cartesian position to convert to cartographic representation.
     * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid on which the position lies.
     * @param {Cartographic} [result] The object onto which to store the result.
     * @returns {Cartographic} The modified result parameter, new Cartographic instance if none was provided, or undefined if the cartesian is at the center of the ellipsoid.
     */
    Cartographic.fromCartesian = function(cartesian, ellipsoid, result) {
        var oneOverRadii = defined(ellipsoid) ? ellipsoid.oneOverRadii : wgs84OneOverRadii;
        var oneOverRadiiSquared = defined(ellipsoid) ? ellipsoid.oneOverRadiiSquared : wgs84OneOverRadiiSquared;
        var centerToleranceSquared = defined(ellipsoid) ? ellipsoid._centerToleranceSquared : wgs84CenterToleranceSquared;

        //`cartesian is required.` is thrown from scaleToGeodeticSurface
        var p = scaleToGeodeticSurface(cartesian, oneOverRadii, oneOverRadiiSquared, centerToleranceSquared, cartesianToCartographicP);

        if (!defined(p)) {
            return undefined;
        }

        var n = Cartesian3.multiplyComponents(p, oneOverRadiiSquared, cartesianToCartographicN);
        n = Cartesian3.normalize(n, n);

        var h = Cartesian3.subtract(cartesian, p, cartesianToCartographicH);

        var longitude = Math.atan2(n.y, n.x);
        var latitude = Math.asin(n.z);
        var height = CesiumMath.sign(Cartesian3.dot(h, cartesian)) * Cartesian3.magnitude(h);

        if (!defined(result)) {
            return new Cartographic(longitude, latitude, height);
        }
        result.longitude = longitude;
        result.latitude = latitude;
        result.height = height;
        return result;
    };

    /**
     * Returns a Cartesian3 position from a {@link Cartographic} input.
     *
     * @param {Cartographic} Cartographic input to be converted into a Cartesian3 output.
     * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid on which the position lies.
     * @param {Cartesian3} [result] The object onto which to store the result.
     * @returns {Cartesian3} The position
     */
    Cartographic.toCartesian3 = function(cartographicLocation, ellipsoid, result) {
        //>>includeStart('debug', pragmas.debug);
        Check.typeOf.number('cartographicLocation', Cartographic);
        //>>includeEnd('debug');

        return Cartesian3.fromRadians(cartographicLocation.longitude, cartographicLocation.latitude, cartographicLocation.height, ellipsoid, result);
    };

    /**
     * Duplicates a Cartographic instance.
     *
     * @param {Cartographic} cartographic The cartographic to duplicate.
     * @param {Cartographic} [result] The object onto which to store the result.
     * @returns {Cartographic} The modified result parameter or a new Cartographic instance if one was not provided. (Returns undefined if cartographic is undefined)
     */
    Cartographic.clone = function(cartographic, result) {
        if (!defined(cartographic)) {
            return undefined;
        }
        if (!defined(result)) {
            return new Cartographic(cartographic.longitude, cartographic.latitude, cartographic.height);
        }
        result.longitude = cartographic.longitude;
        result.latitude = cartographic.latitude;
        result.height = cartographic.height;
        return result;
    };

    /**
     * Compares the provided cartographics componentwise and returns
     * true if they are equal, false otherwise.
     *
     * @param {Cartographic} [left] The first cartographic.
     * @param {Cartographic} [right] The second cartographic.
     * @returns {Boolean} true if left and right are equal, false otherwise.
     */
    Cartographic.equals = function(left, right) {
        return (left === right) ||
                ((defined(left)) &&
                 (defined(right)) &&
                 (left.longitude === right.longitude) &&
                 (left.latitude === right.latitude) &&
                 (left.height === right.height));
    };

    /**
     * Compares the provided cartographics componentwise and returns
     * true if they are within the provided epsilon,
     * false otherwise.
     *
     * @param {Cartographic} [left] The first cartographic.
     * @param {Cartographic} [right] The second cartographic.
     * @param {Number} epsilon The epsilon to use for equality testing.
     * @returns {Boolean} true if left and right are within the provided epsilon, false otherwise.
     */
    Cartographic.equalsEpsilon = function(left, right, epsilon) {
        //>>includeStart('debug', pragmas.debug);
        Check.typeOf.number('epsilon', epsilon);
        //>>includeEnd('debug');

        return (left === right) ||
               ((defined(left)) &&
                (defined(right)) &&
                (Math.abs(left.longitude - right.longitude) <= epsilon) &&
                (Math.abs(left.latitude - right.latitude) <= epsilon) &&
                (Math.abs(left.height - right.height) <= epsilon));
    };

    /**
     * An immutable Cartographic instance initialized to (0.0, 0.0, 0.0).
     *
     * @type {Cartographic}
     * @constant
     */
    Cartographic.ZERO = freezeObject(new Cartographic(0.0, 0.0, 0.0));

    /**
     * Duplicates this instance.
     *
     * @param {Cartographic} [result] The object onto which to store the result.
     * @returns {Cartographic} The modified result parameter or a new Cartographic instance if one was not provided.
     */
    Cartographic.prototype.clone = function(result) {
        return Cartographic.clone(this, result);
    };

    /**
     * Compares the provided against this cartographic componentwise and returns
     * true if they are equal, false otherwise.
     *
     * @param {Cartographic} [right] The second cartographic.
     * @returns {Boolean} true if left and right are equal, false otherwise.
     */
    Cartographic.prototype.equals = function(right) {
        return Cartographic.equals(this, right);
    };

    /**
     * Compares the provided against this cartographic componentwise and returns
     * true if they are within the provided epsilon,
     * false otherwise.
     *
     * @param {Cartographic} [right] The second cartographic.
     * @param {Number} epsilon The epsilon to use for equality testing.
     * @returns {Boolean} true if left and right are within the provided epsilon, false otherwise.
     */
    Cartographic.prototype.equalsEpsilon = function(right, epsilon) {
        return Cartographic.equalsEpsilon(this, right, epsilon);
    };

    /**
     * Creates a string representing this cartographic in the format '(longitude, latitude, height)'.
     *
     * @returns {String} A string representing the provided cartographic in the format '(longitude, latitude, height)'.
     */
    Cartographic.prototype.toString = function() {
        return '(' + this.longitude + ', ' + this.latitude + ', ' + this.height + ')';
    };

    return Cartographic;
});
<commit_msg>finished swap<commit_after>define([
        './Cartesian3',
        './Check',
        './defaultValue',
        './defined',
        './DeveloperError',
        './freezeObject',
        './Math',
        './scaleToGeodeticSurface'
    ], function(
        Cartesian3,
        Check,
        defaultValue,
        defined,
        DeveloperError,
        freezeObject,
        CesiumMath,
        scaleToGeodeticSurface) {
    'use strict';

    /**
     * A position defined by longitude, latitude, and height.
     * @alias Cartographic
     * @constructor
     *
     * @param {Number} [longitude=0.0] The longitude, in radians.
     * @param {Number} [latitude=0.0] The latitude, in radians.
     * @param {Number} [height=0.0] The height, in meters, above the ellipsoid.
     *
     * @see Ellipsoid
     */
    function Cartographic(longitude, latitude, height) {
        /**
         * The longitude, in radians.
         * @type {Number}
         * @default 0.0
         */
        this.longitude = defaultValue(longitude, 0.0);

        /**
         * The latitude, in radians.
         * @type {Number}
         * @default 0.0
         */
        this.latitude = defaultValue(latitude, 0.0);

        /**
         * The height, in meters, above the ellipsoid.
         * @type {Number}
         * @default 0.0
         */
        this.height = defaultValue(height, 0.0);
    }

    /**
     * Creates a new Cartographic instance from longitude and latitude
     * specified in radians.
     *
     * @param {Number} longitude The longitude, in radians.
     * @param {Number} latitude The latitude, in radians.
     * @param {Number} [height=0.0] The height, in meters, above the ellipsoid.
     * @param {Cartographic} [result] The object onto which to store the result.
     * @returns {Cartographic} The modified result parameter or a new Cartographic instance if one was not provided.
     */
    Cartographic.fromRadians = function(longitude, latitude, height, result) {
        //>>includeStart('debug', pragmas.debug);
        Check.typeOf.number('longitude', longitude);
        Check.typeOf.number('latitude', latitude);
        //>>includeEnd('debug');

        height = defaultValue(height, 0.0);

        if (!defined(result)) {
            return new Cartographic(longitude, latitude, height);
        }

        result.longitude = longitude;
        result.latitude = latitude;
        result.height = height;
        return result;
    };

    /**
     * Creates a new Cartographic instance from longitude and latitude
     * specified in degrees.  The values in the resulting object will
     * be in radians.
     *
     * @param {Number} longitude The longitude, in degrees.
     * @param {Number} latitude The latitude, in degrees.
     * @param {Number} [height=0.0] The height, in meters, above the ellipsoid.
     * @param {Cartographic} [result] The object onto which to store the result.
     * @returns {Cartographic} The modified result parameter or a new Cartographic instance if one was not provided.
     */
    Cartographic.fromDegrees = function(longitude, latitude, height, result) {
        //>>includeStart('debug', pragmas.debug);
        Check.typeOf.number('longitude', longitude);
        Check.typeOf.number('latitude', latitude);
        //>>includeEnd('debug');
        longitude = CesiumMath.toRadians(longitude);
        latitude = CesiumMath.toRadians(latitude);

        return Cartographic.fromRadians(longitude, latitude, height, result);
    };

    var cartesianToCartographicN = new Cartesian3();
    var cartesianToCartographicP = new Cartesian3();
    var cartesianToCartographicH = new Cartesian3();
    var wgs84OneOverRadii = new Cartesian3(1.0 / 6378137.0, 1.0 / 6378137.0, 1.0 / 6356752.3142451793);
    var wgs84OneOverRadiiSquared = new Cartesian3(1.0 / (6378137.0 * 6378137.0), 1.0 / (6378137.0 * 6378137.0), 1.0 / (6356752.3142451793 * 6356752.3142451793));
    var wgs84CenterToleranceSquared = CesiumMath.EPSILON1;

    /**
     * Creates a new Cartographic instance from a Cartesian position. The values in the
     * resulting object will be in radians.
     *
     * @param {Cartesian3} cartesian The Cartesian position to convert to cartographic representation.
     * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid on which the position lies.
     * @param {Cartographic} [result] The object onto which to store the result.
     * @returns {Cartographic} The modified result parameter, new Cartographic instance if none was provided, or undefined if the cartesian is at the center of the ellipsoid.
     */
    Cartographic.fromCartesian = function(cartesian, ellipsoid, result) {
        var oneOverRadii = defined(ellipsoid) ? ellipsoid.oneOverRadii : wgs84OneOverRadii;
        var oneOverRadiiSquared = defined(ellipsoid) ? ellipsoid.oneOverRadiiSquared : wgs84OneOverRadiiSquared;
        var centerToleranceSquared = defined(ellipsoid) ? ellipsoid._centerToleranceSquared : wgs84CenterToleranceSquared;

        //`cartesian is required.` is thrown from scaleToGeodeticSurface
        var p = scaleToGeodeticSurface(cartesian, oneOverRadii, oneOverRadiiSquared, centerToleranceSquared, cartesianToCartographicP);

        if (!defined(p)) {
            return undefined;
        }

        var n = Cartesian3.multiplyComponents(p, oneOverRadiiSquared, cartesianToCartographicN);
        n = Cartesian3.normalize(n, n);

        var h = Cartesian3.subtract(cartesian, p, cartesianToCartographicH);

        var longitude = Math.atan2(n.y, n.x);
        var latitude = Math.asin(n.z);
        var height = CesiumMath.sign(Cartesian3.dot(h, cartesian)) * Cartesian3.magnitude(h);

        if (!defined(result)) {
            return new Cartographic(longitude, latitude, height);
        }
        result.longitude = longitude;
        result.latitude = latitude;
        result.height = height;
        return result;
    };

    /**
     * Returns a Cartesian3 position from a {@link Cartographic} input.
     *
     * @param {Cartographic} Cartographic input to be converted into a Cartesian3 output.
     * @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid on which the position lies.
     * @param {Cartesian3} [result] The object onto which to store the result.
     * @returns {Cartesian3} The position
     */
    Cartographic.toCartesian3 = function(cartographic, ellipsoid, result) {
        //>>includeStart('debug', pragmas.debug);
        if (!defined(cartographic)) {
            throw new DeveloperError('cartographic is required.');
        }
        //>>includeEnd('debug');

        return Cartesian3.fromRadians(cartographic.longitude, cartographic.latitude, cartographic.height, ellipsoid, result);
    };

    /**
     * Duplicates a Cartographic instance.
     *
     * @param {Cartographic} cartographic The cartographic to duplicate.
     * @param {Cartographic} [result] The object onto which to store the result.
     * @returns {Cartographic} The modified result parameter or a new Cartographic instance if one was not provided. (Returns undefined if cartographic is undefined)
     */
    Cartographic.clone = function(cartographic, result) {
        if (!defined(cartographic)) {
            return undefined;
        }
        if (!defined(result)) {
            return new Cartographic(cartographic.longitude, cartographic.latitude, cartographic.height);
        }
        result.longitude = cartographic.longitude;
        result.latitude = cartographic.latitude;
        result.height = cartographic.height;
        return result;
    };

    /**
     * Compares the provided cartographics componentwise and returns
     * true if they are equal, false otherwise.
     *
     * @param {Cartographic} [left] The first cartographic.
     * @param {Cartographic} [right] The second cartographic.
     * @returns {Boolean} true if left and right are equal, false otherwise.
     */
    Cartographic.equals = function(left, right) {
        return (left === right) ||
                ((defined(left)) &&
                 (defined(right)) &&
                 (left.longitude === right.longitude) &&
                 (left.latitude === right.latitude) &&
                 (left.height === right.height));
    };

    /**
     * Compares the provided cartographics componentwise and returns
     * true if they are within the provided epsilon,
     * false otherwise.
     *
     * @param {Cartographic} [left] The first cartographic.
     * @param {Cartographic} [right] The second cartographic.
     * @param {Number} epsilon The epsilon to use for equality testing.
     * @returns {Boolean} true if left and right are within the provided epsilon, false otherwise.
     */
    Cartographic.equalsEpsilon = function(left, right, epsilon) {
        //>>includeStart('debug', pragmas.debug);
        Check.typeOf.number('epsilon', epsilon);
        //>>includeEnd('debug');

        return (left === right) ||
               ((defined(left)) &&
                (defined(right)) &&
                (Math.abs(left.longitude - right.longitude) <= epsilon) &&
                (Math.abs(left.latitude - right.latitude) <= epsilon) &&
                (Math.abs(left.height - right.height) <= epsilon));
    };

    /**
     * An immutable Cartographic instance initialized to (0.0, 0.0, 0.0).
     *
     * @type {Cartographic}
     * @constant
     */
    Cartographic.ZERO = freezeObject(new Cartographic(0.0, 0.0, 0.0));

    /**
     * Duplicates this instance.
     *
     * @param {Cartographic} [result] The object onto which to store the result.
     * @returns {Cartographic} The modified result parameter or a new Cartographic instance if one was not provided.
     */
    Cartographic.prototype.clone = function(result) {
        return Cartographic.clone(this, result);
    };

    /**
     * Compares the provided against this cartographic componentwise and returns
     * true if they are equal, false otherwise.
     *
     * @param {Cartographic} [right] The second cartographic.
     * @returns {Boolean} true if left and right are equal, false otherwise.
     */
    Cartographic.prototype.equals = function(right) {
        return Cartographic.equals(this, right);
    };

    /**
     * Compares the provided against this cartographic componentwise and returns
     * true if they are within the provided epsilon,
     * false otherwise.
     *
     * @param {Cartographic} [right] The second cartographic.
     * @param {Number} epsilon The epsilon to use for equality testing.
     * @returns {Boolean} true if left and right are within the provided epsilon, false otherwise.
     */
    Cartographic.prototype.equalsEpsilon = function(right, epsilon) {
        return Cartographic.equalsEpsilon(this, right, epsilon);
    };

    /**
     * Creates a string representing this cartographic in the format '(longitude, latitude, height)'.
     *
     * @returns {String} A string representing the provided cartographic in the format '(longitude, latitude, height)'.
     */
    Cartographic.prototype.toString = function() {
        return '(' + this.longitude + ', ' + this.latitude + ', ' + this.height + ')';
    };

    return Cartographic;
});
<|endoftext|>