<commit_before>'use strict';

var $ = require('streamhub-sdk/jquery');
var ContentListView = require('streamhub-sdk/content/views/content-list-view');
var forEach = require('mout/array/forEach');
var inherits = require('inherits');
var L = require('livefyre-map/leaflet/main');
var PackageAttribute = require('livefyre-map/package-attribute');

/**
 * A view to visualize StreamHub content on a map.
 * @constructor
 * @param [opts] {Object} Configuration options for the MapView
 * @param [opts.leafletMapOptions] {Object} An object representing the options
 *   passed into the creation of a Leaflet Map (L.Map)
 * @param [opts.mapboxTileOptions] {number} The mapbox map id and other tile options
 */
function MapView(opts) {
  opts = opts || {};

  this._id = new Date().getTime();
  this._mapboxTileOptions = opts.mapboxTileOptions || {};
  this._mapboxTileOptions.mapId = this._mapboxTileOptions.mapId || 'examples.map-i86nkdio';
  this._mapboxTileOptions.format = this._mapboxTileOptions.format || 'png';
  this._leafletMapOptions = opts.leafletMapOptions || {};

  this._overlayViews = [];
  this._dataPoints = [];
  this._elClass = 'hub-map-view hub-map-view-' + this._id;

  ContentListView.call(this, opts);

  this.el && PackageAttribute.decorate(this.el);

  if (this.modal) {
    PackageAttribute.decorateModal(this.modal);
    this.modal.$el.attr(opts.prefix, opts.uuid);
  }

  this._drawMap();
};
inherits(MapView, ContentListView);

/**
 * The URL for tile images being loaded.
 * @const {string}
 */
var TILE_URL = 'https://{s}.tiles.mapbox.com/{version}/{mapId}/{z}/{x}/{y}.{format}';

/**
 * Draw the map and add a tile layer.
 * @private
 */
MapView.prototype._drawMap = function() {
  this._map = new L.Map(this.el, this._leafletMapOptions).setView(
    this._leafletMapOptions.center || [0,0],
    this._leafletMapOptions.zoom || 2
  );

  this._map.attributionControl
    .setPrefix('')
    .addAttribution("© OpenStreetMap");

  this._tileLayer = new L.TileLayer(this._getVersionedTileURL(), {
    mapId: this._mapboxTileOptions.mapId,
    format: this._mapboxTileOptions.format
  }).addTo(this._map);
};

/**
 * Create a LagLng object from a point.
 * @param {ContentPoint} point The point to convert.
 * @return {L.LatLng}
 * @private
 */
MapView.prototype._getLatLngFromPoint = function(point) {
  return new L.LatLng(point.lat, point.lon);
};

/**
 * Gets a versioned tile URL based on the config options.
 * @return {string}
 * @private
 */
MapView.prototype._getVersionedTileURL = function() {
  var accessToken = this._mapboxTileOptions.accessToken;
  if (!accessToken) {
    return TILE_URL.replace('{version}', 'v3');
  }
  return [TILE_URL.replace('{version}', 'v4'), '?access_token=', accessToken].join('');
};

/**
 * Add a Point instance to be visualized on the map
 * @param {Point} point The point to be visualized on the map
 */
MapView.prototype.add = function(point) {
  this._dataPoints.push(point);
  this.$el.trigger('addDataPoint.hub', point);
};

/**
 * Add the marker to the map.
 * @param {L.Marker} marker The marker to add to the map.
 */
MapView.prototype.addMarkerToMap = function(marker) {
  marker.addTo(this._map);
};

/**
 * Create a marker for a specific data point.
 * @param {ContentPoint} dataPoint The point to create.
 * @return {L.Marker} The marker based on the data point.
 */
MapView.prototype.createMarker = function(dataPoint) {
  return new L.Marker(this._getLatLngFromPoint(dataPoint));
};

/** @override */
MapView.prototype.destroy = function() {
  this._map && this._map.remove();
  this._map = null;
  ContentListView.prototype.destroy.call(this);
};

/**
 * Draw the marker on the map.
 * @param {ContentPoint} dataPoint The data point to draw on the map.
 * @return {L.Marker}
 */
MapView.prototype.drawMarker = function(dataPoint) {
  var marker = this.createMarker(dataPoint);
  marker && this.addMarkerToMap(marker);
  return marker;
};

/**
 * Remove a data point from the map.
 * @param {ContentPoint} dataPoint The data point to remove.
 */
MapView.prototype.removeDataPoint = function(dataPoint) {
  var index = this._dataPoints.indexOf(dataPoint);
  if (index === -1) {
    return;
  }
  this._dataPoints.splice(index, 1);
  this.$el.trigger('removeDataPoint.hub');
};

/**
 * Set the element that the map view will use.
 * @param {Element} el The element to set.
 * @override
 */
MapView.prototype.setElement = function(el) {
  ContentListView.prototype.setElement.call(this, el);
  this.$el.addClass(this._elClass);

  var self = this;

  this.$el.on('imageError.hub', function (evt) {
    var badImageSrc = $(evt.target).attr('src');
    var dataPoint;
    forEach(self._dataPoints, function (dataPoint) {
      if (!dataPoint || typeof dataPoint.getContent !== 'function') {
        return;
      }
      var content = dataPoint.getContent() || {};
      var author = content.author || {};
      var attachments = content.attachments || [];
      var firstAttachment = attachments[0] || {};
      // Either the attachment or the avatar is bad. Check the bad image src
      // against both of them and remove if one of them match.
      if ([firstAttachment.thumbnail_url, author.avatar].indexOf(badImageSrc) > -1) {
        self.removeDataPoint(dataPoint);
      }
    });
  });

  this.$el.on('addDataPoint.hub', function (evt, dataPoint) {
    self.drawMarker(dataPoint);
  });
};

module.exports = MapView;
<commit_msg>Use a non-broken non-prod mapId<commit_after>'use strict';

var $ = require('streamhub-sdk/jquery');
var ContentListView = require('streamhub-sdk/content/views/content-list-view');
var forEach = require('mout/array/forEach');
var inherits = require('inherits');
var L = require('livefyre-map/leaflet/main');
var PackageAttribute = require('livefyre-map/package-attribute');

/**
 * A view to visualize StreamHub content on a map.
 * @constructor
 * @param [opts] {Object} Configuration options for the MapView
 * @param [opts.leafletMapOptions] {Object} An object representing the options
 *   passed into the creation of a Leaflet Map (L.Map)
 * @param [opts.mapboxTileOptions] {number} The mapbox map id and other tile options
 */
function MapView(opts) {
  opts = opts || {};

  this._id = new Date().getTime();
  this._mapboxTileOptions = opts.mapboxTileOptions || {};
  this._mapboxTileOptions.mapId = this._mapboxTileOptions.mapId || 'bengoering.f7a2fe08';
  this._mapboxTileOptions.format = this._mapboxTileOptions.format || 'png';
  this._leafletMapOptions = opts.leafletMapOptions || {};

  this._overlayViews = [];
  this._dataPoints = [];
  this._elClass = 'hub-map-view hub-map-view-' + this._id;

  ContentListView.call(this, opts);

  this.el && PackageAttribute.decorate(this.el);

  if (this.modal) {
    PackageAttribute.decorateModal(this.modal);
    this.modal.$el.attr(opts.prefix, opts.uuid);
  }

  this._drawMap();
};
inherits(MapView, ContentListView);

/**
 * The URL for tile images being loaded.
 * @const {string}
 */
var TILE_URL = 'https://{s}.tiles.mapbox.com/{version}/{mapId}/{z}/{x}/{y}.{format}';

/**
 * Draw the map and add a tile layer.
 * @private
 */
MapView.prototype._drawMap = function() {
  this._map = new L.Map(this.el, this._leafletMapOptions).setView(
    this._leafletMapOptions.center || [0,0],
    this._leafletMapOptions.zoom || 2
  );

  this._map.attributionControl
    .setPrefix('')
    .addAttribution("© OpenStreetMap");

  this._tileLayer = new L.TileLayer(this._getVersionedTileURL(), {
    mapId: this._mapboxTileOptions.mapId,
    format: this._mapboxTileOptions.format
  }).addTo(this._map);
};

/**
 * Create a LagLng object from a point.
 * @param {ContentPoint} point The point to convert.
 * @return {L.LatLng}
 * @private
 */
MapView.prototype._getLatLngFromPoint = function(point) {
  return new L.LatLng(point.lat, point.lon);
};

/**
 * Gets a versioned tile URL based on the config options.
 * @return {string}
 * @private
 */
MapView.prototype._getVersionedTileURL = function() {
  var accessToken = this._mapboxTileOptions.accessToken;
  if (!accessToken) {
    return TILE_URL.replace('{version}', 'v3');
  }
  return [TILE_URL.replace('{version}', 'v4'), '?access_token=', accessToken].join('');
};

/**
 * Add a Point instance to be visualized on the map
 * @param {Point} point The point to be visualized on the map
 */
MapView.prototype.add = function(point) {
  this._dataPoints.push(point);
  this.$el.trigger('addDataPoint.hub', point);
};

/**
 * Add the marker to the map.
 * @param {L.Marker} marker The marker to add to the map.
 */
MapView.prototype.addMarkerToMap = function(marker) {
  marker.addTo(this._map);
};

/**
 * Create a marker for a specific data point.
 * @param {ContentPoint} dataPoint The point to create.
 * @return {L.Marker} The marker based on the data point.
 */
MapView.prototype.createMarker = function(dataPoint) {
  return new L.Marker(this._getLatLngFromPoint(dataPoint));
};

/** @override */
MapView.prototype.destroy = function() {
  this._map && this._map.remove();
  this._map = null;
  ContentListView.prototype.destroy.call(this);
};

/**
 * Draw the marker on the map.
 * @param {ContentPoint} dataPoint The data point to draw on the map.
 * @return {L.Marker}
 */
MapView.prototype.drawMarker = function(dataPoint) {
  var marker = this.createMarker(dataPoint);
  marker && this.addMarkerToMap(marker);
  return marker;
};

/**
 * Remove a data point from the map.
 * @param {ContentPoint} dataPoint The data point to remove.
 */
MapView.prototype.removeDataPoint = function(dataPoint) {
  var index = this._dataPoints.indexOf(dataPoint);
  if (index === -1) {
    return;
  }
  this._dataPoints.splice(index, 1);
  this.$el.trigger('removeDataPoint.hub');
};

/**
 * Set the element that the map view will use.
 * @param {Element} el The element to set.
 * @override
 */
MapView.prototype.setElement = function(el) {
  ContentListView.prototype.setElement.call(this, el);
  this.$el.addClass(this._elClass);

  var self = this;

  this.$el.on('imageError.hub', function (evt) {
    var badImageSrc = $(evt.target).attr('src');
    var dataPoint;
    forEach(self._dataPoints, function (dataPoint) {
      if (!dataPoint || typeof dataPoint.getContent !== 'function') {
        return;
      }
      var content = dataPoint.getContent() || {};
      var author = content.author || {};
      var attachments = content.attachments || [];
      var firstAttachment = attachments[0] || {};
      // Either the attachment or the avatar is bad. Check the bad image src
      // against both of them and remove if one of them match.
      if ([firstAttachment.thumbnail_url, author.avatar].indexOf(badImageSrc) > -1) {
        self.removeDataPoint(dataPoint);
      }
    });
  });

  this.$el.on('addDataPoint.hub', function (evt, dataPoint) {
    self.drawMarker(dataPoint);
  });
};

