<commit_before>var util = require('util');
var colors = require('colors');
var moment = require('moment');
var logentries = require('node-logentries');
var config = require('../../config');

var mode = process.env.COLLECTOR_MODE;

var log = logentries.logger({
	token: config.logentries.token
});

log.level('info');

module.exports = {
	success: function (message) {
		message = typeof message === 'string' ? message : JSON.stringify(message);
		console.log(this.timestamptMessage(util.format('SUCCESS: %s', message)).green);
		log.log('info', message);
	},

	warning: function (message) {
		message = typeof message === 'string' ? message : JSON.stringify(message);
		console.log(this.timestamptMessage(util.format('WARNING: %s', message)).yellow);
		log.log('warning', message);
	},

	error: function (message) {
		message = typeof message === 'string' ? message : JSON.stringify(message);
		console.log(this.timestamptMessage(util.format('ERROR: %s', message)).red);
		log.log('err', message);
	},

	fatal: function (message) {
		message = typeof message === 'string' ? message : JSON.stringify(message);
		console.log(this.timestamptMessage(util.format('ERROR: %s', message)).red);
		log.log('emerg', message);
	},

	info: function (message) {
		message = typeof message === 'string' ? message : JSON.stringify(message);
		console.log(this.timestamptMessage(message));
		log.log('info', message);
	},

	connector: function (name) {
		var me = this;

		return {
			info: function (message) {
				me.info('connector ' + name + ': ' + message);
			},
			warning: function (message) {
				me.warning('connector ' + name + ': ' + message);
			},
			error: function (message) {
				me.error('connector ' + name + ': ' + message);
			},
			success: function (message) {
				me.success('connector ' + name + ': ' + message);
			}
		};
	},

	timestamptMessage: function (message) {
		return util.format('[%s] (%s mode) %s', moment(), mode, message);
	}
};<commit_msg>logger<commit_after>var util = require('util');
var colors = require('colors');
var moment = require('moment');
var logentries = require('node-logentries');
var config = require('../../config');

var mode = process.env.COLLECTOR_MODE;

var log = logentries.logger({
	token: config.logentries.token
});

log.level('info');

module.exports = {
	success: function (message) {
		message = typeof message === 'string' ? message : JSON.stringify(message);
		console.log(this.timestamptMessage(util.format('SUCCESS: %s', message)).green);
		log.log('info', util.format('[%s mode] %s', mode, message));
	},

	warning: function (message) {
		message = typeof message === 'string' ? message : JSON.stringify(message);
		console.log(this.timestamptMessage(util.format('WARNING: %s', message)).yellow);
		log.log('warning', util.format('[%s mode] %s', mode, message));
	},

	error: function (message) {
		message = typeof message === 'string' ? message : JSON.stringify(message);
		console.log(this.timestamptMessage(util.format('ERROR: %s', message)).red);
		log.log('err', util.format('[%s mode] %s', mode, message));
	},

	fatal: function (message) {
		message = typeof message === 'string' ? message : JSON.stringify(message);
		console.log(this.timestamptMessage(util.format('ERROR: %s', message)).red);
		log.log('emerg', util.format('[%s mode] %s', mode, message));
	},

	info: function (message) {
		message = typeof message === 'string' ? message : JSON.stringify(message);
		console.log(this.timestamptMessage(message));
		log.log('info', util.format('[%s mode] %s', mode, message));
	},

	connector: function (name) {
		var me = this;

		return {
			info: function (message) {
				me.info('connector ' + name + ': ' + message);
			},
			warning: function (message) {
				me.warning('connector ' + name + ': ' + message);
			},
			error: function (message) {
				me.error('connector ' + name + ': ' + message);
			},
			success: function (message) {
				me.success('connector ' + name + ': ' + message);
			}
		};
	},

	timestamptMessage: function (message) {
		return util.format('[%s] [%s mode] %s', moment(), mode, message);
	}
};<|endoftext|>


<commit_before>'use strict';
/**
 * JSON Translator Factory
 * A factory to handle translation of JSON -> SPARQL
 *
 */

angular.module('GSB.services.translatorToSPARQL', ['GSB.config'])
  .factory('TranslatorToSPARQL', ['globalConfig', '$log', function (globalConfig, $log) {

    var factory = {};

    /**
     * Function to start translation process, with call to changeURIs for the mockup data
	   * and replaceAliasSpaces to replace spaces with underscores
	   * @param json
     */
    factory.translateJSONToSPARQL = function (json) {

      //json = factory.changeURIs(json);

	    json = factory.replaceAliasSpaces(json);

	    return factory.translateAll(json);
    };

    /**
     *  Initial translation function that takes a JSON-object, looks for the main class and starts translation there,
     *  and in the end of the process adds shown values and SPARQL-'header' (e.g. SELECT DISTINCT..)
     * @param json
     */
    factory.translateAll = function (json) {

      var shownValues = [];
      var translated = [];
      var SPARQL = "";

      for(var i = 0; i < json.SUBJECTS.length; i++)
      {
        if(json.SUBJECTS[i].alias === json['START'].link.linkPartner)
        {
          SPARQL +=  factory.translateSubject(json.SUBJECTS[i], shownValues, translated, json);
        }
      }

	 SPARQL += factory.translateInverseSubjects(shownValues, translated, json);

    return factory.translateStartpoint(json, shownValues) + "\nwhere {\n" + SPARQL + "\n} LIMIT 200";
  };

	factory.translateInverseSubjects = function (shownValues, translated, json) {

	  var SPARQL = "";

	  for(var i = 0; i < json.SUBJECTS.length; i++)
        {
          if(!factory.presentInArray(translated, json.SUBJECTS[i].alias))
          {
            SPARQL +=  factory.translateSubject(json.SUBJECTS[i], shownValues, translated, json);
          }
        }

		return SPARQL;
	};

  /**
   * Function to translate the header of a SPARQL query, including the shown values
   * @param json
   * @param shownValues
   */
  factory.translateStartpoint = function (json, shownValues) {

    var SPARQLStart = "";

    if(json.START.type === "LIST_ALL")   {
      SPARQLStart = "SELECT DISTINCT ";
    }
    else {
      SPARQLStart = "SELECT ";
    }

    for(var i = 0; i < shownValues.length; i++) {
      SPARQLStart += "?" + shownValues[i] + " ";
    }

    return SPARQLStart;
  };

    /**
     * Function to translate the header of a SPARQL query, including the shown values
     * @param json
     * @param shownValues
     */
    factory.translateStartpoint = function (json, shownValues) {

      var SPARQLStart = "";

      if(json.START.type === "LIST_ALL")   {
        SPARQLStart = "SELECT DISTINCT ";
      } else {
        SPARQLStart = "SELECT ";
      }

      for(var i = 0; i < shownValues.length; i++) {
        SPARQLStart += "?" + shownValues[i] + " ";
      }

      var spePro = false;
      //Search for specialProperty in the JSON
      for(i = 0; i < json.SUBJECTS.length; i++){

        for(var j = 0; j < json.SUBJECTS[i].properties.length; j++){
          if(json.SUBJECTS[i].properties[j].uri == 'test/specialObjectProperty' || json.SUBJECTS[i].properties[j].uri == 'test/specialDatatypeProperty') {spePro = true;}
        }
      }
      //If specialProperty is part of the properties it's added to the shown values
      if (spePro) {SPARQLStart += '?unknownConnection ';}

      return SPARQLStart;
    };

    /**
     * Function to translate a subject. Calls all translate-property functions for all the subjects properties
     * @param oneSubject
     * @param shownValues
     * @param translated
     * @param json
     */
    factory.translateSubject = function (oneSubject, shownValues, translated, json) {

      var SPARQL = "";

      if(!factory.presentInArray(translated, oneSubject.alias)) {
        if(oneSubject.uri != 'test/Thing')SPARQL += "?" + oneSubject.alias + " a <" + oneSubject.uri + "> .\n";

        if(oneSubject.view) {
          shownValues[shownValues.length] = oneSubject.alias;
        }

        translated[translated.length] = oneSubject.alias;

        for(var i in oneSubject.properties) {

          if(oneSubject.properties[i].type === "OBJECT_PROPERTY") {
            SPARQL += factory.translateObjectProperty(oneSubject, oneSubject.properties[i], shownValues, translated, json) + '\n';
          }
          else {
            SPARQL += factory.translateDatatypeProperty(oneSubject, oneSubject.properties[i], shownValues, translated, json) + '\n';
          }
        }
      }

      return SPARQL;
    };

    /**
     * function to translate Object properties. Checks for operator of property, calls translateSubject when necessary
     * @param itsSubject
     * @param eigenschaft
     * @param shownValues
     * @param translated
     * @param json
     */
    factory.translateObjectProperty = function (itsSubject, eigenschaft, shownValues, translated, json) {

      var SPARQL = "";

      if(eigenschaft.optional) {
	    $log.info("OPTIONAL PROP  - " + eigenschaft.alias);
        SPARQL += "OPTIONAL { \n";
      }

      if(eigenschaft.operator === globalConfig.propertyOperators[0].value) {
        //Special-property has to be translated with ?alias instead of it's URI
        var tailoredURI = eigenschaft.uri;
        if(eigenschaft.uri == 'test/specialObjectProperty') {
          tailoredURI = '?' + 'unknownConnection';
        } else {
          tailoredURI = '<'+ tailoredURI + '>';
        }
        SPARQL += "?" + itsSubject.alias + " " + tailoredURI + " ?";

        if(typeof eigenschaft.link.linkPartner != "undefined") {
          SPARQL +=  eigenschaft.link.linkPartner + " .\n";

          for(i = 0; i < json.SUBJECTS.length; i++) {
            if(json.SUBJECTS[i].alias === eigenschaft.link.linkPartner) {
              SPARQL +=  factory.translateSubject(json.SUBJECTS[i], shownValues, translated, json);
            }
          }
        } else {
          SPARQL +=  eigenschaft.alias  + " .\n";
          if(eigenschaft.optional) {
            SPARQL += "}\n";
          }
          shownValues[shownValues.length] =  + eigenschaft.alias;
        }
      }

      if(eigenschaft.operator === globalConfig.propertyOperators[1].value) {
        if(typeof eigenschaft.link.linkPartner != "undefined") {
          for(i = 0; i < json.SUBJECTS.length; i++) {
            if(json.SUBJECTS[i].alias === eigenschaft.link.linkPartner) {
              SPARQL +=  factory.translateSubject(json.SUBJECTS[i], shownValues, translated, json);
            }
          }

          SPARQL += "FILTER NOT EXISTS { ?"  + itsSubject.alias + " <" + eigenschaft.uri + "> ?" + eigenschaft.link.linkPartner + " } .\n";
        } else {
          SPARQL += "FILTER NOT EXISTS { ?" + itsSubject.alias + " <" + eigenschaft.uri + "> ?"  + eigenschaft.alias + " } .\n";
        }
      }

      if(eigenschaft.operator === globalConfig.inversePropertyOperators[0].value) {
        SPARQL +=  "?" + itsSubject.alias + " ^<" + eigenschaft.uri +  "> ?"  + eigenschaft.link.linkPartner + " .\n";
        for(i = 0; i < json.SUBJECTS.length; i++) {
          if(json.SUBJECTS[i].alias === eigenschaft.link.linkPartner) {
            SPARQL +=  factory.translateSubject(json.SUBJECTS[i], shownValues, translated, json);
          }
        }
      }

      if(eigenschaft.operator === globalConfig.inversePropertyOperators[1].value) {
        for(var i = 0; i < json.SUBJECTS.length; i++) {
          if(json.SUBJECTS[i].alias === eigenschaft.link.linkPartner) {
            SPARQL +=  factory.translateSubject(json.SUBJECTS[i], shownValues, translated, json);
          }
        }
        SPARQL += "FILTER NOT EXISTS { ?" + itsSubject.alias + " ^<" + eigenschaft.uri +  "> ?" + eigenschaft.link.linkPartner + " } .\n";
      }

		  if(eigenschaft.optional) {
        SPARQL += "}\n";
      }

      return SPARQL;
    };

    /**
     * function to translate Datatype properties. Checks for operator of property
     * @param itsSubject
     * @param eigenschaft
     * @param shownValues
     * @param translated
     * @param json
     */
    factory.translateDatatypeProperty = function (itsSubject, eigenschaft, shownValues, translated, json) {

      var SPARQL = "";
      var x,y;
      x = "?" + itsSubject.alias + "_" + eigenschaft.alias;
      y = x;

	  if (eigenschaft.optional) {
          SPARQL += "OPTIONAL { \n";
        }

      if(eigenschaft.operator === globalConfig.propertyOperators[0].value) {

        if (eigenschaft.arithmetic !== null && eigenschaft.arithmetic != "x") {
          x = y + "_temp";
          SPARQL += "?" + itsSubject.alias + " <" + eigenschaft.uri + "> " + x + ".\n";
          SPARQL += "BIND ((" + eigenschaft.arithmetic.replace(/x/g, x) + ") as " + y + ") .\n";
        }
        else {

          //Tailors the uri if the subject is thing.
          // Necessary because Properties have URIs like: <http://dbpedia.org/ontology/Person/weight> but <http://dbpedia.org/ontology/weight> is needed
          var tailoredURI = eigenschaft.uri;
          if (itsSubject.uri == 'test/Thing' && eigenschaft.uri !== 'test/specialDatatypeProperty') {
            var prop = tailoredURI.substr(tailoredURI.lastIndexOf('/'), tailoredURI.length - 1);
            tailoredURI = tailoredURI.substr(0, tailoredURI.lastIndexOf('/'));
            tailoredURI = tailoredURI.substr(0, tailoredURI.lastIndexOf('/')) + prop;

          }

          //Special-property has to be translated with ?alias instead of it's URI
          tailoredURI = '<' + tailoredURI + '>';
          if (eigenschaft.uri == 'test/specialDatatypeProperty') {
            tailoredURI = '?' + eigenschaft.alias;
          }

          SPARQL += "?" + itsSubject.alias + " " + tailoredURI + " " + y + " .\n";
        }

        if (eigenschaft.compare !== null) {

          SPARQL += "FILTER ( "
          + eigenschaft.compare
            .replace(/%before_arithmetic%/g, x)
            .replace(/%after_arithmetic%/g, y)
          + " ) .\n";

        }
      }

      if(eigenschaft.operator === globalConfig.propertyOperators[1].value) {
        SPARQL += "FILTER NOT EXISTS { ?" +  itsSubject.alias + " <" + eigenschaft.uri + "> ?" +  y + " } .\n";
      }

      if(eigenschaft.view === true) {
        shownValues[shownValues.length] =  itsSubject.alias + "_" + eigenschaft.alias;
      }

	  if (eigenschaft.optional) {
          SPARQL += "}\n";
        }

      return SPARQL;
    };

    /**
     * little helper function to replace spaces in aliases with an underscore
     * @param json
     */
    factory.replaceAliasSpaces = function (json) {

      var patt = new RegExp("[^A-Za-z0-9_]","g");

      for(var i = 0; i < json.SUBJECTS.length; i++) {

        json.SUBJECTS[i].alias = json.SUBJECTS[i].alias.replace(patt, "_");

        for(var j = 0; j < json.SUBJECTS[i].properties.length; j++) {

          json.SUBJECTS[i].properties[j].alias = json.SUBJECTS[i].properties[j].alias.replace(patt, "_");
        }
      }
      return json;
    };

    /**
     * little helper function to check, if an object obj is present in an array arr
     * @param arr
     * @param obj
     */
    factory.presentInArray = function (arr, obj) {

      for(var i=0; i<arr.length; i++) {
        if (arr[i] == obj) return true;
      }
      return false;
    };

    return factory;

  }]);
