<commit_before>/*---------------------------------------------------------
 * John Resig Class, to be moved to openerp.base.Class
 *---------------------------------------------------------*/

(function() {
  var initializing = false, fnTest = /xyz/.test(function(){xyz;}) ? /\b_super\b/ : /.*/;
  // The base Class implementation (does nothing)
  this.Class = function(){};

  // Create a new Class that inherits from this class
  Class.extend = function(prop) {
    var _super = this.prototype;

    // Instantiate a base class (but only create the instance,
    // don't run the init constructor)
    initializing = true;
    var prototype = new this();
    initializing = false;

    // Copy the properties over onto the new prototype
    for (var name in prop) {
      // Check if we're overwriting an existing function
      prototype[name] = typeof prop[name] == "function" &&
        typeof _super[name] == "function" && fnTest.test(prop[name]) ?
        (function(name, fn){
          return function() {
            var tmp = this._super;

            // Add a new ._super() method that is the same method
            // but on the super-class
            this._super = _super[name];

            // The method only need to be bound temporarily, so we
            // remove it when we're done executing
            var ret = fn.apply(this, arguments);
            this._super = tmp;

            return ret;
          };
        })(name, prop[name]) :
        prop[name];
    }

    // The dummy class constructor
    function Class() {
      // All construction is actually done in the init method
      if ( !initializing && this.init )
        this.init.apply(this, arguments);
    }

    // Populate our constructed prototype object
    Class.prototype = prototype;

    // Enforce the constructor to be what we expect
    Class.constructor = Class;

    // And make this class extendable
    Class.extend = arguments.callee;

    return Class;
  };
})();

//---------------------------------------------------------
// OpenERP initialisation and black magic about the pool
//---------------------------------------------------------

(function(){

if(this.openerp)
    return;

var openerp = this.openerp = function() {
    // create a new pool instance
    var o = {};

    // links to the global openerp
    o._openerp = openerp;

    // Only base will be loaded, the rest will be by loaded by
    // openerp.base.Connection on the first connection
    o._modules_loaded = false;

    // this unique id will be replaced by hostname_databasename by
    // openerp.base.Connection on the first connection
    o._session_id = "session" + openerp.sessions.length;
    openerp.sessions[o._session_id] = o;

    o.screen = openerp.screen;
    o.sessions = openerp.sessions;
    o.base = {};
    openerp.base(o);

    return o;
};

// element_ids registry linked to all controllers on the page
// TODO rename to elements, or keep gtk naming?
this.openerp.screen = {};

// Per session namespace
// openerp.<module> will map to
// openerp.sessions.servername_port_dbname_login.<module> using a closure
this.openerp.sessions = {};

})();

// vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax:
<commit_msg>Rename and reindent elements in boot.js to makes scope and flows clearer. Also use object literal when available<commit_after>/*---------------------------------------------------------
 * John Resig Class, to be moved to openerp.base.Class
 *---------------------------------------------------------*/

(function() {
  var initializing = false, fnTest = /xyz/.test(function(){xyz;}) ? /\b_super\b/ : /.*/;
  // The base Class implementation (does nothing)
  this.Class = function(){};

  // Create a new Class that inherits from this class
  Class.extend = function(prop) {
    var _super = this.prototype;

    // Instantiate a base class (but only create the instance,
    // don't run the init constructor)
    initializing = true;
    var prototype = new this();
    initializing = false;

    // Copy the properties over onto the new prototype
    for (var name in prop) {
      // Check if we're overwriting an existing function
      prototype[name] = typeof prop[name] == "function" &&
        typeof _super[name] == "function" && fnTest.test(prop[name]) ?
        (function(name, fn){
          return function() {
            var tmp = this._super;

            // Add a new ._super() method that is the same method
            // but on the super-class
            this._super = _super[name];

            // The method only need to be bound temporarily, so we
            // remove it when we're done executing
            var ret = fn.apply(this, arguments);
            this._super = tmp;

            return ret;
          };
        })(name, prop[name]) :
        prop[name];
    }

    // The dummy class constructor
    function Class() {
      // All construction is actually done in the init method
      if ( !initializing && this.init )
        this.init.apply(this, arguments);
    }

    // Populate our constructed prototype object
    Class.prototype = prototype;

    // Enforce the constructor to be what we expect
    Class.constructor = Class;

    // And make this class extendable
    Class.extend = arguments.callee;

    return Class;
  };
})();

//---------------------------------------------------------
// OpenERP initialisation and black magic about the pool
//---------------------------------------------------------

(function() {
    if (this.openerp)
        return;

    // openerp instance constructor
    var openerp = this.openerp = function() {
        var new_instance = {
            // links to the global openerp
            _openerp: openerp,
            // Only base will be loaded, the rest will be by loaded by
            // openerp.base.Connection on the first connection
            _modules_loaded: false,
            // this unique id will be replaced by hostname_databasename by
            // openerp.base.Connection on the first connection
            _session_id: "session" + openerp.sessions.length,
            screen: openerp.screen,
            sessions: openerp.sessions,
            base: {}
        };
        openerp.sessions[new_instance._session_id] = new_instance;
        openerp.base(new_instance);

        return new_instance;
    };

    // element_ids registry linked to all controllers on the page
    // TODO rename to elements, or keep gtk naming?
    this.openerp.screen = {};

    // Per session namespace
    // openerp.<module> will map to
    // openerp.sessions.servername_port_dbname_login.<module> using a closure
    this.openerp.sessions = {};

})();

// vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax:
<|endoftext|>


<commit_before><commit_msg>Clean out unused models in Project Controller<commit_after><|endoftext|>


<commit_before>/*
 * Waltz - Enterprise Architecture
 * Copyright (C) 2016, 2017 Waltz open source project
 * See README.md for more information
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

import template from "./immediate-hierarchy-navigator.html";
import {initialiseData} from "../../../common/index";

const bindings = {
    parents: '<',
    children: '<'
};

const initialState = {
    parents: [],
    children: []
};

function controller($state) {

    const vm = initialiseData(this, initialState);

    vm.$onChanges = ((changes) => {
        console.log({ parents: vm.parents, children: vm.children })
    });
}

controller.$inject = ['$state'];

const component = {
    template,
    controller,
    bindings
};

export default component;<commit_msg>Better tooltips - bonus refactored the org unit view<commit_after>/*
 * Waltz - Enterprise Architecture
 * Copyright (C) 2016, 2017 Waltz open source project
 * See README.md for more information
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

import template from "./immediate-hierarchy-navigator.html";
import {initialiseData} from "../../../common/index";

const bindings = {
    parents: '<',
    children: '<'
};

const initialState = {
    parents: [],
    children: []
};

function controller($state) {
    const vm = initialiseData(this, initialState);
}

controller.$inject = ['$state'];

const component = {
    template,
    controller,
    bindings
};

export default component;<|endoftext|>


<commit_before><commit_msg>Resize all genoverse tracks manually so that empty tracks are not collapsed<commit_after><|endoftext|>


<commit_before><commit_msg>Added migration to tickets table<commit_after><|endoftext|>


<commit_before>/**
 * Created by sivashchenko on 12/25/2014.
 */
var marker;
function fillAddress(latitude, logitude) {
    GMaps.geocode({
        latLng: {
            lat: latitude,
            lng: logitude
        },
        callback: function (results, status) {
            if (status == 'OK') {
                $('#form_address').val(results[0].formatted_address);
            }
        }
    })
}
var map = new GMaps({
    el: '#map',
    lat: -12.043333,
    lng: -77.028333,
    click: function(args) {
        if (marker) {
            marker.setPosition({
                lat: args.latLng.lat(),
                lng: args.latLng.lng()
            });
        } else {
            marker = map.addMarker({
                lat: args.latLng.lat(),
                lng: args.latLng.lng()
            });
        }
        $('#form_position').val(String(args.latLng.lat()) + ',' + (String(args.latLng.lng())));
        fillAddress(args.latLng.lat(), args.latLng.lng());
    },
});
GMaps.geolocate({
    success: function(position) {
        map.setCenter(position.coords.latitude, position.coords.longitude);
        $('#form_position').val(String(position.coords.latitude) + ',' + (String(position.coords.longitude)));
        fillAddress(position.coords.latitude, position.coords.longitude);
        marker = map.addMarker({
            lat: position.coords.latitude,
            lng: position.coords.longitude
        });
    },
    error: function(error) {
        //map.setCenter(-12.043333, -77.028333);
    },
    not_supported: function() {
        //alert("Your browser does not support geolocation");
    },
    always: function() {
        //alert("Done!");
    }
});
$('#form_address').change(function() {
    GMaps.geocode({
        address: $('#form_address').val(),
        callback: function(results, status) {
            if (status == 'OK') {
                var latLng = results[0].geometry.location;
                map.setCenter(latLng.lat(), latLng.lng());
                $('#form_position').val(String(latLng.lat()) + ',' + (String(latLng.lng())));
                //fillAddress(latLng.lat(), latLng.lng());
                if (marker) {
                    marker.setPosition({
                        lat: latLng.lat(),
                        lng: latLng.lng()
                    });
                } else {
                    marker = map.addMarker({
                        lat: latLng.lat(),
                        lng: latLng.lng()
                    });
                }
            }
        }
    });
});
$('[data-role="create_category"]').click(function() {
    $.ajax({
        type: 'post',
        url: $(this).data('url'),
        data: { name: $('#category_name').val() },
        success: function(data) {
            category = JSON.parse(data);
            var option = new Option(category.name, category.id);
            $('#form_category').append($(option));
            $('#form_category').val(category.id);
            $('#createCategoryPopup').modal('hide');
        }
    });
});<commit_msg>#23363922957061 Shorted address<commit_after>/**
 * Created by sivashchenko on 12/25/2014.
 */
var marker;
function fillAddress(latitude, logitude) {
    GMaps.geocode({
        latLng: {
            lat: latitude,
            lng: logitude
        },
        callback: function (results, status) {
            if (status == 'OK') {
                $('#form_address').val(results[0].address_components[1].short_name + ', ' + results[0].address_components[0].short_name);
            }
        }
    })
}
var map = new GMaps({
    el: '#map',
    lat: -12.043333,
    lng: -77.028333,
    click: function(args) {
        if (marker) {
            marker.setPosition({
                lat: args.latLng.lat(),
                lng: args.latLng.lng()
            });
        } else {
            marker = map.addMarker({
                lat: args.latLng.lat(),
                lng: args.latLng.lng()
            });
        }
        $('#form_position').val(String(args.latLng.lat()) + ',' + (String(args.latLng.lng())));
        fillAddress(args.latLng.lat(), args.latLng.lng());
    },
});
GMaps.geolocate({
    success: function(position) {
        map.setCenter(position.coords.latitude, position.coords.longitude);
        $('#form_position').val(String(position.coords.latitude) + ',' + (String(position.coords.longitude)));
        fillAddress(position.coords.latitude, position.coords.longitude);
        marker = map.addMarker({
            lat: position.coords.latitude,
            lng: position.coords.longitude
        });
    },
    error: function(error) {
        //map.setCenter(-12.043333, -77.028333);
    },
    not_supported: function() {
        //alert("Your browser does not support geolocation");
    },
    always: function() {
        //alert("Done!");
    }
});
$('#form_address').change(function() {
    GMaps.geocode({
        address: $('#form_address').val(),
        callback: function(results, status) {
            if (status == 'OK') {
                var latLng = results[0].geometry.location;
                map.setCenter(latLng.lat(), latLng.lng());
                $('#form_position').val(String(latLng.lat()) + ',' + (String(latLng.lng())));
                //fillAddress(latLng.lat(), latLng.lng());
                if (marker) {
                    marker.setPosition({
                        lat: latLng.lat(),
                        lng: latLng.lng()
                    });
                } else {
                    marker = map.addMarker({
                        lat: latLng.lat(),
                        lng: latLng.lng()
                    });
                }
            }
        }
    });
});
$('[data-role="create_category"]').click(function() {
    $.ajax({
        type: 'post',
        url: $(this).data('url'),
        data: { name: $('#category_name').val() },
        success: function(data) {
            category = JSON.parse(data);
            var option = new Option(category.name, category.id);
            $('#form_category').append($(option));
            $('#form_category').val(category.id);
            $('#createCategoryPopup').modal('hide');
        }
    });
});<|endoftext|>