module.exports = MapView;
<|endoftext|>


<commit_before>
/* RedisStorage */

function RedisStorage(app, config) {

  /** { host: 'localhost',
        port: 6379,
        db: 1,
        pass: 'password'
      } */

  this.constructor.prototype.__construct.call(this, app, config);

}

/* RedisStorage::prototype */

framework.extend(RedisStorage.prototype, framework.storageProto);

framework.extend(RedisStorage.prototype, new function() {

  var redis = require('redis'),
      util = require('util');

  this.options = {
    // Parser defaults to hiredis if installed
  }

  // Constructor
  this.__construct = function(app, config) {
    var self = this;
    this.app = app;
    this.config = config || {};
    this.className = this.constructor.name;

    // Set redis client
    this.client = redis.createClient(config.port, config.host, this.options);

    // Authenticate if password provided
    if (typeof config.pass == 'string') {
      client.auth(config.pass, function(err, res) {
        if (err) throw err;
      })
    }

    // Handle error event
    this.client.on('error', function(err) {
      app.log(err);
    });

    // Select db if specified
    if (typeof config.db == 'number' && config.db !== 0) {
      self.client.select(config.db, function(err, res) {
        if (err) throw err;
      });
    }

    // Set enumerable properties
    framework.util.onlySetEnumerable(this, ['className', 'config']);
  }

  /** Storage API get */

  this.get = function(key, callback) {
    var self = this;

    // If key is a string
    if (typeof key == 'string') {

      this.client.get(key, function(err, data) {
        if (err) callback.call(self, err, null);
        else {
          callback.call(self, null, data);
        }
      })

    // If key is an array
    } else if (util.isArray(key)) {

      var i, out = {}, keys = key,
          multi = this.client.multi();

      for (i=0; i < keys.length; i++) {
        multi.get(keys[i]);
      }

      multi.exec(function(err, data) {
        if (err) callback.call(self, err, null);
        else {
          for (i=0; i < keys.length; i++) {
            out[keys[i]] = data[i];
          }
          callback.call(self, null, out);
        }
      })
    }
  }

  /** Storage API getHash */

  this.getHash = function(key, callback) {
    var self = this;
    this.client.hgetall(key, function(err, data) {
      if (err) callback.call(self, err, null);
      else {
        callback.call(self, null, data);
      }
    })
  }

  /** Storage API set */

  this.set = function(key, value, callback) {
    var self = this;

    // If key is a string
    if (typeof key == 'string') {

      // Set single value
      this.client.set(key, value, function(err, data) {
        if (err) callback.call(self, err);
        else {
          callback.call(self, null);
        }
      });

    // If key is an array
    } else if (typeof key == 'object') {

      // Set multiple values
      var object = key,
          callback = value,
          multi = this.client.multi();

      for (key in object) {
        multi.set(key, object[key]);
      }

      multi.exec(function(err, data) {
        if (err) callback.call(self, err);
        else {
          callback.call(self, null);
        }
      });

    }
  }

  /** Storage API setHash */

  this.setHash = function(key, object, callback) {
    var self = this;
    this.client.hmset(key, object, function(err, data) {
      if (err) callback.call(self, err);
      else {
        callback.call(self, null);
      }
    });
  }

  /** Storage API delete */

  this.delete = function(key, callback) {
    var self = this;

    // If key is a string
    if (typeof key == 'string') {

      this.client.del(key, function(err, data) {
        if (err) callback.call(self, err);
        else {
          callback.call(self, null);
        }
      });

    // If key is an array
    } else if (util.isArray(key)) {
      var i, keys = key,
          multi = this.client.multi();

      for (i=0; i < keys.length; i++) {
        multi.del(keys[i]);
      }

      multi.exec(function(err, data) {
        if (err) callback.call(self, err);
        else {
          callback.call(self, null);
        }
      });

    }
  }

});

module.exports = RedisStorage;
<commit_msg>Semicolons<commit_after>
/* RedisStorage */

function RedisStorage(app, config) {

  /** { host: 'localhost',
        port: 6379,
        db: 1,
        pass: 'password'
      } */

  this.constructor.prototype.__construct.call(this, app, config);

}

/* RedisStorage::prototype */

framework.extend(RedisStorage.prototype, framework.storageProto);

framework.extend(RedisStorage.prototype, new function() {

  var redis = require('redis'),
      util = require('util');

  this.options = {
    // Parser defaults to hiredis if installed
  }

  // Constructor
  this.__construct = function(app, config) {
    var self = this;
    this.app = app;
    this.config = config || {};
    this.className = this.constructor.name;

    // Set redis client
    this.client = redis.createClient(config.port, config.host, this.options);

    // Authenticate if password provided
    if (typeof config.pass == 'string') {
      client.auth(config.pass, function(err, res) {
        if (err) throw err;
      });
    }

    // Handle error event
    this.client.on('error', function(err) {
      app.log(err);
    });

    // Select db if specified
    if (typeof config.db == 'number' && config.db !== 0) {
      self.client.select(config.db, function(err, res) {
        if (err) throw err;
      });
    }

    // Set enumerable properties
    framework.util.onlySetEnumerable(this, ['className', 'config']);
  }

  /** Storage API get */

  this.get = function(key, callback) {
    var self = this;

    // If key is a string
    if (typeof key == 'string') {

      this.client.get(key, function(err, data) {
        if (err) callback.call(self, err, null);
        else {
          callback.call(self, null, data);
        }
      });

    // If key is an array
    } else if (util.isArray(key)) {

      var i, out = {}, keys = key,
          multi = this.client.multi();

      for (i=0; i < keys.length; i++) {
        multi.get(keys[i]);
      }

      multi.exec(function(err, data) {
        if (err) callback.call(self, err, null);
        else {
          for (i=0; i < keys.length; i++) {
            out[keys[i]] = data[i];
          }
          callback.call(self, null, out);
        }
      });
    }
  }

  /** Storage API getHash */

  this.getHash = function(key, callback) {
    var self = this;
    this.client.hgetall(key, function(err, data) {
      if (err) callback.call(self, err, null);
      else {
        callback.call(self, null, data);
      }
    });
  }

  /** Storage API set */

  this.set = function(key, value, callback) {
    var self = this;

    // If key is a string
    if (typeof key == 'string') {

      // Set single value
      this.client.set(key, value, function(err, data) {
        if (err) callback.call(self, err);
        else {
          callback.call(self, null);
        }
      });

    // If key is an array
    } else if (typeof key == 'object') {

      // Set multiple values
      var object = key,
          callback = value,
          multi = this.client.multi();

      for (key in object) {
        multi.set(key, object[key]);
      }

      multi.exec(function(err, data) {
        if (err) callback.call(self, err);
        else {
          callback.call(self, null);
        }
      });

    }
  }

  /** Storage API setHash */

  this.setHash = function(key, object, callback) {
    var self = this;
    this.client.hmset(key, object, function(err, data) {
      if (err) callback.call(self, err);
      else {
        callback.call(self, null);
      }
    });
  }

  /** Storage API delete */

  this.delete = function(key, callback) {
    var self = this;

    // If key is a string
    if (typeof key == 'string') {

      this.client.del(key, function(err, data) {
        if (err) callback.call(self, err);
        else {
          callback.call(self, null);
        }
      });

    // If key is an array
    } else if (util.isArray(key)) {
      var i, keys = key,
          multi = this.client.multi();

      for (i=0; i < keys.length; i++) {
        multi.del(keys[i]);
      }

      multi.exec(function(err, data) {
        if (err) callback.call(self, err);
        else {
          callback.call(self, null);
        }
      });

    }
  }

});

module.exports = RedisStorage;
<|endoftext|>


<commit_before><commit_msg>fix assets<commit_after><|endoftext|>


<commit_before>
var reserved = ["break","default","function","return","var","case","delete","if","switch","void","catch","do","in","this","while","const","else","instanceof","throw","with","continue","finally","let","try","debugger","for","new","typeof"];//reserved words cannot be used for property names

//Make a dictionary from text
function popDictJS(txt){
	//Takes a String, builds dictionary of all words in the file mapped to their counts. Returns dictionary.
	var user = {};
	var words = txt.split(" ");
	//remove any reserved words (I could remove the frequent words here too)
	var finalWords = [];
	for (i=0; i<words.length; i++){
		var safeWord = true;
		for (j=0; j<reserved.length; j++){
			if (words[i]==reserved[j]){
				safeWord = false;
				break;
			}
		}
		if (safeWord){
			finalWords.push(words[i]);
		}
	}
	//remove . , ? ! : ; ) (  and  eol  and  make lowercase
	for (i=0; i<finalWords.length; i++){
		var word = finalWords[i];
		word = word.replace(/(\r\n|\n|\r)/gm,"");
		if (word.length>1){
			if (word.charAt(word.length-1) == "." || word.charAt(word.length-1) == "," || word.charAt(word.length-1) == "!" || word.charAt(word.length-1) == "?" || word.charAt(word.length-1) == ":" || word.charAt(word.length-1) == ";" || word.charAt(word.length-1) == ")"){
				//console.log("Found . , ? ! : ; in "+word);
				finalWords[i] = word.substr(0,word.length-1);
			}
			if(word.charAt(0) == "("){
				finalWords[i] = word.substr(1,word.length);
			}
		}
		finalWords[i] = finalWords[i].toLowerCase();
	}

	//put counts in dict
	for (i=0; i<finalWords.length; i++){
		var hf = false;
		for (w=0;w<highFreq.length;w++){
			if (highFreq[w] == finalWords[i]){
				hf=true;
				}
			}
		if (hf==false){
			if (user[finalWords[i]] == undefined){
				user[finalWords[i]] = 1;
			}
			else{
				user[finalWords[i]] += 1;
			}
		}
	}
	//divide counts by total
	var total = 0;
	for (var word in user) {
		total += user[word];
	}
	for (var word in user){
		user[word] = user[word]/total;
	}

	return user;
}

//compare vector with python-generated dictionaries in supplements.js
function categorize(input, option1, option2){
	//Find all the words in all the dictionaries, so each dict can be filled out for all words
	var allWords = $.extend({},input, option1, option2);
	//console.log("input: "+Object.keys(input).length);
	//console.log("option1: "+Object.keys(option1).length);
	//console.log("option2: "+Object.keys(option2).length);
	//console.log("allWords: "+Object.keys(allWords).length);
	//console.log("---");

	//make vectors with counts for all words`
	var vectorInput = [];
	var vectorOption1 = [];
	var vectorOption2 = [];
	for(var key in allWords) {
		//console.log("input key-val: "+key+"-"+input[key]);
		//console.log("option1 key-val: "+key+"-"+option1[key]);
		//console.log("option2 key-val: "+key+"-"+option2[key]);
		if (input[key]>=0){
			vectorInput.push(input[key]);
		}
		else if (input[key]==undefined){
			vectorInput.push(0);
		}
		if (option1[key]>=0){
			vectorOption1.push(option1[key]);
		}
		else if (option1[key]==undefined){
			vectorOption1.push(0);
		}
		if (option2[key]>=0){
			vectorOption2.push(option2[key]);
		}
		else if (option2[key]==undefined){
			vectorOption2.push(0);
		}
	}
	//console.log("input: "+vectorInput.length);
	//console.log("       "+vectorInput);
	//console.log("Option1: "+vectorOption1.length);
	//console.log("         "+vectorOption1);
	//console.log("Option2: "+vectorOption2.length);
	//console.log("         "+vectorOption2);

	//calculate cos
	var cos1 = math.dot(vectorOption1,vectorInput)/(math.norm(vectorOption1)*math.norm(vectorInput));
    var cos2 = math.dot(vectorOption2,vectorInput)/(math.norm(vectorOption2)*math.norm(vectorInput));

   //make output
	var winnerString = "";
    if (cos1 > cos2){
		winnerString += "
Your text most matches Kirk!
";
	}
	else if(cos1 < cos2){
		winnerString += "
Your text most matches Spock!
";
	}
	else{
		winnerString += "It's a tie!";
	}

	winnerString += "
Kirk's cos = "+cos1+"
";
	winnerString += "
Spock's cos = "+cos2+"
";
	winnerString += "
Biggest cosine / smallest angle wins
";

	var counter = 0;
	winnerString +="
";//add borders to hd, td...
	winnerString +="
Word	Kirk	you	Spock
";
	for (var word in allWords){
		winnerString +="
";
		winnerString += ""+word+"	";
		winnerString += ""+vectorOption1[counter]+"	";
		winnerString += ""+vectorInput[counter]+"	";
		winnerString += ""+vectorOption2[counter]+"	";
		winnerString +="
";
		counter +=1;
	}
	winnerString +="
";

	//make output div visible
	document.getElementById("inoutput").style.visibility = "visible";

	return winnerString;
}

