<commit_before>/**
* COMPONENT_CALCULATION
*
*
*
*/
var component_calculation = new function() {

	"use strict"

	// LOCAL VARS
	this.url_trigger = DEDALO_LIB_BASE_URL + '/component_calculation/trigger.component_calculation.php';

	/**
	* INIT
	*/
	this.inited = []
	this.init = function(options) {

		const self = this

		const component_name 		= options.component_name
		const uid 			 		= options.uid
		const aditional_save_event 	= options.aditional_save_event

		// id_wrapper. Overwrited when is set in options
		const id_wrapper  = (typeof options.id_wrapper!=="undefined") ? options.id_wrapper : 'wrapper_' + options.uid
		const wrapper_obj = document.getElementById(id_wrapper)
			if (!wrapper_obj) {
				// Error on find wrapper
				let msg = "[component_calculation:init] ERROR. wrapper_obj not found! ("+id_wrapper+")"
				console.warn(msg, "id_wrapper: ",id_wrapper)
				alert(msg)
				return false
			}

		const init_uid = wrapper_obj.dataset.section_tipo +"_"+ wrapper_obj.dataset.parent +"_"+ wrapper_obj.dataset.tipo
			//console.log("this.inited", init_uid, this.inited, this.inited[init_uid]);

		//this.get_dato(wrapper_obj)
		if (typeof component_calculation.inited[init_uid]==="undefined" || component_calculation.inited[init_uid]!==true) {

			const formula   	 		= wrapper_obj.dataset.formula
			const formula_parsed 		= JSON.parse(formula)
			const ar_components_formula	= wrapper_obj.dataset.ar_components_formula
			const data 					= JSON.parse(ar_components_formula)
			const custom  				= formula_parsed.custom
			// Merge and remove duplicates
			const ar_component_save 	= Array.from(new Set(data.concat(aditional_save_event))); //data.concat(aditional_save_event)

			// Load custom script for do calculations ex: in ../extra/mdcat/calulation/expresos.js
				if(custom){
					common.load_script(DEDALO_LIB_BASE_URL +"/extras"+custom.file, {"async":false})
				}

			// Load page event
				window.addEventListener("load", function (event) {
					component_calculation.get_dato(wrapper_obj)
				});

			// Save component event. Triggerred on save component with tipo inckuded in formula
				window.addEventListener('component_save', function(event){
					// console.log("event:",event.detail.dataset.tipo, event.detail.dataset.component_name, event.detail.dataset.label);
					const saved_tipo = event.detail.dataset.tipo
					if(SHOW_DEBUG===true) {
						console.log("[component_calculation.init] event component_save saved_tipo, ar_component_save tipo: ", saved_tipo, ar_component_save, uid);
					}
					if(ar_component_save.includes(saved_tipo)){

						// Re select wrapper and reload twice
							const current_wrapper = document.getElementById(id_wrapper)
							if (current_wrapper) {
								const js_promise = component_common.load_component_by_wrapper_id(id_wrapper).then(function(response){
									//update the dato
									const new_component = document.getElementById(id_wrapper)
									const dato_promise  = self.get_dato(new_component)

									dato_promise.then(function(){
										component_common.load_component_by_wrapper_id(id_wrapper)
									},false)
								})
							}
					}
				},false)

		}//end if (this.inited!==true)

		// Set as initied
		component_calculation.inited[init_uid] = true

		return true
	};//end init

	/**
	* GET_DATO
	* @return
	*/
	this.get_dato = function(wrapper_obj) {

		const self = this

		//console.log(wrapper_obj);
		return new Promise(function(resolve, reject) {

			const saved_dato 	= wrapper_obj.dataset.dato
			const content_data 	= wrapper_obj.querySelector('div.css_calculation')
			self.solve_the_formula(content_data).then(function(dato_solved){

				// unify numbers format
					const saved_dato_sure = common.safe_number(saved_dato)

				//console.log("saved_dato", dato);
				//console.log("new dato",dato);
				//console.log("dato != saved_dato", dato != saved_dato);
				//console.log("+++ dato_solved", dato_solved, typeof dato_solved,"saved_dato_sure:", saved_dato_sure, typeof saved_dato_sure, "!=", dato_solved!=saved_dato_sure, "!==", dato_solved!==saved_dato_sure);

				if(dato_solved!==saved_dato_sure) {
					// Fix dato
						wrapper_obj.dataset.dato = dato_solved
						content_data.innerHTML   = dato_solved
						//wrapper_obj.dataset.formula = content_data.dataset.formula

					//self.save_arguments.dato = JSON.stringify(dato);
					self.save_arguments.dato = dato_solved;
					// Save changed dato
					self.Save(content_data).then(function(response){
						resolve(dato_solved);
					})
				}else{
					// Fix dato
						wrapper_obj.dataset.dato = dato_solved
						content_data.innerHTML   = dato_solved

					resolve(dato_solved);
				}

			})

		})
	};//end get_dato

	/**
	* SAVE
	* @return
	*/
	this.save_arguments = {}
	this.Save = function(component_obj) {

		const self = this
		// Exec general save

		const jsPromise = component_common.Save(component_obj, self.save_arguments);

		jsPromise.then(function(response) {

		}, function(xhrObj) {
		  	console.log(xhrObj);
		});

		return jsPromise;
	};//end Save

	/**
	* SOLVE_THE_FORMULA
	* @return
	*/
	this.solve_the_formula = function(content_data) {

		const self = this

		const data 	 	= JSON.parse(content_data.dataset.formula).data
		const custom  	= JSON.parse(content_data.dataset.formula).custom
		const rules  	= JSON.parse(content_data.dataset.formula).rules
		const formula_result = JSON.parse(content_data.dataset.formula).result

		return new Promise(function(resolve, reject) {

			//custom formula rules
			if(custom){
				const options = custom.options
				      options.data = data

				const ar_paths 	= custom.process.split('.')

				if (typeof window[ar_paths[0]][ar_paths[1]]==="undefined") {

					console.warn("custom.process is not function:",custom.process, typeof window[custom.process]);

					resolve(false)

				}else{

					const result = window[ar_paths[0]][ar_paths[1]](options)

					resolve(result)
				}
			}

			//standard way
			if(formula_result === 'date'){
				const result = self.preproces_data_date(data, rules)
				resolve(result)
			}

			jsonLogic.add_operation("Math", Math);

			// Apply rules to data
			let result = jsonLogic.apply(rules, data)

			if(formula_result === 'int'){
				result = Math.round(result)
			}

			if(formula_result && formula_result.number_type === 'float'){
				const precision = formula_result.precision

				let multipicator = "1"
				for (var i = precision - 1; i >= 0; i--) {
					multipicator = multipicator + "0"
				}

				multipicator = parseInt(multipicator)

				result = Math.round(result * multipicator) / multipicator
			}

			if(formula_result && formula_result.process){
				const proces_result = self[formula_result.process]({
					result:	result,
					options: formula_result.options})
				result = proces_result
			}

			if(SHOW_DEBUG===true) {
				console.log("[solve_the_formula] rules:",rules);
			}

			resolve(result)
		})
	};//end solve_the_formula

	/**
	* REFRESH_DATO
	* @return
	*/
	this.refresh_dato = function(wrapper_obj) {

		const self = this

		const id_wrapper = wrapper_obj.id

		const js_promise = component_common.load_component_by_wrapper_id(id_wrapper).then(function(response){
			//update the dato
			return new Promise(function(resolve, reject) {
				let new_component = document.getElementById(id_wrapper)
				resolve(self.get_dato(new_component))

			})
		})

		return js_promise
	};//end refresh_dato

	/**
	* PREPROCES_DATA_DATE
	* @return
	*/
	this.preproces_data_date = function(data, rules, options) {

		var result
		for(var operator in rules){

			for (var i = 0; i < rules[operator].length; i++) {

				const item = rules[operator][i].var
				const dd_date = data[item]
				const date = {}

				if (data[item].format==='date'){
					date[item] = new Date(dd_date.year, dd_date.month -1, dd_date.day);
				}else{
					date[item] = dd_date
				}

				if (i===0) {
					result = date[item]
				}else{

					if (data[item].format==='period') {

						if(data[item].day){
							const day = parseInt(operator + data[item].day);
							result.setDate(result.getDate() + day )
						}

						if(data[item].month){
							const month = parseInt(operator + data[item].month);
							result.setMonth(result.getMonth() + month)
						}

						if(data[item].year){
							const year = parseInt(operator + data[item].year);
							result.setFullYear(result.getFullYear() + year)
						}
					}else{
						// TO DEFINE WHEN THE CASE WIL DONE
						result = result + date[item]
					}
				}
			}
		}//end for(var operator in rules)

		// Format date using locale format
			const locale = common.get_locale_from_code(page_globals.dedalo_data_lang)
			result = result.toLocaleString(locale, {year:"numeric",month:"numeric",day:"numeric"});

		return result
	}//end preproces_data_date

	/**
	* PROCES_SECONS_TO_PERIOD
	* @return
	*/
	this.proces_secons_to_period = function(request_options){

		const seconds = request_options.result
		const options = request_options.options

		const minutes 		= Math.floor(seconds / 60)
		const hours 		= Math.floor(seconds / 60 / 60)
		const total_days 	= Math.floor(seconds / 60 / 60 / 24)
		const years 		= Math.floor(total_days / 365)
		const years_days 	= total_days - (years * 365)
		const total_months 	= Math.floor(total_days / 30.42)

		let months 	= 0
		let days 	= 0

		switch(true){
			//decembre + 30
			case years_days >= 334 :
				months 		= 11
				days 		= years_days - 334
			break;
			//novembre + 31
			case years_days >= 304 :
				months 		= 10
				days 		= years_days - 304
			break;
			//october + 30
			case years_days >= 272 :
				months 		= 9
				days 		= years_days - 272
			break;
			//septembre + 31
			case years_days >= 242 :
				months 		= 8
				days 		= years_days - 242
			break;
			//agost + 31
			case years_days >= 211 :
				months 		= 7
				days 		= years_days - 211
			break;
			//july + 30
			case years_days >= 180 :
				months 		= 6
				days 		= years_days - 180
			break;
			//juny + 31
			case years_days >= 150 :
				months 		= 5
				days 		= years_days - 150
			break;
			//may + 30
			case years_days >= 119 :
				months 		= 4
				days 		= years_days - 119
			break;
			//april + 31
			case years_days >= 89 :
				months 		= 3
				days 		= years_days - 89
			break;
			//march + 28
			case years_days >= 59 :
				months 		= 2
				days 		= years_days - 59
			break;
			//february + 31
			case years_days >= 31 :
				months 		= 1
				days 		= years_days - 31
			break;
			//January + 0
			case years_days >= 0 :
				months 		= 0
				days 		= years_days
			break;

		}

		let period = []

		if(years > 0 && options.years === true){
			const year_label = years == 1 ? get_label["anyo"] : get_label["anyos"]
			const year_value = (options.label===true) ? years + ' ' + year_label : years
			period.push(year_value)
		}

		if(months > 0 && options.months === true){
			const months_label = months == 1 ? get_label["mes"] : get_label["meses"]
			let months_value = ""
			if(options.total === true){
				months_value = (options.label===true) ? total_months + ' ' + months_label : total_months
			}else{
				months_value = (options.label===true) ? months + ' ' + months_label : months
			}
			period.push(months_value)
		}

		if(days > 0 && options.days === true){
			const days_label = days == 1 ? get_label["dia"] : get_label["dias"]
			let days_value = ""
			if(options.total === true){
				days_value = (options.label===true) ? total_days + ' ' + days_label : total_days
			}else{
				days_value = (options.label===true) ? days + ' ' + days_label : days

			}
			period.push(days_value)
		}

		const result = period.join(', ')

		return result

	}//end proces_secons_to_period

}//end component_calculation<commit_msg>Fix the date calculation when preriod or date = 0<commit_after>/**
* COMPONENT_CALCULATION
*
*
*
*/
var component_calculation = new function() {

	"use strict"

	// LOCAL VARS
	this.url_trigger = DEDALO_LIB_BASE_URL + '/component_calculation/trigger.component_calculation.php';

	/**
	* INIT
	*/
	this.inited = []
	this.init = function(options) {

		const self = this

		const component_name 		= options.component_name
		const uid 			 		= options.uid
		const aditional_save_event 	= options.aditional_save_event

		// id_wrapper. Overwrited when is set in options
		const id_wrapper  = (typeof options.id_wrapper!=="undefined") ? options.id_wrapper : 'wrapper_' + options.uid
		const wrapper_obj = document.getElementById(id_wrapper)
			if (!wrapper_obj) {
				// Error on find wrapper
				let msg = "[component_calculation:init] ERROR. wrapper_obj not found! ("+id_wrapper+")"
				console.warn(msg, "id_wrapper: ",id_wrapper)
				alert(msg)
				return false
			}

		const init_uid = wrapper_obj.dataset.section_tipo +"_"+ wrapper_obj.dataset.parent +"_"+ wrapper_obj.dataset.tipo
			//console.log("this.inited", init_uid, this.inited, this.inited[init_uid]);

		//this.get_dato(wrapper_obj)
		if (typeof component_calculation.inited[init_uid]==="undefined" || component_calculation.inited[init_uid]!==true) {

			const formula   	 		= wrapper_obj.dataset.formula
			const formula_parsed 		= JSON.parse(formula)
			const ar_components_formula	= wrapper_obj.dataset.ar_components_formula
			const data 					= JSON.parse(ar_components_formula)
			const custom  				= formula_parsed.custom
			// Merge and remove duplicates
			const ar_component_save 	= Array.from(new Set(data.concat(aditional_save_event))); //data.concat(aditional_save_event)

			// Load custom script for do calculations ex: in ../extra/mdcat/calulation/expresos.js
				if(custom){
					common.load_script(DEDALO_LIB_BASE_URL +"/extras"+custom.file, {"async":false})
				}

			// Load page event
				window.addEventListener("load", function (event) {
					component_calculation.get_dato(wrapper_obj)
				});

			// Save component event. Triggerred on save component with tipo inckuded in formula
				window.addEventListener('component_save', function(event){
					// console.log("event:",event.detail.dataset.tipo, event.detail.dataset.component_name, event.detail.dataset.label);
					const saved_tipo = event.detail.dataset.tipo
					if(SHOW_DEBUG===true) {
						console.log("[component_calculation.init] event component_save saved_tipo, ar_component_save tipo: ", saved_tipo, ar_component_save, uid);
					}
					if(ar_component_save.includes(saved_tipo)){

						// Re select wrapper and reload twice
							const current_wrapper = document.getElementById(id_wrapper)
							if (current_wrapper) {
								const js_promise = component_common.load_component_by_wrapper_id(id_wrapper).then(function(response){
									//update the dato
									const new_component = document.getElementById(id_wrapper)
									const dato_promise  = self.get_dato(new_component)

									dato_promise.then(function(){
										component_common.load_component_by_wrapper_id(id_wrapper)
									},false)
								})
							}
					}
				},false)

		}//end if (this.inited!==true)

		// Set as initied
		component_calculation.inited[init_uid] = true

		return true
	};//end init

	/**
	* GET_DATO
	* @return
	*/
	this.get_dato = function(wrapper_obj) {

		const self = this

		//console.log(wrapper_obj);
		return new Promise(function(resolve, reject) {

			const saved_dato 	= wrapper_obj.dataset.dato
			const content_data 	= wrapper_obj.querySelector('div.css_calculation')
			self.solve_the_formula(content_data).then(function(dato_solved){

				// unify numbers format
					const saved_dato_sure = common.safe_number(saved_dato)

				//console.log("saved_dato", dato);
				//console.log("new dato",dato);
				//console.log("dato != saved_dato", dato != saved_dato);
				//console.log("+++ dato_solved", dato_solved, typeof dato_solved,"saved_dato_sure:", saved_dato_sure, typeof saved_dato_sure, "!=", dato_solved!=saved_dato_sure, "!==", dato_solved!==saved_dato_sure);

				if(dato_solved!==saved_dato_sure) {
					// Fix dato
						wrapper_obj.dataset.dato = dato_solved
						content_data.innerHTML   = dato_solved
						//wrapper_obj.dataset.formula = content_data.dataset.formula

					//self.save_arguments.dato = JSON.stringify(dato);
					self.save_arguments.dato = dato_solved;
					// Save changed dato
					self.Save(content_data).then(function(response){
						resolve(dato_solved);
					})
				}else{
					// Fix dato
						wrapper_obj.dataset.dato = dato_solved
						content_data.innerHTML   = dato_solved

					resolve(dato_solved);
				}

			})

		})
	};//end get_dato

	/**
	* SAVE
	* @return
	*/
	this.save_arguments = {}
	this.Save = function(component_obj) {

		const self = this
		// Exec general save

		const jsPromise = component_common.Save(component_obj, self.save_arguments);

		jsPromise.then(function(response) {

		}, function(xhrObj) {
		  	console.log(xhrObj);
		});

		return jsPromise;
	};//end Save

	/**
	* SOLVE_THE_FORMULA
	* @return
	*/
	this.solve_the_formula = function(content_data) {

		const self = this

		const data 	 	= JSON.parse(content_data.dataset.formula).data
		const custom  	= JSON.parse(content_data.dataset.formula).custom
		const rules  	= JSON.parse(content_data.dataset.formula).rules
		const formula_result = JSON.parse(content_data.dataset.formula).result

		return new Promise(function(resolve, reject) {

			//custom formula rules
			if(custom){
				const options = custom.options
				      options.data = data

				const ar_paths 	= custom.process.split('.')

				if (typeof window[ar_paths[0]][ar_paths[1]]==="undefined") {

					console.warn("custom.process is not function:",custom.process, typeof window[custom.process]);

					resolve(false)

				}else{

					const result = window[ar_paths[0]][ar_paths[1]](options)

					resolve(result)
				}
			}

			//standard way
			if(formula_result === 'date'){
				const result = self.preproces_data_date(data, rules)
				resolve(result)
			}

			jsonLogic.add_operation("Math", Math);

			// Apply rules to data
			let result = jsonLogic.apply(rules, data)

			if(formula_result === 'int'){
				result = Math.round(result)
			}

			if(formula_result && formula_result.number_type === 'float'){
				const precision = formula_result.precision

				let multipicator = "1"
				for (var i = precision - 1; i >= 0; i--) {
					multipicator = multipicator + "0"
				}

				multipicator = parseInt(multipicator)

				result = Math.round(result * multipicator) / multipicator
			}

			if(formula_result && formula_result.process){
				const proces_result = self[formula_result.process]({
					result:	result,
					options: formula_result.options})
				result = proces_result
			}

			if(SHOW_DEBUG===true) {
				console.log("[solve_the_formula] rules:",rules);
			}

			resolve(result)
		})
	};//end solve_the_formula

	/**
	* REFRESH_DATO
	* @return
	*/
	this.refresh_dato = function(wrapper_obj) {

		const self = this

		const id_wrapper = wrapper_obj.id

		const js_promise = component_common.load_component_by_wrapper_id(id_wrapper).then(function(response){
			//update the dato
			return new Promise(function(resolve, reject) {
				let new_component = document.getElementById(id_wrapper)
				resolve(self.get_dato(new_component))

			})
		})

		return js_promise
	};//end refresh_dato

	/**
	* PREPROCES_DATA_DATE
	* @return
	*/
	this.preproces_data_date = function(data, rules, options) {

		var result
		for(var operator in rules){

			for (var i = 0; i < rules[operator].length; i++) {

				const item = rules[operator][i].var
				const dd_date = data[item]
				const date = {}

				if (data[item].format==='date'){
					date[item] = new Date(dd_date.year, dd_date.month -1, dd_date.day);
				}else{
					date[item] = dd_date
				}

				if (i===0) {
					result = date[item]
				}else{

					if (data[item].format==='period') {

						if(data[item].day){
							const day = parseInt(operator + data[item].day);
							result.setDate(result.getDate() + day )
						}

						if(data[item].month){
							const month = parseInt(operator + data[item].month);
							result.setMonth(result.getMonth() + month)
						}

						if(data[item].year){
							const year = parseInt(operator + data[item].year);
							result.setFullYear(result.getFullYear() + year)
						}

					}else{
						// TO DEFINE WHEN THE CASE WIL DONE
						if (date[item] ===0){
							result = result
						}else{
							result = result + date[item]
						}

					}
				}
			}
		}//end for(var operator in rules)

		// Format date using locale format
			const locale = common.get_locale_from_code(page_globals.dedalo_data_lang)
			result = result.toLocaleString(locale, {year:"numeric",month:"numeric",day:"numeric"});

		return result
	}//end preproces_data_date

	/**
	* PROCES_SECONS_TO_PERIOD
	* @return
	*/
	this.proces_secons_to_period = function(request_options){

		const seconds = request_options.result
		const options = request_options.options

		const minutes 		= Math.floor(seconds / 60)
		const hours 		= Math.floor(seconds / 60 / 60)
		const total_days 	= Math.floor(seconds / 60 / 60 / 24)
		const years 		= Math.floor(total_days / 365)
		const years_days 	= total_days - (years * 365)
		const total_months 	= Math.floor(total_days / 30.42)

		let months 	= 0
		let days 	= 0

		switch(true){
			//decembre + 30
			case years_days >= 334 :
				months 		= 11
				days 		= years_days - 334
			break;
			//novembre + 31
			case years_days >= 304 :
				months 		= 10
				days 		= years_days - 304
			break;
			//october + 30
			case years_days >= 272 :
				months 		= 9
				days 		= years_days - 272
			break;
			//septembre + 31
			case years_days >= 242 :
				months 		= 8
				days 		= years_days - 242
			break;
			//agost + 31
			case years_days >= 211 :
				months 		= 7
				days 		= years_days - 211
			break;
			//july + 30
			case years_days >= 180 :
				months 		= 6
				days 		= years_days - 180
			break;
			//juny + 31
			case years_days >= 150 :
				months 		= 5
				days 		= years_days - 150
			break;
			//may + 30
			case years_days >= 119 :
				months 		= 4
				days 		= years_days - 119
			break;
			//april + 31
			case years_days >= 89 :
				months 		= 3
				days 		= years_days - 89
			break;
			//march + 28
			case years_days >= 59 :
				months 		= 2
				days 		= years_days - 59
			break;
			//february + 31
			case years_days >= 31 :
				months 		= 1
				days 		= years_days - 31
			break;
			//January + 0
			case years_days >= 0 :
				months 		= 0
				days 		= years_days
			break;

		}

		let period = []

		if(years > 0 && options.years === true){
			const year_label = years == 1 ? get_label["anyo"] : get_label["anyos"]
			const year_value = (options.label===true) ? years + ' ' + year_label : years
			period.push(year_value)
		}

		if(months > 0 && options.months === true){
			const months_label = months == 1 ? get_label["mes"] : get_label["meses"]
			let months_value = ""
			if(options.total === true){
				months_value = (options.label===true) ? total_months + ' ' + months_label : total_months
			}else{
				months_value = (options.label===true) ? months + ' ' + months_label : months
			}
			period.push(months_value)
		}

		if(days > 0 && options.days === true){
			const days_label = days == 1 ? get_label["dia"] : get_label["dias"]
			let days_value = ""
			if(options.total === true){
				days_value = (options.label===true) ? total_days + ' ' + days_label : total_days
			}else{
				days_value = (options.label===true) ? days + ' ' + days_label : days

			}
			period.push(days_value)
		}

		const result = period.join(', ')

		return result

	}//end proces_secons_to_period

}//end component_calculation<|endoftext|>