<commit_before>/* global statsData, moment */
(function() {
	'use strict';

	statsData.events = statsData.events || {};

	statsData.events.updates = {
		styling: {
			color: '#FFFF00'
		},

		data: [
			{
				title: '10.73 Update',
				date: '2015-01-20'
			},
			{
				title: '10.72 Update',
				date: '2015-01-13'
			},
			{
				title: '10.71 Update',
				date: '2014-12-16'
			},
			{
				title: '10.70 Update',
				date: '2014-12-10'
			},
			{
				title: '10.64 Update',
				date: '2014-12-04'
			},
			{
				title: '10.63 Update',
				date: '2014-11-19'
			},
			{
				title: '10.62 Update',
				date: '2014-11-12'
			},
			{
				title: '10.61 Update',
				date: '2014-10-30'
			},
			{
				title: '10.60 Update',
				date: '2014-10-28'
			},
			{
				title: '10.59 Update',
				date: '2014-10-08'
			},
			{
				title: '10.58 Update',
				date: '2014-10-06'
			},
			{
				title: '10.57 Update',
				date: '2014-09-30'
			},
			{
				title: '10.56 Update',
				date: '2014-09-24'
			},
			{
				title: '10.55 Update',
				date: '2014-09-15'
			},
			{
				title: '10.54 Update',
				date: '2014-09-09'
			},
			{
				title: '10.53 Update',
				date: '2014-08-26'
			},
			{
				title: '10.52 Update',
				date: '2014-08-12'
			},
			{
				title: '10.51 Update',
				date: '2014-07-22'
			},
			{
				title: '10.50 Update',
				date:  '2014-07-07'
			},
			{
				title: '10.41 Update',
				date: '2014-05-27'
			},
			{
				title: '10.40 Update',
				date: '2014-05-20'
			},
			{
				title: '10.39 Update',
				date: '2014-04-28'
			},
			{
				title: '10.38 Update',
				date: '2014-03-31'
			},
		]
	};

	statsData.events.updates.data.forEach(function (update) {
		update.date = moment.tz(update.date + ' 10:00', 'Europe/Berlin');
	});
})();<commit_msg>Add 10.74 update<commit_after>/* global statsData, moment */
(function() {
	'use strict';

	statsData.events = statsData.events || {};

	statsData.events.updates = {
		styling: {
			color: '#FFFF00'
		},

		data: [
			{
				title: '10.74 Update',
				date: '2015-01-27'
			},
			{
				title: '10.73 Update',
				date: '2015-01-20'
			},
			{
				title: '10.72 Update',
				date: '2015-01-13'
			},
			{
				title: '10.71 Update',
				date: '2014-12-16'
			},
			{
				title: '10.70 Update',
				date: '2014-12-10'
			},
			{
				title: '10.64 Update',
				date: '2014-12-04'
			},
			{
				title: '10.63 Update',
				date: '2014-11-19'
			},
			{
				title: '10.62 Update',
				date: '2014-11-12'
			},
			{
				title: '10.61 Update',
				date: '2014-10-30'
			},
			{
				title: '10.60 Update',
				date: '2014-10-28'
			},
			{
				title: '10.59 Update',
				date: '2014-10-08'
			},
			{
				title: '10.58 Update',
				date: '2014-10-06'
			},
			{
				title: '10.57 Update',
				date: '2014-09-30'
			},
			{
				title: '10.56 Update',
				date: '2014-09-24'
			},
			{
				title: '10.55 Update',
				date: '2014-09-15'
			},
			{
				title: '10.54 Update',
				date: '2014-09-09'
			},
			{
				title: '10.53 Update',
				date: '2014-08-26'
			},
			{
				title: '10.52 Update',
				date: '2014-08-12'
			},
			{
				title: '10.51 Update',
				date: '2014-07-22'
			},
			{
				title: '10.50 Update',
				date:  '2014-07-07'
			},
			{
				title: '10.41 Update',
				date: '2014-05-27'
			},
			{
				title: '10.40 Update',
				date: '2014-05-20'
			},
			{
				title: '10.39 Update',
				date: '2014-04-28'
			},
			{
				title: '10.38 Update',
				date: '2014-03-31'
			},
		]
	};

	statsData.events.updates.data.forEach(function (update) {
		update.date = moment.tz(update.date + ' 10:00', 'Europe/Berlin');
	});
})();<|endoftext|>


<commit_before>// Dynamic script loader that tracks loaded scripts.
// Can also use an event (similar to 'devireready' in Cordova)
// to notify when scripts are loaded (by using a script loading
// counter to track progress).

var evothings = (function(evothings)
{
	var scriptLoadingCounter = 0;
	var loadedScripts = {};
	var scriptsLoadedCallbacks = [];

	/**
	 * Load a script.
	 * @param url - URL or path to the script. Relative paths are
	 * relative to the HTML file that initiated script loading.
	 * @param callback - optional parameterless function that will
	 * be called when the script has loaded.
	 */
	evothings.loadScript = function(url, callback)
	{
		// If script is already loaded call callback directly and return.
		if (loadedScripts[url])
		{
			callback && callback();
			return;
		}

		// Add script to dictionaly of loaded scripts.
		loadedScripts[url] = 'loadingstarted';
		++scriptLoadingCounter;

		// Create script tag.
		var script = document.createElement('script');
		script.type = 'text/javascript';
		script.src = url;

		// Bind the onload event.
		script.onload = function()
		{
			// Mark as loaded.
			loadedScripts[url] = 'loadingcomplete';
			--scriptLoadingCounter;

			// Call callback if given.
			callback && callback();

			// Call scripts loaded callbacks if this was the last script loaded.
			if (0 == scriptLoadingCounter)
			{
				for (var i = 0; i < scriptsLoadedCallbacks.length; ++i)
				{
					(scriptsLoadedCallbacks[i])();
				}

				// Clear callbacks - should we do this???
				scriptsLoadedCallbacks = [];
			}
		}

		// onerror fires for things like malformed URLs and 404's.
		// If this function is called, the matching onload will not be called and
		// scriptsLoaded will not fire.
		script.onerror = function() {
			throw "Could not load script '"+url+"'";
		};

		// Attaching the script tag to the document starts loading the script.
		document.head.appendChild(script);
	}

	/**
	 * Add a callback that will be called when all scripts are loaded.
	 * @param callback - optional parameterless function that will
	 * be called when all scripts have loaded.
	 */
	evothings.scriptsLoaded = function(callback)
	{
		// If scripts are already loaded call the callback directly,
		// else add the callback to the callbacks array.
		if (0 != Object.keys(loadedScripts).length &&
			0 == scriptLoadingCounter)
		{
			callback();
		}
		else
		{
			scriptsLoadedCallbacks.push(callback);
		}
	};

	return evothings;

// If for some reason the global evothings variable is already defined we use it.
})(window.evothings || {});

window.addEventListener('DOMContentLoaded', function(e) {
	/* Set an absolute base font size in iOS 7 due to that viewport-relative
	font sizes doesn't work properly caused by the WebKit bug described at
	https://bugs.webkit.org/show_bug.cgi?id=131863. */
	if (/iP(hone|ad|od).*OS 7/.test(navigator.userAgent))
	{
		document.body.style.fontSize = '20pt'
	}
})
<commit_msg>Added platform checking functions.<commit_after>// Dynamic script loader that tracks loaded scripts.
// Can also use an event (similar to 'devireready' in Cordova)
// to notify when scripts are loaded (by using a script loading
// counter to track progress).

var evothings = (function(evothings)
{
	/* ------------------ Script loading ------------------ */

	var scriptLoadingCounter = 0;
	var loadedScripts = {};
	var scriptsLoadedCallbacks = [];

	/**
	 * Load a script.
	 * @param url - URL or path to the script. Relative paths are
	 * relative to the HTML file that initiated script loading.
	 * @param callback - optional parameterless function that will
	 * be called when the script has loaded.
	 */
	evothings.loadScript = function(url, callback)
	{
		// If script is already loaded call callback directly and return.
		if (loadedScripts[url])
		{
			callback && callback();
			return;
		}

		// Add script to dictionaly of loaded scripts.
		loadedScripts[url] = 'loadingstarted';
		++scriptLoadingCounter;

		// Create script tag.
		var script = document.createElement('script');
		script.type = 'text/javascript';
		script.src = url;

		// Bind the onload event.
		script.onload = function()
		{
			// Mark as loaded.
			loadedScripts[url] = 'loadingcomplete';
			--scriptLoadingCounter;

			// Call callback if given.
			callback && callback();

			// Call scripts loaded callbacks if this was the last script loaded.
			if (0 == scriptLoadingCounter)
			{
				for (var i = 0; i < scriptsLoadedCallbacks.length; ++i)
				{
					(scriptsLoadedCallbacks[i])();
				}

				// Clear callbacks - should we do this???
				scriptsLoadedCallbacks = [];
			}
		}

		// onerror fires for things like malformed URLs and 404's.
		// If this function is called, the matching onload will not be called and
		// scriptsLoaded will not fire.
		script.onerror = function() {
			throw "Could not load script '"+url+"'";
		};

		// Attaching the script tag to the document starts loading the script.
		document.head.appendChild(script);
	}

	/**
	 * Add a callback that will be called when all scripts are loaded.
	 * @param callback - optional parameterless function that will
	 * be called when all scripts have loaded.
	 */
	evothings.scriptsLoaded = function(callback)
	{
		// If scripts are already loaded call the callback directly,
		// else add the callback to the callbacks array.
		if (0 != Object.keys(loadedScripts).length &&
			0 == scriptLoadingCounter)
		{
			callback();
		}
		else
		{
			scriptsLoadedCallbacks.push(callback);
		}
	};

	/* ------------------ Platform check ------------------ */

	evothings.os = {};

	evothings.os.isIOS = function()
	{
		return /iP(hone|ad|od)/.test(navigator.userAgent);
	};

	evothings.os.isIOS7 = function()
	{
		return /iP(hone|ad|od).*OS 7/.test(navigator.userAgent);
	};

	evothings.os.isAndroid = function()
	{
		return /Android|android/.test(navigator.userAgent);
	};

	evothings.os.isWP = function()
	{
		return /Windows Phone/.test(navigator.userAgent);
	};

	return evothings;

// If for some reason the global evothings variable is already defined we use it.
})(window.evothings || {});

