<commit_before>'use strict';

angular.module('myApp.bar', ['ngRoute'])
.service('barService',['$timeout', function($timeout) {
		   var currentID = 0;
		   var self = this;
		   var defaultBarThickness = 20;

		   //this function simulates a 2 second delay from getting information from the server
		   //this function should be called when no data is given to the bar chart, so as to
		   //visualize configuration details
		   //returns a promise
		   this._getDefaultBarData = function () {
			   return $timeout(function() {
				   return [
						{name: "Ford",     value: 15},
						{name: "Jarrah",   value: 16},
						{name: "Locke",    value:  4},
						{name: "Reyes",    value:  8},
						{name: "Shephard", value: 23},
						{name: "Kwon",     value: 49}
	                ];
				   }, 2000);	//2000 ms = 2 seconds
		   };

		   this._initBarScale = function (id, attrs) {
		   //this function should generate the scale function for the bar chart
		   //depending on attrs. maybe data as well?
			   if (1) {
				   return function(d) { return d.value * 10 + "px"; };
			   }
			   else
			   {
				   return 0;
			   }
		   };

		   this._calculateDataRanges = function (data, id) {
		   //this function should calculate the mins and maxes of the dataset. Useful for things like scaling
			   var sortedData = data.slice(0);	//clones array
			   sortedData.sort(function(a, b){return a.value-b.value});
			   console.log('calcing data ranges');
			   console.log(sortedData);
			   self[id].max = sortedData[sortedData.length - 1].value;
			   self[id].min = sortedData[0].value;
			   return {
				   max: sortedData[sortedData.length - 1].value,
				   min: sortedData[0].value,
			   };
		   };

		   //this function should get a new ID, and also initialize heatmapConfig for the current ID
		   //it also initializes the configuration details based upon the attributes fed into the function.
		   this.initHeatmap = function (attrs) {
			   var id = currentID++;
		       self[id] = {};
		       if (0) { //if statement should parse attrs object, and determine where to grab data from
		    	   var dataURL = attrs.dataSource;
		    	   dataURL.getData();
		       }
		       else { //if the data location is undefined, or not mentioned
		    	   self[id].barData = self._getDefaultBarData();
		    	   self[id].barData.then(
		    			   function (data) {
		    				   var range = self._calculateDataRanges(data, id);
		    			   },
		    			   function (data) {alert('oops2');}
    			   );
		       }
		       self[id].thickness = attrs.thickness ? attr.thickness : defaultBarThickness;

		       return id;
		   };

		   //discrete getters and setters
		   //require id in order to correctly serve/reference the controller/chart instance
		   this.getBarData = function (id) {
		       return self[id].barData;
		   };
		   this.setBarData = function (id, data) {
		   //this may have the ability to alter data on server-side...
			   //currently jsut alters the $scope data.
			   self[id].barData = data;
			   return self[id].barData;
		   };
		   this.getBarWidth = function (id) {
			   return self[id].barScale;
		   };
		   this.getMax = function (id) {return self[id].max};
		   this.getMin = function (id) {return self[id].min};
		   this.getThickness = function(id) {return self[id].thickness};
}])

.controller('barCtrl', ['$scope', 'barService',
                    function($scope, barService) {
	$scope.barID = barService.initHeatmap({});
	var id = $scope.barID;
	$scope.loading = "Now Loading...";

	barService.getBarData(id).then( function(data) {
		$scope.loading = '';
		$scope.barData = data;
		console.log(barService[id]);
		var width = barService.getMax(id)*10,
		    barHeight = barService.getThickness(id);

		var x = d3.scale.linear()
		    .domain([0, barService.getMax(id)])
		    .range([0, width]);

		var chart = d3.select(".chart")
		    .attr("width", width)
		    .attr("height", barHeight * data.length);

		var bar = chart.selectAll("g")
		    .data(data)
		  .enter().append("g")
		    .attr("transform", function(d, i) { return "translate(0," + i * barHeight + ")"; });

		 bar.append("rect")
	      .attr("width", function(d) { return x(d.value); })
	      .attr("height", barHeight - 1);

		bar.append("text")
		    .attr("x", function(d) { return x(d.value) - 3; })
		    .attr("y", barHeight / 2)
		    .attr("dy", ".35em")
		    .text(function(d) { return d.value; });

	}, function() { alert('oops');});

}]);<commit_msg>Bar chart is rotatable with attribute.<commit_after>'use strict';

angular.module('myApp.bar', ['ngRoute'])
.service('barService',['$timeout', function($timeout) {
		   var currentID = 0;
		   var self = this;
		   var defaultChartParallel = 400;
		   var defaultChartPerpendicular = 600;

		   //this function simulates a 2 second delay from getting information from the server
		   //this function should be called when no data is given to the bar chart, so as to
		   //visualize configuration details
		   //returns a promise
		   this._getDefaultBarData = function () {
			   return $timeout(function() {
				   return [
						{name: "Ford",     value: 15},
						{name: "Jarrah",   value: 16},
						{name: "Locke",    value:  4},
						{name: "Reyes",    value:  8},
						{name: "Shephard", value: 23},
						{name: "Kwon",     value: 49}
	                ];
				   }, 2000);	//2000 ms = 2 seconds
		   };

		   this._initBarScale = function (id, attrs) {
		   //this function should generate the scale function for the bar chart
		   //depending on attrs. maybe data as well?
			   if (1) {
				   return function(d) { return d.value * 10 + "px"; };
			   }
			   else
			   {
				   return 0;
			   }
		   };

		   this._calculateDataRanges = function (data, id) {
		   //this function should calculate the mins and maxes of the dataset. Useful for things like scaling
			   var sortedData = data.slice(0);	//clones array
			   sortedData.sort(function(a, b){return a.value-b.value});
			   console.log('calcing data ranges');
			   console.log(sortedData);
			   self[id].max = sortedData[sortedData.length - 1].value;
			   self[id].min = sortedData[0].value;
			   return {
				   max: sortedData[sortedData.length - 1].value,
				   min: sortedData[0].value,
			   };
		   };

		   //this function should get a new ID, and also initialize heatmapConfig for the current ID
		   //it also initializes the configuration details based upon the attributes fed into the function.
		   this.initHeatmap = function (attrs) {
			   var id = currentID++;
		       self[id] = {};
		       if (0) { //if statement should parse attrs object, and determine where to grab data from
		    	   var dataURL = attrs.dataSource;
		    	   dataURL.getData();
		       }
		       else { //if the data location is undefined, or not mentioned
		    	   self[id].barData = self._getDefaultBarData();
		    	   self[id].barData.then(
		    			   function (data) {
		    				   var range = self._calculateDataRanges(data, id);
		    			   },
		    			   function (error) {alert('oops2');}
    			   );
		       }
		       if(attrs.rotate === 'y') {
		    	   self[id].height = attrs.height ? attr.height : defaultChartPerpendicular;
		    	   self[id].width = attrs.width ? attr.width : defaultChartParallel;
		       }
		       else {
		    	   attrs.rotate = 'x';
		    	   self[id].height = attrs.height ? attr.height : defaultChartParallel;
		    	   self[id].width = attrs.width ? attr.width : defaultChartPerpendicular;
		       }

		       return id;
		   };

		   //discrete getters and setters
		   //require id in order to correctly serve/reference the controller/chart instance
		   this.getBarData = function (id) {
		       return self[id].barData;
		   };
		   this.setBarData = function (id, data) {
		   //this may have the ability to alter data on server-side...
			   //currently jsut alters the $scope data.
			   self[id].barData = data;
			   return self[id].barData;
		   };
		   this.getBarWidth = function (id) {
			   return self[id].barScale;
		   };
		   this.getMax = function (id) {return self[id].max};
		   this.getMin = function (id) {return self[id].min};
		   this.getHeight = function(id) {return self[id].height};
		   this.getWidth = function(id) {return self[id].width}
}])

.controller('barCtrl', ['$scope', 'barService',
                    function($scope, barService) {
	var attrs = {'rotate': 'y'};
	$scope.barID = barService.initHeatmap(attrs);
	var id = $scope.barID;
	$scope.loading = "Now Loading...";

	barService.getBarData(id).then( function(data) {
		$scope.loading = '';
		$scope.barData = data;
		console.log(barService[id]);
		if(attrs.rotate === 'x') {
			var width = barService.getWidth(id),
			    height = barService.getHeight(id),
			    dataLength = data.length,
			    barThickness = height/dataLength;

			var x = d3.scale.linear()
			    .domain([0, barService.getMax(id)])
			    .range([0, width]);

			var chart = d3.select(".chart")
			    .attr("width", width)
			    .attr("height", height);

			var bar = chart.selectAll("g")
			    .data(data)
			  .enter().append("g")
			    .attr("transform", function(d, i) { return "translate(0," + i * barThickness + ")"; });

			 bar.append("rect")
		      .attr("width", function(d) { return x(d.value); })
		      .attr("height", barThickness - 1);

			bar.append("text")
			    .attr("x", function(d) { return x(d.value) - 3; })
			    .attr("y", barThickness / 2)
			    .attr("dy", ".35em")
			    .text(function(d) { return d.value; });
		}
		else {
			var width = barService.getWidth(id),
		    height = barService.getHeight(id),
		    dataLength = data.length,
		    barThickness = width/dataLength;

			var y = d3.scale.linear()
			    .range([height, 0]);

			var chart = d3.select(".chart")
			    .attr("width", width)
			    .attr("height", height);

		  y.domain([0, d3.max(data, function(d) { return d.value; })]);

		  var bar = chart.selectAll("g")
		      .data(data)
		    .enter().append("g")
		      .attr("transform", function(d, i) { return "translate(" + i * barThickness + ",0)"; });

		  bar.append("rect")
		      .attr("y", function(d) { return y(d.value); })
		      .attr("height", function(d) { return height - y(d.value); })
		      .attr("width", barThickness - 1);

		  bar.append("text")
		      .attr("x", barThickness / 2)
		      .attr("y", function(d) { return y(d.value) + 3; })
		      .attr("dy", ".75em")
		      .text(function(d) { return d.value; });
		}
	}, function(error) { alert('oops');});

}]);<|endoftext|>


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

/**
 * @fileoverview Utilities for element styles.
 * These methods are not specific to Blockly, and could be factored out into
 * a JavaScript framework such as Closure.
 * @author samelh@google.com (Sam El-Husseini)
 */
'use strict';

/**
 * @name Blockly.utils.style
 * @namespace
 */
goog.provide('Blockly.utils.style');

goog.require('Blockly.utils.Coordinate');
goog.require('Blockly.utils.Size');

/**
 * Gets the height and width of an element.
 * Similar to Closure's goog.style.getSize
 * @param {Element} element Element to get size of.
 * @return {!Blockly.utils.Size} Object with width/height properties.
 */