<commit_before>'use strict';

const BaseGenerator = require('./Base');
const path = require('path');
const i = require('inflect');
const toFieldType = require('../helpers/str-to-field-type');
const toModelProperty = require('../helpers/field-type-to-model-property');

class ModelGenerator extends BaseGenerator {

  /**
   * returns signature to be used by ace
   * @return {String}
   *
   * @public
   */
  get signature() {
    const migrationsFlag = '{-m,--migration?:Create migration for a given model}';

    return `g:model {name} {fields...} ${migrationsFlag}`;
  }

  /**
   * returns description to be used by ace as help command
   * @return {String}
   *
   * @public
   */
  get description() {
    return 'Create a new model with optional migration';
  }

  /**
   * handle method will be executed by ace. Here we
   * create the model to models directory.
   * @param  {Object} args
   * @param  {Object} options
   *
   * @public
   */
  * handle(args, options) {
    const name = args.name;
    const entity = this._makeEntityName(name, 'model', false, 'singular');
    const toPath = path.join(this.helpers.appPath(), 'Model', `${entity.entityPath}.js`);
    const template = options.template || 'model';
    const fieldStrs = args['fields...'] || [];
    const fields = fieldStrs.map(toFieldType).map(toModelProperty).filter((x) => x !== '');
    const templateOptions = {
      fields,
      name: entity.entityName,
      table: options.table,
      connection: options.connection,
    };

    try {
      yield this.write(template, toPath, templateOptions);
      this._success(toPath);
      this._createMigration(options, args);
    } catch (e) {
      this._error(e.message);
    }
  }

