<commit_before>//loading overlay vars:
var loading = $("#content").busyBox({spinner: ''} );

_.extend(_, {
  sum: function (arr) {
    return _.reduce(arr, function(sum, v) {return sum + v;}, 0);
  },
  isPresent : function(obj) {
    return !(_.isNull(obj) || _.isUndefined(obj));
  }
});

window.AppView = Backbone.View.extend({
  API_URL : globals.api_url,

  initialize : function() {
    _.bindAll(this, 'api_result', 'handleInputElementsUpdate');

    // this at the moment used for the loading box. to figure out
    // if there are still api calls happening.
    this.api_call_stack = [];

    // Jaap MVC legacy
    this.inputElementsController = window.input_elements;
    this.inputElementsController.bind("change", this.handleInputElementsUpdate);

    this.municipalityController = new MunicipalityController();

    this.settings = new Setting(); // At this point settings is empty!!
    // let's get the ruby-fetched api_session_key
    this.settings.set({'api_session_key' : globals.api_session_key});
    this.scenario = new Scenario();
    this.peak_load = null; // initialize later in bootstrap, because we need to know what country it is
  },

  // At this point we have all the settings initialized.
  bootstrap : function() {
    // DEBT Add check, so that boostrap is only called once.
    if (this.settings.get('country') == 'nl') {
      this.peak_load = new PeakLoad();
    }
    if (this.scenario.api_session_key() == null) {
      this.scenario.new_session();
      // after copmleting new_session() App.bootstrap is called again and will thus continue the else part
    } else {
      this.load_user_values();
      this.call_api();
    }
  },

  // Load User values for Sliders
  load_user_values : function() {
    this.inputElementsController.load_user_values();
  },

  call_api : function(input_params) {
    var self = this;
    var url = this.scenario.query_url(input_params);
    var keys = window.gqueries.keys();

    var keys_ids = _.select(keys, function(key) { return !key.match(/\(/)});
    var keys_string = _.select(keys, function(key) { return key.match(/\(/)});

    var params = {'r' : keys_ids.join(';'), 'result' : keys_string, 'use_fce' : App.settings.get('use_fce') };

    LockableFunction.setLock('call_api');
    this.showLoading();
    var jsonp = $.jsonp({
      url: url,
      data: params,
      success: this.handle_api_result,
      error: function() {
        console.log("Something went wrong");
        self.hideLoading();
      }
    });
    this.register_api_call(jsonp);
  },

  has_unfinished_api_calls : function() {
    return _.isEmpty(this.api_call_stack);
  },

  register_api_call : function(api_call) {
    this.api_call_stack.push(api_call);
  },

  unregister_api_call : function(api_call) {
    this.api_call_stack = _.without(this.api_call_stack, api_call);
  },

  // The following method could need some refactoring
  // e.g. el.set({ api_result : value_arr })
  // window.charts.first().trigger('change');
  // window.dashboard.trigger('change');
  handle_api_result : function(data) {
    //#############################################
    //
    // ATTENTION: This method is not called in the context of App
    //            but in the context of the jsonp object. So 'this'
    //            refers to the jsonp (that's how we get access to data)
    //            and not the App object.
    //
    //#############################################
    App.unregister_api_call(this);

    LockableFunction.removeLock('call_api');
    loading.fadeIn('fast'); //show loading overlay
    var result   = data.result;   // Results of this request for every "result[]" parameter

    $.each(result, function(gquery_key, value_arr) {
      $.each(window.gqueries.with_key(gquery_key), function(i, gquery) {
        gquery.handle_api_result(value_arr);
      });
    });
    window.charts.each(function(chart) { chart.trigger('change'); });
    window.policy_goals.invoke('update_view');
    window.policy_goals.update_totals();

    if (App.peak_load != null) {
      App.peak_load.trigger('change');
    }

    $("body").trigger("dashboardUpdate");
    App.hideLoading();
  },

  /**
   * Set the update in a cancelable action. When you
   * pull a slider A this method is called. It will call doUpdateRequest
   * after 500ms. When a slider is pulled again, that call will be canceled
   * (so that we don't flood the server). doUpdateRequest will get the dirty
   * sliders, reset all dirtyiness and make an API call.
   */
  handleInputElementsUpdate:function() {
    var func = $.proxy(this.doUpdateRequest, this);
    var lockable_function = function() { LockableFunction.deferExecutionIfLocked('update', func); };
    Util.cancelableAction('update',  lockable_function, {'sleepTime': 100});
  },

  /**
   * Get the value of all changed sliders. Get the chart. Sends those values to the server.
   */
  doUpdateRequest:function() {
    var dirtyInputElements = window.input_elements.dirty();

    if (dirtyInputElements.length == 0) { return; }

    var input_params = window.input_elements.api_update_params();
    window.input_elements.reset_dirty();
    window.App.call_api(input_params);
  },

  /*
   * Shows a busy box. Only if api_call_stack is empty. Make sure
   * that you call the showLoading before adding the jsonp to api_call_stack.
   */
  showLoading : function () {
    if (this.has_unfinished_api_calls()) {
      $("#charts_wrapper").busyBox({
        spinner: ''
      }).fadeIn('fast')
      $("#constraints").busyBox({
        classes: 'busybox ontop',
        spinner: ''
      }).fadeIn('fast');
    }
  },

  /*
   * Closes the loading box. will only close if there's no api_calls
   * running at the moment
   */
  hideLoading : function() {
    if (this.has_unfinished_api_calls()) {
      $("#charts_wrapper").busyBox('close');
      $("#constraints").busyBox('close');
      //loading.busyBox('close');
    }
  }
});

window.App = App = new AppView();

<commit_msg>fixed some lint<commit_after>//loading overlay vars:
var loading = $("#content").busyBox({spinner: ''} );

_.extend(_, {
  sum: function (arr) {
    return _.reduce(arr, function(sum, v) {return sum + v;}, 0);
  },
  isPresent : function(obj) {
    return !(_.isNull(obj) || _.isUndefined(obj));
  }
});

window.AppView = Backbone.View.extend({
  API_URL : globals.api_url,

  initialize : function() {
    _.bindAll(this, 'api_result', 'handleInputElementsUpdate');

    // this at the moment used for the loading box. to figure out
    // if there are still api calls happening.
    this.api_call_stack = [];

    // Jaap MVC legacy
    this.inputElementsController = window.input_elements;
    this.inputElementsController.bind("change", this.handleInputElementsUpdate);

    this.municipalityController = new MunicipalityController();

    this.settings = new Setting(); // At this point settings is empty!!
    // let's get the ruby-fetched api_session_key
    this.settings.set({'api_session_key' : globals.api_session_key});
    this.scenario = new Scenario();
    this.peak_load = null; // initialize later in bootstrap, because we need to know what country it is
  },

  // At this point we have all the settings initialized.
  bootstrap : function() {
    // DEBT Add check, so that boostrap is only called once.
    if (this.settings.get('country') == 'nl') {
      this.peak_load = new PeakLoad();
    }
    if (this.scenario.api_session_key() == null) {
      this.scenario.new_session();
      // after copmleting new_session() App.bootstrap is called again and will thus continue the else part
    } else {
      this.load_user_values();
      this.call_api();
    }
  },

  // Load User values for Sliders
  load_user_values : function() {
    this.inputElementsController.load_user_values();
  },

  call_api : function(input_params) {
    var self = this;
    var url = this.scenario.query_url(input_params);
    var keys = window.gqueries.keys();

    var keys_ids = _.select(keys, function(key) { return !key.match(/\(/);});
    var keys_string = _.select(keys, function(key) { return key.match(/\(/);});

    var params = {'r' : keys_ids.join(';'), 'result' : keys_string, 'use_fce' : App.settings.get('use_fce') };

    LockableFunction.setLock('call_api');
    this.showLoading();
    var jsonp = $.jsonp({
      url: url,
      data: params,
      success: this.handle_api_result,
      error: function() {
        console.log("Something went wrong");
        self.hideLoading();
      }
    });
    this.register_api_call(jsonp);
  },

  has_unfinished_api_calls : function() {
    return _.isEmpty(this.api_call_stack);
  },

  register_api_call : function(api_call) {
    this.api_call_stack.push(api_call);
  },

  unregister_api_call : function(api_call) {
    this.api_call_stack = _.without(this.api_call_stack, api_call);
  },

  // The following method could need some refactoring
  // e.g. el.set({ api_result : value_arr })
  // window.charts.first().trigger('change');
  // window.dashboard.trigger('change');
  handle_api_result : function(data) {
    //#############################################
    //
    // ATTENTION: This method is not called in the context of App
    //            but in the context of the jsonp object. So 'this'
    //            refers to the jsonp (that's how we get access to data)
    //            and not the App object.
    //
    //#############################################
    App.unregister_api_call(this);

    LockableFunction.removeLock('call_api');
    loading.fadeIn('fast'); //show loading overlay
    var result   = data.result;   // Results of this request for every "result[]" parameter

    $.each(result, function(gquery_key, value_arr) {
      $.each(window.gqueries.with_key(gquery_key), function(i, gquery) {
        gquery.handle_api_result(value_arr);
      });
    });
    window.charts.each(function(chart) { chart.trigger('change'); });
    window.policy_goals.invoke('update_view');
    window.policy_goals.update_totals();

    if (App.peak_load != null) {
      App.peak_load.trigger('change');
    }

    $("body").trigger("dashboardUpdate");
    App.hideLoading();
  },

  /**
   * Set the update in a cancelable action. When you
   * pull a slider A this method is called. It will call doUpdateRequest
   * after 500ms. When a slider is pulled again, that call will be canceled
   * (so that we don't flood the server). doUpdateRequest will get the dirty
   * sliders, reset all dirtyiness and make an API call.
   */
  handleInputElementsUpdate:function() {
    var func = $.proxy(this.doUpdateRequest, this);
    var lockable_function = function() { LockableFunction.deferExecutionIfLocked('update', func); };
    Util.cancelableAction('update',  lockable_function, {'sleepTime': 100});
  },

  /**
   * Get the value of all changed sliders. Get the chart. Sends those values to the server.
   */
  doUpdateRequest:function() {
    var dirtyInputElements = window.input_elements.dirty();

    if (dirtyInputElements.length == 0) { return; }

    var input_params = window.input_elements.api_update_params();
    window.input_elements.reset_dirty();
    window.App.call_api(input_params);
  },

  /*
   * Shows a busy box. Only if api_call_stack is empty. Make sure
   * that you call the showLoading before adding the jsonp to api_call_stack.
   */
  showLoading : function () {
    if (this.has_unfinished_api_calls()) {
      $("#charts_wrapper").busyBox({
        spinner: ''
      }).fadeIn('fast');
      $("#constraints").busyBox({
        classes: 'busybox ontop',
        spinner: ''
      }).fadeIn('fast');
    }
  },

  /*
   * Closes the loading box. will only close if there's no api_calls
   * running at the moment
   */
  hideLoading : function() {
    if (this.has_unfinished_api_calls()) {
      $("#charts_wrapper").busyBox('close');
      $("#constraints").busyBox('close');
      //loading.busyBox('close');
    }
  }
});

window.App = App = new AppView();

<|endoftext|>


<commit_before>'use strict';

/**
 * controller for (rickshaw) graph on entry page
 */
analyticsControllers.controller('RGraphController', ['$scope', '$attrs', 'EntrySvc',
    function($scope, $attrs, EntrySvc) {
		var self = this;
		var graphElement = null; 	// HTML element showing the graph
		var graph = null;			// graph JS object
		var series = null;			// data container

		this.init = function init (element) {
			graphElement = element;
			var d = new Date();
			var t = d.getTime()/1000;
			series = [{
					color : 'steelblue',
					data : [ {x:t, y:0} ],
					name : "Line 1"
				}];

			graph = createGraph(series, element);
		};

		var graphClickHandler = function graphClickHandler(time) {
			if (!$scope.entry.isLive) {
				// click - only for recorded entries that are not currently live
				$scope.$emit('gotoTime', time);
			}
		};

		/**
		 * create graph and its parts
		 * @param series
		 * @param element
		 * @return rickshaw graph
		 */
		var createGraph = function createGraph(series, element) {
			var graph = new Rickshaw.Graph({
				element : element[0].children[0],
				width : element.width(),
				height : element.height() - 20,
				renderer : 'line',
				interpolation: 'linear',
				series : series
			});
			graph.render();

			var preview = new Rickshaw.Graph.RangeSlider({
				graph : graph,
				element : element[0].children[1]
			});

			var xAxis = new Rickshaw.Graph.Axis.Time({
				graph : graph,
				ticksTreatment : 'glow',
				timeFixture : new KTime_Local()
			});
			xAxis.render();

			var yAxis = new Rickshaw.Graph.Axis.Y({
				graph : graph,
				tickFormat : Rickshaw.Fixtures.Number.formatKMBT,
				ticksTreatment : 'glow'
			});
			yAxis.render();

			var hoverDetail = new KHoverDetail( {
			    graph: graph,
			    formatter: function(series, x, y, formattedXValue, formattedYValue, point) {
			    	return formattedXValue + '
' + y + ' views';
			    },
				onClick : graphClickHandler
			} );

			return graph;
		};

		/**
		 * @param str	info string
		 * @return Array [{x, y}, ..]
		 */
		var parseData = function parseData(str) {
			var os = str.split(';');
			var objects = new Array();
			os.forEach(function (sLine) {
				if (sLine) {
					var vals = sLine.split(',');
					objects.push({'x':parseInt(vals[0], 10), 'timestamp':parseInt(vals[0], 10), 'y':parseInt(vals[1], 10)});
				}
			});
			return objects;
		};

		/**
		 * add 0 points where no data received
		 * for live - all the way
		 * for dead - after first point, before last point
		 * @param data 		objects array with "holes"
		 * @param fromDate	timestamp, seconds
		 * @param toDate	timestamp, seconds
		 * @param fillAll	boolean, should data outside existing range be filled
		 * @return array without "holes"
		 */
		var balanceData = function balanceData(data, fromDate, toDate, fillAll) {
			var firstPoint = Math.floor(fromDate/10)*10;	// init like this for when no data
			var lastPoint = firstPoint;
			var curx, nextx, i = 1;
			if (data.length) {
				firstPoint = data[0].x;
				lastPoint = data[data.length-1].x;
			}

			// add points between lastPoint and firstPoint
			curx = firstPoint + 10;
			while (curx < lastPoint) {
				nextx = data[i].x;
				if (curx < nextx) {
					// need to add point here
					data.splice(i, 0, {'x':curx, 'timestamp':curx, 'y':0});
				}
				curx += 10;
				i++;
			}

			if (fillAll) {
				// add points between firstPoint and fromDate
				curx = firstPoint - 10;
				while (curx >= fromDate) {
					data.unshift({'x':curx, 'timestamp':curx, 'y':0});
					curx -= 10;
				}

				// add points after lastPoint
				curx = lastPoint + 10;
				while (curx <= toDate) {
					data.push({'x':curx, 'timestamp':curx, 'y':0});
					curx += 10;
				}
			}
			return data;
		};

		/**
		 * get graph data for the last 36 hrs
		 * @param end of 36 hrs term (timestamp sec)
		 */
		var getGraph36Hrs = function getGraph36Hrs(toDate) {
			toDate = toDate - 60;
			var fromDate = toDate - 12960; // 60 sec per minute * 60 minutes per hour * 36 hrs
			EntrySvc.getGraph($scope.entryId, -129660, -60).then(function(data) {
				if (data[0] && graph != null) {
					// parse string into objects
					var objects = parseData(data[0].data);
					// add 0 points where no data received
					objects = balanceData(objects, fromDate, toDate, $scope.entry.isLive);
					if (!$scope.entry.isLive) {
						var firstBroadcast = parseInt($scope.entry.firstBroadcast, 10);
						// trim data edges:
						if (!isNaN(firstBroadcast)) {	// non-kaltura don't have firstBroadcast
							for (var i = 0; i < objects.length; i++) {
								if (objects[i].timestamp >= firstBroadcast) {
									break;
								}
							}
						}
						for (var j = objects.length - 1; j>=0; j--) {
							if (objects[j].value != 0) {
								j++;
								break;
							}
						}
						objects = objects.slice(i, j);
						$scope.$emit('TimeBoundsSet', objects[0].timestamp, objects[objects.length - 1].timestamp);
					}
					resetGraphContent(objects);
				};
			});
		};

		/**
		 * get graph data for the last 30 secs
		 * @param endTime (timestamp sec) get graph data for 30 secs up to this time
		 */
		var getGraph30Secs = function getGraph30Secs(endTime) {
			var toDate = -60;	//endTime;
			var fromDate = -122;
			EntrySvc.getGraph($scope.entryId, fromDate, toDate).then(function(data) {
				var objects = parseData(data[0].data);
				objects = balanceData(objects, endTime-122, endTime-60, $scope.entry.isLive);
				if (graph != null) {
					updateGraphContent(objects);
				}
			});
		};

		/**
		 * remove all previous data and set new
		 * @param value
		 */
		var resetGraphContent = function resetGraphContent(value) {
			var ar = series[0].data;
			while (ar.length > 0) {
				ar.pop();
			}
			for ( var i = 0; i < value.length; i++) {
				ar.push(value[i]);
			}
			graph.update();
		};

		/**
		 * add new data and purge oldest so we keep only 36 hrs
		 * @param value points to add tot he graph
		 */
		var updateGraphContent = function updateGraphContent(value) {
			var graphData = series[0].data; // already in the graph
			var lastGraphDataX = graphData[graphData.length-1].x;
			// first see if any existing values need to be updated
			for (var i = 0; i<value.length; i++) {
				var valX = value[i].x;
				if (valX <= lastGraphDataX) {
					// this x value is already in the graph
					for (var j = graphData.length-1; j>=0; j--) {
						if (graphData[j].x == valX) {
							if ( value[i].y != 0) {
								graphData[j].y = value[i].y;
							}
							break;
						}
						else if (graphData[j].x < valX) {
							// j will only become smaller
							break;
						}
					}
				}
				else {
					// valX is out of graphData bounds, will be so for any larger i
					break;
				}
			}

			// then shift/push for new ones
			while(i < value.length) {
				graphData.shift();
				graphData.push(value[i]);
				i++;
			}

			graph.update();
		};

		/**
		 * event handler for main screen setup event
		 * @param event
		 * @param time (timestamp sec)
		 */
		var setupScreenHandler = function setupScreenHandler(event, time) {
			getGraph36Hrs(time);
		};

		/**
		 * event handler for main screen update interval
		 * @param event
		 * @param time (timestamp sec)
		 */
		var updateScreenHandler = function updateScreenHandler(event, time) {
			getGraph30Secs(time);
		};

		$scope.$on('setupScreen', setupScreenHandler);
		$scope.$on('updateScreen', updateScreenHandler);
}]);<commit_msg>don't push data off the graph if less than 36 hrs<commit_after>'use strict';

/**
 * controller for (rickshaw) graph on entry page
 */
analyticsControllers.controller('RGraphController', ['$scope', '$attrs', 'EntrySvc',
    function($scope, $attrs, EntrySvc) {
		var self = this;
		var graphElement = null; 	// HTML element showing the graph
		var graph = null;			// graph JS object
		var series = null;			// data container

		this.init = function init (element) {
			graphElement = element;
			var d = new Date();
			var t = d.getTime()/1000;
			series = [{
					color : 'steelblue',
					data : [ {x:t, y:0} ],
					name : "Line 1"
				}];

			graph = createGraph(series, element);
		};

		var graphClickHandler = function graphClickHandler(time) {
			if (!$scope.entry.isLive) {
				// click - only for recorded entries that are not currently live
				$scope.$emit('gotoTime', time);
			}
		};

		/**
		 * create graph and its parts
		 * @param series
		 * @param element
		 * @return rickshaw graph
		 */
		var createGraph = function createGraph(series, element) {
			var graph = new Rickshaw.Graph({
				element : element[0].children[0],
				width : element.width(),
				height : element.height() - 20,
				renderer : 'line',
				interpolation: 'linear',
				series : series
			});
			graph.render();

			var preview = new Rickshaw.Graph.RangeSlider({
				graph : graph,
				element : element[0].children[1]
			});

			var xAxis = new Rickshaw.Graph.Axis.Time({
				graph : graph,
				ticksTreatment : 'glow',
				timeFixture : new KTime_Local()
			});
			xAxis.render();

			var yAxis = new Rickshaw.Graph.Axis.Y({
				graph : graph,
				tickFormat : Rickshaw.Fixtures.Number.formatKMBT,
				ticksTreatment : 'glow'
			});
			yAxis.render();

			var hoverDetail = new KHoverDetail( {
			    graph: graph,
			    formatter: function(series, x, y, formattedXValue, formattedYValue, point) {
			    	return formattedXValue + '
' + y + ' views';
			    },
				onClick : graphClickHandler
			} );

			return graph;
		};

		/**
		 * @param str	info string
		 * @return Array [{x, y}, ..]
		 */
		var parseData = function parseData(str) {
			var os = str.split(';');
			var objects = new Array();
			os.forEach(function (sLine) {
				if (sLine) {
					var vals = sLine.split(',');
					objects.push({'x':parseInt(vals[0], 10), 'timestamp':parseInt(vals[0], 10), 'y':parseInt(vals[1], 10)});
				}
			});
			return objects;
		};

		/**
		 * add 0 points where no data received
		 * for live - all the way
		 * for dead - after first point, before last point
		 * @param data 		objects array with "holes"
		 * @param fromDate	timestamp, seconds
		 * @param toDate	timestamp, seconds
		 * @param fillAll	boolean, should data outside existing range be filled
		 * @return array without "holes"
		 */
		var balanceData = function balanceData(data, fromDate, toDate, fillAll) {
			var firstPoint = Math.floor(fromDate/10)*10;	// init like this for when no data
			var lastPoint = firstPoint;
			var curx, nextx, i = 1;
			if (data.length) {
				firstPoint = data[0].x;
				lastPoint = data[data.length-1].x;
			}

			// add points between lastPoint and firstPoint
			curx = firstPoint + 10;
			while (curx < lastPoint) {
				nextx = data[i].x;
				if (curx < nextx) {
					// need to add point here
					data.splice(i, 0, {'x':curx, 'timestamp':curx, 'y':0});
				}
				curx += 10;
				i++;
			}

			if (fillAll) {
				// add points between firstPoint and fromDate
				curx = firstPoint - 10;
				while (curx >= fromDate) {
					data.unshift({'x':curx, 'timestamp':curx, 'y':0});
					curx -= 10;
				}

				// add points after lastPoint
				curx = lastPoint + 10;
				while (curx <= toDate) {
					data.push({'x':curx, 'timestamp':curx, 'y':0});
					curx += 10;
				}
			}
			return data;
		};

		/**
		 * get graph data for the last 36 hrs
		 * @param end of 36 hrs term (timestamp sec)
		 */
		var getGraph36Hrs = function getGraph36Hrs(toDate) {
			toDate = toDate - 60;
			var fromDate = toDate - 12960; // 60 sec per minute * 60 minutes per hour * 36 hrs
			EntrySvc.getGraph($scope.entryId, -129660, -60).then(function(data) {
				if (data[0] && graph != null) {
					// parse string into objects
					var objects = parseData(data[0].data);
					// add 0 points where no data received
					objects = balanceData(objects, fromDate, toDate, $scope.entry.isLive);
					if (!$scope.entry.isLive) {
						var firstBroadcast = parseInt($scope.entry.firstBroadcast, 10);
						// trim data edges:
						if (!isNaN(firstBroadcast)) {	// non-kaltura don't have firstBroadcast
							for (var i = 0; i < objects.length; i++) {
								if (objects[i].timestamp >= firstBroadcast) {
									break;
								}
							}
						}
						for (var j = objects.length - 1; j>=0; j--) {
							if (objects[j].value != 0) {
								j++;
								break;
							}
						}
						objects = objects.slice(i, j);
						$scope.$emit('TimeBoundsSet', objects[0].timestamp, objects[objects.length - 1].timestamp);
					}
					resetGraphContent(objects);
				};
			});
		};

		/**
		 * get graph data for the last 30 secs
		 * @param endTime (timestamp sec) get graph data for 30 secs up to this time
		 */
		var getGraph30Secs = function getGraph30Secs(endTime) {
			var toDate = -60;	//endTime;
			var fromDate = -122;
			EntrySvc.getGraph($scope.entryId, fromDate, toDate).then(function(data) {
				var objects = parseData(data[0].data);
				objects = balanceData(objects, endTime-122, endTime-60, $scope.entry.isLive);
				if (graph != null) {
					updateGraphContent(objects);
				}
			});
		};

		/**
		 * remove all previous data and set new
		 * @param value
		 */
		var resetGraphContent = function resetGraphContent(value) {
			var ar = series[0].data;
			while (ar.length > 0) {
				ar.pop();
			}
			for ( var i = 0; i < value.length; i++) {
				ar.push(value[i]);
			}
			graph.update();
		};

		/**
		 * add new data and purge oldest so we keep only 36 hrs
		 * @param value points to add tot he graph
		 */
		var updateGraphContent = function updateGraphContent(value) {
			var graphData = series[0].data; // already in the graph
			var lastGraphDataX = graphData[graphData.length-1].x;
			// first see if any existing values need to be updated
			for (var i = 0; i<value.length; i++) {
				var valX = value[i].x;
				if (valX <= lastGraphDataX) {
					// this x value is already in the graph
					for (var j = graphData.length-1; j>=0; j--) {
						if (graphData[j].x == valX) {
							if ( value[i].y != 0) {
								graphData[j].y = value[i].y;
							}
							break;
						}
						else if (graphData[j].x < valX) {
							// j will only become smaller
							break;
						}
					}
				}
				else {
					// valX is out of graphData bounds, will be so for any larger i
					break;
				}
			}

			// then shift/push for new ones
			while(i < value.length) {
				if (graphData.length >= 12960)
					graphData.shift();
				graphData.push(value[i]);
				i++;
			}

			graph.update();
		};

		/**
		 * event handler for main screen setup event
		 * @param event
		 * @param time (timestamp sec)
		 */
		var setupScreenHandler = function setupScreenHandler(event, time) {
			getGraph36Hrs(time);
		};

		/**
		 * event handler for main screen update interval
		 * @param event
		 * @param time (timestamp sec)
		 */
		var updateScreenHandler = function updateScreenHandler(event, time) {
			getGraph30Secs(time);
		};

		$scope.$on('setupScreen', setupScreenHandler);
		$scope.$on('updateScreen', updateScreenHandler);
}]);<|endoftext|>


<commit_before>'use strict';

var vscode = require('vscode');
var Comb = require('csscomb');

/**
 * Check file extension
 *
 * @param  {String} ext
 */
var _testExtension = function(ext) {
	return /(css|less|sass|scss)/.test(ext);
};

/**
 * Attempt to parse the JSON data
 *
 * @param  {String} fileData
 */
var _parseJsonFile = function(fileData) {
	try {
		return JSON.parse(fileData);
	} catch (err) {
		vscode.window.showErrorMessage('Provided JSON file contains syntax errors. Used standard configuration!');
	}
};

/**
 * Initialization();
 *
 * @param  {Object} textEditor
 * @param  {Object} edit
 */
function Formatter(textEditor) {
	this.textEditor = textEditor;
}

/**
 * Run CSScomb
 *
 * @param  {Object} config
 */
Formatter.prototype._comb = function(config) {
	var document = this.textEditor.document;
	var targetText = document.getText();
	var lang = document.languageId || document._languageId;
	var comb = new Comb();
	comb.configure(config);

	if (_testExtension(lang)) {
		try {
			return comb.processString(targetText, { syntax: lang });
		} catch (err) {
			// For VS Code API: Sass === Scss
			if (err.syntax === 'sass') {
				return comb.processString(targetText, { syntax: 'scss' });
			}

			vscode.window.showErrorMessage(err);
		}
	}

	vscode.window.showWarningMessage('Cannot execute CSScomb because there is not style files.');
	return false;
};

/**
 * Modification (saving) of data in the editor
 *
 * @param  {String} combedStyles
 */
Formatter.prototype._modifyEditorText = function(combedStyles) {
	var document = this.textEditor.document;
	var lastLine = document.lineAt(document.lineCount - 1);
	var selectAll = new vscode.Range(0, 0, lastLine.lineNumber, lastLine.range.end.character);
	this.textEditor.edit(function(editBuilder) {
		editBuilder.replace(selectAll, combedStyles);
	});
};

/**
 * Lifecycle extensions
 */
Formatter.prototype.cssComb = function() {
	var _that = this;
	var preset = vscode.workspace.getConfiguration('csscomb').preset || 'csscomb';
	if (typeof preset === 'string') {
		preset = Comb.getConfig(preset);
	}

	return vscode.workspace.findFiles('**/*csscomb.json', '{**/node_modules/**,**/bower_components/**}', 1)
		// Get array of files contain `csscomb.json` in name
		.then(function(arrayOfFiles) {
			if (arrayOfFiles.length) {
				return arrayOfFiles[0];
			}
		})
		// Read the configuration file
		.then(function(configPath) {
			if (configPath) {
				return vscode.workspace.openTextDocument(configPath);
			}
		})
		// Attempt to parse the JSON data
		.then(function(fileData) {
			if (fileData) {
				return _parseJsonFile(fileData.getText());
			}
		})
		// Run CSScomb
		.then(function(config) {
			var combedStyles = (config) ? _that._comb(config) : _that._comb(preset);
			if (combedStyles) {
				return _that._modifyEditorText(combedStyles);
			}
		});
};

exports.Engine = Formatter;
<commit_msg>Popup warning too verbose<commit_after>'use strict';

var vscode = require('vscode');
var Comb = require('csscomb');

/**
 * Check file extension
 *
 * @param  {String} ext
 */
var _testExtension = function(ext) {
	return /(css|less|sass|scss)/.test(ext);
};

/**
 * Attempt to parse the JSON data
 *
 * @param  {String} fileData
 */
var _parseJsonFile = function(fileData) {
	try {
		return JSON.parse(fileData);
	} catch (err) {
		vscode.window.showErrorMessage('Provided JSON file contains syntax errors. Used standard configuration!');
	}
};

/**
 * Initialization();
 *
 * @param  {Object} textEditor
 * @param  {Object} edit
 */
function Formatter(textEditor) {
	this.textEditor = textEditor;
}

/**
 * Run CSScomb
 *
 * @param  {Object} config
 */
Formatter.prototype._comb = function(config) {
	var document = this.textEditor.document;
	var targetText = document.getText();
	var lang = document.languageId || document._languageId;
	var comb = new Comb();
	comb.configure(config);

	if (_testExtension(lang)) {
		try {
			return comb.processString(targetText, { syntax: lang });
		} catch (err) {
			// For VS Code API: Sass === Scss
			if (err.syntax === 'sass') {
				return comb.processString(targetText, { syntax: 'scss' });
			}

			vscode.window.showErrorMessage(err);
		}
	}

	console.error('Cannot execute CSScomb because there is not style files.');
	return false;
};

/**
 * Modification (saving) of data in the editor
 *
 * @param  {String} combedStyles
 */
Formatter.prototype._modifyEditorText = function(combedStyles) {
	var document = this.textEditor.document;
	var lastLine = document.lineAt(document.lineCount - 1);
	var selectAll = new vscode.Range(0, 0, lastLine.lineNumber, lastLine.range.end.character);
	this.textEditor.edit(function(editBuilder) {
		editBuilder.replace(selectAll, combedStyles);
	});
};

/**
 * Lifecycle extensions
 */
Formatter.prototype.cssComb = function() {
	var _that = this;
	var preset = vscode.workspace.getConfiguration('csscomb').preset || 'csscomb';
	if (typeof preset === 'string') {
		preset = Comb.getConfig(preset);
	}

	return vscode.workspace.findFiles('**/*csscomb.json', '{**/node_modules/**,**/bower_components/**}', 1)
		// Get array of files contain `csscomb.json` in name
		.then(function(arrayOfFiles) {
			if (arrayOfFiles.length) {
				return arrayOfFiles[0];
			}
		})
		// Read the configuration file
		.then(function(configPath) {
			if (configPath) {
				return vscode.workspace.openTextDocument(configPath);
			}
		})
		// Attempt to parse the JSON data
		.then(function(fileData) {
			if (fileData) {
				return _parseJsonFile(fileData.getText());
			}
		})
		// Run CSScomb
		.then(function(config) {
			var combedStyles = (config) ? _that._comb(config) : _that._comb(preset);
			if (combedStyles) {
				return _that._modifyEditorText(combedStyles);
			}
		});
};

exports.Engine = Formatter;
<|endoftext|>


<commit_before>/* global define, $ */
define(function(require, exports, module) {
    var http_cache = require("../../lib/http_cache");

    /**
     * A request wrapper around the jQuery AJAX function.
     *
     * options:
     *
     *     headers: {Object}
     *
     *         The HTTP headers
     *
     *     data: {Object || String} (optional)
     *
     *          The HTTP request body payload.
     *
     *     type: {String} (optional; default = "Intelligent Guess")
     *
     *          The type of data expected from the server.
     *
     * @param {String} verb The HTTP verb (e.g. POST, PUT, etc.)
     * @param {String} url The URL endpoint to which the request should be send.
     * @param {Object} options The jQuery request configuration.
     *
     */
    function request (verb, url, options) {
        var args = {};

        options = options || {};
        args.url = url;
        args.type = verb;
        args.headers = options.headers;
        args.data = options.data;
        args.dataType = options.type;

        return $.ajax(args);
    }

    return {
        fetchUrl: function(url, callback) {
            http_cache.fetchUrl(url, {}, callback);
        },
        get: function(url, type, callback) {
            var options = {
                dataType: type
            };

            request('GET', url, options)
                .done(function onDone (data, status, jqXHR) {
                    var payload = [data, jqXHR.status, jqXHR.getAllResponseHeaders()];

                    callback(null, payload);
                })
                .fail(function onFail (jqXHR) {
                    callback(jqXHR.status)
                });
        },
        post: function(url, options, callback) {
            request('POST', url, options)
                .done(function onDone (data, status, jqXHR) {
                    var payload = [data, jqXHR.status, jqXHR.getAllResponseHeaders()];

                    callback(null, payload);
                })
                .fail(function onFail (jqXHR) {
                    callback(jqXHR.status);
                });
        },
        put: function(url, options, callback) {
             request('PUT', url, options)
                 .done(function onDone (data, status, jqXHR) {
                     var payload = [data, jqXHR.status, jqXHR.getAllResponseHeaders()];

                     callback(null, payload);
                 })
                 .fail(function onFail (jqXHR) {
                     callback(jqXHR.status);
                 });
         },
         del: function(url, options, callback) {
              request('DELETE', url, options)
                  .done(function onDone (data, status, jqXHR) {
                      var payload = [data, jqXHR.status, jqXHR.getAllResponseHeaders()];

                      callback(null, payload);
                  })
                  .fail(function onFail (jqXHR) {
                      callback(jqXHR.status);
                  });
          }
    };
});<commit_msg>Fixed #369 - The parameter passing was wrong due to a typo. The deserialization of the 'package.json' will now work as expected.<commit_after>/* global define, $ */
define(function(require, exports, module) {
    var http_cache = require("../../lib/http_cache");

    /**
     * A request wrapper around the jQuery AJAX function.
     *
     * options:
     *
     *     headers: {Object}
     *
     *         The HTTP headers
     *
     *     data: {Object || String} (optional)
     *
     *          The HTTP request body payload.
     *
     *     type: {String} (optional; default = "Intelligent Guess")
     *
     *          The type of data expected from the server.
     *
     * @param {String} verb The HTTP verb (e.g. POST, PUT, etc.)
     * @param {String} url The URL endpoint to which the request should be send.
     * @param {Object} options The jQuery request configuration.
     *
     */
    function request (verb, url, options) {
        var args = {};

        options = options || {};
        args.url = url;
        args.type = verb;
        args.headers = options.headers;
        args.data = options.data;
        args.dataType = options.dataType;

        return $.ajax(args);
    }

    return {
        fetchUrl: function(url, callback) {
            http_cache.fetchUrl(url, {}, callback);
        },
        get: function(url, type, callback) {
            var options = {
                dataType: type
            };

            request('GET', url, options)
                .done(function onDone (data, status, jqXHR) {
                    var payload = [data, jqXHR.status, jqXHR.getAllResponseHeaders()];

                    callback(null, payload);
                })
                .fail(function onFail (jqXHR) {
                    callback(jqXHR.status)
                });
        },
        post: function(url, options, callback) {
            request('POST', url, options)
                .done(function onDone (data, status, jqXHR) {
                    var payload = [data, jqXHR.status, jqXHR.getAllResponseHeaders()];

                    callback(null, payload);
                })
                .fail(function onFail (jqXHR) {
                    callback(jqXHR.status);
                });
        },
        put: function(url, options, callback) {
             request('PUT', url, options)
                 .done(function onDone (data, status, jqXHR) {
                     var payload = [data, jqXHR.status, jqXHR.getAllResponseHeaders()];

                     callback(null, payload);
                 })
                 .fail(function onFail (jqXHR) {
                     callback(jqXHR.status);
                 });
         },
         del: function(url, options, callback) {
              request('DELETE', url, options)
                  .done(function onDone (data, status, jqXHR) {
                      var payload = [data, jqXHR.status, jqXHR.getAllResponseHeaders()];

                      callback(null, payload);
                  })
                  .fail(function onFail (jqXHR) {
                      callback(jqXHR.status);
                  });
          }
    };
});<|endoftext|>


<commit_before>var
	request = require('request'),
	http = require('http'),
	fs = require('fs'),
	async = require('async'),
	wrench = require('wrench'),
	path = require('path'),
	url = require('url'),

	freezeray = module.exports = function (app, opts, done) {
		return new Freezeray(app, opts || {}, done || function() {});
	};

function Freezeray (app, opts, done) {

	var
		publishDir = opts.publishDir || './publish',
		publicDir = opts.publicDir || './public',
		routes = app.routes.get,
		server = http.createServer(app),
		serverConfig = opts.serverConfig || {
			protocol: 'http',
			hostname: 'localhost',
			port: 50505
		},
		requestUrl = url.format(serverConfig),
		verbose = opts.verbose || false;

	this.publicDir = publicDir;
	this.publishDir = publishDir;
	this.requestUrl = requestUrl;
	this.verbose = verbose;
	this.cb = done;
	this.server = server;

	// clean up before starting
	if (fs.existsSync(publishDir)) {
		wrench.rmdirSyncRecursive(publishDir);
	}
	fs.mkdirSync(publishDir);

	// copy assets
	this.log('copying', publicDir);
	try {
		wrench.copyDirSyncRecursive(publicDir, publishDir);
	}
	catch (err) {
		this.done(err);
		return;
	}

	server.listen(serverConfig.port, serverConfig.hostname, function() {
		// get all the pages
		this.log('scraping pages...');
		async.forEachLimit(routes, 100, this.getPage.bind(this), function(err) {
			if (!err) {
				this.log('Done!');
			}
			this.done(err);
		}.bind(this));
	}.bind(this));

}

Freezeray.prototype.getPage = function (route, callback) {

	var url = this.requestUrl + route.path;
	request.get(url, function(err, res, body) {
		if (!err) {
			this.writeFile(route.path, body, callback);
		}
		else {
			callback(err);
		}
	}.bind(this));

};

Freezeray.prototype.writeFile = function (filename, contents, callback) {

	var pubFilename = path.join(this.publishDir, filename);

	if (!path.extname(filename)) {
		pubFilename = path.join(pubFilename, 'index.html');
	}

	try {
		wrench.mkdirSyncRecursive(path.dirname(pubFilename));
	}
	catch(err) {
		this.done(err);
		return;
	}
	this.log('writing', pubFilename);
	fs.writeFile(pubFilename, contents, callback);

};

Freezeray.prototype.done = function(err) {

	this.cb(err);
	try {
		this.server.close();
	} catch(err) {}

};

Freezeray.prototype.log = function() {

	if (this.verbose) {
		console.log.apply(console, [].slice.call(arguments));
	}

};
<commit_msg>change default port to 3456<commit_after>var
	request = require('request'),
	http = require('http'),
	fs = require('fs'),
	async = require('async'),
	wrench = require('wrench'),
	path = require('path'),
	url = require('url'),

	freezeray = module.exports = function (app, opts, done) {
		return new Freezeray(app, opts || {}, done || function() {});
	};

function Freezeray (app, opts, done) {

	var
		publishDir = opts.publishDir || './publish',
		publicDir = opts.publicDir || './public',
		routes = app.routes.get,
		server = http.createServer(app),
		serverConfig = opts.serverConfig || {
			protocol: 'http',
			hostname: 'localhost',
			port: 3456
		},
		requestUrl = url.format(serverConfig),
		verbose = opts.verbose || false;

	this.publicDir = publicDir;
	this.publishDir = publishDir;
	this.requestUrl = requestUrl;
	this.verbose = verbose;
	this.cb = done;
	this.server = server;

	// clean up before starting
	if (fs.existsSync(publishDir)) {
		wrench.rmdirSyncRecursive(publishDir);
	}
	fs.mkdirSync(publishDir);

	// copy assets
	this.log('copying', publicDir);
	try {
		wrench.copyDirSyncRecursive(publicDir, publishDir);
	}
	catch (err) {
		this.done(err);
		return;
	}

	server.listen(serverConfig.port, serverConfig.hostname, function() {
		// get all the pages
		this.log('scraping pages...');
		async.forEachLimit(routes, 100, this.getPage.bind(this), function(err) {
			if (!err) {
				this.log('Done!');
			}
			this.done(err);
		}.bind(this));
	}.bind(this));

}

Freezeray.prototype.getPage = function (route, callback) {

	var url = this.requestUrl + route.path;
	request.get(url, function(err, res, body) {
		if (!err) {
			this.writeFile(route.path, body, callback);
		}
		else {
			callback(err);
		}
	}.bind(this));

};

Freezeray.prototype.writeFile = function (filename, contents, callback) {

	var pubFilename = path.join(this.publishDir, filename);

	if (!path.extname(filename)) {
		pubFilename = path.join(pubFilename, 'index.html');
	}

	try {
		wrench.mkdirSyncRecursive(path.dirname(pubFilename));
	}
	catch(err) {
		this.done(err);
		return;
	}
	this.log('writing', pubFilename);
	fs.writeFile(pubFilename, contents, callback);

};

Freezeray.prototype.done = function(err) {

	this.cb(err);
	try {
		this.server.close();
	} catch(err) {}

};

Freezeray.prototype.log = function() {

	if (this.verbose) {
		console.log.apply(console, [].slice.call(arguments));
	}

};
<|endoftext|>


<commit_before>var whois = require('whois');
var async = require('async');

/**
 * Iterate over string array and serach for substring
 * @param  {String} string
 * @param  {Array} String array
 * @return {String|Boolean}
 */
var searchStringInArray = function (str, strArray) {
    for (var j=0; j<strArray.length; j++) {
        if (strArray[j].match(str)) return j;
    }
    return -1;
};

/**
 * Copy the default response object
 * and return the clone
 * @return {Object}
 */
var createResponseObject = function (){
  var template = {
    'status': 'success'
  };

  return Object.assign({}, template);
};

/**
 * Check if specific TLD is allowed via
 * configuration file
 * @param  {Object}  $config
 * @param  {String}  $tld
 * @return {Boolean}
 */
var isTldAllowed = function (config, tld){
  if (config.tlds.indexOf(tld) === -1) {
    return false;
  } else {
    return true;
  }
};

/**
 * Whois domain name
 * @param  {String}   domain
 * @return {Callback}
 */
var whoisDomain = function (domain, callback){
  var options = {
    "server": 'whois.autodns3.de'
  };

  whois.lookup('full ' + domain, options, function(err, data) {
    if (err) {
      return callback(false);
    }
    callback(data.split(/\r?\n/));
  })
};

/**
 * Check availability of multiple domains using the
 * custom AutoDNS WhoisProxy
 * @param  {String}   domain
 * @return {Callback}
 */
var checkAvailability = function (domains, cb){
  var responseObject = createResponseObject(),
      domainString = '';

  var options = {
    "server": 'whois.autodns3.de'
  };

  // Loop over available domains and append in domainString
  for (var index = 0; index < domains.length; ++index) {
    domainString += domains[index] + ',';
  }

  // Turn data element into Object
  responseObject.data = {};

  // Send whois request
  whois.lookup('multi ' + domainString, options, function(error, whoisResponse) {
    // Check for general whois errors
    if (error) {
      responseObject.status = 'error';
      responseObject.message = err;
      return cb(responseObject);
    }

    // Split respons per new line, since AutoDNS returns a dedicated line
    // for each requested domain
    var whoisResponseLines = whoisResponse.split(/\r?\n/);

    // For each domain, try to evaluate result
    for (var index = 0; index < domains.length; ++index) {

      // Create full domain name based on domain + tld, search for index in
      // whois result and create a sub response object
      var fullDomain = domains[index],
          arrayIndex = searchStringInArray(fullDomain + ':', whoisResponseLines)
          domainResponseObject = createResponseObject();

      // The pattern that indicates that the domain is available, assigned or invalid
      var needleAvailable = fullDomain + ': free';
      var needleAssigned = fullDomain + ': assigned';
      var needleInvalid = fullDomain + ': invalid';

      // Evaluate the response line for the specific domain
      if (whoisResponseLines[arrayIndex].indexOf(needleAvailable) !== -1) {
        domainResponseObject.available = true;
      } else if (whoisResponseLines[arrayIndex].indexOf(needleAssigned) !== -1) {
        domainResponseObject.available = false;
      } else {
        domainResponseObject.status = 'error';
        domainResponseObject.message = whoisResponseLines[arrayIndex].replace(fullDomain + ': ', '');
      }

      // Push domain objkect into response object
      responseObject.data[fullDomain] = domainResponseObject;
    }

    // Return response
    return cb(responseObject);
  })
};

module.exports = {
  searchStringInArray: searchStringInArray,
  createResponseObject: createResponseObject,
  isTldAllowed: isTldAllowed,
  whoisDomain: whoisDomain,
  checkAvailability: checkAvailability
};
<commit_msg>Check for domain in whois response lines<commit_after>var whois = require('whois');
var async = require('async');

/**
 * Iterate over string array and serach for substring
 * @param  {String} string
 * @param  {Array} String array
 * @return {String|Boolean}
 */
var searchStringInArray = function (str, strArray) {
    for (var j=0; j<strArray.length; j++) {
        if (strArray[j].match(str)) return j;
    }
    return -1;
};

/**
 * Copy the default response object
 * and return the clone
 * @return {Object}
 */
var createResponseObject = function (){
  var template = {
    'status': 'success'
  };

  return Object.assign({}, template);
};

/**
 * Check if specific TLD is allowed via
 * configuration file
 * @param  {Object}  $config
 * @param  {String}  $tld
 * @return {Boolean}
 */
var isTldAllowed = function (config, tld){
  if (config.tlds.indexOf(tld) === -1) {
    return false;
  } else {
    return true;
  }
};

/**
 * Whois domain name
 * @param  {String}   domain
 * @return {Callback}
 */
var whoisDomain = function (domain, callback){
  var options = {
    "server": 'whois.autodns3.de'
  };

  whois.lookup('full ' + domain, options, function(err, data) {
    if (err) {
      return callback(false);
    }
    callback(data.split(/\r?\n/));
  })
};

/**
 * Check availability of multiple domains using the
 * custom AutoDNS WhoisProxy
 * @param  {String}   domain
 * @return {Callback}
 */
var checkAvailability = function (domains, cb){
  var responseObject = createResponseObject(),
      domainString = '';

  var options = {
    "server": 'whois.autodns3.de'
  };

  // Loop over available domains and append in domainString
  for (var index = 0; index < domains.length; ++index) {
    domainString += domains[index] + ',';
  }

  // Turn data element into Object
  responseObject.data = {};

  // Send whois request
  whois.lookup('multi ' + domainString, options, function(error, whoisResponse) {
    // Check for general whois errors
    if (error) {
      responseObject.status = 'error';
      responseObject.message = err;
      return cb(responseObject);
    }

    // Split respons per new line, since AutoDNS returns a dedicated line
    // for each requested domain
    var whoisResponseLines = whoisResponse.split(/\r?\n/);

    // For each domain, try to evaluate result
    for (var index = 0; index < domains.length; ++index) {

      // Create full domain name based on domain + tld, search for index in
      // whois result and create a sub response object
      var fullDomain = domains[index],
          arrayIndex = searchStringInArray(fullDomain + ':', whoisResponseLines)
          domainResponseObject = createResponseObject();

      // Check if line is found that contains requested domain
      if (arrayIndex === -1) {
        domainResponseObject.status = 'error';
        domainResponseObject.message = 'Couldn\'t find domain in whois response';
      } else {
        // The pattern that indicates that the domain is available, assigned or invalid
        var needleAvailable = fullDomain + ': free';
        var needleAssigned = fullDomain + ': assigned';
        var needleInvalid = fullDomain + ': invalid';

        // Evaluate the response line for the specific domain
        if (whoisResponseLines[arrayIndex].indexOf(needleAvailable) !== -1) {
          domainResponseObject.available = true;
        } else if (whoisResponseLines[arrayIndex].indexOf(needleAssigned) !== -1) {
          domainResponseObject.available = false;
        } else {
          domainResponseObject.status = 'error';
          domainResponseObject.message = whoisResponseLines[arrayIndex].replace(fullDomain + ': ', '');
        }
      }

      // Push domain objkect into response object
      responseObject.data[fullDomain] = domainResponseObject;
    }

    // Return response
    return cb(responseObject);
  })
};

module.exports = {
  searchStringInArray: searchStringInArray,
  createResponseObject: createResponseObject,
  isTldAllowed: isTldAllowed,
  whoisDomain: whoisDomain,
  checkAvailability: checkAvailability
};
<|endoftext|>


<commit_before>/**
 * Settings storage for all Gateway Services
 * General API Settings are stored in api/apiConfig and should be imported here
 */

import {
    rudexAPIs,
    bitsparkAPIs,
    openledgerAPIs,
    cryptoBridgeAPIs,
    gdex2APIs,
    xbtsxAPIs,
    citadelAPIs,
    deexAPIs
} from "api/apiConfig";
import {allowedGateway} from "branding";
import {isGatewayTemporarilyDisabled} from "../chain/onChainConfig";
import SettingsStore from "stores/SettingsStore";

const _isEnabled = gatewayKey => {
    return async function(options = {}) {
        if (__DEV__) {
            console.log("Checking " + gatewayKey + " gateway ...");
        }
        if (!options.onlyOnChainConfig) {
            // is the gateway configured in branding?
            const setInBranding = allowedGateway(gatewayKey);
            if (!setInBranding) {
                if (__DEV__) {
                    console.log("  ... disabled in branding.js");
                }
                return false;
            } else {
                if (!!options.onlyBranding) {
                    if (__DEV__) {
                        console.log("  ... may be used!");
                    }
                    return true;
                }
            }
        }
        // is it deactivated on-chain?
        const temporarilyDisabled = await isGatewayTemporarilyDisabled(
            gatewayKey
        );
        if (temporarilyDisabled) {
            if (__DEV__) {
                console.log("  ... disabled on-chain");
            }
            return false;
        } else {
            if (!!options.onlyOnChainConfig) {
                if (__DEV__) {
                    console.log("  ... may be used!");
                }
                return true;
            }
        }
        // has the user filtered it out?
        let filteredServiceProviders = SettingsStore.getState().settings.get(
            "filteredServiceProviders",
            []
        );
        if (!filteredServiceProviders) {
            filteredServiceProviders = [];
        }
        let userAllowed = false;
        if (
            filteredServiceProviders.length == 1 &&
            filteredServiceProviders[0] == "all"
        ) {
            userAllowed = true;
        } else {
            userAllowed = filteredServiceProviders.indexOf(gatewayKey) >= 0;
        }
        if (!userAllowed) {
            if (__DEV__) {
                console.log("  ... disabled by user");
            }
            return false;
        }
        if (__DEV__) {
            console.log("  ... may be used!");
        }
        return true;
    };
};

export const availableGateways = {
    OPEN: {
        id: "OPEN",
        name: "OpenLedger",
        baseAPI: openledgerAPIs,
        isEnabled: false,
        selected: false,
        options: {
            enabled: false,
            selected: false
        },
        landing: "https://dex.openledger.io/news/ol-dex-is-closing-all-activities/",
        wallet: "Shutdown"
    },
    RUDEX: {
        id: "RUDEX",
        name: "RuDEX",
        baseAPI: rudexAPIs,
        isEnabled: _isEnabled("RUDEX"),
        isSimple: true,
        selected: false,
        simpleAssetGateway: true,
        fixedMemo: {
            prepend_default: "dex:",
            prepend_btsid: "btsid-",
            append: ""
        },
        addressValidatorMethod: "POST",
        options: {
            enabled: false,
            selected: false
        },
        landing: "https://rudex.org/",
        wallet: "https://market.rudex.org/"
    },
    SPARKDEX: {
        id: "SPARKDEX",
        name: "BitSpark",
        baseAPI: bitsparkAPIs,
        isEnabled: _isEnabled("SPARKDEX"),
        selected: false,
        options: {
            enabled: false,
            selected: false
        },
        landing: "https://www.bitspark.io/for-traders",
        wallet: "https://dex.bitspark.io/"
    },
    BRIDGE: {
        id: "BRIDGE",
        name: "CryptoBridge",
        baseAPI: cryptoBridgeAPIs,
        isEnabled: _isEnabled("BRIDGE"),
        selected: false,
        singleWallet: true, // Has no coresponging coinType == backingCoinType specific wallet
        addressValidatorAsset: true, // Address validator requires output_asset parameter
        useFullAssetName: true, // Adds <gateway>.<asset> to memo and address object
        intermediateAccount: "cryptobridge", // Fixed intermediateAccount
        options: {
            enabled: false,
            selected: false
        },
        landing: "Shutdown",
        wallet: "Shutdown"
    },
    GDEX: {
        id: "GDEX",
        name: "GDEX",
        baseAPI: gdex2APIs,
        isEnabled: _isEnabled("GDEX"),
        options: {
            enabled: false,
            selected: false
        },
        wallet: "https://www.gdex.io/"
    },
    XBTSX: {
        id: "XBTSX",
        name: "XBTS",
        baseAPI: xbtsxAPIs,
        isEnabled: _isEnabled("XBTSX"),
        isSimple: true,
        selected: false,
        addressValidatorMethod: "POST",
        options: {
            enabled: false,
            selected: false
        },
        landing: "https://xbts.io/",
        wallet: "https://ex.xbts.io/"
    },
    CITADEL: {
        id: "CITADEL",
        name: "Citadel",
        baseAPI: citadelAPIs,
        isEnabled: _isEnabled("CITADEL"),
        selected: false,
        assetWithdrawlAlias: {monero: "xmr"}, // if asset name doesn't equal to memo
        options: {
            enabled: false,
            selected: false
        },
        landing: "https://citadel.li/",
        wallet: "https://citadel.li/wallet/"
    },
    DEEX: {
        id: "DEEX",
        name: "DEEX",
        baseAPI: deexAPIs,
        isSimple: true,
        simpleAssetGateway: false,
        fixedMemo: {
            prepend_default: "dex:",
            append: ""
        },
        isEnabled: _isEnabled("DEEX"),
        addressValidatorMethod: "POST",
        options: {
            enabled: false,
            selected: false
        },
        landing: "https://deex.one/",
        wallet: "https://deex.exchange/"
    }
};

export const availableBridges = {
    TRADE: {
        id: "TRADE",
        name: "Blocktrades",
        isEnabled: _isEnabled("TRADE"),
        landing: "https://blocktrades.us"
    }
};

export const gatewayPrefixes = Object.keys(availableGateways);

export function getPossibleGatewayPrefixes(bases) {
    return gatewayPrefixes.reduce((assets, prefix) => {
        bases.forEach(a => {
            assets.push(`${prefix}.${a}`);
        });
        return assets;
    }, []);
}

export default availableGateways;
<commit_msg>Update gateways.js<commit_after>/**
 * Settings storage for all Gateway Services
 * General API Settings are stored in api/apiConfig and should be imported here
 */

import {
    rudexAPIs,
    bitsparkAPIs,
    openledgerAPIs,
    cryptoBridgeAPIs,
    gdex2APIs,
    xbtsxAPIs,
    citadelAPIs
} from "api/apiConfig";
import {allowedGateway} from "branding";
import {isGatewayTemporarilyDisabled} from "../chain/onChainConfig";
import SettingsStore from "stores/SettingsStore";

const _isEnabled = gatewayKey => {
    return async function(options = {}) {
        if (__DEV__) {
            console.log("Checking " + gatewayKey + " gateway ...");
        }
        if (!options.onlyOnChainConfig) {
            // is the gateway configured in branding?
            const setInBranding = allowedGateway(gatewayKey);
            if (!setInBranding) {
                if (__DEV__) {
                    console.log("  ... disabled in branding.js");
                }
                return false;
            } else {
                if (!!options.onlyBranding) {
                    if (__DEV__) {
                        console.log("  ... may be used!");
                    }
                    return true;
                }
            }
        }
        // is it deactivated on-chain?
        const temporarilyDisabled = await isGatewayTemporarilyDisabled(
            gatewayKey
        );
        if (temporarilyDisabled) {
            if (__DEV__) {
                console.log("  ... disabled on-chain");
            }
            return false;
        } else {
            if (!!options.onlyOnChainConfig) {
                if (__DEV__) {
                    console.log("  ... may be used!");
                }
                return true;
            }
        }
        // has the user filtered it out?
        let filteredServiceProviders = SettingsStore.getState().settings.get(
            "filteredServiceProviders",
            []
        );
        if (!filteredServiceProviders) {
            filteredServiceProviders = [];
        }
        let userAllowed = false;
        if (
            filteredServiceProviders.length == 1 &&
            filteredServiceProviders[0] == "all"
        ) {
            userAllowed = true;
        } else {
            userAllowed = filteredServiceProviders.indexOf(gatewayKey) >= 0;
        }
        if (!userAllowed) {
            if (__DEV__) {
                console.log("  ... disabled by user");
            }
            return false;
        }
        if (__DEV__) {
            console.log("  ... may be used!");
        }
        return true;
    };
};

export const availableGateways = {
    OPEN: {
        id: "OPEN",
        name: "OpenLedger",
        baseAPI: openledgerAPIs,
        isEnabled: false,
        selected: false,
        options: {
            enabled: false,
            selected: false
        },
        landing: "https://dex.openledger.io/news/ol-dex-is-closing-all-activities/",
        wallet: "Shutdown"
    },
    RUDEX: {
        id: "RUDEX",
        name: "RuDEX",
        baseAPI: rudexAPIs,
        isEnabled: _isEnabled("RUDEX"),
        isSimple: true,
        selected: false,
        simpleAssetGateway: true,
        fixedMemo: {
            prepend_default: "dex:",
            prepend_btsid: "btsid-",
            append: ""
        },
        addressValidatorMethod: "POST",
        options: {
            enabled: false,
            selected: false
        },
        landing: "https://rudex.org/",
        wallet: "https://market.rudex.org/"
    },
    SPARKDEX: {
        id: "SPARKDEX",
        name: "BitSpark",
        baseAPI: bitsparkAPIs,
        isEnabled: _isEnabled("SPARKDEX"),
        selected: false,
        options: {
            enabled: false,
            selected: false
        },
        landing: "https://www.bitspark.io/for-traders",
        wallet: "https://dex.bitspark.io/"
    },
    BRIDGE: {
        id: "BRIDGE",
        name: "CryptoBridge",
        baseAPI: cryptoBridgeAPIs,
        isEnabled: _isEnabled("BRIDGE"),
        selected: false,
        singleWallet: true, // Has no coresponging coinType == backingCoinType specific wallet
        addressValidatorAsset: true, // Address validator requires output_asset parameter
        useFullAssetName: true, // Adds <gateway>.<asset> to memo and address object
        intermediateAccount: "cryptobridge", // Fixed intermediateAccount
        options: {
            enabled: false,
            selected: false
        },
        landing: "Shutdown",
        wallet: "Shutdown"
    },
    GDEX: {
        id: "GDEX",
        name: "GDEX",
        baseAPI: gdex2APIs,
        isEnabled: _isEnabled("GDEX"),
        options: {
            enabled: false,
            selected: false
        },
        wallet: "https://www.gdex.io/"
    },
    XBTSX: {
        id: "XBTSX",
        name: "XBTS",
        baseAPI: xbtsxAPIs,
        isEnabled: _isEnabled("XBTSX"),
        isSimple: true,
        selected: false,
        addressValidatorMethod: "POST",
        options: {
            enabled: false,
            selected: false
        },
        landing: "https://xbts.io/",
        wallet: "https://ex.xbts.io/"
    },
    CITADEL: {
        id: "CITADEL",
        name: "Citadel",
        baseAPI: citadelAPIs,
        isEnabled: _isEnabled("CITADEL"),
        selected: false,
        assetWithdrawlAlias: {monero: "xmr"}, // if asset name doesn't equal to memo
        options: {
            enabled: false,
            selected: false
        },
        landing: "https://citadel.li/",
        wallet: "https://citadel.li/wallet/"
    }
};

export const availableBridges = {
    TRADE: {
        id: "TRADE",
        name: "Blocktrades",
        isEnabled: _isEnabled("TRADE"),
        landing: "https://blocktrades.us"
    }
};

export const gatewayPrefixes = Object.keys(availableGateways);

export function getPossibleGatewayPrefixes(bases) {
    return gatewayPrefixes.reduce((assets, prefix) => {
        bases.forEach(a => {
            assets.push(`${prefix}.${a}`);
        });
        return assets;
    }, []);
}

export default availableGateways;
<|endoftext|>


<commit_before>/**
 * This is generated code - it will be overwritten. Do not modify.
 * Copyright (c) 2012 by Appcelerator, Inc. All Rights Reserved.
 */

function InvokeService(path, method, data, cb) {
   if (typeof(data) == "function") {
      cb = data; data = null;
   }
   var xhr = Ti.Network.createHTTPClient();
   if (typeof(cb) == "function") {
        xhr.onload = function(e) {
           var r = this.responseText;
           if (xhr.getResponseHeader("content-type").indexOf("json") != -1) {
               try { r = JSON.parse(r); } catch (E) { }
           }
           cb(r, e);
        };
   }
   if(exports.URL.match('/$') == '/' && path.indexOf('/') == 0) {
       xhr.open(method, exports.URL + path.substring(1));
   } else {
       xhr.open(method, exports.URL + path);
   }
   alert(AG.Cloud.sessionId);
   xhr.setRequestHeader( "Set-Cookie", "_session_id="+AG.Cloud.sessionId );
   xhr.send(data);
};

var url = Ti.App.Properties.getString("acs-service-baseurl-slimer");

if(url && url.replace(/^\s+|\s+$/g, "")) {
   exports.URL = url.replace(/^\s+|\s+$/g, "");
} else {
   exports.URL = "http://localhost:8080";
}

exports.application_index = function(data, cb) {
   var path = [];
   path.push('/');
   InvokeService(path.join(''), "GET", data, cb);
};

exports.pic_showPic = function(data, id, cb) {
   if(!id) throw 'id is required!';
   var path = [];
   path.push('/pic');
   if(id) {
      path.push('/' + id);
   }
   InvokeService(path.join(''), "GET", data, cb);
};

exports.pic_ogImage = function(data, id, cb) {
   if(!id) throw 'id is required!';
   var path = [];
   path.push('/og_image');
   if(id) {
      path.push('/' + id);
   }
   InvokeService(path.join(''), "GET", data, cb);
};

exports.application_showMe = function(data, cb) {
   var path = [];
   path.push('/show_me');
   InvokeService(path.join(''), "GET", data, cb);
};
<commit_msg>간단히 성공 .. Cookie라고 해서 보내야함.<commit_after>/**
 * This is generated code - it will be overwritten. Do not modify.
 * Copyright (c) 2012 by Appcelerator, Inc. All Rights Reserved.
 */

function InvokeService(path, method, data, cb) {
   if (typeof(data) == "function") {
      cb = data; data = null;
   }
   var xhr = Ti.Network.createHTTPClient();
   if (typeof(cb) == "function") {
        xhr.onload = function(e) {
           var r = this.responseText;
           if (xhr.getResponseHeader("content-type").indexOf("json") != -1) {
               try { r = JSON.parse(r); } catch (E) { }
           }
           cb(r, e);
        };
   }
   if(exports.URL.match('/$') == '/' && path.indexOf('/') == 0) {
       xhr.open(method, exports.URL + path.substring(1));
   } else {
       xhr.open(method, exports.URL + path);
   }
   alert(AG.Cloud.sessionId);
   xhr.setRequestHeader( "Cookie", "_session_id="+AG.Cloud.sessionId );
   xhr.send(data);
};

var url = Ti.App.Properties.getString("acs-service-baseurl-slimer");

if(url && url.replace(/^\s+|\s+$/g, "")) {
   exports.URL = url.replace(/^\s+|\s+$/g, "");
} else {
   exports.URL = "http://localhost:8080";
}

exports.application_index = function(data, cb) {
   var path = [];
   path.push('/');
   InvokeService(path.join(''), "GET", data, cb);
};

exports.pic_showPic = function(data, id, cb) {
   if(!id) throw 'id is required!';
   var path = [];
   path.push('/pic');
   if(id) {
      path.push('/' + id);
   }
   InvokeService(path.join(''), "GET", data, cb);
};

exports.pic_ogImage = function(data, id, cb) {
   if(!id) throw 'id is required!';
   var path = [];
   path.push('/og_image');
   if(id) {
      path.push('/' + id);
   }
   InvokeService(path.join(''), "GET", data, cb);
};

exports.application_showMe = function(data, cb) {
   var path = [];
   path.push('/show_me');
   InvokeService(path.join(''), "GET", data, cb);
};
<|endoftext|>


<commit_before>'use strict';

// Load requirements
const fs = require('fs'),
      path = require('path'),
      os = require('os');

// Load modules
const utils = require('../utils'),
      logger = require('../log');

// Variables
const configDir = path.resolve('./config'),
      settingsFile = path.join(configDir, 'settings.json');

// Create directory
if ( ! fs.existsSync(configDir) ) {
  fs.mkdirSync(configDir);
}

// Create example settings
if ( ! fs.existsSync(settingsFile) ) {
  fs.writeFileSync(settingsFile, JSON.stringify(require('./data/sample'), null, 4));
  // logger.warn('Created a new settings file in config, please customise these settings before running again');
  // process.exit(0);
}

// Define the recursive settings object builds
const buildSettings = function(rules) {
  for ( let prop in rules ) {
    Object.defineProperty(this, prop, {
      get: function() { // jshint ignore:line
        if ( rules[prop] !== null && typeof rules[prop] === 'object' && ! Array.isArray(rules[prop]) )
          return new buildSettings(rules[prop]);
        else
          return rules[prop];
      }
    });
  }
};

// Create a dynamic object
let settings = new buildSettings(require(settingsFile));

// Export the object
module.exports = settings;
<commit_msg>Update settings to not require creation of default settings<commit_after>'use strict';

// Load requirements
const fs = require('fs'),
      path = require('path'),
      os = require('os');

// Load modules
const utils = require(__base + 'libs/utils'),
      logger = require(__base + 'libs/log');

// Variables
const config = require(path.join(__base, '../config/config')),
      settingsFile = path.join(config.directories.settings, 'settings.json');

// Define the recursive settings object builds
const buildSettings = function(rules) {
  for ( let prop in rules ) {
    Object.defineProperty(this, prop, {
      get: function() { // jshint ignore:line
        if ( rules[prop] !== null && typeof rules[prop] === 'object' && ! Array.isArray(rules[prop]) )
          return new buildSettings(rules[prop]);
        else
          return rules[prop];
      }
    });
  }
};

// Create a dynamic object
let obj = require(settingsFile);
obj.directory = config.directories.settings;
let settings = new buildSettings(obj);

// Export the object
module.exports = settings;
<|endoftext|>


<commit_before>core.factory("AbstractModel", function($rootScope, $q, $sanitize, $timeout, WsApi, ValidationStore) {

    return function AbstractModel() {

        var abstractModel;

        var mapping;

        var defer = $q.defer();

        var listenCallbacks = [];

        var shadow = {};

        var entityName;

        var validations;

        var validationResults = {};

        $rootScope.$on("$locationChangeSuccess", function() {
            listenCallbacks.length = 0;
        });

        this.fetch = function() {
            if (mapping.instantiate !== undefined) {
                WsApi.fetch(mapping.instantiate).then(function(res) {
                    processResponse(res);
                    listen();
                });
            }
        }

        this.init = function(data, apiMapping) {

            abstractModel = this;

            entityName = abstractModel.constructor.name;

            validations = ValidationStore.getValidations(entityName);

            mapping = apiMapping;

            if (data) {
                setData(data);
            } else {
                if (!mapping.lazy) {
                    this.fetch();
                }
            }

        };

        this.getEntityName = function() {
            return entityName;
        };

        this.getValidations = function() {
            return validations;
        };

        this.getMapping = function() {
            return mapping;
        };

        this.ready = function() {
            return defer.promise;
        };

        this.save = function() {
            var promise = $q(function(resolve) {
                if (abstractModel.dirty()) {
                    angular.extend(mapping.update, {
                        data: abstractModel
                    });
                    WsApi.fetch(mapping.update).then(function(res) {
                        resolve(res);
                    });
                } else {
                    var payload = {};
                    payload[abstractModel.constructor.name] = abstractModel;
                    resolve({
                        body: angular.toJson({
                            payload: payload,
                            meta: {
                                type: "SUCCESS"
                            }
                        })
                    });
                }
            });
            promise.then(function(res) {
                if (angular.fromJson(res.body).meta.type != "INVALID") {
                    angular.extend(abstractModel, angular.fromJson(res.body).payload);
                    shadow = angular.copy(abstractModel);
                }
            });
            return promise;
        };

        this.delete = function() {
            angular.extend(mapping.remove, {
                data: abstractModel
            });
            var promise = WsApi.fetch(mapping.remove);
            promise.then(function(res) {
                if (angular.fromJson(res.body).meta.type == "INVALID") {
                    angular.extend(abstractModel, angular.fromJson(res.body).payload);
                }
            });
            return promise;
        };

        this.listen = function(cb) {
            listenCallbacks.push(cb);
        };

        this.refresh = function() {
            angular.extend(abstractModel, shadow);
        };

        this.dirty = function() {
            return angular.toJson(abstractModel) !== angular.toJson(shadow);
        };

        this.setValidationResults = function(results) {
            angular.extend(validationResults, results);
        };

        this.getValidationResults = function() {
            return validationResults;
        };

        this.clearValidationResults = function() {
            if (validationResults.messages !== undefined) {
                delete validationResults.messages;
            }
        };

        this.update = function(data) {
            angular.extend(abstractModel, data);
            shadow = angular.copy(abstractModel);
        };

        var setData = function(data) {
            angular.extend(abstractModel, data);
            shadow = angular.copy(abstractModel);
            defer.resolve();
        };

        var listen = function() {

            if (abstractModel.id && mapping.listen) {
                angular.extend(mapping.listen, {
                    method: "/" + abstractModel.id
                });
                var notifyPromise = WsApi.listen(mapping.listen);
                notifyPromise.then(null, null, function(res) {
                    processResponse(res);
                    angular.forEach(listenCallbacks, function(cb) {
                        cb(res);
                    });
                });
                return notifyPromise;
            }

        };

        var processResponse = function(res) {

            var resObj = angular.fromJson(res.body);

            var meta = resObj.meta;

            if (meta.type != 'ERROR') {
                var payload = resObj.payload;

                angular.forEach(payload, function(datum) {
                    angular.extend(abstractModel, datum);
                });

                setData(abstractModel);
            } else {
                abstractModel.refresh();
            }

        };

        // additional core level model methods and variables

        return this;

    };

});
<commit_msg>Moved listen to setData.<commit_after>core.factory("AbstractModel", function($rootScope, $q, $sanitize, $timeout, WsApi, ValidationStore) {

    return function AbstractModel() {

        var abstractModel;

        var mapping;

        var defer = $q.defer();

        var listenCallbacks = [];

        var shadow = {};

        var entityName;

        var validations;

        var validationResults = {};

        $rootScope.$on("$locationChangeSuccess", function() {
            listenCallbacks.length = 0;
        });

        this.fetch = function() {
            if (mapping.instantiate !== undefined) {
                WsApi.fetch(mapping.instantiate).then(function(res) {
                    processResponse(res);
                });
            }
        }

        this.init = function(data, apiMapping) {

            abstractModel = this;

            entityName = abstractModel.constructor.name;

            validations = ValidationStore.getValidations(entityName);

            mapping = apiMapping;

            if (data) {
                setData(data);
            } else {
                if (!mapping.lazy) {
                    this.fetch();
                }
            }

        };

        this.getEntityName = function() {
            return entityName;
        };

        this.getValidations = function() {
            return validations;
        };

        this.getMapping = function() {
            return mapping;
        };

        this.ready = function() {
            return defer.promise;
        };

        this.save = function() {
            var promise = $q(function(resolve) {
                if (abstractModel.dirty()) {
                    angular.extend(mapping.update, {
                        data: abstractModel
                    });
                    WsApi.fetch(mapping.update).then(function(res) {
                        resolve(res);
                    });
                } else {
                    var payload = {};
                    payload[abstractModel.constructor.name] = abstractModel;
                    resolve({
                        body: angular.toJson({
                            payload: payload,
                            meta: {
                                type: "SUCCESS"
                            }
                        })
                    });
                }
            });
            promise.then(function(res) {
                if (angular.fromJson(res.body).meta.type != "INVALID") {
                    angular.extend(abstractModel, angular.fromJson(res.body).payload);
                    shadow = angular.copy(abstractModel);
                }
            });
            return promise;
        };

        this.delete = function() {
            angular.extend(mapping.remove, {
                data: abstractModel
            });
            var promise = WsApi.fetch(mapping.remove);
            promise.then(function(res) {
                if (angular.fromJson(res.body).meta.type == "INVALID") {
                    angular.extend(abstractModel, angular.fromJson(res.body).payload);
                }
            });
            return promise;
        };

        this.listen = function(cb) {
            listenCallbacks.push(cb);
        };

        this.refresh = function() {
            angular.extend(abstractModel, shadow);
        };

        this.dirty = function() {
            return angular.toJson(abstractModel) !== angular.toJson(shadow);
        };

        this.setValidationResults = function(results) {
            angular.extend(validationResults, results);
        };

        this.getValidationResults = function() {
            return validationResults;
        };

        this.clearValidationResults = function() {
            if (validationResults.messages !== undefined) {
                delete validationResults.messages;
            }
        };

        this.update = function(data) {
            angular.extend(abstractModel, data);
            shadow = angular.copy(abstractModel);
        };

        var setData = function(data) {
            angular.extend(abstractModel, data);
            shadow = angular.copy(abstractModel);
            listen();
            defer.resolve();
        };

        var listen = function() {

            if (abstractModel.id && mapping.listen) {
                angular.extend(mapping.listen, {
                    method: "/" + abstractModel.id
                });
                var notifyPromise = WsApi.listen(mapping.listen);
                notifyPromise.then(null, null, function(res) {
                    processResponse(res);
                    angular.forEach(listenCallbacks, function(cb) {
                        cb(res);
                    });
                });
                return notifyPromise;
            }

        };

        var processResponse = function(res) {

            var resObj = angular.fromJson(res.body);

            var meta = resObj.meta;

            if (meta.type != 'ERROR') {
                var payload = resObj.payload;

                angular.forEach(payload, function(datum) {
                    angular.extend(abstractModel, datum);
                });

                setData(abstractModel);
            } else {
                abstractModel.refresh();
            }

        };

        // additional core level model methods and variables

        return this;

    };

});
<|endoftext|>


<commit_before>// ```
// recipe.model.js
// (c) 2016 David Newman
// david.r.niciforovic@gmail.com
// recipe.model.js may be freely distributed under the MIT license
// ```

// */app/models/recipe.model.js*

// # Recipe Model

// Note: MongoDB will autogenerate an _id for each Recipe object created

// Grab the Mongoose module
import mongoose from 'mongoose';

// Create a `schema` for the `Todo` object
let recipeSchema = new mongoose.Schema({
  title: { type : String },
  tags: { type: Array },
  rating: { type: Number},
  creator: { type: String},
  description: { type : String },
  ingredients: [{
    amount: {
      type: String
    },

    unit: {
      type: String
    },

    name: {
      type: String
    }
  }],
  directions: { type: Array }
});

// Expose the model so that it can be imported and used in
// the controller (to search, delete, etc.)
export default mongoose.model('Recipe', recipeSchema);
<commit_msg>Prueba de modificacion<commit_after>
import mongoose from 'mongoose';

// Create a `schema` for the `Todo` object
let recipeSchema = new mongoose.Schema({
  title: { type : String },
  tags: { type: Array },
  rating: { type: Number},
  creator: { type: String},
  description: { type : String },
  ingredients: [{
    amount: {
      type: String
    },

    unit: {
      type: String
    },

    name: {
      type: String
    }
  }],
  directions: { type: Array }
});

// Expose the model so that it can be imported and used in
// the controller (to search, delete, etc.)
export default mongoose.model('Recipe', recipeSchema);
<|endoftext|>


<commit_before>'use strict';

angular.module('myApp.Beers', ['ngRoute'])
.config(['$routeProvider', beersConfig])
.controller('BeerListController', BeerListController)
.controller('BeerCreateController', BeerCreateController);

// Config
function beersConfig($routeProvider){
  $routeProvider.when('/beers', {
      templateUrl: 'modules/beers/list.html',
      controller: 'BeerListController'
    });
}
beersConfig['$inject'] = ['$routeProvider'];

// Controllers
function BeerListController($scope, $http) {
  var httpRequest = {
        url: 'http://localhost:3000/api/beers'
      , method: 'GET'
      }
    ;

  $http(httpRequest)
  .success(function(data) {
    console.log('SUCESSO: ', data);
    $scope.beers = data;
    $scope.msg = 'Listagem feita com sucesso.';
  })
  .error(function(err) {
    console.log('ERRO: ', err);
    $scope.msg = 'Listagem não podde ser feita.';

  });

};

function BeerCreateController($scope, $http) {
  var httpRequest = {
        url: 'http://localhost:3000/api/beers'
      , method: 'POST'
      }
    ;

  $http(httpRequest)
  .success(function(data) {
    console.log('SUCESSO: ', data);
    // $scope.beers = data;
    $scope.msg = 'Cadastro da cerveja feito com sucesso.';
  })
  .error(function(err) {
    console.log('ERRO: ', err);
    $scope.msg = 'Cadastro da cerveja não pode ser feito.';

  });

};

BeerListController.$inject = ['$scope', '$http'];
BeerCreateController.$inject = ['$scope', '$http'];

<commit_msg>Subindo controller de create<commit_after>'use strict';

angular.module('myApp.Beers', ['ngRoute'])
.config(['$routeProvider', beersConfig])
.controller('BeerListController', BeerListController)
.controller('BeerCreateController', BeerCreateController);

// Config
function beersConfig($routeProvider){
  $routeProvider
    .when('/beers', {
      templateUrl: 'modules/beers/list.html',
      controller: 'BeerListController'
    })
    .when('/beers/create', {
      templateUrl: 'modules/beers/create.html',
      controller: 'BeerCreateController'
    })
    ;
}
beersConfig['$inject'] = ['$routeProvider'];

// Controllers
function BeerListController($scope, $http) {
  var httpRequest = {
        url: 'http://localhost:3000/api/beers'
      , method: 'GET'
      }
    ;

  $http(httpRequest)
  .success(function(data) {
    console.log('SUCESSO: ', data);
    $scope.beers = data;
    $scope.msg = 'Listagem feita com sucesso.';
  })
  .error(function(err) {
    console.log('ERRO: ', err);
    $scope.msg = 'Listagem não podde ser feita.';

  });

};

function BeerCreateController($scope, $http) {

  $scope.create = function(beer) {
    var httpRequest = {
          url: 'http://localhost:3000/api/beers'
        , method: 'POST'
        , data: beer
        }
      ;

    $http(httpRequest)
    .success(function(data) {
      console.log('SUCESSO: ', data);
      // $scope.beers = data;
      $scope.msg = 'Cadastro da cerveja feito com sucesso.';
    })
    .error(function(err) {
      console.log('ERRO: ', err);
      $scope.msg = 'Cadastro da cerveja não pode ser feito.';

    });
  }

};

BeerListController.$inject = ['$scope', '$http'];
BeerCreateController.$inject = ['$scope', '$http'];

<|endoftext|>


<commit_before>var filewalker  = require('filewalker');
var path        = require('path');
var fs          = require('fs');
var exec        = require('child_process').exec;
var deferred    = require('deferred');
var extend      = require('extend');
/**
 *
 * @param command
 * @param onSuccess
 * @param onError
 */
function execute(command,params){
	var def = deferred();
	console.log([command,params].join(' '));
	exec([command,params].join(' '), function(error,stdout){
		if (error !== null)
			def.reject(error);
		else
			def.resolve(stdout);
	});
	return def.promise;
};
/**
 *
 * @param p
 * @returns {*}
 */
function xGetText( p ) {
    var o  = [];
    o.push('--force-po');
    if(p.charset){
        o.push(['--from-code=', p.charset].join(''));
    }
    if(p.language){
        o.push(['--language=', p.language].join(''));
    }
    if(p.directory){
        o.push('-d');
        o.push(p.directory);
    }
    o.push('-o');
    o.push(p.potfile);
    if(p.keywords){
        p.keywords.forEach(function (keyword) {
            o.push('--keyword='+keyword);
        });
    }
    o.push(p.files.join(' '));
    return execute('xgettext', o.join(' '));
};
/**
 *
 * @param target
 * @param folders
 * @returns {*}
 */
function createFolders(target, folders ){
    folders.forEach(function(item){
        target = path.join(target,item);
        if(!fs.existsSync(target)) fs.mkdirSync(target);
    });
    return target;
};
/**
 *
 * @param filePath
 * @param onSuccess
 */
function removeFile( filePath ) {
    return execute('rm',['-f',filePath].join(' '));
};
/**
 *
 * @param options
 * @param input
 * @param output
 */
function msgAttrib(options,input,output) {
	return execute('msgattrib',[options,'-o',output||input,input].join(' '));
};
/**
 *
 * @param pofile
 * @param potfile
 * @returns {*}
 */
function msgMerge(pofile,potfile){
    var def = deferred();
    fs.open(pofile,'r',function (po){
        var o,c;
        if (po !== null) {
            c = 'cp';
            o = [];
            o.push(potfile);
            o.push(pofile);
        }
        else {
            c = 'msgmerge';
            o = ['-q','-U','--no-fuzzy-matching','--previous'];
            o.push(pofile);
            o.push(potfile);
        }
        execute(c, o.join(' ') ).then(function(){
            def.resolve();
        },function(e){
            def.reject(e);
        });
    });
    return def.promise;
};

function msgFmt(pofile,mofile){
    var def = deferred();
    var opt = [pofile,'-o',mofile];
    execute('msgfmt', opt.join(' ')).then(function(){
        def.resolve();
    },function(e){
        def.reject(e);
    });
    return def;
}

function findFiles(source){
	var files  = [];
	var result = deferred();
	var source = typeof(source)=='string' ? [source] : source ;
	deferred.map(source,function(folder){
		var def = deferred();
		filewalker( folder ).on('file',function(p){
			files.push(path.join(folder,p));
		}).on('done',function(){
			def.resolve();
		}).on('error', function(err){
			def.reject(err);
		}).walk();
		return def.promise;
	}).then(function(){
		result.resolve(files);
	});
	return result.promise;
};

/**
 *
 * @param options
 */
function GetTextGenerator(options){
    var locales   = options.locales  || [];
    var keywords  = options.keywords || [];
	var defer     = deferred();
	findFiles(options.source).then(function(files){
		deferred.map(locales,function(locale) {
			var folder  = createFolders( options.target , [ locale , 'LC_MESSAGES' ] );
			var potfile = path.join( folder , [options.name,'pot'].join('.') );
			var pofile  = path.join( folder , [options.name,'po'].join('.') );
			var tmpfile = path.join( folder , [options.name,'tmp'].join('.') );
			var mofile  = path.join( folder , [options.name,'mo'].join('.') );
			return removeFile( potfile ).then(function(){
				return xGetText({
					potfile   : potfile ,
					keywords  : keywords ,
					files     : files ,
					language  : options.language,
					charset   : options.charset
				});
			}).then(function(){
				return msgMerge(pofile,potfile);
			}).then(function(){
				return msgAttrib('--untranslated',pofile,tmpfile);
			}).then(function(){
				return msgFmt(pofile,mofile);
			}).then(function(){
				return removeFile(potfile);
			});
		})(function(){
			defer.resolve();
		});
    });
	return defer.promise;
};

function Generator(options){
    return GetTextGenerator(extend({
        name:'base',
        language:'JavaScript',
        charset:'UTF-8',
        keywords:[],
        source:['.'],
        target:'.',
        locales:[]
    },options));
};

Generator.msgMerge   = msgMerge;
Generator.msgAttrib  = msgAttrib;
Generator.msgFmt     = msgFmt;
Generator.removeFile = removeFile;

module.exports = Generator;<commit_msg>add function to module<commit_after>var filewalker  = require('filewalker');
var path        = require('path');
var fs          = require('fs');
var exec        = require('child_process').exec;
var deferred    = require('deferred');
var extend      = require('extend');
/**
 *
 * @param command
 * @param onSuccess
 * @param onError
 */
function execute(command,params){
	var def = deferred();
	console.log([command,params].join(' '));
	exec([command,params].join(' '), function(error,stdout){
		if (error !== null)
			def.reject(error);
		else
			def.resolve(stdout);
	});
	return def.promise;
};
/**
 *
 * @param p
 * @returns {*}
 */
function xGetText( p ) {
    var o  = [];
    o.push('--force-po');
    if(p.charset){
        o.push(['--from-code=', p.charset].join(''));
    }
    if(p.language){
        o.push(['--language=', p.language].join(''));
    }
    if(p.directory){
        o.push('-d');
        o.push(p.directory);
    }
    o.push('-o');
    o.push(p.potfile);
    if(p.keywords){
        p.keywords.forEach(function (keyword) {
            o.push('--keyword='+keyword);
        });
    }
    o.push(p.files.join(' '));
    return execute('xgettext', o.join(' '));
};
/**
 *
 * @param target
 * @param folders
 * @returns {*}
 */
function createFolders(target, folders ){
    folders.forEach(function(item){
        target = path.join(target,item);
        if(!fs.existsSync(target)) fs.mkdirSync(target);
    });
    return target;
};
/**
 *
 * @param filePath
 * @param onSuccess
 */
function removeFile( filePath ) {
    return execute('rm',['-f',filePath].join(' '));
};
/**
 *
 * @param options
 * @param input
 * @param output
 */
function msgAttrib(options,input,output) {
	return execute('msgattrib',[options,'-o',output||input,input].join(' '));
};
/**
 *
 * @param pofile
 * @param potfile
 * @returns {*}
 */
function msgMerge(pofile,potfile){
    var def = deferred();
    fs.open(pofile,'r',function (po){
        var o,c;
        if (po !== null) {
            c = 'cp';
            o = [];
            o.push(potfile);
            o.push(pofile);
        }
        else {
            c = 'msgmerge';
            o = ['-q','-U','--no-fuzzy-matching','--previous'];
            o.push(pofile);
            o.push(potfile);
        }
        execute(c, o.join(' ') ).then(function(){
            def.resolve();
        },function(e){
            def.reject(e);
        });
    });
    return def.promise;
};

function msgFmt(pofile,mofile){
    var def = deferred();
    var opt = [pofile,'-o',mofile];
    execute('msgfmt', opt.join(' ')).then(function(){
        def.resolve();
    },function(e){
        def.reject(e);
    });
    return def;
}

function findFiles(source){
	var files  = [];
	var result = deferred();
	var source = typeof(source)=='string' ? [source] : source ;
	deferred.map(source,function(folder){
		var def = deferred();
		filewalker( folder ).on('file',function(p){
			files.push(path.join(folder,p));
		}).on('done',function(){
			def.resolve();
		}).on('error', function(err){
			def.reject(err);
		}).walk();
		return def.promise;
	}).then(function(){
		result.resolve(files);
	});
	return result.promise;
};

/**
 *
 * @param options
 */
function GetTextGenerator(options){
    var locales   = options.locales  || [];
    var keywords  = options.keywords || [];
	var defer     = deferred();
	findFiles(options.source).then(function(files){
		deferred.map(locales,function(locale) {
			var folder  = createFolders( options.target , [ locale , 'LC_MESSAGES' ] );
			var potfile = path.join( folder , [options.name,'pot'].join('.') );
			var pofile  = path.join( folder , [options.name,'po'].join('.') );
			var tmpfile = path.join( folder , [options.name,'tmp'].join('.') );
			var mofile  = path.join( folder , [options.name,'mo'].join('.') );
			return removeFile( potfile ).then(function(){
				return xGetText({
					potfile   : potfile ,
					keywords  : keywords ,
					files     : files ,
					language  : options.language,
					charset   : options.charset
				});
			}).then(function(){
				return msgMerge(pofile,potfile);
			}).then(function(){
				return msgAttrib('--untranslated',pofile,tmpfile);
			}).then(function(){
				return msgFmt(pofile,mofile);
			}).then(function(){
				return removeFile(potfile);
			});
		})(function(){
			defer.resolve();
		});
    });
	return defer.promise;
};

function Generator(options){
    return GetTextGenerator(extend({
        name:'base',
        language:'JavaScript',
        charset:'UTF-8',
        keywords:[],
        source:['.'],
        target:'.',
        locales:[]
    },options));
};

Generator.msgMerge   = msgMerge;
Generator.msgAttrib  = msgAttrib;
Generator.msgFmt     = msgFmt;
Generator.removeFile = removeFile;
Generator.execute    = execute;

module.exports = Generator;<|endoftext|>