//Give results
function returnResults(){
	var userTxt = document.getElementById("input").value;
	var input = popDictJS(userTxt);
	document.getElementById("output").innerHTML = categorize(input, dictKirk, dictSpock);
	//document.getElementById("output").innerHTML = categorize(input, dictTest1, dictTest2);
	document.getElementById("inputAgain").innerHTML = userTxt;
}
<commit_msg>Add table borders<commit_after>
var reserved = ["break","default","function","return","var","case","delete","if","switch","void","catch","do","in","this","while","const","else","instanceof","throw","with","continue","finally","let","try","debugger","for","new","typeof"];//reserved words cannot be used for property names

//Make a dictionary from text
function popDictJS(txt){
	//Takes a String, builds dictionary of all words in the file mapped to their counts. Returns dictionary.
	var user = {};
	var words = txt.split(" ");
	//remove any reserved words (I could remove the frequent words here too)
	var finalWords = [];
	for (i=0; i<words.length; i++){
		var safeWord = true;
		for (j=0; j<reserved.length; j++){
			if (words[i]==reserved[j]){
				safeWord = false;
				break;
			}
		}
		if (safeWord){
			finalWords.push(words[i]);
		}
	}
	//remove . , ? ! : ; ) (  and  eol  and  make lowercase
	for (i=0; i<finalWords.length; i++){
		var word = finalWords[i];
		word = word.replace(/(\r\n|\n|\r)/gm,"");
		if (word.length>1){
			if (word.charAt(word.length-1) == "." || word.charAt(word.length-1) == "," || word.charAt(word.length-1) == "!" || word.charAt(word.length-1) == "?" || word.charAt(word.length-1) == ":" || word.charAt(word.length-1) == ";" || word.charAt(word.length-1) == ")"){
				//console.log("Found . , ? ! : ; in "+word);
				finalWords[i] = word.substr(0,word.length-1);
			}
			if(word.charAt(0) == "("){
				finalWords[i] = word.substr(1,word.length);
			}
		}
		finalWords[i] = finalWords[i].toLowerCase();
	}

	//put counts in dict
	for (i=0; i<finalWords.length; i++){
		var hf = false;
		for (w=0;w<highFreq.length;w++){
			if (highFreq[w] == finalWords[i]){
				hf=true;
				}
			}
		if (hf==false){
			if (user[finalWords[i]] == undefined){
				user[finalWords[i]] = 1;
			}
			else{
				user[finalWords[i]] += 1;
			}
		}
	}
	//divide counts by total
	var total = 0;
	for (var word in user) {
		total += user[word];
	}
	for (var word in user){
		user[word] = user[word]/total;
	}

	return user;
}

//compare vector with python-generated dictionaries in supplements.js
function categorize(input, option1, option2){
	//Find all the words in all the dictionaries, so each dict can be filled out for all words
	var allWords = $.extend({},input, option1, option2);
	//console.log("input: "+Object.keys(input).length);
	//console.log("option1: "+Object.keys(option1).length);
	//console.log("option2: "+Object.keys(option2).length);
	//console.log("allWords: "+Object.keys(allWords).length);
	//console.log("---");

	//make vectors with counts for all words`
	var vectorInput = [];
	var vectorOption1 = [];
	var vectorOption2 = [];
	for(var key in allWords) {
		//console.log("input key-val: "+key+"-"+input[key]);
		//console.log("option1 key-val: "+key+"-"+option1[key]);
		//console.log("option2 key-val: "+key+"-"+option2[key]);
		if (input[key]>=0){
			vectorInput.push(input[key]);
		}
		else if (input[key]==undefined){
			vectorInput.push(0);
		}
		if (option1[key]>=0){
			vectorOption1.push(option1[key]);
		}
		else if (option1[key]==undefined){
			vectorOption1.push(0);
		}
		if (option2[key]>=0){
			vectorOption2.push(option2[key]);
		}
		else if (option2[key]==undefined){
			vectorOption2.push(0);
		}
	}
	//console.log("input: "+vectorInput.length);
	//console.log("       "+vectorInput);
	//console.log("Option1: "+vectorOption1.length);
	//console.log("         "+vectorOption1);
	//console.log("Option2: "+vectorOption2.length);
	//console.log("         "+vectorOption2);

	//calculate cos
	var cos1 = math.dot(vectorOption1,vectorInput)/(math.norm(vectorOption1)*math.norm(vectorInput));
    var cos2 = math.dot(vectorOption2,vectorInput)/(math.norm(vectorOption2)*math.norm(vectorInput));

   //make output
	var winnerString = "";
    if (cos1 > cos2){
		winnerString += "
Your text most matches Kirk!
";
	}
	else if(cos1 < cos2){
		winnerString += "
Your text most matches Spock!
";
	}
	else{
		winnerString += "It's a tie!";
	}

	winnerString += "
Kirk's cos = "+cos1+"
";
	winnerString += "
Spock's cos = "+cos2+"
";
	winnerString += "
Biggest cosine / smallest angle wins
";

	var counter = 0;
	winnerString +="
";//add borders to hd, td...
	winnerString +="
Word	Kirk	you	Spock
";
	for (var word in allWords){
		winnerString +="
";
		winnerString += ""+word+"	";
		winnerString += ""+vectorOption1[counter]+"	";
		winnerString += ""+vectorInput[counter]+"	";
		winnerString += ""+vectorOption2[counter]+"	";
		winnerString +="
";
		counter +=1;
	}
	winnerString +="
";

	//make output div visible
	document.getElementById("inoutput").style.visibility = "visible";

	return winnerString;
}

//Give results
function returnResults(){
	var userTxt = document.getElementById("input").value;
	var input = popDictJS(userTxt);
	document.getElementById("output").innerHTML = categorize(input, dictKirk, dictSpock);
	//document.getElementById("output").innerHTML = categorize(input, dictTest1, dictTest2);
	document.getElementById("inputAgain").innerHTML = userTxt;
}
<|endoftext|>


<commit_before>require('./Data/Config');
require('./Data/State');
var db = require('mysql2')
  , io = require('socket.io')
  , storage = require('./IO/DB')(db)
  , eventData = require('./Data/EventData')
  , stateValidators = require('./Game/StateValidators')(storage)
  , eventHandlers = require('./Game/EventHandlers')(storage);

io.sockets.on('connection', function(socket) {
	socket.on('gameState', function(data)	{
		if (!('eventName' in data))	{
			socket.emit("NO_EVENT");
			return;
		}

		if (!(data.eventName in eventData))	{
			socket.emit("INVALID_EVENT");
			return;
		}

		var event = eventData[data.eventName];
		var stateChecker = event.stateChecker;
		var eventHandler = event.handler;

		if (!stateValidators.checkSocketParams(event.socketParams, data))	{
			socket.emit("INVALID_PARAMS");
			return;
		}

		if (!(stateChecker in stateValidators))	{
			socket.emit("NO_STATE_CHECKER");
			return;
		}

		if (!(eventHandler in eventHandlers))	{
			socket.emit("NO_EVENT_HANDLER");
			return;
		}

		if (!stateValidators.stateChecker(data, socket))	{
			return;
		}

		eventHandlers.eventHandler.execute(data, socket);

	});
});

console.log("Ready");<commit_msg>Added inline documentation for the main socket handler<commit_after>require('./Data/Config');
require('./Data/State');

var db = require('mysql2')
, io = require('socket.io')
, storage = require('./IO/DB')(db)
, eventData = require('./Data/EventData')
, stateValidators = require('./Game/StateValidators')(storage)
, eventHandlers = require('./Game/EventHandlers')(storage);

io.sockets.on('connection', function(socket) {
	socket.on('gameState', function(data) {
		/**
		 * Check if an eventName was given
		 */
		if (!('eventName' in data)) {
			socket.emit("NO_EVENT");
			return;
		}

		/**
		 * Checks if the event actually exists/has handlers
		 */
		if (!(data.eventName in eventData)) {
			socket.emit("INVALID_EVENT");
			return;
		}

		var event = eventData[data.eventName];
		var stateChecker = event.stateChecker;
		var eventHandler = event.handler;

		/**
		 * Check if the socket data contains the parameters necessary to execute
		 * the request
		 */
		if (!stateValidators.checkSocketParams(event.socketParams, data)) {
			socket.emit("INVALID_PARAMS");
			return;
		}

		/**
		 * Checks if the statehandler for this event exists
		 */
		if (!(stateChecker in stateValidators)) {
			socket.emit("NO_STATE_CHECKER");
			return;
		}

		/**
		 * Check if the eventHandler exists
		 */
		if (!(eventHandler in eventHandlers)) {
			socket.emit("NO_EVENT_HANDLER");
			return;
		}

		/**
		 * Validates the gamestate before executing the event handler
		 */
		if (!stateValidators.stateChecker(data, socket)) {
			return;
		}

		/**
		 * Executes the eventhandler for the event
		 */
		eventHandlers.eventHandler.execute(data, socket);

	});
});

console.log("Ready");<|endoftext|>


<commit_before>"use strict"