<commit_msg>Added empty aggregate function and handling<commit_after>'use strict';
/**
 * JSON Translator Factory
 * A factory to handle translation of JSON -> SPARQL
 *
 */

angular.module('GSB.services.translatorToSPARQL', ['GSB.config'])
  .factory('TranslatorToSPARQL', ['globalConfig', '$log', function (globalConfig, $log) {

    var factory = {};

    /**
     * Function to start translation process, with call to changeURIs for the mockup data
	   * and replaceAliasSpaces to replace spaces with underscores
	   * @param json
     */
    factory.translateJSONToSPARQL = function (json) {

      //json = factory.changeURIs(json);

	    json = factory.replaceAliasSpaces(json);

	    return factory.translateAll(json);
    };

    /**
     *  Initial translation function that takes a JSON-object, looks for the main class and starts translation there,
     *  and in the end of the process adds shown values and SPARQL-'header' (e.g. SELECT DISTINCT..)
     * @param json
     */
    factory.translateAll = function (json) {

      var shownValues = [];
      var translated = [];
      var SPARQL = "";

      for(var i = 0; i < json.SUBJECTS.length; i++)
      {
        if(json.SUBJECTS[i].alias === json['START'].link.linkPartner)
        {
          SPARQL +=  factory.translateSubject(json.SUBJECTS[i], shownValues, translated, json);
        }
      }

	 SPARQL += factory.translateInverseSubjects(shownValues, translated, json);

    return factory.translateStartpoint(json, shownValues) + "\nwhere {\n" + SPARQL + "\n} LIMIT 200";
  };

	factory.translateInverseSubjects = function (shownValues, translated, json) {

	  var SPARQL = "";

	  for(var i = 0; i < json.SUBJECTS.length; i++)
        {
          if(!factory.presentInArray(translated, json.SUBJECTS[i].alias))
          {
            SPARQL +=  factory.translateSubject(json.SUBJECTS[i], shownValues, translated, json);
          }
        }

		return SPARQL;
	};

  /**
   * Function to translate the header of a SPARQL query, including the shown values
   * @param json
   * @param shownValues
   */
  factory.translateStartpoint = function (json, shownValues) {

    var SPARQLStart = "";

    if(json.START.type === "LIST_ALL")   {
      SPARQLStart = "SELECT DISTINCT ";
    }
    else {
      SPARQLStart = "SELECT ";
    }

    for(var i = 0; i < shownValues.length; i++) {
      SPARQLStart += "?" + shownValues[i] + " ";
    }

    return SPARQLStart;
  };

    /**
     * Function to translate the header of a SPARQL query, including the shown values
     * @param json
     * @param shownValues
     */
    factory.translateStartpoint = function (json, shownValues) {

      var SPARQLStart = "";

      if(json.START.type === "LIST_ALL")   {
        SPARQLStart = "SELECT DISTINCT ";
      } else {
        SPARQLStart = "SELECT ";
      }

      for(var i = 0; i < shownValues.length; i++) {
        SPARQLStart += "?" + shownValues[i] + " ";
      }

      var spePro = false;
      //Search for specialProperty in the JSON
      for(i = 0; i < json.SUBJECTS.length; i++){

        for(var j = 0; j < json.SUBJECTS[i].properties.length; j++){
          if(json.SUBJECTS[i].properties[j].uri == 'test/specialObjectProperty' || json.SUBJECTS[i].properties[j].uri == 'test/specialDatatypeProperty') {spePro = true;}
        }
      }
      //If specialProperty is part of the properties it's added to the shown values
      if (spePro) {SPARQLStart += '?unknownConnection ';}

      return SPARQLStart;
    };

    /**
     * Function to translate a subject. Calls all translate-property functions for all the subjects properties
     * @param oneSubject
     * @param shownValues
     * @param translated
     * @param json
     */
    factory.translateSubject = function (oneSubject, shownValues, translated, json) {

      var SPARQL = "";

      if(!factory.presentInArray(translated, oneSubject.alias)) {
        if(oneSubject.uri != 'test/Thing')SPARQL += "?" + oneSubject.alias + " a <" + oneSubject.uri + "> .\n";

        if(oneSubject.view) {
          shownValues[shownValues.length] = oneSubject.alias;
        }

        translated[translated.length] = oneSubject.alias;

        for(var i in oneSubject.properties) {

          if(oneSubject.properties[i].type === "OBJECT_PROPERTY") {
            SPARQL += factory.translateObjectProperty(oneSubject, oneSubject.properties[i], shownValues, translated, json) + '\n';
          }
		  else if(oneSubject.properties[i].type === "AGGREGATE_PROPERTY") {
		    SPARQL += factory.translateAggregateProperty(oneSubject, oneSubject.properties[i], shownValues, translated, json) + '\n';
		  }
          else {
            SPARQL += factory.translateDatatypeProperty(oneSubject, oneSubject.properties[i], shownValues, translated, json) + '\n';
          }
        }
      }

      return SPARQL;
    };

    /**
     * function to translate Object properties. Checks for operator of property, calls translateSubject when necessary
     * @param itsSubject
     * @param eigenschaft
     * @param shownValues
     * @param translated
     * @param json
     */
    factory.translateObjectProperty = function (itsSubject, eigenschaft, shownValues, translated, json) {

      var SPARQL = "";

      if(eigenschaft.optional) {
	    $log.info("OPTIONAL PROP  - " + eigenschaft.alias);
        SPARQL += "OPTIONAL { \n";
      }

      if(eigenschaft.operator === globalConfig.propertyOperators[0].value) {
        //Special-property has to be translated with ?alias instead of it's URI
        var tailoredURI = eigenschaft.uri;
        if(eigenschaft.uri == 'test/specialObjectProperty') {
          tailoredURI = '?' + 'unknownConnection';
        } else {
          tailoredURI = '<'+ tailoredURI + '>';
        }
        SPARQL += "?" + itsSubject.alias + " " + tailoredURI + " ?";

        if(typeof eigenschaft.link.linkPartner != "undefined") {
          SPARQL +=  eigenschaft.link.linkPartner + " .\n";

          for(i = 0; i < json.SUBJECTS.length; i++) {
            if(json.SUBJECTS[i].alias === eigenschaft.link.linkPartner) {
              SPARQL +=  factory.translateSubject(json.SUBJECTS[i], shownValues, translated, json);
            }
          }
        } else {
          SPARQL +=  eigenschaft.alias  + " .\n";
          if(eigenschaft.optional) {
            SPARQL += "}\n";
          }
          shownValues[shownValues.length] =  + eigenschaft.alias;
        }
      }

      if(eigenschaft.operator === globalConfig.propertyOperators[1].value) {
        if(typeof eigenschaft.link.linkPartner != "undefined") {
          for(i = 0; i < json.SUBJECTS.length; i++) {
            if(json.SUBJECTS[i].alias === eigenschaft.link.linkPartner) {
              SPARQL +=  factory.translateSubject(json.SUBJECTS[i], shownValues, translated, json);
            }
          }

          SPARQL += "FILTER NOT EXISTS { ?"  + itsSubject.alias + " <" + eigenschaft.uri + "> ?" + eigenschaft.link.linkPartner + " } .\n";
        } else {
          SPARQL += "FILTER NOT EXISTS { ?" + itsSubject.alias + " <" + eigenschaft.uri + "> ?"  + eigenschaft.alias + " } .\n";
        }
      }

      if(eigenschaft.operator === globalConfig.inversePropertyOperators[0].value) {
        SPARQL +=  "?" + itsSubject.alias + " ^<" + eigenschaft.uri +  "> ?"  + eigenschaft.link.linkPartner + " .\n";
        for(i = 0; i < json.SUBJECTS.length; i++) {
          if(json.SUBJECTS[i].alias === eigenschaft.link.linkPartner) {
            SPARQL +=  factory.translateSubject(json.SUBJECTS[i], shownValues, translated, json);
          }
        }
      }

      if(eigenschaft.operator === globalConfig.inversePropertyOperators[1].value) {
        for(var i = 0; i < json.SUBJECTS.length; i++) {
          if(json.SUBJECTS[i].alias === eigenschaft.link.linkPartner) {
            SPARQL +=  factory.translateSubject(json.SUBJECTS[i], shownValues, translated, json);
          }
        }
        SPARQL += "FILTER NOT EXISTS { ?" + itsSubject.alias + " ^<" + eigenschaft.uri +  "> ?" + eigenschaft.link.linkPartner + " } .\n";
      }

		  if(eigenschaft.optional) {
        SPARQL += "}\n";
      }

      return SPARQL;
    };

    /**
     * function to translate Datatype properties. Checks for operator of property
     * @param itsSubject
     * @param eigenschaft
     * @param shownValues
     * @param translated
     * @param json
     */
    factory.translateDatatypeProperty = function (itsSubject, eigenschaft, shownValues, translated, json) {

      var SPARQL = "";
      var x,y;
      x = "?" + itsSubject.alias + "_" + eigenschaft.alias;
      y = x;

	  if (eigenschaft.optional) {
          SPARQL += "OPTIONAL { \n";
        }

      if(eigenschaft.operator === globalConfig.propertyOperators[0].value) {

        if (eigenschaft.arithmetic !== null && eigenschaft.arithmetic != "x") {
          x = y + "_temp";
          SPARQL += "?" + itsSubject.alias + " <" + eigenschaft.uri + "> " + x + ".\n";
          SPARQL += "BIND ((" + eigenschaft.arithmetic.replace(/x/g, x) + ") as " + y + ") .\n";
        }
        else {

          //Tailors the uri if the subject is thing.
          // Necessary because Properties have URIs like: <http://dbpedia.org/ontology/Person/weight> but <http://dbpedia.org/ontology/weight> is needed
          var tailoredURI = eigenschaft.uri;
          if (itsSubject.uri == 'test/Thing' && eigenschaft.uri !== 'test/specialDatatypeProperty') {
            var prop = tailoredURI.substr(tailoredURI.lastIndexOf('/'), tailoredURI.length - 1);
            tailoredURI = tailoredURI.substr(0, tailoredURI.lastIndexOf('/'));
            tailoredURI = tailoredURI.substr(0, tailoredURI.lastIndexOf('/')) + prop;

          }

          //Special-property has to be translated with ?alias instead of it's URI
          tailoredURI = '<' + tailoredURI + '>';
          if (eigenschaft.uri == 'test/specialDatatypeProperty') {
            tailoredURI = '?' + eigenschaft.alias;
          }

          SPARQL += "?" + itsSubject.alias + " " + tailoredURI + " " + y + " .\n";
        }

        if (eigenschaft.compare !== null) {

          SPARQL += "FILTER ( "
          + eigenschaft.compare
            .replace(/%before_arithmetic%/g, x)
            .replace(/%after_arithmetic%/g, y)
          + " ) .\n";

        }
      }

      if(eigenschaft.operator === globalConfig.propertyOperators[1].value) {
        SPARQL += "FILTER NOT EXISTS { ?" +  itsSubject.alias + " <" + eigenschaft.uri + "> ?" +  y + " } .\n";
      }

      if(eigenschaft.view === true) {
        shownValues[shownValues.length] =  itsSubject.alias + "_" + eigenschaft.alias;
      }

	  if (eigenschaft.optional) {
          SPARQL += "}\n";
        }

      return SPARQL;
    };

	/**
     * function to translate Aggregate properties. Checks for operator of property
     * @param itsSubject
     * @param eigenschaft
     * @param shownValues
     * @param translated
     * @param json
     */
    factory.translateAggregateProperty = function (itsSubject, eigenschaft, shownValues, translated, json) {

      var SPARQL = "";

	  return SPARQL;
	}

    /**
     * little helper function to replace spaces in aliases with an underscore
     * @param json
     */
    factory.replaceAliasSpaces = function (json) {

      var patt = new RegExp("[^A-Za-z0-9_]","g");

      for(var i = 0; i < json.SUBJECTS.length; i++) {

        json.SUBJECTS[i].alias = json.SUBJECTS[i].alias.replace(patt, "_");

        for(var j = 0; j < json.SUBJECTS[i].properties.length; j++) {

          json.SUBJECTS[i].properties[j].alias = json.SUBJECTS[i].properties[j].alias.replace(patt, "_");
        }
      }
      return json;
    };

    /**
     * little helper function to check, if an object obj is present in an array arr
     * @param arr
     * @param obj
     */
    factory.presentInArray = function (arr, obj) {

      for(var i=0; i<arr.length; i++) {
        if (arr[i] == obj) return true;
      }
      return false;
    };

    return factory;

  }]);