Blockly.utils.style.getSize = function(element) {
  if (Blockly.utils.style.getStyle_(element, 'display') != 'none') {
    return Blockly.utils.style.getSizeWithDisplay_(element);
  }

  // Evaluate size with a temporary element.
  var style = element.style;
  var originalDisplay = style.display;
  var originalVisibility = style.visibility;
  var originalPosition = style.position;

  style.visibility = 'hidden';
  style.position = 'absolute';
  style.display = 'inline';

  var offsetWidth = /** @type {!HTMLElement} */ (element).offsetWidth;
  var offsetHeight = /** @type {!HTMLElement} */ (element).offsetHeight;

  style.display = originalDisplay;
  style.position = originalPosition;
  style.visibility = originalVisibility;

  return new Blockly.utils.Size(offsetWidth, offsetHeight);
};

/**
 * Gets the height and width of an element when the display is not none.
 * @param {Element} element Element to get size of.
 * @return {!goog.math.Size} Object with width/height properties.
 * @private
 */
Blockly.utils.style.getSizeWithDisplay_ = function(element) {
  var offsetWidth = /** @type {!HTMLElement} */ (element).offsetWidth;
  var offsetHeight = /** @type {!HTMLElement} */ (element).offsetHeight;
  return new Blockly.utils.Size(offsetWidth, offsetHeight);
};

/**
 * Cross-browser pseudo get computed style. It returns the computed style where
 * available. If not available it tries the cascaded style value (IE
 * currentStyle) and in worst case the inline style value.  It shouldn't be
 * called directly, see http://wiki/Main/ComputedStyleVsCascadedStyle for
 * discussion.
 *
 * Copied from Closure's goog.style.getStyle_
 *
 * @param {Element} element Element to get style of.
 * @param {string} style Property to get (must be camelCase, not css-style.).
 * @return {string} Style value.
 * @private
 */
Blockly.utils.style.getStyle_ = function(element, style) {
  return Blockly.utils.style.getComputedStyle(element, style) ||
      Blockly.utils.style.getCascadedStyle(element, style) ||
      (element.style && element.style[style]);
};

/**
 * Retrieves a computed style value of a node. It returns empty string if the
 * value cannot be computed (which will be the case in Internet Explorer) or
 * "none" if the property requested is an SVG one and it has not been
 * explicitly set (firefox and webkit).
 *
 * Copied from Closure's goog.style.getComputedStyle
 *
 * @param {Element} element Element to get style of.
 * @param {string} property Property to get (camel-case).
 * @return {string} Style value.
 */
Blockly.utils.style.getComputedStyle = function(element, property) {
  if (document.defaultView && document.defaultView.getComputedStyle) {
    var styles = document.defaultView.getComputedStyle(element, null);
    if (styles) {
      // element.style[..] is undefined for browser specific styles
      // as 'filter'.
      return styles[property] || styles.getPropertyValue(property) || '';
    }
  }
  return '';
};

/**
 * Gets the cascaded style value of a node, or null if the value cannot be
 * computed (only Internet Explorer can do this).
 *
 * Copied from Closure's goog.style.getCascadedStyle
 *
 * @param {Element} element Element to get style of.
 * @param {string} style Property to get (camel-case).
 * @return {string} Style value.
 */
Blockly.utils.style.getCascadedStyle = function(element, style) {
  return /** @type {string} */ (
      element.currentStyle ? element.currentStyle[style] : null);
};

/**
 * Returns a Coordinate object relative to the top-left of the HTML document.
 * Similar to Closure's goog.style.getPageOffset
 * @param {Element} el Element to get the page offset for.
 * @return {!Blockly.utils.Coordinate} The page offset.
 */
Blockly.utils.style.getPageOffset = function(el) {
  var pos = new Blockly.utils.Coordinate(0, 0);
  var box = el.getBoundingClientRect();
  var documentElement = document.documentElement;
  // Must add the scroll coordinates in to get the absolute page offset
  // of element since getBoundingClientRect returns relative coordinates to
  // the viewport.
  var scrollCoord = new Blockly.utils.Coordinate(
      window.pageXOffset || documentElement.scrollLeft,
      window.pageYOffset || documentElement.scrollTop);
  pos.x = box.left + scrollCoord.x;
  pos.y = box.top + scrollCoord.y;

  return pos;
};

/**
 * Calculates the viewport coordinates relative to the document.
 * Similar to Closure's goog.style.getViewportPageOffset
 * @return {!Blockly.utils.Coordinate} The page offset of the viewport.
 */
Blockly.utils.style.getViewportPageOffset = function() {
  var body = document.body;
  var documentElement = document.documentElement;
  var scrollLeft = body.scrollLeft || documentElement.scrollLeft;
  var scrollTop = body.scrollTop || documentElement.scrollTop;
  return new Blockly.utils.Coordinate(scrollLeft, scrollTop);
};

/**
 * Shows or hides an element from the page. Hiding the element is done by
 * setting the display property to "none", removing the element from the
 * rendering hierarchy so it takes up no space. To show the element, the default
 * inherited display property is restored (defined either in stylesheets or by
 * the browser's default style rules).
 * Copied from Closure's goog.style.getViewportPageOffset
 *
 * @param {Element} el Element to show or hide.
 * @param {*} isShown True to render the element in its default style,
 *     false to disable rendering the element.
 */
Blockly.utils.style.setElementShown = function(el, isShown) {
  el.style.display = isShown ? '' : 'none';
};

/**
 * Returns true if the element is using right to left (rtl) direction.
 * Copied from Closure's goog.style.isRightToLeft
 *
 * @param {Element} el  The element to test.
 * @return {boolean} True for right to left, false for left to right.
 */
Blockly.utils.style.isRightToLeft = function(el) {
  return 'rtl' == Blockly.utils.style.getStyle_(el, 'direction');
};

/**
 * Gets the computed border widths (on all sides) in pixels
 * Copied from Closure's goog.style.getBorderBox
 * @param {Element} element  The element to get the border widths for.
 * @return {!Object} The computed border widths.
 */
Blockly.utils.style.getBorderBox = function(element) {
  var left = Blockly.utils.style.getComputedStyle(element, 'borderLeftWidth');
  var right = Blockly.utils.style.getComputedStyle(element, 'borderRightWidth');
  var top = Blockly.utils.style.getComputedStyle(element, 'borderTopWidth');
  var bottom = Blockly.utils.style.getComputedStyle(element, 'borderBottomWidth');

  return {
    top: parseFloat(top),
    right: parseFloat(right),
    bottom: parseFloat(bottom),
    left: parseFloat(left)
  };
};

/**
 * Changes the scroll position of `container` with the minimum amount so
 * that the content and the borders of the given `element` become visible.
 * If the element is bigger than the container, its top left corner will be
 * aligned as close to the container's top left corner as possible.
 * Copied from Closure's goog.style.scrollIntoContainerView
 *
 * @param {Element} element The element to make visible.
 * @param {Element} container The container to scroll. If not set, then the
 *     document scroll element will be used.
 * @param {boolean=} opt_center Whether to center the element in the container.
 *     Defaults to false.
 */
Blockly.utils.style.scrollIntoContainerView = function(
    element, container, opt_center) {
  var offset =
      Blockly.utils.style.getContainerOffsetToScrollInto(element,
          container, opt_center);
  container.scrollLeft = offset.x;
  container.scrollTop = offset.y;
};

/**
 * Calculate the scroll position of `container` with the minimum amount so
 * that the content and the borders of the given `element` become visible.
 * If the element is bigger than the container, its top left corner will be
 * aligned as close to the container's top left corner as possible.
 * Copied from Closure's goog.style.getContainerOffsetToScrollInto
 *
 * @param {Element} element The element to make visible.
 * @param {Element} container The container to scroll. If not set, then the
 *     document scroll element will be used.
 * @param {boolean=} opt_center Whether to center the element in the container.
 *     Defaults to false.
 * @return {!Blockly.utils.Coordinate} The new scroll position of the container,
 *     in form of goog.math.Coordinate(scrollLeft, scrollTop).
 */
Blockly.utils.style.getContainerOffsetToScrollInto = function(
    element, container, opt_center) {
  // Absolute position of the element's border's top left corner.
  var elementPos = Blockly.utils.style.getPageOffset(element);
  // Absolute position of the container's border's top left corner.
  var containerPos = Blockly.utils.style.getPageOffset(container);
  var containerBorder = Blockly.utils.style.getBorderBox(container);
  // Relative pos. of the element's border box to the container's content box.
  var relX = elementPos.x - containerPos.x - containerBorder.left;
  var relY = elementPos.y - containerPos.y - containerBorder.top;
  // How much the element can move in the container, i.e. the difference between
  // the element's bottom-right-most and top-left-most position where it's
  // fully visible.
  var elementSize = Blockly.utils.style.getSizeWithDisplay_(element);
  var spaceX = container.clientWidth - elementSize.width;
  var spaceY = container.clientHeight - elementSize.height;
  var scrollLeft = container.scrollLeft;
  var scrollTop = container.scrollTop;
  if (opt_center) {
    // All browsers round non-integer scroll positions down.
    scrollLeft += relX - spaceX / 2;
    scrollTop += relY - spaceY / 2;
  } else {
    // This formula was designed to give the correct scroll values in the
    // following cases:
    // - element is higher than container (spaceY < 0) => scroll down by relY
    // - element is not higher that container (spaceY >= 0):
    //   - it is above container (relY < 0) => scroll up by abs(relY)
    //   - it is below container (relY > spaceY) => scroll down by relY - spaceY
    //   - it is in the container => don't scroll
    scrollLeft += Math.min(relX, Math.max(relX - spaceX, 0));
    scrollTop += Math.min(relY, Math.max(relY - spaceY, 0));
  }
  return new Blockly.utils.Coordinate(scrollLeft, scrollTop);
};
<commit_msg>Revert "Add extra style methods used by closure components"<commit_after>/**
 * @license
 * Visual Blocks Editor
 *
 * Copyright 2019 Google Inc.
 * https://developers.google.com/blockly/
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * @fileoverview Utilities for element styles.
 * These methods are not specific to Blockly, and could be factored out into
 * a JavaScript framework such as Closure.
 * @author samelh@google.com (Sam El-Husseini)
 */
'use strict';

/**
 * @name Blockly.utils.style
 * @namespace
 */
goog.provide('Blockly.utils.style');

goog.require('Blockly.utils.Coordinate');
goog.require('Blockly.utils.Size');

/**
 * Gets the height and width of an element.
 * Similar to Closure's goog.style.getSize.
 * @param {Element} element Element to get size of.
 * @return {!Blockly.utils.Size} Object with width/height properties.
 */
Blockly.utils.style.getSize = function(element) {
  if (Blockly.utils.style.getStyle_(element, 'display') != 'none') {
    var offsetWidth = /** @type {!HTMLElement} */ (element).offsetWidth;
    var offsetHeight = /** @type {!HTMLElement} */ (element).offsetHeight;
    return new Blockly.utils.Size(offsetWidth, offsetHeight);
  }

  // Evaluate size with a temporary element.
  var style = element.style;
  var originalDisplay = style.display;
  var originalVisibility = style.visibility;
  var originalPosition = style.position;

  style.visibility = 'hidden';
  style.position = 'absolute';
  style.display = 'inline';

  var offsetWidth = /** @type {!HTMLElement} */ (element).offsetWidth;
  var offsetHeight = /** @type {!HTMLElement} */ (element).offsetHeight;

  style.display = originalDisplay;
  style.position = originalPosition;
  style.visibility = originalVisibility;

  return new Blockly.utils.Size(offsetWidth, offsetHeight);
};

