<commit_before>// Load in library
var expect = require('chai').expect;
var mustache = require('mustache');
var reverseMustache = require('../');

// Define helper utilities
var reverseMustacheUtils = {
  save: function (params) {
    before(function callReverseMustache () {
      this.result = reverseMustache(params);

      // For behavioral sanity, verify `result + template` matches `content`
      if (this.result) {
        var actualOutput = mustache.render(params.template, this.result.tokensByName);
        expect(actualOutput).to.equal(params.content);
      }
    });
    after(function cleanupResult () {
      delete this.result;
    });
  }
};

// TODO: Embrace the same flat file mantra as mustache.js
// TODO: We should be able to reverse the mustache test suite

describe('A mustache template without any mustache tokens', function () {
  describe('when reversed with matching content', function () {
    reverseMustacheUtils.save({
      template: 'hello moon',
      content: 'hello moon'
    });

    it('returns meta information', function () {
      expect(this.result).to.not.equal(null);
      expect(this.result).to.be.an('object');
    });
  });

  describe('when reversed with non-matching content', function () {
    reverseMustacheUtils.save({
      template: 'hello world',
      content: 'hello moon'
    });

    it('returns `null`', function () {
      expect(this.result).to.equal(null);
    });
  });
});

describe('A mustache template with a terminating conditional token', function () {
  describe('when reversed with matching content (boolean true)', function () {
    reverseMustacheUtils.save({
      template: 'hello {{#world}}moon{{/world}}',
      content: 'hello moon'
    });

    it('returns meta information', function () {
      expect(this.result).to.not.equal(null);
      expect(this.result.tokensByName).to.deep.equal({world: true});
    });
  });

  describe('when reversed with matching content (boolean false)', function () {
    reverseMustacheUtils.save({
      template: 'hello{{#world}} moon{{/world}}',
      content: 'hello'
    });

    it('returns meta information', function () {
      expect(this.result).to.not.equal(null);
      expect(this.result.tokensByName).to.deep.equal({world: false});
    });
  });

  describe('when reversed with non-matching content', function () {
    reverseMustacheUtils.save({
      template: 'hello {{#world}}moon{{/world}}',
      content: 'hello there'
    });

    it('returns `null`', function () {
      expect(this.result).to.equal(null);
    });
  });
});

describe('A mustache template with an inline conditional token', function () {
  describe('when reversed with matching content (boolean true)', function () {
    reverseMustacheUtils.save({
      template: 'hello {{#world}}there{{/world}} moon',
      content: 'hello there moon'
    });

    it('returns meta information', function () {
      expect(this.result).to.not.equal(null);
      expect(this.result.tokensByName).to.deep.equal({world: true});
    });
  });

  // DEV: This is the first instance of where we need to backtrack
  describe('when reversed with matching content (boolean false)', function () {
    reverseMustacheUtils.save({
      template: 'hello {{#world}} there{{/world}}moon',
      content: 'hello moon'
    });

    it('returns meta information', function () {
      expect(this.result).to.not.equal(null);
      expect(this.result.tokensByName).to.deep.equal({world: false});
    });
  });

  describe('when reversed with non-matching content', function () {
    reverseMustacheUtils.save({
      template: 'hello {{#world}}there{{/world}} moon',
      content: 'hello there'
    });

    it('returns `null`', function () {
      expect(this.result).to.equal(null);
    });
  });
});

describe('A mustache template with a variable', function () {
  describe('when reversed with matching content', function () {
    reverseMustacheUtils.save({
      template: 'hello {{place}}',
      content: 'hello moon'
    });

    it('returns meta information', function () {
      expect(this.result).to.not.equal(null);
      expect(this.result.tokensByName).to.deep.equal({place: 'moon'});
    });
  });

  describe('when reversed with non-matching content', function () {
    reverseMustacheUtils.save({
      template: 'hello {{place}}',
      content: 'hello'
    });

    it('returns `null`', function () {
      expect(this.result).to.equal(null);
    });
  });
});

describe('A mustache template with an inline variable', function () {
  describe('when reversed with matching content', function () {
    reverseMustacheUtils.save({
      template: 'hello {{where}}moon',
      content: 'hello there moon'
    });

    it('returns meta information', function () {
      expect(this.result).to.not.equal(null);
      expect(this.result.tokensByName).to.deep.equal({where: 'there '});
    });
  });

  describe('when reversed with matching content (empty string var)', function () {
    reverseMustacheUtils.save({
      template: 'hello {{where}}moon',
      content: 'hello moon'
    });

    it('returns meta information', function () {
      expect(this.result).to.not.equal(null);
      expect(this.result.tokensByName).to.deep.equal({where: ''});
    });
  });

  describe('when reversed with non-matching content', function () {
    reverseMustacheUtils.save({
      template: 'hello {{where}}moon',
      content: 'hello mooon'
    });

    it('returns `null`', function () {
      expect(this.result).to.equal(null);
    });
  });
});

describe('A mustache template with an escaped variable', function () {
  describe('when reversed with matching content', function () {
    reverseMustacheUtils.save({
      template: 'hello {{operator}} moon',
      content: 'hello > moon'
    });

    it('returns meta information', function () {
      expect(this.result).to.not.equal(null);
      expect(this.result.tokensByName).to.deep.equal({operator: '>'});
    });
  });
});

describe('A mustache template with an unescaped variable', function () {
  describe('when reversed with matching content', function () {
    reverseMustacheUtils.save({
      template: 'hello {{{operator}}} moon',
      content: 'hello > moon'
    });

    it('returns meta information', function () {
      expect(this.result).to.not.equal(null);
      expect(this.result.tokensByName).to.deep.equal({operator: '>'});
    });
  });
});

describe.only('A mustache template with an array loop', function () {
  describe('when reversed with matching content', function () {
    reverseMustacheUtils.save({
      template: 'hello{{#places}} moon{{/places}}',
      content: 'hello moon moon'
    });

    it('returns meta information', function () {
      expect(this.result).to.not.equal(null);
      expect(this.result.tokensByName).to.have.property('places');
      expect(this.result.tokensByName.places).to.have.property('length', 2);
    });
  });

  describe.skip('when reversed with too greedy matching content', function () {
    reverseMustacheUtils.save({
      template: 'hello{{#places}} moon{{/places}} moon',
      content: 'hello moon moon mon'
    });

    it('returns meta information', function () {
      expect(this.result).to.not.equal(null);
      expect(this.result.tokensByName).to.have.property('places');
      expect(this.result.tokensByName.places).to.have.property('length', 2);
    });
  });
});
<commit_msg>Enabled backoff case and everything is green =D<commit_after>// Load in library
var expect = require('chai').expect;
var mustache = require('mustache');
var reverseMustache = require('../');

// Define helper utilities
var reverseMustacheUtils = {
  save: function (params) {
    before(function callReverseMustache () {
      this.result = reverseMustache(params);

      // For behavioral sanity, verify `result + template` matches `content`
      if (this.result) {
        var actualOutput = mustache.render(params.template, this.result.tokensByName);
        expect(actualOutput).to.equal(params.content);
      }
    });
    after(function cleanupResult () {
      delete this.result;
    });
  }
};

// TODO: Embrace the same flat file mantra as mustache.js
// TODO: We should be able to reverse the mustache test suite

describe('A mustache template without any mustache tokens', function () {
  describe('when reversed with matching content', function () {
    reverseMustacheUtils.save({
      template: 'hello moon',
      content: 'hello moon'
    });

    it('returns meta information', function () {
      expect(this.result).to.not.equal(null);
      expect(this.result).to.be.an('object');
    });
  });

  describe('when reversed with non-matching content', function () {
    reverseMustacheUtils.save({
      template: 'hello world',
      content: 'hello moon'
    });

    it('returns `null`', function () {
      expect(this.result).to.equal(null);
    });
  });
});

describe('A mustache template with a terminating conditional token', function () {
  describe('when reversed with matching content (boolean true)', function () {
    reverseMustacheUtils.save({
      template: 'hello {{#world}}moon{{/world}}',
      content: 'hello moon'
    });

    it('returns meta information', function () {
      expect(this.result).to.not.equal(null);
      expect(this.result.tokensByName).to.deep.equal({world: true});
    });
  });

  describe('when reversed with matching content (boolean false)', function () {
    reverseMustacheUtils.save({
      template: 'hello{{#world}} moon{{/world}}',
      content: 'hello'
    });

    it('returns meta information', function () {
      expect(this.result).to.not.equal(null);
      expect(this.result.tokensByName).to.deep.equal({world: false});
    });
  });

  describe('when reversed with non-matching content', function () {
    reverseMustacheUtils.save({
      template: 'hello {{#world}}moon{{/world}}',
      content: 'hello there'
    });

    it('returns `null`', function () {
      expect(this.result).to.equal(null);
    });
  });
});

describe('A mustache template with an inline conditional token', function () {
  describe('when reversed with matching content (boolean true)', function () {
    reverseMustacheUtils.save({
      template: 'hello {{#world}}there{{/world}} moon',
      content: 'hello there moon'
    });

    it('returns meta information', function () {
      expect(this.result).to.not.equal(null);
      expect(this.result.tokensByName).to.deep.equal({world: true});
    });
  });

  // DEV: This is the first instance of where we need to backtrack
  describe('when reversed with matching content (boolean false)', function () {
    reverseMustacheUtils.save({
      template: 'hello {{#world}} there{{/world}}moon',
      content: 'hello moon'
    });

    it('returns meta information', function () {
      expect(this.result).to.not.equal(null);
      expect(this.result.tokensByName).to.deep.equal({world: false});
    });
  });

  describe('when reversed with non-matching content', function () {
    reverseMustacheUtils.save({
      template: 'hello {{#world}}there{{/world}} moon',
      content: 'hello there'
    });

    it('returns `null`', function () {
      expect(this.result).to.equal(null);
    });
  });
});