window.addEventListener('DOMContentLoaded', function(e) {
	/* Set an absolute base font size in iOS 7 due to that viewport-relative
	font sizes doesn't work properly caused by the WebKit bug described at
	https://bugs.webkit.org/show_bug.cgi?id=131863. */
	if (evothings.os.isIOS7())
	{
		document.body.style.fontSize = '20pt'
	}
})
<|endoftext|>


<commit_before>/*
 * Copyright 2016 EPAM Systems
 *
 *
 * This file is part of EPAM Report Portal.
 * https://github.com/reportportal/service-ui
 *
 * Report Portal is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Report Portal is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Report Portal.  If not, see <http://www.gnu.org/licenses/>.
 */

define(function (require) {
    'use strict';

    var $ = require('jquery');
    var Epoxy = require('backbone-epoxy');
    var Util = require('util');
    var FilterSearchItemView = require('modals/addWidget/widgetSettings/SettingFilters/SettingFilterSearchItemView');
    var FilterModel = require('filters/FilterModel');
    var FilterListener = require('controlers/filterControler/FilterListener');

    var FilterSearchItem = Epoxy.View.extend({
        className: 'setting-filter-selected',
        template: 'tpl-modal-add-widget-setting-filter-selected',
        events: {
            'click [data-js-filter-edit]': 'onClickFilterEdit'
        },
        initialize: function (options) {
            var self = this;
            this.model = options.gadgetModel;
            this.filterListener = new FilterListener();
            this.filterEvents = this.filterListener.events;
            this.render();
            this.filterModel = new FilterModel({
                id: this.model.get('filter_id'),
                temp: true,
                active: true
            });
            this.$el.addClass('load');
            self.filterListener.trigger(self.filterEvents.ON_LOAD_FILTER,
                this.model.get('filter_id')
            );
            this.listenTo(this.filterModel, 'change:load', this.onChangeLoadFilter);
        },
        onChangeLoadFilter: function (model, load) {
            this.model.set('filter_model', model);
            if (!load) {
                this.$el.removeClass('load');
                this.filterView && this.filterView.destroy();
                this.filterView = new FilterSearchItemView({ model: this.filterModel });
                $('[data-js-filter-info]', this.$el).html(this.filterView.$el);
            }
        },
        render: function () {
            this.$el.html(Util.templates(this.template, {}));
        },
        onClickFilterEdit: function () {
            // config.trackingDispatcher.trackEventNumber(321);
            this.trigger('edit');
        },
        validate: function () {
            console.dir(this.el);
        },
        onDestroy: function () {
            this.filterView && this.filterView.destroy();
            this.filterModel.destroy();
            this.$el.remove();
        }
    });

    return FilterSearchItem;
});
<commit_msg>fix edit widget modal<commit_after>/*
 * Copyright 2016 EPAM Systems
 *
 *
 * This file is part of EPAM Report Portal.
 * https://github.com/reportportal/service-ui
 *
 * Report Portal is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Report Portal is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Report Portal.  If not, see <http://www.gnu.org/licenses/>.
 */

define(function (require) {
    'use strict';

    var $ = require('jquery');
    var Epoxy = require('backbone-epoxy');
    var Util = require('util');
    var FilterSearchItemView = require('modals/addWidget/widgetSettings/SettingFilters/SettingFilterSearchItemView');
    var FilterModel = require('filters/FilterModel');
    var FilterListener = require('controlers/filterControler/FilterListener');

    var FilterSearchItem = Epoxy.View.extend({
        className: 'setting-filter-selected',
        template: 'tpl-modal-add-widget-setting-filter-selected',
        events: {
            'click [data-js-filter-edit]': 'onClickFilterEdit'
        },
        initialize: function (options) {
            var self = this;
            this.model = options.gadgetModel;
            this.filterListener = new FilterListener();
            this.filterEvents = this.filterListener.events;
            this.render();
            this.filterModel = new FilterModel({
                id: this.model.get('filter_id'),
                temp: true,
                active: true
            });
            this.$el.addClass('load');
            self.filterListener.trigger(self.filterEvents.ON_LOAD_FILTER,
                this.model.get('filter_id')
            );
            this.listenTo(this.filterModel, 'change:load', this.onChangeLoadFilter);
        },
        onChangeLoadFilter: function (model, load) {
            this.model.set('filter_model', model);
            if (!load) {
                this.$el.removeClass('load');
                this.filterView && this.filterView.destroy();
                this.filterView = new FilterSearchItemView({ model: this.filterModel });
                $('[data-js-filter-info]', this.$el).html(this.filterView.$el);
            }
        },
        render: function () {
            this.$el.html(Util.templates(this.template, {}));
        },
        onClickFilterEdit: function () {
            // config.trackingDispatcher.trackEventNumber(321);
            this.trigger('edit');
        },
        validate: function () {
            return true;
        },
        onDestroy: function () {
            this.filterView && this.filterView.destroy();
            this.filterModel.destroy();
            this.$el.remove();
        }
    });

    return FilterSearchItem;
});
<|endoftext|>