<|endoftext|>


<commit_before>import {SVG_NAMESPACE} from "./settings";
import ParametricAttribute from "./parametric-attribute";

/**
 * @class VirtualTree
 */

export default class VirtualTree {

  constructor (entryPoints, properties) {
    // Extend the instance's properties with `properties`.
    Object.assign(this
      , { _parameters: {}
        , _parametricAttributes: []
        }
      , properties
      );

    // Populate `this._parameters`.
    let parametricAttributes = this._parametricAttributes;
    let pushAttributeIfValid = (element) => (attribute) => {
      let parametricAttribute = new ParametricAttribute(attribute, element);
      if (!parametricAttribute.error) parametricAttributes.push(parametricAttribute);
      };
    entryPoints.forEach(function recurse (element) {
      if (element.namespaceURI === SVG_NAMESPACE) {
        Array.from(element.attributes).forEach(pushAttributeIfValid(element));
        }
      Array.from(element.childNodes).forEach(recurse);
      });

    // Allow chaining.
    return this;
    }

  _render () {
    // Call `.update()` on every ParametricAttribute,
    let getParameter = (name) => this._parameters[name];
    this._parametricAttributes.forEach(parametricAttribute => {
      // passing relevant values from `this._parameters`.
      parametricAttribute.update(
        ...parametricAttribute.parameterNames.map(getParameter)
        );
      });

    // Allow chaining.
    return this;
    }
  }
<commit_msg>Fix parameter retrieval<commit_after>import {SVG_NAMESPACE} from "./settings";
import ParametricAttribute from "./parametric-attribute";

/**
 * @class VirtualTree
 */

export default class VirtualTree {

  constructor (entryPoints, properties) {
    // Extend the instance's properties with `properties`.
    Object.assign(this
      , { _parameters: {}
        , _parametricAttributes: []
        }
      , properties
      );

    // Populate `this._parameters`.
    let parametricAttributes = this._parametricAttributes;
    let pushAttributeIfValid = (element) => (attribute) => {
      let parametricAttribute = new ParametricAttribute(attribute, element);
      if (!parametricAttribute.error) parametricAttributes.push(parametricAttribute);
      };
    entryPoints.forEach(function recurse (element) {
      if (element.namespaceURI === SVG_NAMESPACE) {
        Array.from(element.attributes).forEach(pushAttributeIfValid(element));
        }
      Array.from(element.childNodes).forEach(recurse);
      });

    // Allow chaining.
    return this;
    }

  _render () {
    // Call `.update()` on every ParametricAttribute,
    let getParameter = (name) => {
      let parameter = this._parameters[name];
      return parameter && parameter.value;
      };
    this._parametricAttributes.forEach(parametricAttribute => {
      // passing relevant values from `this._parameters`.
      parametricAttribute.update(
        ...parametricAttribute.parameterNames.map(getParameter)
        );
      });

    // Allow chaining.
    return this;
    }
  }
<|endoftext|>


<commit_before>
exports.client = {};

function quotes (result) {
    return exports.client.mysql ? result : result.replace(/`/g,'"');
}

exports.sql = function (name) {
    var s = '';
    switch (name) {
        // select
        case 'list-view': s = this.client.mysql
                ? "SELECT {0} FROM `{1}` {2} ORDER BY {3} LIMIT {4},{5} ;"
                : "SELECT {0} FROM `{1}` {2} ORDER BY {3} LIMIT {5} OFFSET {4} ;";
        break;
        case 'get-record': s =
                "SELECT {0} FROM `{1}` WHERE `{2}`={3} ;";
        break;
        case 'get-records': s =
                "SELECT {0} FROM `{1}` ;";
        break;
        case 'total': s =
                "SELECT COUNT(*) AS `count` FROM `{0}` ;";
        break;
        // edit
        case 'insert': s = this.client.mysql
                ? "INSERT INTO `{0}` ({1}) VALUES ({2}) ;"
                : "INSERT INTO `{0}` ({1}) VALUES ({2}) RETURNING `{3}` ;";
        break;
        case 'update': s =
                "UPDATE `{0}` SET {1} WHERE `{2}`={3} ;";
        break;
        case 'delete': s =
                "DELETE FROM `{0}` WHERE `{1}`={2} ;";
        break;
        // many to many
        case 'insert-many': s =
                "INSERT INTO `{0}` ({1}) VALUES {2} ;";
        break;
        case 'delete-many': s =
                "DELETE FROM `{0}` WHERE `{1}`={2} AND `{3}` IN ({4}) ;";
        break;

        // config queries
        case 'show-tables': s = this.client.mysql
                ? "SHOW TABLES IN `{0}` ;"
                : "SELECT table_name FROM information_schema.tables WHERE table_schema = '{0}' ;";
        break;
        case 'show-columns': s = this.client.mysql
                ? "SHOW COLUMNS IN `{0}` IN `{1}` ;"
                : 'SELECT cs.column_name AS "Field", cs.data_type AS "Type", cs.is_nullable AS "Null", tc.constraint_type AS "Key", cs.column_default AS "Default",'+
                'cs.numeric_precision, cs.numeric_precision_radix, cs.numeric_scale, cs.character_maximum_length'+
                'FROM information_schema.columns cs'+
                'LEFT JOIN information_schema.key_column_usage kc'+
                '	ON cs.column_name = kc.column_name'+
                '	AND cs.table_schema = kc.table_schema'+
                '	AND cs.table_name = kc.table_name'+
                'LEFT JOIN information_schema.table_constraints tc'+
                '	ON kc.constraint_name = tc.constraint_name'+
                '	AND kc.table_schema = tc.table_schema'+
                '	AND kc.table_name = tc.table_name'+
                'WHERE'+
                '	cs.table_schema = \'{0}\''+
                '	AND cs.table_name = \'{1}\' ;';
        break;

        default: s = 'Query name doesn\'t exist'; break;
    }
    return s;
}

exports.replace = function () {
    if (!arguments.length) return null;
    var sql = quotes(this.sql(arguments[0]));
    if (arguments.length > 1) {
        [].splice.call(arguments, 0, 1);
        for (var i=0; i < arguments.length; i++) {
            sql = sql.replace('{'+i+'}', arguments[i]);
        }
    }
    return sql;
}
<commit_msg>Fixes for pg show-columns query<commit_after>
exports.client = {};

function quotes (result) {
    return exports.client.mysql ? result : result.replace(/`/g,'"');
}

exports.sql = function (name) {
    var s = '';
    switch (name) {
        // select
        case 'list-view': s = this.client.mysql
                ? "SELECT {0} FROM `{1}` {2} ORDER BY {3} LIMIT {4},{5} ;"
                : "SELECT {0} FROM `{1}` {2} ORDER BY {3} LIMIT {5} OFFSET {4} ;";
        break;
        case 'get-record': s =
                "SELECT {0} FROM `{1}` WHERE `{2}`={3} ;";
        break;
        case 'get-records': s =
                "SELECT {0} FROM `{1}` ;";
        break;
        case 'total': s =
                "SELECT COUNT(*) AS `count` FROM `{0}` ;";
        break;
        // edit
        case 'insert': s = this.client.mysql
                ? "INSERT INTO `{0}` ({1}) VALUES ({2}) ;"
                : "INSERT INTO `{0}` ({1}) VALUES ({2}) RETURNING `{3}` ;";
        break;
        case 'update': s =
                "UPDATE `{0}` SET {1} WHERE `{2}`={3} ;";
        break;
        case 'delete': s =
                "DELETE FROM `{0}` WHERE `{1}`={2} ;";
        break;
        // many to many
        case 'insert-many': s =
                "INSERT INTO `{0}` ({1}) VALUES {2} ;";
        break;
        case 'delete-many': s =
                "DELETE FROM `{0}` WHERE `{1}`={2} AND `{3}` IN ({4}) ;";
        break;

        // config queries
        case 'show-tables': s = this.client.mysql
                ? "SHOW TABLES IN `{0}` ;"
                : "SELECT table_name FROM information_schema.tables WHERE table_schema = '{0}' ;";
        break;
        case 'show-columns': s = this.client.mysql
                ? "SHOW COLUMNS IN `{0}` IN `{1}` ;"
                : 'SELECT cs.column_name AS "Field", cs.data_type AS "Type", cs.is_nullable AS "Null", tc.constraint_type AS "Key", cs.column_default AS "Default", '+
                'cs.numeric_precision, cs.numeric_precision_radix, cs.numeric_scale, cs.character_maximum_length '+
                'FROM "information_schema"."columns" cs '+
                'LEFT JOIN "information_schema"."key_column_usage" kc '+
                '	ON cs.column_name = kc.column_name '+
                '	AND cs.table_schema = kc.table_schema '+
                '	AND cs.table_name = kc.table_name '+
                'LEFT JOIN "information_schema"."table_constraints" tc '+
                '	ON kc.constraint_name = tc.constraint_name '+
                '	AND kc.table_schema = tc.table_schema '+
                '	AND kc.table_name = tc.table_name '+
                'WHERE '+
                '	cs.table_name = \'{0}\' '+
                '	AND cs.table_schema = \'{1}\' ;';
        break;

        default: s = 'Query name doesn\'t exist'; break;
    }
    return s;
}