  /**
   * creates migration for corresponding model, if
   * options.migration is defined.
   *
   * @param  {Object} options
   * @param  {String} name
   *
   * @private
   */
  _createMigration(options, { name, 'fields...': fields }) {
    if (options.migration) {
      this.run('g:migration', [name, ...fields]);
    }
  }

}

module.exports = ModelGenerator;
<commit_msg>Fixes model generating foreign keys<commit_after>'use strict';

const BaseGenerator = require('./Base');
const path = require('path');
const i = require('inflect');
const toFieldType = require('../helpers/str-to-field-type');
const toModelProperty = require('../helpers/field-type-to-model-property');

class ModelGenerator extends BaseGenerator {

  /**
   * returns signature to be used by ace
   * @return {String}
   *
   * @public
   */
  get signature() {
    const migrationsFlag = '{-m,--migration?:Create migration for a given model}';

    return `g:model {name} {fields...} ${migrationsFlag}`;
  }

  /**
   * returns description to be used by ace as help command
   * @return {String}
   *
   * @public
   */
  get description() {
    return 'Create a new model with optional migration';
  }

  /**
   * handle method will be executed by ace. Here we
   * create the model to models directory.
   * @param  {Object} args
   * @param  {Object} options
   *
   * @public
   */
  * handle(args, options) {
    const name = args.name;
    const entity = this._makeEntityName(name, 'model', false, 'singular');
    const toPath = path.join(this.helpers.appPath(), 'Model', `${entity.entityPath}.js`);
    const template = options.template || 'model';
    const fieldStrs = args['fields...'] || [];
    const fields = fieldStrs
      .map((field) => toFieldType(field, entity.entityPath))
      .map(toModelProperty)
      .filter((x) => x !== '');
    const templateOptions = {
      fields,
      name: entity.entityName,
      table: options.table,
      connection: options.connection,
    };

    try {
      yield this.write(template, toPath, templateOptions);
      this._success(toPath);
      this._createMigration(options, args);
    } catch (e) {
      this._error(e.message);
    }
  }

  /**
   * creates migration for corresponding model, if
   * options.migration is defined.
   *
   * @param  {Object} options
   * @param  {String} name
   *
   * @private
   */
  _createMigration(options, { name, 'fields...': fields }) {
    if (options.migration) {
      this.run('g:migration', [name, ...fields]);
    }
  }

}

module.exports = ModelGenerator;
<|endoftext|>


<commit_before>var contextMenu = require("sdk/context-menu");
var self = require("sdk/self");
var data = self.data;
var addOnPrefs = require("sdk/simple-prefs").prefs;
var ui = require('sdk/ui');
var tabs = require("sdk/tabs");
var requestHelper = require("./request-helper");
var storage = require("./storage");
var tracking = require("./tracking");
var panel = require("sdk/panel");
var notifications = require("sdk/notifications");

exports.useContextMenu = useContextMenu;
exports.cleanUpTab = cleanUpTab;

var contextMenus = {};

/**
 * Turns on the context menu with the datawake.
 * @param tab The tab to add the context to.
 */
function useContextMenu(tab) {
    if (addOnPrefs.useContextMenu) {
        var url = tab.url;
        var tabId = tab.id;
        destroyPreviousContextMenu(tabId);
        var datawakeInfo = storage.getDatawakeInfo(tabId);
        contextMenus[tabId] = contextMenu.Menu({
            label: "Datawake Menu: " + datawakeInfo.domain.name,
            contentScriptFile: data.url("js/datawake/selections.js"),
            context: contextMenu.URLContext(url),
            items: [
                contextMenu.Item({ label: "Capture Selection", data: "selection", context: contextMenu.SelectionContext()}),
                contextMenu.Item({ label: "Tag a feature", data: "feedback", context: contextMenu.SelectionContext()}),
                contextMenu.Item({ label: "InstaWake", data: "geolocate", context: contextMenu.SelectionContext()}),
                contextMenu.Separator(),
                contextMenu.Item({ label: "Hide Selections", data: "hide"}),
                contextMenu.Item({ label: "Show Selections", data: "highlight"}),

            ],
            onMessage: function (message) {
                var tabId = tabs.activeTab.id;
                var datawakeInfo = storage.getDatawakeInfo(tabId);
                switch (message.intent) {
                    case "highlight":
                        highlightAllTextOnPage(tabId, datawakeInfo);
                        break;
                    case "selection":
                        saveWindowSelection(datawakeInfo, tabs.activeTab.url, message.text);
                        break;
                    case "feedback":
                        saveFeedback(message.text, tabs.activeTab.url, datawakeInfo);
                        break;
                    case "hide":
                        hideSelections("selections");
                        break;
                    case "geolocate":
                        geolocateWindowSelection(message.text);
                        break;
                }
            }
        });
    }
}

function hideSelections(className) {
    tracking.hideSelections(className);
}

/**
 * Saves extractor feedback
 * @param raw_text raw_text that was highlighted
 * @param url the url it occurred on
 * @param domain domain it was apart of.
 */
function saveFeedback(raw_text, url, datawakeinfo) {

    tracking.promptForExtractedFeedback(raw_text, function (type, extractedValue) {
        var post_obj = {};
        post_obj.raw_text = raw_text;
        post_obj.feature_value = extractedValue;
        post_obj.feature_type = type;
        post_obj.url = url;
        post_obj.team_id = datawakeinfo.team.id;
        post_obj.domain_id = datawakeinfo.domain.id;
        post_obj.trail_id = datawakeinfo.trail.id;
        function logSuccess(response) {
            console.log(raw_text + " was successfully saved as feedback.");
        }

        requestHelper.post(addOnPrefs.datawakeDeploymentUrl + "/feedback/add_manual_feature", JSON.stringify(post_obj), logSuccess);
    });

}

/**
 * Highlights all selction text on the current page.
 * @param tabId The Id of the tab to highlight.
 * @param datawakeInfo The datawake information associated with this request.
 */
function highlightAllTextOnPage(tabId, datawakeInfo) {
    var post_data = JSON.stringify({
        team_id: datawakeInfo.team.id,
        domain_id: datawakeInfo.domain.id,
        trail_id: datawakeInfo.trail.id,
        url: tabs.activeTab.url
    });
    var post_url = addOnPrefs.datawakeDeploymentUrl + "/selections/get";
    requestHelper.post(post_url, post_data, function (response) {
        if (response.status != 200){
            // TODO error handling
            console.error(response)
        }
        else{
            tracking.emitHighlightTextToTabWorker(tabId, response.json);
        }

    });
}

/**
 * Saves the current window selection.
 * @param datawakeInfo The datawake information associated with this request.
 * @param url The url associated with this request.
 * @param selectionText The text selected.
 */
function saveWindowSelection(datawakeInfo, url, selectionText) {
    var post_data = JSON.stringify({
        team_id: datawakeInfo.team.id,
        domain_id: datawakeInfo.domain.id,
        trail_id: datawakeInfo.trail.id,
        url: url,
        selection: selectionText
    });
    var post_url = addOnPrefs.datawakeDeploymentUrl + "/selections/save";
    requestHelper.post(post_url, post_data, function (response) {
        console.debug("Selection saved");
    });
}

function geolocateWindowSelection(selectionText) {
    var geo_no_plugin_url = addOnPrefs.datawakeDeploymentUrl.replace(/\/plugin/,'');
    var get_url = geo_no_plugin_url + "/geo/instagram?address=" + encodeURIComponent(selectionText);
    requestHelper.get(get_url, function (response) {
        message = response.json.streetAddress + ', ' + response.json.city + ', ' + response.json.state + ' - Instagram Image Count: ' + response.json.imageCount;
        require("sdk/tabs").open('http://geogram-stream.52.8.42.59.xip.io/');
    });
}

/**
 * Cleans up the old context menu.
 * @param tabId TabId Associated with the menu
 */
function destroyPreviousContextMenu(tabId) {
    if (contextMenus.hasOwnProperty(tabId))
        contextMenus[tabId].destroy();
}

/**
 * Cleans up and frees all memory associated with a tab.
 * @param tabId The tabId to free.
 */
function cleanUpTab(tabId) {
    destroyPreviousContextMenu(tabId);
}
<commit_msg>removing instawake from context menu<commit_after>var contextMenu = require("sdk/context-menu");
var self = require("sdk/self");
var data = self.data;
var addOnPrefs = require("sdk/simple-prefs").prefs;
var ui = require('sdk/ui');
var tabs = require("sdk/tabs");
var requestHelper = require("./request-helper");
var storage = require("./storage");
var tracking = require("./tracking");
var panel = require("sdk/panel");
var notifications = require("sdk/notifications");

exports.useContextMenu = useContextMenu;
exports.cleanUpTab = cleanUpTab;

var contextMenus = {};

/**
 * Turns on the context menu with the datawake.
 * @param tab The tab to add the context to.
 */
function useContextMenu(tab) {
    if (addOnPrefs.useContextMenu) {
        var url = tab.url;
        var tabId = tab.id;
        destroyPreviousContextMenu(tabId);
        var datawakeInfo = storage.getDatawakeInfo(tabId);
        contextMenus[tabId] = contextMenu.Menu({
            label: "Datawake Menu: " + datawakeInfo.domain.name,
            contentScriptFile: data.url("js/datawake/selections.js"),
            context: contextMenu.URLContext(url),
            items: [
                contextMenu.Item({ label: "Capture Selection", data: "selection", context: contextMenu.SelectionContext()}),
                contextMenu.Item({ label: "Tag a feature", data: "feedback", context: contextMenu.SelectionContext()}),
                contextMenu.Separator(),
                contextMenu.Item({ label: "Hide Selections", data: "hide"}),
                contextMenu.Item({ label: "Show Selections", data: "highlight"}),

            ],
            onMessage: function (message) {
                var tabId = tabs.activeTab.id;
                var datawakeInfo = storage.getDatawakeInfo(tabId);
                switch (message.intent) {
                    case "highlight":
                        highlightAllTextOnPage(tabId, datawakeInfo);
                        break;
                    case "selection":
                        saveWindowSelection(datawakeInfo, tabs.activeTab.url, message.text);
                        break;
                    case "feedback":
                        saveFeedback(message.text, tabs.activeTab.url, datawakeInfo);
                        break;
                    case "hide":
                        hideSelections("selections");
                        break;
                    case "geolocate":
                        geolocateWindowSelection(message.text);
                        break;
                }
            }
        });
    }
}

function hideSelections(className) {
    tracking.hideSelections(className);
}