<commit_before>if (typeof(OpenM_SSOConnectionProxy) === 'undefined') {
    var OpenM_SSOConnectionProxy = {
        url: "",
        session_mode: "",
        api_selected: "",
        alreadyHaveConnectionOK: false,
        alreadyHaveTryingReconnection: false,
        MODE_PARAMETER: "API_SESSION_MODE",
        API_SELECTION_PARAMETER: "API",
        MODE_API_SELECTION: "API_SELECTION",
        MODE_ALL_API: "ALL_API",
        MODE_WITHOUT_API: "WITHOUT_API",
        ACTION_PARAMETER: "ACTION",
        IS_CONNECTED_ACTION: "isConnected",
        RETURN_IS_CONNECTED_PARAMETER: "isConnected",
        LOGIN_ACTION: "login",
        RETURN_TO_PARAMETER: "proxy_return_to",
        DASH: "! !",
        connected: false,
        frame: undefined,
        waitingConnectionInterval: 1000,
        waitingConnectionTimeOut: 120,
        waitingReConnectionTimeOut: 30,
        waitingConnectionInProgress: false,
        waitingReConnectionInProgress: false,
        redirectionToLoginFormEnabled: false,
        login: function() {
            if (this.connected)
                return;
            var u = this.url + "?" + this.MODE_PARAMETER + "=" + this.session_mode + "&" + this.API_SELECTION_PARAMETER + "=" + this.api_selected + "&" + this.ACTION_PARAMETER + "=" + this.LOGIN_ACTION + "&" + this.RETURN_TO_PARAMETER + "=" + encodeURI(window.location.href.replace("#", this.DASH));
            window.location = u;
        },
        open: function() {
            if (this.redirectionToLoginFormEnabled)
                return this.login();
            if (this.connected)
                return;
            if (this.waitingConnectionInProgress && typeof(this.frame) !== 'undefined' && !this.frame.closed)
                return;
            var width = 450;
            var height = 450;
            var left = (screen.width - width) / 2;
            var top = (screen.height - height) / 2;
            this.frame = window.open(this.url + "?" + this.MODE_PARAMETER + "=" + this.session_mode + "&" + this.API_SELECTION_PARAMETER + "=" + this.api_selected, "popup", "toolbar=0, location=0, directories=0, status=0, resizable=0, copyhistory=0, height=" + height + ", width=" + width + ", top=" + top + ", left=" + left + "");
            if (this.waitingConnectionInProgress)
                return;
            var c = this;
            var t;
            c.waitingConnectionInProgress = true;
            var i = setInterval(function() {
                if (typeof(c.frame) !== 'undefined' && c.frame.closed) {
                    if (typeof(t) !== 'undefined')
                        clearTimeout(t);
                    c.waitingConnectionInProgress = false;
                    if (typeof(i) !== 'undefined')
                        clearInterval(i);
                }
                c.isConnected(function() {
                    if (c.connected) {
                        clearInterval(i);
                        if (typeof(t) !== 'undefined')
                            clearTimeout(t);
                        if (c.frame !== undefined && typeof(c.frame.close) === 'function')
                            c.frame.close();
                        c.waitingConnectionInProgress = false;
                        c.onReconnectionOK();
                    }
                });
            }, c.waitingConnectionInterval);
            t = setTimeout(function() {
                if (typeof(i) !== 'undefined')
                    clearInterval(i);
                if (c.frame !== undefined && typeof(c.frame.close) === 'function')
                    c.frame.close();
                c.waitingConnectionInProgress = false;
            }, c.waitingConnectionTimeOut * 1000);
        },
        reconnectframe: undefined,
        reconnectionCheckInterval: undefined,
        reconnectionTimeOut: undefined,
        reconnect: function(loginIfNotConnected) {
            if (!this.alreadyHaveConnectionOK && loginIfNotConnected !== true)
                return;
            if (!this.alreadyHaveConnectionOK && loginIfNotConnected === true && this.alreadyHaveTryingReconnection === true)
                return this.open();
            if (this.waitingReConnectionInProgress)
                return;
            this.connected = false;
            this.alreadyHaveTryingReconnection = true;
            clearInterval(this.reconnectionCheckInterval);
            clearTimeout(this.reconnectionTimeOut);
            if (this.reconnectframe !== undefined)
                this.reconnectframe.remove();
            this.reconnectframe = $(document.createElement("iframe"));
            this.reconnectframe.attr("src", this.url + "?" + this.MODE_PARAMETER + "=" + this.session_mode + "&" + this.API_SELECTION_PARAMETER + "=" + this.api_selected);
            this.reconnectframe.attr("position", "absolute");
            this.reconnectframe.attr("right", 0);
            this.reconnectframe.attr("bottom", 0);
            this.reconnectframe.attr("width", 1);
            this.reconnectframe.attr("height", 1);
            this.reconnectframe.attr("border", 0);
            this.reconnectframe.attr("background-color", "transparent");
            this.reconnectframe.attr("z-index", 0);
            $("html body").append(this.reconnectframe);
            var c = this;
            var t = c.reconnectionTimeOut;
            c.waitingReConnectionInProgress = true;
            var i = c.reconnectionCheckInterval;
            i = setInterval(function() {
                c.isConnected(function() {
                    if (c.connected) {
                        clearInterval(i);
                        if (typeof(t) !== 'undefined')
                            clearTimeout(t);
                        if (c.reconnectframe !== undefined)
                            c.reconnectframe.remove();
                        c.waitingReConnectionInProgress = false;
                        c.onReconnectionOK();
                    }
                });
            }, c.waitingConnectionInterval);
            t = setTimeout(function() {
                if (typeof(i) !== 'undefined')
                    clearInterval(i);
                if (c.reconnectframe !== undefined && typeof(c.reconnectframe.close) === 'function')
                    c.reconnectframe.close();
                c.waitingReConnectionInProgress = false;
            }, c.waitingReConnectionTimeOut * 1000);
        },
        isConnected: function(callBack, synchro) {
            var c = this;
            if (synchro === undefined)
                synchro = false;
            var cb = callBack;
            var a = {
                async: !synchro,
                type: 'POST',
                data: {},
                url: this.url + "?" + this.MODE_PARAMETER + "=" + this.session_mode + "&" + this.API_SELECTION_PARAMETER + "=" + this.api_selected,
                dataType: 'json',
                success: function(data) {
                    if (data[c.RETURN_IS_CONNECTED_PARAMETER] === 1) {
                        c.connected = true;
                        c.alreadyHaveConnectionOK = true;
                    }
                    if (cb !== undefined)
                        cb();
                }
            };
            a.data[this.ACTION_PARAMETER] = this.IS_CONNECTED_ACTION;
            $.ajax(a);
            return this.connected;
        },
        reconnectionOkListeners: new Array(),
        addReconnectionOKListener: function(listener) {
            this.reconnectionOkListeners.push(listener);
        },
        onReconnectionOK: function() {
            $.each(this.reconnectionOkListeners, function(key, value) {
                if (typeof(value) === 'function')
                    value();
            });
        }
    };
}<commit_msg>add window reload on reconnect failure<commit_after>if (typeof(OpenM_SSOConnectionProxy) === 'undefined') {
    var OpenM_SSOConnectionProxy = {
        url: "",
        session_mode: "",
        api_selected: "",
        alreadyHaveConnectionOK: false,
        alreadyHaveTryingReconnection: false,
        MODE_PARAMETER: "API_SESSION_MODE",
        API_SELECTION_PARAMETER: "API",
        MODE_API_SELECTION: "API_SELECTION",
        MODE_ALL_API: "ALL_API",
        MODE_WITHOUT_API: "WITHOUT_API",
        ACTION_PARAMETER: "ACTION",
        IS_CONNECTED_ACTION: "isConnected",
        RETURN_IS_CONNECTED_PARAMETER: "isConnected",
        LOGIN_ACTION: "login",
        RETURN_TO_PARAMETER: "proxy_return_to",
        DASH: "! !",
        connected: false,
        frame: undefined,
        waitingConnectionInterval: 1000,
        waitingConnectionTimeOut: 120,
        waitingReConnectionTimeOut: 30,
        waitingConnectionInProgress: false,
        waitingReConnectionInProgress: false,
        redirectionToLoginFormEnabled: false,
        login: function() {
            if (this.connected)
                return;
            var u = this.url + "?" + this.MODE_PARAMETER + "=" + this.session_mode + "&" + this.API_SELECTION_PARAMETER + "=" + this.api_selected + "&" + this.ACTION_PARAMETER + "=" + this.LOGIN_ACTION + "&" + this.RETURN_TO_PARAMETER + "=" + encodeURI(window.location.href.replace("#", this.DASH));
            window.location = u;
        },
        open: function() {
            if (this.redirectionToLoginFormEnabled)
                return this.login();
            if (this.connected)
                return;
            if (this.waitingConnectionInProgress && typeof(this.frame) !== 'undefined' && !this.frame.closed)
                return;
            var width = 450;
            var height = 450;
            var left = (screen.width - width) / 2;
            var top = (screen.height - height) / 2;
            this.frame = window.open(this.url + "?" + this.MODE_PARAMETER + "=" + this.session_mode + "&" + this.API_SELECTION_PARAMETER + "=" + this.api_selected, "popup", "toolbar=0, location=0, directories=0, status=0, resizable=0, copyhistory=0, height=" + height + ", width=" + width + ", top=" + top + ", left=" + left + "");
            if (this.waitingConnectionInProgress)
                return;
            var c = this;
            var t;
            c.waitingConnectionInProgress = true;
            var i = setInterval(function() {
                if (typeof(c.frame) !== 'undefined' && c.frame.closed) {
                    if (typeof(t) !== 'undefined')
                        clearTimeout(t);
                    c.waitingConnectionInProgress = false;
                    if (typeof(i) !== 'undefined')
                        clearInterval(i);
                }
                c.isConnected(function() {
                    if (c.connected) {
                        clearInterval(i);
                        if (typeof(t) !== 'undefined')
                            clearTimeout(t);
                        if (c.frame !== undefined && typeof(c.frame.close) === 'function')
                            c.frame.close();
                        c.waitingConnectionInProgress = false;
                        c.onReconnectionOK();
                    }
                });
            }, c.waitingConnectionInterval);
            t = setTimeout(function() {
                if (typeof(i) !== 'undefined')
                    clearInterval(i);
                if (c.frame !== undefined && typeof(c.frame.close) === 'function')
                    c.frame.close();
                c.waitingConnectionInProgress = false;
            }, c.waitingConnectionTimeOut * 1000);
        },
        reconnectFail: function() {
            window.location.reload();
        },
        reconnectframe: undefined,
        reconnectionCheckInterval: undefined,
        reconnectionTimeOut: undefined,
        reconnect: function(loginIfNotConnected) {
            if (!this.alreadyHaveConnectionOK && loginIfNotConnected !== true)
                return;
            if (!this.alreadyHaveConnectionOK && loginIfNotConnected === true && this.alreadyHaveTryingReconnection === true)
                return this.open();
            if (this.waitingReConnectionInProgress)
                return;
            this.connected = false;
            this.alreadyHaveTryingReconnection = true;
            clearInterval(this.reconnectionCheckInterval);
            clearTimeout(this.reconnectionTimeOut);
            if (this.reconnectframe !== undefined)
                this.reconnectframe.remove();
            this.reconnectframe = $(document.createElement("iframe"));
            this.reconnectframe.attr("src", this.url + "?" + this.MODE_PARAMETER + "=" + this.session_mode + "&" + this.API_SELECTION_PARAMETER + "=" + this.api_selected);
            this.reconnectframe.attr("position", "absolute");
            this.reconnectframe.attr("right", 0);
            this.reconnectframe.attr("bottom", 0);
            this.reconnectframe.attr("width", 1);
            this.reconnectframe.attr("height", 1);
            this.reconnectframe.attr("border", 0);
            this.reconnectframe.attr("background-color", "transparent");
            this.reconnectframe.attr("z-index", 0);
            $("html body").append(this.reconnectframe);
            var c = this;
            var t = c.reconnectionTimeOut;
            c.waitingReConnectionInProgress = true;
            var i = c.reconnectionCheckInterval;
            i = setInterval(function() {
                c.isConnected(function() {
                    if (c.connected) {
                        clearInterval(i);
                        if (typeof(t) !== 'undefined')
                            clearTimeout(t);
                        if (c.reconnectframe !== undefined) {
                            setTimeout(function() {
                                if (c.reconnectframe !== undefined)
                                    c.reconnectframe.remove();
                            }, 2000);
                        }
                        c.waitingReConnectionInProgress = false;
                        c.onReconnectionOK();
                    }
                });
            }, c.waitingConnectionInterval);
            t = setTimeout(function() {
                if (typeof(i) !== 'undefined')
                    clearInterval(i);
                if (c.reconnectframe !== undefined && typeof(c.reconnectframe.close) === 'function')
                    setTimeout(function() {
                        if (c.reconnectframe !== undefined && typeof(c.reconnectframe.close) === 'function')
                            c.reconnectframe.close();
                    }, 2000);
                c.waitingReConnectionInProgress = false;
                if (!c.connected && typeof(c.reconnectFail) === "function")
                    c.reconnectFail();
            }, c.waitingReConnectionTimeOut * 1000);
        },
        isConnected: function(callBack, synchro) {
            var c = this;
            if (synchro === undefined)
                synchro = false;
            var cb = callBack;
            var a = {
                async: !synchro,
                type: 'POST',
                data: {},
                url: this.url + "?" + this.MODE_PARAMETER + "=" + this.session_mode + "&" + this.API_SELECTION_PARAMETER + "=" + this.api_selected,
                dataType: 'json',
                success: function(data) {
                    if (data[c.RETURN_IS_CONNECTED_PARAMETER] === 1) {
                        c.connected = true;
                        c.alreadyHaveConnectionOK = true;
                    }
                    if (cb !== undefined)
                        cb();
                }
            };
            a.data[this.ACTION_PARAMETER] = this.IS_CONNECTED_ACTION;
            $.ajax(a);
            return this.connected;
        },
        reconnectionOkListeners: new Array(),
        addReconnectionOKListener: function(listener) {
            this.reconnectionOkListeners.push(listener);
        },
        onReconnectionOK: function() {
            $.each(this.reconnectionOkListeners, function(key, value) {
                if (typeof(value) === 'function')
                    value();
            });
        }
    };
}<|endoftext|>


<commit_before><commit_msg>add wincent db tables<commit_after><|endoftext|>


<commit_before>// Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';

var Admin = require('../../bin/admin.js');
var allocCluster = require('../lib/test-cluster.js');

allocCluster.test('disable rate limiter and forward', {
    size: 3
}, function t(cluster, assert) {
    var bob = cluster.remotes.bob;

    Admin.exec('rate-limiter disable', {
        hosts: cluster.hostPortList
    }, function onSet1(err, arr) {
        assert.ifError(err);
        assert.equal(arr.length, 0);

        Admin.exec('rate-limiter total-limit 0', {
            hosts: cluster.hostPortList
        }, onSet2);
    });

    function onSet2(err, arr) {
        assert.ifError(err);
        assert.equal(arr.length, 0);

        Admin.exec('rate-limiter query', {
            hosts: cluster.hostPortList
        }, onQuery);
    }

    function onQuery(err, results) {
        assert.ifError(err);

        for (var i = 0; i < results.length; i++) {
            var result = results[i];
            assert.equal(result.settings.enabled, false, 'disable should work');
            assert.equal(result.settings.totalRpsLimit, 0, 'set totalRpsLimit should work');
        }

        bob.clientChannel.request({
            serviceName: 'steve',
            timeout: 10
        }).send('echo', null, JSON.stringify('oh hi lol'), onForwarded);
    }

    function onForwarded(err, res, arg2, arg3) {
        assert.ok(!err && res, 'should not fail');
        assert.end();
    }
});