exports.replace = function () {
    if (!arguments.length) return null;
    var sql = quotes(this.sql(arguments[0]));
    if (arguments.length > 1) {
        [].splice.call(arguments, 0, 1);
        for (var i=0; i < arguments.length; i++) {
            sql = sql.replace('{'+i+'}', arguments[i]);
        }
    }
    return sql;
}
<|endoftext|>


<commit_before>
var
allFields = ["firstName","lastName","major","majorShort","email","phone","room","college","country","year","status","username"]; //all possible fields

//build some Regexes
var noQuoteQuery = new RegExp("("+allFields.join("|")+"):\\s?([^\\s\\\"\\']+)", "gi");
var singleQuoteQuery = new RegExp("("+allFields.join("|")+"):\\s?'([^']+)'", "gi");
var doubleQuoteQuery = new RegExp("("+allFields.join("|")+'):\\s?"([^"]+)"', "gi");

//some more Regexes
var yearRegEx = new RegExp("\\b(\\d{2})\\b", "gi");
var phoneRegEx = new RegExp("\\b(?:(?:00)?\\s?49\\s*)?(?:\\s*200)?\\s*(\\d{4})\\b", "gi");

function escapeRegExp(str) {
    //escapes a string for a regexp.
    //from: https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions
    return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}

function escapeFullName(fullName){
    var names = fullName.replace("\\s+", " ").split(" ");
    names = names.map(function(e){
        return "(\\w+\\-)?"+e+"(\\-\\w+)?";
    });

    return names.join(" ([\\w]+ )*")
}

exports.parse = function (query) {
    var query = query || "";
    var result = null;
    var conditions = {};

    //find the full name query by just replaceing everything.
    var fullNameQuery = query
    .replace(noQuoteQuery, "")
    .replace(singleQuoteQuery, "")
    .replace(doubleQuoteQuery, "")
    .trim();

    //go over the phone
    result = phoneRegEx.exec(query);
    while (result != null) {
        conditions["phone"] = "^"+result[1]+"$";
        result = phoneRegEx.exec(query);
    }

    //replace the phone
    fullNameQuery = fullNameQuery.replace(phoneRegEx, "").trim();

    //go over the years
    result = yearRegEx.exec(query);
    while (result != null) {
        conditions["year"] = result[1]+"$";
        result = yearRegEx.exec(query);
    }

    //replace the years
    fullNameQuery = fullNameQuery.replace(yearRegEx, "").trim();

    //iterate over the noQuote Results
    result = noQuoteQuery.exec(query);
    while (result != null) {
        conditions[result[1]] = escapeRegExp(result[2]).replace(", ", ",").split(",").join("|");
        result = noQuoteQuery.exec(query);
    }

    //go over single quotes => these just search with spaces.
    result = singleQuoteQuery.exec(query);
    while (result != null) {
        conditions[result[1]] = escapeRegExp(result[2]).replace(", ", ",").split(",").join("|");
        result = singleQuoteQuery.exec(query);
    }

    //go over double quotes => these just search exact matches (without case).
    result = doubleQuoteQuery.exec(query);
    while (result != null) {
        conditions[result[1]] = "^"+escapeRegExp(result[2]).replace(", ", ",").split(",").join("|")+"$";
        result = doubleQuoteQuery.exec(query);
    }

    //ok, now for the sp

    if(fullNameQuery.trim() != ""){
        //go over the full name if its on-empty
        conditions.fullName = escapeFullName(fullNameQuery);
    }

    //console.log(conditions);
    return conditions;
};
<commit_msg>Added email to autocomplete endpoint<commit_after>
var
allFields = ["firstName","lastName","major","majorShort","email","phone","room","college","country","year","status","username"]; //all possible fields

//build some Regexes
var noQuoteQuery = new RegExp("("+allFields.join("|")+"):\\s?([^\\s\\\"\\']+)", "gi");
var singleQuoteQuery = new RegExp("("+allFields.join("|")+"):\\s?'([^']+)'", "gi");
var doubleQuoteQuery = new RegExp("("+allFields.join("|")+'):\\s?"([^"]+)"', "gi");

//some more Regexes
var yearRegEx = new RegExp("\\b(\\d{2})\\b", "gi");
var phoneRegEx = new RegExp("\\b(?:(?:00)?\\s?49\\s*)?(?:\\s*200)?\\s*(\\d{4})\\b", "gi");
var emailRegEx = new RegExp("\\b([\\w\\.]+)@((j(a(c(o(b(s(-(u(n(i(v(e(r(s(i(t(y(\\.(d(e)?)?)?)?)?)?)?)?)?)?)?)?)?)?)?)?)?)?)?)?\\b|\\s|$)")

function escapeRegExp(str) {
    //escapes a string for a regexp.
    //from: https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions
    return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}

function escapeFullName(fullName){
    var names = fullName.replace("\\s+", " ").split(" ");
    names = names.map(function(e){
        return "(\\w+\\-)?"+e+"(\\-\\w+)?";
    });

    return names.join(" ([\\w]+ )*")
}

exports.parse = function (query) {
    var query = query || "";
    var result = null;
    var conditions = {};

    //find the full name query by just replaceing everything.
    var fullNameQuery = query
    .replace(noQuoteQuery, "")
    .replace(singleQuoteQuery, "")
    .replace(doubleQuoteQuery, "")
    .trim();

    //go over the phone
    result = phoneRegEx.exec(query);
    while (result != null) {
        conditions["phone"] = "^"+result[1]+"$";
        result = phoneRegEx.exec(query);
    }

    //replace the phone
    fullNameQuery = fullNameQuery.replace(phoneRegEx, "").trim();

    //go over the years
    result = yearRegEx.exec(query);
    while (result != null) {
        conditions["year"] = result[1]+"$";
        result = yearRegEx.exec(query);
    }

    //go over the emails
    result = emailRegEx.exec(query);
    while (result != null) {
        conditions["email"] = "^"+result[1]+"@jacobs-university.de$";
        result = emailRegEx.exec(query);
    }

    //replace the years
    fullNameQuery = fullNameQuery.replace(yearRegEx, "").trim();

    //iterate over the noQuote Results
    result = noQuoteQuery.exec(query);
    while (result != null) {
        conditions[result[1]] = escapeRegExp(result[2]).replace(", ", ",").split(",").join("|");
        result = noQuoteQuery.exec(query);
    }

    //go over single quotes => these just search with spaces.
    result = singleQuoteQuery.exec(query);
    while (result != null) {
        conditions[result[1]] = escapeRegExp(result[2]).replace(", ", ",").split(",").join("|");
        result = singleQuoteQuery.exec(query);
    }

    //go over double quotes => these just search exact matches (without case).
    result = doubleQuoteQuery.exec(query);
    while (result != null) {
        conditions[result[1]] = "^"+escapeRegExp(result[2]).replace(", ", ",").split(",").join("|")+"$";
        result = doubleQuoteQuery.exec(query);
    }

    //ok, now for the sp

    if(fullNameQuery.trim() != ""){
        //go over the full name if its on-empty
        conditions.fullName = escapeFullName(fullNameQuery);
    }

    //console.log(conditions);
    return conditions;
};
<|endoftext|>


<commit_before>console.log('121')
if (window.hljs) {
  console.log('111')
  var blocks = document.querySelectorAll('pre code')
  blocks.forEach(window.hljs.highlightBlock)
}
<commit_msg>🔥 remove console.log()<commit_after>if (window.hljs) {
  var blocks = document.querySelectorAll('pre code')
  blocks.forEach(window.hljs.highlightBlock)
}
<|endoftext|>


<commit_before>let http = require('follow-redirects').http;
let https = require('follow-redirects').https;
const {canonicalHost} = require('./host');

const balanceRegex = /([0-9]+) ?([a-zA-Z]*)/;

function joinPath() {
  const path = require('path');
  return path.join.apply(path.join, arguments);
}

function dirname() {
  const path = require('path');
  return path.dirname.apply(path.dirname, arguments);
}

function filesMatchingPattern(files) {
  const globule = require('globule');
  return globule.find(files, {nonull: true});
}

function fileMatchesPattern(patterns, intendedPath) {
  const globule = require('globule');
  return globule.isMatch(patterns, intendedPath);
}

function recursiveMerge(target, source) {
  const merge = require('merge');
  return merge.recursive(target, source);
}

function checkIsAvailable(url, callback) {
  http.get(url, function (_res) {
    callback(true);
  }).on('error', function (_res) {
    callback(false);
  });
}

function httpGetRequest(httpObj, url, callback) {
  httpObj.get(url, function (res) {
    let body = '';
    res.on('data', function (d) {
      body += d;
    });
    res.on('end', function () {
      callback(null, body);
    });
  }).on('error', function (err) {
    callback(err);
  });
}

function httpGet(url, callback) {
  httpGetRequest(http, url, callback);
}

function httpsGet(url, callback) {
  httpGetRequest(https, url, callback);
}

function httpGetJson(url, callback) {
  httpGetRequest(http, url, function (err, body) {
    try {
      let parsed = JSON.parse(body);
      return callback(err, parsed);
    } catch (e) {
      return callback(e);
    }
  });
}

function httpsGetJson(url, callback) {
  httpGetRequest(https, url, function (err, body) {
    try {
      let parsed = JSON.parse(body);
      return callback(err, parsed);
    } catch (e) {
      return callback(e);
    }
  });
}

function getJson(url, cb) {
  if (url.indexOf('https') === 0) {
    return httpsGetJson(url, cb);
  }
  httpGetJson(url, cb);
}

function pingEndpoint(host, port, type, protocol, origin, callback) {
  const options = {
    protocolVersion: 13,
    perMessageDeflate: true,
    origin: origin,
    host: host,
    port: port
  };
  if (type === 'ws') {
    options.headers = {
      'Sec-WebSocket-Version': 13,
      Connection: 'Upgrade',
      Upgrade: 'websocket',
      'Sec-WebSocket-Extensions': 'permessage-deflate; client_max_window_bits',
      Origin: origin
    };
  }
  let req;
  // remove trailing api key from infura, ie rinkeby.infura.io/nmY8WtT4QfEwz2S7wTbl
  if (options.host.indexOf('/') > -1) {
    options.host = options.host.split('/')[0];
  }
  if (protocol === 'https') {
    req = require('https').get(options);
  } else {
    req = require('http').get(options);
  }

  req.on('error', (err) => {
    callback(err);
  });

  req.on('response', (_response) => {
    callback();
  });

  req.on('upgrade', (_res, _socket, _head) => {
    callback();
  });
}

function runCmd(cmd, options, callback) {
  const shelljs = require('shelljs');
  options = options || {silent: true, exitOnError: true};
  console.log(cmd, options, typeof callback);
  let result = shelljs.exec(cmd);
  if (result.code !== 0) {
    console.log("error doing.. " + cmd);
    console.log(result.output);
    if (result.stderr !== undefined) {
      console.log(result.stderr);
    }
    if (typeof callback === 'function') {
      return callback(result, null);
    }
    if (options.exitOnError) {
      exit();
    }
  }
  callback(null, result);
}

function cd(folder) {
  const shelljs = require('shelljs');
  shelljs.cd(folder);
}

function sed(file, pattern, replace) {
  const shelljs = require('shelljs');
  shelljs.sed('-i', pattern, replace, file);
}

function exit(code) {
  process.exit(code);
}

function downloadFile(url, dest, cb) {
  const o_fs = require('fs-extra');
  var file = o_fs.createWriteStream(dest);
  (url.substring(0, 5) === 'https' ? https : http).get(url, function (response) {
    response.pipe(file);
    file.on('finish', function () {
      file.close(cb);
    });
  }).on('error', function (err) {
    o_fs.unlink(dest);
    if (cb) cb(err.message);
  });
}