/**
 * Saves extractor feedback
 * @param raw_text raw_text that was highlighted
 * @param url the url it occurred on
 * @param domain domain it was apart of.
 */
function saveFeedback(raw_text, url, datawakeinfo) {

    tracking.promptForExtractedFeedback(raw_text, function (type, extractedValue) {
        var post_obj = {};
        post_obj.raw_text = raw_text;
        post_obj.feature_value = extractedValue;
        post_obj.feature_type = type;
        post_obj.url = url;
        post_obj.team_id = datawakeinfo.team.id;
        post_obj.domain_id = datawakeinfo.domain.id;
        post_obj.trail_id = datawakeinfo.trail.id;
        function logSuccess(response) {
            console.log(raw_text + " was successfully saved as feedback.");
        }

        requestHelper.post(addOnPrefs.datawakeDeploymentUrl + "/feedback/add_manual_feature", JSON.stringify(post_obj), logSuccess);
    });

}

/**
 * Highlights all selction text on the current page.
 * @param tabId The Id of the tab to highlight.
 * @param datawakeInfo The datawake information associated with this request.
 */
function highlightAllTextOnPage(tabId, datawakeInfo) {
    var post_data = JSON.stringify({
        team_id: datawakeInfo.team.id,
        domain_id: datawakeInfo.domain.id,
        trail_id: datawakeInfo.trail.id,
        url: tabs.activeTab.url
    });
    var post_url = addOnPrefs.datawakeDeploymentUrl + "/selections/get";
    requestHelper.post(post_url, post_data, function (response) {
        if (response.status != 200){
            // TODO error handling
            console.error(response)
        }
        else{
            tracking.emitHighlightTextToTabWorker(tabId, response.json);
        }

    });
}

/**
 * Saves the current window selection.
 * @param datawakeInfo The datawake information associated with this request.
 * @param url The url associated with this request.
 * @param selectionText The text selected.
 */
function saveWindowSelection(datawakeInfo, url, selectionText) {
    var post_data = JSON.stringify({
        team_id: datawakeInfo.team.id,
        domain_id: datawakeInfo.domain.id,
        trail_id: datawakeInfo.trail.id,
        url: url,
        selection: selectionText
    });
    var post_url = addOnPrefs.datawakeDeploymentUrl + "/selections/save";
    requestHelper.post(post_url, post_data, function (response) {
        console.debug("Selection saved");
    });
}

function geolocateWindowSelection(selectionText) {
    var geo_no_plugin_url = addOnPrefs.datawakeDeploymentUrl.replace(/\/plugin/,'');
    var get_url = geo_no_plugin_url + "/geo/instagram?address=" + encodeURIComponent(selectionText);
    requestHelper.get(get_url, function (response) {
        message = response.json.streetAddress + ', ' + response.json.city + ', ' + response.json.state + ' - Instagram Image Count: ' + response.json.imageCount;
        require("sdk/tabs").open('http://geogram-stream.52.8.42.59.xip.io/');
    });
}

/**
 * Cleans up the old context menu.
 * @param tabId TabId Associated with the menu
 */
function destroyPreviousContextMenu(tabId) {
    if (contextMenus.hasOwnProperty(tabId))
        contextMenus[tabId].destroy();
}

/**
 * Cleans up and frees all memory associated with a tab.
 * @param tabId The tabId to free.
 */
function cleanUpTab(tabId) {
    destroyPreviousContextMenu(tabId);
}
<|endoftext|>


<commit_before>'use strict';

// MODULES //

var resolve = require( 'path' ).resolve;
var exec = require( 'child_process' ).exec;
var tape = require( 'tape' );
var IS_BROWSER = require( '@stdlib/assert/is-browser' );
var IS_WINDOWS = require( '@stdlib/assert/is-windows' );
var EOL = require( '@stdlib/regexp/eol' );
var readFileSync = require( '@stdlib/fs/read-file' ).sync;

// VARIABLES //

var fpath = resolve( __dirname, '..', 'bin', 'cli' );
var opts = {
	'skip': IS_BROWSER || IS_WINDOWS
};

// FIXTURES //

var PKG_VERSION = require( './../package.json' ).version;

// TESTS //

tape( 'command-line interface', function test( t ) {
	t.ok( true, __filename );
	t.end();
});

tape( 'when invoked with a `--help` flag, the command-line interface prints the help text to `stderr`', opts, function test( t ) {
	var expected;
	var cmd;

	expected = readFileSync( resolve( __dirname, '..', 'bin', 'usage.txt' ), {
		'encoding': 'utf8'
	});
	cmd = [
		process.execPath,
		fpath,
		'--help'
	];

	exec( cmd.join( ' ' ), done );

	function done( error, stdout, stderr ) {
		if ( error ) {
			t.fail( error.message );
		} else {
			t.strictEqual( stdout.toString(), '', 'does not print to `stdout`' );
			t.strictEqual( stderr.toString(), expected+'\n', 'expected value' );
		}
		t.end();
	}
});

tape( 'when invoked with a `-h` flag, the command-line interface prints the help text to `stderr`', opts, function test( t ) {
	var expected;
	var cmd;

	expected = readFileSync( resolve( __dirname, '..', 'bin', 'usage.txt' ), {
		'encoding': 'utf8'
	});
	cmd = [
		process.execPath,
		fpath,
		'-h'
	];

	exec( cmd.join( ' ' ), done );

	function done( error, stdout, stderr ) {
		if ( error ) {
			t.fail( error.message );
		} else {
			t.strictEqual( stdout.toString(), '', 'does not print to `stdout`' );
			t.strictEqual( stderr.toString(), expected+'\n', 'expected value' );
		}
		t.end();
	}
});

tape( 'when invoked with a `--version` flag, the command-line interface prints the version to `stderr`', opts, function test( t ) {
	var cmd = [
		process.execPath,
		fpath,
		'--version'
	];

	exec( cmd.join( ' ' ), done );

	function done( error, stdout, stderr ) {
		if ( error ) {
			t.fail( error.message );
		} else {
			t.strictEqual( stdout.toString(), '', 'does not print to `stdout`' );
			t.strictEqual( stderr.toString(), PKG_VERSION+'\n', 'expected value' );
		}
		t.end();
	}
});

tape( 'when invoked with a `-V` flag, the command-line interface prints the version to `stderr`', opts, function test( t ) {
	var cmd = [
		process.execPath,
		fpath,
		'-V'
	];

	exec( cmd.join( ' ' ), done );

	function done( error, stdout, stderr ) {
		if ( error ) {
			t.fail( error.message );
		} else {
			t.strictEqual( stdout.toString(), '', 'does not print to `stdout`' );
			t.strictEqual( stderr.toString(), PKG_VERSION+'\n', 'expected value' );
		}
		t.end();
	}
});

tape( 'the command-line interface prints a list of packages', opts, function test( t ) {
	var cmd = [
		process.execPath,
		fpath,
		resolve( __dirname, '..', '..', '..', '..', '..' ) // WARNING: fragile, as assumes a particular directory structure
	];

	exec( cmd.join( ' ' ), done );

	function done( error, stdout, stderr ) {
		if ( error ) {
			t.fail( error.message );
		} else {
			t.strictEqual( stdout.toString().split( EOL ).length > 1, true, 'prints a newline-delimited list' );
			t.strictEqual( stderr.toString(), '', 'does not print to `stderr`' );
		}
		t.end();
	}
});

tape( 'the command-line interface supports searching based on a pattern', opts, function test( t ) {
	var cmd = [
		process.execPath,
		fpath,
		resolve( __dirname, '..', '..', '..', '..', '..' ), // WARNING: fragile, as assumes a particular directory structure
		'--pattern \'**/math/base/blas/dasum/package.json\''
	];

	exec( cmd.join( ' ' ), done );

	function done( error, stdout, stderr ) {
		if ( error ) {
			t.fail( error.message );
		} else {
			// Includes trailing newline...
			t.strictEqual( stdout.toString().split( EOL ).length, 2, 'prints a newline-delimited list' );
			t.strictEqual( stderr.toString(), '', 'does not print to `stderr`' );
		}
		t.end();
	}
});

tape( 'the command-line interface supports providing an exclusion pattern', opts, function test( t ) {
	var cmd;
	var dir;

	dir = resolve( __dirname, '..', '..', '..', '..', '..' ); // WARNING: fragile, as assumes a particular directory structure

	cmd = [
		process.execPath,
		fpath,
		dir,
		'--ignore \''+dir+'/**\'' // the same directory we are searching!
	];

	exec( cmd.join( ' ' ), done );

	function done( error, stdout, stderr ) {
		if ( error ) {
			t.fail( error.message );
		} else {
			// Only prints a linebreak...
			t.strictEqual( stdout.toString().split( EOL ).length, 1, 'excludes matches' );
			t.strictEqual( stderr.toString(), '', 'does not print to `stderr`' );
		}
		t.end();
	}
});

tape( 'the command-line interface supports providing multiple exclusion patterns', opts, function test( t ) {
	var cmd;
	var dir;

	dir = resolve( __dirname, '..', '..', '..', '..', '..' ); // WARNING: fragile, as assumes a particular directory structure

	cmd = [
		process.execPath,
		fpath,
		dir,
		'--ignore \''+dir+'/**\'', // the same directory we are searching!
		'--ignore build/**'
	];

	exec( cmd.join( ' ' ), done );

	function done( error, stdout, stderr ) {
		if ( error ) {
			t.fail( error.message );
		} else {
			// Only prints a linebreak...
			t.strictEqual( stdout.toString().split( EOL ).length, 1, 'excludes matches' );
			t.strictEqual( stderr.toString(), '', 'does not print to `stderr`' );
		}
		t.end();
	}
});
<commit_msg>Update path<commit_after>'use strict';

// MODULES //

var resolve = require( 'path' ).resolve;
var exec = require( 'child_process' ).exec;
var tape = require( 'tape' );
var IS_BROWSER = require( '@stdlib/assert/is-browser' );
var IS_WINDOWS = require( '@stdlib/assert/is-windows' );
var EOL = require( '@stdlib/regexp/eol' );
var readFileSync = require( '@stdlib/fs/read-file' ).sync;

// VARIABLES //

var fpath = resolve( __dirname, '..', 'bin', 'cli' );
var opts = {
	'skip': IS_BROWSER || IS_WINDOWS
};

// FIXTURES //

var PKG_VERSION = require( './../package.json' ).version;

// TESTS //

tape( 'command-line interface', function test( t ) {
	t.ok( true, __filename );
	t.end();
});

tape( 'when invoked with a `--help` flag, the command-line interface prints the help text to `stderr`', opts, function test( t ) {
	var expected;
	var cmd;

	expected = readFileSync( resolve( __dirname, '..', 'bin', 'usage.txt' ), {
		'encoding': 'utf8'
	});
	cmd = [
		process.execPath,
		fpath,
		'--help'
	];

	exec( cmd.join( ' ' ), done );

	function done( error, stdout, stderr ) {
		if ( error ) {
			t.fail( error.message );
		} else {
			t.strictEqual( stdout.toString(), '', 'does not print to `stdout`' );
			t.strictEqual( stderr.toString(), expected+'\n', 'expected value' );
		}
		t.end();
	}
});

tape( 'when invoked with a `-h` flag, the command-line interface prints the help text to `stderr`', opts, function test( t ) {
	var expected;
	var cmd;

	expected = readFileSync( resolve( __dirname, '..', 'bin', 'usage.txt' ), {
		'encoding': 'utf8'
	});
	cmd = [
		process.execPath,
		fpath,
		'-h'
	];

	exec( cmd.join( ' ' ), done );

	function done( error, stdout, stderr ) {
		if ( error ) {
			t.fail( error.message );
		} else {
			t.strictEqual( stdout.toString(), '', 'does not print to `stdout`' );
			t.strictEqual( stderr.toString(), expected+'\n', 'expected value' );
		}
		t.end();
	}
});