/**
 * Cross-browser pseudo get computed style. It returns the computed style where
 * available. If not available it tries the cascaded style value (IE
 * currentStyle) and in worst case the inline style value.  It shouldn't be
 * called directly, see http://wiki/Main/ComputedStyleVsCascadedStyle for
 * discussion.
 *
 * Copied from Closure's goog.ui.style
 *
 * @param {Element} element Element to get style of.
 * @param {string} style Property to get (must be camelCase, not css-style.).
 * @return {string} Style value.
 * @private
 */
Blockly.utils.style.getStyle_ = function(element, style) {
  return Blockly.utils.style.getComputedStyle(element, style) ||
      Blockly.utils.style.getCascadedStyle(element, style) ||
      (element.style && element.style[style]);
};

/**
 * Retrieves a computed style value of a node. It returns empty string if the
 * value cannot be computed (which will be the case in Internet Explorer) or
 * "none" if the property requested is an SVG one and it has not been
 * explicitly set (firefox and webkit).
 *
 * Copied from Closure's goog.ui.style
 *
 * @param {Element} element Element to get style of.
 * @param {string} property Property to get (camel-case).
 * @return {string} Style value.
 */
Blockly.utils.style.getComputedStyle = function(element, property) {
  if (document.defaultView && document.defaultView.getComputedStyle) {
    var styles = document.defaultView.getComputedStyle(element, null);
    if (styles) {
      // element.style[..] is undefined for browser specific styles
      // as 'filter'.
      return styles[property] || styles.getPropertyValue(property) || '';
    }
  }

  return '';
};

/**
 * Gets the cascaded style value of a node, or null if the value cannot be
 * computed (only Internet Explorer can do this).
 *
 * Copied from Closure's goog.ui.style
 *
 * @param {Element} element Element to get style of.
 * @param {string} style Property to get (camel-case).
 * @return {string} Style value.
 */
Blockly.utils.style.getCascadedStyle = function(element, style) {
  return /** @type {string} */ (
      element.currentStyle ? element.currentStyle[style] : null);
};

/**
 * Returns a Coordinate object relative to the top-left of the HTML document.
 * Similar to Closure's goog.style.getPageOffset.
 * @param {Element} el Element to get the page offset for.
 * @return {!Blockly.utils.Coordinate} The page offset.
 */
Blockly.utils.style.getPageOffset = function(el) {
  var pos = new Blockly.utils.Coordinate(0, 0);
  var box = el.getBoundingClientRect();
  var documentElement = document.documentElement;
  // Must add the scroll coordinates in to get the absolute page offset
  // of element since getBoundingClientRect returns relative coordinates to
  // the viewport.
  var scrollCoord = new Blockly.utils.Coordinate(
      window.pageXOffset || documentElement.scrollLeft,
      window.pageYOffset || documentElement.scrollTop);
  pos.x = box.left + scrollCoord.x;
  pos.y = box.top + scrollCoord.y;

  return pos;
};

/**
 * Calculates the viewport coordinates relative to the document.
 * Similar to Closure's goog.style.getViewportPageOffset.
 * @return {!Blockly.utils.Coordinate} The page offset of the viewport.
 */
Blockly.utils.style.getViewportPageOffset = function() {
  var body = document.body;
  var documentElement = document.documentElement;
  var scrollLeft = body.scrollLeft || documentElement.scrollLeft;
  var scrollTop = body.scrollTop || documentElement.scrollTop;
  return new Blockly.utils.Coordinate(scrollLeft, scrollTop);
};
<|endoftext|>


<commit_before>'use strict';

module.exports = {
  up: function (queryInterface, Sequelize) {
    return queryInterface.changeColumn('Groups', 'mission', { type: DataTypes.STRING(125) })
  },

  down: function (queryInterface, Sequelize) {
    return queryInterface.changeColumn('Groups', 'mission', { type: DataTypes.STRING(100) })
  },
};
<commit_msg>Update 20161205175944-increase-group-mission-length-migration.js<commit_after>'use strict';

module.exports = {
  up: function (queryInterface, Sequelize) {
    return queryInterface.changeColumn('Groups', 'mission', { type: DataTypes.STRING(128) })
  },

  down: function (queryInterface, Sequelize) {
    return queryInterface.changeColumn('Groups', 'mission', { type: DataTypes.STRING(100) })
  },
};
<|endoftext|>


<commit_before>// Example of change method with a failure closure
// This structure can be used in any methods of Pressure
// The failure block will return with an "error" and message showing why the device doesn't support 3D Touch and Force Touch
var block = {
  start: function(event){
    console.log('start', event);
  },

  change: function(force, event){
    this.style.width = $.pressureMap(force, 0, 1, 200, 300) + 'px';
    this.innerHTML = force;
    console.log('change', event);
  },

  startDeepPress: function(event){
    console.log('start deep press', event);
  },

  endDeepPress: function(){
    console.log('end deep press');
  },

  end: function(){
    console.log('end');
    this.style.width = '200px';
    this.innerHTML = 0;
  },

  unsupported: function(){
    console.log(this);
    this.innerHTML = 'Your device / browser does not support this :(';
  }
}

Pressure.set(document.querySelectorAll('#el1'), {preventDefault: false}, block);
Pressure.set($('#el2'), {only: 'force'}, block);
Pressure.set('#el3', {only: '3d'}, block);

$('#el1-jquery').pressure(block);
$('#el2-jquery').pressure({only: 'force', preventDefault: false}, block);
$('#el3-jquery').pressure({only: '3d'}, block);

$('h3').pressure({preventDefault: false},{
  start: function(){
    console.log('preventDefault text');
  }
});
<commit_msg>Maybe I  will switch this, but leaving for now<commit_after>// Example of change method with a failure closure
// This structure can be used in any methods of Pressure
// The failure block will return with an "error" and message showing why the device doesn't support 3D Touch and Force Touch
var block = {
  start: function(event){
    console.log('start', event);
  },

  change: function(force, event){
    this.style.width = $.pressureMap(force, 0, 1, 200, 300) + 'px';
    this.innerHTML = force;
    console.log('change', event);
  },

  startDeepPress: function(event){
    console.log('start deep press', event);
  },

  endDeepPress: function(){
    console.log('end deep press');
  },

  end: function(){
    console.log('end');
    this.style.width = '200px';
    this.innerHTML = 0;
  },

  unsupported: function(){
    console.log(this);
    this.innerHTML = 'Your device / browser does not support this :(';
  }
}

Pressure.set(document.querySelectorAll('#el1'), block, {preventDefault: false});
Pressure.set($('#el2'), block, {only: 'force'});
Pressure.set('#el3', block, {only: '3d'});

$('#el1-jquery').pressure(block);
$('#el2-jquery').pressure(block, {only: 'force', preventDefault: false});
$('#el3-jquery').pressure(block, {only: '3d'});

// $('h3').pressure({
//   start: function(){
//     console.log('preventDefault text');
//   }
// }, {preventDefault: false});
<|endoftext|>


<commit_before>const db = require('../index')
const baseUrl = process.env.DB_URL || 'http://localhost:5984'
const dbName = 'testdb'

db.getInfo(baseUrl)
.then(console.log)
// { headers: { ... },
//   data:
//    { couchdb: 'Welcome',
//      version: '2.0.0',
//      vendor: { name: 'The Apache Software Foundation' } },
//   status: 200,
//   message: 'OK - Request completed successfully',
//   duration: 36 }

db.createDatabase(baseUrl, dbName)
.then(console.log)
// { headers: { ... },
//   data: { ok: true },
//   status: 201,
//   message: 'Created - Database created successfully',
//   duration: 131 }

.then(() => db.getDatabaseHead(baseUrl, dbName))
.then(console.log)
// { headers: { ... },
//   data: {},
//   status: 200,
//   message: 'OK - Database exists',
//   duration: 4 }

.then(() => db.listDatabases(baseUrl))
.then(console.log)
// { headers: { ... },
//   data: [ '_replicator', '_users', 'testdb' ],
//   status: 200,
//   message: 'OK - Request completed successfully',
//   duration: 4 }

.then(() => db.createDocument(baseUrl, dbName, {name: 'Bob'}))
.then(console.log)
// { headers: { ... },
//   data:
//    { ok: true,
//      id: 'daae0752c6909d7ca4cd833f46014605',
//      rev: '1-5a26fa4b20e40bc9e2d3e47b168be460' },
//   status: 201,
//   message: 'Created – Document created and stored on disk',
//   duration: 42 }

.then(() => db.createDocument(baseUrl, dbName, {name: 'Alice'}, 'doc2'))
.then(console.log)
// { headers: { ... },
//   data:
//    { ok: true,
//      id: 'doc2',
//      rev: '1-88b10f13383b5d1e34d1d66d296f061f' },
//   status: 201,
//   message: 'Created – Document created and stored on disk',
//   duration: 38 }

.then(() => db.getDocumentHead(baseUrl, dbName, 'doc2'))
.then(console.log)
// { headers:
//    { server: 'CouchDB/1.6.1 (Erlang OTP/18)',
//      etag: '"1-88b10f13383b5d1e34d1d66d296f061f"',
//      date: 'Sat, 01 Oct 2016 09:46:09 GMT',
//      'content-type': 'application/json',
//      'content-length': '74',
//      'cache-control': 'must-revalidate' },
//   data: {},
//   status: 200,
//   message: 'OK - Document exists',
//   duration: 6 }

.then(() => db.getDocument(baseUrl, dbName, 'doc2'))
.then(response => { console.log(response); return response.data })
// { headers: { ... },
//   data:
//    { _id: 'doc2',
//      _rev: '1-88b10f13383b5d1e34d1d66d296f061f',
//      name: 'Alice' },
//   status: 200,
//   message: 'OK - Request completed successfully',
//   duration: 11 }

.then((doc) => {
  doc.age = 42
  return db.createDocument(baseUrl, dbName, doc, 'doc2')
})
.then(console.log)
// { headers: { ... },
//   data:
//    { ok: true,
//      id: 'doc2',
//      rev: '2-ee5ea9ac0bb1bec913a9b5e7bc11b113' },
//   status: 201,
//   message: 'Created – Document created and stored on disk',
//   duration: 36 }

.then(() => db.getAllDocuments(baseUrl, dbName, {
  descending: true,
  include_docs: true
}))
.then(console.log)
// { headers: { ... },
//   data: { total_rows: 2, offset: 0, rows: [ [Object], [Object] ] },
//   status: 200,
//   message: 'OK - Request completed successfully',
//   duration: 9 }