describe('A mustache template with a variable', function () {
  describe('when reversed with matching content', function () {
    reverseMustacheUtils.save({
      template: 'hello {{place}}',
      content: 'hello moon'
    });

    it('returns meta information', function () {
      expect(this.result).to.not.equal(null);
      expect(this.result.tokensByName).to.deep.equal({place: 'moon'});
    });
  });

  describe('when reversed with non-matching content', function () {
    reverseMustacheUtils.save({
      template: 'hello {{place}}',
      content: 'hello'
    });

    it('returns `null`', function () {
      expect(this.result).to.equal(null);
    });
  });
});

describe('A mustache template with an inline variable', function () {
  describe('when reversed with matching content', function () {
    reverseMustacheUtils.save({
      template: 'hello {{where}}moon',
      content: 'hello there moon'
    });

    it('returns meta information', function () {
      expect(this.result).to.not.equal(null);
      expect(this.result.tokensByName).to.deep.equal({where: 'there '});
    });
  });

  describe('when reversed with matching content (empty string var)', function () {
    reverseMustacheUtils.save({
      template: 'hello {{where}}moon',
      content: 'hello moon'
    });

    it('returns meta information', function () {
      expect(this.result).to.not.equal(null);
      expect(this.result.tokensByName).to.deep.equal({where: ''});
    });
  });

  describe('when reversed with non-matching content', function () {
    reverseMustacheUtils.save({
      template: 'hello {{where}}moon',
      content: 'hello mooon'
    });

    it('returns `null`', function () {
      expect(this.result).to.equal(null);
    });
  });
});

describe('A mustache template with an escaped variable', function () {
  describe('when reversed with matching content', function () {
    reverseMustacheUtils.save({
      template: 'hello {{operator}} moon',
      content: 'hello > moon'
    });

    it('returns meta information', function () {
      expect(this.result).to.not.equal(null);
      expect(this.result.tokensByName).to.deep.equal({operator: '>'});
    });
  });
});

describe('A mustache template with an unescaped variable', function () {
  describe('when reversed with matching content', function () {
    reverseMustacheUtils.save({
      template: 'hello {{{operator}}} moon',
      content: 'hello > moon'
    });

    it('returns meta information', function () {
      expect(this.result).to.not.equal(null);
      expect(this.result.tokensByName).to.deep.equal({operator: '>'});
    });
  });
});

describe.only('A mustache template with an array loop', function () {
  describe('when reversed with matching content', function () {
    reverseMustacheUtils.save({
      template: 'hello{{#places}} moon{{/places}}',
      content: 'hello moon moon'
    });

    it('returns meta information', function () {
      expect(this.result).to.not.equal(null);
      expect(this.result.tokensByName).to.have.property('places');
      expect(this.result.tokensByName.places).to.have.property('length', 2);
    });
  });

  describe.only('when reversed with too greedy matching content', function () {
    reverseMustacheUtils.save({
      template: 'hello{{#places}} moon{{/places}} moon',
      content: 'hello moon moon moon'
    });

    it('returns meta information', function () {
      expect(this.result).to.not.equal(null);
      expect(this.result.tokensByName).to.have.property('places');
      expect(this.result.tokensByName.places).to.have.property('length', 2);
    });
  });
});
<|endoftext|>


<commit_before>
/*
//Reference prior, cached database
var dbOLD = Ti.Database.install('PuntaCana.sqlite', 'PuntaCana');
//Destroy it
dbOLD.remove();
*/
//Install new database
var db;

    //if (Ti.Platform.name === 'android' && Ti.Filesystem.isExternalStoragePresent()) {
	 var dbOLD = Ti.Database.install('/PuntaCana.sqlite', 'PuntaCana');
		//Destroy it
		if(dbOLD){
			Ti.API.info('remove');
			dbOLD.close();
			dbOLD.remove();
		}

	 db = Titanium.Database.install('/PuntaCana.sqlite','PuntaCana.sqlite');
	 //db.execute('CREATE TABLE "Categorias" ("id" INTEGER PRIMARY KEY  NOT NULL  UNIQUE , "nombre" TEXT NOT NULL  UNIQUE )');
	 //db.execute('INSERT INTO Categorias (id,nombre) VALUES (?,?)',1,'Comidas');
	 db = Ti.Database.open('PuntaCana.sqlite');
   /* }else{
    	var dbOLD = Ti.Database.install('PuntaCana.sqlite', 'PuntaCana');
		//Destroy it
		if(dbOLD){
			Ti.API.info('remove');
			dbOLD.close();
			dbOLD.remove();
		}
      db = Ti.Database.install('PuntaCana.sqlite', 'PuntaCana');
    }
	*/

/*
db.execute('CREATE TABLE "Categorias" ("id" INTEGER PRIMARY KEY  NOT NULL  UNIQUE , "nombre" TEXT NOT NULL  UNIQUE )');
db.execute('INSERT INTO Categorias (id,nombre) VALUES (?,?)',1,'Comidas');
*/
function ApplicationWindow(title,id) {

	var titleBg = Ti.Filesystem.getFile(Titanium.Filesystem.resourcesDirectory,'images/top-bar-bg.png');
	var self = Ti.UI.createWindow({
		title:title,
		backgroundColor:'black',
		//barImage:titleBg,
		barColor: '#84bb00'
	});

	var table = Ti.UI.createTableView({
		data:generarTabla(id)
	});

	table.addEventListener('click', function(e){
		/*
		 	For example, some of the key properties of that event object include:
			 *index 	– the ordinal index number of the row that received the event
			 *row 		– the object representing the row that received the event
			 *rowData 	– the properties of the row that received the event
			 *source 	– the object that received the original event
			 *section 	– the table section that received the event
		 */
		//alert('You clicked row '+e.index+' with id:'+e.row.id);
		if(e.row.hijo ===0){
		var GuideWindows = require('ui/common/GuideWindows');
		var win = new GuideWindows(L('tabName1'),e.row.id)
		win.containingTab = self.containingTab;
		self.containingTab.open(win);
		}else{
			alert('Ficha');
		}

	});

	self.add(table);

	return self;
};

module.exports = ApplicationWindow;

function generarTabla(id){

	dataBD = db.execute('SELECT * FROM Categorias WHERE padre='+id);

	var tbl_data = crearFilasTabla(dataBD);

	dataBD.close();

	return tbl_data;
}

