<commit_before>function airline_init_pre() {
  prop.airline = {};
  prop.airline.airlines = {};
}

/**
 * An aircrcraft operating agency
 */
zlsa.atc.Airline = Fiber.extend(function() {
  return {
    /**
     * Create new airline
     */
    init: function (icao, options) {
      /** ICAO airline designation */
      this.icao = "YYY";

      /** Agency name */
      this.name = "Default airline";

      /** Radio callsign */
      this.callsign = 'Default';

      /** Parameters for flight number generation */
      this.flightNumberGeneration = {
        /** How many characters in the flight number */
        length: 3,
        /** Whether to use alphabetical characters */
        alpha: false,
      };

      /** Named weighted sets of aircraft */
      this.fleets = {
        default: [],
      };

      this.parse(icao, options);
    },

    /**
     * Initialize object from data
     */
    parse: function (icao, data) {
      if (data.icao)
        this.icao = data.icao;
      else
        this.icao = icao;

      this.name = data.name;
      this.callsign = data.callsign.name;
      this.flightNumberGeneration.length = data.callsign.length;
      this.flightNumberGeneration.alpha = (data.callsign.alpha === true);
      if (data.fleets)
        this.fleets = data.fleets;
      else
        this.fleets.default = data.aircraft;

      for (var f in this.fleets) {
        for (var j=0;j<this.fleets[f].length;j++) {
          this.fleets[f][j][0] = this.fleets[f][j][0].toLowerCase();
        }
      }
    },

    /**
     * Return a random ICAO aircraft designator from the given fleet
     *
     * If no fleet is specified the default fleet is used
     */
    chooseAircraft: function (fleet) {
      if (!fleet)
        fleet = 'default';

      try {
        return choose_weight(this.fleets[fleet.toLowerCase()]);
      }
      catch (e) {
        console.log("Unable to find fleet " + fleet
                    + " for airline " + this.icao);
        throw e;
      }
    },

    /**
     * Create a flight number/identifier
     */
    generateFlightNumber: function () {
      var flightNumberLength = this.flightNumberGeneration.length;
      var flightNumber = "";

      var list = "0123456789";

      // Start with a number other than zero
      flightNumber += choose(list.substr(1));

      if (this.flightNumberGeneration.alpha) {
        for (var i=0; i<flightNumberLength - 3; i++)
          flightNumber += choose(list);
        list = "abcdefghijklmnopqrstuvwxyz";
        for (var i=0; i<2; i++)
          flightNumber += choose(list);
      } else {
        for (var i=1; i<flightNumberLength;i++)
          flightNumber += choose(list);
      }
      return flightNumber;
    },

    /**
     * Checks all fleets for valid aircraft identifiers and log errors
     */
    validateFleets: function () {
      for (var f in this.fleets) {
        for (var j=0;j<this.fleets[f].length;j++) {
          if (!(this.fleets[f][j][0] in prop.aircraft.models)) {
            console.warn("Airline " + this.icao.toUpperCase()
                         + " uses nonexistent aircraft " + this.fleets[f][j][0]
                         + ", expect errors");
          }

          if (typeof this.fleets[f][j][1] != "number") {
            console.warn("Airline " + this.icao.toUpperCase()
                         + " uses non numeric weight for aircraft " +
                         this.fleets[f][j][0] + ", expect errors");
          }
        }
      }
    },
  };
});

function airline_init() {
  airline_load("AAL");
  airline_load("ACA");
  airline_load("AEA");
  airline_load("AFL");
  airline_load("AFR");
  airline_load("AIRTAXI");
  airline_load("AMX");
  airline_load("ARG");
  airline_load("ASA");
  airline_load("ASQ");
  airline_load("AUA");
  airline_load("AVA");
  airline_load("AWE");
  airline_load("AWI");
  airline_load("AWQ");
  airline_load("AZA");
  airline_load("AZU");
  airline_load("BAW");
  airline_load("BCY");
  airline_load("BER");
  airline_load("BTK");
  airline_load("BWA");
  airline_load("CCA");
  airline_load("CES");
  airline_load("CESSNA");
  airline_load("CFG");
  airline_load("CFS");
  airline_load("CPA");
  airline_load("CPZ");
  airline_load("CSN");
  airline_load("CTV");
  airline_load("CWC");
  airline_load("DAL");
  airline_load("DLH");
  airline_load("EIN");
  airline_load("EMBRAER");
  airline_load("ENY");
  airline_load("ETD");
  airline_load("EVA");
  airline_load("EZY");
  airline_load("FAB");
  airline_load("FASTGA");
  airline_load("FDX");
  airline_load("FFT");
  airline_load("FLG");
  airline_load("GIA");
  airline_load("GJS");
  airline_load("GLO");
  airline_load("GWI");
  airline_load("HAL");
  airline_load("HDA");
  airline_load("IBE");
  airline_load("JAL");
  airline_load("JBU");
  airline_load("JIA");
  airline_load("KAL");
  airline_load("KAP");
  airline_load("KLC");
  airline_load("KLM");
  airline_load("LAN");
  airline_load("LIGHTGA");
  airline_load("LNI");
  airline_load("MOV");
  airline_load("NAX");
  airline_load("NKS");
  airline_load("ONE");
  airline_load("PAA");
  airline_load("PDT");
  airline_load("QXE");
  airline_load("RFF");
  airline_load("RLU");
  airline_load("RPA");
  airline_load("RYR");
  airline_load("SAS");
  airline_load("SBI");
  airline_load("SCX");
  airline_load("SJY");
  airline_load("SKW");
  airline_load("SLK");
  airline_load("SVR");
  airline_load("SWA");
  airline_load("SWR");
  airline_load("SXD");
  airline_load("TAM");
  airline_load("TCF");
  airline_load("TCX");
  airline_load("THY");
  airline_load("TOM");
  airline_load("TSO");
  airline_load("TUI");
  airline_load("TWA");
  airline_load("TYA");
  airline_load("UAE");
  airline_load("UAL");
  airline_load("UPS");
  airline_load("USAF");
  airline_load("VIR");
  airline_load("VRD");
}

function airline_load(icao) {
  icao = icao.toLowerCase();
  new Content({
    type: "json",
    url: "assets/airlines/"+icao+".json",
    payload: icao.toLowerCase(),
    callback: function(status, data, payload) {
      if(status == "ok") {
        prop.airline.airlines[payload] = new zlsa.atc.Airline(payload, data);
      }
    }
  });
}

function airline_get(icao) {
  icao = icao.toLowerCase();
  return prop.airline.airlines[icao];
}

function airline_ready() {
  for(var i in prop.airline.airlines) {
    prop.airline.airlines[i].validateFleets();
  }
}
<commit_msg>Load all the airlines<commit_after>function airline_init_pre() {
  prop.airline = {};
  prop.airline.airlines = {};
}

/**
 * An aircrcraft operating agency
 */
zlsa.atc.Airline = Fiber.extend(function() {
  return {
    /**
     * Create new airline
     */
    init: function (icao, options) {
      /** ICAO airline designation */
      this.icao = "YYY";

      /** Agency name */
      this.name = "Default airline";

      /** Radio callsign */
      this.callsign = 'Default';

      /** Parameters for flight number generation */
      this.flightNumberGeneration = {
        /** How many characters in the flight number */
        length: 3,
        /** Whether to use alphabetical characters */
        alpha: false,
      };

      /** Named weighted sets of aircraft */
      this.fleets = {
        default: [],
      };

      this.parse(icao, options);
    },

    /**
     * Initialize object from data
     */
    parse: function (icao, data) {
      if (data.icao)
        this.icao = data.icao;
      else
        this.icao = icao;

      this.name = data.name;
      this.callsign = data.callsign.name;
      this.flightNumberGeneration.length = data.callsign.length;
      this.flightNumberGeneration.alpha = (data.callsign.alpha === true);
      if (data.fleets)
        this.fleets = data.fleets;
      else
        this.fleets.default = data.aircraft;

      for (var f in this.fleets) {
        for (var j=0;j<this.fleets[f].length;j++) {
          this.fleets[f][j][0] = this.fleets[f][j][0].toLowerCase();
        }
      }
    },

    /**
     * Return a random ICAO aircraft designator from the given fleet
     *
     * If no fleet is specified the default fleet is used
     */
    chooseAircraft: function (fleet) {
      if (!fleet)
        fleet = 'default';

      try {
        return choose_weight(this.fleets[fleet.toLowerCase()]);
      }
      catch (e) {
        console.log("Unable to find fleet " + fleet
                    + " for airline " + this.icao);
        throw e;
      }
    },

    /**
     * Create a flight number/identifier
     */
    generateFlightNumber: function () {
      var flightNumberLength = this.flightNumberGeneration.length;
      var flightNumber = "";

      var list = "0123456789";

      // Start with a number other than zero
      flightNumber += choose(list.substr(1));

      if (this.flightNumberGeneration.alpha) {
        for (var i=0; i<flightNumberLength - 3; i++)
          flightNumber += choose(list);
        list = "abcdefghijklmnopqrstuvwxyz";
        for (var i=0; i<2; i++)
          flightNumber += choose(list);
      } else {
        for (var i=1; i<flightNumberLength;i++)
          flightNumber += choose(list);
      }
      return flightNumber;
    },

    /**
     * Checks all fleets for valid aircraft identifiers and log errors
     */
    validateFleets: function () {
      for (var f in this.fleets) {
        for (var j=0;j<this.fleets[f].length;j++) {
          if (!(this.fleets[f][j][0] in prop.aircraft.models)) {
            console.warn("Airline " + this.icao.toUpperCase()
                         + " uses nonexistent aircraft " + this.fleets[f][j][0]
                         + ", expect errors");
          }

          if (typeof this.fleets[f][j][1] != "number") {
            console.warn("Airline " + this.icao.toUpperCase()
                         + " uses non numeric weight for aircraft " +
                         this.fleets[f][j][0] + ", expect errors");
          }
        }
      }
    },
  };
});