tape( 'when invoked with a `--version` flag, the command-line interface prints the version to `stderr`', opts, function test( t ) {
	var cmd = [
		process.execPath,
		fpath,
		'--version'
	];

	exec( cmd.join( ' ' ), done );

	function done( error, stdout, stderr ) {
		if ( error ) {
			t.fail( error.message );
		} else {
			t.strictEqual( stdout.toString(), '', 'does not print to `stdout`' );
			t.strictEqual( stderr.toString(), PKG_VERSION+'\n', 'expected value' );
		}
		t.end();
	}
});

tape( 'when invoked with a `-V` flag, the command-line interface prints the version to `stderr`', opts, function test( t ) {
	var cmd = [
		process.execPath,
		fpath,
		'-V'
	];

	exec( cmd.join( ' ' ), done );

	function done( error, stdout, stderr ) {
		if ( error ) {
			t.fail( error.message );
		} else {
			t.strictEqual( stdout.toString(), '', 'does not print to `stdout`' );
			t.strictEqual( stderr.toString(), PKG_VERSION+'\n', 'expected value' );
		}
		t.end();
	}
});

tape( 'the command-line interface prints a list of packages', opts, function test( t ) {
	var cmd = [
		process.execPath,
		fpath,
		resolve( __dirname, '..', '..', '..', '..', '..' ) // WARNING: fragile, as assumes a particular directory structure
	];

	exec( cmd.join( ' ' ), done );

	function done( error, stdout, stderr ) {
		if ( error ) {
			t.fail( error.message );
		} else {
			t.strictEqual( stdout.toString().split( EOL ).length > 1, true, 'prints a newline-delimited list' );
			t.strictEqual( stderr.toString(), '', 'does not print to `stderr`' );
		}
		t.end();
	}
});

tape( 'the command-line interface supports searching based on a pattern', opts, function test( t ) {
	var cmd = [
		process.execPath,
		fpath,
		resolve( __dirname, '..', '..', '..', '..', '..' ), // WARNING: fragile, as assumes a particular directory structure
		'--pattern \'**/blas/base/dasum/package.json\''
	];

	exec( cmd.join( ' ' ), done );

	function done( error, stdout, stderr ) {
		if ( error ) {
			t.fail( error.message );
		} else {
			// Includes trailing newline...
			t.strictEqual( stdout.toString().split( EOL ).length, 2, 'prints a newline-delimited list' );
			t.strictEqual( stderr.toString(), '', 'does not print to `stderr`' );
		}
		t.end();
	}
});

tape( 'the command-line interface supports providing an exclusion pattern', opts, function test( t ) {
	var cmd;
	var dir;

	dir = resolve( __dirname, '..', '..', '..', '..', '..' ); // WARNING: fragile, as assumes a particular directory structure

	cmd = [
		process.execPath,
		fpath,
		dir,
		'--ignore \''+dir+'/**\'' // the same directory we are searching!
	];

	exec( cmd.join( ' ' ), done );

	function done( error, stdout, stderr ) {
		if ( error ) {
			t.fail( error.message );
		} else {
			// Only prints a linebreak...
			t.strictEqual( stdout.toString().split( EOL ).length, 1, 'excludes matches' );
			t.strictEqual( stderr.toString(), '', 'does not print to `stderr`' );
		}
		t.end();
	}
});

tape( 'the command-line interface supports providing multiple exclusion patterns', opts, function test( t ) {
	var cmd;
	var dir;

	dir = resolve( __dirname, '..', '..', '..', '..', '..' ); // WARNING: fragile, as assumes a particular directory structure

	cmd = [
		process.execPath,
		fpath,
		dir,
		'--ignore \''+dir+'/**\'', // the same directory we are searching!
		'--ignore build/**'
	];

	exec( cmd.join( ' ' ), done );

	function done( error, stdout, stderr ) {
		if ( error ) {
			t.fail( error.message );
		} else {
			// Only prints a linebreak...
			t.strictEqual( stdout.toString().split( EOL ).length, 1, 'excludes matches' );
			t.strictEqual( stderr.toString(), '', 'does not print to `stderr`' );
		}
		t.end();
	}
});
<|endoftext|>


<commit_before>'use strict';

// MODULES //

var bench = require( '@stdlib/bench' );
var isArray = require( '@stdlib/assert/is-array' );
var pkg = require( './../package.json' ).name;
var tokenize = require( './../lib' );

// MAIN //

bench( pkg, function benchmark( b ) {
	var out;
	var str;
	var i;

	b.tic();
	for ( i = 0; i < b.iterations; i++ ) {
		str = 'To be, or not to be, that is the question' + String.fromCharCode( i%126 );
		out = tokenize( str );
		if ( !isArray( out ) ) {
			b.fail( 'should return an array' );
		}
	}
	b.toc();
	if ( isArray( out ) ) {
		b.pass( 'benchmark finished' );
	} else {
		b.fail( 'should return an array' );
	}
	b.end();
});
<commit_msg>Always finish benchmark<commit_after>'use strict';

// MODULES //

var bench = require( '@stdlib/bench' );
var isArray = require( '@stdlib/assert/is-array' );
var pkg = require( './../package.json' ).name;
var tokenize = require( './../lib' );

// MAIN //

bench( pkg, function benchmark( b ) {
	var out;
	var str;
	var i;

	b.tic();
	for ( i = 0; i < b.iterations; i++ ) {
		str = 'To be, or not to be, that is the question' + String.fromCharCode( i%126 );
		out = tokenize( str );
		if ( !isArray( out ) ) {
			b.fail( 'should return an array' );
		}
	}
	b.toc();
	if ( !isArray( out ) ) {
		b.fail( 'should return an array' );
	}
	b.pass( 'benchmark finished' );
	b.end();
});
<|endoftext|>