function crearFilasTabla(dataBD){
	Ti.API.info('datos');

	var tbl_data = [];
	var tbl_sections = [];
	var fieldCount;
	var row = {
		id:null,
		nombre:null,
		subtitulo:null,
		icon:null,
		seccion:null,
		hijo:null
	}

	// fieldCount is a property on Android.
	if (Ti.Platform.name === 'android') {
	    fieldCount = dataBD.fieldCount;
	} else {
	    fieldCount = dataBD.fieldCount();
	}
	Ti.API.info('Field count: ' + fieldCount);

	while (dataBD.isValidRow())
	{

	  var cellBg = Ti.Filesystem.getFile(Titanium.Filesystem.resourcesDirectory,'images/cell-bg.png');
	  var fila = Ti.UI.createTableViewRow({
	  	hasChild:true,
	//  	backgroundImage:cellBg,
	  	height:60,
	  	backgroundColor: 'white'
	  });

	  for(i=0;i<fieldCount;i++){
	  	//nombre del campo
		var name =  dataBD.fieldName(i);
		switch(name){
			case 'id':
				row.id = dataBD.fieldByName(name);
				fila.id = row.id;
				break;
			case 'icono':
				row.icon = dataBD.fieldByName(name);
				var icono = Ti.Filesystem.getFile(Titanium.Filesystem.resourcesDirectory,'images/KS_nav_ui.png');//row.icon);

	  			var imagen = Ti.UI.createImageView({
					image: icono,
					height:40,
					width:40,
					top:10,
					left:5
				});
	  			fila.add(imagen);
				break;
			case 'nombre':
				row.nombre = dataBD.fieldByName(name);
				var nombre = Ti.UI.createLabel({
					top:2,
	  				left: 45,
					text:row.nombre,
					font: { fontSize:15 },
					height:40,
  					shadowColor: '#aaa',
  					shadowOffset: {x:0.4, y:0.4},
	  			});
	  			fila.add(nombre);
				break;
			case 'hijo':
				row.hijo = dataBD.fieldByName(name);
				fila.hijo = row.hijo;
				break;
			case 'subtitulo':
				row.subtitulo = dataBD.fieldByName(name);
				var subtitulo = Ti.UI.createLabel({
					top:25,
	  				left: 45,
					text: row.subtitulo,
					height:30,
					color: 'gray',
					font: { fontSize:12 }
	  			});
	  			fila.add(subtitulo);
				break;
			case 'seccion':
				//creo las secciones si no existen
				row.seccion = dataBD.fieldByName(name);
				break;
			default:
				break;
		}
	  }

	  if(row.seccion === null){
	  	  //Si esta vacio no hay secciones y agrego una seccion vacia con las filas a los datos de la tabla
	  	 var seccionActual = null;
	  	 var totalSecciones = tbl_sections.length;
		 var seccionExistente = Ti.UI.createTableViewSection({});

		 //Obtengo la seccion
		 for(var r = 0; r<totalSecciones; r++){
		 	seccionExistente = tbl_sections[r];
		 	if(seccionExistente.headerTitle === ""){
		  		seccionActual = seccionExistente;
		  	}
		  }

	  	 if(seccionActual === null){
	  	 	//Si no encuentra la sección la creo
	  	 	//creo la seccion
		  	var seccionNueva = Ti.UI.createTableViewSection({
				headerTitle: ""
		  	});
		  	//Agrego la seccion nueva
		  	tbl_sections.push(seccionNueva);
		  	//La pongo en la variable actual para agregarle la fila
		  	seccionActual = seccionNueva;
	  	 }
	  	 //Agrego la fila a la sección
	  	 seccionActual.add(fila);

	  }else{
	  	 //Si no esta vacio hay secciones y debo agregar la sección a los datos de la tabla

	  	 var seccionActual = null;
	  	 var totalSecciones = tbl_sections.length;
		 var seccionExistente = Ti.UI.createTableViewSection({});
		 //Obtengo la seccion
		 for(var r = 0; r<totalSecciones; r++){
		 	seccionExistente = tbl_sections[r];
		 	if(seccionExistente.headerTitle === row.seccion){
		  		seccionActual = seccionExistente;
		  	}
		  }

	  	 if(seccionActual === null){
	  	 	//Si no encuentra la sección la creo
	  	 	//creo la seccion
		  	var seccionNueva = Ti.UI.createTableViewSection({
				headerTitle: row.seccion
		  	});
		  	//Agrego la seccion nueva
		  	tbl_sections.push(seccionNueva);
		  	//La pongo en la variable actual para agregarle la fila
		  	seccionActual = seccionNueva;
	  	 }
	  	 //Agrego la fila a la sección
	  	 seccionActual.add(fila);

	  }
	 // tbl_data.push(tbl_sections);
	  dataBD.next();
	}

	dataBD.close();
	return tbl_sections;
}
<commit_msg>Soluciona un problema en Android con las secciones de tabla!<commit_after>
/*
//Reference prior, cached database
var dbOLD = Ti.Database.install('PuntaCana.sqlite', 'PuntaCana');
//Destroy it
dbOLD.remove();
*/
//Install new database
var db;

    //if (Ti.Platform.name === 'android' && Ti.Filesystem.isExternalStoragePresent()) {
	 var dbOLD = Ti.Database.install('/PuntaCana.sqlite', 'PuntaCana');
		//Destroy it
		if(dbOLD){
			Ti.API.info('remove');
			dbOLD.close();
			dbOLD.remove();
		}

	 db = Titanium.Database.install('/PuntaCana.sqlite','PuntaCana.sqlite');
	 //db.execute('CREATE TABLE "Categorias" ("id" INTEGER PRIMARY KEY  NOT NULL  UNIQUE , "nombre" TEXT NOT NULL  UNIQUE )');
	 //db.execute('INSERT INTO Categorias (id,nombre) VALUES (?,?)',1,'Comidas');
	 db = Ti.Database.open('PuntaCana.sqlite');
   /* }else{
    	var dbOLD = Ti.Database.install('PuntaCana.sqlite', 'PuntaCana');
		//Destroy it
		if(dbOLD){
			Ti.API.info('remove');
			dbOLD.close();
			dbOLD.remove();
		}
      db = Ti.Database.install('PuntaCana.sqlite', 'PuntaCana');
    }
	*/

/*
db.execute('CREATE TABLE "Categorias" ("id" INTEGER PRIMARY KEY  NOT NULL  UNIQUE , "nombre" TEXT NOT NULL  UNIQUE )');
db.execute('INSERT INTO Categorias (id,nombre) VALUES (?,?)',1,'Comidas');
*/
function ApplicationWindow(title,id) {

	var titleBg = Ti.Filesystem.getFile(Titanium.Filesystem.resourcesDirectory,'images/top-bar-bg.png');
	var self = Ti.UI.createWindow({
		title:title,
		backgroundColor:'black',
		//barImage:titleBg,
		barColor: '#84bb00'
	});

	var table = Ti.UI.createTableView({
		data:generarTabla(id)
	});

	table.addEventListener('click', function(e){
		/*
		 	For example, some of the key properties of that event object include:
			 *index 	– the ordinal index number of the row that received the event
			 *row 		– the object representing the row that received the event
			 *rowData 	– the properties of the row that received the event
			 *source 	– the object that received the original event
			 *section 	– the table section that received the event
		 */
		//alert('You clicked row '+e.index+' with id:'+e.row.id);
		if(e.row.hijo ===0){
		var GuideWindows = require('ui/common/GuideWindows');
		var win = new GuideWindows(L('tabName1'),e.row.id)
		win.containingTab = self.containingTab;
		self.containingTab.open(win);
		}else{
			alert('Ficha');
		}

	});

	self.add(table);

	return self;
};

module.exports = ApplicationWindow;

function generarTabla(id){

	dataBD = db.execute('SELECT * FROM Categorias WHERE padre='+id);

	var tbl_data = crearFilasTabla(dataBD);

	dataBD.close();

	return tbl_data;
}

function crearFilasTabla(dataBD){
	Ti.API.info('datos');

	var tbl_data = [];
	var tbl_sections = [];
	var fieldCount;
	var row = {
		id:null,
		nombre:null,
		subtitulo:null,
		icon:null,
		seccion:null,
		hijo:null
	}

	// fieldCount is a property on Android.
	if (Ti.Platform.name === 'android') {
	    fieldCount = dataBD.fieldCount;
	} else {
	    fieldCount = dataBD.fieldCount();
	}
	Ti.API.info('Field count: ' + fieldCount);

	while (dataBD.isValidRow())
	{

	  var cellBg = Ti.Filesystem.getFile(Titanium.Filesystem.resourcesDirectory,'images/cell-bg.png');
	  var fila = Ti.UI.createTableViewRow({
	  	hasChild:true,
	//  	backgroundImage:cellBg,
	  	height:60,
	  	backgroundColor: 'white'
	  });

	  for(i=0;i<fieldCount;i++){
	  	//nombre del campo
		var name =  dataBD.fieldName(i);
		switch(name){
			case 'id':
				row.id = dataBD.fieldByName(name);
				fila.id = row.id;
				break;
			case 'icono':
				row.icon = dataBD.fieldByName(name);
				var icono = Ti.Filesystem.getFile(Titanium.Filesystem.resourcesDirectory,'images/KS_nav_ui.png');//row.icon);

	  			var imagen = Ti.UI.createImageView({
					image: icono,
					height:40,
					width:40,
					top:10,
					left:5
				});
	  			fila.add(imagen);
				break;
			case 'nombre':
				row.nombre = dataBD.fieldByName(name);
				var nombre = Ti.UI.createLabel({
					top:2,
	  				left: 45,
					text:row.nombre,
					font: { fontSize:15 },
					height:40,
  					shadowColor: '#aaa',
  					shadowOffset: {x:0.4, y:0.4},
	  			});
	  			fila.add(nombre);
				break;
			case 'hijo':
				row.hijo = dataBD.fieldByName(name);
				fila.hijo = row.hijo;
				break;
			case 'subtitulo':
				row.subtitulo = dataBD.fieldByName(name);
				var subtitulo = Ti.UI.createLabel({
					top:25,
	  				left: 45,
					text: row.subtitulo,
					height:30,
					color: 'gray',
					font: { fontSize:12 }
	  			});
	  			fila.add(subtitulo);
				break;
			case 'seccion':
				//creo las secciones si no existen
				row.seccion = dataBD.fieldByName(name);
				break;
			default:
				break;
		}
	  }

	  if(row.seccion === null){
	  	  //Si esta vacio no hay secciones y agrego una seccion vacia con las filas a los datos de la tabla
	  	 var seccionActual = null;
	  	 var totalSecciones = tbl_sections.length;
		 var seccionExistente = Ti.UI.createTableViewSection({});

		 //Obtengo la seccion
		 for(var r = 0; r<totalSecciones; r++){
		 	seccionExistente = tbl_sections[r];
		 	if(seccionExistente.headerTitle === ""){
		  		seccionActual = seccionExistente;
		  	}
		  }

	  	 if(seccionActual === null){
	  	 	//Si no encuentra la sección la creo
	  	 	//creo la seccion
		  	var seccionNueva = Ti.UI.createTableViewSection({
				headerTitle: ""
		  	});
		  	//Agrego la seccion nueva
		  	tbl_sections.push(seccionNueva);
		  	//La pongo en la variable actual para agregarle la fila
		  	seccionActual = seccionNueva;
	  	 }
	  	 //Agrego la fila a la sección
	  	 seccionActual.add(fila);

		//Enguille seccion para Android
		tbl_data.push(fila);
	  }else{
	  	 //Si no esta vacio hay secciones y debo agregar la sección a los datos de la tabla

	  	 var seccionActual = null;
	  	 var totalSecciones = tbl_sections.length;
		 var seccionExistente = Ti.UI.createTableViewSection({});
		 //Obtengo la seccion
		 for(var r = 0; r<totalSecciones; r++){
		 	seccionExistente = tbl_sections[r];
		 	if(seccionExistente.headerTitle === row.seccion){
		  		seccionActual = seccionExistente;
		  	}
		  }

	  	 if(seccionActual === null){
	  	 	//Si no encuentra la sección la creo
	  	 	//creo la seccion
		  	var seccionNueva = Ti.UI.createTableViewSection({
				headerTitle: row.seccion
		  	});
		  	//Agrego la seccion nueva
		  	tbl_sections.push(seccionNueva);
		  	//La pongo en la variable actual para agregarle la fila
		  	seccionActual = seccionNueva;
	  	 }
	  	 //Agrego la fila a la sección
	  	 seccionActual.add(fila);

	  }
	 // tbl_data.push(tbl_sections);
	  dataBD.next();
	}

	dataBD.close();

	var seccionVacia = Ti.UI.createTableViewSection({});
	seccionVacia = tbl_sections[0];
	if(tbl_sections.length === 1 && seccionVacia.headerTitle === ""){
		return tbl_data
	}else{
		return tbl_sections;
	}
}
<|endoftext|>