allocCluster.test('set total rate limiter and forward', {
    size: 1,
    remoteConfig: {
        'rateLimiting.enabled': true,
        'rateLimiting.totalRpsLimit': 2,
        'rateLimiting.rpsLimitForServiceName': {
            'steve': 10
        },
        'rateLimiting.exemptServices': [
            'hyperbahn',
            'autobahn',
            'ringpop',
            'tcollector'
        ]
    }
}, function t(cluster, assert) {
    var bob = cluster.remotes.bob;

    Admin.exec('rate-limiter total-limit 0', {
        hosts: cluster.hostPortList
    }, function onSet(err, arr) {
        assert.ifError(err);
        assert.equal(arr.length, 0);

        Admin.exec('rate-limiter query', {
            hosts: cluster.hostPortList
        }, onQuery);
    });

    function onQuery(err, results) {
        assert.ifError(err);

        for (var i = 0; i < results.length; i++) {
            var result = results[i];
            assert.equal(result.settings.totalRpsLimit, 0, 'set totalRpsLimit should work');
            assert.equal(result.settings.rpsLimitForServiceName.steve, 10, 'set service limit should not affect others');
        }

        bob.clientChannel.request({
            serviceName: 'steve',
            timeout: 10
        }).send('echo', null, JSON.stringify('oh hi lol'), onReq);

        function onReq(err2) {
            assert.ifError(err2);

            bob.clientChannel.request({
                serviceName: 'steve',
                timeout: 10
            }).send('echo', null, JSON.stringify('oh hi lol'), onForwarded);
        }
    }

    function onForwarded(err, res, arg2, arg3) {
        assert.ok(err, 'should fail');
        assert.equal(err && err.type, 'tchannel.busy',
            'error type should be busy');

        assert.end();
    }
});

allocCluster.test('set service rate limiter and forward', {
    size: 1,
    remoteConfig: {
        'rateLimiting.enabled': true,
        'rateLimiting.totalRpsLimit': 1000,
        'rateLimiting.rpsLimitForServiceName': {
            'steve': 10
        },
        'rateLimiting.exemptServices': [
            'hyperbahn',
            'ringpop',
            'tcollector'
        ]
    }
}, function t(cluster, assert) {
    var bob = cluster.remotes.bob;

    Admin.exec('rate-limiter limit steve 1', {
        hosts: cluster.hostPortList
    }, function onSet(err, arr) {
        assert.ifError(err);
        assert.equal(arr.length, 0);

        Admin.exec('rate-limiter query', {
            hosts: cluster.hostPortList
        }, onQuery);
    });

    function onQuery(err, results) {
        assert.ifError(err);

        for (var i = 0; i < results.length; i++) {
            var result = results[i];
            assert.equal(result.settings.rpsLimitForServiceName.steve, 1, 'set service limit should work');
            assert.equal(result.settings.totalRpsLimit, 1000, 'set service limit should not affect others');
        }

        forward();
    }

    var count = 0;
    function forward() {
        var cb;
        if (count++ <= 1) {
            cb = forward;
        } else {
            cb = onForwarded;
        }
        bob.clientChannel.request({
            serviceName: 'steve',
            timeout: 10
        }).send('echo', null, JSON.stringify('oh hi lol'), cb);
    }

    function onForwarded(err, res, arg2, arg3) {
        assert.ok(err, 'should fail');
        assert.equal(err && err.type, 'tchannel.busy',
            'error type should be busy');

        assert.end();
    }
});

allocCluster.test('set exempt service and forward', {
    size: 2,
    remoteConfig: {
        'rateLimiting.enabled': true,
        'rateLimiting.totalRpsLimit': 1000,
        'rateLimiting.rpsLimitForServiceName': {
            'steve': 0
        },
        'rateLimiting.exemptServices': [
            'hyperbahn',
            'ringpop',
            'tcollector'
        ]
    }
}, function t(cluster, assert) {
    var bob = cluster.remotes.bob;

    Admin.exec('rate-limiter exempt add steve', {
        hosts: cluster.hostPortList
    }, function onSet(err, arr) {
        assert.ifError(err);
        assert.equal(arr.length, 0);

        Admin.exec('rate-limiter query', {
            hosts: cluster.hostPortList
        }, onQuery);
    });

    function onQuery(err, results) {
        assert.ifError(err);

        for (var i = 0; i < results.length; i++) {
            var result = results[i];
            assert.equal(result.settings.exemptServices[3], 'steve', 'set exempt services should work');
        }

        bob.clientChannel.request({
            serviceName: 'steve',
            timeout: 10
        }).send('echo', null, JSON.stringify('oh hi lol'), onForwarded);
    }

    function onForwarded(err, res, arg2, arg3) {
        assert.ok(!err, 'should not fail');
        assert.end();
    }
});
<commit_msg>Fix flappy Hyperbahn rate limit test<commit_after>// Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';

var Admin = require('../../bin/admin.js');
var allocCluster = require('../lib/test-cluster.js');

allocCluster.test('disable rate limiter and forward', {
    size: 3
}, function t(cluster, assert) {
    var bob = cluster.remotes.bob;

    Admin.exec('rate-limiter disable', {
        hosts: cluster.hostPortList
    }, function onSet1(err, arr) {
        assert.ifError(err);
        assert.equal(arr.length, 0);

        Admin.exec('rate-limiter total-limit 0', {
            hosts: cluster.hostPortList
        }, onSet2);
    });

    function onSet2(err, arr) {
        assert.ifError(err);
        assert.equal(arr.length, 0);

        Admin.exec('rate-limiter query', {
            hosts: cluster.hostPortList
        }, onQuery);
    }

    function onQuery(err, results) {
        assert.ifError(err);

        for (var i = 0; i < results.length; i++) {
            var result = results[i];
            assert.equal(result.settings.enabled, false, 'disable should work');
            assert.equal(result.settings.totalRpsLimit, 0, 'set totalRpsLimit should work');
        }

        bob.clientChannel.request({
            serviceName: 'steve',
            timeout: 100
        }).send('echo', null, JSON.stringify('oh hi lol'), onForwarded);
    }

    function onForwarded(err, res, arg2, arg3) {
        assert.ok(!err && res, 'should not fail');
        assert.end();
    }
});

allocCluster.test('set total rate limiter and forward', {
    size: 1,
    remoteConfig: {
        'rateLimiting.enabled': true,
        'rateLimiting.totalRpsLimit': 2,
        'rateLimiting.rpsLimitForServiceName': {
            'steve': 10
        },
        'rateLimiting.exemptServices': [
            'hyperbahn',
            'autobahn',
            'ringpop',
            'tcollector'
        ]
    }
}, function t(cluster, assert) {
    var bob = cluster.remotes.bob;

    Admin.exec('rate-limiter total-limit 0', {
        hosts: cluster.hostPortList
    }, function onSet(err, arr) {
        assert.ifError(err);
        assert.equal(arr.length, 0);

        Admin.exec('rate-limiter query', {
            hosts: cluster.hostPortList
        }, onQuery);
    });

    function onQuery(err, results) {
        assert.ifError(err);

        for (var i = 0; i < results.length; i++) {
            var result = results[i];
            assert.equal(result.settings.totalRpsLimit, 0, 'set totalRpsLimit should work');
            assert.equal(result.settings.rpsLimitForServiceName.steve, 10, 'set service limit should not affect others');
        }

        bob.clientChannel.request({
            serviceName: 'steve',
            timeout: 10
        }).send('echo', null, JSON.stringify('oh hi lol'), onReq);

        function onReq(err2) {
            assert.ifError(err2);

            bob.clientChannel.request({
                serviceName: 'steve',
                timeout: 10
            }).send('echo', null, JSON.stringify('oh hi lol'), onForwarded);
        }
    }

    function onForwarded(err, res, arg2, arg3) {
        assert.ok(err, 'should fail');
        assert.equal(err && err.type, 'tchannel.busy',
            'error type should be busy');

        assert.end();
    }
});

allocCluster.test('set service rate limiter and forward', {
    size: 1,
    remoteConfig: {
        'rateLimiting.enabled': true,
        'rateLimiting.totalRpsLimit': 1000,
        'rateLimiting.rpsLimitForServiceName': {
            'steve': 10
        },
        'rateLimiting.exemptServices': [
            'hyperbahn',
            'ringpop',
            'tcollector'
        ]
    }
}, function t(cluster, assert) {
    var bob = cluster.remotes.bob;

    Admin.exec('rate-limiter limit steve 1', {
        hosts: cluster.hostPortList
    }, function onSet(err, arr) {
        assert.ifError(err);
        assert.equal(arr.length, 0);

        Admin.exec('rate-limiter query', {
            hosts: cluster.hostPortList
        }, onQuery);
    });

    function onQuery(err, results) {
        assert.ifError(err);

        for (var i = 0; i < results.length; i++) {
            var result = results[i];
            assert.equal(result.settings.rpsLimitForServiceName.steve, 1, 'set service limit should work');
            assert.equal(result.settings.totalRpsLimit, 1000, 'set service limit should not affect others');
        }

        forward();
    }

    var count = 0;
    function forward() {
        var cb;
        if (count++ <= 1) {
            cb = forward;
        } else {
            cb = onForwarded;
        }
        bob.clientChannel.request({
            serviceName: 'steve',
            timeout: 10
        }).send('echo', null, JSON.stringify('oh hi lol'), cb);
    }

    function onForwarded(err, res, arg2, arg3) {
        assert.ok(err, 'should fail');
        assert.equal(err && err.type, 'tchannel.busy',
            'error type should be busy');

        assert.end();
    }
});

allocCluster.test('set exempt service and forward', {
    size: 2,
    remoteConfig: {
        'rateLimiting.enabled': true,
        'rateLimiting.totalRpsLimit': 1000,
        'rateLimiting.rpsLimitForServiceName': {
            'steve': 0
        },
        'rateLimiting.exemptServices': [
            'hyperbahn',
            'ringpop',
            'tcollector'
        ]
    }
}, function t(cluster, assert) {
    var bob = cluster.remotes.bob;

    Admin.exec('rate-limiter exempt add steve', {
        hosts: cluster.hostPortList
    }, function onSet(err, arr) {
        assert.ifError(err);
        assert.equal(arr.length, 0);

        Admin.exec('rate-limiter query', {
            hosts: cluster.hostPortList
        }, onQuery);
    });

    function onQuery(err, results) {
        assert.ifError(err);

        for (var i = 0; i < results.length; i++) {
            var result = results[i];
            assert.equal(result.settings.exemptServices[3], 'steve', 'set exempt services should work');
        }

        bob.clientChannel.request({
            serviceName: 'steve',
            timeout: 10
        }).send('echo', null, JSON.stringify('oh hi lol'), onForwarded);
    }

    function onForwarded(err, res, arg2, arg3) {
        assert.ok(!err, 'should not fail');
        assert.end();
    }
});
<|endoftext|>


<commit_before>angular.module('sfSense', ['ionic'])