<commit_before>[
{"id":"align_relative_to","title":"相對對齊 ..."},
{"id":"angle","title":"旋轉角度"},
{"id":"angleLabel","textContent":"角度:"},
{"id":"bkgnd_color","title":"更改背景顏色/不透明"},
{"id":"circle_cx","title":"改變圓的CX坐標"},
{"id":"circle_cy","title":"改變圓的CY坐標"},
{"id":"circle_r","title":"改變圓的半徑"},
{"id":"cornerRadiusLabel","textContent":"角半徑："},
{"id":"curve_segments","textContent":"曲線"},
{"id":"ellipse_cx","title":"改變橢圓的圓心x軸座標"},
{"id":"ellipse_cy","title":"改變橢圓的圓心y軸座標"},
{"id":"ellipse_rx","title":"改變橢圓的x軸長"},
{"id":"ellipse_ry","title":"改變橢圓的y軸長"},
{"id":"fill_color","title":"更改填充顏色"},
{"id":"fill_tool_bottom","textContent":"填充:"},
{"id":"fitToContent","textContent":"適合內容"},
{"id":"fit_to_all","textContent":"適合所有的內容"},
{"id":"fit_to_canvas","textContent":"適合畫布"},
{"id":"fit_to_layer_content","textContent":"適合圖層內容"},
{"id":"fit_to_sel","textContent":"適合選取的物件"},
{"id":"font_family","title":"更改字體"},
{"id":"font_size","title":"更改字體大小"},
{"id":"group_opacity","title":"更改所選項目不透明度"},
{"id":"icon_large","textContent":"大"},
{"id":"icon_medium","textContent":"中"},
{"id":"icon_small","textContent":"小"},
{"id":"icon_xlarge","textContent":"特大"},
{"id":"iheightLabel","textContent":"高度:"},
{"id":"image_height","title":"更改圖像高度"},
{"id":"image_opt_embed","textContent":"內嵌資料 (本地端檔案)"},
{"id":"image_opt_ref","textContent":"使用檔案參照"},
{"id":"image_url","title":"更改網址"},
{"id":"image_width","title":"更改圖像的寬度"},
{"id":"includedImages","textContent":"包含圖像"},
{"id":"iwidthLabel","textContent":"寬度:"},
{"id":"largest_object","textContent":"最大的物件"},
{"id":"layer_delete","title":"刪除圖層"},
{"id":"layer_down","title":"向下移動圖層"},
{"id":"layer_new","title":"新增圖層"},
{"id":"layer_rename","title":"重新命名圖層"},
{"id":"layer_up","title":"向上移動圖層"},
{"id":"layersLabel","textContent":"圖層:"},
{"id":"line_x1","title":"更改行的起點的x坐標"},
{"id":"line_x2","title":"更改行的終點x坐標"},
{"id":"line_y1","title":"更改行的起點的y坐標"},
{"id":"line_y2","title":"更改行的終點y坐標"},
{"id":"page","textContent":"網頁"},
{"id":"palette","title":"點擊更改填充顏色，按住Shift鍵單擊更改線條顏色"},
{"id":"path_node_x","title":"改變節點的x軸座標"},
{"id":"path_node_y","title":"改變節點的y軸座標"},
{"id":"rect_height","title":"更改矩形的高度"},
{"id":"rect_rx","title":"矩形角半徑的變化"},
{"id":"rect_width","title":"更改矩形的寬度"},
{"id":"relativeToLabel","textContent":"相對於:"},
{"id":"rheightLabel","textContent":"高度："},
{"id":"rwidthLabel","textContent":"寬度："},
{"id":"seg_type","title":"Change Segment type"},
{"id":"selLayerLabel","textContent":"移動物件到:"},
{"id":"selLayerNames","title":"移動被點選的物件其他圖層"},
{"id":"selectedPredefined","textContent":"使用預設值:"},
{"id":"selected_objects","textContent":"選取物件"},
{"id":"selected_x","title":"調整 X 軸"},
{"id":"selected_y","title":"調整 Y 軸"},
{"id":"smallest_object","textContent":"最小的物件"},
{"id":"straight_segments","textContent":"直線"},
{"id":"stroke_color","title":"線條顏色"},
{"id":"stroke_style","title":"更改線條（虛線）風格"},
{"id":"stroke_tool_bottom","textContent":"線條:"},
{"id":"stroke_width","title":"線條寬度"},
{"id":"svginfo_bg_note","textContent":"注意: 編輯器背景不會和圖像一起儲存"},
{"id":"svginfo_change_background","textContent":"編輯器背景"},
{"id":"svginfo_dim","textContent":"畫布大小"},
{"id":"svginfo_editor_prefs","textContent":"編輯器屬性"},
{"id":"svginfo_height","textContent":"高度:"},
{"id":"svginfo_icons","textContent":"圖示大小"},
{"id":"svginfo_image_props","textContent":"圖片屬性"},
{"id":"svginfo_lang","textContent":"語言"},
{"id":"svginfo_title","textContent":"標題"},
{"id":"svginfo_width","textContent":"寬度:"},
{"id":"text","title":"更改文字內容"},
{"id":"tool_alignbottom","title":"底部對齊"},
{"id":"tool_aligncenter","title":"居中對齊"},
{"id":"tool_alignleft","title":"向左對齊"},
{"id":"tool_alignmiddle","title":"中間對齊"},
{"id":"tool_alignright","title":"向右對齊"},
{"id":"tool_aligntop","title":"頂端對齊"},
{"id":"tool_bold","title":"粗體"},
{"id":"tool_circle","title":"圓"},
{"id":"tool_clear","title":"清空圖像"},
{"id":"tool_clone","title":"複製"},
{"id":"tool_clone_multi","title":"複製所選元素"},
{"id":"tool_delete","title":"刪除"},
{"id":"tool_delete_multi","title":"刪除所選元素"},
{"id":"tool_docprops","title":"文件屬性"},
{"id":"tool_docprops_cancel","textContent":"取消"},
{"id":"tool_docprops_save","textContent":"保存"},
{"id":"tool_ellipse","title":"橢圓"},
{"id":"tool_fhellipse","title":"徒手畫橢圓"},
{"id":"tool_fhpath","title":"鉛筆工具"},
{"id":"tool_fhrect","title":"徒手畫矩形"},
{"id":"tool_group","title":"群組"},
{"id":"tool_image","title":"圖像工具"},
{"id":"tool_italic","title":"斜體"},
{"id":"tool_line","title":"線工具"},
{"id":"tool_move_bottom","title":"移至底部"},
{"id":"tool_move_top","title":"移動到頂部"},
{"id":"tool_node_clone","title":"增加節點"},
{"id":"tool_node_delete","title":"刪除節點"},
{"id":"tool_node_link","title":"將控制點連起來"},
{"id":"tool_open","title":"打開圖像"},
{"id":"tool_path","title":"路徑工具"},
{"id":"tool_rect","title":"矩形"},
{"id":"tool_redo","title":"復原"},
{"id":"tool_reorient","title":"調整路徑"},
{"id":"tool_save","title":"保存圖像"},
{"id":"tool_select","title":"選擇工具"},
{"id":"tool_source","title":"編輯SVG原始碼"},
{"id":"tool_source_cancel","textContent":"取消"},
{"id":"tool_source_save","textContent":"保存"},
{"id":"tool_square","title":"方形"},
{"id":"tool_text","title":"文字工具"},
{"id":"tool_topath","title":"轉換成路徑"},
{"id":"tool_undo","title":"取消復原"},
{"id":"tool_ungroup","title":"取消群組"},
{"id":"tool_wireframe","title":"框線模式（只瀏覽線條）"},
{"id":"tool_zoom","title":"縮放工具"},
{"id":"tools_ellipse_show","title":"橢圓/圓工具"},
{"id":"tools_rect_show","title":"矩形/方形工具"},
{"id":"zoom","title":"更改縮放級別"},
{"id":"zoomLabel","textContent":"調整頁面大小:"},
{"id":"sidepanel_handle","textContent":"圖層","title":"拖拉以改變側邊面板的大小"},
{
 "js_strings": {
  "QerrorsRevertToSource":"SVG原始碼解析錯誤\n要回復到原本的SVG原始碼嗎？",
	"QignoreSourceChanges":"要忽略對SVG原始碼的更動嗎？",
  "QmoveElemsToLayer":"要搬移所選取的物件到'%s'層嗎?",
	"QwantToClear":"要清空圖像嗎？\n這會順便清空你的回復紀錄！",
	"cancel":"取消",
	"dupeLayerName":"喔不！已經有另一個同樣名稱的圖層了！",
	"enterNewImgURL":"輸入新的圖片網址",
	"enterUniqueLayerName":"請輸入一個名稱不重複的",
	"enterNewLayerName":"請輸入新圖層的名稱",
	"featNotSupported":"未提供此功能",
	"invalidAttrValGiven":"數值給定錯誤",
	"key_backspace":"空白",
	"key_del":"刪除",
	"key_down":"下",
	"key_up":"上",
	"layer":"圖層",
	"layerHasThatName":"圖層本來就是這個名稱（抱怨）",
	"noContentToFitTo":"找不到符合的內容",
	"ok":"確定",
	"pathCtrlPtTooltip":"拖拉控制點以改變曲線性質",
  "pathNodeTooltip":"拖拉節點以移動， 連擊節點以改變線段型態（直線/曲線）"
 }
}
]<commit_msg>Main menu items in zh-TW now display in Chinese. Also remove _show entries no longer needed. Thank you Mook!<commit_after>[
{"id":"align_relative_to","title":"相對對齊 ..."},
{"id":"angle","title":"旋轉角度"},
{"id":"angleLabel","textContent":"角度:"},
{"id":"bkgnd_color","title":"更改背景顏色/不透明"},
{"id":"circle_cx","title":"改變圓的CX坐標"},
{"id":"circle_cy","title":"改變圓的CY坐標"},
{"id":"circle_r","title":"改變圓的半徑"},
{"id":"cornerRadiusLabel","textContent":"角半徑："},
{"id":"curve_segments","textContent":"曲線"},
{"id":"ellipse_cx","title":"改變橢圓的圓心x軸座標"},
{"id":"ellipse_cy","title":"改變橢圓的圓心y軸座標"},
{"id":"ellipse_rx","title":"改變橢圓的x軸長"},
{"id":"ellipse_ry","title":"改變橢圓的y軸長"},
{"id":"fill_color","title":"更改填充顏色"},
{"id":"fill_tool_bottom","textContent":"填充:"},
{"id":"fitToContent","textContent":"適合內容"},
{"id":"fit_to_all","textContent":"適合所有的內容"},
{"id":"fit_to_canvas","textContent":"適合畫布"},
{"id":"fit_to_layer_content","textContent":"適合圖層內容"},
{"id":"fit_to_sel","textContent":"適合選取的物件"},
{"id":"font_family","title":"更改字體"},
{"id":"font_size","title":"更改字體大小"},
{"id":"group_opacity","title":"更改所選項目不透明度"},
{"id":"icon_large","textContent":"大"},
{"id":"icon_medium","textContent":"中"},
{"id":"icon_small","textContent":"小"},
{"id":"icon_xlarge","textContent":"特大"},
{"id":"iheightLabel","textContent":"高度:"},
{"id":"image_height","title":"更改圖像高度"},
{"id":"image_opt_embed","textContent":"內嵌資料 (本地端檔案)"},
{"id":"image_opt_ref","textContent":"使用檔案參照"},
{"id":"image_url","title":"更改網址"},
{"id":"image_width","title":"更改圖像的寬度"},
{"id":"includedImages","textContent":"包含圖像"},
{"id":"iwidthLabel","textContent":"寬度:"},
{"id":"largest_object","textContent":"最大的物件"},
{"id":"layer_delete","title":"刪除圖層"},
{"id":"layer_down","title":"向下移動圖層"},
{"id":"layer_new","title":"新增圖層"},
{"id":"layer_rename","title":"重新命名圖層"},
{"id":"layer_up","title":"向上移動圖層"},
{"id":"layersLabel","textContent":"圖層:"},
{"id":"line_x1","title":"更改行的起點的x坐標"},
{"id":"line_x2","title":"更改行的終點x坐標"},
{"id":"line_y1","title":"更改行的起點的y坐標"},
{"id":"line_y2","title":"更改行的終點y坐標"},
{"id":"page","textContent":"網頁"},
{"id":"palette","title":"點擊更改填充顏色，按住Shift鍵單擊更改線條顏色"},
{"id":"path_node_x","title":"改變節點的x軸座標"},
{"id":"path_node_y","title":"改變節點的y軸座標"},
{"id":"rect_height","title":"更改矩形的高度"},
{"id":"rect_rx","title":"矩形角半徑的變化"},
{"id":"rect_width","title":"更改矩形的寬度"},
{"id":"relativeToLabel","textContent":"相對於:"},
{"id":"rheightLabel","textContent":"高度："},
{"id":"rwidthLabel","textContent":"寬度："},
{"id":"seg_type","title":"Change Segment type"},
{"id":"selLayerLabel","textContent":"移動物件到:"},
{"id":"selLayerNames","title":"移動被點選的物件其他圖層"},
{"id":"selectedPredefined","textContent":"使用預設值:"},
{"id":"selected_objects","textContent":"選取物件"},
{"id":"selected_x","title":"調整 X 軸"},
{"id":"selected_y","title":"調整 Y 軸"},
{"id":"smallest_object","textContent":"最小的物件"},
{"id":"straight_segments","textContent":"直線"},
{"id":"stroke_color","title":"線條顏色"},
{"id":"stroke_style","title":"更改線條（虛線）風格"},
{"id":"stroke_tool_bottom","textContent":"線條:"},
{"id":"stroke_width","title":"線條寬度"},
{"id":"svginfo_bg_note","textContent":"注意: 編輯器背景不會和圖像一起儲存"},
{"id":"svginfo_change_background","textContent":"編輯器背景"},
{"id":"svginfo_dim","textContent":"畫布大小"},
{"id":"svginfo_editor_prefs","textContent":"編輯器屬性"},
{"id":"svginfo_height","textContent":"高度:"},
{"id":"svginfo_icons","textContent":"圖示大小"},
{"id":"svginfo_image_props","textContent":"圖片屬性"},
{"id":"svginfo_lang","textContent":"語言"},
{"id":"svginfo_title","textContent":"標題"},
{"id":"svginfo_width","textContent":"寬度:"},
{"id":"text","title":"更改文字內容"},
{"id":"tool_alignbottom","title":"底部對齊"},
{"id":"tool_aligncenter","title":"居中對齊"},
{"id":"tool_alignleft","title":"向左對齊"},
{"id":"tool_alignmiddle","title":"中間對齊"},
{"id":"tool_alignright","title":"向右對齊"},
{"id":"tool_aligntop","title":"頂端對齊"},
{"id":"tool_bold","title":"粗體"},
{"id":"tool_circle","title":"圓"},
{"id":"tool_clear","textContent":"清空圖像"},
{"id":"tool_clone","title":"複製"},
{"id":"tool_clone_multi","title":"複製所選元素"},
{"id":"tool_delete","title":"刪除"},
{"id":"tool_delete_multi","title":"刪除所選元素"},
{"id":"tool_docprops","textContent":"文件屬性"},
{"id":"tool_docprops_cancel","textContent":"取消"},
{"id":"tool_docprops_save","textContent":"保存"},
{"id":"tool_ellipse","title":"橢圓"},
{"id":"tool_fhellipse","title":"徒手畫橢圓"},
{"id":"tool_fhpath","title":"鉛筆工具"},
{"id":"tool_fhrect","title":"徒手畫矩形"},
{"id":"tool_group","title":"群組"},
{"id":"tool_image","title":"圖像工具"},
{"id":"tool_italic","title":"斜體"},
{"id":"tool_line","title":"線工具"},
{"id":"tool_move_bottom","title":"移至底部"},
{"id":"tool_move_top","title":"移動到頂部"},
{"id":"tool_node_clone","title":"增加節點"},
{"id":"tool_node_delete","title":"刪除節點"},
{"id":"tool_node_link","title":"將控制點連起來"},
{"id":"tool_open","textContent":"打開圖像"},
{"id":"tool_path","title":"路徑工具"},
{"id":"tool_rect","title":"矩形"},
{"id":"tool_redo","title":"復原"},
{"id":"tool_reorient","title":"調整路徑"},
{"id":"tool_save","textContent":"保存圖像"},
{"id":"tool_select","title":"選擇工具"},
{"id":"tool_source","title":"編輯SVG原始碼"},
{"id":"tool_source_cancel","textContent":"取消"},
{"id":"tool_source_save","textContent":"保存"},
{"id":"tool_square","title":"方形"},
{"id":"tool_text","title":"文字工具"},
{"id":"tool_topath","title":"轉換成路徑"},
{"id":"tool_undo","title":"取消復原"},
{"id":"tool_ungroup","title":"取消群組"},
{"id":"tool_wireframe","title":"框線模式（只瀏覽線條）"},
{"id":"tool_zoom","title":"縮放工具"},
{"id":"zoom","title":"更改縮放級別"},
{"id":"zoomLabel","textContent":"調整頁面大小:"},
{"id":"sidepanel_handle","textContent":"圖層","title":"拖拉以改變側邊面板的大小"},
{
 "js_strings": {
  "QerrorsRevertToSource":"SVG原始碼解析錯誤\n要回復到原本的SVG原始碼嗎？",
	"QignoreSourceChanges":"要忽略對SVG原始碼的更動嗎？",
  "QmoveElemsToLayer":"要搬移所選取的物件到'%s'層嗎?",
	"QwantToClear":"要清空圖像嗎？\n這會順便清空你的回復紀錄！",
	"cancel":"取消",
	"dupeLayerName":"喔不！已經有另一個同樣名稱的圖層了！",
	"enterNewImgURL":"輸入新的圖片網址",
	"enterUniqueLayerName":"請輸入一個名稱不重複的",
	"enterNewLayerName":"請輸入新圖層的名稱",
	"featNotSupported":"未提供此功能",
	"invalidAttrValGiven":"數值給定錯誤",
	"key_backspace":"空白",
	"key_del":"刪除",
	"key_down":"下",
	"key_up":"上",
	"layer":"圖層",
	"layerHasThatName":"圖層本來就是這個名稱（抱怨）",
	"noContentToFitTo":"找不到符合的內容",
	"ok":"確定",
	"pathCtrlPtTooltip":"拖拉控制點以改變曲線性質",
  "pathNodeTooltip":"拖拉節點以移動， 連擊節點以改變線段型態（直線/曲線）"
 }
}
]<|endoftext|>