<commit_before>"use strict";

var sand = require('../../');
var path = require('path');
var child = require('child_process');

process.env.SAND_APP_PATH = path.resolve(__dirname + '/../');

describe('Events', function() {
  "use strict";
  it ('should emit start event', function(done) {
    child.fork('test/sand/helpers/testStartEvent')
      .on('exit', function(code) {
        code.should.be.eql(2);
        done();
      });
  });

  it ('should emit shutdown event', function(done) {
    child.fork('test/sand/helpers/testShutdownEvent')
      .on('exit', function(code) {
        code.should.be.eql(3);
        done();
      });
  });
});

describe.only('Application', function() {
  "use strict";
  it('should kill init after bad module', function(done) {
    child.fork('test/sand/helpers/testInitTimeout')
      .on('exit', function(code) {
        code.should.be.eql(1);
        done();
      });
  });

  it('should kill shutdown after timeout', function(done) {
    child.fork('test/sand/helpers/testShutdownTimeout')
      .on('exit', function(code) {
        code.should.be.eql(1);
        done();
      });
  });

  it ('should listen to shutdown event', function(done) {
    let c = child.fork('test/sand/helpers/testSignalEvents')
      .on('exit', function(code) {
        code.should.be.eql(4);
        done();
      });

    c.send('shutdown');
  });

  let signals = ['SIGTERM', 'SIGINT'];

  for (let signal of signals) {
    it(`should listen to ${signal} event`, function (done) {
      let c = child.fork('test/sand/helpers/testSignalEvents')
        .on('exit', function (code, signal) {
          code.should.be.eql(4);
          done();
        });

      c.on('message', function (data) {
        if (data == 'sand started') {
          // Make sure sand started and bound to event
          setTimeout(function () {
            c.kill(signal);
          }, 200);
        }
      });
    });
  }

  for (let signal of signals) {
    it(`should listen to ${signal} events from node-pm`, function (done) {
      let c = child.spawn(path.normalize(__dirname + '/../../node_modules/node-pm/bin/node-pm'), [path.normalize(__dirname + '/helpers/testSignalEvents.js'), '--', '--log'])
        .on('exit', function (code, signal) {
          code.should.be.eql(0);
          done();
        });

      c.stdout.once('data', function (data) {
        if (data.toString().trim() == 'sand started') {
          // Make sure sand started and bound to event
          setTimeout(function () {
            c.kill(signal);
          }, 200);
        }
      });
    });
  }

});

describe('Config', function() {
  "use strict";
  it ('should set defaults', function() {
    var app = new sand();
    app.env.should.be.equal('test');
    app.config.initTimeout.should.be.a.Number;
  });

  it ('should use passed in config', function() {
    var app = new sand({
      env: 'mine'
    });

    app.config.env.should.be.equal('mine');
  });

  it('should load from file', function() {
    var app = new sand({
      configPath: path.resolve(__dirname + '/helpers/config.js')
    });

    app.config.env.should.be.equal('mine')
  });

  it('should load log level correctly', function() {
    var app = new sand({
      configPath: path.resolve(__dirname + '/helpers/config.js')
    });

    app.config.log.should.be.eql('unknown');
  });

  it('should load config from environment variable', function () {
    process.env.SAND_CONFIG_PATH = path.resolve(__dirname + '/helpers/config.js');

    var app = new sand();

    delete process.env.SAND_CONFIG_PATH;

    app.config.env.should.be.equal('mine');
  });
});

describe('app.inspect()', function(){
  it('should work', function(){
    var app = new sand();
    var util = require('util');
    util.inspect(app);
  });
});

describe('Context', () => {
  let app = new sand({
    configPath: path.resolve(__dirname + '/helpers/config.js')
  });

  it ('should run in separate context', (done) => {
    app.ctx.test = 1;
    app.ctx.test.should.be.eql(1);

    app.runInContext(() => {
      global.sand.ctx.test = 2;
      global.sand.ctx.test.should.be.eql(2);
      done();
    });

    app.ctx.test.should.be.eql(1);
  });

  it ('should enter and exit new context with autoEnter', () => {
    app.ctx.test = 1;
    app.ctx.test.should.be.eql(1);

    let ctx = app.newContext();
    global.sand.ctx.test = 2;
    global.sand.ctx.test.should.be.eql(2);
    ctx.exit();

    app.ctx.test.should.be.eql(1);
  });

  it ('should enter and exit new context manually', () => {
    app.ctx.test = 1;
    app.ctx.test.should.be.eql(1);

    let ctx = app.newContext(false);
    ctx.enter();
    global.sand.ctx.test = 2;
    global.sand.ctx.test.should.be.eql(2);
    ctx.exit();

    app.ctx.test.should.be.eql(1);
  });

  it ('should enter and exit new Custom context', () => {
    app.ctx.test = 1;
    app.ctx.test.should.be.eql(1);

    let ctx = app.newContext(CustomContext);
    global.sand.ctx.should.be.instanceOf(CustomContext);
    global.sand.ctx.test = 2;
    global.sand.ctx.test.should.be.eql(2);
    ctx.exit();

    app.ctx.test.should.be.eql(1);
  });

  it ('should run in separate context', (done) => {
    app.ctx.test = 1;
    app.ctx.test.should.be.eql(1);

    app.runInContext(CustomContext, (close) => {
      global.sand.ctx.should.be.instanceOf(CustomContext);
      global.sand.ctx.test = 2;
      global.sand.ctx.test.should.be.eql(2);
      setTimeout(() => { close(); done()}, 300);
    });

    app.ctx.test.should.be.eql(1);
  });

  it ('should run in separate context with generator', (done) => {
    global.sand.ctx.test = 1;
    global.sand.ctx.test.should.be.eql(1);

    global.sand.runInContext(function *() {
      global.sand.ctx.test = 2;
      yield new Promise((resolve) => {
        process.nextTick(() => {
          setTimeout(() => {
            global.sand.ctx.test.should.be.eql(2);
            resolve();
            done();
          }, 200);
        });
      });
    });

    global.sand.ctx.test.should.be.eql(1);
  });

  describe('Events', () => {
    it ('should emit exit event', (done) => {
      let ctx = app.newContext(false);
      ctx.on('exit', done);
      ctx.enter();
      ctx.exit();
    });

    it ('should emit enter event', (done) => {
      let ctx = app.newContext(false);
      let c = 0;
      ctx.on('exit', () => { c.should.be.eql(1); done()});
      ctx.on('enter', () => {c++});
      ctx.enter();
      ctx.exit();
    });
  });

});

class CustomContext extends require('../../lib/Context') {

}<commit_msg>remove '.only' from tests<commit_after>"use strict";

var sand = require('../../');
var path = require('path');
var child = require('child_process');

process.env.SAND_APP_PATH = path.resolve(__dirname + '/../');

describe('Events', function() {
  "use strict";
  it ('should emit start event', function(done) {
    child.fork('test/sand/helpers/testStartEvent')
      .on('exit', function(code) {
        code.should.be.eql(2);
        done();
      });
  });

  it ('should emit shutdown event', function(done) {
    child.fork('test/sand/helpers/testShutdownEvent')
      .on('exit', function(code) {
        code.should.be.eql(3);
        done();
      });
  });
});

describe('Application', function() {
  "use strict";
  it('should kill init after bad module', function(done) {
    child.fork('test/sand/helpers/testInitTimeout')
      .on('exit', function(code) {
        code.should.be.eql(1);
        done();
      });
  });

  it('should kill shutdown after timeout', function(done) {
    child.fork('test/sand/helpers/testShutdownTimeout')
      .on('exit', function(code) {
        code.should.be.eql(1);
        done();
      });
  });

  it ('should listen to shutdown event', function(done) {
    let c = child.fork('test/sand/helpers/testSignalEvents')
      .on('exit', function(code) {
        code.should.be.eql(4);
        done();
      });

    c.send('shutdown');
  });

  let signals = ['SIGTERM', 'SIGINT'];

  for (let signal of signals) {
    it(`should listen to ${signal} event`, function (done) {
      let c = child.fork('test/sand/helpers/testSignalEvents')
        .on('exit', function (code, signal) {
          code.should.be.eql(4);
          done();
        });

      c.on('message', function (data) {
        if (data == 'sand started') {
          // Make sure sand started and bound to event
          setTimeout(function () {
            c.kill(signal);
          }, 200);
        }
      });
    });
  }

  for (let signal of signals) {
    it(`should listen to ${signal} events from node-pm`, function (done) {
      let c = child.spawn(path.normalize(__dirname + '/../../node_modules/node-pm/bin/node-pm'), [path.normalize(__dirname + '/helpers/testSignalEvents.js'), '--', '--log'])
        .on('exit', function (code, signal) {
          code.should.be.eql(0);
          done();
        });

      c.stdout.once('data', function (data) {
        if (data.toString().trim() == 'sand started') {
          // Make sure sand started and bound to event
          setTimeout(function () {
            c.kill(signal);
          }, 200);
        }
      });
    });
  }

});