/*
 * This file is part of Omega Noc
 * Copyright Omega Noc (C) 2014 Omega Cube and contributors
 * Xavier Roger-Machart, xrm@omegacube.fr
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

// Omega Noc main launcher script
// This script configures Require.js and loads the actual starting script for the currently loading page

// Configure RequireJS
requirejs.config({
    // Shims
    shim: {
        'jquery.hashchange': ['jquery'],
        'jquery.scrollbar': ['jquery'],
        'jstree': ['jquery'],
        'gridster': ['jquery'],
        'svg.easing': ['svg'],
    },
    // Paths
    paths: {
        'widget': '../../widgets'
    }
});

requirejs(['jquery','onoc.tooltips'], function($,Tooltips) {
    var onoc_start = function(module) {
        if(typeof(module) === 'string') {
            module = [module];
        }

        return requirejs(module);
    }

    $(document).ready(function() {
        var help = new Tooltips();
        help.bind($('#content'));
        if(onoc_main_modules && onoc_main_modules.length > 0) {
            onoc_start(onoc_main_modules);
        }
    });
});
<commit_msg>Updated onoc.js to use a jQuery var name instead of $<commit_after>"use strict"

/*
 * This file is part of Omega Noc
 * Copyright Omega Noc (C) 2014 Omega Cube and contributors
 * Xavier Roger-Machart, xrm@omegacube.fr
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

// Omega Noc main launcher script
// This script configures Require.js and loads the actual starting script for the currently loading page

// Configure RequireJS
requirejs.config({
    // Shims
    shim: {
        'jquery.hashchange': ['jquery'],
        'jquery.scrollbar': ['jquery'],
        'jstree': ['jquery'],
        'gridster': ['jquery'],
        'svg.easing': ['svg'],
    },
    // Paths
    paths: {
        'widget': '../../widgets'
    }
});

requirejs(['jquery','onoc.tooltips'], function(jQuery,Tooltips) {
    var onoc_start = function(module) {
        if(typeof(module) === 'string') {
            module = [module];
        }

        return requirejs(module);
    }

    jQuery(document).ready(function() {
        var help = new Tooltips();
        help.bind(jQuery('#content'));
        if(onoc_main_modules && onoc_main_modules.length > 0) {
            onoc_start(onoc_main_modules);
        }
    });
});
<|endoftext|>


<commit_before>var vm = new Vue({
  el: '#app',
  data: {
    modeEnum: {
      NORMAL: 'normal',
      PLANNING: 'planning'
    },
    mode: '',
    meals: [],
    ingredients: [],
    shoppingList: [],
    orphanIngredient: ''
  },
  computed: {
    selectedMeals: function() {
      console.log("filtering");
      var filtered = [];
      for(var i = 0; i < this.meals.length; i++) {
        if(this.meals[i].selected) {
          filtered.push(this.meals[i]);
        }
      }
      return filtered;
    }
  },
  methods: {
    setMode: function(mode) {
      vm.mode = mode;
    },
    togglePlanningMode: function() {
      if(vm.mode === vm.modeEnum.PLANNING) {
        vm.mode = vm.modeEnum.NORMAL;
        vm.shoppingList = [];
      }
      else {
        vm.mode = vm.modeEnum.PLANNING;
        for(var i = 0; i < vm.meals.length; i++) {
          vm.meals[i].selected = false;
          //todo this feels hacky:
          Vue.set(vm.meals, i, vm.meals[i]);
        }
      }
    },
    toggleMealSelected: function(meal, index) {
      if(!meal.selected) {
        meal.selected = true;
        Vue.set(vm.meals, index, meal);
      }
      else {
        meal.selected = false;
        vm.removeFromShoppingList(meal.ingredients);
      }
      Vue.set(vm.meals, index, meal);
    },
    toggleShoppingList: function(ingredient) {
      var alreadyExists = false;
      for(var i = 0; i < vm.shoppingList.length; i++) {
        var shoppingItem = vm.shoppingList[i];
        //todo maybe get meal_ingredient_id from server for the if-statement
        if(shoppingItem.id === ingredient.id
            && shoppingItem.meal_name === ingredient.meal_name) {
          ingredient.selected = false;
          vm.shoppingList.splice(i,1);
          alreadyExists = true;
        }
      }
      if(!alreadyExists) {
        vm.shoppingList.push(ingredient);
      }
    },
    sortShoppingList: function(event) {

      //todo room for improvement
      //some potential solutions may reveal vue.js oddities

      var original = vm.shoppingList[event.oldIndex];
      vm.shoppingList.splice(vm.newIndex, 0, original);
      if(event.newIndex < event.oldIndex) {
        //moved up
        vm.shoppingList.splice(vm.oldIndex + 1, 1);
      }
      else {
        //moved down
        vm.shoppingList.splice(vm.oldIndex, 1);
      }

    },
    removeFromShoppingList: function(ingredients) {
      for(var i = 0; i < ingredients.length; i++) {
        var ingredient = ingredients[i];
        for(var j = 0; j < vm.shoppingList.length; j++) {
          var shoppingItem = vm.shoppingList[j];
          //todo maybe get meal_ingredient_id from server for the if-statement
          if(shoppingItem.id === ingredient.id
              && shoppingItem.meal_name === ingredient.meal_name) {
            vm.shoppingList.splice(j,1);
          }
        }
      }
    },
    addOrphanIngredient: function(name) {
      if(vm.orphanIngredient.length > 0) {
        vm.shoppingList.push({name: name, showNoteField: false, note: ''});
      }
      vm.orphanIngredient = '';
    },
    showNoteField(item) {
      item.showNoteField = true;
    },
    saveIngredientNote(item) {
      item.showNoteField = false;
    },
    addShoppingItemNote: function(item) {

    },
    getMeals: function() {
      dinner_http.getMeals(getMeals_success, getMeals_failed);
      function getMeals_success(response) {
        var meals = response.data;
        for(var i = 0; i < meals.length; i++) {
          var meal = meals[i];
          for(var j = 0; j < meal.ingredients.length; j++) {
            var ingredient = meal.ingredients[j];
            ingredient.meal_name = meal.name;
            ingredient.note = '';
            ingredient.showNoteField = false;
            //Vue.set(meal.ingredients, j, ingredient);
          }
        }
        vm.meals = meals;
      }
      function getMeals_failed(error) {
        console.log(error);
      }
    },
    getIngredients: function() {
      dinner_http.getIngredients(getIngredients_success, getIngredients_failed);
      function getIngredients_success(response) {
        vm.ingredients = response.data;
      }
      function getIngredients_failed(error) {
        console.log(error);
      }
    }
  }
});

vm.setMode(vm.modeEnum.PLANNING);
//vm.getIngredients();
vm.getMeals();
<commit_msg>bugfix after remove meal<commit_after>var vm = new Vue({
  el: '#app',
  data: {
    modeEnum: {
      NORMAL: 'normal',
      PLANNING: 'planning'
    },
    mode: '',
    meals: [],
    ingredients: [],
    shoppingList: [],
    orphanIngredient: ''
  },
  computed: {
    selectedMeals: function() {
      console.log("filtering");
      var filtered = [];
      for(var i = 0; i < this.meals.length; i++) {
        if(this.meals[i].selected) {
          filtered.push(this.meals[i]);
        }
      }
      return filtered;
    }
  },
  methods: {
    setMode: function(mode) {
      vm.mode = mode;
    },
    togglePlanningMode: function() {
      if(vm.mode === vm.modeEnum.PLANNING) {
        vm.mode = vm.modeEnum.NORMAL;
        vm.shoppingList = [];
      }
      else {
        vm.mode = vm.modeEnum.PLANNING;
        for(var i = 0; i < vm.meals.length; i++) {
          vm.meals[i].selected = false;
          //todo this feels hacky:
          Vue.set(vm.meals, i, vm.meals[i]);
        }
      }
    },
    toggleMealSelected: function(meal, index) {
      if(!meal.selected) {
        meal.selected = true;
        Vue.set(vm.meals, index, meal);
      }
      else {
        meal.selected = false;
        for(var i = 0; i < meal.ingredients.length; i++) {
          meal.ingredients[i].selected = false;
        }
        vm.removeFromShoppingList(meal.ingredients);
      }
      Vue.set(vm.meals, index, meal);
    },
    toggleShoppingList: function(ingredient) {
      var alreadyExists = false;
      for(var i = 0; i < vm.shoppingList.length; i++) {
        var shoppingItem = vm.shoppingList[i];
        //todo maybe get meal_ingredient_id from server for the if-statement
        if(shoppingItem.id === ingredient.id
            && shoppingItem.meal_name === ingredient.meal_name) {
          ingredient.selected = false;
          vm.shoppingList.splice(i,1);
          alreadyExists = true;
        }
      }
      if(!alreadyExists) {
        vm.shoppingList.push(ingredient);
      }
    },
    sortShoppingList: function(event) {

      //todo room for improvement
      //some potential solutions may reveal vue.js oddities

      var original = vm.shoppingList[event.oldIndex];
      vm.shoppingList.splice(vm.newIndex, 0, original);
      if(event.newIndex < event.oldIndex) {
        //moved up
        vm.shoppingList.splice(vm.oldIndex + 1, 1);
      }
      else {
        //moved down
        vm.shoppingList.splice(vm.oldIndex, 1);
      }

    },
    removeFromShoppingList: function(ingredients) {
      for(var i = 0; i < ingredients.length; i++) {
        var ingredient = ingredients[i];
        for(var j = 0; j < vm.shoppingList.length; j++) {
          var shoppingItem = vm.shoppingList[j];
          //todo maybe get meal_ingredient_id from server for the if-statement
          if(shoppingItem.id === ingredient.id
              && shoppingItem.meal_name === ingredient.meal_name) {
            vm.shoppingList.splice(j,1);
          }
        }
      }
    },
    addOrphanIngredient: function(name) {
      if(vm.orphanIngredient.length > 0) {
        vm.shoppingList.push({name: name, showNoteField: false, note: ''});
      }
      vm.orphanIngredient = '';
    },
    showNoteField(item) {
      item.showNoteField = true;
    },
    saveIngredientNote(item) {
      item.showNoteField = false;
    },
    addShoppingItemNote: function(item) {

    },
    getMeals: function() {
      dinner_http.getMeals(getMeals_success, getMeals_failed);
      function getMeals_success(response) {
        var meals = response.data;
        for(var i = 0; i < meals.length; i++) {
          var meal = meals[i];
          for(var j = 0; j < meal.ingredients.length; j++) {
            var ingredient = meal.ingredients[j];
            ingredient.meal_name = meal.name;
            ingredient.note = '';
            ingredient.showNoteField = false;
            //Vue.set(meal.ingredients, j, ingredient);
          }
        }
        vm.meals = meals;
      }
      function getMeals_failed(error) {
        console.log(error);
      }
    },
    getIngredients: function() {
      dinner_http.getIngredients(getIngredients_success, getIngredients_failed);
      function getIngredients_success(response) {
        vm.ingredients = response.data;
      }
      function getIngredients_failed(error) {
        console.log(error);
      }
    }
  }
});

vm.setMode(vm.modeEnum.PLANNING);
//vm.getIngredients();
vm.getMeals();
<|endoftext|>


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

/*
 * A hook to add resources class (R.java) import to Android classes which uses it.
 */

function getRegexGroupMatches(string, regex, index) {
    index || (index = 1)

    var matches = [];
    var match;
    if (regex.global) {
        while (match = regex.exec(string)) {
            matches.push(match[index]);
            console.log('Match:', match);
        }
    }
    else {
        if (match = regex.exec(string)) {
            matches.push(match[index]);
        }
    }

    return matches;
}

// Adapted from
// https://stackoverflow.com/a/5827895
// Using this and not one of the wrapper modules
// e.g. `file` or `node-dir` because I don't see an obvious way to add
// javascript modules using plugin.xml, and this uses only standard modules

var walk = function(ctx, dir, done) {
  var results = [];

  var fs = ctx.requireCordovaModule('fs'),
      path = ctx.requireCordovaModule('path');

  fs.readdir(dir, function(err, list) {
    if (err) return done(err);
    var pending = list.length;
    if (!pending) return done(null, results);
    list.forEach(function(file) {
      file = path.resolve(dir, file);
      fs.stat(file, function(err, stat) {
        if (stat && stat.isDirectory()) {
          walk(ctx, file, function(err, res) {
            results = results.concat(res);
            if (!--pending) done(null, results);
          });
        } else {
          results.push(file);
          if (!--pending) done(null, results);
        }
      });
    });
  });
};