<commit_before>/*! simpleWeather v3.0.2 - http://simpleweatherjs.com */
(function($) {
  "use strict";

  function getAltTemp(unit, temp) {
    if(unit === 'f') {
      return Math.round((5.0/9.0)*(temp-32.0));
    } else {
      return Math.round((9.0/5.0)*temp+32.0);
    }
  }

  $.extend({
    simpleWeather: function(options){
      options = $.extend({
        location: '',
        woeid: '',
        unit: 'f',
        success: function(weather){},
        error: function(message){}
      }, options);

      var now = new Date();
      var weatherUrl = 'https://query.yahooapis.com/v1/public/yql?format=json&rnd='+now.getFullYear()+now.getMonth()+now.getDay()+now.getHours()+'&diagnostics=true&callback=?&q=';
      if(options.location !== '') {
        weatherUrl += 'select * from weather.forecast where woeid in (select woeid from geo.placefinder where text="'+options.location+'" and gflags="R" limit 1) and u="'+options.unit+'"';
      } else if(options.woeid !== '') {
        weatherUrl += 'select * from weather.forecast where woeid='+options.woeid+' and u="'+options.unit+'"';
      } else {
        options.error({message: "Could not retrieve weather due to an invalid location."});
        return false;
      }

      $.getJSON(
        encodeURI(weatherUrl),
        function(data) {
          if(data !== null && data.query !== null && data.query.results !== null && data.query.results.channel.description !== 'Yahoo! Weather Error') {
            var result = data.query.results.channel,
                weather = {},
                forecast,
                compass = ['N', 'NNE', 'NE', 'ENE', 'E', 'ESE', 'SE', 'SSE', 'S', 'SSW', 'SW', 'WSW', 'W', 'WNW', 'NW', 'NNW', 'N'],
                image404 = "https://s.yimg.com/os/mit/media/m/weather/images/icons/l/44d-100567.png";

            weather.title = result.item.title;
            weather.temp = result.item.condition.temp;
            weather.code = result.item.condition.code;
            weather.todayCode = result.item.forecast[0].code;
            weather.currently = result.item.condition.text;
            weather.high = result.item.forecast[0].high;
            weather.low = result.item.forecast[0].low;
            weather.text = result.item.forecast[0].text;
            weather.humidity = result.atmosphere.humidity;
            weather.pressure = result.atmosphere.pressure;
            weather.rising = result.atmosphere.rising;
            weather.visibility = result.atmosphere.visibility;
            weather.sunrise = result.astronomy.sunrise;
            weather.sunset = result.astronomy.sunset;
            weather.description = result.item.description;
            weather.city = result.location.city;
            weather.country = result.location.country;
            weather.region = result.location.region;
            weather.updated = result.item.pubDate;
            weather.link = result.item.link;
            weather.units = {temp: result.units.temperature, distance: result.units.distance, pressure: result.units.pressure, speed: result.units.speed};
            weather.wind = {chill: result.wind.chill, direction: compass[Math.round(result.wind.direction / 22.5)], speed: result.wind.speed};

            if(result.item.condition.temp < 80 && result.atmosphere.humidity < 40) {
              weather.heatindex = -42.379+2.04901523*result.item.condition.temp+10.14333127*result.atmosphere.humidity-0.22475541*result.item.condition.temp*result.atmosphere.humidity-6.83783*(Math.pow(10, -3))*(Math.pow(result.item.condition.temp, 2))-5.481717*(Math.pow(10, -2))*(Math.pow(result.atmosphere.humidity, 2))+1.22874*(Math.pow(10, -3))*(Math.pow(result.item.condition.temp, 2))*result.atmosphere.humidity+8.5282*(Math.pow(10, -4))*result.item.condition.temp*(Math.pow(result.atmosphere.humidity, 2))-1.99*(Math.pow(10, -6))*(Math.pow(result.item.condition.temp, 2))*(Math.pow(result.atmosphere.humidity,2));
            } else {
              weather.heatindex = result.item.condition.temp;
            }

            if(result.item.condition.code == "3200") {
              weather.thumbnail = image404;
              weather.image = image404;
            } else {
              weather.thumbnail = "https://s.yimg.com/zz/combo?a/i/us/nws/weather/gr/"+result.item.condition.code+"ds.png";
              weather.image = "https://s.yimg.com/zz/combo?a/i/us/nws/weather/gr/"+result.item.condition.code+"d.png";
            }

            weather.alt = {temp: getAltTemp(options.unit, result.item.condition.temp), high: getAltTemp(options.unit, result.item.forecast[0].high), low: getAltTemp(options.unit, result.item.forecast[0].low)};
            if(options.unit === 'f') {
              weather.alt.unit = 'c';
            } else {
              weather.alt.unit = 'f';
            }

            weather.forecast = [];
            for(var i=0;i<result.item.forecast.length;i++) {
              forecast = result.item.forecast[i];
              forecast.alt = {high: getAltTemp(options.unit, result.item.forecast[i].high), low: getAltTemp(options.unit, result.item.forecast[i].low)};

              if(result.item.forecast[i].code == "3200") {
                forecast.thumbnail = image404;
                forecast.image = image404;
              } else {
                forecast.thumbnail = "https://s.yimg.com/zz/combo?a/i/us/nws/weather/gr/"+result.item.forecast[i].code+"ds.png";
                forecast.image = "https://s.yimg.com/zz/combo?a/i/us/nws/weather/gr/"+result.item.forecast[i].code+"d.png";
              }

              weather.forecast.push(forecast);
            }

            options.success(weather);
          } else {
            options.error({message: "There was an error retrieving the latest weather information. Please try again.", error: data.query.results.channel.item.title});
          }
        }
      );
      return this;
    }
  });
})(jQuery);
<commit_msg>Removed the non-minified version of jquery.simpleweather<commit_after><|endoftext|>


<commit_before>/**
 * transform elastic search related entity query to display format.  See data-model.json
 */

/* globals _ */
/* exported relatedEntityTransform */
var relatedEntityTransform = (function() {

    function getOfferSummary(record) {
        /**  build offer summary record:
            {
                "_id": "http://someuri",
                "_type": "offer",
                "title": "1234567890", // just gets first phone number
                "subtitle": "*Hello World -- google.com", // title of offer
                "details": {
                    "date": "2012-04-23T18:25:43.511Z",
                    "address": "Los Angeles", // just use locality
                    "publisher": "backpage.com"
                }
            }
        */
        var offerObj = {
            _id: record._id,
            _type: record._type,
            title: _.get(record, '_source.seller.telephone.name', 'Phone N/A'),
            subtitle: _.get(record, '_source.mainEntityOfPage.name', 'Title N/A'),
            details: {
                date: _.get(record, '_source.validFrom'),
                address: _.get(record, '_source.availableAtOrFrom.address[0].addressLocality'),
                publisher: _.get(record, '_source.mainEntityOfPage.publisher.name')
            }
        };

        return offerObj;
    }

    function getPhoneSummary(record) {
        /**
            build phone summary object:
            {
                "_id": "http://someuri",
                "_type": "phone",
                "title": "1234567890", // phone number
                "subtitle": "2 offer(s)" // number of offers
            }
        */
        var phoneObj = {
            _id: record._id,
            _type: record._type,
            title: _.get(record, '_source.name', 'Phone N/A'),
            subtitle: _.get(record, '_source.owner[0].makesOffer.length', 0) + ' offer(s)'
        };
        return phoneObj;
    }

    function getEmailSummary(record) {
        /**
            build email summary object:
            {
                "_id": "http://someuri",
                "_type": "email",
                "title": "abc@xyz.com", // email address
                "subtitle": "2 offer(s)" // number of offers
            }
        */
        var emailObj = {
            _id: record._id,
            _type: record._type,
            title: _.get(record, '_source.name', 'Email N/A'),
            subtitle: _.get(record, '_source.owner[0].makesOffer.length', 0) + ' offer(s)'
        };
        return emailObj;
    }

    function getSellerSummary(record) {
        /**
            build seller summary object:
            {
                "_id": "http://someuri",
                "_type": "seller",
                "title": "1234567890", // phone number associated with seller
                "subtitle": "2 offer(s)" // number of offers
            }
        */
        var sellerObj = {
            _id: record._id,
            _type: record._type,
            title: _.get(record, '_source.telephone.name', 'Phone N/A'),
            subtitle: _.get(record, '_source.makesOffer.length', 0) + ' offer(s)'
        };
        return sellerObj;
    }

    function getAddressArray(record) {
        /** build address array:
            "addresses": ["Los Angeles"]
        */
        var addresses = [];
        var addressesArr = _.get(record, '_source.mainEntity.availableAtOrFrom.address', []);

        addressesArr.forEach(function(addressElem) {
            var locality = _.get(addressElem, 'addressLocality');
            var region = _.get(addressElem, 'addressRegion');
            var country = _.get(addressElem, 'addressCountry');

            if(locality) {
                address = locality + ', ' + region + ', ' + country
                addresses.push(address);
            }
        });
        return addresses;
    }

    function getWebpageSummary(record) {
        /*  build webpage summary object:
            {
                "_id": "http://someuri",
                "_type": "webpage",
                "title": "yahoo.com",   // publisher
                "subtitle": "*Hello World -- google.com", // title of webpage
                "details": {
                    "url": "http://someurlhere.com",
                    "body": "description text here",
                    "addresses": ["Los Angeles"],
                    """if phone exists"""
                    "phone": "<phonenumber>",
                    """if email exists"""
                    "email": "<email>"
                    "date": "2012-04-23T18:25:43.511Z"
                }
            }
        */
        var webpageObj = {
            _id: record._id,
            _type: record._type,
            title: _.get(record, '_source.name', 'Title N/A'),
            subtitle: _.get(record, '_source.publisher.name', 'Publisher N/A'),
            details: {
                url: _.get(record, '_source.url'),
                body: _.get(record, '_source.description'),
                addresses: getAddressArray(record),
                _sortedKeys: ['url', 'body', 'addresses', 'phone', 'email', 'date']
            }

        };
        if (_.get(record, '_source.mainEntity.seller.telephone.name') != undefined) {
            webpageObj.details.phone = _.get(record, '_source.mainEntity.seller.telephone.name')
        }
        if (_.get(record, '_source.mainEntity.seller.email.name') != undefined) {
            webpageObj.details.email = _.get(record, '_source.mainEntity.seller.email.name')
        }
        webpageObj.details.date = _.get(record, '_source.dateCreated')

        return webpageObj;
    }

    function getServiceSummary(record) {
        /*
            build service/person summary object:
            {
                "_id": "http://someuri",
                "_type": "person",
                "title": "Emily", // person name
                "subtitle": "Age: 20", // age
                "details": {
                    "height": 64,
                    "weight": 115,
                    "ethnicity": "white"
                }
            }
        */
        var serviceObj = {
            _id: record._id,
            _type: 'person', // hardcode 'person' value for now
            title: _.get(record, '_source.name', 'Name N/A'),
            subtitle: 'Age: ' + _.get(record, '_source.age', 'N/A'),
            details: {
                height: _.get(record, '_source.height'),
                weight: _.get(record, '_source.weight'),
                ethnicity: _.get(record, '_source.ethnicity'),
            }
        };
        return serviceObj;
    }

    return {
        // expected data is from an elasticsearch query
        offer: function(data) {
            var newObj = {data: [], count: 0};
            if(data.hits.hits.length > 0) {
                _.each(data.hits.hits, function(record) {
                    newObj.data.push(getOfferSummary(record));
                });
                newObj.count = data.hits.total;
            }
            return newObj;
        },
        phone: function(data) {
            var newObj = {data: [], count: 0};
            if(data.hits.hits.length > 0) {
                _.each(data.hits.hits, function(record) {
                    newObj.data.push(getPhoneSummary(record));
                });
                newObj.count = data.hits.total;
            }
            return newObj;
        },
        email: function(data) {
            var newObj = {data: [], count: 0};
            if(data.hits.hits.length > 0) {
                _.each(data.hits.hits, function(record) {
                    newObj.data.push(getEmailSummary(record));
                });
                newObj.count = data.hits.total;
            }
            return newObj;
        },
        seller: function(data) {
            var newObj = {data: [], count: 0};
            if(data.hits.hits.length > 0) {
                _.each(data.hits.hits, function(record) {
                    newObj.data.push(getSellerSummary(record));
                });
                newObj.count = data.hits.total;
            }
            return newObj;
        },
        service: function(data) {
            var newObj = {data: [], count: 0};
            if(data.hits.hits.length > 0) {
                _.each(data.hits.hits, function(record) {
                    newObj.data.push(getServiceSummary(record));
                });
                newObj.count = data.hits.total;
            }
            return newObj;
        },
        webpage: function(data) {
            var newObj = {data: [], count: 0};
            if(data.hits.hits.length > 0) {
                _.each(data.hits.hits, function(record) {
                    newObj.data.push(getWebpageSummary(record));
                });
                newObj.count = data.hits.total;
            }
            return newObj;
        },
        // transform for combined sets of results not separated by type
        combinedResults: function(data) {
            var newObj = {data: [], count: 0};
            if(data && data.hits && data.hits.hits.length > 0) {
                _.each(data.hits.hits, function(record) {
                    switch(record._type) {
                        case 'email': newObj.data.push(getEmailSummary(record));
                            break;
                        case 'adultservice': newObj.data.push(getServiceSummary(record));
                            break;
                        case 'phone': newObj.data.push(getPhoneSummary(record));
                            break;
                        case 'offer': newObj.data.push(getOfferSummary(record));
                            break;
                        case 'seller': newObj.data.push(getSellerSummary(record));
                            break;
                        case 'webpage': newObj.data.push(getWebpageSummary(record));
                            break;
                    }
                });
                newObj.count = data.hits.total;
            }
            return newObj;
        },

        cityResults: function(data) {
            if(data && data.aggregations && data.aggregations.webpageCityAgg && data.aggregations.webpageCityAgg.webpageCityAgg.buckets) {
                _.each(data.aggregations.webpageCityAgg.webpageCityAgg.buckets, function(record) {
                    keys = record.key.split(':');
                    //record['key'] = keys[0] + ',' + keys[1];
                    record['text'] = keys[0];
                });
            }
            return data;
        }
    };

})();