describe('Config', function() {
  "use strict";
  it ('should set defaults', function() {
    var app = new sand();
    app.env.should.be.equal('test');
    app.config.initTimeout.should.be.a.Number;
  });

  it ('should use passed in config', function() {
    var app = new sand({
      env: 'mine'
    });

    app.config.env.should.be.equal('mine');
  });

  it('should load from file', function() {
    var app = new sand({
      configPath: path.resolve(__dirname + '/helpers/config.js')
    });

    app.config.env.should.be.equal('mine')
  });

  it('should load log level correctly', function() {
    var app = new sand({
      configPath: path.resolve(__dirname + '/helpers/config.js')
    });

    app.config.log.should.be.eql('unknown');
  });

  it('should load config from environment variable', function () {
    process.env.SAND_CONFIG_PATH = path.resolve(__dirname + '/helpers/config.js');

    var app = new sand();

    delete process.env.SAND_CONFIG_PATH;

    app.config.env.should.be.equal('mine');
  });
});

describe('app.inspect()', function(){
  it('should work', function(){
    var app = new sand();
    var util = require('util');
    util.inspect(app);
  });
});

describe('Context', () => {
  let app = new sand({
    configPath: path.resolve(__dirname + '/helpers/config.js')
  });

  it ('should run in separate context', (done) => {
    app.ctx.test = 1;
    app.ctx.test.should.be.eql(1);

    app.runInContext(() => {
      global.sand.ctx.test = 2;
      global.sand.ctx.test.should.be.eql(2);
      done();
    });

    app.ctx.test.should.be.eql(1);
  });

  it ('should enter and exit new context with autoEnter', () => {
    app.ctx.test = 1;
    app.ctx.test.should.be.eql(1);

    let ctx = app.newContext();
    global.sand.ctx.test = 2;
    global.sand.ctx.test.should.be.eql(2);
    ctx.exit();

    app.ctx.test.should.be.eql(1);
  });

  it ('should enter and exit new context manually', () => {
    app.ctx.test = 1;
    app.ctx.test.should.be.eql(1);

    let ctx = app.newContext(false);
    ctx.enter();
    global.sand.ctx.test = 2;
    global.sand.ctx.test.should.be.eql(2);
    ctx.exit();

    app.ctx.test.should.be.eql(1);
  });

  it ('should enter and exit new Custom context', () => {
    app.ctx.test = 1;
    app.ctx.test.should.be.eql(1);

    let ctx = app.newContext(CustomContext);
    global.sand.ctx.should.be.instanceOf(CustomContext);
    global.sand.ctx.test = 2;
    global.sand.ctx.test.should.be.eql(2);
    ctx.exit();

    app.ctx.test.should.be.eql(1);
  });

  it ('should run in separate context', (done) => {
    app.ctx.test = 1;
    app.ctx.test.should.be.eql(1);

    app.runInContext(CustomContext, (close) => {
      global.sand.ctx.should.be.instanceOf(CustomContext);
      global.sand.ctx.test = 2;
      global.sand.ctx.test.should.be.eql(2);
      setTimeout(() => { close(); done()}, 300);
    });

    app.ctx.test.should.be.eql(1);
  });

  it ('should run in separate context with generator', (done) => {
    global.sand.ctx.test = 1;
    global.sand.ctx.test.should.be.eql(1);

    global.sand.runInContext(function *() {
      global.sand.ctx.test = 2;
      yield new Promise((resolve) => {
        process.nextTick(() => {
          setTimeout(() => {
            global.sand.ctx.test.should.be.eql(2);
            resolve();
            done();
          }, 200);
        });
      });
    });

    global.sand.ctx.test.should.be.eql(1);
  });

  describe('Events', () => {
    it ('should emit exit event', (done) => {
      let ctx = app.newContext(false);
      ctx.on('exit', done);
      ctx.enter();
      ctx.exit();
    });

    it ('should emit enter event', (done) => {
      let ctx = app.newContext(false);
      let c = 0;
      ctx.on('exit', () => { c.should.be.eql(1); done()});
      ctx.on('enter', () => {c++});
      ctx.enter();
      ctx.exit();
    });
  });

});

class CustomContext extends require('../../lib/Context') {

}<|endoftext|>


<commit_before>// Author: Bricklen
// Trufflehunter project home: https://github.com/bricklen/trufflehunter

var http = require('http'),
    util = require('util'),
    formidable = require('../node_modules/formidable'),
    server,
    serverport = 80, //22089,
    fs = require('fs');
    path = require("path"),
    extensions = {
        ".html": "text/html",
        ".css": "text/css",
        ".js": "application/javascript",
        ".png": "image/png",
        ".gif": "image/gif",
        ".jpg": "image/jpeg",
        ".log": "text/plain",
        ".gz": "application/x-gzip"
    };
var rootpath = __dirname,
    uploadDir = rootpath + '../public/uploads',
    config_file, fname, dir, ext;

// TODO: Add security measures to prevent users from reading other directories.