.then(() => db.createBulkDocuments(baseUrl, dbName, [
  {name: 'Tick'}, {name: 'Trick'}, {name: 'Track'}
], {all_or_nothing: false}))
.then(console.log)
// { headers: { ... },
//   data:
//   [ { ok: true,
//       id: '5413cf41edaedaec6b63aee93db86e1f',
//       rev: '1-d7f23e94e65978ea9252d753fe5dc3f6' },
//     { ok: true,
//       id: '5413cf41edaedaec6b63aee93db877cc',
//       rev: '1-646cd5f84634632f42fee2bdf4ff753a' },
//     { ok: true,
//       id: '5413cf41edaedaec6b63aee93db87c3d',
//       rev: '1-9cc8cf1e775b686ca337f69cd39ff772' } ],
//   status: 201,
//   message: 'Created – Document(s) have been created or updated',
//   duration: 74 }

.then(() => db.findDocuments(baseUrl, dbName, {
  selector: {
    $or: [{ name: 'Tick' }, {name: 'Track'}]
  },
  fields: ['_id', 'name']
}))
.catch(response => {
  if (response.status === 400) {
    return 'Warning: findDocument() requires CouchDB >= 2.0.0. Error ignored'
  }
})
.then(console.log)
// { headers: { ... },
//   data:
//    { warning: 'no matching index found, create an index to optimize query time',
//      docs: [ [Object], [Object] ] },
//   status: 200,
//   message: 'OK - Request completed successfully',
//   duration: 14 }

.then(() => db.deleteDocument(baseUrl, dbName, 'doc2', '2-ee5ea9ac0bb1bec913a9b5e7bc11b113'))
.then(console.log)
// { headers: { ... },
//   data:
//    { ok: true,
//      id: 'doc2',
//      rev: '3-ec0a86a95c5e98a5cd52c29b79b66372' },
//   status: 200,
//   message: 'OK - Document successfully removed',
//   duration: 39 }

.then(() => db.getUuids(baseUrl, 3))
.then(console.log)
// { headers: { ... },
//   data:
//    { uuids:
//       [ 'daae0752c6909d7ca4cd833f46014c47',
//         'daae0752c6909d7ca4cd833f460150c5',
//         'daae0752c6909d7ca4cd833f460156c5' ] },
//   status: 200,
//   message: 'OK - Request completed successfully',
//   duration: 4 }

.then(() => db.deleteDatabase(baseUrl, dbName))
.then(console.log)
// { headers: { ... },
//   data: { ok: true },
//   status: 200,
//   message: 'OK - Database removed successfully',
//   duration: 40 }

.then(() => db.getDocument(baseUrl, dbName, 'doc1'))
.catch(console.error)
// { headers: { ... },
//   data: { error: 'not_found', reason: 'no_db_file' },
//   status: 404,
//   message: 'Not Found - Document not found',
//   duration: 5 }
<commit_msg>example.js: correct error handling<commit_after>const db = require('../index')
const baseUrl = process.env.DB_URL || 'http://localhost:5984'
const dbName = 'testdb'

db.getInfo(baseUrl)
.then(console.log)
// { headers: { ... },
//   data:
//    { couchdb: 'Welcome',
//      version: '2.0.0',
//      vendor: { name: 'The Apache Software Foundation' } },
//   status: 200,
//   message: 'OK - Request completed successfully',
//   duration: 36 }

db.createDatabase(baseUrl, dbName)
.then(console.log)
// { headers: { ... },
//   data: { ok: true },
//   status: 201,
//   message: 'Created - Database created successfully',
//   duration: 131 }

.then(() => db.getDatabaseHead(baseUrl, dbName))
.then(console.log)
// { headers: { ... },
//   data: {},
//   status: 200,
//   message: 'OK - Database exists',
//   duration: 4 }

.then(() => db.listDatabases(baseUrl))
.then(console.log)
// { headers: { ... },
//   data: [ '_replicator', '_users', 'testdb' ],
//   status: 200,
//   message: 'OK - Request completed successfully',
//   duration: 4 }

.then(() => db.createDocument(baseUrl, dbName, {name: 'Bob'}))
.then(console.log)
// { headers: { ... },
//   data:
//    { ok: true,
//      id: 'daae0752c6909d7ca4cd833f46014605',
//      rev: '1-5a26fa4b20e40bc9e2d3e47b168be460' },
//   status: 201,
//   message: 'Created – Document created and stored on disk',
//   duration: 42 }

.then(() => db.createDocument(baseUrl, dbName, {name: 'Alice'}, 'doc2'))
.then(console.log)
// { headers: { ... },
//   data:
//    { ok: true,
//      id: 'doc2',
//      rev: '1-88b10f13383b5d1e34d1d66d296f061f' },
//   status: 201,
//   message: 'Created – Document created and stored on disk',
//   duration: 38 }

.then(() => db.getDocumentHead(baseUrl, dbName, 'doc2'))
.then(console.log)
// { headers:
//    { server: 'CouchDB/1.6.1 (Erlang OTP/18)',
//      etag: '"1-88b10f13383b5d1e34d1d66d296f061f"',
//      date: 'Sat, 01 Oct 2016 09:46:09 GMT',
//      'content-type': 'application/json',
//      'content-length': '74',
//      'cache-control': 'must-revalidate' },
//   data: {},
//   status: 200,
//   message: 'OK - Document exists',
//   duration: 6 }

.then(() => db.getDocument(baseUrl, dbName, 'doc2'))
.then(response => { console.log(response); return response.data })
// { headers: { ... },
//   data:
//    { _id: 'doc2',
//      _rev: '1-88b10f13383b5d1e34d1d66d296f061f',
//      name: 'Alice' },
//   status: 200,
//   message: 'OK - Request completed successfully',
//   duration: 11 }

.then((doc) => {
  doc.age = 42
  return db.createDocument(baseUrl, dbName, doc, 'doc2')
})
.then(console.log)
// { headers: { ... },
//   data:
//    { ok: true,
//      id: 'doc2',
//      rev: '2-ee5ea9ac0bb1bec913a9b5e7bc11b113' },
//   status: 201,
//   message: 'Created – Document created and stored on disk',
//   duration: 36 }

.then(() => db.getAllDocuments(baseUrl, dbName, {
  descending: true,
  include_docs: true
}))
.then(console.log)
// { headers: { ... },
//   data: { total_rows: 2, offset: 0, rows: [ [Object], [Object] ] },
//   status: 200,
//   message: 'OK - Request completed successfully',
//   duration: 9 }

.then(() => db.createBulkDocuments(baseUrl, dbName, [
  {name: 'Tick'}, {name: 'Trick'}, {name: 'Track'}
], {all_or_nothing: false}))
.then(console.log)
// { headers: { ... },
//   data:
//   [ { ok: true,
//       id: '5413cf41edaedaec6b63aee93db86e1f',
//       rev: '1-d7f23e94e65978ea9252d753fe5dc3f6' },
//     { ok: true,
//       id: '5413cf41edaedaec6b63aee93db877cc',
//       rev: '1-646cd5f84634632f42fee2bdf4ff753a' },
//     { ok: true,
//       id: '5413cf41edaedaec6b63aee93db87c3d',
//       rev: '1-9cc8cf1e775b686ca337f69cd39ff772' } ],
//   status: 201,
//   message: 'Created – Document(s) have been created or updated',
//   duration: 74 }

.then(() => db.findDocuments(baseUrl, dbName, {
  selector: {
    $or: [{ name: 'Tick' }, {name: 'Track'}]
  },
  fields: ['_id', 'name']
}))
.catch(response => {
  if (response.status === 400) {
    return 'Warning: findDocument() requires CouchDB >= 2.0.0. Error ignored'
  } else {
    return Promise.reject(response)
  }
})
.then(console.log)
// { headers: { ... },
//   data:
//    { warning: 'no matching index found, create an index to optimize query time',
//      docs: [ [Object], [Object] ] },
//   status: 200,
//   message: 'OK - Request completed successfully',
//   duration: 14 }

.then(() => db.deleteDocument(baseUrl, dbName, 'doc2', '2-ee5ea9ac0bb1bec913a9b5e7bc11b113'))
.then(console.log)
// { headers: { ... },
//   data:
//    { ok: true,
//      id: 'doc2',
//      rev: '3-ec0a86a95c5e98a5cd52c29b79b66372' },
//   status: 200,
//   message: 'OK - Document successfully removed',
//   duration: 39 }

.then(() => db.getUuids(baseUrl, 3))
.then(console.log)
// { headers: { ... },
//   data:
//    { uuids:
//       [ 'daae0752c6909d7ca4cd833f46014c47',
//         'daae0752c6909d7ca4cd833f460150c5',
//         'daae0752c6909d7ca4cd833f460156c5' ] },
//   status: 200,
//   message: 'OK - Request completed successfully',
//   duration: 4 }

.then(() => db.deleteDatabase(baseUrl, dbName))
.then(console.log)
// { headers: { ... },
//   data: { ok: true },
//   status: 200,
//   message: 'OK - Database removed successfully',
//   duration: 40 }

.then(() => db.getDocument(baseUrl, dbName, 'doc1'))
.catch(console.error)
// { headers: { ... },
//   data: { error: 'not_found', reason: 'no_db_file' },
//   status: 404,
//   message: 'Not Found - Document not found',
//   duration: 5 }
<|endoftext|>


<commit_before>var Middleware = require('../middleware/middleware');
var Routing    = require('./routing');
var routes     = require('../config/routes');