<commit_msg>create new object in city-> key to text transform<commit_after>/**
 * transform elastic search related entity query to display format.  See data-model.json
 */

/* globals _ */
/* exported relatedEntityTransform */
var relatedEntityTransform = (function() {

    function getOfferSummary(record) {
        /**  build offer summary record:
            {
                "_id": "http://someuri",
                "_type": "offer",
                "title": "1234567890", // just gets first phone number
                "subtitle": "*Hello World -- google.com", // title of offer
                "details": {
                    "date": "2012-04-23T18:25:43.511Z",
                    "address": "Los Angeles", // just use locality
                    "publisher": "backpage.com"
                }
            }
        */
        var offerObj = {
            _id: record._id,
            _type: record._type,
            title: _.get(record, '_source.seller.telephone.name', 'Phone N/A'),
            subtitle: _.get(record, '_source.mainEntityOfPage.name', 'Title N/A'),
            details: {
                date: _.get(record, '_source.validFrom'),
                address: _.get(record, '_source.availableAtOrFrom.address[0].addressLocality'),
                publisher: _.get(record, '_source.mainEntityOfPage.publisher.name')
            }
        };

        return offerObj;
    }

    function getPhoneSummary(record) {
        /**
            build phone summary object:
            {
                "_id": "http://someuri",
                "_type": "phone",
                "title": "1234567890", // phone number
                "subtitle": "2 offer(s)" // number of offers
            }
        */
        var phoneObj = {
            _id: record._id,
            _type: record._type,
            title: _.get(record, '_source.name', 'Phone N/A'),
            subtitle: _.get(record, '_source.owner[0].makesOffer.length', 0) + ' offer(s)'
        };
        return phoneObj;
    }

    function getEmailSummary(record) {
        /**
            build email summary object:
            {
                "_id": "http://someuri",
                "_type": "email",
                "title": "abc@xyz.com", // email address
                "subtitle": "2 offer(s)" // number of offers
            }
        */
        var emailObj = {
            _id: record._id,
            _type: record._type,
            title: _.get(record, '_source.name', 'Email N/A'),
            subtitle: _.get(record, '_source.owner[0].makesOffer.length', 0) + ' offer(s)'
        };
        return emailObj;
    }

    function getSellerSummary(record) {
        /**
            build seller summary object:
            {
                "_id": "http://someuri",
                "_type": "seller",
                "title": "1234567890", // phone number associated with seller
                "subtitle": "2 offer(s)" // number of offers
            }
        */
        var sellerObj = {
            _id: record._id,
            _type: record._type,
            title: _.get(record, '_source.telephone.name', 'Phone N/A'),
            subtitle: _.get(record, '_source.makesOffer.length', 0) + ' offer(s)'
        };
        return sellerObj;
    }

    function getAddressArray(record) {
        /** build address array:
            "addresses": ["Los Angeles"]
        */
        var addresses = [];
        var addressesArr = _.get(record, '_source.mainEntity.availableAtOrFrom.address', []);

        addressesArr.forEach(function(addressElem) {
            var locality = _.get(addressElem, 'addressLocality');
            var region = _.get(addressElem, 'addressRegion');
            var country = _.get(addressElem, 'addressCountry');

            if(locality) {
                address = locality + ', ' + region + ', ' + country
                addresses.push(address);
            }
        });
        return addresses;
    }

    function getWebpageSummary(record) {
        /*  build webpage summary object:
            {
                "_id": "http://someuri",
                "_type": "webpage",
                "title": "yahoo.com",   // publisher
                "subtitle": "*Hello World -- google.com", // title of webpage
                "details": {
                    "url": "http://someurlhere.com",
                    "body": "description text here",
                    "addresses": ["Los Angeles"],
                    """if phone exists"""
                    "phone": "<phonenumber>",
                    """if email exists"""
                    "email": "<email>"
                    "date": "2012-04-23T18:25:43.511Z"
                }
            }
        */
        var webpageObj = {
            _id: record._id,
            _type: record._type,
            title: _.get(record, '_source.name', 'Title N/A'),
            subtitle: _.get(record, '_source.publisher.name', 'Publisher N/A'),
            details: {
                url: _.get(record, '_source.url'),
                body: _.get(record, '_source.description'),
                addresses: getAddressArray(record),
                _sortedKeys: ['url', 'body', 'addresses', 'phone', 'email', 'date']
            }

        };
        if (_.get(record, '_source.mainEntity.seller.telephone.name') != undefined) {
            webpageObj.details.phone = _.get(record, '_source.mainEntity.seller.telephone.name')
        }
        if (_.get(record, '_source.mainEntity.seller.email.name') != undefined) {
            webpageObj.details.email = _.get(record, '_source.mainEntity.seller.email.name')
        }
        webpageObj.details.date = _.get(record, '_source.dateCreated')

        return webpageObj;
    }

    function getServiceSummary(record) {
        /*
            build service/person summary object:
            {
                "_id": "http://someuri",
                "_type": "person",
                "title": "Emily", // person name
                "subtitle": "Age: 20", // age
                "details": {
                    "height": 64,
                    "weight": 115,
                    "ethnicity": "white"
                }
            }
        */
        var serviceObj = {
            _id: record._id,
            _type: 'person', // hardcode 'person' value for now
            title: _.get(record, '_source.name', 'Name N/A'),
            subtitle: 'Age: ' + _.get(record, '_source.age', 'N/A'),
            details: {
                height: _.get(record, '_source.height'),
                weight: _.get(record, '_source.weight'),
                ethnicity: _.get(record, '_source.ethnicity'),
            }
        };
        return serviceObj;
    }

    return {
        // expected data is from an elasticsearch query
        offer: function(data) {
            var newObj = {data: [], count: 0};
            if(data.hits.hits.length > 0) {
                _.each(data.hits.hits, function(record) {
                    newObj.data.push(getOfferSummary(record));
                });
                newObj.count = data.hits.total;
            }
            return newObj;
        },
        phone: function(data) {
            var newObj = {data: [], count: 0};
            if(data.hits.hits.length > 0) {
                _.each(data.hits.hits, function(record) {
                    newObj.data.push(getPhoneSummary(record));
                });
                newObj.count = data.hits.total;
            }
            return newObj;
        },
        email: function(data) {
            var newObj = {data: [], count: 0};
            if(data.hits.hits.length > 0) {
                _.each(data.hits.hits, function(record) {
                    newObj.data.push(getEmailSummary(record));
                });
                newObj.count = data.hits.total;
            }
            return newObj;
        },
        seller: function(data) {
            var newObj = {data: [], count: 0};
            if(data.hits.hits.length > 0) {
                _.each(data.hits.hits, function(record) {
                    newObj.data.push(getSellerSummary(record));
                });
                newObj.count = data.hits.total;
            }
            return newObj;
        },
        service: function(data) {
            var newObj = {data: [], count: 0};
            if(data.hits.hits.length > 0) {
                _.each(data.hits.hits, function(record) {
                    newObj.data.push(getServiceSummary(record));
                });
                newObj.count = data.hits.total;
            }
            return newObj;
        },
        webpage: function(data) {
            var newObj = {data: [], count: 0};
            if(data.hits.hits.length > 0) {
                _.each(data.hits.hits, function(record) {
                    newObj.data.push(getWebpageSummary(record));
                });
                newObj.count = data.hits.total;
            }
            return newObj;
        },
        // transform for combined sets of results not separated by type
        combinedResults: function(data) {
            var newObj = {data: [], count: 0};
            if(data && data.hits && data.hits.hits.length > 0) {
                _.each(data.hits.hits, function(record) {
                    switch(record._type) {
                        case 'email': newObj.data.push(getEmailSummary(record));
                            break;
                        case 'adultservice': newObj.data.push(getServiceSummary(record));
                            break;
                        case 'phone': newObj.data.push(getPhoneSummary(record));
                            break;
                        case 'offer': newObj.data.push(getOfferSummary(record));
                            break;
                        case 'seller': newObj.data.push(getSellerSummary(record));
                            break;
                        case 'webpage': newObj.data.push(getWebpageSummary(record));
                            break;
                    }
                });
                newObj.count = data.hits.total;
            }
            return newObj;
        },

        cityResults: function(data) {
            var newObject = {};

           if(data && data.aggregations && data.aggregations.webpageCityAgg && data.aggregations.webpageCityAgg.webpageCityAgg.buckets) {
                newObject.aggregations = {};
                newObject.aggregations.webpageCityAgg = {};
                newObject.aggregations.webpageCityAgg.webpageCityAgg = {};
                newObject.aggregations.webpageCityAgg.webpageCityAgg.buckets = [];
                _.each(data.aggregations.webpageCityAgg.webpageCityAgg.buckets, function(record) {

                    newObj = {};
                    newObj.key = record.key;
                    keys = record.key.split(':');
                    newObj.text = keys[0];
                    newObj.doc_count = record.doc_count;

                    newObject.aggregations.webpageCityAgg.webpageCityAgg.buckets.push(newObj);
                    //record['key'] = keys[0] + ',' + keys[1];
                    // record['text'] = keys[0];
                });
            }
            // console.log(data);
            return newObject;
        }
    };

})();

<|endoftext|>