function airline_init() {
  airline_load("AAL");
  airline_load("ACA");
  airline_load("AEA");
  airline_load("AFL");
  airline_load("AFR");
  airline_load("AIC");
  airline_load("AIRTAXI");
  airline_load("AMX");
  airline_load("ARG");
  airline_load("ASA");
  airline_load("ASQ");
  airline_load("AUA");
  airline_load("AVA");
  airline_load("AWE");
  airline_load("AWI");
  airline_load("AWQ");
  airline_load("AXB");
  airline_load("AZA");
  airline_load("AZU");
  airline_load("BAW");
  airline_load("BCY");
  airline_load("BER");
  airline_load("BTK");
  airline_load("BWA");
  airline_load("CCA");
  airline_load("CES");
  airline_load("CESSNA");
  airline_load("CFG");
  airline_load("CFS");
  airline_load("CPA");
  airline_load("CPZ");
  airline_load("CSN");
  airline_load("CTV");
  airline_load("CWC");
  airline_load("DAL");
  airline_load("DLH");
  airline_load("EIN");
  airline_load("EMBRAER");
  airline_load("ENY");
  airline_load("ETD");
  airline_load("EVA");
  airline_load("EZY");
  airline_load("FAB");
  airline_load("FASTGA");
  airline_load("FDX");
  airline_load("FFT");
  airline_load("FLG");
  airline_load("GIA");
  airline_load("GJS");
  airline_load("GLO");
  airline_load("GOW");
  airline_load("GWI");
  airline_load("HAL");
  airline_load("HDA");
  airline_load("IAD");
  airline_load("IBE");
  airline_load("IGO");
  airline_load("JAI");
  airline_load("JAL");
  airline_load("JBU");
  airline_load("JIA");
  airline_load("KAL");
  airline_load("KAP");
  airline_load("KLC");
  airline_load("KLM");
  airline_load("LAN");
  airline_load("LIGHTGA");
  airline_load("LLR");
  airline_load("LNI");
  airline_load("MOV");
  airline_load("NAX");
  airline_load("NKS");
  airline_load("ONE");
  airline_load("PAA");
  airline_load("PDT");
  airline_load("QXE");
  airline_load("RFF");
  airline_load("RLU");
  airline_load("RPA");
  airline_load("RYR");
  airline_load("SAS");
  airline_load("SBI");
  airline_load("SCX");
  airline_load("SEJ");
  airline_load("SJY");
  airline_load("SKW");
  airline_load("SLK");
  airline_load("SVR");
  airline_load("SWA");
  airline_load("SWR");
  airline_load("SXD");
  airline_load("TAM");
  airline_load("TCF");
  airline_load("TCX");
  airline_load("THY");
  airline_load("TOM");
  airline_load("TSO");
  airline_load("TUI");
  airline_load("TWA");
  airline_load("TYA");
  airline_load("UAE");
  airline_load("UAL");
  airline_load("UPS");
  airline_load("USAF");
  airline_load("VIR");
  airline_load("VRD");
  airline_load("VTI");
  airline_load("XAX");
}

function airline_load(icao) {
  icao = icao.toLowerCase();
  new Content({
    type: "json",
    url: "assets/airlines/"+icao+".json",
    payload: icao.toLowerCase(),
    callback: function(status, data, payload) {
      if(status == "ok") {
        prop.airline.airlines[payload] = new zlsa.atc.Airline(payload, data);
      }
    }
  });
}

function airline_get(icao) {
  icao = icao.toLowerCase();
  return prop.airline.airlines[icao];
}

function airline_ready() {
  for(var i in prop.airline.airlines) {
    prop.airline.airlines[i].validateFleets();
  }
}
<|endoftext|>