module.exports = function (ctx) {
    // If Android platform is not installed, don't even execute
    if (ctx.opts.cordova.platforms.indexOf('android') < 0)
        return;

    var fs = ctx.requireCordovaModule('fs'),
        path = ctx.requireCordovaModule('path'),
        Q = ctx.requireCordovaModule('q');

    var deferral = Q.defer();

    var platformSourcesRoot = path.join(ctx.opts.projectRoot, 'platforms/android/src');
    var pluginSourcesRoot = path.join(ctx.opts.plugin.dir, 'src/android');

    var androidPluginsData = JSON.parse(fs.readFileSync(path.join(ctx.opts.projectRoot, 'plugins', 'android.json'), 'utf8'));
    var appPackage = androidPluginsData.installed_plugins[ctx.opts.plugin.id]['PACKAGE_NAME'];

    walk(ctx, pluginSourcesRoot, function (err, files) {
        console.log("walk callback with files = "+files);
        if (err) {
            console.error('Error when reading file:', err)
            deferral.reject();
            return
        }

        var deferrals = [];

        files.filter(function (file) { return path.extname(file) === '.java'; })
            .forEach(function (file) {
                var deferral = Q.defer();

                // console.log("Considering file "+file);
                var filename = path.basename(file);
                // console.log("basename "+filename);
                // var file = path.join(pluginSourcesRoot, filename);
                // console.log("newfile"+file);
                fs.readFile(file, 'utf-8', function (err, contents) {
                    if (err) {
                        console.error('Error when reading file:', err)
                        deferral.reject();
                        return
                    }

                    if (contents.match(/[^\.\w]R\./) || contents.match(/[^\.\w]BuildConfig\./) || contents.match(/[^\.\w]MainActivity\./)) {
                        console.log('Trying to get packages from file:', filename);
                        var packages = getRegexGroupMatches(contents, /package ([^;]+);/);
                        for (var p = 0; p < packages.length; p++) {
                            try {
                                var package = packages[p];
                                console.log('Handling package:', package);

                                var sourceFile = path.join(platformSourcesRoot, package.replace(/\./g, '/'), filename)
                                console.log('sourceFile:', sourceFile);
                                if (!fs.existsSync(sourceFile))
                                    throw 'Can\'t find file in installed platform directory: "' + sourceFile + '".';

                                var sourceFileContents = fs.readFileSync(sourceFile, 'utf8');
                                if (!sourceFileContents)
                                    throw 'Can\'t read file contents.';

                                var newContents = sourceFileContents;

                                if (contents.match(/[^\.\w]R\./)) {
                                    newContents = sourceFileContents
                                        .replace(/(import ([^;]+).R;)/g, '')
                                        .replace(/(package ([^;]+);)/g, '$1 \n// Auto fixed by post-plugin hook \nimport ' + appPackage + '.R;');
                                }

                                // replace BuildConfig as well
                                if (contents.match(/[^\.\w]BuildConfig\./)) {
                                    newContents = newContents
                                        .replace(/(import ([^;]+).BuildConfig;)/g, '')
                                        .replace(/(package ([^;]+);)/g, '$1 \n// Auto fixed by post-plugin hook \nimport ' + appPackage + '.BuildConfig;');
                                }

                                // replace MainActivity as well
                                if (contents.match(/[^\.\w]MainActivity\./)) {
                                    newContents = newContents
                                        .replace(/(import ([^;]+).MainActivity;)/g, '')
                                        .replace(/(package ([^;]+);)/g, '$1 \n// Auto fixed by post-plugin hook \nimport ' + appPackage + '.MainActivity;');
                                }

                                fs.writeFileSync(sourceFile, newContents, 'utf8');
                                break;
                            }
                            catch (ex) {
                                console.log('Could not add import to "' +  filename + '" using package "' + package + '". ' + ex);
                            }
                        }
                    }
                });

                deferrals.push(deferral.promise);
            });

        Q.all(deferrals)
            .then(function() {
                console.log('Done with the hook!');
                deferral.resolve();
            })
    });

    return deferral.promise;
}
<commit_msg>Make the hook synchronous<commit_after>#!/usr/bin/env node

/*
 * A hook to add resources class (R.java) import to Android classes which uses it.
 */

function getRegexGroupMatches(string, regex, index) {
    index || (index = 1)

    var matches = [];
    var match;
    if (regex.global) {
        while (match = regex.exec(string)) {
            matches.push(match[index]);
            console.log('Match:', match);
        }
    }
    else {
        if (match = regex.exec(string)) {
            matches.push(match[index]);
        }
    }

    return matches;
}

// Adapted from
// https://stackoverflow.com/a/5827895
// Using this and not one of the wrapper modules
// e.g. `file` or `node-dir` because I don't see an obvious way to add
// javascript modules using plugin.xml, and this uses only standard modules

var walk = function(ctx, dir, done) {
  var results = [];

  var fs = ctx.requireCordovaModule('fs'),
      path = ctx.requireCordovaModule('path');

  fs.readdir(dir, function(err, list) {
    if (err) return done(err);
    var pending = list.length;
    if (!pending) return done(null, results);
    list.forEach(function(file) {
      file = path.resolve(dir, file);
      fs.stat(file, function(err, stat) {
        if (stat && stat.isDirectory()) {
          walk(ctx, file, function(err, res) {
            results = results.concat(res);
            if (!--pending) done(null, results);
          });
        } else {
          results.push(file);
          if (!--pending) done(null, results);
        }
      });
    });
  });
}

module.exports = function (ctx) {
    // If Android platform is not installed, don't even execute
    if (ctx.opts.cordova.platforms.indexOf('android') < 0)
        return;

    var fs = ctx.requireCordovaModule('fs'),
        path = ctx.requireCordovaModule('path'),
        Q = ctx.requireCordovaModule('q');

    var platformSourcesRoot = path.join(ctx.opts.projectRoot, 'platforms/android/src');
    var pluginSourcesRoot = path.join(ctx.opts.plugin.dir, 'src/android');

    var androidPluginsData = JSON.parse(fs.readFileSync(path.join(ctx.opts.projectRoot, 'plugins', 'android.json'), 'utf8'));
    var appPackage = androidPluginsData.installed_plugins[ctx.opts.plugin.id]['PACKAGE_NAME'];

    walk(ctx, pluginSourcesRoot, function (err, files) {
        console.log("walk callback with files = "+files);
        if (err) {
            console.error('Error when reading file:', err)
            return
        }

        var deferrals = [];

        files.filter(function (file) { return path.extname(file) === '.java'; })
            .forEach(function (file) {
                var deferral = Q.defer();

                // console.log("Considering file "+file);
                var filename = path.basename(file);
                // console.log("basename "+filename);
                // var file = path.join(pluginSourcesRoot, filename);
                // console.log("newfile"+file);
                fs.readFile(file, 'utf-8', function (err, contents) {
                    if (err) {
                        console.error('Error when reading file:', err)
                        deferral.reject();
                        return
                    }

                    if (contents.match(/[^\.\w]R\./) || contents.match(/[^\.\w]BuildConfig\./) || contents.match(/[^\.\w]MainActivity\./)) {
                        console.log('Trying to get packages from file:', filename);
                        var packages = getRegexGroupMatches(contents, /package ([^;]+);/);
                        for (var p = 0; p < packages.length; p++) {
                            try {
                                var package = packages[p];
                                console.log('Handling package:', package);

                                var sourceFile = path.join(platformSourcesRoot, package.replace(/\./g, '/'), filename)
                                console.log('sourceFile:', sourceFile);
                                if (!fs.existsSync(sourceFile))
                                    throw 'Can\'t find file in installed platform directory: "' + sourceFile + '".';

                                var sourceFileContents = fs.readFileSync(sourceFile, 'utf8');
                                if (!sourceFileContents)
                                    throw 'Can\'t read file contents.';

                                var newContents = sourceFileContents;

                                if (contents.match(/[^\.\w]R\./)) {
                                    newContents = sourceFileContents
                                        .replace(/(import ([^;]+).R;)/g, '')
                                        .replace(/(package ([^;]+);)/g, '$1 \n// Auto fixed by post-plugin hook \nimport ' + appPackage + '.R;');
                                }

                                // replace BuildConfig as well
                                if (contents.match(/[^\.\w]BuildConfig\./)) {
                                    newContents = newContents
                                        .replace(/(import ([^;]+).BuildConfig;)/g, '')
                                        .replace(/(package ([^;]+);)/g, '$1 \n// Auto fixed by post-plugin hook \nimport ' + appPackage + '.BuildConfig;');
                                }

                                // replace MainActivity as well
                                if (contents.match(/[^\.\w]MainActivity\./)) {
                                    newContents = newContents
                                        .replace(/(import ([^;]+).MainActivity;)/g, '')
                                        .replace(/(package ([^;]+);)/g, '$1 \n// Auto fixed by post-plugin hook \nimport ' + appPackage + '.MainActivity;');
                                }

                                fs.writeFileSync(sourceFile, newContents, 'utf8');
                                break;
                            }
                            catch (ex) {
                                console.log('Could not add import to "' +  filename + '" using package "' + package + '". ' + ex);
                            }
                        }
                    }
                });

                deferrals.push(deferral.promise);
            });

        Q.all(deferrals)
            .then(function() {
                console.log('Done with the hook!');
            })
    });
}
<|endoftext|>


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

'use strict';

var assert = require('assert');
var util = require('util');
var timers = require('timers');
var NullStatsd = require('uber-statsd-client/null');

var BaseBackend = require('./base-backend');

module.exports = ReservoirBackend;

function ReservoirBackend(options) {
    if (!(this instanceof ReservoirBackend)) {
        return new ReservoirBackend(options);
    }

    var self = this;

    BaseBackend.call(self);

    self.backend = options.backend;
    assert(
        typeof self.backend === 'object' &&
        typeof self.backend.logMany === 'function',
        'options.backend must be object with `logMany` method'
    );

    self.statsd = options.statsd || NullStatsd();
    assert(
        typeof self.statsd === 'object' &&
        typeof self.statsd.gauge === 'function',
        'options.statsd must be object with `gauge` method'
    );

    self.size = options.size || 100;
    assert(
        typeof self.size === 'number' &&
        self.size >= 5 && self.size < 1000000000,
        'options.size must be number 5 >= n > 1000000000'
    );

    self.rangeRand = options.rangeRand || ReservoirBackend.rangeRand;
    assert(
        typeof self.rangeRand === 'function',
        'options.rangeRand must be function'
    );

    self.flushInterval = options.flushInterval || 50;
    assert(
        typeof self.flushInterval === 'number' &&
        self.flushInterval > 1 && self.flushInterval < 1000000,
        'options.flushInterval must be number 1 > n > 1000000'
    );

    self.timers = options.timers || timers;
    assert(
        typeof self.timers === 'object' &&
        typeof self.timers.setTimeout === 'function',
        'options.timers must be object with setTimeout function'
    );

    self.now = options.now || Date.now;
    assert(
        typeof self.now === 'function',
        'options.now must be function'
    );

    self.timer = null;
    self.count = 0;
    self.records = [];
    self.dropCount = {};
    self.logCount = {};
}

util.inherits(ReservoirBackend, BaseBackend);

ReservoirBackend.rangeRand = function rand(lo, hi) {
    return Math.floor(Math.random() * (hi - lo) + lo);
};