.factory('googleMaps', function(){
  // OVERVIEW
  // 1. setup map options
  // 2. create map
  // 3. get data for crime lat and lng
  // 4. create markers
  // 5. add markers to map
  var map;
  var markers = {};
  var filterOn = 'all';
  var isViolent = {
    'ASSAULT': true,
    'NON-CRIMINAL': false,
    'OTHER OFFENSES': false,
    'ROBBERY': true,
    'LARCENY/THEFT': false,
    'VANDALISM': false,
    'BURGLARY': false,
    'VEHICLE THEFT': false,
    'FRAUD': false,
    'DRUNKENNESS': false,
    'WARRANTS': false,
    'TRESPASS': false,
    'KIDNAPPING': true,
    'SEX OFFENSES': true,
    'WEAPON LAWS': true,
    'DRUG/NARCOTIC': false,
    'FORGERY/COUNTERFEITING': false,
    'MISSING PERSON': false,
    'LIQUOR LAWS': false,
    'BAD CHECKS': false,
    'RUNAWAY': false,
    'EMBEZZLEMENT': false
  };

  var iconPath = '../www/img/icons/';

  // TODO: add marker img for each category
  var markerImg = {
    'BURGLARY': 'robbery.png',
    'LARCENY/THEFT': 'theft.png',
    'ASSAULT': 'robbery.png',
    'MISSING PERSON': 'missing.png',
    'DEFAULT': 'blast.png'
  };

  var createMarker = function(crime) {

    if (markers[crime.id] === undefined) { // if crime isn't displayed yet add it
      var latlng = new google.maps.LatLng(crime.latitude,crime.longitude);

      var icon;

      if(markerImg[crime.category]){
        icon = iconPath + markerImg[crime.category];
      } else {
        icon = iconPath + markerImg.DEFAULT;
      }

      var newMarker = new google.maps.Marker({
        position: latlng,
        animation: google.maps.Animation.DROP,
        title: crime.category,
        icon: icon,
        id: crime.id,
        category: crime.category,
        date: crime.date,
        time: crime.time,
        description: crime.descript,
        type: crime.type.toLowerCase()
      });

      // check if the marker should be displayed or not
      if (filterOn === 'all' || filterOn === crime.type) {
        newMarker.setMap(map);
      }
      // make a new InfoWindow and associate it to the marker
      newMarker.info = new google.maps.InfoWindow({
        content: '
' + newMarker.description + '
'
      });
      // add the map listener here
      google.maps.event.addListener(newMarker, 'mouseover', function(){
        newMarker.info.open(map, newMarker);
      });

      markers[crime.id] = newMarker; // add it to the markers object
    }
  };

  return {

    // Add in google maps functions here

    createMap: function(lat, lng){
      var mapOptions = {
        center: new google.maps.LatLng(lat, lng),
        zoom: 17,
        panControl: false,
        zoomControl: false,
        mapTypeControl: false,
        streetViewControl: false,
        overviewMapControl: false
      };

      map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
    },

    // CreateMap is not invoked yet so we define addListener to add the event listener
    // Once the map has been created, call addListener
    // Moving method outside of the create call allows access to other services in googleMaps
    // There will only be one map variable so accept only the event and function
    addListener: function(event, func) {
      google.maps.event.addListener(map, event, func);
    },

    createMarkers: function(crimes) {
        for(var i = 0; i < crimes.length; i++){
          createMarker(crimes[i]);
        }
    },

    clearMap: function() {
      // first hide all the markers by setting map to null
      for (var i = 0; i < markers.length; i++) {
        markers[i].setMap(null);
      }
      // we no longer want access to the markers so remove them
      markers = {};
    },

    moveTo: function(lat, lng){
      var latlng = new google.maps.LatLng(lat,lng);
      map.panTo(latlng);
    },

    getCenter: function() {
      // returns latlng object with lat() and lng() methods
      return map.getCenter();
    },

    searchLocByAddress: function(address, cb) {
      var city = 'san francisco';
      var re = RegExp(city, 'i');

      if(!re.exec(address)){
        address = address + ' ' + city;
      }

      geocoder = new google.maps.Geocoder();

      geocoder.geocode( {'address': address}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
          map.setCenter(results[0].geometry.location);

          cb(results[0].geometry.location.k, results[0].geometry.location.A);

        } else {
          navigator.notification.alert('Error with find location: ' + status);
        }
      });
    },

    searchLoc: function(lat, lng, cb){
      var latlng = new google.maps.LatLng(lat,lng);
      map.setCenter(latlng);
      cb(lat, lng);
    },

    filterBy: function(filter){
      // set filterOn
      filterOn = filter;
      // the filter will match the type field on the markers
      for (var markerID in markers) {

        var marker = markers[markerID];
        var cat = marker.type;

        // check if the filter is all, if so, show all markers
        if (filter === 'all') {
          marker.setMap(map);
        } else { // a filter was specified
          if (filter === cat) { // filter matches marker type
            marker.setMap(map);
          } else { // filter doesn't match marker type
            marker.setMap(null);
          }
        }
      }
    }
  };
})

.controller('MapCtrl', function($scope, $http, googleMaps){

  $scope.filters = ['other', 'assault', 'theft'];

  var hideKeyboard = function() {
    document.activeElement.blur();
    $("input").blur();
  };

  var init = function() {
    // SF center lat and lng
    var lat = 37.783522;
    var lng = -122.408964;

    googleMaps.createMap(lat, lng);

    // After map has been created, add listeners here
    googleMaps.addListener('dragend', function(){
      // get the lng and lat and call getCrimes with them
      var newCenter = googleMaps.getCenter();
      // clear the map of current markers and infowindows
      // googleMaps.clearMap();
      $scope.getCrimes(newCenter.lat(), newCenter.lng());
    });
  };

  $scope.gpsSearchCrime = function(){

    var onSuccess = function(pos){
      var lat = pos.coords.latitude;
      var lng = pos.coords.longitude;
      googleMaps.searchLoc(lat, lng, $scope.getCrimes);
    };

    var onError = function(error) {
      navigator.notification.alert('Code: ' + error.code + '\n' + 'Message:' + error.message);
    };

    navigator.geolocation.getCurrentPosition(onSuccess, onError);
  };

  $scope.getCrimes = function(lat, lng){

    var url = "http://sf-sense-server.herokuapp.com/near?longitude=" + lng + "&latitude="+ lat + "&distance=0.3";

    $http({
      headers: {
      "Authorization" : "Basic " + btoa("sf-sense:858F8CDDB1F324A762DBEFDC77844")
      },
      url: url,
      dataType: 'json',
      method: "GET"
    }).success(function(response){
      googleMaps.createMarkers(response);
    }).error(function(error){
      navigator.notification.alert('There was an error: ' + error);
    });
  };

  $scope.searchCrime = function() {
    // $scope.mapSearch is a street address
    // on success, calls getCrimes with the lat/lng

    // if map search if undefined use current location. Placeholder is current location.
    if(!$scope.mapSearch) {
      $scope.gpsSearchCrime();
    } else {
      googleMaps.searchLocByAddress($scope.mapSearch, $scope.getCrimes);
    }

    hideKeyboard();
  };

  $scope.filterBy = function (filterArg) {
    if (!filterArg) filterArg = 'all';
    googleMaps.filterBy(filterArg);
  };

  $scope.trackLocation = function() {
    alert('Tracking');
    var bgGeo = window.plugins.backgroundGeoLocation;

    var onSuccess = function(pos){
      var lat = pos.latitude;
      var lng = pos.longitude;
      alert(lat);
      // googleMaps.searchLoc(lat, lng, $scope.getCrimes);
    };

    var onError = function(error) {
      navigator.notification.alert('Code: ' + error.code + '\n' + 'Message:' + error.message);
    };

    bgGeo.configure(onSuccess, onError, {
      desiredAccuracy: 10,
      stationaryRadius: 20,
      distanceFilter: 30,
      debug: true // <-- enable this hear sounds for background-geolocation life-cycle.
    });

    bgGeo.start();
  };

  init();
})

.run(function($ionicPlatform) {
  $ionicPlatform.ready(function() {
    // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
    // for form inputs)
    if(window.cordova && window.cordova.plugins.Keyboard) {
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
    }
    if(window.StatusBar) {
      StatusBar.styleDefault();
    }
  });
});

<commit_msg>Closes all infowindows before opening one, adds some tests for the pinchinfowindow bug<commit_after>angular.module('sfSense', ['ionic'])

.factory('googleMaps', function(){
  // OVERVIEW
  // 1. setup map options
  // 2. create map
  // 3. get data for crime lat and lng
  // 4. create markers
  // 5. add markers to map
  var map;
  var markers = {};
  var filterOn = 'all';
  var isViolent = {
    'ASSAULT': true,
    'NON-CRIMINAL': false,
    'OTHER OFFENSES': false,
    'ROBBERY': true,
    'LARCENY/THEFT': false,
    'VANDALISM': false,
    'BURGLARY': false,
    'VEHICLE THEFT': false,
    'FRAUD': false,
    'DRUNKENNESS': false,
    'WARRANTS': false,
    'TRESPASS': false,
    'KIDNAPPING': true,
    'SEX OFFENSES': true,
    'WEAPON LAWS': true,
    'DRUG/NARCOTIC': false,
    'FORGERY/COUNTERFEITING': false,
    'MISSING PERSON': false,
    'LIQUOR LAWS': false,
    'BAD CHECKS': false,
    'RUNAWAY': false,
    'EMBEZZLEMENT': false
  };

  var iconPath = '../www/img/icons/';

  // TODO: add marker img for each category
  var markerImg = {
    'BURGLARY': 'robbery.png',
    'LARCENY/THEFT': 'theft.png',
    'ASSAULT': 'robbery.png',
    'MISSING PERSON': 'missing.png',
    'DEFAULT': 'blast.png'
  };

  var createMarker = function(crime) {

    if (markers[crime.id] === undefined) { // If crime isn't displayed yet add it
      var latlng = new google.maps.LatLng(crime.latitude,crime.longitude);

      var icon;

      if(markerImg[crime.category]){
        icon = iconPath + markerImg[crime.category];
      } else {
        icon = iconPath + markerImg.DEFAULT;
      }

      var newMarker = new google.maps.Marker({
        position: latlng,
        animation: google.maps.Animation.DROP,
        title: crime.category,
        icon: icon,
        id: crime.id,
        category: crime.category,
        date: crime.date,
        time: crime.time,
        description: crime.descript,
        type: crime.type.toLowerCase()
      });

      // Check if the marker should be displayed or not
      if (filterOn === 'all' || filterOn === crime.type) {
        newMarker.setMap(map);
      }
      // Make a new InfoWindow and associate it to the marker
      newMarker.info = new google.maps.InfoWindow({
        content: '
' + newMarker.description + '
'
      });
      // Add the map listener here
      google.maps.event.addListener(newMarker, 'mouseover', function(){
        // Close all open crime info windows first
        for (var crimeID in markers) {
          markers[crimeID].info.close();
        }
        // Open the pertinent info window
        newMarker.info.open(map, newMarker);
      });
      markers[crime.id] = newMarker; // add it to the markers object
    }
  };

  return {

    // Add in google maps functions here

    createMap: function(lat, lng){
      var mapOptions = {
        center: new google.maps.LatLng(lat, lng),
        zoom: 17,
        panControl: false,
        zoomControl: false,
        mapTypeControl: false,
        streetViewControl: false,
        overviewMapControl: false,
        //begin map options to fix pinch displaying info windows bug
        maxZoom: 17,
        minZoom: 17,
        scrollwheel: false
      };

      map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
    },

    // CreateMap is not invoked yet so we define addListener to add the event listener
    // Once the map has been created, call addListener
    // Moving method outside of the create call allows access to other services in googleMaps
    // There will only be one map variable so accept only the event and function
    addListener: function(event, func) {
      google.maps.event.addListener(map, event, func);
    },

    createMarkers: function(crimes) {
      for(var i = 0; i < crimes.length; i++){
        createMarker(crimes[i]);
      }
    },

    clearMap: function() {
      // first hide all the markers by setting map to null
      for (var i = 0; i < markers.length; i++) {
        markers[i].setMap(null);
      }
      // we no longer want access to the markers so remove them
      markers = {};
    },

    moveTo: function(lat, lng){
      var latlng = new google.maps.LatLng(lat,lng);
      map.panTo(latlng);
    },

    getCenter: function() {
      // returns latlng object with lat() and lng() methods
      return map.getCenter();
    },

    searchLocByAddress: function(address, cb) {
      var city = 'san francisco';
      var re = RegExp(city, 'i');

      if(!re.exec(address)){
        address = address + ' ' + city;
      }

      geocoder = new google.maps.Geocoder();

      geocoder.geocode( {'address': address}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
          map.setCenter(results[0].geometry.location);

          cb(results[0].geometry.location.k, results[0].geometry.location.A);

        } else {
          navigator.notification.alert('Error with find location: ' + status);
        }
      });
    },

    searchLoc: function(lat, lng, cb){
      var latlng = new google.maps.LatLng(lat,lng);
      map.setCenter(latlng);
      cb(lat, lng);
    },

    filterBy: function(filter){
      // set filterOn
      filterOn = filter;
      // the filter will match the type field on the markers
      for (var markerID in markers) {

        var marker = markers[markerID];
        var cat = marker.type;

        // check if the filter is all, if so, show all markers
        if (filter === 'all') {
          marker.setMap(map);
        } else { // a filter was specified
          if (filter === cat) { // filter matches marker type
            marker.setMap(map);
          } else { // filter doesn't match marker type
            marker.setMap(null);
          }
        }
      }
    }
  };
})