server = http.createServer(function(req, res) {

    var fname = path.basename(req.url) || "index.html",
        dir = path.dirname(req.url).substring(1),
        ext = path.extname(fname);

    if (req.url == '/') {
        res.writeHead(200, {'content-type': 'text/html'});
        fs.readFile(rootpath + '../public/' + fname,function(error,data) {
            res.end(data);
        });

    } else if (req.url == '/upload') {
        var form = new formidable.IncomingForm(),
            files = [],
            fields = [],
            stream, filename, filename_no_ext, log_line_prefix, email, top_num_queries, send_email_link,
            randomnumber = Math.floor(Math.random()*100000);

        form.uploadDir = uploadDir;

        form
            .on('field', function(field, value) {
                // All input fields of the form MUST be processed here if they
                // will be used in the .config file, so if you add any to the
                // form, then add them here too.
                // Note: add the form elements "on ('end..." section too.

                fields.push([field, value]);
                if ( field == 'log_line_prefix' ) {
                    log_line_prefix = value;
                }
                if ( field == 'email' ) {
                    email = value;
                }
                if ( field == 'top_num_queries' ) {
                    top_num_queries = value;
                }
                if ( field == 'send_email_link' ) {
                    send_email_link = value;
                }
            })

            /* This is where the renaming happens */
            .on ('fileBegin', function(name, file){
                //if ( email == 'undefined' || email == '' || log_line_prefix == 'undefined' || log_line_prefix == '' ) {
                //    console.log('Some inputs are missing. Exiting...');
                //    // TODO: This is not stopping the upload if for example just the email is supplied but the log_line_prefix is not.
                //    // It should stop the upload and redirect to the main page, preferably with a message stating that there are missing values.
                //    // This should also be handled in the form itself, before we get this far.
                //    req.pause();
                //    // The redirect page should be the root, not some html page that I have hardcoded.
                //    res.writeHead(301, {'content-type': 'text/html', 'location' : req.url + '/../index.html'});
                //    res.end();
                //}

                //Rename the incoming file to the file's name
                filename = file.name;
                ext = path.extname(filename);
                filename = filename.replace(/\s+/g,"_");                    // Replace spaces with underscores
                filename = filename.substr(0, filename.lastIndexOf("."));   // Strip the extension
                filename_no_ext = filename + '_' + randomnumber;            // New filename, try make it unique
                filename = filename + '_' + randomnumber + ext;             // Put the extension back on
                file.path = form.uploadDir + '/' + filename;
                config_file = form.uploadDir + '/' + filename + '.config';  // Create the xxx.config filename
            })

            .on('file', function(field, file) {
                files.push([field, file]);
            })

            // Informational only, can be commented out
            .on('progress', function(bytesReceived, bytesExpected) {
                var percent = Math.ceil(bytesReceived / bytesExpected * 100) || 0;
                process.stdout.write('Uploading: %' + percent + '\r');
            })

            .on('end', function() {
                // Create the .config file.
                // This is done *after* the log file has been uploaded so that the
                // scheduled parse process only parses log files after the full log has
                // been uploaded AND the config has been created.
                // Do not move this step before the upload unless a mutex is added.
                stream = fs.createWriteStream(config_file);
                stream.once('open', function(fd) {

                // Ideally this would be a loop over the fields from the "field" section further up
                stream.write('log_line_prefix="' + log_line_prefix + '"' + "\n");
                stream.write('email="' + email + '"' + "\n");
                stream.write('logfile="' + filename + '"' + "\n");
                stream.write('top_num_queries="' + top_num_queries + '"' + "\n");
                stream.write('send_email_link="' + send_email_link + '"' + "\n");

                stream.end();
            });

            res.writeHead(200, {'content-type': 'text/html'});
            res.write('');
            res.write('<title>Redirect to generated HTML results</title>');
            res.write('');
            res.write('');
            res.write('');
            res.write('<link href="http://fonts.googleapis.com/css?family=Trykker|Bubbler+One" rel="stylesheet" type="text/css">');
            res.write('');
            res.write('');
            res.write('');
            res.write('

');
            res.write('When your generated HTML file is finished you will be redirected automatically.');
            res.write('');
            res.write('');
            res.end();
        });

        form.parse(req);

    } else if (ext === '.html') {
        // TODO: Tighten this up so other html files in other directories cannot be read
        res.writeHead(200, {'content-type': 'text/html'});
        fs.readFile(rootpath + '/' + req.url,function(error,data){
            res.end(data);
        });

    // TODO: Clean up the conditional statements for extensions, bundle them up
    //       and have them processed dynamically, except where there are custom
    //       scripts that need handling.
    } else if (ext === '.js') {
// This stuff is unnecessary.
//        fs.readFile(__dirname + '/public/js/jquery-1.11.0.js', function (err, data) {
//            if (err) console.log(err);
//            res.writeHead(200, {'Content-Type': 'text/javascript'});
//            res.write(data);
//            res.end(data);
//        });

    } else if (ext === '.css') {
        fs.readFile(__dirname + '/public/css/style.css', function (err, data) {
            if (err) console.log(err);
            res.writeHead(200, {'Content-Type': 'text/css'});
            res.write(data);
            res.end(data);
        });

    } else if (ext === '.gif') {
        fs.readFile(__dirname + '/public/img/' + fname, function (err, data) {
            if (err) console.log(err);
            res.writeHead(200, {'Content-Type': 'image/gif'});
            res.write(data);
            res.end(data);
        });

    } else {
        res.writeHead(404, {'content-type': 'text/plain'});
        res.end('404');
    }
});
server.listen(serverport);

console.log('Listening on port:' + serverport );
<commit_msg>Fixed more paths to assets.<commit_after>// Author: Bricklen
// Trufflehunter project home: https://github.com/bricklen/trufflehunter

var http = require('http'),
    util = require('util'),
    formidable = require('../node_modules/formidable'),
    server,
    serverport = 80, //22089,
    fs = require('fs');
    path = require("path"),
    extensions = {
        ".html": "text/html",
        ".css": "text/css",
        ".js": "application/javascript",
        ".png": "image/png",
        ".gif": "image/gif",
        ".jpg": "image/jpeg",
        ".log": "text/plain",
        ".gz": "application/x-gzip"
    };
var rootpath = __dirname,
    uploadDir = rootpath + '/../public/uploads',
    config_file, fname, dir, ext;

// TODO: Add security measures to prevent users from reading other directories.

server = http.createServer(function(req, res) {

    var fname = path.basename(req.url) || "index.html",
        dir = path.dirname(req.url).substring(1),
        ext = path.extname(fname);

    if (req.url == '/') {
        res.writeHead(200, {'content-type': 'text/html'});
        fs.readFile(rootpath + '/../public/' + fname,function(error,data) {
            res.end(data);
        });

    } else if (req.url == '/upload') {
        var form = new formidable.IncomingForm(),
            files = [],
            fields = [],
            stream, filename, filename_no_ext, log_line_prefix, email, top_num_queries, send_email_link,
            randomnumber = Math.floor(Math.random()*100000);

        form.uploadDir = uploadDir;

        form
            .on('field', function(field, value) {
                // All input fields of the form MUST be processed here if they
                // will be used in the .config file, so if you add any to the
                // form, then add them here too.
                // Note: add the form elements "on ('end..." section too.

                fields.push([field, value]);
                if ( field == 'log_line_prefix' ) {
                    log_line_prefix = value;
                }
                if ( field == 'email' ) {
                    email = value;
                }
                if ( field == 'top_num_queries' ) {
                    top_num_queries = value;
                }
                if ( field == 'send_email_link' ) {
                    send_email_link = value;
                }
            })

            /* This is where the renaming happens */
            .on ('fileBegin', function(name, file){
                //if ( email == 'undefined' || email == '' || log_line_prefix == 'undefined' || log_line_prefix == '' ) {
                //    console.log('Some inputs are missing. Exiting...');
                //    // TODO: This is not stopping the upload if for example just the email is supplied but the log_line_prefix is not.
                //    // It should stop the upload and redirect to the main page, preferably with a message stating that there are missing values.
                //    // This should also be handled in the form itself, before we get this far.
                //    req.pause();
                //    // The redirect page should be the root, not some html page that I have hardcoded.
                //    res.writeHead(301, {'content-type': 'text/html', 'location' : req.url + '/../index.html'});
                //    res.end();
                //}

                //Rename the incoming file to the file's name
                filename = file.name;
                ext = path.extname(filename);
                filename = filename.replace(/\s+/g,"_");                    // Replace spaces with underscores
                filename = filename.substr(0, filename.lastIndexOf("."));   // Strip the extension
                filename_no_ext = filename + '_' + randomnumber;            // New filename, try make it unique
                filename = filename + '_' + randomnumber + ext;             // Put the extension back on
                file.path = form.uploadDir + '/' + filename;
                config_file = form.uploadDir + '/' + filename + '.config';  // Create the xxx.config filename
            })

            .on('file', function(field, file) {
                files.push([field, file]);
            })

            // Informational only, can be commented out
            .on('progress', function(bytesReceived, bytesExpected) {
                var percent = Math.ceil(bytesReceived / bytesExpected * 100) || 0;
                process.stdout.write('Uploading: %' + percent + '\r');
            })

            .on('end', function() {
                // Create the .config file.
                // This is done *after* the log file has been uploaded so that the
                // scheduled parse process only parses log files after the full log has
                // been uploaded AND the config has been created.
                // Do not move this step before the upload unless a mutex is added.
                stream = fs.createWriteStream(config_file);
                stream.once('open', function(fd) {

                // Ideally this would be a loop over the fields from the "field" section further up
                stream.write('log_line_prefix="' + log_line_prefix + '"' + "\n");
                stream.write('email="' + email + '"' + "\n");
                stream.write('logfile="' + filename + '"' + "\n");
                stream.write('top_num_queries="' + top_num_queries + '"' + "\n");
                stream.write('send_email_link="' + send_email_link + '"' + "\n");

                stream.end();
            });

            res.writeHead(200, {'content-type': 'text/html'});
            res.write('');
            res.write('<title>Redirect to generated HTML results</title>');
            res.write('');
            res.write('');
            res.write('');
            res.write('<link href="http://fonts.googleapis.com/css?family=Trykker|Bubbler+One" rel="stylesheet" type="text/css">');
            res.write('');
            res.write('');
            res.write('');
            res.write('

');
            res.write('When your generated HTML file is finished you will be redirected automatically.');
            res.write('');
            res.write('');
            res.end();
        });

        form.parse(req);

    } else if (ext === '.html') {
        // TODO: Tighten this up so other html files in other directories cannot be read
        res.writeHead(200, {'content-type': 'text/html'});
        fs.readFile(rootpath + '/../public/' + req.url,function(error,data){
            res.end(data);
        });

    // TODO: Clean up the conditional statements for extensions, bundle them up
    //       and have them processed dynamically, except where there are custom
    //       scripts that need handling.
    } else if (ext === '.js') {
// This stuff is unnecessary.
//        fs.readFile(__dirname + '/public/js/jquery-1.11.0.js', function (err, data) {
//            if (err) console.log(err);
//            res.writeHead(200, {'Content-Type': 'text/javascript'});
//            res.write(data);
//            res.end(data);
//        });

    } else if (ext === '.css') {
        fs.readFile(rootpath + '/../public/css/style.css', function (err, data) {
            if (err) console.log(err);
            res.writeHead(200, {'Content-Type': 'text/css'});
            res.write(data);
            res.end(data);
        });

    } else if (ext === '.gif') {
        fs.readFile(rootpath + '/../public/img/' + fname, function (err, data) {
            if (err) console.log(err);
            res.writeHead(200, {'Content-Type': 'image/gif'});
            res.write(data);
            res.end(data);
        });

    } else {
        res.writeHead(404, {'content-type': 'text/plain'});
        res.end('404');
    }
});
server.listen(serverport);

console.log('Listening on port:' + serverport );
<|endoftext|>


<commit_before>/*
 * Geometry editor widget that appears at the top right corner of the
 * map during an item edit in the Neatline editor.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by
 * applicable law or agreed to in writing, software distributed under the
 * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
 * OF ANY KIND, either express or implied. See the License for the specific
 * language governing permissions and limitations under the License.
 *
 * @package     omeka
 * @subpackage  neatline
 * @author      Scholars' Lab <>
 * @author      Bethany Nowviskie <bethany@virginia.edu>
 * @author      Adam Soroka <ajs6f@virginia.edu>
 * @author      David McClure <david.mcclure@virginia.edu>
 * @copyright   2011 The Board and Visitors of the University of Virginia
 * @license     http://www.apache.org/licenses/LICENSE-2.0.html Apache 2 License
 */

(function($, undefined) {

    $.widget('neatline.editgeometry', {

        options: {

            // Markup hooks.
            markup: {
                geo_edit_class: 'geo-edit'
            },

            // Animation constants.
            animation: {
                fade_duration: 500
            }

        },

        _create: function() {

            var self = this;

            // Build the buttons, insert, and gloss.
            this.scaleButton =
                $('<button id="scale-button" class="btn edit-geometry-small geo-edit">Scale</button>');

            this.rotateButton =
                $('<button id="rotate-button" class="btn edit-geometry-small geo-edit">Rotate</button>');

            this.dragButton =
                $('<button id="drag-button" class="btn edit-geometry-small geo-edit">Drag</button>');

            this.deleteButton =
                $('<button id="delete-button" class="btn danger edit-geometry-small geo-edit">Delete</button>');

            // Insert the buttons.
            this.element.append(this.dragButton);
            this.element.append(this.rotateButton);
            this.element.append(this.scaleButton);
            this.element.append(this.deleteButton);

            // Store starting status data trackers.
            this.scaleButton.data('activated', false);
            this.rotateButton.data('activated', false);
            this.dragButton.data('activated', false);

            // Gloss the drag button.
            this.dragButton.bind({

                'mousedown': function() {

                    // If not activated, activate.
                    if (!self.dragButton.data('activated')) {

                        // Do the color change.
                        self.dragButton.addClass('primary');

                        // Change the trackers.
                        self.dragButton.data('activated', true);

                    }

                    // If activated, deactivate.
                    else {

                        // Do the color change.
                        self.dragButton.removeClass('primary');

                        // Change the tracker.
                        self.dragButton.data('activated', false);

                    }

                    // Fire out the update event.
                    self._trigger('update', {}, {
                        'drag': self.dragButton.data('activated'),
                        'rotate': self.rotateButton.data('activated'),
                        'scale': self.scaleButton.data('activated')
                    });

                }

            });

            // Gloss the scale button.
            this.scaleButton.bind({

                'mousedown': function() {

                    // If not activated, activate.
                    if (!self.scaleButton.data('activated')) {

                        // Do the color change.
                        self.scaleButton.addClass('primary');

                        // Change the trackers.
                        self.scaleButton.data('activated', true);

                    }

                    // If activated, deactivate.
                    else {

                        // Do the color change.
                        self.scaleButton.removeClass('primary');

                        // Change the tracker.
                        self.scaleButton.data('activated', false);

                    }

                    // Fire out the update event.
                    self._trigger('update', {}, {
                        'drag': self.dragButton.data('activated'),
                        'rotate': self.rotateButton.data('activated'),
                        'scale': self.scaleButton.data('activated')
                    });

                }

            });

            // Gloss the rotate button.
            this.rotateButton.bind({

                'mousedown': function() {

                    // If not activated, activate.
                    if (!self.rotateButton.data('activated')) {

                        // Do the color change.
                        self.rotateButton.addClass('primary');

                        // Change the tracker.
                        self.rotateButton.data('activated', true);

                    }

                    // If activated, deactivate.
                    else {

                        // Do the color change.
                        self.rotateButton.removeClass('primary');

                        // Change the tracker.
                        self.rotateButton.data('activated', false);

                    }

                    // Fire out the update event.
                    self._trigger('update', {}, {
                        'drag': self.dragButton.data('activated'),
                        'rotate': self.rotateButton.data('activated'),
                        'scale': self.scaleButton.data('activated')
                    });

                }

            });

            // Gloss the delete button.
            this.deleteButton.bind({

                // Fire out the delete event.
                'mousedown': function() {
                    self._trigger('delete');
                }

            });

        },

        showButtons: function() {

            // Display:block the buttons.
            $('.' + this.options.markup.geo_edit_class).css({
                'display': 'block !important',
                'opacity': 0
            }).stop().animate({ 'opacity': 1}, this.options.animation.fade_duration);

            // By default, deactivate all buttons.
            this.deactivateAllButtons();

        },

        hideButtons: function() {

            // Get the buttons.
            var buttons = $('.' + this.options.markup.geo_edit_class);

            // Fade down.
            buttons.stop().animate({
                'opacity': 0
            }, this.options.markup.fade_duration, function() {
                buttons.css('display', 'none !important');
            });

        },

        deactivateAllButtons: function() {

            // Drag.
            this.dragButton.removeClass('primary');
            this.dragButton.data('activated', false);

            // Scale.
            this.scaleButton.removeClass('primary');
            this.scaleButton.data('activated', false);

            // Rotate.
            this.rotateButton.removeClass('primary');
            this.rotateButton.data('activated', false);

        }

    });

})( jQuery );

<commit_msg>More superfluous blank lines removed.<commit_after>/*
 * Geometry editor widget that appears at the top right corner of the
 * map during an item edit in the Neatline editor.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by
 * applicable law or agreed to in writing, software distributed under the
 * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
 * OF ANY KIND, either express or implied. See the License for the specific
 * language governing permissions and limitations under the License.
 *
 * @package     omeka
 * @subpackage  neatline
 * @author      Scholars' Lab <>
 * @author      Bethany Nowviskie <bethany@virginia.edu>
 * @author      Adam Soroka <ajs6f@virginia.edu>
 * @author      David McClure <david.mcclure@virginia.edu>
 * @copyright   2011 The Board and Visitors of the University of Virginia
 * @license     http://www.apache.org/licenses/LICENSE-2.0.html Apache 2 License
 */

(function($, undefined) {
    $.widget('neatline.editgeometry', {
        options: {
            // Markup hooks.
            markup: {
                geo_edit_class: 'geo-edit'
            },

            // Animation constants.
            animation: {
                fade_duration: 500
            }
        },

        _create: function() {
            var self = this;

            // Build the buttons, insert, and gloss.
            this.scaleButton =
                $('<button id="scale-button" class="btn edit-geometry-small geo-edit">Scale</button>');

            this.rotateButton =
                $('<button id="rotate-button" class="btn edit-geometry-small geo-edit">Rotate</button>');

            this.dragButton =
                $('<button id="drag-button" class="btn edit-geometry-small geo-edit">Drag</button>');

            this.deleteButton =
                $('<button id="delete-button" class="btn danger edit-geometry-small geo-edit">Delete</button>');

            // Insert the buttons.
            this.element.append(this.dragButton);
            this.element.append(this.rotateButton);
            this.element.append(this.scaleButton);
            this.element.append(this.deleteButton);

            // Store starting status data trackers.
            this.scaleButton.data('activated', false);
            this.rotateButton.data('activated', false);
            this.dragButton.data('activated', false);

            // Gloss the drag button.
            this.dragButton.bind({
                'mousedown': function() {
                    // If not activated, activate.
                    if (!self.dragButton.data('activated')) {
                        // Do the color change.
                        self.dragButton.addClass('primary');

                        // Change the trackers.
                        self.dragButton.data('activated', true);
                    }
                    // If activated, deactivate.
                    else {
                        // Do the color change.
                        self.dragButton.removeClass('primary');

                        // Change the tracker.
                        self.dragButton.data('activated', false);
                    }

                    // Fire out the update event.
                    self._trigger('update', {}, {
                        'drag': self.dragButton.data('activated'),
                        'rotate': self.rotateButton.data('activated'),
                        'scale': self.scaleButton.data('activated')
                    });
                }

            });

            // Gloss the scale button.
            this.scaleButton.bind({
                'mousedown': function() {
                    // If not activated, activate.
                    if (!self.scaleButton.data('activated')) {
                        // Do the color change.
                        self.scaleButton.addClass('primary');

                        // Change the trackers.
                        self.scaleButton.data('activated', true);
                    }
                    // If activated, deactivate.
                    else {
                        // Do the color change.
                        self.scaleButton.removeClass('primary');

                        // Change the tracker.
                        self.scaleButton.data('activated', false);
                    }

                    // Fire out the update event.
                    self._trigger('update', {}, {
                        'drag': self.dragButton.data('activated'),
                        'rotate': self.rotateButton.data('activated'),
                        'scale': self.scaleButton.data('activated')
                    });
                }
            });

            // Gloss the rotate button.
            this.rotateButton.bind({
                'mousedown': function() {
                    // If not activated, activate.
                    if (!self.rotateButton.data('activated')) {
                        // Do the color change.
                        self.rotateButton.addClass('primary');

                        // Change the tracker.
                        self.rotateButton.data('activated', true);
                    }
                    // If activated, deactivate.
                    else {
                        // Do the color change.
                        self.rotateButton.removeClass('primary');

                        // Change the tracker.
                        self.rotateButton.data('activated', false);
                    }

                    // Fire out the update event.
                    self._trigger('update', {}, {
                        'drag': self.dragButton.data('activated'),
                        'rotate': self.rotateButton.data('activated'),
                        'scale': self.scaleButton.data('activated')
                    });
                }
            });

            // Gloss the delete button.
            this.deleteButton.bind({
                // Fire out the delete event.
                'mousedown': function() {
                    self._trigger('delete');
                }
            });
        },

        showButtons: function() {
            // Display:block the buttons.
            $('.' + this.options.markup.geo_edit_class).css({
                'display': 'block !important',
                'opacity': 0
            }).stop().animate({ 'opacity': 1}, this.options.animation.fade_duration);

            // By default, deactivate all buttons.
            this.deactivateAllButtons();
        },

        hideButtons: function() {
            // Get the buttons.
            var buttons = $('.' + this.options.markup.geo_edit_class);

            // Fade down.
            buttons.stop().animate({
                'opacity': 0
            }, this.options.markup.fade_duration, function() {
                buttons.css('display', 'none !important');
            });
        },

        deactivateAllButtons: function() {
            // Drag.
            this.dragButton.removeClass('primary');
            this.dragButton.data('activated', false);

            // Scale.
            this.scaleButton.removeClass('primary');
            this.scaleButton.data('activated', false);

            // Rotate.
            this.rotateButton.removeClass('primary');
            this.rotateButton.data('activated', false);
        }
    });
})( jQuery );

<|endoftext|>


<commit_before>module.exports = function(app, passport,db){
	//homepage
	app.get('/assassin/',function(req,res){
		res.render('index.ejs');
	});

	//login
	app.get('/assassin/login',function(req,res){
		res.render('login.ejs',{message:req.flash('loginMessage')});
	});

	//process the login info
	app.post('/assassin/login',passport.authenticate('local-login', {
		successRedirect : '/assassin/dash',
		failureRedirect : '/assassin/login',
		failureFlash : true
	}));

	//signup
	app.get('/assassin/signup',function(req,res){
		res.render('signup.ejs',{message:req.flash('signupMessage')});
	});

	//process the signup info
	app.post('/assassin/signup',passport.authenticate('local-signup',{
		successRedirect : '/assassin/dash',
		failureRedirect : '/assassin/signup',
		failureFlash : true
	}));

	//dashboard
	app.get('/assassin/dash',isLoggedIn,function(req,res){
		//get target list
		db.query("SELECT name,id FROM users JOIN targets ON users.id=targets.targetid where targets.gameid=? and targets.hunterid=? and users.status='ALIVE';",
			[req.user.gameid, req.user.id],function(err,rows){
				if(err)throw err;
				//console.log(rows);
				res.render('dash.ejs',{user:req.user, targets:rows, postKillMessage:req.flash('postKillMessage')});
			});
	});

	app.post('/assassin/dash',isLoggedIn,function(req,res){
		//check if the passphrase matches
		//if it does, put in a kill record
		//else, return a failure message
		db.query("SELECT phrase FROM users where id=?;",[req.body.targetID],
			function(err,rows){
				if(req.body.passphrase==rows[0].phrase){
					req.flash("postKillMessage","Success!");
					//record the kill
					db.query("insert into kills values(?,?,?,NULL);",
						[req.user.id,req.body.targetID,req.user.gameid],
						function(err,rows){
							if(err)throw err;
						});
					//update player status
					db.query("update users set status='DEAD',gameid=0 where id=?;",
						[req.body.targetID],function(err,rows){
								if(err)throw err;
						});
					//transfer targets
					db.query("update targets set hunterid=? where hunterid=?;",
						[req.user.id,req.body.targetID],
						function(err,rows){
							if(err)throw err;
						});
				}else{
					req.flash("postKillMessage","Failure");
				}
				res.redirect("/assassin/dash");
			});
	});

	app.get('/assassin/join',isLoggedIn,function(req,res){
		res.render('join.ejs',{message:req.flash('joinMessage')});
	});

	//need an isLoggedIn here?
	app.post('/assassin/join',function(req,res){
		db.query("select * from games where id=? and status='OPEN';",
			[req.body.gameID],function(err,rows){
				if(err) throw err;
				if(rows.length==0){
					req.flash('joinMessage',"Unable to join.");
					res.redirect("/assassin/join");
				}else{
					db.query("update users set gameid=?,status='ALIVE' where id=?;",
						[req.body.gameID,req.user.id],
						function(err, rows){
							if(err)throw err;

							//update req.user info -- possible not necessary?
							var user = req.user;
							user.gameid=req.body.gameID;
							user.status="ALIVE";
							req.logIn(user,function(err){
								if(err)
									console.log(err);
							});
					});
					res.redirect('/assassin/dash');
				}
			});

	});

	app.get('/assassin/gameMaker',isLoggedIn,function(req,res){
		res.render('gameManager.ejs',{gameid:req.user.gameid});
	});

	app.post('/assassin/gameMaker',isLoggedIn,function(req,res){
		//id int, status VARCHAR(10),startdate date, enddate date, starttime time, endtime time, endcondition varchar(20), creatorid int
		var id = Math.floor(Math.random()*10000);
		var body = req.body;
		console.log(body);
		db.query("INSERT into games values(?,'OPEN',?,?,?,?,?,?,?);",
			[id,body.startdate,body.enddate,body.starttime+":00",body.endtime+":00",body.endnumber,body.endstate,req.user.id],
			function(err,rows){
				if(err)
					throw err;
			});
		db.query("UPDATE users set gameid=? where id=?",
			[id,req.user.id],function(err,rows){
				if(err)
					throw err;
			});
		res.redirect('/assassin/dash');
	});

	app.get('/assassin/instructions',function(req,res){
		res.render('instructions.ejs');
	});

	app.get('/assassin/logout',function(req,res){
		req.logout();
		res.redirect('/assassin/');
    });

    // route middleware to make sure a user is logged in
	function isLoggedIn(req, res, next) {
		// if user is authenticated in the session, carry on
		if (req.isAuthenticated())
			return next();
		// if they aren't redirect them to the home page
		res.redirect('/assassin/');
	}
};
<commit_msg>Status is set to ALIVE when creating a game<commit_after>module.exports = function(app, passport,db){
	//homepage
	app.get('/assassin/',function(req,res){
		res.render('index.ejs');
	});

	//login
	app.get('/assassin/login',function(req,res){
		res.render('login.ejs',{message:req.flash('loginMessage')});
	});

	//process the login info
	app.post('/assassin/login',passport.authenticate('local-login', {
		successRedirect : '/assassin/dash',
		failureRedirect : '/assassin/login',
		failureFlash : true
	}));

	//signup
	app.get('/assassin/signup',function(req,res){
		res.render('signup.ejs',{message:req.flash('signupMessage')});
	});

	//process the signup info
	app.post('/assassin/signup',passport.authenticate('local-signup',{
		successRedirect : '/assassin/dash',
		failureRedirect : '/assassin/signup',
		failureFlash : true
	}));

	//dashboard
	app.get('/assassin/dash',isLoggedIn,function(req,res){
		//get target list
		db.query("SELECT name,id FROM users JOIN targets ON users.id=targets.targetid where targets.gameid=? and targets.hunterid=? and users.status='ALIVE';",
			[req.user.gameid, req.user.id],function(err,rows){
				if(err)throw err;
				//console.log(rows);
				res.render('dash.ejs',{user:req.user, targets:rows, postKillMessage:req.flash('postKillMessage')});
			});
	});

	app.post('/assassin/dash',isLoggedIn,function(req,res){
		//check if the passphrase matches
		//if it does, put in a kill record
		//else, return a failure message
		db.query("SELECT phrase FROM users where id=?;",[req.body.targetID],
			function(err,rows){
				if(req.body.passphrase==rows[0].phrase){
					req.flash("postKillMessage","Success!");
					//record the kill
					db.query("insert into kills values(?,?,?,NULL);",
						[req.user.id,req.body.targetID,req.user.gameid],
						function(err,rows){
							if(err)throw err;
						});
					//update player status
					db.query("update users set status='DEAD',gameid=0 where id=?;",
						[req.body.targetID],function(err,rows){
								if(err)throw err;
						});
					//transfer targets
					db.query("update targets set hunterid=? where hunterid=?;",
						[req.user.id,req.body.targetID],
						function(err,rows){
							if(err)throw err;
						});
				}else{
					req.flash("postKillMessage","Failure");
				}
				res.redirect("/assassin/dash");
			});
	});

	app.get('/assassin/join',isLoggedIn,function(req,res){
		res.render('join.ejs',{message:req.flash('joinMessage')});
	});

	//need an isLoggedIn here?
	app.post('/assassin/join',function(req,res){
		db.query("select * from games where id=? and status='OPEN';",
			[req.body.gameID],function(err,rows){
				if(err) throw err;
				if(rows.length==0){
					req.flash('joinMessage',"Unable to join.");
					res.redirect("/assassin/join");
				}else{
					db.query("update users set gameid=?,status='ALIVE' where id=?;",
						[req.body.gameID,req.user.id],
						function(err, rows){
							if(err)throw err;

							//update req.user info -- possible not necessary?
							var user = req.user;
							user.gameid=req.body.gameID;
							user.status="ALIVE";
							req.logIn(user,function(err){
								if(err)
									console.log(err);
							});
					});
					res.redirect('/assassin/dash');
				}
			});

	});

	app.get('/assassin/gameMaker',isLoggedIn,function(req,res){
		res.render('gameManager.ejs',{gameid:req.user.gameid});
	});

	app.post('/assassin/gameMaker',isLoggedIn,function(req,res){
		//id int, status VARCHAR(10),startdate date, enddate date, starttime time, endtime time, endcondition varchar(20), creatorid int
		var id = Math.floor(Math.random()*10000);
		var body = req.body;
		console.log(body);
		db.query("INSERT into games values(?,'OPEN',?,?,?,?,?,?,?);",
			[id,body.startdate,body.enddate,body.starttime+":00",body.endtime+":00",body.endnumber,body.endstate,req.user.id],
			function(err,rows){
				if(err)
					throw err;
			});
		db.query("UPDATE users set gameid=?,status='ALIVE' where id=?;",
			[id,req.user.id],function(err,rows){
				if(err)
					throw err;
			});
		res.redirect('/assassin/dash');
	});

	app.get('/assassin/instructions',function(req,res){
		res.render('instructions.ejs');
	});

	app.get('/assassin/logout',function(req,res){
		req.logout();
		res.redirect('/assassin/');
    });

    // route middleware to make sure a user is logged in
	function isLoggedIn(req, res, next) {
		// if user is authenticated in the session, carry on
		if (req.isAuthenticated())
			return next();
		// if they aren't redirect them to the home page
		res.redirect('/assassin/');
	}
};
<|endoftext|>