var Requester = {

  /**
  * Init Default object for routing
  */
  initDefault: function(defaults) {
    this.defaults = defaults;
  },

  /**
  * Create a new route
  * @params router Object Express router object
  * @params path   String route path
  * @params route  Object route infos (method, action, controller etc...)
  * @params io     Object Socket.io object
  */
  createRoute: function(router, path, route, io) {
    // Init the route object
    if (!this.defaults)
      this.defaults = {};

    // Route initialisation
    this.route = this.initRoute(path, route);

    // Create new express router instance
    this.initRouter(router, this.route, io);
  },

  /**
  * Init the route object with the right options
  * @params String path
  * @params Object route
  * @return Object route
  */
  initRoute: function(path, route) {

    // Adding path in route object
    route.path = path;

    // Set the method
    route.method = this.initMethod(route.method);

    // Set controller
    if (route.uses) {
      var uses = this.initUses(route.uses);
      route.controller = this.initController(uses.controller, uses.action);
      route.action     = uses.action;
    }else
      route.controller = this.initController(route.controller, route.action);

    // Set middlewares
    route.middlewares = this.initMiddleware(route.middlewares, route.auth);

    return route;
  },

  /**
  * Init middlewares functions for the routes
  * @params Array   middlewares
  * @params Boolean auth
  * @return Array   middlewares
  */
  initMiddleware: function(middlewares, auth) {
    // If there is middlewares
    if (middlewares) {
      // Foreach middleware we push it in middlewares
      for (m in middlewares) {
          middlewares[m] = Middleware[middlewares[m]];
      }
    }
    else if (this.defaults.middlewares) {
      var middlewares = [];
      for (m in this.defaults.middlewares) {
          middlewares[m] = Middleware[this.defaults.middlewares[m]];
      }
    }else
      middlewares = [];

    // Check auth middleware
    if (auth)
      middlewares.unshift(Middleware['auth']);
    else if (this.defaults.auth === true && auth !== false)
      middlewares.unshift(Middleware['auth']);

    return middlewares;
  },

  /**
  * Init uses return controller and action
  * @params String uses
  * @return Object controller and action
  */
  initUses: function(uses) {
    uses = uses.split('@');
    return {
      controller : uses[0],
      action     : uses[1]
    };

  },

  /**
  * Set the controller
  * @params String controller
  * @params String action
  * @return null || controller object
  */
  initController: function(controller, action) {
    // If action is a function there is no controller
    if (typeof action == 'function') {
      return null;
    }
    else {
      // If there is a controller return the module
      if (controller) {
        return require('../controllers/' + controller);
      }
      // If there is a default controller
      else if (this.defaults.controller) {
        return require('../controllers/' + this.defaults.controller);
      }
      // No controller
      else {
        return null;
      }
    }
  },

  /**
  * Set the method
  * @params String method
  * @return String the method
  */
  initMethod: function(method) {
    if (method) {
      method = method.toLowerCase();
      if (['get', 'post', 'put', 'delete'].indexOf(method) > -1)
        return method;
    }
    else if (this.defaults.method) {
      return this.defaults.method.toLowerCase();
    }

    // Default
    return 'get';

  },

  /**
  * Create a new Express Router instance
  * @params Function express router
  * @params Object   route infos
  * @Params Object   Socket
  */
  initRouter: function(router, route, io) {
    Routing(router, route, io);
  }
};

module.exports = function(router, io) {

  if (routes['default'])
    Requester.initDefault(routes['default']);

  for (var r in routes) {
    if (r != 'default')
      Requester.createRoute(router, r, routes[r], io);
  }

  // In case of routing error
  router.all('*', function(req, res, next) {
    res.status(404).send({status: 404, message: 'No ressources find. Please read the doc.'});
  });
};
<commit_msg>init socket requester<commit_after>var Middleware = require('../middleware/middleware');
var Routing    = require('./routing');
var routes     = require('../config/routes');

var Requester = {

  /**
  * Init Default object for routing
  */
  initDefault: function(defaults) {
    this.defaults = defaults;
  },

  /**
  * Create a new route
  * @params router Object Express router object
  * @params path   String route path
  * @params route  Object route infos (method, action, controller etc...)
  * @params io     Object Socket.io object
  */
  createRoute: function(router, path, route, io) {
    // Init the route object
    if (!this.defaults)
      this.defaults = {};

    // Route initialisation
    this.route = this.initRoute(path, route);

    // Create new express router instance
    this.initRouter(router, this.route, io);
  },

  /**
  * Init the route object with the right options
  * @params String path
  * @params Object route
  * @return Object route
  */
  initRoute: function(path, route) {

    // Adding path in route object
    route.path = path;

    // Set the method
    route.method = this.initMethod(route.method);

    // Set controller
    if (route.uses) {
      var uses = this.initUses(route.uses);
      route.controller = this.initController(uses.controller, uses.action);
      route.action     = uses.action;
    }else
      route.controller = this.initController(route.controller, route.action);

    // Set socket
    route.socket = this.initSocket(route.socket);

    // Set middlewares
    route.middlewares = this.initMiddleware(route.middlewares, route.auth);

    return route;
  },

  /**
  * Init socket
  * @params boolean route socket infos
  * @return boolean
  */
  initSocket: function(socket) {
    if(socket || (this.defaults.socket && socket !== false))
      return true;
    else
      return false;
  },

  /**
  * Init middlewares functions for the routes
  * @params Array   middlewares
  * @params Boolean auth
  * @return Array   middlewares
  */
  initMiddleware: function(middlewares, auth) {
    // If there is middlewares
    if (middlewares) {
      // Foreach middleware we push it in middlewares
      for (m in middlewares) {
          middlewares[m] = Middleware[middlewares[m]];
      }
    }
    else if (this.defaults.middlewares) {
      var middlewares = [];
      for (m in this.defaults.middlewares) {
          middlewares[m] = Middleware[this.defaults.middlewares[m]];
      }
    }else
      middlewares = [];

    // Check auth middleware
    if (auth)
      middlewares.unshift(Middleware['auth']);
    else if (this.defaults.auth === true && auth !== false)
      middlewares.unshift(Middleware['auth']);

    return middlewares;
  },

  /**
  * Init uses return controller and action
  * @params String uses
  * @return Object controller and action
  */
  initUses: function(uses) {
    uses = uses.split('@');
    return {
      controller : uses[0],
      action     : uses[1]
    };

  },

  /**
  * Set the controller
  * @params String controller
  * @params String action
  * @return null || controller object
  */
  initController: function(controller, action) {
    // If action is a function there is no controller
    if (typeof action == 'function') {
      return null;
    }
    else {
      // If there is a controller return the module
      if (controller) {
        return require('../controllers/' + controller);
      }
      // If there is a default controller
      else if (this.defaults.controller) {
        return require('../controllers/' + this.defaults.controller);
      }
      // No controller
      else {
        return null;
      }
    }
  },

  /**
  * Set the method
  * @params String method
  * @return String the method
  */
  initMethod: function(method) {
    if (method) {
      method = method.toLowerCase();
      if (['get', 'post', 'put', 'delete'].indexOf(method) > -1)
        return method;
    }
    else if (this.defaults.method) {
      return this.defaults.method.toLowerCase();
    }

    // Default
    return 'get';

  },

  /**
  * Create a new Express Router instance
  * @params Function express router
  * @params Object   route infos
  * @Params Object   Socket
  */
  initRouter: function(router, route, io) {
    Routing(router, route, io);
  }
};

module.exports = function(router, io) {

  if (routes['default'])
    Requester.initDefault(routes['default']);

  for (var r in routes) {
    if (r != 'default')
      Requester.createRoute(router, r, routes[r], io);
  }

  // In case of routing error
  router.all('*', function(req, res, next) {
    res.status(404).send({status: 404, message: 'No ressources find. Please read the doc.'});
  });
};
<|endoftext|>


<commit_before>'use strict';

describe('weather.dash module', function() {

  describe('weather controller', function(){
    var scope, dashCtrl, $httpBackend;

    beforeEach(module('weather.dash'));
    beforeEach(inject(function(_$httpBackend_, $rootScope, $controller) {
      $httpBackend = _$httpBackend_;
      $httpBackend.expectGET('dash/testdata.json').
          respond({"channel":{"id": 22967},"feeds":[{"entry_id": 1,"field1":"69","field2":"49"}]});

      scope = $rootScope.$new();
      dashCtrl = $controller('DashCtrl', {$scope: scope});
    }));

    it('should ....', function() {
      expect(dashCtrl).toBeDefined();
    });

    it('should create "channel" model', function() {
      expect(scope.channel).toBeUndefined();
      $httpBackend.flush();
      expect(scope.channel).toBeDefined();
      expect(scope.channel.id).toBeDefined();
    });

    it('should create "feeds" model with list of feed items', function() {
      expect(scope.feeds).toBeUndefined();
      $httpBackend.flush();
      expect(scope.feeds).toBeDefined();
      expect(scope.feeds[0].field1).toEqual('69');
      expect(scope.feeds[0].field2).toEqual('49');
    });

  });
});<commit_msg>add feed load test<commit_after>'use strict';

describe('weather.dash module', function() {

  describe('weather controller', function(){
    var scope, dashCtrl, $httpBackend;

    beforeEach(module('weather.dash'));
    beforeEach(inject(function(_$httpBackend_, $rootScope, $controller) {
      $httpBackend = _$httpBackend_;
      $httpBackend.expectGET('dash/testdata.json').
          respond({"channel":{"id": 22967},"feeds":[{"entry_id": 1,"field1":"69","field2":"49"}]});

      scope = $rootScope.$new();
      dashCtrl = $controller('DashCtrl', {$scope: scope});
    }));

    it('should ....', function() {
      expect(dashCtrl).toBeDefined();
    });

    it('should create "channel" model', function() {
      expect(scope.channel).toBeUndefined();
      $httpBackend.flush();
      expect(scope.channel).toBeDefined();
      expect(scope.channel.id).toBeDefined();
    });

    it('should create "feeds" model with list of feed items', function() {
      expect(scope.feeds).toBeUndefined();
      $httpBackend.flush();
      expect(scope.feeds).toBeDefined();
      expect(scope.feeds[0].field1).toEqual('69');
      expect(scope.feeds[0].field2).toEqual('49');
    });

    it('should set feedLoaded to true after data load', function() {
      expect(scope.feedLoaded).toBeUndefined();
      $httpBackend.flush();
      expect(scope.feedLoaded).toBeDefined();
      expect(scope.feedLoaded).toEqual(true);
    })

  });
});<|endoftext|>


<commit_before>import React from 'react';
import { SprkLink, SprkIcon } from '@sparkdesignsystem/spark-react';
import CentralColumnLayout from '../../containers/CentralColumnLayout/CentralColumnLayout';
import ExampleContainer from '../../containers/ExampleContainer/ExampleContainer';

const SprkLinkDocs = () => (
  <CentralColumnLayout>

External Links

    <ExampleContainer>
      <SprkLink id="foo" href="https://google.com" target="_blank">https://google.com</SprkLink>
    </ExampleContainer>

    <ExampleContainer>
      <SprkLink id="foo" href="https://google.com" target="_blank">http://google.com</SprkLink>
    </ExampleContainer>

Same Page Links

    <ExampleContainer>
      <SprkLink href="#info">Jump Link</SprkLink>
    </ExampleContainer>

    <ExampleContainer>
      <SprkLink href="/button#foo">Jump Link with Page</SprkLink>
    </ExampleContainer>

    <ExampleContainer>
      <SprkLink variant="unstyled">Unstyled Link</SprkLink>
    </ExampleContainer>

    <ExampleContainer>
      <SprkLink variant="simple" idString="simple-link">
        Simple Link
      </SprkLink>
    </ExampleContainer>

    <ExampleContainer>
      <SprkLink variant="has-icon" target="_blank" analyticsString="foo">
        <SprkIcon
          additionalClasses="sprk-c-Icon--xl"
          iconName="communication"
        />
        Icon With Text Link
      </SprkLink>
    </ExampleContainer>

    <ExampleContainer>
      <SprkLink variant="disabled">Disabled Link</SprkLink>
    </ExampleContainer>

    <ExampleContainer>
      <SprkLink variant="plain" additionalClasses="foo">
        Plain Link
      </SprkLink>
    </ExampleContainer>

Hi, I'm info!

  </CentralColumnLayout>
);