.controller('MapCtrl', function($scope, $http, googleMaps){

  $scope.filters = ['other', 'assault', 'theft'];

  var hideKeyboard = function() {
    document.activeElement.blur();
    $("input").blur();
  };

  var init = function() {
    // SF center lat and lng
    var lat = 37.783522;
    var lng = -122.408964;

    googleMaps.createMap(lat, lng);

    // After map has been created, add listeners here
    googleMaps.addListener('dragend', function(){
      // get the lng and lat and call getCrimes with them
      var newCenter = googleMaps.getCenter();
      // clear the map of current markers and infowindows
      // googleMaps.clearMap();
      $scope.getCrimes(newCenter.lat(), newCenter.lng());
    });
  };

  $scope.gpsSearchCrime = function(){

    var onSuccess = function(pos){
      var lat = pos.coords.latitude;
      var lng = pos.coords.longitude;
      googleMaps.searchLoc(lat, lng, $scope.getCrimes);
    };

    var onError = function(error) {
      navigator.notification.alert('Code: ' + error.code + '\n' + 'Message:' + error.message);
    };

    navigator.geolocation.getCurrentPosition(onSuccess, onError);
  };

  $scope.getCrimes = function(lat, lng){

    var url = "http://sf-sense-server.herokuapp.com/near?longitude=" + lng + "&latitude="+ lat + "&distance=0.3";

    $http({
      headers: {
      "Authorization" : "Basic " + btoa("sf-sense:858F8CDDB1F324A762DBEFDC77844")
      },
      url: url,
      dataType: 'json',
      method: "GET"
    }).success(function(response){
      googleMaps.createMarkers(response);
    }).error(function(error){
      navigator.notification.alert('There was an error: ' + error);
    });
  };

  $scope.searchCrime = function() {
    // $scope.mapSearch is a street address
    // on success, calls getCrimes with the lat/lng

    // if map search if undefined use current location. Placeholder is current location.
    if(!$scope.mapSearch) {
      $scope.gpsSearchCrime();
    } else {
      googleMaps.searchLocByAddress($scope.mapSearch, $scope.getCrimes);
    }

    hideKeyboard();
  };

  $scope.filterBy = function (filterArg) {
    if (!filterArg) filterArg = 'all';
    googleMaps.filterBy(filterArg);
  };

  $scope.trackLocation = function() {
    alert('Tracking');
    var bgGeo = window.plugins.backgroundGeoLocation;

    var onSuccess = function(pos){
      var lat = pos.latitude;
      var lng = pos.longitude;
      alert(lat);
      // googleMaps.searchLoc(lat, lng, $scope.getCrimes);
    };

    var onError = function(error) {
      navigator.notification.alert('Code: ' + error.code + '\n' + 'Message:' + error.message);
    };

    bgGeo.configure(onSuccess, onError, {
      desiredAccuracy: 10,
      stationaryRadius: 20,
      distanceFilter: 30,
      debug: true // <-- enable this hear sounds for background-geolocation life-cycle.
    });

    bgGeo.start();
  };

  init();
})

.run(function($ionicPlatform) {
  $ionicPlatform.ready(function() {
    // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
    // for form inputs)
    if(window.cordova && window.cordova.plugins.Keyboard) {
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
    }
    if(window.StatusBar) {
      StatusBar.styleDefault();
    }
  });
});

<|endoftext|>


<commit_before>// XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
// XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
var onoff = 0;
var acc = {}; // TEMP STORE
var rot = {}; // TEMP STORE
// DECLARATIONS AND RUN
// ============================================================
// point in time data captured from phone
var captures = {
    // start: Date(),
    // doSupported: false,
    // dmSupported: false
};
// var resHist = [];  // will collect our history of captures

// we set our declared variables in a function as we can later
// use that function as a reset
var vel = {}, pos = {}, cords = {};
var nIntervId; // interval stamps for our clock
var series = {  // default dots in graph
    name: 'Signature',
};
var rem = 2;  // countdown clock, 3 seconds
// And run
motionVars();
getDeviceData();

// MAIN FUNCTIONS
// ============================================================
function getDeviceData() {
    // call motion
    if (window.DeviceMotionEvent) {
        window.addEventListener('devicemotion', MotionHandler, false);
    } else {
        document.getElementById("dmEvent").innerHTML = "Motion not supported."
    }
    // call orientation
    if (window.DeviceOrientationEvent) {
        window.addEventListener('deviceorientation', OrientationHandler, false);
    } else {
        document.getElementById("dmEvent2").innerHTML = "Orientation not supported."
    }
}

function MotionHandler(eventData) {
    /* Grab the acceleration from the results
    alpha is the compass direction
    beta is the front-to-back tilt in degrees, where front is positive
    gamma is the left-to-right tilt in degrees, where right is positive */
    /*
    var info, xyz = "[X, Y, Z, ra, rb, rg, a, b, g]"; d = Date();
    document.getElementById("dmEvent").innerHTML = "DeviceMotion";
    info = xyz.replace("X", round(eventData.acceleration.x));
    info = info.replace("Y", round(eventData.acceleration.y));
    info = info.replace("Z", round(eventData.acceleration.z));
    info = info.replace("ra", round(eventData.rotationRate.alpha));
    info = info.replace("rb", round(eventData.rotationRate.beta));
    info = info.replace("rg", round(eventData.rotationRate.gamma));
    document.getElementById("moCapture").innerHTML = info;
    info = eventData.interval;
    document.getElementById("moInterval").innerHTML = info;
    */
    // captures.dmSupported = true;
    // captures.interval = eventData.interval;
    captures.milli = new Date().getMilliseconds();
    captures.acc_x = round(eventData.acceleration.x);
    captures.acc_y = round(eventData.acceleration.y);
    captures.acc_z = round(eventData.acceleration.z);
    // captures.ra = round(eventData.rotationRate.alpha);
    // captures.rb = round(eventData.rotationRate.beta);
    // captures.rg = round(eventData.rotationRate.gamma);
}

function OrientationHandler(eventData) {
    /*
    alpha is the compass direction (rotation around z axis);
    varies 0 to 360;
    beta is rotation around the long y axis on LHS of phone;
    varies -90 to +90 (so doesn't know if upside down);
    think of as capturing the off-horizontal;
    gamma is rotation around short x axis at base of phone;
    varies -180 to +180;
    /*
    var info, xyz = "[a, b, g]";
    document.getElementById("dmEvent2").innerHTML = "DeviceOrientation";
    info = xyz.replace("a", round(eventData.alpha));
    info = info.replace("b", round(eventData.beta));
    info = info.replace("g", round(eventData.gamma));
    document.getElementById("moCapture2").innerHTML = info;
    info = eventData.interval;
    document.getElementById("moInterval2").innerHTML = info;
    */
    // captures.doSupported = true;
    true_a = Math.round(eventData.alpha);
    true_b = Math.round(eventData.beta);
    true_g = Math.round(eventData.gamma);
    document.getElementById('raws').innerHTML = [
        true_a, true_b, true_g
    ]; // temp fudge
    captures.dir_a = Math.round(Math.abs(round(eventData.alpha) - 180));
    captures.dir_b = Math.round(Math.abs(round(eventData.beta)));
    captures.dir_g = Math.round(Math.abs(round(eventData.gamma)) * 2);
    captures.interval = round(eventData.interval);
    document.getElementById('north').innerHTML = [
        captures.dir_a, captures.dir_b, captures.dir_g
    ]; // temp fudge
}

// RUNNING OUR SAMPLER
// ============================================================
function addCountDownLayer(task, millis) {
     repeatit(
        countAndGo, [task, millis], 1000
    );
}

function repeatit(task, param, millis) {
    nIntervId = setInterval(
        function() { task(param); }, millis);
}
function stopCollecting() {
    clearInterval(nIntervId);
    document.getElementById('egg').innerHTML = "Capture";
}

// VELOCITY CALCS
// ============================================================
function terminal_vel(millis) {
    var secs = millis / 1000;
    // run through our xyz axes
    for (var axis in vel) {
        var t_acc = 'acc_' + axis;
        var foo = Math.floor(Math.random() * 11) - 5.5;  // temp fudge
        if (onoff != 0) {
            captures[t_acc] = foo;  // temp fudge
        };
        acc[axis].push(captures[t_acc]);  // temp store
        // v = u + at
        // we need mean a;
        var u = vel[axis].slice(-1)[0];
        mean_a = ( acc[axis].slice(-2)[0] + acc[axis].slice(-2)[1] ) / 2;
        var v = u + mean_a * secs;
        vel[axis].push(v);
        // s = (u + v) / 2 * t
        // but we want cumulative s
        pos[axis].push(
            pos[axis].slice(-1)[0] + (u + v) * 0.5 * secs
        );
    }
    // turn our tilts into colours and gather
    var r = captures.dir_a * (1 - onoff) + Math.floor(Math.random() * 256) * onoff; //FUDGE
    var g = captures.dir_g * (1 - onoff) + Math.floor(Math.random() * 256) * onoff; //FFF
    var b = captures.dir_b * (1 - onoff) + Math.floor(Math.random() * 256) * onoff; //FFF
    rot['r'].push(r);
    rot['g'].push(g);
    rot['b'].push(b);
    var opacity = 0.5;
    // pop data xy co-ordinates
    cords.push({
        x: pos.x.slice(-1)[0],
        y: pos.y.slice(-1)[0],
        color: 'rgba(' + r + ',' + g + ',' + b + ',' + opacity + ')'
    });
    // populate page
    document.getElementById('pos').innerHTML = JSON.stringify(cords);
    document.getElementById('vel').innerHTML = JSON.stringify(vel);
    document.getElementById('acc').innerHTML = JSON.stringify(acc);
    document.getElementById('rot').innerHTML = JSON.stringify(rot);
    // populate our pre-defined chart with data
    series.data = cords;
    chartsettings.series = [series];
    $('#sigbox').highcharts(chartsettings);
}