ReservoirBackend.prototype.flush = function flush(records) {
    var self = this;

    var start = self.now();

    var i;
    var keys = Object.keys(self.dropCount);
    for (i = 0; i < keys.length; i++) {
        self.statsd.increment('larch.dropped.' + keys[i], self.dropCount[keys[i]]);
        self.dropCount[keys[i]] = 0;
    }

    for (i = 0; i < self.records.length; i++) {
        self.countLog(self.records[i].data.level);
    }

    keys = Object.keys(self.logCount);
    for (i = 0; i < keys.length; i++) {
        self.statsd.increment('larch.logged.' + keys[i], self.logCount[keys[i]]);
        self.logCount[keys[i]] = 0;
    }

    var copy = records.slice(0);
    self.backend.logMany(copy, onLoggingDone);

    function onLoggingDone(err) {
        // TODO: what to do when flush fails? Generate a log message?
        var count = 1;
        if (err.count) {
            count = err.count;
        }

        self.statsd.incr('larch.errors', count);
        self.statsd.timing('larch.flushTime', self.now() - start);
    }

    self.records.length = 0;
    self.count = 0;
};

ReservoirBackend.prototype.log = function log(record, cb) {
    var self = this;

    self.count += 1;

    if (self.records.length < self.size) {
        self.records.push(record);
    } else {
        var probability = self.rangeRand(0, self.count);
        if (probability < self.size) {
            // record drop for the record we're evicting
            self.countDrop(self.records[probability].data.level);

            self.records[probability] = record;
        } else {
            // record drop for record we're dropping
            self.countDrop(record.data.level);
        }
    }

    if (typeof cb === 'function') {
        cb();
    }
};

ReservoirBackend.prototype.countDrop = function countDrop(level) {
    var self = this;

    if (!self.dropCount[level]) {
        self.dropCount[level] = 1;
    } else {
        self.dropCount[level] += 1;
    }
};

ReservoirBackend.prototype.countLog = function countLog(level) {
    var self = this;

    if (!self.logCount[level]) {
        self.logCount[level] = 1;
    } else {
        self.logCount[level] += 1;
    }
};

ReservoirBackend.prototype.destroy = function destroy(cb) {
    var self = this;

    self.timers.clearTimeout(self.timer);
    self.backend.destroy(cb);
};