export default SprkLinkDocs;
<commit_msg>add documentation<commit_after>import React from 'react';
import { SprkLink, SprkIcon } from '@sparkdesignsystem/spark-react';
import CentralColumnLayout from '../../containers/CentralColumnLayout/CentralColumnLayout';
import ExampleContainer from '../../containers/ExampleContainer/ExampleContainer';

const SprkLinkDocs = () => (
  <CentralColumnLayout>

Links

    <ExampleContainer>
      <SprkLink href="/">This is a standard Spark Link!</SprkLink>
    </ExampleContainer>

    <ExampleContainer>

        Here is a
        <SprkLink href="/"> link </SprkLink>
        in the middle of a line.

    </ExampleContainer>

    <ExampleContainer>
      <SprkLink variant="unstyled">Unstyled Link</SprkLink>
    </ExampleContainer>

    <ExampleContainer>
      <SprkLink variant="simple" idString="simple-link">
        Simple Link
      </SprkLink>
    </ExampleContainer>

    <ExampleContainer>
      <SprkLink variant="plain">Plain Link</SprkLink>
    </ExampleContainer>

External Links

    <ExampleContainer>
      <SprkLink id="foo" href="https://google.com" target="_blank">https://google.com</SprkLink>
    </ExampleContainer>

    <ExampleContainer>
      <SprkLink id="foo" href="https://google.com" target="_blank">http://google.com</SprkLink>
    </ExampleContainer>

Same Page Links

    <ExampleContainer>
      <SprkLink href="#info">Jump Link</SprkLink>
    </ExampleContainer>

    <ExampleContainer>
      <SprkLink href="/button#foo">Jump Link with Page</SprkLink>
    </ExampleContainer>

Link with no href provided

    <ExampleContainer>
      <SprkLink>No href provided.</SprkLink>
    </ExampleContainer>

Link Using Tel

    <ExampleContainer>
      <SprkLink href="tel:+123456789">Tel Link</SprkLink>
    </ExampleContainer>

Link Using mailto

    <ExampleContainer>
      <SprkLink href="mailto:example@example.com">mailto Link</SprkLink>
    </ExampleContainer>

Additional Classes

    <ExampleContainer>
      <SprkLink additionalClasses="sprk-u-mbm">
        Link with Margin Bottom class
      </SprkLink>
    </ExampleContainer>

Disabled Link

    <ExampleContainer>
      <SprkLink variant="disabled">Disabled Link</SprkLink>
    </ExampleContainer>

Icon With Text Link

    <ExampleContainer>
      <SprkLink variant="has-icon" target="_blank" analyticsString="foo">
        <SprkIcon
          additionalClasses="sprk-c-Icon--xl"
          iconName="communication"
        />
        Message Us
      </SprkLink>
    </ExampleContainer>

Hi, I'm info!

  </CentralColumnLayout>
);

export default SprkLinkDocs;
<|endoftext|>


<commit_before>'use strict';

angular.module('forms').controller('enrollmentFormController', ['$scope', 'Authentication', '$location', '$stateParams', '$window', 'EnrollmentFormsService', 'PatientsService', 'PracticesService', 'PetOwnersService', 'DogBreedsService', 'DogFoodService', 'ActivePatient',
    function($scope, Authentication, $location, $stateParams, $window, EnrollmentFormsService, PatientsService, PracticesService, PetOwnersService, DogBreedsService, DogFoodService, ActivePatient) {
        // This provides Authentication context.
        $scope.authentication = Authentication;

        // If the user is not logged in, redirect
        if (!$scope.authentication.user) {
            $location.path('/');
        }

        $scope.activePatient = ActivePatient.getActivePatient();
        $scope.phoneMask = '999-999-9999';
        // List of dog breeds already in database
        $scope.dogBreeds = [];
        $scope.dogFoods = [];
        $scope.dogFoodNames = [];

        // Get the values from the form to be sent to the database
        if(ActivePatient.activePatientSet()) {
            $scope.disableInput = true;
            $scope.vetApproval = true;

            $scope.dateCreated = new Date($scope.activePatient.enrollmentForm.dateCreated);
            $scope.firstName = $scope.activePatient.firstName;
            $scope.patientId = $scope.activePatient.patientId;

            $scope.clientLastName = $scope.activePatient.petOwner.lastName;
            $scope.clientFirstName = $scope.activePatient.petOwner.firstName;
            $scope.clientTelephone = $scope.activePatient.petOwner.phoneNumber;
            $scope.clientEmail = $scope.activePatient.petOwner.email;

            $scope.birthDate = new Date($scope.activePatient.birthDate);
            $scope.startWeight = $scope.activePatient.startWeight;
            $scope.startWeightLb = ($scope.activePatient.startWeight * 2.2046).toFixed(2)-0;

            $scope.sex = $scope.activePatient.sex;
            $scope.fixed = $scope.activePatient.fixed;
            $scope.breed = $scope.activePatient.breed;
            $scope.bcs = $scope.activePatient.bcs;

            $scope.treats = $scope.activePatient.enrollmentForm.treats;
            $scope.currentMedications = $scope.activePatient.enrollmentForm.currentMedications;
            $scope.medicalHistory = $scope.activePatient.enrollmentForm.medicalHistory;
            $scope.peFindings = $scope.activePatient.enrollmentForm.peFindings;
            $scope.vetSig = $scope.activePatient.enrollmentForm.vetSig;
            $scope.techId = $scope.activePatient.enrollmentForm.techId;
            $scope.vetId = $scope.activePatient.enrollmentForm.vetId;
        }
        else {
            $scope.disableInput = false;
            $scope.dateCreated = new Date();
        }

        $scope.editActive = false;

        // This function allows the form to be edited
        $scope.editForm = function() {
            $scope.disableInput = false;
            $scope.editActive = true;
            $scope.vetApproval = true;
        };

        // This function prevents the form from being edited
        $scope.cancelEdit = function() {
            $scope.disableInput = true;
            $scope.editActive = false;
        };

        // Save changes that were made in the form
        $scope.saveEdit = function() {
            var changedDataPatient = {
                _id: $scope.activePatient._id
            };
            var oldDataPatient = {};
            var patientChanged = false;

            var changedDataForm = {
                _id: $scope.activePatient.enrollmentForm._id
            };
            var oldDataForm = {};
            var formChanged = false;

            var changedDataOwner = {
                _id: $scope.activePatient.petOwner._id
            };
            var oldDataOwner = {};
            var ownerChanged = false;

            if($scope.patientId !== $scope.activePatient.patientId) {
                changedDataPatient.patientId = $scope.patientId;
                oldDataPatient.patientId = $scope.activePatient.patientId;
                patientChanged = true;
            }
            if($scope.firstName !== $scope.activePatient.firstName) {
                changedDataPatient.firstName = $scope.firstName;
                oldDataPatient.firstName = $scope.activePatient.firstName;
                patientChanged = true;
            }

            if($scope.clientLastName !== $scope.activePatient.petOwner.lastName) {
                changedDataOwner.lastName = $scope.clientLastName;
                oldDataOwner.lastName = $scope.activePatient.petOwner.lastName;
                ownerChanged = true;
            }
            if($scope.clientLastName !== $scope.activePatient.petOwner.lastName) {
                changedDataOwner.lastName = $scope.clientLastName;
                oldDataOwner.lastName = $scope.activePatient.petOwner.lastName;
                ownerChanged = true;
            }
            if($scope.clientFirstName !== $scope.activePatient.petOwner.firstName) {
                changedDataOwner.firstName = $scope.clientFirstName;
                oldDataOwner.firstName = $scope.activePatient.petOwner.firstName;
                ownerChanged = true;
            }
            if($scope.clientTelephone !== $scope.activePatient.petOwner.phoneNumber) {
                changedDataOwner.phoneNumber = $scope.clientTelephone;
                oldDataOwner.phoneNumber = $scope.activePatient.petOwner.phoneNumber;
                ownerChanged = true;
            }
            if($scope.clientEmail !== $scope.activePatient.petOwner.email) {
                changedDataOwner.email = $scope.clientEmail;
                oldDataOwner.email = $scope.activePatient.petOwner.email;
                ownerChanged = true;
            }

            if($scope.startWeight !== $scope.activePatient.startWeight) {
                changedDataPatient.startWeight = $scope.startWeight;
                oldDataPatient.startWeight = $scope.activePatient.startWeight;
                patientChanged = true;
            }
            if($scope.sex !== $scope.activePatient.sex) {
                changedDataPatient.sex = $scope.sex;
                oldDataPatient.sex = $scope.activePatient.sex;
                patientChanged = true;
            }
            if($scope.fixed !== $scope.activePatient.fixed) {
                changedDataPatient.fixed = $scope.fixed;
                oldDataPatient.fixed = $scope.activePatient.fixed;
                patientChanged = true;
            }
            if($scope.breed !== $scope.activePatient.breed) {
                changedDataPatient.breed = $scope.breed;
                oldDataPatient.breed = $scope.activePatient.breed;
                patientChanged = true;
            }
            if($scope.bcs !== $scope.activePatient.bcs) {
                changedDataPatient.bcs = $scope.bcs;
                oldDataPatient.bcs = $scope.activePatient.bcs;
                patientChanged = true;
            }

            if($scope.treats !== $scope.activePatient.enrollmentForm.treats) {
                changedDataForm.treats = $scope.treats;
                oldDataForm.treats = $scope.activePatient.enrollmentForm.treats;
                formChanged = true;
            }
            if($scope.currentMedications !== $scope.activePatient.enrollmentForm.currentMedications) {
                changedDataForm.currentMedications = $scope.currentMedications;
                oldDataForm.currentMedications = $scope.activePatient.enrollmentForm.currentMedications;
                formChanged = true;
            }
            if($scope.medicalHistory !== $scope.activePatient.enrollmentForm.medicalHistory) {
                changedDataForm.medicalHistory = $scope.medicalHistory;
                oldDataForm.medicalHistory = $scope.activePatient.enrollmentForm.medicalHistory;
                formChanged = true;
            }
            if($scope.peFindings !== $scope.activePatient.enrollmentForm.peFindings) {
                changedDataForm.peFindings = $scope.peFindings;
                oldDataForm.peFindings = $scope.activePatient.enrollmentForm.peFindings;
                formChanged = true;
            }
            if($scope.vetSig !== $scope.activePatient.enrollmentForm.vetSig) {
                changedDataForm.vetSig = $scope.vetSig;
                oldDataForm.vetSig = $scope.activePatient.enrollmentForm.vetSig;
                formChanged = true;
            }
            if($scope.techId !== $scope.activePatient.enrollmentForm.techId) {
                changedDataForm.techId = $scope.techId;
                oldDataForm.techId = $scope.activePatient.enrollmentForm.techId;
                formChanged = true;
            }
            if($scope.vetId !== $scope.activePatient.enrollmentForm.vetId) {
                changedDataForm.vetId = $scope.vetId;
                oldDataForm.vetId = $scope.activePatient.enrollmentForm.vetId;
                formChanged = true;
            }

            if(patientChanged) {
                changedDataPatient.changedData = oldDataPatient;
                var patient = new PatientsService(changedDataPatient);
                console.log('patient edit:');
                console.log(patient);
                console.log(changedDataPatient);
                patient.$update(function(patientUpdateResponse) {});
            }
            if(formChanged) {
                changedDataForm.changedData = oldDataForm;
                var enrollmentForm = new EnrollmentFormsService(changedDataForm);
                console.log('enrollmentForm edit:');
                console.log(enrollmentForm);
                console.log(changedDataForm);
                enrollmentForm.$update(function(enrollmentFormUpdateResponse) {});
            }
            if(ownerChanged) {
                changedDataOwner.changedData = oldDataOwner;
                var petOwner = new PetOwnersService(changedDataOwner);
                petOwner.$update(function(petOwnerUpdateResponse) {});
            }

            ActivePatient.setPatientNeedsUpdate();
        };

        // Calculate today's date as a Date object. Set todayDate date to today.
        var today = new Date();
        var month = today.getMonth();
        var day = today.getDate();
        var year = today.getFullYear();
        today = new Date(year, month, day);
        $scope.todayDate = today;

        $scope.initPatient = function() {
            $scope.activePatient = ActivePatient.getActivePatient();

            var breeds = new DogBreedsService();

            breeds.$get(function( getDogBreedsResponse ) {
                console.log(getDogBreedsResponse);
                $scope.dogBreeds = getDogBreedsResponse.breeds;
            });

            var foods = DogFoodService.query(function( getDogFoodsResponse ) {
                //console.log(getDogFoodsResponse);
                $scope.dogFoods = getDogFoodsResponse;
                for(var i = 0; i < $scope.dogFoods.length; i++) {
                    $scope.dogFoodNames[i] = $scope.dogFoods[i].name;
                }

            });
        };

        // Create the enrollment form by sending the form values to the database
        $scope.createEnrollmentForm = function() {

            var patient = new PatientsService({
                firstName: this.firstName,
                patientId: this.patientId,
                birthDate: this.birthDate,
                sex: this.sex,
                fixed: this.fixed,
                breed: this.breed,
                startWeight: this.startWeight,
                bcs: this.bcs,
                practice: ActivePatient.getActivePractice()._id
            });

            var petOwner = new PetOwnersService({
                firstName: $scope.clientFirstName,
                lastName: $scope.clientLastName,
                phoneNumber: $scope.clientTelephone,
                email: $scope.clientEmail,
                practice: ActivePatient.getActivePractice()._id
            });

            var enrollmentForm = new EnrollmentFormsService({
                dateCreated: $scope.dateCreated,
                treats: this.treats,
                currentMedications: this.currentMedications,
                medicalHistory: this.medicalHistory,
                peFindings: this.peFindings,
                vetSig: this.vetSig,
                techId: this.techId,
                vetId: this.vetId
            });

            patient.$save(function(patientResponse) {
                ActivePatient.setActivePatient(patientResponse);

                var practice = new PracticesService({
                    _id: ActivePatient.getActivePractice()._id,
                    newPatient: patientResponse._id
                });

                practice.$update(function(updatePracticeResponse) {
                    ActivePatient.updateActivePractice();
                });

                enrollmentForm.patient = patientResponse._id;
                petOwner.pet = patientResponse._id;

                petOwner.$save(function(petOwnerResponse) {
                    enrollmentForm.$save(function(enrollmentFormResponse) {
                        patient = new PatientsService({
                            _id: patientResponse._id,
                            enrollmentForm: enrollmentFormResponse._id,
                            petOwner: petOwnerResponse._id,
                            formSave: true
                        });

                        patient.$update(function(patientAddFormResponse) {
                            var patient = new PatientsService({
                                _id: patientAddFormResponse._id
                            });

                            ActivePatient.updateActivePatient();

                            // Wait until the active patient has been updated. Current setup is not ideal
                            setTimeout(function(){
                                if(ActivePatient.getActivePatient().firstName) {
                                    $location.path('/overview');
                                }
                                else {
                                    setTimeout(function(){ $location.path('/overview'); }, 100);
                                }
                            }, 100);

                        });
                    });
                });
            });
        };

        // Set patient info
        $scope.patientInfo = {
            DOB: new Date(2013, 9, 22)
        };

        $scope.patientInfo.age = function () {
            if($scope.birthDate !== undefined) {
                var DOB = $scope.birthDate; //$scope.activePatient.birthDate
                var age = $scope.yearDifference({year: DOB.getFullYear(), month: DOB.getMonth() + 1, day: DOB.getDate()});
                return age;
            }
            else {
                return '';
            }
        };

        // Calculate the patient's ideal weight based on Trimauxil formula
        $scope.patientInfo.idealWeight = function () {
            var currWeight;
            var bodyFat;
            var idealWeight;

            if($scope.disableInput) {
                currWeight = $scope.activePatient.startWeight;
                bodyFat = $scope.activePatient.bcs * 5; // Assumes each BCS equals 5% body fat
                idealWeight = currWeight * (100 - bodyFat) / 100 / 0.8;

                return idealWeight.toFixed(2);
            }
            else {
                currWeight = $scope.startWeight;
                bodyFat = $scope.bcs * 5; // Assumes each BCS equals 5% body fat
                idealWeight = currWeight * (100 - bodyFat) / 100 / 0.8;

                return idealWeight.toFixed(2);
            }
        };

        // Calculates the ideal cups per feeding (based on Trimauxil formula)
        $scope.patientInfo.cupsPerFeeding = function () {
            var dailykCalIdealWeight = 600; // Use Recommended Daily Caloric Intake for Ideal Weight Chart
            var kCalPerCup = 150; // Eventually need to find on food database
            var cupsPerDay = dailykCalIdealWeight/kCalPerCup;
            var perDay = $scope.patientInfo.perDay;
            var cupsPerFeeding = cupsPerDay/perDay;

            return cupsPerFeeding.toFixed(2);
        };

        // Calculates the difference, in years, between two dates
        $scope.yearDifference = function (date) {
            var curDate = new Date(),
                now     = {
                  year: curDate.getUTCFullYear(),
                  // UTC month value is zero-based
                  month: curDate.getUTCMonth() + 1,
                  day: curDate.getUTCDate()
                },
                diff = now.year % date.year;

            // Do not update the date unless it is time
            if (now.month < date.month || now.month === date.month && now.day < date.day) {
              diff -= 1;
            }

            return diff;
        };

        // Convert a lb weight to kg
        $scope.lbToKg = function(lbWeight) {
            return (lbWeight / 2.2046).toFixed(2);
        };
        // Convert a kg weight to lb
        $scope.kgToLb = function(kgWeight) {
            return (kgWeight * 2.2046).toFixed(2);
        };

        $scope.checkEmail = function () {
          $scope.myForm.confirmEmail.$error.dontMatch = $scope.clientEmail !== $scope.confirmEmail;
        };
    }
]);
<commit_msg>Autocompleted food information is done<commit_after>'use strict';