function extractTar(filename, packageDirectory, cb) {
  const o_fs = require('fs-extra');
  const tar = require('tar');
  o_fs.createReadStream(filename).pipe(
    tar.x({
      strip: 1,
      C: packageDirectory
    }).on('end', function () {
      cb();
    })
  );
}

function extractZip(filename, packageDirectory, opts, cb) {
  const decompress = require('decompress');

  decompress(filename, packageDirectory, opts).then((_files) => {
    cb();
  });
}

function proposeAlternative(word, _dictionary, _exceptions) {
  const propose = require('propose');
  let exceptions = _exceptions || [];
  let dictionary = _dictionary.filter((entry) => {
    return exceptions.indexOf(entry) < 0;
  });
  return propose(word, dictionary, {threshold: 0.3});
}

function getExternalContractUrl(file) {
  const constants = require('../constants');
  let url;
  const RAW_URL = 'https://raw.githubusercontent.com/';
  const MALFORMED_ERROR = 'Malformed Github URL for ';
  if (file.startsWith('https://github')) {
    const match = file.match(/https:\/\/github\.[a-z]+\/(.*)/);
    if (!match) {
      console.error(MALFORMED_ERROR + file);
      return null;
    }
    url = `${RAW_URL}${match[1].replace('blob/', '')}`;
  } else if (file.startsWith('git')) {
    // Match values
    // [0] entire input
    // [1] git://
    // [2] user
    // [3] repository
    // [4] path
    // [5] branch
    const match = file.match(
      /(git:\/\/)?github\.[a-z]+\/([-a-zA-Z0-9@:%_+.~#?&=]+)\/([-a-zA-Z0-9@:%_+.~#?&=]+)\/([-a-zA-Z0-9@:%_+.~?\/&=]+)#?([a-zA-Z0-9\/_.-]*)?/
    );
    if (!match) {
      console.error(MALFORMED_ERROR + file);
      return null;
    }
    let branch = match[5];
    if (!branch) {
      branch = 'master';
    }
    url = `${RAW_URL}${match[2]}/${match[3]}/${branch}/${match[4]}`;
  } else if (file.startsWith('http')) {
    url = file;
  } else {
    return null;
  }
  const match = url.match(
    /\.[a-z]+\/([-a-zA-Z0-9@:%_+.~#?&\/=]+)/
  );
  return {
    url,
    filePath: constants.httpContractsDirectory + match[1]
  };
}

function hexToNumber(hex) {
  const Web3 = require('web3');
  return Web3.utils.hexToNumber(hex);
}

function isHex(hex) {
  const Web3 = require('web3');
  return Web3.utils.isHex(hex);
}

function hashTo32ByteHexString(hash) {
  if (isHex(hash)) {
    if (!hash.startsWith('0x')) {
      hash = '0x' + hash;
    }
    return hash;
  }
  const multihash = require('multihashes');
  let buf = multihash.fromB58String(hash);
  let digest = multihash.decode(buf).digest;
  return '0x' + multihash.toHexString(digest);
}

function isValidDomain(domain) {
  const isValidDomain = require('is-valid-domain');
  return isValidDomain(domain);
}

function isValidEthDomain(ethDomain) {
  if (!isValidDomain(ethDomain)) {
    return false;
  }
  return ethDomain.substring(ethDomain.lastIndexOf('.'), ethDomain.length) === '.eth';
}

function decodeParams(typesArray, hexString) {
  var Web3EthAbi = require('web3-eth-abi');
  return Web3EthAbi.decodeParameters(typesArray, hexString);
}

function toChecksumAddress(address) {
  const Web3 = require('web3');
  return Web3.utils.toChecksumAddress(address);
}

function sha3(arg) {
  const Web3 = require('web3');
  return Web3.utils.sha3(arg);
}

function soliditySha3(arg) {
  const Web3 = require('web3');
  return Web3.utils.soliditySha3(arg);
}

function normalizeInput(input) {
  let args = Object.values(input);
  if (args.length === 0) {
    return "";
  }
  if (args.length === 1) {
    if (Array.isArray(args[0])) {
      return args[0].join(',');
    }
    return args[0] || "";
  }
  return ('[' + args.map((x) => {
    if (x === null) {
      return "null";
    }
    if (x === undefined) {
      return "undefined";
    }
    if (Array.isArray(x)) {
      return x.join(',');
    }
    return x;
  }).toString() + ']');
}

/**
 * Builds a URL
 *
 * @param {string} protocol
 *  The URL protocol, defaults to http.
 * @param {string} host
 *  The URL host, required.
 * @param {string} port
 *  The URL port, default to empty string.
 * @param {string} [type]
 *  Type of connection
 * @returns {string} the constructued URL, with defaults
 */
function buildUrl(protocol, host, port, type) {
  if (!host) throw new Error('utils.buildUrl: parameter \'host\' is required');
  if (port) port = ':' + port;
  else port = '';
  if (!protocol) {
    protocol = type === 'ws' ? 'ws' : 'http';
  }
  return `${protocol}://${host}${port}`;
}

/**
 * Builds a URL
 *
 * @param {object} configObj Object containing protocol, host, and port to be used to construct the url.
 *      * protocol      {String}    (optional) The URL protocol, defaults to http.
 *      * host          {String}    (required) The URL host.
 *      * port          {String}    (optional) The URL port, default to empty string.
 * @returns {string} the constructued URL, with defaults
 */
function buildUrlFromConfig(configObj) {
  if (!configObj) throw new Error('[utils.buildUrlFromConfig]: config object must cannot be null');
  if (!configObj.host) throw new Error('[utils.buildUrlFromConfig]: object must contain a \'host\' property');
  return this.buildUrl(configObj.protocol, canonicalHost(configObj.host), configObj.port, configObj.type);
}

function deconstructUrl(endpoint) {
  const matches = endpoint.match(/(ws|https?):\/\/([a-zA-Z0-9_.-]*):?([0-9]*)?/);
  return {
    protocol: matches[1],
    host: matches[2],
    port: matches[3],
    type: matches[1] === 'ws' ? 'ws' : 'rpc'
  };
}

function getWeiBalanceFromString(balanceString, web3){
  if(!web3){
    throw new Error(__('[utils.getWeiBalanceFromString]: Missing parameter \'web3\''));
  }
  if (!balanceString) {
    return 0;
  }
  const match = balanceString.match(balanceRegex);
  if (!match) {
    throw new Error(__('Unrecognized balance string "%s"', balanceString));
  }
  if (!match[2]) {
    return web3.utils.toHex(parseInt(match[1], 10));
  }

  return web3.utils.toWei(match[1], match[2]);
}

function getHexBalanceFromString(balanceString, web3) {
  if(!web3){
    throw new Error(__('[utils.getWeiBalanceFromString]: Missing parameter \'web3\''));
  }
  if (!balanceString) {
    return 0xFFFFFFFFFFFFFFFFFF;
  }
  if (web3.utils.isHexStrict(balanceString)) {
    return balanceString;
  }
  const match = balanceString.match(balanceRegex);
  if (!match) {
    throw new Error(__('Unrecognized balance string "%s"', balanceString));
  }
  if (!match[2]) {
    return web3.utils.toHex(parseInt(match[1], 10));
  }

  return web3.utils.toHex(web3.utils.toWei(match[1], match[2]));
}

function compact(array) {
  return array.filter(n => n);
}

function groupBy(array, key) {
  return array.reduce(function (rv, x) {
    (rv[x[key]] = rv[x[key]] || []).push(x);
    return rv;
  }, {});
}

function sample(array) {
  return array[Math.floor(Math.random() * array.length)];
}

function last(array) {
  return array[array.length - 1];
}

function interceptLogs(consoleContext, logger) {
  let context = {};
  context.console = consoleContext;

  context.console.log = function () {
    logger.info(normalizeInput(arguments));
  };
  context.console.warn = function () {
    logger.warn(normalizeInput(arguments));
  };
  context.console.info = function () {
    logger.info(normalizeInput(arguments));
  };
  context.console.debug = function () {
    // TODO: ue JSON.stringify
    logger.debug(normalizeInput(arguments));
  };
  context.console.trace = function () {
    logger.trace(normalizeInput(arguments));
  };
  context.console.dir = function () {
    logger.dir(normalizeInput(arguments));
  };
}

function errorMessage(e) {
  if (typeof e === 'string') {
    return e;
  } else if (e && e.message) {
    return e.message;
  }
  return e;
}

module.exports = {
  joinPath,
  dirname,
  filesMatchingPattern,
  fileMatchesPattern,
  recursiveMerge,
  checkIsAvailable,
  httpGet,
  httpsGet,
  httpGetJson,
  httpsGetJson,
  getJson,
  hexToNumber,
  isHex,
  hashTo32ByteHexString,
  isValidDomain,
  isValidEthDomain,
  pingEndpoint,
  decodeParams,
  runCmd,
  cd,
  sed,
  exit,
  downloadFile,
  extractTar,
  extractZip,
  proposeAlternative,
  getExternalContractUrl,
  toChecksumAddress,
  sha3,
  soliditySha3,
  normalizeInput,
  buildUrl,
  buildUrlFromConfig,
  deconstructUrl,
  getWeiBalanceFromString,
  getHexBalanceFromString,
  compact,
  groupBy,
  sample,
  last,
  interceptLogs,
  errorMessage
};
<commit_msg>remove console.log<commit_after>let http = require('follow-redirects').http;
let https = require('follow-redirects').https;
const {canonicalHost} = require('./host');

const balanceRegex = /([0-9]+) ?([a-zA-Z]*)/;

function joinPath() {
  const path = require('path');
  return path.join.apply(path.join, arguments);
}

function dirname() {
  const path = require('path');
  return path.dirname.apply(path.dirname, arguments);
}

function filesMatchingPattern(files) {
  const globule = require('globule');
  return globule.find(files, {nonull: true});
}

function fileMatchesPattern(patterns, intendedPath) {
  const globule = require('globule');
  return globule.isMatch(patterns, intendedPath);
}

function recursiveMerge(target, source) {
  const merge = require('merge');
  return merge.recursive(target, source);
}

function checkIsAvailable(url, callback) {
  http.get(url, function (_res) {
    callback(true);
  }).on('error', function (_res) {
    callback(false);
  });
}

function httpGetRequest(httpObj, url, callback) {
  httpObj.get(url, function (res) {
    let body = '';
    res.on('data', function (d) {
      body += d;
    });
    res.on('end', function () {
      callback(null, body);
    });
  }).on('error', function (err) {
    callback(err);
  });
}

function httpGet(url, callback) {
  httpGetRequest(http, url, callback);
}

function httpsGet(url, callback) {
  httpGetRequest(https, url, callback);
}

function httpGetJson(url, callback) {
  httpGetRequest(http, url, function (err, body) {
    try {
      let parsed = JSON.parse(body);
      return callback(err, parsed);
    } catch (e) {
      return callback(e);
    }
  });
}

function httpsGetJson(url, callback) {
  httpGetRequest(https, url, function (err, body) {
    try {
      let parsed = JSON.parse(body);
      return callback(err, parsed);
    } catch (e) {
      return callback(e);
    }
  });
}

function getJson(url, cb) {
  if (url.indexOf('https') === 0) {
    return httpsGetJson(url, cb);
  }
  httpGetJson(url, cb);
}

function pingEndpoint(host, port, type, protocol, origin, callback) {
  const options = {
    protocolVersion: 13,
    perMessageDeflate: true,
    origin: origin,
    host: host,
    port: port
  };
  if (type === 'ws') {
    options.headers = {
      'Sec-WebSocket-Version': 13,
      Connection: 'Upgrade',
      Upgrade: 'websocket',
      'Sec-WebSocket-Extensions': 'permessage-deflate; client_max_window_bits',
      Origin: origin
    };
  }
  let req;
  // remove trailing api key from infura, ie rinkeby.infura.io/nmY8WtT4QfEwz2S7wTbl
  if (options.host.indexOf('/') > -1) {
    options.host = options.host.split('/')[0];
  }
  if (protocol === 'https') {
    req = require('https').get(options);
  } else {
    req = require('http').get(options);
  }

  req.on('error', (err) => {
    callback(err);
  });

  req.on('response', (_response) => {
    callback();
  });

  req.on('upgrade', (_res, _socket, _head) => {
    callback();
  });
}

function runCmd(cmd, options, callback) {
  const shelljs = require('shelljs');
  options = options || {silent: true, exitOnError: true};
  let result = shelljs.exec(cmd);
  if (result.code !== 0) {
    console.log("error doing.. " + cmd);
    console.log(result.output);
    if (result.stderr !== undefined) {
      console.log(result.stderr);
    }
    if (typeof callback === 'function') {
      return callback(result, null);
    }
    if (options.exitOnError) {
      exit();
    }
  }
  callback(null, result);
}

function cd(folder) {
  const shelljs = require('shelljs');
  shelljs.cd(folder);
}

function sed(file, pattern, replace) {
  const shelljs = require('shelljs');
  shelljs.sed('-i', pattern, replace, file);
}

function exit(code) {
  process.exit(code);
}

function downloadFile(url, dest, cb) {
  const o_fs = require('fs-extra');
  var file = o_fs.createWriteStream(dest);
  (url.substring(0, 5) === 'https' ? https : http).get(url, function (response) {
    response.pipe(file);
    file.on('finish', function () {
      file.close(cb);
    });
  }).on('error', function (err) {
    o_fs.unlink(dest);
    if (cb) cb(err.message);
  });
}

function extractTar(filename, packageDirectory, cb) {
  const o_fs = require('fs-extra');
  const tar = require('tar');
  o_fs.createReadStream(filename).pipe(
    tar.x({
      strip: 1,
      C: packageDirectory
    }).on('end', function () {
      cb();
    })
  );
}

function extractZip(filename, packageDirectory, opts, cb) {
  const decompress = require('decompress');

  decompress(filename, packageDirectory, opts).then((_files) => {
    cb();
  });
}

function proposeAlternative(word, _dictionary, _exceptions) {
  const propose = require('propose');
  let exceptions = _exceptions || [];
  let dictionary = _dictionary.filter((entry) => {
    return exceptions.indexOf(entry) < 0;
  });
  return propose(word, dictionary, {threshold: 0.3});
}

function getExternalContractUrl(file) {
  const constants = require('../constants');
  let url;
  const RAW_URL = 'https://raw.githubusercontent.com/';
  const MALFORMED_ERROR = 'Malformed Github URL for ';
  if (file.startsWith('https://github')) {
    const match = file.match(/https:\/\/github\.[a-z]+\/(.*)/);
    if (!match) {
      console.error(MALFORMED_ERROR + file);
      return null;
    }
    url = `${RAW_URL}${match[1].replace('blob/', '')}`;
  } else if (file.startsWith('git')) {
    // Match values
    // [0] entire input
    // [1] git://
    // [2] user
    // [3] repository
    // [4] path
    // [5] branch
    const match = file.match(
      /(git:\/\/)?github\.[a-z]+\/([-a-zA-Z0-9@:%_+.~#?&=]+)\/([-a-zA-Z0-9@:%_+.~#?&=]+)\/([-a-zA-Z0-9@:%_+.~?\/&=]+)#?([a-zA-Z0-9\/_.-]*)?/
    );
    if (!match) {
      console.error(MALFORMED_ERROR + file);
      return null;
    }
    let branch = match[5];
    if (!branch) {
      branch = 'master';
    }
    url = `${RAW_URL}${match[2]}/${match[3]}/${branch}/${match[4]}`;
  } else if (file.startsWith('http')) {
    url = file;
  } else {
    return null;
  }
  const match = url.match(
    /\.[a-z]+\/([-a-zA-Z0-9@:%_+.~#?&\/=]+)/
  );
  return {
    url,
    filePath: constants.httpContractsDirectory + match[1]
  };
}

function hexToNumber(hex) {
  const Web3 = require('web3');
  return Web3.utils.hexToNumber(hex);
}

function isHex(hex) {
  const Web3 = require('web3');
  return Web3.utils.isHex(hex);
}

function hashTo32ByteHexString(hash) {
  if (isHex(hash)) {
    if (!hash.startsWith('0x')) {
      hash = '0x' + hash;
    }
    return hash;
  }
  const multihash = require('multihashes');
  let buf = multihash.fromB58String(hash);
  let digest = multihash.decode(buf).digest;
  return '0x' + multihash.toHexString(digest);
}

function isValidDomain(domain) {
  const isValidDomain = require('is-valid-domain');
  return isValidDomain(domain);
}

function isValidEthDomain(ethDomain) {
  if (!isValidDomain(ethDomain)) {
    return false;
  }
  return ethDomain.substring(ethDomain.lastIndexOf('.'), ethDomain.length) === '.eth';
}

function decodeParams(typesArray, hexString) {
  var Web3EthAbi = require('web3-eth-abi');
  return Web3EthAbi.decodeParameters(typesArray, hexString);
}

function toChecksumAddress(address) {
  const Web3 = require('web3');
  return Web3.utils.toChecksumAddress(address);
}

function sha3(arg) {
  const Web3 = require('web3');
  return Web3.utils.sha3(arg);
}

function soliditySha3(arg) {
  const Web3 = require('web3');
  return Web3.utils.soliditySha3(arg);
}

function normalizeInput(input) {
  let args = Object.values(input);
  if (args.length === 0) {
    return "";
  }
  if (args.length === 1) {
    if (Array.isArray(args[0])) {
      return args[0].join(',');
    }
    return args[0] || "";
  }
  return ('[' + args.map((x) => {
    if (x === null) {
      return "null";
    }
    if (x === undefined) {
      return "undefined";
    }
    if (Array.isArray(x)) {
      return x.join(',');
    }
    return x;
  }).toString() + ']');
}

/**
 * Builds a URL
 *
 * @param {string} protocol
 *  The URL protocol, defaults to http.
 * @param {string} host
 *  The URL host, required.
 * @param {string} port
 *  The URL port, default to empty string.
 * @param {string} [type]
 *  Type of connection
 * @returns {string} the constructued URL, with defaults
 */
function buildUrl(protocol, host, port, type) {
  if (!host) throw new Error('utils.buildUrl: parameter \'host\' is required');
  if (port) port = ':' + port;
  else port = '';
  if (!protocol) {
    protocol = type === 'ws' ? 'ws' : 'http';
  }
  return `${protocol}://${host}${port}`;
}

/**
 * Builds a URL
 *
 * @param {object} configObj Object containing protocol, host, and port to be used to construct the url.
 *      * protocol      {String}    (optional) The URL protocol, defaults to http.
 *      * host          {String}    (required) The URL host.
 *      * port          {String}    (optional) The URL port, default to empty string.
 * @returns {string} the constructued URL, with defaults
 */
function buildUrlFromConfig(configObj) {
  if (!configObj) throw new Error('[utils.buildUrlFromConfig]: config object must cannot be null');
  if (!configObj.host) throw new Error('[utils.buildUrlFromConfig]: object must contain a \'host\' property');
  return this.buildUrl(configObj.protocol, canonicalHost(configObj.host), configObj.port, configObj.type);
}

function deconstructUrl(endpoint) {
  const matches = endpoint.match(/(ws|https?):\/\/([a-zA-Z0-9_.-]*):?([0-9]*)?/);
  return {
    protocol: matches[1],
    host: matches[2],
    port: matches[3],
    type: matches[1] === 'ws' ? 'ws' : 'rpc'
  };
}

function getWeiBalanceFromString(balanceString, web3){
  if(!web3){
    throw new Error(__('[utils.getWeiBalanceFromString]: Missing parameter \'web3\''));
  }
  if (!balanceString) {
    return 0;
  }
  const match = balanceString.match(balanceRegex);
  if (!match) {
    throw new Error(__('Unrecognized balance string "%s"', balanceString));
  }
  if (!match[2]) {
    return web3.utils.toHex(parseInt(match[1], 10));
  }

  return web3.utils.toWei(match[1], match[2]);
}

function getHexBalanceFromString(balanceString, web3) {
  if(!web3){
    throw new Error(__('[utils.getWeiBalanceFromString]: Missing parameter \'web3\''));
  }
  if (!balanceString) {
    return 0xFFFFFFFFFFFFFFFFFF;
  }
  if (web3.utils.isHexStrict(balanceString)) {
    return balanceString;
  }
  const match = balanceString.match(balanceRegex);
  if (!match) {
    throw new Error(__('Unrecognized balance string "%s"', balanceString));
  }
  if (!match[2]) {
    return web3.utils.toHex(parseInt(match[1], 10));
  }

  return web3.utils.toHex(web3.utils.toWei(match[1], match[2]));
}

function compact(array) {
  return array.filter(n => n);
}

function groupBy(array, key) {
  return array.reduce(function (rv, x) {
    (rv[x[key]] = rv[x[key]] || []).push(x);
    return rv;
  }, {});
}

function sample(array) {
  return array[Math.floor(Math.random() * array.length)];
}

function last(array) {
  return array[array.length - 1];
}

function interceptLogs(consoleContext, logger) {
  let context = {};
  context.console = consoleContext;

  context.console.log = function () {
    logger.info(normalizeInput(arguments));
  };
  context.console.warn = function () {
    logger.warn(normalizeInput(arguments));
  };
  context.console.info = function () {
    logger.info(normalizeInput(arguments));
  };
  context.console.debug = function () {
    // TODO: ue JSON.stringify
    logger.debug(normalizeInput(arguments));
  };
  context.console.trace = function () {
    logger.trace(normalizeInput(arguments));
  };
  context.console.dir = function () {
    logger.dir(normalizeInput(arguments));
  };
}

function errorMessage(e) {
  if (typeof e === 'string') {
    return e;
  } else if (e && e.message) {
    return e.message;
  }
  return e;
}

module.exports = {
  joinPath,
  dirname,
  filesMatchingPattern,
  fileMatchesPattern,
  recursiveMerge,
  checkIsAvailable,
  httpGet,
  httpsGet,
  httpGetJson,
  httpsGetJson,
  getJson,
  hexToNumber,
  isHex,
  hashTo32ByteHexString,
  isValidDomain,
  isValidEthDomain,
  pingEndpoint,
  decodeParams,
  runCmd,
  cd,
  sed,
  exit,
  downloadFile,
  extractTar,
  extractZip,
  proposeAlternative,
  getExternalContractUrl,
  toChecksumAddress,
  sha3,
  soliditySha3,
  normalizeInput,
  buildUrl,
  buildUrlFromConfig,
  deconstructUrl,
  getWeiBalanceFromString,
  getHexBalanceFromString,
  compact,
  groupBy,
  sample,
  last,
  interceptLogs,
  errorMessage
};
<|endoftext|>


<commit_before>
//------------------------------
//- Modulos instalados por mi --
//------------------------------

var nodemailer = require('nodemailer'); // Nodemailer es un módulo externo de node que nos permite mandar correos.
var express = require('express');
var router = express.Router();

// Get home webpage
// I use a REGEX when / and /es will load the same spanish view.
// http://stackoverflow.com/questions/15350025/multiple-routes-single-function-call-express-js

router.get( '/:var(es)?' , function(req, res, next) {
	res.render('index', {
		title: 'Jorge Ferreiro - Programador full stack - Backend / frontend - node, javascript, less.js, jade. ',
		description : 'Full stack programmer. Node, javascript, HTML5, CSS3, JQuery. Desarrollador frontend y backend',
		special : false
	});
});

router.get('/en', function(req, res, next) {
	res.render('index_english', {
		title: 'Jorge Ferreiro - Full-stack programmer - Backend / frontend - node, javascript, less.js, jade. ',
		description : 'Full-stack programmer. Node, javascript, HTML5, CSS3, JQuery. Backend developer and frontend developer',
		special : false
	});
});

router.get( '/en/contact' , function(req, res, next) {
	res.render('contact', {
		title: 'Jorge Ferreiro - Programador full stack - Backend / frontend - node, javascript, less.js, jade. ',
		description : 'Full stack programmer. Node, javascript, HTML5, CSS3, JQuery. Desarrollador frontend y backend',
		special : false
	});
});

router.get('/adaptada', function(req, res, next) {
	res.render('index', {
		title: 'Jorge Ferreiro - Programador full stack - node, javascript, less.js, jade y más. Backend y frontend.',
		description : 'Full stack programmer. Node, javascript, HTML5, CSS3, JQuery',
		special : true
	});
});

router.post('/contact', function(req, res) {
	var form;

	form = {
		subject: 'Tomar algo con Jorge',
	    name: req.body.name,
	    email: req.body.email,
	    day: req.body.day,
	    month: req.body.month,
	    year: req.body.year,
	    time: req.body.time,
	    plan: req.body.plan,
	    error: false
	}

	res.json({
	    data: form          // We pass the form object we created before
	});
});
/*
router.post('/contact2', function (req, res, next) {
    var form; // keep the form data in one variable
    var transporter; // mail variables.
    var msg; // Body message to send the user.

    // Creating a form object and saving the &_POST data.
    // req.body also is an object with the same data  var form = req.body.
    // We use form object to pass the form data to the view and make "JSON" responses.

    form = {
    	subject: 'Tomar algo con Jorge',
        name: req.body.name,
        email: req.body.email,
        day: req.body.day,
        month: req.body.month,
        year: req.body.year,
        time: req.body.time,
        plan: req.body.plan,
        error: false
    }

	// Create reusable transporter object using SMTP transport
	transporter = nodemailer.createTransport({
	    service: 'Gmail',
	    auth: {
	        user: 'landcreativaContactForm@gmail.com',
	        pass: 'landcreativad5Gk6VLpfvmLeGc24HYg'
	    }
	});

	// Preparing email message
	msg =  '';
	msg += '
Mensaje
';
	msg += '
';
	msg += 'Nombre: '  + form.name +'
 ';
	msg += 'Email: '   + form.email + '
';
	msg += 'Date: '    + form.day + '/' + form.month + '/' + form.year + '
';
	msg += 'Time: '    + form.time + '
';
	msg += 'Plan: '    + form.plan + '
';
	msg += '
';
	msg += '';

	// Setup e-mail data with unicode symbols
	var mailOptions = {
	    from: 'Jorge <me@jgferreiro.com>', // sender address
	    to: 'me@jgferreiro.com, ferreirostartups@gmail.com', // list of receivers
	    replyTo: form.email,
	    subject: 'Mensaje de ' + form.name + ' - ' + form.subject, // Subject line
	    html: msg // html body
	};

	// Send mail with defined transport object
	transporter.sendMail(mailOptions, function(error, info) {
		form.error = error; // True: error on the email | false: everything is ok
	});

    // Devolver JSON para cuando se haga un formulario ajax.
    res.json({
        data: form          // We pass the form object we created before
    });

});
*/

module.exports = router;
<commit_msg>Trying to fix a bug in server side<commit_after>
//------------------------------
//- Modulos instalados por mi --
//------------------------------

var nodemailer = require('nodemailer'); // Nodemailer es un módulo externo de node que nos permite mandar correos.
var express = require('express');
var router = express.Router();

// Get home webpage
// I use a REGEX when / and /es will load the same spanish view.
// http://stackoverflow.com/questions/15350025/multiple-routes-single-function-call-express-js

router.get( '/:var(es)?' , function(req, res, next) {
	res.render('index', {
		title: 'Jorge Ferreiro - Programador full stack - Backend / frontend - node, javascript, less.js, jade. ',
		description : 'Full stack programmer. Node, javascript, HTML5, CSS3, JQuery. Desarrollador frontend y backend',
		special : false
	});
});

router.get('/en', function(req, res, next) {
	res.render('index_english', {
		title: 'Jorge Ferreiro - Full-stack programmer - Backend / frontend - node, javascript, less.js, jade. ',
		description : 'Full-stack programmer. Node, javascript, HTML5, CSS3, JQuery. Backend developer and frontend developer',
		special : false
	});
});

router.get( '/en/contact' , function(req, res, next) {
	res.render('contact', {
		title: 'Jorge Ferreiro - Programador full stack - Backend / frontend - node, javascript, less.js, jade. ',
		description : 'Full stack programmer. Node, javascript, HTML5, CSS3, JQuery. Desarrollador frontend y backend',
		special : false
	});
});

router.get('/adaptada', function(req, res, next) {
	res.render('index', {
		title: 'Jorge Ferreiro - Programador full stack - node, javascript, less.js, jade y más. Backend y frontend.',
		description : 'Full stack programmer. Node, javascript, HTML5, CSS3, JQuery',
		special : true
	});
});

router.post('/contact', function(req, res) {
	var form;

	form = {
		subject: 'Tomar algo con Jorge',
	    name: req.body.name,
	    email: req.body.email,
	    day: req.body.day,
	    month: req.body.month,
	    year: req.body.year,
	    time: req.body.time,
	    plan: req.body.plan,
	    error: false
	}

	res.json({"error": false}); // We pass the form object we created before

});
/*
router.post('/contact2', function (req, res, next) {
    var form; // keep the form data in one variable
    var transporter; // mail variables.
    var msg; // Body message to send the user.

    // Creating a form object and saving the &_POST data.
    // req.body also is an object with the same data  var form = req.body.
    // We use form object to pass the form data to the view and make "JSON" responses.

    form = {
    	subject: 'Tomar algo con Jorge',
        name: req.body.name,
        email: req.body.email,
        day: req.body.day,
        month: req.body.month,
        year: req.body.year,
        time: req.body.time,
        plan: req.body.plan,
        error: false
    }

	// Create reusable transporter object using SMTP transport
	transporter = nodemailer.createTransport({
	    service: 'Gmail',
	    auth: {
	        user: 'landcreativaContactForm@gmail.com',
	        pass: 'landcreativad5Gk6VLpfvmLeGc24HYg'
	    }
	});

	// Preparing email message
	msg =  '';
	msg += '
Mensaje
';
	msg += '
';
	msg += 'Nombre: '  + form.name +'
 ';
	msg += 'Email: '   + form.email + '
';
	msg += 'Date: '    + form.day + '/' + form.month + '/' + form.year + '
';
	msg += 'Time: '    + form.time + '
';
	msg += 'Plan: '    + form.plan + '
';
	msg += '
';
	msg += '';

	// Setup e-mail data with unicode symbols
	var mailOptions = {
	    from: 'Jorge <me@jgferreiro.com>', // sender address
	    to: 'me@jgferreiro.com, ferreirostartups@gmail.com', // list of receivers
	    replyTo: form.email,
	    subject: 'Mensaje de ' + form.name + ' - ' + form.subject, // Subject line
	    html: msg // html body
	};

	// Send mail with defined transport object
	transporter.sendMail(mailOptions, function(error, info) {
		form.error = error; // True: error on the email | false: everything is ok
	});

    // Devolver JSON para cuando se haga un formulario ajax.
    res.json({
        data: form          // We pass the form object we created before
    });

});
*/

module.exports = router;
<|endoftext|>


<commit_before>var express = require('express');
var router = express.Router();
var request = require('request');
var _ = require('lodash');

router.get('/', function(req, res) {
   var url = "https://seeclickfix.com/api/v2/issues?place_url=hampton&state=VA&per_page=10&page=1";
   request(url, function(err, response, body) {
   	if(err){
   		console.error(err);
   	}
   	 var list = JSON.parse(body).issues;
  	 var metadata = JSON.parse(body).metadata;
   	 var per_page = metadata.pagination.per_page;
   	 var city = 'hampton';
   	 var pages = list.length;
  	 var lat = _.pluck(list,'lat');
   	 var lng = _.pluck(list, 'lng');
     var start = 0;
   	 var summary = _.pluck(list, 'summary');
     var address = _.pluck(list, 'address');
   	res.render('index', { title: 'Hampton', list: list,
      lat:lat, lng:lng,
      summary:summary, per_page:pages,
      start:start,pages:pages, city:city,
      address:address});
    });
});

router.get('/:city', function(req, res) {
  var city = req.params.city;

  res.redirect('/' + city + '/1');

});

router.get('/:city/:id',function(req,res) {
	var city = req.params.city;
  var id = req.params.id;
  var url = "https://seeclickfix.com/api/v2/issues?place_url="+ city +"&state=VA&per_page=20&page=" + id;

   request(url, function(err, response, body) {
    if(err) {
      console.error(err);
    }
    var list = JSON.parse(body).issues;
    var metadata = JSON.parse(body).metadata;
    var per_page = metadata.pagination.per_page;
    var pages = metadata.pagination.pages;
    var lat = _.pluck(list,'lat');
    var lng = _.pluck(list, 'lng');
    var summary = _.pluck(list, 'summary');
    var address = _.pluck(list, 'address');
    var start = 0;
    var next_page = 2;
    console.log('This is how many pages ', pages);
    if (id <= pages) {
      start = per_page * (id-1);

    }
    if(id < pages) {
      next_page = (Number(id)+1);
    }

    if (city == 'newport-news') {
      title = "newport news";
    } else if (city == 'virginia-beach') {
      title = "virginia beach";
    } else if(city == 'hampton') {
      title = 'hampton';
    } else {
    title = city;
    }
    res.render('index', { title: title, list: list, lat:lat, lng:lng, summary:summary, per_page:per_page, pages:pages,
    start:start, city:city, next_page:next_page, address: address });
    });
});

router.post('/',function(req,res){
  //req.body.city = city name from drop down
  var city = req.body.city;
  var url = "https://seeclickfix.com/api/v2/issues?place_url=" + city + "&state=VA"; //insert city in this link
  request(url, function(err, response, body) {
    if(err){
      console.error(err);
    }
    var list = JSON.parse(body).issues;
    var lat = _.pluck(list,'lat');
    var lng = _.pluck(list, 'lng');
    var summary = _.pluck(list, 'summary');
    res.render('index', { title: city, list:list, lat:lat, lng:lng, summary:summary });
  });

});

module.exports = router;
<commit_msg>Deleted comment in code<commit_after>var express = require('express');
var router = express.Router();
var request = require('request');
var _ = require('lodash');

router.get('/', function(req, res) {
   var url = "https://seeclickfix.com/api/v2/issues?place_url=hampton&state=VA&per_page=10&page=1";
   request(url, function(err, response, body) {
   	if(err){
   		console.error(err);
   	}
   	 var list = JSON.parse(body).issues;
  	 var metadata = JSON.parse(body).metadata;
   	 var per_page = metadata.pagination.per_page;
   	 var city = 'hampton';
   	 var pages = list.length;
  	 var lat = _.pluck(list,'lat');
   	 var lng = _.pluck(list, 'lng');
     var start = 0;
   	 var summary = _.pluck(list, 'summary');
     var address = _.pluck(list, 'address');
   	res.render('index', { title: 'Hampton', list: list,
      lat:lat, lng:lng,
      summary:summary, per_page:pages,
      start:start,pages:pages, city:city,
      address:address});
    });
});

router.get('/:city', function(req, res) {
  var city = req.params.city;

  res.redirect('/' + city + '/1');

});

router.get('/:city/:id',function(req,res) {
	var city = req.params.city;
  var id = req.params.id;
  var url = "https://seeclickfix.com/api/v2/issues?place_url="+ city +"&state=VA&per_page=20&page=" + id;

   request(url, function(err, response, body) {
    if(err) {
      console.error(err);
    }
    var list = JSON.parse(body).issues;
    var metadata = JSON.parse(body).metadata;
    var per_page = metadata.pagination.per_page;
    var pages = metadata.pagination.pages;
    var lat = _.pluck(list,'lat');
    var lng = _.pluck(list, 'lng');
    var summary = _.pluck(list, 'summary');
    var address = _.pluck(list, 'address');
    var start = 0;
    var next_page = 2;
    console.log('This is how many pages ', pages);
    if (id <= pages) {
      start = per_page * (id-1);

    }
    if(id < pages) {
      next_page = (Number(id)+1);
    }

    if (city == 'newport-news') {
      title = "newport news";
    } else if (city == 'virginia-beach') {
      title = "virginia beach";
    } else if(city == 'hampton') {
      title = 'hampton';
    } else {
    title = city;
    }
    res.render('index', { title: title, list: list, lat:lat, lng:lng, summary:summary, per_page:per_page, pages:pages,
    start:start, city:city, next_page:next_page, address: address });
    });
});

router.post('/',function(req,res){
    var city = req.body.city;
    var url = "https://seeclickfix.com/api/v2/issues?place_url=" + city + "&state=VA"; //insert city in this link
    request(url, function(err, response, body) {
      if(err){
        console.error(err);
      }
      var list = JSON.parse(body).issues;
      var lat = _.pluck(list,'lat');
      var lng = _.pluck(list, 'lng');
      var summary = _.pluck(list, 'summary');
      res.render('index', { title: city, list:list, lat:lat, lng:lng, summary:summary });
  });

});

module.exports = router;
<|endoftext|>


<commit_before>var vash = require('vash');

var dateDiff = function(fromdate, todate) {
    var seconds = Math.abs(todate - fromdate) / 1000;
    var divideBy = {
        w: 604800,
        d: 86400,
        h: 3600,
        n: 60,
        s: 1
    };
    var weeks = Math.floor(seconds / divideBy['w']);
    if (weeks > 0)
        return weeks + " weeks ago";
    var days = Math.floor(seconds / divideBy['d']);
    if (days > 0)
        return days + " days ago";
    var hours = Math.floor(seconds / divideBy['h']);
    if (hours > 0)
        return hours + " hours ago";
    var minutes = Math.floor(seconds / divideBy['n']);
    if (minutes > 0)
        return minutes + " minutes ago";
    var secs = Math.floor(seconds / divideBy['s']);
    if (secs > 0)
        return secs + " seconds ago";
};
var today = new Date().toDateString();

var fixupOffset = function(date) {
    date.setHours(date.getHours() - 7);
	return new Date(date);
}

var tpl4 = vash.compile(
    ''+
    '' +
    '' +
        '

' +
        '

' +
        '
OneNote Daily Shared Notes Alerts
' +
        '
' + today + '
' +
        '

' +
        '

' +
    '@model.forEach(' +
    ' function(t) {' +
         '

' +
         '

' +
         '

		' +
         '
@t.name

' +
    '@t.pages.forEach(' +
    'function(pmd) {' +
        '

' +
        '
@pmd.pageTitle

' +
       '@pmd.paragraphs.forEach( function(paramd) { ' +
           '

' +
           '
 @paramd.text …
' +
           '
  was last modified by  @paramd.author   • ' +
           '  @paramd.lastModifiedTime   •
' +
           '

})' +
       '@pmd.images.forEach( function(paramd) { ' +
           '

' +
           '
Found an image containing : @paramd.text …
' +
           '
  was last modified by  @paramd.author   • ' +
           '  @paramd.lastModifiedTime   •
' +
           '

})' +
    '})' +
    '})' +
   '

');

var Vasher = function() {
    this.composeMailBody = function (apiJson) {
        for (var i in apiJson) {
            if (apiJson.hasOwnProperty(i)) {
                for (var j in apiJson[i].pages) {
                    if (apiJson[i].pages.hasOwnProperty(j)) {
                        for (var k in apiJson[i].pages[j].paragraphs) {
                            if (apiJson[i].pages[j].paragraphs.hasOwnProperty(k)) {
                                apiJson[i].pages[j].paragraphs[k].lastModifiedTime = dateDiff(fixupOffset(apiJson[i].pages[j].paragraphs[k].lastModifiedTime), new Date());
                            }
                        }
                        for (var k in apiJson[i].pages[j].images) {
                            if (apiJson[i].pages[j].images.hasOwnProperty(k)) {
                                apiJson[i].pages[j].images[k].lastModifiedTime = dateDiff(fixupOffset(apiJson[i].pages[j].images[k].lastModifiedTime), new Date());
                            }
                        }
                    }
                }
            }
        }
        return tpl4(apiJson);
    };
};

module.exports = new Vasher();
<commit_msg>add new vs update page info to email html<commit_after>var vash = require('vash');

var dateDiff = function(fromdate, todate) {
    var seconds = Math.abs(todate - fromdate) / 1000;
    var divideBy = {
        w: 604800,
        d: 86400,
        h: 3600,
        n: 60,
        s: 1
    };
    var weeks = Math.floor(seconds / divideBy['w']);
    if (weeks > 0)
        return weeks + " weeks ago";
    var days = Math.floor(seconds / divideBy['d']);
    if (days > 0)
        return days + " days ago";
    var hours = Math.floor(seconds / divideBy['h']);
    if (hours > 0)
        return hours + " hours ago";
    var minutes = Math.floor(seconds / divideBy['n']);
    if (minutes > 0)
        return minutes + " minutes ago";
    var secs = Math.floor(seconds / divideBy['s']);
    if (secs > 0)
        return secs + " seconds ago";
};
var today = new Date().toDateString();

var fixupOffset = function(date) {
    date.setHours(date.getHours() - 7);
	return new Date(date);
}

var tpl4 = vash.compile(
    ''+
    '' +
    '' +
        '

' +
        '

' +
        '
OneNote Daily Shared Notes Alerts
' +
        '
' + today + '
' +
        '

' +
        '

' +
    '@model.forEach(' +
    ' function(t) {' +
         '

' +
         '

' +
         '

		' +
         '
@t.name

' +
    '@t.pages.forEach(' +
    'function(pmd) {' +
        '

' +
        '
@{var type = pmd.isNew ? "NEW " : " UPDATE ";} @type @pmd.pageTitle

' +
       '@pmd.paragraphs.forEach( function(paramd) { ' +
           '

' +
           '
 @paramd.text …
' +
           '
  was last modified by  @paramd.author   • ' +
           '  @paramd.lastModifiedTime   •
' +
           '

})' +
       '@pmd.images.forEach( function(paramd) { ' +
           '

' +
           '
Found an image containing : @paramd.text …
' +
           '
  was last modified by  @paramd.author   • ' +
           '  @paramd.lastModifiedTime   •
' +
           '

})' +
    '})' +
    '})' +
   '

');

var Vasher = function() {
    this.composeMailBody = function (apiJson) {
        for (var i in apiJson) {
            if (apiJson.hasOwnProperty(i)) {
                for (var j in apiJson[i].pages) {
                    if (apiJson[i].pages.hasOwnProperty(j)) {
                        for (var k in apiJson[i].pages[j].paragraphs) {
                            if (apiJson[i].pages[j].paragraphs.hasOwnProperty(k)) {
                                apiJson[i].pages[j].paragraphs[k].lastModifiedTime = dateDiff(fixupOffset(apiJson[i].pages[j].paragraphs[k].lastModifiedTime), new Date());
                            }
                        }
                        for (var k in apiJson[i].pages[j].images) {
                            if (apiJson[i].pages[j].images.hasOwnProperty(k)) {
                                apiJson[i].pages[j].images[k].lastModifiedTime = dateDiff(fixupOffset(apiJson[i].pages[j].images[k].lastModifiedTime), new Date());
                            }
                        }
                    }
                }
            }
        }
        return tpl4(apiJson);
    };
};

module.exports = new Vasher();
<|endoftext|>


<commit_before>var express = require('express');
var router = express.Router();

var package = require("../package.json")
/*
 * GET
 */
router.get('/', function(req, res) {
    res.json({doc:"./doc",version:package.version});
});

module.exports = router;<commit_msg>Health check endpoint<commit_after>var express = require('express');
var router = express.Router();

var package = require("../package.json")

/*
 * GET
 */
router.get('/', function(req, res) {
    res.json({doc:"./doc",version:package.version});
});

// Health check
router.get('/sys/info/ping', function(req, res) {
	res.set('Content-Type', 'text/plain');
    res.send("\"OK\"");
});

module.exports = router;<|endoftext|>


<commit_before>//= require_self

$(document).ready(function(){

  var $loader = $('#js-loader');

  function show_loader(block) {
    var w = block.innerWidth(),
        h = block.innerHeight(),
        l = block.offset().left,
        t = block.offset().top;

    $loader.show();

    $loader.css({
      'width': w + 10,
      'height': h + 10,
      'left': l - 5,
      'top': t - 5
    });
  }

// edit name
  (function(){
    var $edit_name = $('#js-edit-name');

    $edit_name.on('keyup', 'input', function(){
      if ($(this).val() === '') {
        $edit_name.removeClass('edit');
      }
      else {
        $edit_name.addClass('edit');
      }
    });

    $edit_name.on('blur', 'input', function(){
      $edit_name.removeClass('edit');
    });
  }());

// tooltips
  (function(){
    var tooltip = $('');

    $('body').append(tooltip);

    var item = $('[data-tooltip]');

    item.hover(function(){
      var $this = $(this),
          offset = $this.offset(),
          tooltip_str = $this.data('tooltip');

      tooltip.html(tooltip_str);

      tooltip.removeClass('hidden');

      var width = tooltip.innerWidth(),
          width_this = $this.innerWidth(),
          height = tooltip.innerHeight();

      tooltip.css({
        'left': (offset.left - (width / 2)) + (width_this / 2),
        'top': offset.top - height - 10
      })
    }, function(){
      tooltip.addClass('hidden');
    });

  }());

// $change-password
  (function(){
    var change_password = $('#change-password'),
        form = $('.fpassword', change_password);

    $('.open', change_password).click(function(){
      $(this).hide();
      $('.fpassword', change_password).removeClass('hide');
      return false;
    });
  }());

  function ajax_go(form, block, name) {
    show_loader(block);

    setTimeout(function(){
      $.ajax({
        type: form.attr('method'),
        url: form.attr('action'),
        data: form.serialize(),
        success: function(data) {
          block.html(data);
          $loader.hide();
          if (name) {
            block.removeClass('edit');
          }
        }
      });
    }, 500);
  }

  $('#js-edit-name').on('submit', 'form', function(){
    var $this = $(this),
        block = $this.parent();

    if (!$('.field input', $this).val()) { return false; }

    ajax_go($this, block, true);

    return false;
  });

  $('#js-registration').on('submit', 'form', function(){
    var $this = $(this),
        block = $this.parent();

    ajax_go($this, block);
    return false;
  });

  $('#js-logo-form input').change(function(){
    $(this).closest('form').submit();
  });

});
<commit_msg>fix js<commit_after>//= require_self

$(document).ready(function(){

  var $loader = $('#js-loader');

  function show_loader(block) {
    var w = block.innerWidth(),
        h = block.innerHeight(),
        l = block.offset().left,
        t = block.offset().top;

    $loader.show();

    $loader.css({
      'width': w + 10,
      'height': h + 10,
      'left': l - 5,
      'top': t - 5
    });
  }

// edit name
  (function(){
    var $edit_name = $('#js-edit-name');

    $edit_name.on('keyup', 'input', function(){
      if ($(this).val() === '') {
        $edit_name.removeClass('edit');
      }
      else {
        $edit_name.addClass('edit');
      }
    });

    $edit_name.on('blur', 'input', function(){
      $edit_name.removeClass('edit');
    });
  }());

// tooltips
  (function(){
    var tooltip = $('');

    $('body').append(tooltip);

    var item = $('[data-tooltip]');

    item.hover(function(){
      var $this = $(this),
          offset = $this.offset(),
          tooltip_str = $this.data('tooltip');

      tooltip.html(tooltip_str);

      tooltip.removeClass('hidden');

      var width = tooltip.innerWidth(),
          width_this = $this.innerWidth(),
          height = tooltip.innerHeight();

      tooltip.css({
        'left': (offset.left - (width / 2)) + (width_this / 2),
        'top': offset.top - height - 10
      })
    }, function(){
      tooltip.addClass('hidden');
    });
  }());

// $change-password
  (function(){
    var change_password = $('#change-password'),
        form = $('.fpassword', change_password);

    $('.open', change_password).click(function(){
      $(this).hide();
      $('.fpassword', change_password).removeClass('hide');
      return false;
    });
  }());

  function ajax_go(form, block, name) {
    show_loader(block);

    setTimeout(function(){
      $.ajax({
        type: form.attr('method'),
        url: form.attr('action'),
        data: form.serialize(),
        success: function(data) {
          block.html(data);
          $loader.hide();
          if (name) {
            block.removeClass('edit');
          }
        }
      });
    }, 500);
  }

  $('#js-edit-name').on('submit', 'form', function(){
    var $this = $(this),
        block = $this.parent();

    if (!$('.field input', $this).val()) { return false; }

    ajax_go($this, block, true);

    return false;
  });

  $('#js-registration').on('submit', 'form', function(){
    var $this = $(this),
        block = $this.parent();

    ajax_go($this, block);
    return false;
  });

  $('#js-logo-form input').change(function(){
    $(this).closest('form').submit();
  });
});
<|endoftext|>