ReservoirBackend.prototype.bootstrap = function bootstrap(cb) {
    var self = this;

    assert(
        typeof cb === 'function',
        'bootstrap must be called with a callback'
    );

    self.timer = self.timers.setTimeout(onTimer, self.flushInterval);

    function onTimer() {
        self.flush(self.records);

        self.timer = self.timers.setTimeout(onTimer, self.flushInterval);
    }

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

'use strict';

var assert = require('assert');
var util = require('util');
var timers = require('timers');
var NullStatsd = require('uber-statsd-client/null');

var BaseBackend = require('./base-backend');

module.exports = ReservoirBackend;

function ReservoirBackend(options) {
    if (!(this instanceof ReservoirBackend)) {
        return new ReservoirBackend(options);
    }

    var self = this;

    BaseBackend.call(self);

    self.backend = options.backend;
    assert(
        typeof self.backend === 'object' &&
        typeof self.backend.logMany === 'function',
        'options.backend must be object with `logMany` method'
    );

    self.statsd = options.statsd || NullStatsd();
    assert(
        typeof self.statsd === 'object' &&
        typeof self.statsd.gauge === 'function',
        'options.statsd must be object with `gauge` method'
    );

    self.size = options.size || 100;
    assert(
        typeof self.size === 'number' &&
        self.size >= 5 && self.size < 1000000000,
        'options.size must be number 5 >= n > 1000000000'
    );

    self.rangeRand = options.rangeRand || ReservoirBackend.rangeRand;
    assert(
        typeof self.rangeRand === 'function',
        'options.rangeRand must be function'
    );

    self.flushInterval = options.flushInterval || 50;
    assert(
        typeof self.flushInterval === 'number' &&
        self.flushInterval > 1 && self.flushInterval < 1000000,
        'options.flushInterval must be number 1 > n > 1000000'
    );

    self.timers = options.timers || timers;
    assert(
        typeof self.timers === 'object' &&
        typeof self.timers.setTimeout === 'function',
        'options.timers must be object with setTimeout function'
    );

    self.now = options.now || Date.now;
    assert(
        typeof self.now === 'function',
        'options.now must be function'
    );

    self.timer = null;
    self.count = 0;
    self.records = [];
    self.dropCount = {};
    self.logCount = {};
}

util.inherits(ReservoirBackend, BaseBackend);

ReservoirBackend.rangeRand = function rand(lo, hi) {
    return Math.floor(Math.random() * (hi - lo) + lo);
};

ReservoirBackend.prototype.flush = function flush(records) {
    var self = this;

    var start = self.now();

    var i;
    var keys = Object.keys(self.dropCount);
    for (i = 0; i < keys.length; i++) {
        self.statsd.increment('larch.dropped.' + keys[i], self.dropCount[keys[i]]);
        self.dropCount[keys[i]] = 0;
    }

    for (i = 0; i < self.records.length; i++) {
        self.countLog(self.records[i].data.level);
    }

    keys = Object.keys(self.logCount);
    for (i = 0; i < keys.length; i++) {
        self.statsd.increment('larch.logged.' + keys[i], self.logCount[keys[i]]);
        self.logCount[keys[i]] = 0;
    }

    var copy = records.slice(0);
    self.backend.logMany(copy, onLoggingDone);

    function onLoggingDone(err) {
        // TODO: what to do when flush fails? Generate a log message?
        if (err) {
            var count = 1;
            if (err.count) {
                count = err.count;
            }

            self.statsd.incr('larch.errors', count);
        }

        self.statsd.timing('larch.flushTime', self.now() - start);
    }

    self.records.length = 0;
    self.count = 0;
};

ReservoirBackend.prototype.log = function log(record, cb) {
    var self = this;

    self.count += 1;

    if (self.records.length < self.size) {
        self.records.push(record);
    } else {
        var probability = self.rangeRand(0, self.count);
        if (probability < self.size) {
            // record drop for the record we're evicting
            self.countDrop(self.records[probability].data.level);

            self.records[probability] = record;
        } else {
            // record drop for record we're dropping
            self.countDrop(record.data.level);
        }
    }

    if (typeof cb === 'function') {
        cb();
    }
};

ReservoirBackend.prototype.countDrop = function countDrop(level) {
    var self = this;

    if (!self.dropCount[level]) {
        self.dropCount[level] = 1;
    } else {
        self.dropCount[level] += 1;
    }
};

ReservoirBackend.prototype.countLog = function countLog(level) {
    var self = this;

    if (!self.logCount[level]) {
        self.logCount[level] = 1;
    } else {
        self.logCount[level] += 1;
    }
};

ReservoirBackend.prototype.destroy = function destroy(cb) {
    var self = this;

    self.timers.clearTimeout(self.timer);
    self.backend.destroy(cb);
};

ReservoirBackend.prototype.bootstrap = function bootstrap(cb) {
    var self = this;

    assert(
        typeof cb === 'function',
        'bootstrap must be called with a callback'
    );

    self.timer = self.timers.setTimeout(onTimer, self.flushInterval);

    function onTimer() {
        self.flush(self.records);

        self.timer = self.timers.setTimeout(onTimer, self.flushInterval);
    }

    self.backend.bootstrap(cb);
};
<|endoftext|>


<commit_before>phoxy._ApiSubsystem =
{
  ApiAnswer : function(answer, callback)
    {
      if (answer.error !== undefined)
        return phoxy._.api.keyword.error(answer, callback);

      if (answer.reset !== undefined)
        return phoxy._.api.keyword.reset(answer, callback);

      function ReadyForDesignRender()
      {
        phoxy._.api.IfKeyword(answer, callback, "before", phoxy._.api.ScriptsLoaded);
      }

      phoxy._.api.IfKeyword(answer, callback, "script", ReadyForDesignRender);
    }
  ,
  AJAX : function(url, callback, params)
    {
      url = phoxy.ConstructURL(url);

      var current_ajax_id = phoxy.state.ajax.active_id++;
      phoxy.state.ajax.active[current_ajax_id] = arguments;

      if (!phoxy.state.ajax.nesting_level++)
        if (typeof phoxy._.prestart.OnAjaxBegin === 'function')
          phoxy._.prestart.OnAjaxBegin(phoxy.state.ajax.active[current_ajax_id]);

      phoxy._.api.ajax(phoxy.Config()['api_dir'] + "/" + url, function(response)
        {
          data = JSON.parse(response);
          if (params == undefined)
            params = [];
          params.unshift(data);
          callback.apply(this, params);

          if (!--phoxy.state.ajax.nesting_level)
            if (typeof phoxy._.prestart.OnAjaxEnd === 'function')
              phoxy._.prestart.OnAjaxEnd(phoxy.state.ajax.active[current_ajax_id]);
          delete phoxy.state.ajax.active[current_ajax_id];
        });
    }
  ,
  ConstructURL : function(arr)
    {
      if (typeof arr === 'string')
        return arr;

      arr = arr.slice(0);
      var url = arr.shift();
      if (arr.length > 0)
        url += '(' + phoxy._.api.Serialize(arr) + ')';
      return url;
    }
  ,
  ApiRequest : function(url, callback)
    {
      if (phoxy._.deprecated.ObjectOptionalRelaunch(this, phoxy.ApiRequest, arguments))
        return;

      phoxy.AJAX(url, phoxy.ApiAnswer, [callback]);
    }
  ,
  MenuCall : function(url, callback)
    {
      if (phoxy._.deprecated.ObjectOptionalRelaunch(this, phoxy.MenuCall, arguments))
        return;

      phoxy.ChangeURL(url);
      phoxy.ApiRequest(url, callback);
    }
}

phoxy._ApiSubsystem._ = {};
phoxy._ApiSubsystem._.api =
{
  ScriptsLoaded : function(answer, callback)
    {
      function ScriptsFiresUp()
      {
        phoxy._.api.keyword.routeline(answer, callback);
        if (callback)
          callback(answer);
        if (!phoxy.state.loaded)
          phoxy._.internal.Load();
      }

      if (answer.exception !== undefined)
        return phoxy._.api.keyword.exception(answer, ScriptsFiresUp);

      phoxy._.api.IfKeyword(answer, callback, "design", ScriptsFiresUp);
    }
  ,
  FindRouteline : function(routeline)
    {
      if (typeof routeline === 'undefined')
        return function() {};
      if (typeof window[routeline] === 'function')
        return window[routeline];
      var arr = routeline.split(".");
      var method = arr.pop();

      var obj = window;
      for (var k in arr)
        if (typeof obj[arr[k]] === 'undefined')
          throw "Routeline context locate failed";
        else
          obj = obj[arr[k]];

      if (typeof obj[method] !== 'function')
        throw "Routeline locate failed";

      return obj[method];
    }
  ,
  ForwardDownload : function(url, callback_or_true_for_return)
    {
      if (typeof(storage) === "undefined")
        storage = {};

      if (callback_or_true_for_return === true)
        return storage[url];

      function AddToLocalStorage(data)
      {
        storage[url] = data;
        if (typeof(callback_or_true_for_return) === 'function')
          callback_or_true_for_return(data);
      }

      if (storage[url] != undefined)
      {
        if (typeof(callback_or_true_for_return) === 'function')
          callback_or_true_for_return(storage[url]);
        return true;
      }

      phoxy._.internal.ajax(url, AddToLocalStorage);
      return false;
    }
  ,
  ajax : function ()
    {
      phoxy._.internal.ajax.apply(this, arguments);
    }
  ,
  Serialize : function(obj, nested_mode)
    {
      json_encoded = JSON.stringify(obj);
      send_string = json_encoded.substring(1, json_encoded.length - 1);

      function EscapeReserved(str, reserved)
      {
        reserved_characters = reserved.split('');
        search_string = "\\" + reserved_characters.join("|\\");
        var regexp = new RegExp(search_string, "gi");

        return str.replace(regexp,
          function(matched)
          {
            return escape(escape(matched));
          });
      }

      return EscapeReserved(send_string, "()?#\\");
    }
  ,
  IfKeyword : function(answer, callback, keyword, next)
    {
      if (answer[keyword] !== undefined)
        phoxy._.api.keyword[keyword](answer, callback, next);
      else if (next !== undefined)
        next(answer, callback);
    }
  ,
  PlugInKeyword : function(keyword, args)
  {
    require([phoxy._.EarlyStage.subsystem_dir + "/" + keyword + ".js"], function()
    {
      if (phoxy._.api.keyword[keyword] === undefined)
        Log(0, "Keyword handler for '" + keyword + "' is missing");
      phoxy._.api.keyword[keyword].apply(phoxy._.api.keyword, args);
    });
  }
  ,
  KeywordMissing : function(keyword)
  {
    return function()
    {
      return phoxy._.api.PlugInKeyword(keyword, arguments);
    };
  }
};

phoxy._ApiSubsystem._.api.keyword =
{
  error: function(answer, callback)
    {
      alert(answer.error);
      if (answer.reset !== undefined)
        phoxy.Reset(answer.reset);
    }
  ,
  reset: function(answer, callback)
    {
      phoxy.Reset(answer.reset);
    }
  ,
  script: function(answer, callback, next)
    {
      require(answer.script, next);
    }
  ,
  before: function(answer, callback, next)
    {
      function AfterBefore(_answer)
      {
        if (_answer !== undefined)
          answer = _answer;
        next(answer, callback);
      }

      phoxy._.api.FindRouteline(answer.before)(AfterBefore, answer);
    }
  ,
  routeline: function(answer, callback)
    {
      phoxy._.api.FindRouteline(answer.routeline, answer)();
    }
  ,
  design: function(answer, callback, next)
    {
      var canvas = phoxy._.render.PrepareCanvas('<render>');

      var url = phoxy.Config()['ejs_dir'] + "/" + answer.design + ".ejs";
      phoxy._.api.ForwardDownload(url, function()
      {
        if (answer.replace !== undefined)
          phoxy._.api.keyword.replace(answer, callback, canvas);
        else if (answer.result !== undefined)
          phoxy._.api.keyword.result(answer, callback, canvas);
        else
          document.getElementsByTagName('body')[0].appendChild(canvas.obj);

        phoxy._.render.RenderReplace(
          canvas.id,
          answer.design,
          answer.data || {},
          next);
      });

      return canvas;
    }
  ,
  replace: function(answer, callback, canvas)
    {
      canvas.id = answer.replace;
    }
  ,
  result: function(answer, callback, canvas)
    {
      if (typeof answer.result === 'string')
        return document.getElementById(answer.result).innerHTML = canvas.html;

      for (var k in answer.result)
      {
        var v = document.getElementById(answer.result[k]);
        if (v != null)
          v.innerHTML = canvas.html;
      }
    }
  ,
  exception: phoxy._ApiSubsystem._.api.KeywordMissing("exception")
  ,
};<commit_msg>Fix issue when data array causing recursive load at Fancy<commit_after>phoxy._ApiSubsystem =
{
  ApiAnswer : function(answer, callback)
    {
      if (answer.error !== undefined)
        return phoxy._.api.keyword.error(answer, callback);

      if (answer.reset !== undefined)
        return phoxy._.api.keyword.reset(answer, callback);

      function ReadyForDesignRender()
      {
        phoxy._.api.IfKeyword(answer, callback, "before", phoxy._.api.ScriptsLoaded);
      }

      phoxy._.api.IfKeyword(answer, callback, "script", ReadyForDesignRender);
    }
  ,
  AJAX : function(url, callback, params)
    {
      url = phoxy.ConstructURL(url);

      var current_ajax_id = phoxy.state.ajax.active_id++;
      phoxy.state.ajax.active[current_ajax_id] = arguments;

      if (!phoxy.state.ajax.nesting_level++)
        if (typeof phoxy._.prestart.OnAjaxBegin === 'function')
          phoxy._.prestart.OnAjaxBegin(phoxy.state.ajax.active[current_ajax_id]);

      phoxy._.api.ajax(phoxy.Config()['api_dir'] + "/" + url, function(response)
        {
          data = JSON.parse(response);

          // http://stackoverflow.com/questions/4215737/convert-array-to-object
          if (Array.isArray(data.data))
            if (data.data.length == 0)
              data.data = {};
            else
              data.data = data.data.reduce(function(o, v, i) { o[i] = v; return o; });

          if (params == undefined)
            params = [];
          params.unshift(data);
          callback.apply(this, params);

          if (!--phoxy.state.ajax.nesting_level)
            if (typeof phoxy._.prestart.OnAjaxEnd === 'function')
              phoxy._.prestart.OnAjaxEnd(phoxy.state.ajax.active[current_ajax_id]);
          delete phoxy.state.ajax.active[current_ajax_id];
        });
    }
  ,
  ConstructURL : function(arr)
    {
      if (typeof arr === 'string')
        return arr;

      arr = arr.slice(0);
      var url = arr.shift();
      if (arr.length > 0)
        url += '(' + phoxy._.api.Serialize(arr) + ')';
      return url;
    }
  ,
  ApiRequest : function(url, callback)
    {
      if (phoxy._.deprecated.ObjectOptionalRelaunch(this, phoxy.ApiRequest, arguments))
        return;

      phoxy.AJAX(url, phoxy.ApiAnswer, [callback]);
    }
  ,
  MenuCall : function(url, callback)
    {
      if (phoxy._.deprecated.ObjectOptionalRelaunch(this, phoxy.MenuCall, arguments))
        return;

      phoxy.ChangeURL(url);
      phoxy.ApiRequest(url, callback);
    }
}

phoxy._ApiSubsystem._ = {};
phoxy._ApiSubsystem._.api =
{
  ScriptsLoaded : function(answer, callback)
    {
      function ScriptsFiresUp()
      {
        phoxy._.api.keyword.routeline(answer, callback);
        if (callback)
          callback(answer);
        if (!phoxy.state.loaded)
          phoxy._.internal.Load();
      }

      if (answer.exception !== undefined)
        return phoxy._.api.keyword.exception(answer, ScriptsFiresUp);

      phoxy._.api.IfKeyword(answer, callback, "design", ScriptsFiresUp);
    }
  ,
  FindRouteline : function(routeline)
    {
      if (typeof routeline === 'undefined')
        return function() {};
      if (typeof window[routeline] === 'function')
        return window[routeline];
      var arr = routeline.split(".");
      var method = arr.pop();

      var obj = window;
      for (var k in arr)
        if (typeof obj[arr[k]] === 'undefined')
          throw "Routeline context locate failed";
        else
          obj = obj[arr[k]];

      if (typeof obj[method] !== 'function')
        throw "Routeline locate failed";

      return obj[method];
    }
  ,
  ForwardDownload : function(url, callback_or_true_for_return)
    {
      if (typeof(storage) === "undefined")
        storage = {};

      if (callback_or_true_for_return === true)
        return storage[url];

      function AddToLocalStorage(data)
      {
        storage[url] = data;
        if (typeof(callback_or_true_for_return) === 'function')
          callback_or_true_for_return(data);
      }

      if (storage[url] != undefined)
      {
        if (typeof(callback_or_true_for_return) === 'function')
          callback_or_true_for_return(storage[url]);
        return true;
      }

      phoxy._.internal.ajax(url, AddToLocalStorage);
      return false;
    }
  ,
  ajax : function ()
    {
      phoxy._.internal.ajax.apply(this, arguments);
    }
  ,
  Serialize : function(obj, nested_mode)
    {
      json_encoded = JSON.stringify(obj);
      send_string = json_encoded.substring(1, json_encoded.length - 1);

      function EscapeReserved(str, reserved)
      {
        reserved_characters = reserved.split('');
        search_string = "\\" + reserved_characters.join("|\\");
        var regexp = new RegExp(search_string, "gi");

        return str.replace(regexp,
          function(matched)
          {
            return escape(escape(matched));
          });
      }

      return EscapeReserved(send_string, "()?#\\");
    }
  ,
  IfKeyword : function(answer, callback, keyword, next)
    {
      if (answer[keyword] !== undefined)
        phoxy._.api.keyword[keyword](answer, callback, next);
      else if (next !== undefined)
        next(answer, callback);
    }
  ,
  PlugInKeyword : function(keyword, args)
  {
    require([phoxy._.EarlyStage.subsystem_dir + "/" + keyword + ".js"], function()
    {
      if (phoxy._.api.keyword[keyword] === undefined)
        Log(0, "Keyword handler for '" + keyword + "' is missing");
      phoxy._.api.keyword[keyword].apply(phoxy._.api.keyword, args);
    });
  }
  ,
  KeywordMissing : function(keyword)
  {
    return function()
    {
      return phoxy._.api.PlugInKeyword(keyword, arguments);
    };
  }
};

phoxy._ApiSubsystem._.api.keyword =
{
  error: function(answer, callback)
    {
      alert(answer.error);
      if (answer.reset !== undefined)
        phoxy.Reset(answer.reset);
    }
  ,
  reset: function(answer, callback)
    {
      phoxy.Reset(answer.reset);
    }
  ,
  script: function(answer, callback, next)
    {
      require(answer.script, next);
    }
  ,
  before: function(answer, callback, next)
    {
      function AfterBefore(_answer)
      {
        if (_answer !== undefined)
          answer = _answer;
        next(answer, callback);
      }

      phoxy._.api.FindRouteline(answer.before)(AfterBefore, answer);
    }
  ,
  routeline: function(answer, callback)
    {
      phoxy._.api.FindRouteline(answer.routeline, answer)();
    }
  ,
  design: function(answer, callback, next)
    {
      var canvas = phoxy._.render.PrepareCanvas('<render>');

      var url = phoxy.Config()['ejs_dir'] + "/" + answer.design + ".ejs";
      phoxy._.api.ForwardDownload(url, function()
      {
        if (answer.replace !== undefined)
          phoxy._.api.keyword.replace(answer, callback, canvas);
        else if (answer.result !== undefined)
          phoxy._.api.keyword.result(answer, callback, canvas);
        else
          document.getElementsByTagName('body')[0].appendChild(canvas.obj);

        phoxy._.render.RenderReplace(
          canvas.id,
          answer.design,
          answer.data || {},
          next);
      });

      return canvas;
    }
  ,
  replace: function(answer, callback, canvas)
    {
      canvas.id = answer.replace;
    }
  ,
  result: function(answer, callback, canvas)
    {
      if (typeof answer.result === 'string')
        return document.getElementById(answer.result).innerHTML = canvas.html;

      for (var k in answer.result)
      {
        var v = document.getElementById(answer.result[k]);
        if (v != null)
          v.innerHTML = canvas.html;
      }
    }
  ,
  exception: phoxy._ApiSubsystem._.api.KeywordMissing("exception")
  ,
};<|endoftext|>


<commit_before>import {PanelButtonContext} from './toolbar'
import {PanelWizardContext} from './panelWizard'
import {connect, select} from 'store'
import Icon from 'widget/icon'
import PropTypes from 'prop-types'
import React from 'react'
import actionBuilder from 'action-builder'
import styles from './panel.module.css'

const mapStateToProps = (state, ownProps) => {
    const {statePath} = ownProps
    return {
        initialized: select([statePath, 'initialized']),
        selectedPanel: select([statePath, 'selectedPanel'])
    }
}

class Panel extends React.Component {
    componentDidMount() {
        const {initialized, form, modalOnDirty = true} = this.props
        if (modalOnDirty) {
            this.setModal(!initialized)
            if (initialized) {
                form.onDirty(() => this.setModal(true))
                form.onClean(() => this.setModal(false))
            }
        }
    }

    setModal(modal) {
        const {statePath} = this.props
        actionBuilder('SET_MODAL', {modal})
            .set([statePath, 'modal'], modal)
            .dispatch()
    }

    selectPanel(panel) {
        const {statePath} = this.props
        actionBuilder('SELECT_PANEL', {panel})
            .set([statePath, 'selectedPanel'], panel)
            .dispatch()
    }

    setInitialized() {
        const {statePath} = this.props
        actionBuilder('SET_INITIALIZED')
            .set([statePath, 'initialized'], true)
            .dispatch()
    }

    closePanel() {
        this.setModal(false)
        this.selectPanel()
    }

    apply() {
        const {form, onApply} = this.props
        onApply(form && form.values())
    }

    ok() {
        const {form, isActionForm} = this.props
        if (form && (isActionForm || form.isDirty())) {
            this.apply()
            this.closePanel()
        } else {
            this.cancel()
        }
    }

    cancel() {
        const {onCancel} = this.props
        onCancel && onCancel()
        this.closePanel()
    }

    back(panel) {
        this.apply()
        this.selectPanel(panel)
    }

    next(panel) {
        this.apply()
        this.selectPanel(panel)
    }

    done() {
        this.apply()
        this.setInitialized()
        this.closePanel()
    }

    renderForm({form, onApply, top, bottom, left, right, center, inline, panelButtonPosition, className}, content) {
        const classNames = [
            styles.panel,
            top || (panelButtonPosition && panelButtonPosition.top) ? styles.top : null,
            bottom || (panelButtonPosition && panelButtonPosition.bottom) ? styles.bottom : null,
            right || (panelButtonPosition && panelButtonPosition.right) ? styles.right : null,
            left ? styles.bottom : null,
            center ? styles.center : null,
            inline || (panelButtonPosition && panelButtonPosition.inline) ? styles.inline : null,
            className
        ].join(' ')
        return form
            ? (
                <form
                    className={classNames}
                    onSubmit={e => {
                        e.preventDefault()
                        onApply && onApply(form && form.values())
                    }}>
                    {content}
                </form>
            )
            : (

{content}

            )
    }

    renderModal({modal}, content) {
        return modal
            ?
{content}

            : content
    }

    render() {
        const {form = false, isActionForm, initialized, onApply, top, bottom, left, right, center, inline, modal, className, children} = this.props
        const {selectedPanel} = this.props
        return (
            <PanelWizardContext.Consumer>
                {panels => {
                    const wizard = panels && !initialized
                    const selectedPanelIndex = panels.indexOf(selectedPanel)
                    const first = selectedPanelIndex === 0
                    const last = selectedPanelIndex === panels.length - 1
                    // const first = _.first(panels) === selectedPanel
                    // const last = _.last(panels) === selectedPanel
                    return (
                        <PanelContext.Provider value={{
                            wizard,
                            first,
                            last,
                            isActionForm: form && isActionForm,
                            dirty: form && form.isDirty(),
                            invalid: form && form.isInvalid(),
                            onOk: () => this.ok(),
                            onCancel: () => this.cancel(),
                            onBack: () => !first && this.back(panels[selectedPanelIndex - 1]),
                            onNext: () => !last && this.next(panels[selectedPanelIndex + 1]),
                            onDone: () => this.done()
                        }}>
                            <PanelButtonContext.Consumer>
                                {panelButtonPosition =>
                                    this.renderModal({modal},
                                        this.renderForm({form, onApply, top, bottom, left, right, center, inline, panelButtonPosition, className}, children)
                                    )
                                }
                            </PanelButtonContext.Consumer>
                        </PanelContext.Provider>
                    )}}
            </PanelWizardContext.Consumer>

        )
    }
}

export default connect(mapStateToProps)(Panel)

Panel.propTypes = {
    children: PropTypes.any.isRequired,
    statePath: PropTypes.string.isRequired,
    bottom: PropTypes.any,
    center: PropTypes.any,
    className: PropTypes.string,
    form: PropTypes.object,
    initialized: PropTypes.any,
    inline: PropTypes.any,
    isActionForm: PropTypes.any,
    left: PropTypes.any,
    modal: PropTypes.any,
    modalOnDirty: PropTypes.any,
    right: PropTypes.any,
    top: PropTypes.any,
    onApply: PropTypes.func,
    onCancel: PropTypes.func,
}

export const PanelHeader = ({icon, title, children}) =>

        {children
            ? children
            : <React.Fragment>
                <Icon name={icon}/>
                {title}
            </React.Fragment>
        }

PanelHeader.propTypes = {
    children: PropTypes.any,
    icon: PropTypes.string,
    title: PropTypes.string,
}

export const PanelContent = ({className, children}) =>

        {children}

PanelContent.propTypes = {
    children: PropTypes.any.isRequired,
    className: PropTypes.string,
}

export const PanelContext = React.createContext()
<commit_msg>Cleanup.<commit_after>import {PanelButtonContext} from './toolbar'
import {PanelWizardContext} from './panelWizard'
import {connect, select} from 'store'
import Icon from 'widget/icon'
import PropTypes from 'prop-types'
import React from 'react'
import actionBuilder from 'action-builder'
import styles from './panel.module.css'

const mapStateToProps = (state, ownProps) => {
    const {statePath} = ownProps
    return {
        initialized: select([statePath, 'initialized']),
        selectedPanel: select([statePath, 'selectedPanel'])
    }
}

class Panel extends React.Component {
    componentDidMount() {
        const {initialized, form, modalOnDirty = true} = this.props
        if (modalOnDirty) {
            this.setModal(!initialized)
            if (initialized) {
                form.onDirty(() => this.setModal(true))
                form.onClean(() => this.setModal(false))
            }
        }
    }

    setModal(modal) {
        const {statePath} = this.props
        actionBuilder('SET_MODAL', {modal})
            .set([statePath, 'modal'], modal)
            .dispatch()
    }

    selectPanel(panel) {
        const {statePath} = this.props
        actionBuilder('SELECT_PANEL', {panel})
            .set([statePath, 'selectedPanel'], panel)
            .dispatch()
    }

    setInitialized() {
        const {statePath} = this.props
        actionBuilder('SET_INITIALIZED')
            .set([statePath, 'initialized'], true)
            .dispatch()
    }

    closePanel() {
        this.setModal(false)
        this.selectPanel()
    }

    apply() {
        const {form, onApply} = this.props
        onApply(form && form.values())
    }

    ok() {
        const {form, isActionForm} = this.props
        if (form && (isActionForm || form.isDirty())) {
            this.apply()
            this.closePanel()
        } else {
            this.cancel()
        }
    }

    cancel() {
        const {onCancel} = this.props
        onCancel && onCancel()
        this.closePanel()
    }

    back(panel) {
        this.apply()
        this.selectPanel(panel)
    }

    next(panel) {
        this.apply()
        this.selectPanel(panel)
    }

    done() {
        this.apply()
        this.setInitialized()
        this.closePanel()
    }

    renderForm({form, onApply, top, bottom, left, right, center, inline, panelButtonPosition, className}, content) {
        const classNames = [
            styles.panel,
            top || (panelButtonPosition && panelButtonPosition.top) ? styles.top : null,
            bottom || (panelButtonPosition && panelButtonPosition.bottom) ? styles.bottom : null,
            right || (panelButtonPosition && panelButtonPosition.right) ? styles.right : null,
            left ? styles.bottom : null,
            center ? styles.center : null,
            inline || (panelButtonPosition && panelButtonPosition.inline) ? styles.inline : null,
            className
        ].join(' ')
        return form
            ? (
                <form
                    className={classNames}
                    onSubmit={e => {
                        e.preventDefault()
                        onApply && onApply(form && form.values())
                    }}>
                    {content}
                </form>
            )
            : (

{content}

            )
    }

    renderModal({modal}, content) {
        return modal
            ?
{content}

            : content
    }

    render() {
        const {form = false, isActionForm, initialized, onApply, top, bottom, left, right, center, inline, modal, className, children} = this.props
        const {selectedPanel} = this.props
        return (
            <PanelWizardContext.Consumer>
                {panels => {
                    const wizard = panels && !initialized
                    const selectedPanelIndex = panels.indexOf(selectedPanel)
                    const first = selectedPanelIndex === 0
                    const last = selectedPanelIndex === panels.length - 1
                    return (
                        <PanelButtonContext.Consumer>
                            {panelButtonPosition => (
                                <PanelContext.Provider value={{
                                    wizard,
                                    first,
                                    last,
                                    isActionForm: form && isActionForm,
                                    dirty: form && form.isDirty(),
                                    invalid: form && form.isInvalid(),
                                    onOk: () => this.ok(),
                                    onCancel: () => this.cancel(),
                                    onBack: () => !first && this.back(panels[selectedPanelIndex - 1]),
                                    onNext: () => !last && this.next(panels[selectedPanelIndex + 1]),
                                    onDone: () => this.done()
                                }}>
                                    {this.renderModal({modal},
                                        this.renderForm({form, onApply, top, bottom, left, right, center, inline, panelButtonPosition, className}, children)
                                    )}
                                </PanelContext.Provider>
                            )}
                        </PanelButtonContext.Consumer>
                    )}}
            </PanelWizardContext.Consumer>
        )
    }
}

export default connect(mapStateToProps)(Panel)

Panel.propTypes = {
    children: PropTypes.any.isRequired,
    statePath: PropTypes.string.isRequired,
    bottom: PropTypes.any,
    center: PropTypes.any,
    className: PropTypes.string,
    form: PropTypes.object,
    initialized: PropTypes.any,
    inline: PropTypes.any,
    isActionForm: PropTypes.any,
    left: PropTypes.any,
    modal: PropTypes.any,
    modalOnDirty: PropTypes.any,
    right: PropTypes.any,
    top: PropTypes.any,
    onApply: PropTypes.func,
    onCancel: PropTypes.func,
}

export const PanelHeader = ({icon, title, children}) =>

        {children
            ? children
            : <React.Fragment>
                <Icon name={icon}/>
                {title}
            </React.Fragment>
        }

PanelHeader.propTypes = {
    children: PropTypes.any,
    icon: PropTypes.string,
    title: PropTypes.string,
}

export const PanelContent = ({className, children}) =>

        {children}

PanelContent.propTypes = {
    children: PropTypes.any.isRequired,
    className: PropTypes.string,
}

export const PanelContext = React.createContext()
<|endoftext|>