// CONVENIENCES
// ============================================================
function round(val) {
    var amt = 1000;
    return Math.round(val * amt) /  amt;
}

function motionVars() {
    // cumulative capture of velocity, pos;
    // co-ordinates is just pos restated for the graph;
    // set up like this allows us to reset these vars.
    vel = {
        x: [0],
        y: [0],
        z: [0]
    };
    pos = {
        x: [0],
        y: [0],
        z: [0]
    };
    cords = [{
        x: 0,
        y: 0,
        color: 'rgba(100, 100, 100, .5)'
    }];
    acc = {  // TEMP STORE
        x: [0],
        y: [0],
        z: [0]
    };
    rot = {  // TEMP STORE
        r: [0],
        b: [0],
        g: [0]
    };

}

function rescaleToColor(angle) {
    // we only measure along one direction;
    if (angle < 0) {  // all positive;
        angle += 360;
    }
    angle -= 180;  // reverse polarity for coloring;
    if (angle <= 0) {  // ignore plus/minus;
        angle *= -1;
    }
    return Math.floor(angle * 255 / 180);
}

function countAndGo(fn_param) {
    // runs our timer first & then the main function with its parameters
    if (rem >= 0) {
        document.getElementById('egg').innerHTML = rem;
        rem -= 1;
    } else {
        stopCollecting();
        rem = 2;
        document.getElementById('egg').innerHTML = "Capturing Data";
        // now for the main function
        task = fn_param[0];
        millis = fn_param[1];
        repeatit(task, millis, millis);
    }
}

function toggler() {
    onoff = 1 - onoff;
    document.getElementById('booler').innerHTML = onoff;
}

// TEST FUNCTION
// ============================================================
/*
function flashText(cell_ref) {
    var oElem = document.getElementById(cell_ref);
    oElem.style.color = oElem.style.color == "red" ? "blue" : "red";
    terminal_vel(500);
    resHist.push(JSON.stringify(captures));
    oElem.innerHTML = resHist;
}
*/

<commit_msg>Device data graphics<commit_after>// XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
// XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
var onoff = 0;
var acc = {}; // TEMP STORE
var rot = {}; // TEMP STORE
// DECLARATIONS AND RUN
// ============================================================
// point in time data captured from phone
var captures = {
    // start: Date(),
    // doSupported: false,
    // dmSupported: false
};
// var resHist = [];  // will collect our history of captures

// we set our declared variables in a function as we can later
// use that function as a reset
var vel = {}, pos = {}, cords = {};
var nIntervId; // interval stamps for our clock
var series = {  // default dots in graph
    name: 'Signature',
};
var rem = 2;  // countdown clock, 3 seconds
// And run
motionVars();
getDeviceData();

// MAIN FUNCTIONS
// ============================================================
function getDeviceData() {
    // call motion
    if (window.DeviceMotionEvent) {
        window.addEventListener('devicemotion', MotionHandler, false);
    } else {
        document.getElementById("dmEvent").innerHTML = "Motion not supported."
    }
    // call orientation
    if (window.DeviceOrientationEvent) {
        window.addEventListener('deviceorientation', OrientationHandler, false);
    } else {
        document.getElementById("dmEvent2").innerHTML = "Orientation not supported."
    }
}

function MotionHandler(eventData) {
    /* Grab the acceleration from the results
    alpha is the compass direction
    beta is the front-to-back tilt in degrees, where front is positive
    gamma is the left-to-right tilt in degrees, where right is positive */
    /*
    var info, xyz = "[X, Y, Z, ra, rb, rg, a, b, g]"; d = Date();
    document.getElementById("dmEvent").innerHTML = "DeviceMotion";
    info = xyz.replace("X", round(eventData.acceleration.x));
    info = info.replace("Y", round(eventData.acceleration.y));
    info = info.replace("Z", round(eventData.acceleration.z));
    info = info.replace("ra", round(eventData.rotationRate.alpha));
    info = info.replace("rb", round(eventData.rotationRate.beta));
    info = info.replace("rg", round(eventData.rotationRate.gamma));
    document.getElementById("moCapture").innerHTML = info;
    info = eventData.interval;
    document.getElementById("moInterval").innerHTML = info;
    */
    // captures.dmSupported = true;
    // captures.interval = eventData.interval;
    captures.milli = new Date().getMilliseconds();
    captures.acc_x = round(eventData.acceleration.x);
    captures.acc_y = round(eventData.acceleration.y);
    captures.acc_z = round(eventData.acceleration.z);
    // captures.ra = round(eventData.rotationRate.alpha);
    // captures.rb = round(eventData.rotationRate.beta);
    // captures.rg = round(eventData.rotationRate.gamma);
}

function OrientationHandler(eventData) {
    /*
    alpha is the compass direction (rotation around z axis);
    varies 0 to 360;
    beta is rotation around the long y axis on LHS of phone;
    varies -90 to +90 (so doesn't know if upside down);
    think of as capturing the off-horizontal;
    gamma is rotation around short x axis at base of phone;
    varies -180 to +180;
    /*
    var info, xyz = "[a, b, g]";
    document.getElementById("dmEvent2").innerHTML = "DeviceOrientation";
    info = xyz.replace("a", round(eventData.alpha));
    info = info.replace("b", round(eventData.beta));
    info = info.replace("g", round(eventData.gamma));
    document.getElementById("moCapture2").innerHTML = info;
    info = eventData.interval;
    document.getElementById("moInterval2").innerHTML = info;
    */
    // captures.doSupported = true;
    var true_a = Math.round(eventData.alpha);
    var true_b = Math.round(eventData.beta);
    var true_g = Math.round(eventData.gamma);
    document.getElementById('raws').innerHTML = [
        true_a, true_b, true_g
    ]; // temp fudge
    captures.dir_a = Math.round(Math.abs(round(eventData.alpha) - 180));
    captures.dir_b = Math.round(Math.abs(round(eventData.beta)));
    captures.dir_g = Math.round(Math.abs(round(eventData.gamma)) * 2);
    captures.interval = round(eventData.interval);
    document.getElementById('north').innerHTML = [
        captures.dir_a, captures.dir_b, captures.dir_g
    ]; // temp fudge
}

// RUNNING OUR SAMPLER
// ============================================================
function addCountDownLayer(task, millis) {
     repeatit(
        countAndGo, [task, millis], 1000
    );
}

function repeatit(task, param, millis) {
    nIntervId = setInterval(
        function() { task(param); }, millis);
}
function stopCollecting() {
    clearInterval(nIntervId);
    document.getElementById('egg').innerHTML = "Capture";
}

// VELOCITY CALCS
// ============================================================
function terminal_vel(millis) {
    var secs = millis / 1000;
    // run through our xyz axes
    for (var axis in vel) {
        var t_acc = 'acc_' + axis;
        var foo = Math.floor(Math.random() * 11) - 5.5;  // temp fudge
        if (onoff != 0) {
            captures[t_acc] = foo;  // temp fudge
        };
        acc[axis].push(captures[t_acc]);  // temp store
        // v = u + at
        // we need mean a;
        var u = vel[axis].slice(-1)[0];
        mean_a = ( acc[axis].slice(-2)[0] + acc[axis].slice(-2)[1] ) / 2;
        var v = u + mean_a * secs;
        vel[axis].push(v);
        // s = (u + v) / 2 * t
        // but we want cumulative s
        pos[axis].push(
            pos[axis].slice(-1)[0] + (u + v) * 0.5 * secs
        );
    }
    // turn our tilts into colours and gather
    var r = captures.dir_a * (1 - onoff) + Math.floor(Math.random() * 256) * onoff; //FUDGE
    var g = captures.dir_g * (1 - onoff) + Math.floor(Math.random() * 256) * onoff; //FFF
    var b = captures.dir_b * (1 - onoff) + Math.floor(Math.random() * 256) * onoff; //FFF
    rot['r'].push(r);
    rot['g'].push(g);
    rot['b'].push(b);
    var opacity = 0.5;
    // pop data xy co-ordinates
    cords.push({
        x: pos.x.slice(-1)[0],
        y: pos.y.slice(-1)[0],
        color: 'rgba(' + r + ',' + g + ',' + b + ',' + opacity + ')'
    });
    // populate page
    document.getElementById('pos').innerHTML = JSON.stringify(cords);
    document.getElementById('vel').innerHTML = JSON.stringify(vel);
    document.getElementById('acc').innerHTML = JSON.stringify(acc);
    document.getElementById('rot').innerHTML = JSON.stringify(rot);
    // populate our pre-defined chart with data
    series.data = cords;
    chartsettings.series = [series];
    $('#sigbox').highcharts(chartsettings);
}

// CONVENIENCES
// ============================================================
function round(val) {
    var amt = 1000;
    return Math.round(val * amt) /  amt;
}

function motionVars() {
    // cumulative capture of velocity, pos;
    // co-ordinates is just pos restated for the graph;
    // set up like this allows us to reset these vars.
    vel = {
        x: [0],
        y: [0],
        z: [0]
    };
    pos = {
        x: [0],
        y: [0],
        z: [0]
    };
    cords = [{
        x: 0,
        y: 0,
        color: 'rgba(100, 100, 100, .5)'
    }];
    acc = {  // TEMP STORE
        x: [0],
        y: [0],
        z: [0]
    };
    rot = {  // TEMP STORE
        r: [0],
        b: [0],
        g: [0]
    };

}

function rescaleToColor(angle) {
    // we only measure along one direction;
    if (angle < 0) {  // all positive;
        angle += 360;
    }
    angle -= 180;  // reverse polarity for coloring;
    if (angle <= 0) {  // ignore plus/minus;
        angle *= -1;
    }
    return Math.floor(angle * 255 / 180);
}

function countAndGo(fn_param) {
    // runs our timer first & then the main function with its parameters
    if (rem >= 0) {
        document.getElementById('egg').innerHTML = rem;
        rem -= 1;
    } else {
        stopCollecting();
        rem = 2;
        document.getElementById('egg').innerHTML = "Capturing Data";
        // now for the main function
        task = fn_param[0];
        millis = fn_param[1];
        repeatit(task, millis, millis);
    }
}

function toggler() {
    onoff = 1 - onoff;
    document.getElementById('booler').innerHTML = onoff;
}

// TEST FUNCTION
// ============================================================
/*
function flashText(cell_ref) {
    var oElem = document.getElementById(cell_ref);
    oElem.style.color = oElem.style.color == "red" ? "blue" : "red";
    terminal_vel(500);
    resHist.push(JSON.stringify(captures));
    oElem.innerHTML = resHist;
}
*/

<|endoftext|>


<commit_before><commit_msg>dont allow user to delete referenced answer<commit_after><|endoftext|>