<commit_before>angular.module("seForms.inputs.inlineedit", ["seEvents.seEventHelperService"]).directive("seInlineEdit", function($log, SeEventHelperService, $parse) {
	"use strict";
	var uniqueFormName = 0;
	var SHOW_MODEL_VALIDATION_KEY = "showModelValidation";
	var CHANGED_CELL_CLASS_NAME = "se-inline-edit-dirty";

	function link(scope, element) {
		var values = {};
		function formController() {
			return popoverElement.data("$formController");
		}
		var saveMethod = function() {
			if (formController().$invalid) {
				SeEventHelperService.safeApply(scope, function() {
					formController()[SHOW_MODEL_VALIDATION_KEY] = true;
				});

				return;
			}
			element.addClass(CHANGED_CELL_CLASS_NAME);
			element.popover("hide");
		}
		function addButtons(popoverElement) {
			var emptyRow =  $("

");

			var save = $(" <button type=\"submit\" class=\"btn btn-red\"></button>");
			save.click(saveMethod);

			var cancel = $(" <button type=\"button\" class=\"btn btn-default\"></button>");
			cancel.click(function() {
				element.popover("hide");
				SeEventHelperService.safeApply(scope, function() {
					formController()[SHOW_MODEL_VALIDATION_KEY] = false;
					resetOriginalValues(popoverElement, values);
				});
			});

			popoverElement.append(emptyRow);
			popoverElement.append(cancel);
			popoverElement.append(save);
		}
		function iterateOverOriginalValues(popoverElement, handler) {
			var ngModels = popoverElement.find("[data-ng-model]");
			$.each(ngModels, function() {
				var ngModelElement = $(this);
				var model = ngModelElement.attr("data-ng-model");
				handler(model);
			});
		}
		function saveOriginalValues(popoverElement, values) {
			iterateOverOriginalValues(popoverElement, function(model) {
				values[model] = $parse(model)(scope);
			});
		}
		function resetOriginalValues(popoverElement, values) {
			iterateOverOriginalValues(popoverElement, function(model) {
				$parse(model).assign(scope, values[model]);
			});
		}

		var popoverElement = element.find("[data-se-inline-edit-form]").children();
		addButtons(popoverElement);
		element.click(function() {
			function isAlreadyOpen() {
				return element.next().is(".in");
			}
			if (isAlreadyOpen()) {
				return;
			}

			SeEventHelperService.safeApply(scope, function() {
				saveOriginalValues(popoverElement, values);
			});

			element.popover("show");
			popoverElement.find("[data-ng-model]:first").focus();

			//submit on enter
			popoverElement.keypress(function (e) {
				if (e.which == 13) {
					saveMethod();
					return false;
				}
			});
		});
		element.popover({
			trigger: "manual",
			content: popoverElement,
			placement: "left",
			html: true
		});
	}
	return {
		restrict: "A",
		compile: function(element) {
			function wrapAndHidFormMarker(formMarker) {
				var form = $("
", {"data-ng-form": "seInlineEdit"+(++uniqueFormName)});
				form.attr("data-ng-submit", "saveMethod()");
				formMarker.wrapInner(form);
				formMarker.hide();
			}
			var formMarker = element.find("[data-se-inline-edit-form]");
			if (formMarker.length === 0) {
				$log.error("seInlineEdit: no form", element);
				throw "seInlineEdit: no form";
			}
			wrapAndHidFormMarker(formMarker);
			return link;
		}
	};
});
<commit_msg>#20 Submit inline edit on enter key<commit_after>angular.module("seForms.inputs.inlineedit", ["seEvents.seEventHelperService"]).directive("seInlineEdit", function($log, SeEventHelperService, $parse) {
	"use strict";
	var uniqueFormName = 0;
	var SHOW_MODEL_VALIDATION_KEY = "showModelValidation";
	var CHANGED_CELL_CLASS_NAME = "se-inline-edit-dirty";

	function link(scope, element) {
		var values = {};
		function formController() {
			return popoverElement.data("$formController");
		}
		var saveMethod = function() {
			if (formController().$invalid) {
				SeEventHelperService.safeApply(scope, function() {
					formController()[SHOW_MODEL_VALIDATION_KEY] = true;
				});

				return;
			}
			element.addClass(CHANGED_CELL_CLASS_NAME);
			element.popover("hide");
		}
		function addButtons(popoverElement) {
			var emptyRow =  $("

");

			var save = $(" <button type=\"submit\" class=\"btn btn-red\"></button>");
			save.click(saveMethod);

			var cancel = $(" <button type=\"button\" class=\"btn btn-default\"></button>");
			cancel.click(function() {
				element.popover("hide");
				SeEventHelperService.safeApply(scope, function() {
					formController()[SHOW_MODEL_VALIDATION_KEY] = false;
					resetOriginalValues(popoverElement, values);
				});
			});

			popoverElement.append(emptyRow);
			popoverElement.append(cancel);
			popoverElement.append(save);
		}
		function iterateOverOriginalValues(popoverElement, handler) {
			var ngModels = popoverElement.find("[data-ng-model]");
			$.each(ngModels, function() {
				var ngModelElement = $(this);
				var model = ngModelElement.attr("data-ng-model");
				handler(model);
			});
		}
		function saveOriginalValues(popoverElement, values) {
			iterateOverOriginalValues(popoverElement, function(model) {
				values[model] = $parse(model)(scope);
			});
		}
		function resetOriginalValues(popoverElement, values) {
			iterateOverOriginalValues(popoverElement, function(model) {
				$parse(model).assign(scope, values[model]);
			});
		}

		var popoverElement = element.find("[data-se-inline-edit-form]").children();
		addButtons(popoverElement);
		element.click(function() {
			function isAlreadyOpen() {
				return element.next().is(".in");
			}
			if (isAlreadyOpen()) {
				return;
			}

			SeEventHelperService.safeApply(scope, function() {
				saveOriginalValues(popoverElement, values);
			});

			element.popover("show");
			popoverElement.find("[data-ng-model]:first").focus();

			//submit on enter
			popoverElement.keypress(function (e) {
				if (e.which == 13) {
					saveMethod();
					return false;
				}
			});
		});
		element.popover({
			trigger: "manual",
			content: popoverElement,
			placement: "left",
			html: true
		});
	}
	return {
		restrict: "A",
		compile: function(element) {
			function wrapAndHidFormMarker(formMarker) {
				var form = $("
", {"data-ng-form": "seInlineEdit"+(++uniqueFormName)});
				formMarker.wrapInner(form);
				formMarker.hide();
			}
			var formMarker = element.find("[data-se-inline-edit-form]");
			if (formMarker.length === 0) {
				$log.error("seInlineEdit: no form", element);
				throw "seInlineEdit: no form";
			}
			wrapAndHidFormMarker(formMarker);
			return link;
		}
	};
});
<|endoftext|>


<commit_before>import _ from 'lodash';
import queryString from 'query-string';
import pathMatch from 'path-match';
import parseUrl from 'parse-url';

export const baseInterceptor = ({ routes, host }, fakeService) => {
  const getRoute = ({ handlers, pathname, fullpath }) => {
    const matchesPathname = path => pathMatch()(path)(pathname);
    const route = _.keys(handlers).find(matchesPathname);
    const hasHost = _.includes(fullpath, host);

    return route && hasHost ? route : null;
  };

  const extractUrl = (url, method) => ({
    handlers: routes[method],
    pathname: parseUrl(url).pathname,
    fullpath: parseUrl(url).href
  });

  const getHandler = (url, method) => {
    const extractedUrl = extractUrl(url, method);
    const route = getRoute(extractedUrl);

    return route ? extractedUrl.handlers[route] : null;
  };

  const getParams = (url, method) => {
    const extractedUrl = extractUrl(url, method);
    const matchesPathname = path => pathMatch()(path)(extractedUrl.pathname);
    const route = getRoute(extractedUrl);

    return route ? matchesPathname(route) : null;
  };

  return fakeService.bind(null, {getHandler, getParams});
};
<commit_msg>style(interceptors/baseInterceptor): fixes according to airbnb-javascript guide<commit_after>import _ from 'lodash';
import pathMatch from 'path-match';
import parseUrl from 'parse-url';

export const baseInterceptor = ({ routes, host }, fakeService) => {
  const getRoute = ({ handlers, pathname, fullpath }) => {
    const matchesPathname = path => pathMatch()(path)(pathname);
    const route = _.keys(handlers).find(matchesPathname);
    const hasHost = _.includes(fullpath, host);

    return route && hasHost ? route : null;
  };

  const extractUrl = (url, method) => ({
    handlers: routes[method],
    pathname: parseUrl(url).pathname,
    fullpath: parseUrl(url).href,
  });

  const getHandler = (url, method) => {
    const extractedUrl = extractUrl(url, method);
    const route = getRoute(extractedUrl);

    return route ? extractedUrl.handlers[route] : null;
  };

  const getParams = (url, method) => {
    const extractedUrl = extractUrl(url, method);
    const matchesPathname = path => pathMatch()(path)(extractedUrl.pathname);
    const route = getRoute(extractedUrl);

    return route ? matchesPathname(route) : null;
  };

  return fakeService.bind(null, { getHandler, getParams });
};
<|endoftext|>


<commit_before>import SGoogleMapComponentBase from 'coffeekraken-s-google-map-component-base'
import __whenAttribute from 'coffeekraken-sugar/js/dom/whenAttribute'

/**
 * @name 		SGoogleMapMarkerComponent
 * @extends 	SGoogleMapComponentBase
 * Provide a nice webcomponent wrapper around the google map marker api.
 *
 * @example 	html
 * <s-google-map center="{lat: -25.363, lng: 131.044}">
 * 	<s-google-map-marker position="{lat: -25.363, lng: 131.044}">
 * 	</s-google-map-marker>
 * </s-google-map>
 * @see 	https://www.npmjs.com/package/google-maps
 * @see 	https://developers.google.com/maps/documentation/javascript/
 * @author 	Olivier Bossel <olivier.bossel@gmail.com>
 */

export default class SGoogleMapMarkerComponent extends SGoogleMapComponentBase {

	/**
	 * Default props
	 * @definition 		SWebComponent.defaultProps
	 * @protected
	 */
	static get defaultProps() {
		return {

			/**
			 * @name 	Google Map Marker API
			 * Support all the google map marker API properties
			 * @prop
			 * @type 	{Google.Map.Marker}
			 * @see 	https://developers.google.com/maps/documentation/javascript/3.exp/reference#MarkerOptions 	Google Map Marker Options
			 */

		};
	}

	/**
	 * Mount dependencies
	 * @definition 		SWebComponent.mountDependencies
	 * @protected
	 */
	static get mountDependencies() {
		return [function() {
			return __whenAttribute(this.parentNode, 'inited');
		}];
	}

	/**
	 * Physical props
	 * @definition 		SWebComponent.physicalProps
	 * @protected
	 */
	static get physicalProps() {
		return [];
	}

	/**
	 * Should accept component props
	 * @definition 		SWebComponent.shouldComponentAcceptProp
	 * @protected
	 */
	shouldComponentAcceptProp(prop) {
		return true;
	}

	/**
	 * Component will mount
	 * @definition 		SWebComponent.componentWillMount
	 * @protected
	 */
	componentWillMount() {
		super.componentWillMount();
	}

	/**
	 * Mount component
	 * @definition 		SWebComponent.componentMount
	 * @protected
	 */
	componentMount() {
		super.componentMount();

		// save reference to the parent node to dispatch an event when unmounted
		this._parentNode = this.parentNode;

		// get the map instance to use for this marker.
		// this is grabed from the parent node that need to be a google-map component
		if ( ! this.map) {
			throw `The "${this._componentNameDash}" component has to be a direct child of a "SGoogleMapComponent"`;
		}

		// add the marker to the map
		// load the map api
		if ( ! this._marker) {
			this._initMarker();
		} else {
			this._marker.setMap(this.map);
		}

		// dispatch an event to notify the new marker
		this.dispatchComponentEvent('new-google-map-marker', this._marker);
	}

	/**
	 * Component unmount
	 * @definition 		SWebComponent.componentUnmount
	 * @protected
	 */
	componentUnmount() {
		super.componentUnmount();
		// remove the marker from the map
		if (this._marker) {
			this._marker.setMap(null);
		}
		// dispatch an event to notify the new marker
		this.dispatchComponentEvent('remove-google-map-marker', this._marker, this._parentNode);
	}

	/**
	 * Component will receive props
	 * @definition 		SWebComponent.componentWillReceiveProps
	 * @protected
	 */
	componentWillReceiveProps(nextProps, previousProps) {
		if ( ! this._marker) return;
		this._marker.setOptions(nextProps);
	}

	/**
	 * Render the component
	 * Here goes the code that reflect the this.props state on the actual html element
	 * @definition 		SWebComponent.render
	 * @protected
	 */
	render() {
		super.render();
	}

	/**
	 * Init the marker
	 */
	_initMarker() {
		this._marker = new this.google.maps.Marker(this.props);
		this._marker.setMap(this.map);
		// set the component as inited
		// used by the markers to init when the map is ok
		this.setAttribute('inited', true);
	}

	/**
	 * Access the google map instance
	 * @type 	{Google.Map}
	 */
	get map() {
		return this.parentNode.map;
	}

	/**
	 * Access the google map marker instance
	 * @type 	{Google.Map.Marker}
	 */
	get marker() {
		return this._marker;
	}
}
<commit_msg>fix unmountTimeout<commit_after>import SGoogleMapComponentBase from 'coffeekraken-s-google-map-component-base'
import __whenAttribute from 'coffeekraken-sugar/js/dom/whenAttribute'

/**
 * @name 		SGoogleMapMarkerComponent
 * @extends 	SGoogleMapComponentBase
 * Provide a nice webcomponent wrapper around the google map marker api.
 *
 * @example 	html
 * <s-google-map center="{lat: -25.363, lng: 131.044}">
 * 	<s-google-map-marker position="{lat: -25.363, lng: 131.044}">
 * 	</s-google-map-marker>
 * </s-google-map>
 * @see 	https://www.npmjs.com/package/google-maps
 * @see 	https://developers.google.com/maps/documentation/javascript/
 * @author 	Olivier Bossel <olivier.bossel@gmail.com>
 */

export default class SGoogleMapMarkerComponent extends SGoogleMapComponentBase {

	/**
	 * Default props
	 * @definition 		SWebComponent.defaultProps
	 * @protected
	 */
	static get defaultProps() {
		return {

			// set the unmout timeout to 0 to avoid unwanted delays when adding and removing markers
			unmountTimeout : 0,

			/**
			 * @name 	Google Map Marker API
			 * Support all the google map marker API properties
			 * @prop
			 * @type 	{Google.Map.Marker}
			 * @see 	https://developers.google.com/maps/documentation/javascript/3.exp/reference#MarkerOptions 	Google Map Marker Options
			 */

		};
	}

	/**
	 * Mount dependencies
	 * @definition 		SWebComponent.mountDependencies
	 * @protected
	 */
	static get mountDependencies() {
		return [function() {
			return __whenAttribute(this.parentNode, 'inited');
		}];
	}

	/**
	 * Physical props
	 * @definition 		SWebComponent.physicalProps
	 * @protected
	 */
	static get physicalProps() {
		return [];
	}

	/**
	 * Should accept component props
	 * @definition 		SWebComponent.shouldComponentAcceptProp
	 * @protected
	 */
	shouldComponentAcceptProp(prop) {
		return true;
	}

	/**
	 * Component will mount
	 * @definition 		SWebComponent.componentWillMount
	 * @protected
	 */
	componentWillMount() {
		super.componentWillMount();
	}

	/**
	 * Mount component
	 * @definition 		SWebComponent.componentMount
	 * @protected
	 */
	componentMount() {
		super.componentMount();

		// save reference to the parent node to dispatch an event when unmounted
		this._parentNode = this.parentNode;

		// get the map instance to use for this marker.
		// this is grabed from the parent node that need to be a google-map component
		if ( ! this.map) {
			throw `The "${this._componentNameDash}" component has to be a direct child of a "SGoogleMapComponent"`;
		}

		// add the marker to the map
		// load the map api
		if ( ! this._marker) {
			this._initMarker();
		} else {
			this._marker.setMap(this.map);
		}

		// dispatch an event to notify the new marker
		this.dispatchComponentEvent('new-google-map-marker', this._marker);
	}

	/**
	 * Component unmount
	 * @definition 		SWebComponent.componentUnmount
	 * @protected
	 */
	componentUnmount() {
		super.componentUnmount();
		// remove the marker from the map
		if (this._marker) {
			this._marker.setMap(null);
		}
		// dispatch an event to notify the new marker
		this.dispatchComponentEvent('remove-google-map-marker', this._marker, this._parentNode);
	}

	/**
	 * Component will receive props
	 * @definition 		SWebComponent.componentWillReceiveProps
	 * @protected
	 */
	componentWillReceiveProps(nextProps, previousProps) {
		if ( ! this._marker) return;
		this._marker.setOptions(nextProps);
	}

	/**
	 * Render the component
	 * Here goes the code that reflect the this.props state on the actual html element
	 * @definition 		SWebComponent.render
	 * @protected
	 */
	render() {
		super.render();
	}

	/**
	 * Init the marker
	 */
	_initMarker() {
		this._marker = new this.google.maps.Marker(this.props);
		this._marker.setMap(this.map);
		// set the component as inited
		// used by the markers to init when the map is ok
		this.setAttribute('inited', true);
	}

	/**
	 * Access the google map instance
	 * @type 	{Google.Map}
	 */
	get map() {
		return this.parentNode.map;
	}

	/**
	 * Access the google map marker instance
	 * @type 	{Google.Map.Marker}
	 */
	get marker() {
		return this._marker;
	}
}
<|endoftext|>


<commit_before>'use strict';

app.controller('AppController',
  ['$scope', '$translate', 'LANGUAGES', 'VERSION',
      'DEFAULT_PREFERENCES', '$location', 'localStorageService',
  function($scope, $translate, lang, version,
           defaultPreferences, $location, localStorageService) {
    $scope.init = function() {

      $scope.showFilters = false;
      $scope.toggleFilters = function() {
        $scope.showFilters = !$scope.showFilters;
      };

      // App values & settings
      $scope.kConfig = defaultPreferences;
      $scope.kConfig.lang = $translate.proposedLanguage();
      $scope.version = version;

      // Register Events
      registerEvents();

      // Init localStorage
      initLocalStorage();

      // Init Lang
      $scope.switchLang($scope.kConfig.lang);
    };

    // Private functions & Utils
    $scope.switchLang = function(newlang) {
      $translate.use(newlang);
      $scope.lang = lang[newlang];
      $scope.kConfig.lang = $scope.lang.key;
    };

    function registerEvents() {
      // Events
      $scope.$on('$routeChangeSuccess', function(evt, absNewUrl, absOldUrl) {
        $scope.previous = absOldUrl;
      });
      $scope.$on('$locationChangeSuccess', function() {
        $scope.currentQuery =
          $location.search().q ? '?q=' + $location.search().q : '';
      });
      $scope.$on('newsActive', function(event, args) {
        $scope.newsActive = true;
        $scope.searchActive = false;
        $scope.picturesActive = false;
        $scope.proActive = false;
      });
      $scope.$on('searchActive', function(event, args) {
        $scope.searchActive = true;
        $scope.newsActive = false;
        $scope.picturesActive = false;
        $scope.proActive = false;
      });
      $scope.$on('picturesActive', function(event, args) {
        $scope.picturesActive = true;
        $scope.searchActive = false;
        $scope.newsActive = false;
        $scope.proActive = false;
      });
      $scope.$on('proActive', function(event, args) {
        $scope.searchActive = false;
        $scope.newsActive = false;
        $scope.picturesActive = false;
        $scope.proActive = true;
      });
      $scope.$on('noneActive', function(event, args) {
        $scope.searchActive = false;
        $scope.newsActive = false;
        $scope.picturesActive = false;
        $scope.proActive = false;
      });
    }

    function initLocalStorage() {
      if (localStorageService.isSupported) {

        // Init localstorage values
        for (var prop in $scope.kConfig) {
          if ($scope.kConfig.hasOwnProperty(prop)) {
            if (localStorageService.get(prop) === null) {
              localStorageService.set(prop, $scope.kConfig[prop]);
            }
            localStorageService.bind($scope, 'kConfig.' + prop,
              localStorageService.get(prop), prop);
          }
        }

        var kconKeys = localStorageService.keys();
        if (kconKeys.length > 0) {
          // Clean unused keys from localStorage
          kconKeys.forEach(function(kconKey) {
            if (!$scope.kConfig.hasOwnProperty(kconKey)) {
              localStorageService.remove(kconKey);
            }
          });
        } else {
          console.error('enable to init localStorage');
        }
      } else {
        console.error('localStorage is not supported');
      }
    }

    $scope.init();
  },]);

<commit_msg>fix: lint error<commit_after>'use strict';

app.controller('AppController',
  ['$scope', '$translate', 'LANGUAGES', 'VERSION',
      'DEFAULT_PREFERENCES', '$location', 'localStorageService',
  function($scope, $translate, lang, version,
           defaultPreferences, $location, localStorageService) {
    $scope.init = function() {
      $scope.showFilters = false;
      $scope.toggleFilters = function() {
        $scope.showFilters = !$scope.showFilters;
      };

      // App values & settings
      $scope.kConfig = defaultPreferences;
      $scope.kConfig.lang = $translate.proposedLanguage();
      $scope.version = version;

      // Register Events
      registerEvents();

      // Init localStorage
      initLocalStorage();

      // Init Lang
      $scope.switchLang($scope.kConfig.lang);
    };

    // Private functions & Utils
    $scope.switchLang = function(newlang) {
      $translate.use(newlang);
      $scope.lang = lang[newlang];
      $scope.kConfig.lang = $scope.lang.key;
    };

    function registerEvents() {
      // Events
      $scope.$on('$routeChangeSuccess', function(evt, absNewUrl, absOldUrl) {
        $scope.previous = absOldUrl;
      });
      $scope.$on('$locationChangeSuccess', function() {
        $scope.currentQuery =
          $location.search().q ? '?q=' + $location.search().q : '';
      });
      $scope.$on('newsActive', function(event, args) {
        $scope.newsActive = true;
        $scope.searchActive = false;
        $scope.picturesActive = false;
        $scope.proActive = false;
      });
      $scope.$on('searchActive', function(event, args) {
        $scope.searchActive = true;
        $scope.newsActive = false;
        $scope.picturesActive = false;
        $scope.proActive = false;
      });
      $scope.$on('picturesActive', function(event, args) {
        $scope.picturesActive = true;
        $scope.searchActive = false;
        $scope.newsActive = false;
        $scope.proActive = false;
      });
      $scope.$on('proActive', function(event, args) {
        $scope.searchActive = false;
        $scope.newsActive = false;
        $scope.picturesActive = false;
        $scope.proActive = true;
      });
      $scope.$on('noneActive', function(event, args) {
        $scope.searchActive = false;
        $scope.newsActive = false;
        $scope.picturesActive = false;
        $scope.proActive = false;
      });
    }

    function initLocalStorage() {
      if (localStorageService.isSupported) {

        // Init localstorage values
        for (var prop in $scope.kConfig) {
          if ($scope.kConfig.hasOwnProperty(prop)) {
            if (localStorageService.get(prop) === null) {
              localStorageService.set(prop, $scope.kConfig[prop]);
            }
            localStorageService.bind($scope, 'kConfig.' + prop,
              localStorageService.get(prop), prop);
          }
        }

        var kconKeys = localStorageService.keys();
        if (kconKeys.length > 0) {
          // Clean unused keys from localStorage
          kconKeys.forEach(function(kconKey) {
            if (!$scope.kConfig.hasOwnProperty(kconKey)) {
              localStorageService.remove(kconKey);
            }
          });
        } else {
          console.error('enable to init localStorage');
        }
      } else {
        console.error('localStorage is not supported');
      }
    }

    $scope.init();
  },]);
<|endoftext|>


<commit_before>this.mmooc = this.mmooc || {};

this.mmooc.discussionTopics = function () {
    return {
        setDiscussionTopicPubDate: function(discussionTopic) {
            var formattedDate = mmooc.util.formattedDate(discussionTopic.posted_at);
            var pubDate = $("
" + formattedDate + "
");
            $(pubDate).prependTo('#discussion_topic .discussion-header-right');
        },

        alterDiscussionReadStateLook: function() {
            var self = this;
            $('body').on('click', '.read-unread-button', function (){
               $(this).toggleClass('read');
               $(this).closest(".entry-content").siblings(".discussion-read-state-btn").click();
               self.toggleReadUnreadButton($(this));
           });

            var checkExist = setInterval(function() {
                if ($('.discussion-read-state-btn').length) {
                  clearInterval(checkExist);
                  var readUnreadButton = $("
Marker som lest
");
                  readUnreadButton.appendTo('.discussion_entry .entry-header');
                  self.toggleReadUnreadButton($(this).closest(".discussion_entry").find("read-unread-button"));
                }
            }, 100);
        },

        toggleReadUnreadButton: function(button) {
            $(".discussion-read-state-btn").each(function(index) {
                    var button = $(this).siblings(".entry-content").find(".read-unread-button");
                    if($(this).parent().hasClass("unread")) {
                        button.text('Marker som lest');
                        button.addClass('read');
                    }
                    else {
                        button.text('Marker som ulest');
                        button.removeClass('read');
                    }
                });
        },
        setDiscussionsListUnreadClass: function() {
          var wait = setInterval(function() {
            clearInterval(wait);
            $("#open-discussions .ig-list .discussion").each(function() {
              var unread = $(this).find('.new-items').text();
              if(unread.indexOf('0') == -1) {
                $(this).addClass('unread');
              }
            });
          }, 800);
        },
        insertSearchButton: function() {
          $('.index_view_filter_form').append('<button class="btn btn-discussion-search">');

        }
    };
}();

<commit_msg>MAT-260: Check if elements exists before adding unread class<commit_after>this.mmooc = this.mmooc || {};

this.mmooc.discussionTopics = function () {
    return {
        setDiscussionTopicPubDate: function(discussionTopic) {
            var formattedDate = mmooc.util.formattedDate(discussionTopic.posted_at);
            var pubDate = $("
" + formattedDate + "
");
            $(pubDate).prependTo('#discussion_topic .discussion-header-right');
        },

        alterDiscussionReadStateLook: function() {
            var self = this;
            $('body').on('click', '.read-unread-button', function (){
               $(this).toggleClass('read');
               $(this).closest(".entry-content").siblings(".discussion-read-state-btn").click();
               self.toggleReadUnreadButton($(this));
           });

            var checkExist = setInterval(function() {
                if ($('.discussion-read-state-btn').length) {
                  clearInterval(checkExist);
                  var readUnreadButton = $("
Marker som lest
");
                  readUnreadButton.appendTo('.discussion_entry .entry-header');
                  self.toggleReadUnreadButton($(this).closest(".discussion_entry").find("read-unread-button"));
                }
            }, 100);
        },

        toggleReadUnreadButton: function(button) {
            $(".discussion-read-state-btn").each(function(index) {
                    var button = $(this).siblings(".entry-content").find(".read-unread-button");
                    if($(this).parent().hasClass("unread")) {
                        button.text('Marker som lest');
                        button.addClass('read');
                    }
                    else {
                        button.text('Marker som ulest');
                        button.removeClass('read');
                    }
                });
        },
        setDiscussionsListUnreadClass: function() {
          var checkExist = setInterval(function() {
            if ($("#open-discussions .ig-list .discussion").length) {
              clearInterval(checkExist);
              $("#open-discussions .ig-list .discussion").each(function() {
                var unread = $(this).find('.new-items').text();
                if(unread.indexOf('0') == -1) {
                  $(this).addClass('unread');
                }
              });
            }
          }, 100);
        },
        insertSearchButton: function() {
          $('.index_view_filter_form').append('<button class="btn btn-discussion-search">');
        }
    };
}();

<|endoftext|>


<commit_before>import queries from './queries'

const {
  GSBPMDescription
} = queries

export default {
  GSBPMDescription: {
    descr: 'Retrieve a globale description of the GSBPM',
    whatWeGet: 'phases',
    results: {
      phase: 'phase (uri)',
      phaseLabel: 'phase label',
      subprocess: 'subprocess (uri)',
      subprocessLabel: 'subprocess label'
    },
    params: [],
    queryBuilder: GSBPMDescription
  }
}
<commit_msg>Fix type<commit_after>import queries from './queries'

const {
  GSBPMDescription
} = queries

export default {
  GSBPMDescription: {
    descr: 'Retrieve a global description of the GSBPM',
    whatWeGet: 'phases',
    results: {
      phase: 'phase (uri)',
      phaseLabel: 'phase label',
      subprocess: 'subprocess (uri)',
      subprocessLabel: 'subprocess label'
    },
    params: [],
    queryBuilder: GSBPMDescription
  }
}
<|endoftext|>


<commit_before>/*eslint-env mocha */
const should = require('should') // eslint-disable-line no-unused-vars
const tokeniser = require('js-tokeniser')
const rules = require('./rules')

describe('Tokeniser', () => {
    it('should recognise comments', done => {
        let result = tokeniser('// abc', rules)
        result.should.be.an.array
        result.length.should.equal(1)
        result[0].type.should.equal('comment')
        result[0].matches[0].should.equal('// abc')
        done()
    })

    it('should recognise definitions', done => {
        let result = tokeniser('Name = Test\nAuthor = "Bob Sherman"', rules)
        result[0].type.should.equal('definition')
        result[1].type.should.equal('definition')
        result[0].matches[1].should.equal('Name')
        result[0].matches[2].should.equal('Test')
        result[1].matches[1].should.equal('Author')
        result[1].matches[2].should.equal('"Bob Sherman"')
        done()
    })

    it('should recognise arrays', done => {
        let result = tokeniser('abc [\n\tx = 1\n]', rules)
        result.should.be.an.array
        result.length.should.equal(3)
        result[0].type.should.equal('arrayStart')
        result[0].matches[0].should.equal('abc [')
        result[0].matches[1].should.equal('abc')
        result[2].type.should.equal('arrayEnd')
        result[2].matches[0].trim().should.equal(']')
        done()
    })

    it('should recognise objects', done => {
        let result = tokeniser('abc {\n\tx = 1\n}', rules)
        result.should.be.an.array
        result.length.should.equal(3)
        result[0].type.should.equal('objectStart')
        result[0].matches[0].should.equal('abc {')
        result[0].matches[1].should.equal('abc')
        result[2].type.should.equal('objectEnd')
        result[2].matches[0].trim().should.equal('}')
        done()
    })

    it('should recognise objects in an array', done => {
        let result = tokeniser('Array[\n\t{\n\t}\n]', rules)
        result.length.should.equal(4)
        result[0].type.should.equal('arrayStart')
        result[1].type.should.equal('objectStart')
        result[2].type.should.equal('objectEnd')
        result[3].type.should.equal('arrayEnd')
        result[0].matches[0].should.equal('Array[')
        result[0].matches[1].should.equal('Array')
        result[1].matches[0].should.equal('\n\t{')
        result[1].matches[1].should.equal('')
        result[2].matches[0].should.equal('\n\t}')
        result[3].matches[0].should.equal('\n]')
        done()
    })
    it('should recognise arrays in an array', done => {
        let result = tokeniser('Array[\n\t[\n\t]\n]', rules)
        result.length.should.equal(4)
        result[0].type.should.equal('arrayStart')
        result[1].type.should.equal('arrayStart')
        result[2].type.should.equal('arrayEnd')
        result[3].type.should.equal('arrayEnd')
        result[0].matches[0].should.equal('Array[')
        result[0].matches[1].should.equal('Array')
        result[1].matches[0].should.equal('\n\t[')
        result[1].matches[1].should.equal('')
        result[2].matches[0].should.equal('\n\t]')
        result[3].matches[0].should.equal('\n]')
       done()
    })

    it('should recognise literals in an array', done => {
        let result = tokeniser('abc [1, 2, 3]', rules)
        result.should.be.an.array
        result.length.should.equal(3)
        result[0].type.should.equal('arrayStart')
        result[0].matches[0].should.equal('abc [')
        result[0].matches[1].should.equal('abc')
        result[2].type.should.equal('arrayEnd')
        result[2].matches[0].trim().should.equal(']')
        done()
    })
})
<commit_msg>Use of js-tokeniser<commit_after>/*eslint-env mocha */
const should = require('should') // eslint-disable-line no-unused-vars
const tokeniser = require('js-tokeniser')
const rules = require('./rules')

describe('Tokeniser', () => {
    it('should recognise comments', done => {
        let result = tokeniser('// abc', rules)
        result.should.be.an.array
        result.length.should.equal(1)
        result[0].type.should.equal('comment')
        result[0].matches[0].should.equal('// abc')
        done()
    })

    it('should recognise definitions', done => {
        let result = tokeniser('Name = Test\nAuthor = "Bob Sherman"', rules)
        result[0].type.should.equal('definition')
        result[1].type.should.equal('definition')
        result[0].matches[1].should.equal('Name')
        result[0].matches[2].should.equal('Test')
        result[1].matches[1].should.equal('Author')
        result[1].matches[2].should.equal('"Bob Sherman"')
        done()
    })

    it('should recognise arrays', done => {
        let result = tokeniser('abc [\n\tx = 1\n]', rules)
        result.should.be.an.array
        result.length.should.equal(3)
        result[0].type.should.equal('arrayStart')
        result[0].matches[0].should.equal('abc [')
        result[0].matches[1].should.equal('abc')
        result[2].type.should.equal('arrayEnd')
        result[2].matches[0].trim().should.equal(']')
        done()
    })

    it('should recognise objects', done => {
        let result = tokeniser('abc {\n\tx = 1\n}', rules)
        result.should.be.an.array
        result.length.should.equal(3)
        result[0].type.should.equal('objectStart')
        result[0].matches[0].should.equal('abc {')
        result[0].matches[1].should.equal('abc')
        result[2].type.should.equal('objectEnd')
        result[2].matches[0].trim().should.equal('}')
        done()
    })

    it('should recognise objects in an array', done => {
        let result = tokeniser('Array[\n\t{\n\t}\n]', rules)
        result.length.should.equal(4)
        result[0].type.should.equal('arrayStart')
        result[1].type.should.equal('objectStart')
        result[2].type.should.equal('objectEnd')
        result[3].type.should.equal('arrayEnd')
        result[0].matches[0].should.equal('Array[')
        result[0].matches[1].should.equal('Array')
        result[1].matches[0].should.equal('\n\t{')
        result[1].matches[1].should.equal('')
        result[2].matches[0].should.equal('\n\t}')
        result[3].matches[0].should.equal('\n]')
        done()
    })
    it('should recognise arrays in an array', done => {
        let result = tokeniser('Array[\n\t[\n\t]\n]', rules)
        result.length.should.equal(4)
        result[0].type.should.equal('arrayStart')
        result[1].type.should.equal('arrayStart')
        result[2].type.should.equal('arrayEnd')
        result[3].type.should.equal('arrayEnd')
        result[0].matches[0].should.equal('Array[')
        result[0].matches[1].should.equal('Array')
        result[1].matches[0].should.equal('\n\t[')
        result[1].matches[1].should.equal('')
        result[2].matches[0].should.equal('\n\t]')
        result[3].matches[0].should.equal('\n]')
        done()
    })

    it('should recognise literals in an array', done => {
        let result = tokeniser('abc [1, 2, 3]', rules)
        result.should.be.an.array
        result.length.should.equal(3)
        result[0].type.should.equal('arrayStart')
        result[0].matches[0].should.equal('abc [')
        result[0].matches[1].should.equal('abc')
        result[2].type.should.equal('arrayEnd')
        result[2].matches[0].trim().should.equal(']')
        done()
    })
})
<|endoftext|>


<commit_before>/**
 * Fork Performance Benchmark
 * Measures the cost of forking a repo. This is a good indicator of
 * start up time for complicated trees.
 */

'use strict'

const { Microcosm } = require('../build/microcosm.min')
const time = require('microtime')

const SIZES = [
  100,
  5000,
  15000,
  30000
]

console.log('\nConducting fork benchmark...\n')

var action = 'test'

var Domain = {
  getInitialState: () => 0,
  register() {
    return {
      [action]: (n) => n + 1
    }
  }
}

var results = SIZES.map(function (SIZE) {
  var repo = new Microcosm()

  repo.addDomain('one', Domain)

  var then = time.now()
  for (var i = 0; i < SIZE; i++) {
    repo.fork().on('change', () => {})
  }

  var setup = (time.now() - then) / 1000

  then = time.now()
  repo.push(action, 1)
  var push = (time.now() - then) / 1000

  return {
    'Count'  : SIZE.toLocaleString(),
    'Setup'  : setup.toLocaleString() + 'ms',
    'Push'   : push.toLocaleString() + 'ms'
  }
})

/**
 * Finally, report our findings.
 */

require('console.table')

console.table(results)
<commit_msg>Use different arity in benchmark to avoid deopt<commit_after>/**
 * Fork Performance Benchmark
 * Measures the cost of forking a repo. This is a good indicator of
 * start up time for complicated trees.
 */

'use strict'

const { Microcosm } = require('../build/microcosm.min')
const time = require('microtime')

const SIZES = [
  100,
  5000,
  15000,
  30000
]

console.log('\nConducting fork benchmark...\n')

var action = 'test'

var Domain = {
  getInitialState: () => 0,
  register() {
    return {
      [action]: (a, b) => a + b
    }
  }
}

var results = SIZES.map(function (SIZE) {
  var repo = new Microcosm()

  repo.addDomain('one', Domain)

  var then = time.now()
  for (var i = 0; i < SIZE; i++) {
    repo.fork().on('change', () => {})
  }

  var setup = (time.now() - then) / 1000

  then = time.now()
  repo.push(action, 1)
  var push = (time.now() - then) / 1000

  return {
    'Count'  : SIZE.toLocaleString(),
    'Setup'  : setup.toLocaleString() + 'ms',
    'Push'   : push.toLocaleString() + 'ms'
  }
})

/**
 * Finally, report our findings.
 */

require('console.table')

console.table(results)
<|endoftext|>


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

var path = require("path");
var url = require("url");
var fs = require("fs");

// Local version replaces global one
try {
	var localWebpackDevServer = require.resolve(path.join(process.cwd(), "node_modules", "webpack-dev-server", "bin", "webpack-dev-server.js"));
	if(__filename !== localWebpackDevServer) {
		return require(localWebpackDevServer);
	}
} catch(e) {}

var Server = require("../lib/Server");
var webpack = require("webpack");

var optimist = require("optimist")

	.usage("webpack-dev-server " + require("../package.json").version + "\n" +
			"Usage: http://webpack.github.io/docs/webpack-dev-server.html")

	.boolean("lazy").describe("lazy")

	.boolean("info").describe("info").default("info", true)

	.boolean("quiet").describe("quiet")

	.boolean("inline").describe("inline", "Inline the webpack-dev-server logic into the bundle.")

	.boolean("https").describe("https")

	.string("key").describe("key", "Path to a SSL key.")

	.string("cert").describe("cert", "Path to a SSL certificate.")

	.string("cacert").describe("cacert", "Path to a SSL CA certificate.")

	.string("content-base").describe("content-base", "A directory or URL to serve HTML content from.")

	.string("content-base-target").describe("content-base-target", "Proxy requests to this target.")

	.boolean("history-api-fallback").describe("history-api-fallback", "Fallback to /index.html for Single Page Applications.")

	.boolean("compress").describe("compress", "enable gzip compression")

	.describe("port", "The port").default("port", 8080)

	.describe("host", "The hostname/ip address the server will bind to").default("host", "localhost");

require("webpack/bin/config-optimist")(optimist);

var argv = optimist.argv;

var wpOpt = require("webpack/bin/convert-argv")(optimist, argv, { outputFilename: "/bundle.js" });
var firstWpOpt = Array.isArray(wpOpt) ? wpOpt[0] : wpOpt;

var options = wpOpt.devServer || firstWpOpt.devServer || {};

if(argv.host !== "localhost" || !options.host)
	options.host = argv.host;

if(argv.port !== 8080 || !options.port)
	options.port = argv.port;

if(!options.publicPath) {
	options.publicPath = firstWpOpt.output && firstWpOpt.output.publicPath || "";
	if(!/^(https?:)?\/\//.test(options.publicPath) && options.publicPath[0] !== "/")
		options.publicPath = "/" + options.publicPath;
}

if(!options.outputPath)
	options.outputPath = "/";
if(!options.filename)
	options.filename = firstWpOpt.output && firstWpOpt.output.filename;
[].concat(wpOpt).forEach(function(wpOpt) {
	wpOpt.output.path = "/";
});

if(!options.watchOptions)
	options.watchOptions = firstWpOpt.watchOptions;
if(!options.watchDelay && !options.watchOptions) // TODO remove in next major version
	options.watchDelay = firstWpOpt.watchDelay;

if(!options.hot)
	options.hot = argv["hot"];

if(argv["content-base"]) {
	options.contentBase = argv["content-base"];
	if(/^[0-9]$/.test(options.contentBase))
		options.contentBase = +options.contentBase;
	else if(!/^(https?:)?\/\//.test(options.contentBase))
		options.contentBase = path.resolve(options.contentBase);
} else if(argv["content-base-target"]) {
	options.contentBase = { target: argv["content-base-target"] };
} else if(!options.contentBase) {
	options.contentBase = process.cwd();
}

if(!options.stats) {
	options.stats = {
		cached: false,
		cachedAssets: false
	};
}

if(typeof options.stats === "object" && typeof options.stats.colors === "undefined")
	options.stats.colors = require("supports-color");

if(argv["lazy"])
	options.lazy = true;

if(!argv["info"])
	options.noInfo = true;

if(argv["quiet"])
	options.quiet = true;

if(argv["https"])
	options.https = true;

if(argv["cert"])
	options.cert = fs.readFileSync(path.resolve(argv["cert"]));

if(argv["key"])
	options.key = fs.readFileSync(path.resolve(argv["key"]));

if(argv["cacert"])
	options.cacert = fs.readFileSync(path.resolve(argv["cacert"]));

if(argv["inline"])
	options.inline = true;

if(argv["history-api-fallback"])
	options.historyApiFallback = true;

if(argv["compress"])
	options.compress = true;

var protocol = options.https ? "https" : "http";

if(options.inline) {
	var devClient = [require.resolve("../client/") + "?" + protocol + "://" + options.host + ":" + options.port];

	if(options.hot)
		devClient.push("webpack/hot/dev-server");
	[].concat(wpOpt).forEach(function(wpOpt) {
		if(typeof wpOpt.entry === "object" && !Array.isArray(wpOpt.entry)) {
			Object.keys(wpOpt.entry).forEach(function(key) {
				wpOpt.entry[key] = devClient.concat(wpOpt.entry[key]);
			});
		} else {
			wpOpt.entry = devClient.concat(wpOpt.entry);
		}
	});
}

new Server(webpack(wpOpt), options).listen(options.port, options.host, function(err) {
	if(err) throw err;
	if(options.inline)
		console.log(protocol + "://" + options.host + ":" + options.port + "/");
	else
		console.log(protocol + "://" + options.host + ":" + options.port + "/webpack-dev-server/");
	console.log("webpack result is served from " + options.publicPath);
	if(typeof options.contentBase === "object")
		console.log("requests are proxied to " + options.contentBase.target);
	else
		console.log("content is served from " + options.contentBase);
	if(options.historyApiFallback)
		console.log("404s will fallback to %s", options.historyApiFallback.index || "/index.html");
});
<commit_msg>Added a flag for public ip to seed the inline frame.<commit_after>#!/usr/bin/env node

var path = require("path");
var url = require("url");
var fs = require("fs");

// Local version replaces global one
try {
	var localWebpackDevServer = require.resolve(path.join(process.cwd(), "node_modules", "webpack-dev-server", "bin", "webpack-dev-server.js"));
	if(__filename !== localWebpackDevServer) {
		return require(localWebpackDevServer);
	}
} catch(e) {}

var Server = require("../lib/Server");
var webpack = require("webpack");

var optimist = require("optimist")

	.usage("webpack-dev-server " + require("../package.json").version + "\n" +
			"Usage: http://webpack.github.io/docs/webpack-dev-server.html")

	.boolean("lazy").describe("lazy")

	.boolean("info").describe("info").default("info", true)

	.boolean("quiet").describe("quiet")

	.boolean("inline").describe("inline", "Inline the webpack-dev-server logic into the bundle.")

	.boolean("https").describe("https")

	.string("key").describe("key", "Path to a SSL key.")

	.string("cert").describe("cert", "Path to a SSL certificate.")

	.string("cacert").describe("cacert", "Path to a SSL CA certificate.")

	.string("content-base").describe("content-base", "A directory or URL to serve HTML content from.")

	.string("content-base-target").describe("content-base-target", "Proxy requests to this target.")

	.boolean("history-api-fallback").describe("history-api-fallback", "Fallback to /index.html for Single Page Applications.")

	.boolean("compress").describe("compress", "enable gzip compression")

	.describe("port", "The port").default("port", 8080)

	.describe("public", "The public hostname/ip address of the server")

	.describe("host", "The hostname/ip address the server will bind to").default("host", "localhost");

require("webpack/bin/config-optimist")(optimist);

var argv = optimist.argv;

var wpOpt = require("webpack/bin/convert-argv")(optimist, argv, { outputFilename: "/bundle.js" });
var firstWpOpt = Array.isArray(wpOpt) ? wpOpt[0] : wpOpt;

var options = wpOpt.devServer || firstWpOpt.devServer || {};

if(argv.host !== "localhost" || !options.host)
	options.host = argv.host;

if(!options.public)
	options.public = argv.public;

if(argv.port !== 8080 || !options.port)
	options.port = argv.port;

if(!options.publicPath) {
	options.publicPath = firstWpOpt.output && firstWpOpt.output.publicPath || "";
	if(!/^(https?:)?\/\//.test(options.publicPath) && options.publicPath[0] !== "/")
		options.publicPath = "/" + options.publicPath;
}

if(!options.outputPath)
	options.outputPath = "/";
if(!options.filename)
	options.filename = firstWpOpt.output && firstWpOpt.output.filename;
[].concat(wpOpt).forEach(function(wpOpt) {
	wpOpt.output.path = "/";
});

if(!options.watchOptions)
	options.watchOptions = firstWpOpt.watchOptions;
if(!options.watchDelay && !options.watchOptions) // TODO remove in next major version
	options.watchDelay = firstWpOpt.watchDelay;

if(!options.hot)
	options.hot = argv["hot"];

if(argv["content-base"]) {
	options.contentBase = argv["content-base"];
	if(/^[0-9]$/.test(options.contentBase))
		options.contentBase = +options.contentBase;
	else if(!/^(https?:)?\/\//.test(options.contentBase))
		options.contentBase = path.resolve(options.contentBase);
} else if(argv["content-base-target"]) {
	options.contentBase = { target: argv["content-base-target"] };
} else if(!options.contentBase) {
	options.contentBase = process.cwd();
}

if(!options.stats) {
	options.stats = {
		cached: false,
		cachedAssets: false
	};
}

if(typeof options.stats === "object" && typeof options.stats.colors === "undefined")
	options.stats.colors = require("supports-color");

if(argv["lazy"])
	options.lazy = true;

if(!argv["info"])
	options.noInfo = true;

if(argv["quiet"])
	options.quiet = true;

if(argv["https"])
	options.https = true;

if(argv["cert"])
	options.cert = fs.readFileSync(path.resolve(argv["cert"]));

if(argv["key"])
	options.key = fs.readFileSync(path.resolve(argv["key"]));

if(argv["cacert"])
	options.cacert = fs.readFileSync(path.resolve(argv["cacert"]));

if(argv["inline"])
	options.inline = true;

if(argv["history-api-fallback"])
	options.historyApiFallback = true;

if(argv["compress"])
	options.compress = true;

var protocol = options.https ? "https" : "http";

if(options.inline) {
	var devClient = [require.resolve("../client/") + "?" + protocol + "://" + (options.public || (options.host + ":" + options.port))];

	if(options.hot)
		devClient.push("webpack/hot/dev-server");
	[].concat(wpOpt).forEach(function(wpOpt) {
		if(typeof wpOpt.entry === "object" && !Array.isArray(wpOpt.entry)) {
			Object.keys(wpOpt.entry).forEach(function(key) {
				wpOpt.entry[key] = devClient.concat(wpOpt.entry[key]);
			});
		} else {
			wpOpt.entry = devClient.concat(wpOpt.entry);
		}
	});
}

new Server(webpack(wpOpt), options).listen(options.port, options.host, function(err) {
	if(err) throw err;
	if(options.inline)
		console.log(protocol + "://" + options.host + ":" + options.port + "/");
	else
		console.log(protocol + "://" + options.host + ":" + options.port + "/webpack-dev-server/");
	console.log("webpack result is served from " + options.publicPath);
	if(typeof options.contentBase === "object")
		console.log("requests are proxied to " + options.contentBase.target);
	else
		console.log("content is served from " + options.contentBase);
	if(options.historyApiFallback)
		console.log("404s will fallback to %s", options.historyApiFallback.index || "/index.html");
});
<|endoftext|>


<commit_before>const appInsightsKey = process.env.FORTIS_SERVICES_APPINSIGHTS_KEY;

let client;
let consoleLog = console.log;
let consoleError = console.error;
let consoleWarn = console.warn;

const TRACE_LEVEL_INFO = 1;
const TRACE_LEVEL_WARNING = 2;
const TRACE_LEVEL_ERROR = 3;

function setup() {
  if (appInsightsKey) {
    const appInsights = require('applicationinsights');
    appInsights.setup(appInsightsKey);
    appInsights.start();
    client = appInsights.getClient(appInsightsKey);
    console.log = trackTrace(TRACE_LEVEL_INFO, consoleLog);
    console.warn = trackTrace(TRACE_LEVEL_WARNING, consoleWarn);
    console.error = trackTrace(TRACE_LEVEL_ERROR, consoleError);
  }
}

function trackTrace(level, localLogger) {
  return (message) => {
    if (client) {
      client.trackTrace(message, level);
    }
    localLogger(message);
  };
}

function trackDependency(promiseFunc, dependencyName, callName) {
  if (!client) return promiseFunc;

  function dependencyTracker(...args) {
    return new Promise((resolve, reject) => {
      const start = new Date();
      promiseFunc(...args)
      .then(returnValue => {
        const duration = new Date() - start;
        const success = true;
        client.trackDependency(dependencyName, callName, duration, success);
        resolve(returnValue);
      })
      .catch(err => {
        const duration = new Date() - start;
        const success = false;
        client.trackDependency(dependencyName, callName, duration, success);
        reject(err);
      });
    });
  }

  return dependencyTracker;
}

function trackEvent(promiseFunc, eventName) {
  if (!client) return promiseFunc;

  function eventTracker(...args) {
    return new Promise((resolve, reject) => {
      const start = new Date();
      promiseFunc(...args)
      .then(returnValue => {
        const duration = new Date() - start;
        const success = true;
        client.trackEvent(eventName, { duration: duration, success: success });
        resolve(returnValue);
      })
      .catch(err => {
        const duration = new Date() - start;
        const success = false;
        client.trackEvent(eventName, { duration: duration, success: success });
        reject(err);
      });
    });
  }

  return eventTracker;
}

module.exports = {
  trackDependency: trackDependency,
  trackEvent: trackEvent,
  setup: setup
};
<commit_msg>Add extension point to add properties to event<commit_after>const appInsightsKey = process.env.FORTIS_SERVICES_APPINSIGHTS_KEY;

let client;
let consoleLog = console.log;
let consoleError = console.error;
let consoleWarn = console.warn;

const TRACE_LEVEL_INFO = 1;
const TRACE_LEVEL_WARNING = 2;
const TRACE_LEVEL_ERROR = 3;

function setup() {
  if (appInsightsKey) {
    const appInsights = require('applicationinsights');
    appInsights.setup(appInsightsKey);
    appInsights.start();
    client = appInsights.getClient(appInsightsKey);
    console.log = trackTrace(TRACE_LEVEL_INFO, consoleLog);
    console.warn = trackTrace(TRACE_LEVEL_WARNING, consoleWarn);
    console.error = trackTrace(TRACE_LEVEL_ERROR, consoleError);
  }
}

function trackTrace(level, localLogger) {
  return (message) => {
    if (client) {
      client.trackTrace(message, level);
    }
    localLogger(message);
  };
}

function trackDependency(promiseFunc, dependencyName, callName) {
  if (!client) return promiseFunc;

  function dependencyTracker(...args) {
    return new Promise((resolve, reject) => {
      const start = new Date();
      promiseFunc(...args)
      .then(returnValue => {
        const duration = new Date() - start;
        const success = true;
        client.trackDependency(dependencyName, callName, duration, success);
        resolve(returnValue);
      })
      .catch(err => {
        const duration = new Date() - start;
        const success = false;
        client.trackDependency(dependencyName, callName, duration, success);
        reject(err);
      });
    });
  }

  return dependencyTracker;
}

function trackEvent(promiseFunc, eventName, extraPropsFunc) {
  if (!client) return promiseFunc;
  extraPropsFunc = extraPropsFunc || ((returnValue, err) => ({})); // eslint-disable-line no-unused-vars

  function eventTracker(...args) {
    return new Promise((resolve, reject) => {
      const start = new Date();
      promiseFunc(...args)
      .then(returnValue => {
        const props = extraPropsFunc(returnValue, null);
        props.duration = new Date() - start;
        props.success = true;
        client.trackEvent(eventName, props);
        resolve(returnValue);
      })
      .catch(err => {
        const props = extraPropsFunc(null, err);
        props.duration = new Date() - start;
        props.success = false;
        client.trackEvent(eventName, props);
        reject(err);
      });
    });
  }

  return eventTracker;
}

module.exports = {
  trackDependency: trackDependency,
  trackEvent: trackEvent,
  setup: setup
};
<|endoftext|>


<commit_before>'use strict';
var React = require('react');
var _ = require('underscore');
var moment = require('moment');
var globals = require('./globals');
var fetched = require('./fetched');
var form = require('../libs/bootstrap/form');
var panel = require('../libs/bootstrap/panel');
var parseAndLogError = require('./mixins').parseAndLogError;
var RestMixin = require('./rest').RestMixin;

var Form = form.Form;
var FormMixin = form.FormMixin;
var Input = form.Input;
var Panel = panel.Panel;
var external_url_map = globals.external_url_map;

var Dashboard = React.createClass({
    mixins: [RestMixin],

    getInitialState: function() {
        return {
            userName: '',
            userStatus: '',
            lastLogin: '',
            recentHistory: [],
            gdmList: []
        };
    },

    setUserData: function(props) {
        // sets the display name and curator status
        this.setState({
            userName: props['first_name'],
            userStatus: props['groups'][0].charAt(0).toUpperCase() + props['groups'][0].substring(1),
            lastLogin: ''
        });
    },

    getData: function(userid) {
        // Retrieve all GDMs and other objects related to user via search
        this.getRestDatas(['/search/?type=gdm&limit=all', '/search/?limit=all&owner=' + userid], [function() {}, function() {}]).then(data => {
            // Search objects successfully retrieved; process results

            // Sort results by time. Ideally this would be done by the search function, but until
            // I can figure out how to set sorting for it, this will have to do
            var sortedGdmData = _(data[0]['@graph']).sortBy(function(item) {
                return item.dateTime;
            });
            var sortedHistoryData = _(data[1]['@graph']).sortBy(function(item) {
                return item.dateTime;
            });

            // GDM results; finds GDMs created by user, and also creates PMID-GDM mapping table
            // (stopgap measure until article -> GDM mapping ability is incorporated)
            var tempGdmList = [], tempRecentHistory = [];
            var pmidGdmMapping = {};
            for (var i = 0; i < sortedGdmData.length; i++) {
                var temp = sortedGdmData[i];
                var tempDisplayName = temp['gene']['symbol'] + "-" + temp['disease']['term'] + " (" + temp['modeInheritance'] + ")";
                if (temp['owner'] == userid) {
                    tempGdmList.push({
                        url: temp['uuid'],
                        displayName: tempDisplayName,
                        status: temp['status'],
                        dateTime: temp['dateTime']
                    });
                }
                if (temp['annotations'].length > 0) {
                    for (var j = 0; j < temp['annotations'].length; j++) {
                        pmidGdmMapping[temp['annotations'][j]['uuid']] = {uuid: temp['uuid'], displayName: tempDisplayName};
                    }
                }
            }
            // Recent History panel results; only displays annotation(article) addition and GDM
            // creation history for the time being.
            for (var i = 0; i < sortedHistoryData.length; i++) {
                var display = false;
                var temp = sortedHistoryData[i];
                var tempDisplayName = 'Item';
                var tempUrl = temp['@id'];
                var tempMessage = '';
                var tempDateTime = moment(temp['dateTime']).format( "YYYY MMM DD, h:mm a");
                switch (temp['@type'][0]) {
                    case 'annotation':
                        tempDisplayName = 'PMID: ' + temp['article']['pmid'] + ' to ' + pmidGdmMapping[temp['uuid']]['displayName'];
                        tempUrl = "/curation-central/?gdm=" + pmidGdmMapping[temp['uuid']]['uuid'] + "&pmid=" + temp['article']['pmid'];
                        tempMessage = "added " + tempDateTime;
                        display = true;
                        break;
                    case 'assessment':
                        tempDisplayName = temp['value'] + ' Assessment';
                        break;
                    case 'gdm':
                        tempDisplayName = temp['gene']['symbol'] + '-' + temp['disease']['term'] + " (" + temp['modeInheritance'] + ")";
                        tempUrl = "/curation-central/?gdm=" + temp['uuid'];
                        tempMessage = "created " + tempDateTime;
                        display = true;
                        break;
                    default:
                        tempDisplayName = 'Item';
                }
                if (display === true) {
                    tempRecentHistory.push({
                        url: tempUrl,
                        displayName: tempDisplayName,
                        message: tempMessage
                    });
                }
            }
            // Set states for cleaned results
            this.setState({
                recentHistory: tempRecentHistory,
                gdmList: tempGdmList
            });
        }).catch(parseAndLogError.bind(undefined, 'putRequest'));
    },

    componentDidMount: function() {
        if (this.props.session['user_properties'] !== undefined) {
            this.setUserData(this.props.session['user_properties']);
            this.getData(this.props.session['auth.userid']);
        }
    },

    componentWillReceiveProps: function(nextProps) {
        if (typeof nextProps.session['user_properties'] !== undefined && nextProps.session['user_properties'] != this.props.session['user_properties']) {
            this.setUserData(nextProps.session['user_properties']);
            this.getData(nextProps.session['auth.userid']);
        }
    },

    render: function() {
        return (

Welcome, {this.state.userName}!

Your curator status: {this.state.userStatus}

                        <Panel panelClassName="panel-dashboard">

Tools

View/create gene-disease record

View list of gene-disease records

                        </Panel>
                        <Panel panelClassName="panel-dashboard">

Recent History

                            {this.state.recentHistory.length > 0 ?

                                {this.state.recentHistory.map(function(item) {
                                    return
{item.displayName} ({item.message})
;
                                })}

                            : "You have no activity to display."}
                        </Panel>

                        <Panel panelClassName="panel-dashboard">

Your Gene-Disease Records

                            {this.state.gdmList.length > 0 ?

                                {this.state.gdmList.map(function(item) {
                                    return (

                                            {item.displayName}

                                            Status: {item.status}

                                            Creation Date: {moment(item.dateTime).format( "YYYY MMM DD, h:mm a")}

                                    );
                                })}

                            : "You have not created any Gene-Disease-Mode of Inheritance entries."}
                        </Panel>

        );
    }
});

globals.curator_page.register(Dashboard, 'curator_page', 'dashboard');
<commit_msg>reverse sorting of results; limit history to 10 entries<commit_after>'use strict';
var React = require('react');
var _ = require('underscore');
var moment = require('moment');
var globals = require('./globals');
var fetched = require('./fetched');
var form = require('../libs/bootstrap/form');
var panel = require('../libs/bootstrap/panel');
var parseAndLogError = require('./mixins').parseAndLogError;
var RestMixin = require('./rest').RestMixin;

var Form = form.Form;
var FormMixin = form.FormMixin;
var Input = form.Input;
var Panel = panel.Panel;
var external_url_map = globals.external_url_map;

var Dashboard = React.createClass({
    mixins: [RestMixin],

    getInitialState: function() {
        return {
            userName: '',
            userStatus: '',
            lastLogin: '',
            recentHistory: [],
            gdmList: []
        };
    },

    setUserData: function(props) {
        // sets the display name and curator status
        this.setState({
            userName: props['first_name'],
            userStatus: props['groups'][0].charAt(0).toUpperCase() + props['groups'][0].substring(1),
            lastLogin: ''
        });
    },

    getData: function(userid) {
        // Retrieve all GDMs and other objects related to user via search
        this.getRestDatas(['/search/?type=gdm&limit=all', '/search/?limit=all&owner=' + userid], [function() {}, function() {}]).then(data => {
            // Search objects successfully retrieved; process results

            // Sort results by time. Ideally this would be done by the search function, but until
            // I can figure out how to set sorting for it, this will have to do
            var sortedGdmData = _(data[0]['@graph']).sortBy(function(item) {
                return item.dateTime;
            }).reverse();
            var sortedHistoryData = _(data[1]['@graph']).sortBy(function(item) {
                return item.dateTime;
            }).reverse().slice(0,10);

            // GDM results; finds GDMs created by user, and also creates PMID-GDM mapping table
            // (stopgap measure until article -> GDM mapping ability is incorporated)
            var tempGdmList = [], tempRecentHistory = [];
            var pmidGdmMapping = {};
            for (var i = 0; i < sortedGdmData.length; i++) {
                var temp = sortedGdmData[i];
                var tempDisplayName = temp['gene']['symbol'] + "-" + temp['disease']['term'] + " (" + temp['modeInheritance'] + ")";
                if (temp['owner'] == userid) {
                    tempGdmList.push({
                        url: temp['uuid'],
                        displayName: tempDisplayName,
                        status: temp['status'],
                        dateTime: temp['dateTime']
                    });
                }
                if (temp['annotations'].length > 0) {
                    for (var j = 0; j < temp['annotations'].length; j++) {
                        pmidGdmMapping[temp['annotations'][j]['uuid']] = {uuid: temp['uuid'], displayName: tempDisplayName};
                    }
                }
            }
            // Recent History panel results; only displays annotation(article) addition and GDM
            // creation history for the time being.
            for (var i = 0; i < sortedHistoryData.length; i++) {
                var display = false;
                var temp = sortedHistoryData[i];
                var tempDisplayName = 'Item';
                var tempUrl = temp['@id'];
                var tempMessage = '';
                var tempDateTime = moment(temp['dateTime']).format( "YYYY MMM DD, h:mm a");
                switch (temp['@type'][0]) {
                    case 'annotation':
                        tempDisplayName = 'PMID: ' + temp['article']['pmid'] + ' associated with ' + pmidGdmMapping[temp['uuid']]['displayName'];
                        tempUrl = "/curation-central/?gdm=" + pmidGdmMapping[temp['uuid']]['uuid'] + "&pmid=" + temp['article']['pmid'];
                        tempMessage = "added " + tempDateTime;
                        display = true;
                        break;
                    case 'assessment':
                        tempDisplayName = temp['value'] + ' Assessment';
                        break;
                    case 'gdm':
                        tempDisplayName = temp['gene']['symbol'] + '-' + temp['disease']['term'] + " (" + temp['modeInheritance'] + ")";
                        tempUrl = "/curation-central/?gdm=" + temp['uuid'];
                        tempMessage = "created " + tempDateTime;
                        display = true;
                        break;
                    default:
                        tempDisplayName = 'Item';
                }
                if (display === true) {
                    tempRecentHistory.push({
                        url: tempUrl,
                        displayName: tempDisplayName,
                        message: tempMessage
                    });
                }
            }
            // Set states for cleaned results
            this.setState({
                recentHistory: tempRecentHistory,
                gdmList: tempGdmList
            });
        }).catch(parseAndLogError.bind(undefined, 'putRequest'));
    },

    componentDidMount: function() {
        if (this.props.session['user_properties'] !== undefined) {
            this.setUserData(this.props.session['user_properties']);
            this.getData(this.props.session['auth.userid']);
        }
    },

    componentWillReceiveProps: function(nextProps) {
        if (typeof nextProps.session['user_properties'] !== undefined && nextProps.session['user_properties'] != this.props.session['user_properties']) {
            this.setUserData(nextProps.session['user_properties']);
            this.getData(nextProps.session['auth.userid']);
        }
    },

    render: function() {
        return (

Welcome, {this.state.userName}!

Your curator status: {this.state.userStatus}

                        <Panel panelClassName="panel-dashboard">

Tools

View/create gene-disease record

View list of gene-disease records

                        </Panel>
                        <Panel panelClassName="panel-dashboard">

Recent History

                            {this.state.recentHistory.length > 0 ?

                                {this.state.recentHistory.map(function(item) {
                                    return
{item.displayName} ({item.message})
;
                                })}

                            : "You have no activity to display."}
                        </Panel>

                        <Panel panelClassName="panel-dashboard">

Your Gene-Disease Records

                            {this.state.gdmList.length > 0 ?

                                {this.state.gdmList.map(function(item) {
                                    return (

                                            {item.displayName}

                                            Status: {item.status}

                                            Creation Date: {moment(item.dateTime).format( "YYYY MMM DD, h:mm a")}

                                    );
                                })}

                            : "You have not created any Gene-Disease-Mode of Inheritance entries."}
                        </Panel>

        );
    }
});

globals.curator_page.register(Dashboard, 'curator_page', 'dashboard');
<|endoftext|>


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

'use strict';

function main(
  projectId = 'YOUR_PROJECT_ID',
  location = 'us-central1',
  modelId = 'model-id',
  text = 'text to translate'
) {
  // [START translate_v3_text_with_model]
  /**
   * TODO(developer): Uncomment these variables before running the sample.
   */
  // const projectId = 'YOUR_PROJECT_ID';
  // const location = 'us-central1';
  // const modelId = 'YOUR_MODEL_ID';
  // const text = 'text to translate';

  // Imports the Google Cloud Translation library
  const {TranslationServiceClient} = require('@google-cloud/translate');

  // Instantiates a client
  const translationClient = new TranslationServiceClient();
  async function translateTextWithModel() {
    // Construct request
    const request = {
      parent: `projects/${projectId}/locations/${location}`,
      contents: [text],
      mimeType: 'text/plain', // mime types: text/plain, text/html
      sourceLanguageCode: 'en',
      targetLanguageCode: 'ja',
      model: `projects/${projectId}/locations/${location}/models/${modelId}`,
    };

    // Run request
    const [response] = await translationClient.translateText(request);

    for (const translation of response.translations) {
      console.log(`Translated Content: ${translation.translatedText}`);
    }
  }

  translateTextWithModel();
  // [END translate_v3_text_with_model]
}

main(...process.argv.slice(2));
<commit_msg>fix: region tag (#367)<commit_after>// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

'use strict';

function main(
  projectId = 'YOUR_PROJECT_ID',
  location = 'us-central1',
  modelId = 'model-id',
  text = 'text to translate'
) {
  // [START translate_v3_translate_text_with_model]
  /**
   * TODO(developer): Uncomment these variables before running the sample.
   */
  // const projectId = 'YOUR_PROJECT_ID';
  // const location = 'us-central1';
  // const modelId = 'YOUR_MODEL_ID';
  // const text = 'text to translate';

  // Imports the Google Cloud Translation library
  const {TranslationServiceClient} = require('@google-cloud/translate');

  // Instantiates a client
  const translationClient = new TranslationServiceClient();
  async function translateTextWithModel() {
    // Construct request
    const request = {
      parent: `projects/${projectId}/locations/${location}`,
      contents: [text],
      mimeType: 'text/plain', // mime types: text/plain, text/html
      sourceLanguageCode: 'en',
      targetLanguageCode: 'ja',
      model: `projects/${projectId}/locations/${location}/models/${modelId}`,
    };

    // Run request
    const [response] = await translationClient.translateText(request);

    for (const translation of response.translations) {
      console.log(`Translated Content: ${translation.translatedText}`);
    }
  }

  translateTextWithModel();
  // [END translate_v3_translate_text_with_model]
}

main(...process.argv.slice(2));
<|endoftext|>