angular.module('forms').controller('enrollmentFormController', ['$scope', 'Authentication', '$location', '$stateParams', '$window', 'EnrollmentFormsService', 'PatientsService', 'PracticesService', 'PetOwnersService', 'DogBreedsService', 'DogFoodService', 'ActivePatient',
    function($scope, Authentication, $location, $stateParams, $window, EnrollmentFormsService, PatientsService, PracticesService, PetOwnersService, DogBreedsService, DogFoodService, ActivePatient) {
        // This provides Authentication context.
        $scope.authentication = Authentication;

        // If the user is not logged in, redirect
        if (!$scope.authentication.user) {
            $location.path('/');
        }

        $scope.activePatient = ActivePatient.getActivePatient();
        $scope.phoneMask = '999-999-9999';
        // List of dog breeds already in database
        $scope.dogBreeds = [];
        $scope.dogFoods = [];
        $scope.dogFoodNames = [];

        // Get the values from the form to be sent to the database
        if(ActivePatient.activePatientSet()) {
            $scope.disableInput = true;
            $scope.vetApproval = true;

            $scope.dateCreated = new Date($scope.activePatient.enrollmentForm.dateCreated);
            $scope.firstName = $scope.activePatient.firstName;
            $scope.patientId = $scope.activePatient.patientId;

            $scope.clientLastName = $scope.activePatient.petOwner.lastName;
            $scope.clientFirstName = $scope.activePatient.petOwner.firstName;
            $scope.clientTelephone = $scope.activePatient.petOwner.phoneNumber;
            $scope.clientEmail = $scope.activePatient.petOwner.email;

            $scope.birthDate = new Date($scope.activePatient.birthDate);
            $scope.startWeight = $scope.activePatient.startWeight;
            $scope.startWeightLb = ($scope.activePatient.startWeight * 2.2046).toFixed(2)-0;

            $scope.sex = $scope.activePatient.sex;
            $scope.fixed = $scope.activePatient.fixed;
            $scope.breed = $scope.activePatient.breed;
            $scope.bcs = $scope.activePatient.bcs;

            $scope.treats = $scope.activePatient.enrollmentForm.treats;
            $scope.currentMedications = $scope.activePatient.enrollmentForm.currentMedications;
            $scope.medicalHistory = $scope.activePatient.enrollmentForm.medicalHistory;
            $scope.peFindings = $scope.activePatient.enrollmentForm.peFindings;
            $scope.vetSig = $scope.activePatient.enrollmentForm.vetSig;
            $scope.techId = $scope.activePatient.enrollmentForm.techId;
            $scope.vetId = $scope.activePatient.enrollmentForm.vetId;
        }
        else {
            $scope.disableInput = false;
            $scope.dateCreated = new Date();
        }

        $scope.editActive = false;

        // This function allows the form to be edited
        $scope.editForm = function() {
            $scope.disableInput = false;
            $scope.editActive = true;
            $scope.vetApproval = true;
        };

        // This function prevents the form from being edited
        $scope.cancelEdit = function() {
            $scope.disableInput = true;
            $scope.editActive = false;
        };

        // Save changes that were made in the form
        $scope.saveEdit = function() {
            var changedDataPatient = {
                _id: $scope.activePatient._id
            };
            var oldDataPatient = {};
            var patientChanged = false;

            var changedDataForm = {
                _id: $scope.activePatient.enrollmentForm._id
            };
            var oldDataForm = {};
            var formChanged = false;

            var changedDataOwner = {
                _id: $scope.activePatient.petOwner._id
            };
            var oldDataOwner = {};
            var ownerChanged = false;

            if($scope.patientId !== $scope.activePatient.patientId) {
                changedDataPatient.patientId = $scope.patientId;
                oldDataPatient.patientId = $scope.activePatient.patientId;
                patientChanged = true;
            }
            if($scope.firstName !== $scope.activePatient.firstName) {
                changedDataPatient.firstName = $scope.firstName;
                oldDataPatient.firstName = $scope.activePatient.firstName;
                patientChanged = true;
            }

            if($scope.clientLastName !== $scope.activePatient.petOwner.lastName) {
                changedDataOwner.lastName = $scope.clientLastName;
                oldDataOwner.lastName = $scope.activePatient.petOwner.lastName;
                ownerChanged = true;
            }
            if($scope.clientLastName !== $scope.activePatient.petOwner.lastName) {
                changedDataOwner.lastName = $scope.clientLastName;
                oldDataOwner.lastName = $scope.activePatient.petOwner.lastName;
                ownerChanged = true;
            }
            if($scope.clientFirstName !== $scope.activePatient.petOwner.firstName) {
                changedDataOwner.firstName = $scope.clientFirstName;
                oldDataOwner.firstName = $scope.activePatient.petOwner.firstName;
                ownerChanged = true;
            }
            if($scope.clientTelephone !== $scope.activePatient.petOwner.phoneNumber) {
                changedDataOwner.phoneNumber = $scope.clientTelephone;
                oldDataOwner.phoneNumber = $scope.activePatient.petOwner.phoneNumber;
                ownerChanged = true;
            }
            if($scope.clientEmail !== $scope.activePatient.petOwner.email) {
                changedDataOwner.email = $scope.clientEmail;
                oldDataOwner.email = $scope.activePatient.petOwner.email;
                ownerChanged = true;
            }

            if($scope.startWeight !== $scope.activePatient.startWeight) {
                changedDataPatient.startWeight = $scope.startWeight;
                oldDataPatient.startWeight = $scope.activePatient.startWeight;
                patientChanged = true;
            }
            if($scope.sex !== $scope.activePatient.sex) {
                changedDataPatient.sex = $scope.sex;
                oldDataPatient.sex = $scope.activePatient.sex;
                patientChanged = true;
            }
            if($scope.fixed !== $scope.activePatient.fixed) {
                changedDataPatient.fixed = $scope.fixed;
                oldDataPatient.fixed = $scope.activePatient.fixed;
                patientChanged = true;
            }
            if($scope.breed !== $scope.activePatient.breed) {
                changedDataPatient.breed = $scope.breed;
                oldDataPatient.breed = $scope.activePatient.breed;
                patientChanged = true;
            }
            if($scope.bcs !== $scope.activePatient.bcs) {
                changedDataPatient.bcs = $scope.bcs;
                oldDataPatient.bcs = $scope.activePatient.bcs;
                patientChanged = true;
            }

            if($scope.treats !== $scope.activePatient.enrollmentForm.treats) {
                changedDataForm.treats = $scope.treats;
                oldDataForm.treats = $scope.activePatient.enrollmentForm.treats;
                formChanged = true;
            }
            if($scope.currentMedications !== $scope.activePatient.enrollmentForm.currentMedications) {
                changedDataForm.currentMedications = $scope.currentMedications;
                oldDataForm.currentMedications = $scope.activePatient.enrollmentForm.currentMedications;
                formChanged = true;
            }
            if($scope.medicalHistory !== $scope.activePatient.enrollmentForm.medicalHistory) {
                changedDataForm.medicalHistory = $scope.medicalHistory;
                oldDataForm.medicalHistory = $scope.activePatient.enrollmentForm.medicalHistory;
                formChanged = true;
            }
            if($scope.peFindings !== $scope.activePatient.enrollmentForm.peFindings) {
                changedDataForm.peFindings = $scope.peFindings;
                oldDataForm.peFindings = $scope.activePatient.enrollmentForm.peFindings;
                formChanged = true;
            }
            if($scope.vetSig !== $scope.activePatient.enrollmentForm.vetSig) {
                changedDataForm.vetSig = $scope.vetSig;
                oldDataForm.vetSig = $scope.activePatient.enrollmentForm.vetSig;
                formChanged = true;
            }
            if($scope.techId !== $scope.activePatient.enrollmentForm.techId) {
                changedDataForm.techId = $scope.techId;
                oldDataForm.techId = $scope.activePatient.enrollmentForm.techId;
                formChanged = true;
            }
            if($scope.vetId !== $scope.activePatient.enrollmentForm.vetId) {
                changedDataForm.vetId = $scope.vetId;
                oldDataForm.vetId = $scope.activePatient.enrollmentForm.vetId;
                formChanged = true;
            }

            if(patientChanged) {
                changedDataPatient.changedData = oldDataPatient;
                var patient = new PatientsService(changedDataPatient);
                console.log('patient edit:');
                console.log(patient);
                console.log(changedDataPatient);
                patient.$update(function(patientUpdateResponse) {});
            }
            if(formChanged) {
                changedDataForm.changedData = oldDataForm;
                var enrollmentForm = new EnrollmentFormsService(changedDataForm);
                console.log('enrollmentForm edit:');
                console.log(enrollmentForm);
                console.log(changedDataForm);
                enrollmentForm.$update(function(enrollmentFormUpdateResponse) {});
            }
            if(ownerChanged) {
                changedDataOwner.changedData = oldDataOwner;
                var petOwner = new PetOwnersService(changedDataOwner);
                petOwner.$update(function(petOwnerUpdateResponse) {});
            }

            ActivePatient.setPatientNeedsUpdate();
        };

        // Calculate today's date as a Date object. Set todayDate date to today.
        var today = new Date();
        var month = today.getMonth();
        var day = today.getDate();
        var year = today.getFullYear();
        today = new Date(year, month, day);
        $scope.todayDate = today;

        $scope.initPatient = function() {
            $scope.activePatient = ActivePatient.getActivePatient();

            var breeds = new DogBreedsService();

            breeds.$get(function( getDogBreedsResponse ) {
                console.log(getDogBreedsResponse);
                $scope.dogBreeds = getDogBreedsResponse.breeds;
            });

            var foods = DogFoodService.query(function( getDogFoodsResponse ) {
                //console.log(getDogFoodsResponse);
                $scope.dogFoods = getDogFoodsResponse;
                for(var i = 0; i < $scope.dogFoods.length; i++) {
                    $scope.dogFoods[i].index = i;
                    $scope.dogFoodNames[i] = $scope.dogFoods[i].name;
                }

            });
        };

        // Create the enrollment form by sending the form values to the database
        $scope.createEnrollmentForm = function() {

            var patient = new PatientsService({
                firstName: this.firstName,
                patientId: this.patientId,
                birthDate: this.birthDate,
                sex: this.sex,
                fixed: this.fixed,
                breed: this.breed,
                startWeight: this.startWeight,
                bcs: this.bcs,
                practice: ActivePatient.getActivePractice()._id
            });

            var petOwner = new PetOwnersService({
                firstName: $scope.clientFirstName,
                lastName: $scope.clientLastName,
                phoneNumber: $scope.clientTelephone,
                email: $scope.clientEmail,
                practice: ActivePatient.getActivePractice()._id
            });

            var enrollmentForm = new EnrollmentFormsService({
                dateCreated: $scope.dateCreated,
                treats: this.treats,
                currentMedications: this.currentMedications,
                medicalHistory: this.medicalHistory,
                peFindings: this.peFindings,
                vetSig: this.vetSig,
                techId: this.techId,
                vetId: this.vetId
            });

            patient.$save(function(patientResponse) {
                ActivePatient.setActivePatient(patientResponse);

                var practice = new PracticesService({
                    _id: ActivePatient.getActivePractice()._id,
                    newPatient: patientResponse._id
                });

                practice.$update(function(updatePracticeResponse) {
                    ActivePatient.updateActivePractice();
                });

                enrollmentForm.patient = patientResponse._id;
                petOwner.pet = patientResponse._id;

                petOwner.$save(function(petOwnerResponse) {
                    enrollmentForm.$save(function(enrollmentFormResponse) {
                        patient = new PatientsService({
                            _id: patientResponse._id,
                            enrollmentForm: enrollmentFormResponse._id,
                            petOwner: petOwnerResponse._id,
                            formSave: true
                        });

                        patient.$update(function(patientAddFormResponse) {
                            var patient = new PatientsService({
                                _id: patientAddFormResponse._id
                            });

                            ActivePatient.updateActivePatient();

                            // Wait until the active patient has been updated. Current setup is not ideal
                            setTimeout(function(){
                                if(ActivePatient.getActivePatient().firstName) {
                                    $location.path('/overview');
                                }
                                else {
                                    setTimeout(function(){ $location.path('/overview'); }, 100);
                                }
                            }, 100);

                        });
                    });
                });
            });
        };

        // Set patient info
        $scope.patientInfo = {
            DOB: new Date(2013, 9, 22)
        };

        $scope.patientInfo.age = function () {
            if($scope.birthDate !== undefined) {
                var DOB = $scope.birthDate; //$scope.activePatient.birthDate
                var age = $scope.yearDifference({year: DOB.getFullYear(), month: DOB.getMonth() + 1, day: DOB.getDate()});
                return age;
            }
            else {
                return '';
            }
        };

        // Calculate the patient's ideal weight based on Trimauxil formula
        $scope.patientInfo.idealWeight = function () {
            var currWeight;
            var bodyFat;
            var idealWeight;

            if($scope.disableInput) {
                currWeight = $scope.activePatient.startWeight;
                bodyFat = $scope.activePatient.bcs * 5; // Assumes each BCS equals 5% body fat
                idealWeight = currWeight * (100 - bodyFat) / 100 / 0.8;

                return idealWeight.toFixed(2);
            }
            else {
                currWeight = $scope.startWeight;
                bodyFat = $scope.bcs * 5; // Assumes each BCS equals 5% body fat
                idealWeight = currWeight * (100 - bodyFat) / 100 / 0.8;

                return idealWeight.toFixed(2);
            }
        };

        // Calculates the ideal cups per feeding (based on Trimauxil formula)
        $scope.patientInfo.cupsPerFeeding = function () {
            var dailykCalIdealWeight = 600; // Use Recommended Daily Caloric Intake for Ideal Weight Chart
            var kCalPerCup = 150; // Eventually need to find on food database
            var cupsPerDay = dailykCalIdealWeight/kCalPerCup;
            var perDay = $scope.patientInfo.perDay;
            var cupsPerFeeding = cupsPerDay/perDay;

            return cupsPerFeeding.toFixed(2);
        };

        // Calculates the difference, in years, between two dates
        $scope.yearDifference = function (date) {
            var curDate = new Date(),
                now     = {
                  year: curDate.getUTCFullYear(),
                  // UTC month value is zero-based
                  month: curDate.getUTCMonth() + 1,
                  day: curDate.getUTCDate()
                },
                diff = now.year % date.year;

            // Do not update the date unless it is time
            if (now.month < date.month || now.month === date.month && now.day < date.day) {
              diff -= 1;
            }

            return diff;
        };

        // Convert a lb weight to kg
        $scope.lbToKg = function(lbWeight) {
            return (lbWeight / 2.2046).toFixed(2);
        };
        // Convert a kg weight to lb
        $scope.kgToLb = function(kgWeight) {
            return (kgWeight * 2.2046).toFixed(2);
        };

        $scope.checkEmail = function () {
          $scope.myForm.confirmEmail.$error.dontMatch = $scope.clientEmail !== $scope.confirmEmail;
        };
    }
]);
<|endoftext|>