<commit_before>onload=function()
{
	cAyuda=document.getElementById("mensajesAyuda");
	cNombre=document.getElementById("ayudaTitulo");
	cTex=document.getElementById("ayudaTexto");
	divTransparente=document.getElementById("transparencia");
	divMensaje=document.getElementById("transparenciaMensaje");
	form=document.getElementById("formulario");
	urlDestino="mail.php";
	claseNormal="input";
	claseError="inputError";
	ayuda=new Array();
	ayuda["Nombre Usuario"]="Ingresa tu nombre de usuario. De 4 a 50 caracteres. OBLIGATORIO";
	ayuda["Correo"]="Ingresa una direccin de correo electrnico vlido.";
	ayuda["Contrasea"]="Ingresa una contrasea de un mnimo de 8 caracteres.";
	ayuda["Repetir Contrasea"]="Ingresa de nuevo la contrasea";
	preCarga("imagen/ok.gif", "imagen/loading.gif", "imagen/error.gif");
}

function preCarga()
{

	imagenes=new Array();
	for(i=0; i<arguments.length; i++)
	{
		imagenes[i]=document.createElement("img");
		imagenes[i].src=arguments[i];
	}
}

function nuevoAjax()
{
	var xmlhttp=false;
	try
	{
		// No IE
		xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
	}
	catch(e)
	{
		try
		{
			// IE
			xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
		}
		catch(E) { xmlhttp=false; }
	}
	if (!xmlhttp && typeof XMLHttpRequest!="undefined") { xmlhttp=new XMLHttpRequest(); }
	return xmlhttp;
}

function limpiaForm()
{
	for(i=0; i<=3; i++)
	{
		form.elements[i].className=claseNormal;
	}

}

function campoError(campo)
{
	campo.className=claseError;
	error=1;
}

function ocultaMensaje()
{
	divTransparente.style.display="none";
}

function muestraMensaje(mensaje)
{
	divMensaje.innerHTML=mensaje;
	divTransparente.style.display="block";
}

function eliminaEspacios(cadena)
{
	// Funcion para eliminar espacios delante y detras de cada cadena
	while(cadena.charAt(cadena.length-1)==" ") cadena=cadena.substr(0, cadena.length-1);
	while(cadena.charAt(0)==" ") cadena=cadena.substr(1, cadena.length-1);
	return cadena;
}

function validaLongitud(valor, permiteVacio, minimo, maximo)
{
	var cantCar=valor.length;
	if(valor=="")
	{
		if(permiteVacio) return true;
		else return false;
	}
	else
	{
		if(cantCar>=minimo && cantCar<=maximo) return true;
		else return false;
	}
}

function validaCorreo(valor)
{
	var reg=/(^[a-zA-Z0-9._-]{1,30})@([a-zA-Z0-9.-]{1,30}$)/;
	if(reg.test(valor)) return true;
	else return false;
}

function validaForm()
{
	limpiaForm();
	error=0;

	var inputUser=eliminaEspacios(form.inputUser.value);
	var inputRpass=eliminaEspacios(form.inputRpass.value);
	var inputPass=eliminaEspacios(form.inputPass.value);
	var inputCorreo=eliminaEspacios(form.inputCorreo.value);

	if(!validaLongitud(inputUser, 0, 4, 50)) campoError(form.inputUser);
	if(!validaLongitud(inputRpass, 0, 8, 50)) campoError(form.inputRpass);
	if(!validaLongitud(inputPass, 0, 8, 50)) campoError(form.inputPass);
	if(!validaCorreo(inputCorreo)) campoError(form.inputCorreo);

	if(error==1)
	{
		var texto="

Error: revise los campos en rojo.

<button style='width:45px; height:18px; font-size:10px;' onClick='ocultaMensaje()' type='button'>Ok</button>";
		muestraMensaje(texto);
	}
	else
	{
		var texto="
Enviando. Por favor espere.

<button style='width:60px; height:18px; font-size:10px;' onClick='ocultaMensaje()' type='button'>Ocultar</button>";
		muestraMensaje(texto);

		var ajax=nuevoAjax();
		ajax.open("POST", urlDestino, true);
		ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		ajax.send("inputUser="+inputUser);

		ajax.onreadystatechange=function()
		{
			if (ajax.readyState==4)
			{
				var respuesta=ajax.responseText;
				if(respuesta=="OK")
				{
					var texto="
Gracias por su mensaje.
Le responderemos a la brevedad.

<button style='width:45px; height:18px; font-size:10px;' onClick='ocultaMensaje()' type='button'>Ok</button>";
				}
				else var texto="

Error: intente ms tarde.

<button style='width:45px; height:18px; font-size:10px;' onClick='ocultaMensaje()' type='button'>Ok</button>";

				muestraMensaje(texto);
			}
		}
	}
}

// Mensajes de ayuda

if(navigator.userAgent.indexOf("MSIE")>=0) navegador=0;
else navegador=1;

function colocaAyuda(event)
{
	if(navegador==0)
	{
		var corX=window.event.clientX+document.documentElement.scrollLeft;
		var corY=window.event.clientY+document.documentElement.scrollTop;
	}
	else
	{
		var corX=event.clientX+window.scrollX;
		var corY=event.clientY+window.scrollY;
	}
	cAyuda.style.top=corY+20+"px";
	cAyuda.style.left=corX+15+"px";
}

function ocultaAyuda()
{
	cAyuda.style.display="none";
	if(navegador==0)
	{
		document.detachEvent("onmousemove", colocaAyuda);
		document.detachEvent("onmouseout", ocultaAyuda);
	}
	else
	{
		document.removeEventListener("mousemove", colocaAyuda, true);
		document.removeEventListener("mouseout", ocultaAyuda, true);
	}
}

function muestraAyuda(event, campo)
{
	colocaAyuda(event);

	if(navegador==0)
	{
		document.attachEvent("onmousemove", colocaAyuda);
		document.attachEvent("onmouseout", ocultaAyuda);
	}
	else
	{
		document.addEventListener("mousemove", colocaAyuda, true);
		document.addEventListener("mouseout", ocultaAyuda, true);
	}

	cNombre.innerHTML=campo;
	cTex.innerHTML=ayuda[campo];
	cAyuda.style.display="block";
}
<commit_msg>modificado validaciones.js, validaciones mejoradas<commit_after>onload=function()
{
	cAyuda=document.getElementById("mensajesAyuda");
	cNombre=document.getElementById("ayudaTitulo");
	cTex=document.getElementById("ayudaTexto");
	divTransparente=document.getElementById("transparencia");
	divMensaje=document.getElementById("transparenciaMensaje");
	form=document.getElementById("formulario");
	urlDestino="mail.php";
	claseNormal="input";
	claseError="inputError";
	ayuda=new Array();
	ayuda["Nombre Usuario"]="Ingresa tu nombre de usuario. De 4 a 50 caracteres.";
	ayuda["Correo"]="Ingresa una dirección de correo electrónico válida.";
	ayuda["Contraseña"]="Ingresa una contraseña de un mínimo de 8 caracteres.";
	ayuda["Repetir Contraseña"]="Ingresa de nuevo la contraseña.";
	preCarga("imagen/ok.gif", "imagen/loading.gif", "imagen/error.gif");
}

function preCarga()
{
	imagenes=new Array();
	for(i=0; i<arguments.length; i++)
	{
		imagenes[i]=document.createElement("img");
		imagenes[i].src=arguments[i];
	}
}

function nuevoAjax()
{
	var xmlhttp=false;
	try
	{
		// No IE
		xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
	}
	catch(e)
	{
		try
		{
			// IE
			xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
		}
		catch(E) { xmlhttp=false; }
	}
	if (!xmlhttp && typeof XMLHttpRequest!="undefined") { xmlhttp=new XMLHttpRequest(); }
	return xmlhttp;
}

function limpiaForm()
{
	for(i=0; i<=3; i++)
	{
		form.elements[i].className=claseNormal;
	}
}

function campoError(campo)
{
	campo.className=claseError;
	error=1;
}

function ocultaMensaje()
{
	divTransparente.style.display="none";
}

function muestraMensaje(mensaje)
{
	divMensaje.innerHTML=mensaje;
	divTransparente.style.display="block";
}

function eliminaEspacios(cadena)
{
	// Funcion para eliminar espacios delante y detras de cada cadena
	while(cadena.charAt(cadena.length-1)==" ") cadena=cadena.substr(0, cadena.length-1);
	while(cadena.charAt(0)==" ") cadena=cadena.substr(1, cadena.length-1);
	return cadena;
}

function validaLongitud(valor, permiteVacio, minimo, maximo)
{
	var cantCar=valor.length;
	if(valor=="")
	{
		if(permiteVacio) return true;
		else return false;
	}
	else
	{
		if(cantCar>=minimo && cantCar<=maximo) return true;
		else return false;
	}
}

function validaCorreo(valor)
{
	var reg=/^[0-9a-z_\-\.]+@[0-9a-z\-\.]+\.[a-z]{2,4}$/i;

	if(reg.test(valor)) return true;
	else return false;
}

function validaForm()
{
	limpiaForm();
	error=0;

	var inputUser=eliminaEspacios(form.inputUser.value);
	var inputRpass=eliminaEspacios(form.inputRpass.value);
	var inputPass=eliminaEspacios(form.inputPass.value);
	var inputCorreo=eliminaEspacios(form.inputCorreo.value);

	if(!validaLongitud(inputUser, 0, 4, 50)) campoError(form.inputUser);
	if(!(inputPass==inputRpass)) {
    campoError(form.inputRpass);

    }
	if(!validaLongitud(inputPass, 0, 8, 50)){
       campoError(form.inputPass);
       campoError(form.inputRpass);
  }
	if(!validaCorreo(inputCorreo)) campoError(form.inputCorreo);

	if(error==1)
	{
		var texto="

Error: revise los campos en rojo.

<button style='width:45px; height:18px; font-size:10px;' onClick='ocultaMensaje()' type='button'>Ok</button>";
		muestraMensaje(texto);
	}
	else
	{
		var texto="
Enviando. Por favor espere.

<button style='width:60px; height:18px; font-size:10px;' onClick='ocultaMensaje()' type='button'>Ocultar</button>";
		muestraMensaje(texto);
		var ajax=nuevoAjax();
		ajax.open("POST", urlDestino, true);
		ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		ajax.send("inputUser="+inputUser);
		ajax.onreadystatechange=function()
		{
			if (ajax.readyState==4)
			{
				var respuesta=ajax.responseText;
				if(respuesta=="OK")
				{
					var texto="
Gracias por su mensaje.
Le responderemos a la brevedad.

<button style='width:45px; height:18px; font-size:10px;' onClick='ocultaMensaje()' type='button'>Ok</button>";
				}
				else var texto="

Error: intente más tarde.

<button style='width:45px; height:18px; font-size:10px;' onClick='ocultaMensaje()' type='button'>Ok</button>";
				muestraMensaje(texto);
			}
		}
	}
}

// Mensajes de ayuda
if(navigator.userAgent.indexOf("MSIE")>=0) navegador=0;
else navegador=1;

function colocaAyuda(event)
{
	if(navegador==0)
	{
		var corX=window.event.clientX+document.documentElement.scrollLeft;
		var corY=window.event.clientY+document.documentElement.scrollTop;
	}
	else
	{
		var corX=event.clientX+window.scrollX;
		var corY=event.clientY+window.scrollY;
	}
	cAyuda.style.top=corY+20+"px";
	cAyuda.style.left=corX+15+"px";
}

function ocultaAyuda()
{
	cAyuda.style.display="none";
	if(navegador==0)
	{
		document.detachEvent("onmousemove", colocaAyuda);
		document.detachEvent("onmouseout", ocultaAyuda);
	}
	else
	{
		document.removeEventListener("mousemove", colocaAyuda, true);
		document.removeEventListener("mouseout", ocultaAyuda, true);
	}
}

function muestraAyuda(event, campo)
{
	colocaAyuda(event);

	if(navegador==0)
	{
		document.attachEvent("onmousemove", colocaAyuda);
		document.attachEvent("onmouseout", ocultaAyuda);
	}
	else
	{
		document.addEventListener("mousemove", colocaAyuda, true);
		document.addEventListener("mouseout", ocultaAyuda, true);
	}
	cNombre.innerHTML=campo;
	cTex.innerHTML=ayuda[campo];
	cAyuda.style.display="block";
}
<|endoftext|>


<commit_before>var data = Alloy.Collections.myplaces;
data.fetch();

function maping(e) {
	var index = e.itemIndex;
	var value = data.at(index);
	var map = Alloy.createController('markedMap', {
		details : value
	});
	map.getView().open();
}

$.header.rightNavButton.addEventListener('click', function() {
	Alloy.Globals.menu.toggleRightDrawer();
});

$.header.leftNavButton.addEventListener('click', function() {
	var ctrl = Alloy.createController('AddNewPlaces');
	ctrl.getView().open();
});

Ti.App.addEventListener('app:update', function(argument) {
	data.fetch();
});

function edit (argument) {
 var dialog = Ti.UI.createAlertDialog({
			buttonNames : ['Edit', 'Delete' , 'Cancel'],
			message : 'قم بتعديل اماكنك',
			title : 'تعديل المكان'
		});
		dialog.addEventListener('click' , function(e) {
		  if (e.index == 0) {

		  }else if (e.index == 1) {
		  	data.remove(e.index);
		  	data.fetch();
		  	//data.at(e.index).destroy();
		  }else if (e.index == 2) {

		  };
		});
		dialog.show();
}<commit_msg>user can delete place<commit_after>var data = Alloy.Collections.myplaces;
data.fetch();

function maping(e) {
	var index = e.itemIndex;
	var value = data.at(index);
	var map = Alloy.createController('markedMap', {
		details : value
	});
	map.getView().open();
}

$.header.rightNavButton.addEventListener('click', function() {
	Alloy.Globals.menu.toggleRightDrawer();
});

$.header.leftNavButton.addEventListener('click', function() {
	var ctrl = Alloy.createController('AddNewPlaces');
	ctrl.getView().open();
});

Ti.App.addEventListener('app:update', function(argument) {
	data.fetch();
});

function edit(argument) {
	var dialog = Ti.UI.createAlertDialog({
		buttonNames : ['Delete', 'Cancel'],
		message : 'قم بتعديل اماكنك',
		title : 'تعديل المكان'
	});
	dialog.addEventListener('click', function(e) {
		if (e.index == 0) {
			data.at(e.index).destroy();
			data.remove(e.index);
		}
	});
	dialog.show();
}<|endoftext|>


<commit_before>// **N3Store** objects store N3 triples with an associated context in memory.

var expandPrefixedName = require('./N3Util').expandPrefixedName;

// ## Constructor
function N3Store(triples, prefixes) {
  if (!(this instanceof N3Store))
    return new N3Store(triples, prefixes);

  // The number of triples is initially zero.
  this._size = 0;
  // `_contexts` contains subject, predicate, and object indexes per context.
  this._contexts = Object.create(null);
  // `_entities` maps entities such as `http://xmlns.com/foaf/0.1/name` to numbers.
  // This saves memory, since only the numbers have to be stored in `_contexts`.
  this._entities = Object.create(null);
  this._entities['>>____unused_item_to_make_first_entity_key_non-falsy____<<'] = 0;
  this._entityCount = 0;
  // `_blankNodeIndex` is the index of the last created blank node that was automatically named
  this._blankNodeIndex = 0;

  // Shift parameters if `triples` is not given
  if (!prefixes && triples && !triples[0])
    prefixes = triples, triples = null;

  // Add triples and prefixes if passed
  this._prefixes = Object.create(null);
  triples && this.addTriples(triples);
  prefixes && this.addPrefixes(prefixes);
}

N3Store.prototype = {
  // ## Public properties

  // `defaultContext` is the default context wherein triples are stored.
  get defaultContext() {
    return 'n3/contexts#default';
  },

  // ### `size` returns the number of triples in the store.
  get size() {
    // Return the triple count if if was cached.
    var size = this._size;
    if (size !== null)
      return size;

    // Calculate the number of triples by counting to the deepest level.
    var contexts = this._contexts, subjects, subject;
    for (var contextKey in contexts)
      for (var subjectKey in (subjects = contexts[contextKey].subjects))
        for (var predicateKey in (subject = subjects[subjectKey]))
          size += Object.keys(subject[predicateKey]).length;
    return this._size = size;
  },

  // ## Private methods

  // ### `_addToIndex` adds a triple to a three-layered index.
  _addToIndex: function (index0, key0, key1, key2) {
    // Create layers as necessary.
    var index1 = index0[key0] || (index0[key0] = {});
    var index2 = index1[key1] || (index1[key1] = {});
    // Setting the key to _any_ value signalizes the presence of the triple.
    index2[key2] = null;
  },

  // ### `_removeFromIndex` removes a triple from a three-layered index.
  _removeFromIndex: function (index0, key0, key1, key2) {
    // Remove the triple from the index.
    var index1 = index0[key0], index2 = index1[key1], key;
    delete index2[key2];

    // Remove intermediary index layers if they are empty.
    for (key in index2) return;
    delete index1[key1];
    for (key in index1) return;
    delete index0[key0];
  },

  // ### `_findInIndex` finds a set of triples in a three-layered index.
  // The index base is `index0` and the keys at each level are `key0`, `key1`, and `key2`.
  // Any of these keys can be `null`, which is interpreted as a wildcard.
  // `name0`, `name1`, and `name2` are the names of the keys at each level,
  // used when reconstructing the resulting triple
  // (for instance: _subject_, _predicate_, and _object_).
  // Finally, `context` will be the context of the created triples.
  _findInIndex: function (index0, key0, key1, key2, name0, name1, name2, context) {
    var results = [], entityKeys = Object.keys(this._entities), tmp, index1, index2;

    // If a key is specified, use only that part of index 0.
    if (key0) (tmp = index0, index0 = {})[key0] = tmp[key0];
    for (var value0 in index0) {
      var entity0 = entityKeys[value0];

      if (index1 = index0[value0]) {
        // If a key is specified, use only that part of index 1.
        if (key1) (tmp = index1, index1 = {})[key1] = tmp[key1];
        for (var value1 in index1) {
          var entity1 = entityKeys[value1];

          if (index2 = index1[value1]) {
            // If a key is specified, use only that part of index 2, if it exists.
            var values = key2 ? (key2 in index2 ? [key2] : []) : Object.keys(index2);
            // Create triples for all items found in index 2.
            results.push.apply(results, values.map(function (value2) {
              var result = { context: context };
              result[name0] = entity0;
              result[name1] = entity1;
              result[name2] = entityKeys[value2];
              return result;
            }));
          }
        }
      }
    }
    return results;
  },

  // ### `_countInIndex` counts matching triples in a three-layered index.
  // The index base is `index0` and the keys at each level are `key0`, `key1`, and `key2`.
  // Any of these keys can be `null`, which is interpreted as a wildcard.
  _countInIndex: function (index0, key0, key1, key2) {
    var count = 0, tmp, index1, index2;

    // If a key is specified, count only that part of index 0.
    if (key0) (tmp = index0, index0 = {})[key0] = tmp[key0];
    for (var value0 in index0) {
      if (index1 = index0[value0]) {

        // If a key is specified, count only that part of index 1.
        if (key1) (tmp = index1, index1 = {})[key1] = tmp[key1];
        for (var value1 in index1) {
          if (index2 = index1[value1]) {
            // If a key is specified, count the triple if it exists.
            if (key2) (key2 in index2) && count++;
            // Otherwise, count all triples.
            else count += Object.keys(index2).length;
          }
        }
      }
    }
    return count;
  },

  // ## Public methods

  // ### `addTriple` adds a new N3 triple to the store.
  addTriple: function (subject, predicate, object, context) {
    // Shift arguments if a triple object is given instead of components
    if (!predicate)
      context = subject.context, object = subject.object,
        predicate = subject.predicate, subject = subject.subject;

    // Find the context that will contain the triple.
    context = context || this.defaultContext;
    var contextItem = this._contexts[context];
    // Create the context if it doesn't exist yet.
    if (!contextItem) {
      contextItem = this._contexts[context] = {
        subjects: {},
        predicates: {},
        objects: {}
      };
      // Freezing a context helps subsequent `add` performance,
      // and properties will never be modified anyway.
      Object.freeze(contextItem);
    }

    // Since entities can often be long URIs, we avoid storing them in every index.
    // Instead, we have a separate index that maps entities to numbers,
    // which are then used as keys in the other indexes.
    var entities = this._entities;
    subject   = entities[subject]   || (entities[subject]   = ++this._entityCount);
    predicate = entities[predicate] || (entities[predicate] = ++this._entityCount);
    object    = entities[object]    || (entities[object]    = ++this._entityCount);

    this._addToIndex(contextItem.subjects,   subject,   predicate, object);
    this._addToIndex(contextItem.predicates, predicate, object,    subject);
    this._addToIndex(contextItem.objects,    object,    subject,   predicate);

    // The cached triple count is now invalid.
    this._size = null;
  },

  // ### `addTriples` adds multiple N3 triples to the store.
  addTriples: function (triples) {
    for (var i = triples.length - 1; i >= 0; i--)
      this.addTriple(triples[i]);
  },

  // ### `addPrefix` adds support for querying with the given prefix
  addPrefix: function (prefix, uri) {
    this._prefixes[prefix] = uri;
  },

  // ### `addPrefixex` adds support for querying with the given prefixes
  addPrefixes: function (prefixes) {
    for (var prefix in prefixes)
      this.addPrefix(prefix, prefixes[prefix]);
  },

  // ### `removeTriple` removes an N3 triple from the store if it exists.
  removeTriple: function (subject, predicate, object, context) {
    // Shift arguments if a triple object is given instead of components.
    if (!predicate)
      context = subject.context, object = subject.object,
        predicate = subject.predicate, subject = subject.subject;
    context = context || this.defaultContext;

    // Find internal identifiers for all components.
    var contextItem, entities = this._entities, contexts = this._contexts;
    if (!(subject     = entities[subject]))   return;
    if (!(predicate   = entities[predicate])) return;
    if (!(object      = entities[object]))    return;
    if (!(contextItem = contexts[context]))   return;

    // Verify that the triple exists.
    var subjects, predicates;
    if (!(subjects   = contextItem.subjects[subject])) return;
    if (!(predicates = subjects[predicate])) return;
    if (!(object in predicates)) return;

    // Remove it from all indexes.
    this._removeFromIndex(contextItem.subjects,   subject,   predicate, object);
    this._removeFromIndex(contextItem.predicates, predicate, object,    subject);
    this._removeFromIndex(contextItem.objects,    object,    subject,   predicate);
    if (this._size !== null) this._size--;

    // Remove the context if it is empty.
    for (subject in contextItem.subjects) return;
    delete contexts[context];
  },

  // ### `removeTriples` removes multiple N3 triples from the store.
  removeTriples: function (triples) {
    for (var i = triples.length - 1; i >= 0; i--)
      this.removeTriple(triples[i]);
  },

  // ### `find` finds a set of triples matching a pattern, expanding prefixes as necessary.
  // Setting `subject`, `predicate`, or `object` to `null` means an _anything_ wildcard.
  // Setting `context` to `null` means the default context.
  find: function (subject, predicate, object, context) {
    var prefixes = this._prefixes;
    return this.findByUri(
      expandPrefixedName(subject,   prefixes),
      expandPrefixedName(predicate, prefixes),
      expandPrefixedName(object,    prefixes),
      expandPrefixedName(context,   prefixes)
    );
  },

  // ### `findByUri` finds a set of triples matching a pattern.
  // Setting `subject`, `predicate`, or `object` to `null` means an _anything_ wildcard.
  // Setting `context` to `null` means the default context.
  findByUri: function (subject, predicate, object, context) {
    context = context || this.defaultContext;
    var contextItem = this._contexts[context], entities = this._entities;

    // If the specified context contain no triples, there are no results.
    if (!contextItem) return [];

    // Translate URIs to internal index keys.
    // Optimization: if the entity doesn't exist, no triples with it exist.
    if (subject   && !(subject   = entities[subject]))   return [];
    if (predicate && !(predicate = entities[predicate])) return [];
    if (object    && !(object    = entities[object]))    return [];

    // Choose the optimal index, based on what fields are present
    if (subject) {
      if (object)
        // If subject and object are given, the object index will be the fastest.
        return this._findInIndex(contextItem.objects, object, subject, predicate,
                                 'object', 'subject', 'predicate', context);
      else
        // If only subject and possibly predicate are given, the subject index will be the fastest.
        return this._findInIndex(contextItem.subjects, subject, predicate, object,
                                 'subject', 'predicate', 'object', context);
    }
    else if (predicate) {
      // If only predicate and possibly object are given, the predicate index will be the fastest.
      return this._findInIndex(contextItem.predicates, predicate, object, subject,
                               'predicate', 'object', 'subject', context);
    }
    else {
      // If only object is possibly given, the object index will be the fastest.
      return this._findInIndex(contextItem.objects, object, subject, predicate,
                               'object', 'subject', 'predicate', context);
    }
  },

  // ### `count` returns the number of triples matching a pattern, expanding prefixes as necessary.
  // Setting `subject`, `predicate`, or `object` to `null` means an _anything_ wildcard.
  // Setting `context` to `null` means the default context.
  count: function (subject, predicate, object, context) {
    var prefixes = this._prefixes;
    return this.countByUri(
      expandPrefixedName(subject,   prefixes),
      expandPrefixedName(predicate, prefixes),
      expandPrefixedName(object,    prefixes),
      expandPrefixedName(context,   prefixes)
    );
  },

  // ### `countByUri` returns the number of triples matching a pattern.
  // Setting `subject`, `predicate`, or `object` to `null` means an _anything_ wildcard.
  // Setting `context` to `null` means the default context.
  countByUri: function (subject, predicate, object, context) {
    context = context || this.defaultContext;
    var contextItem = this._contexts[context], entities = this._entities;

    // If the specified context contain no triples, there are no results.
    if (!contextItem) return 0;

    // Translate URIs to internal index keys.
    // Optimization: if the entity doesn't exist, no triples with it exist.
    if (subject   && !(subject   = entities[subject]))   return 0;
    if (predicate && !(predicate = entities[predicate])) return 0;
    if (object    && !(object    = entities[object]))    return 0;

    // Choose the optimal index, based on what fields are present
    if (subject) {
      if (object)
        // If subject and object are given, the object index will be the fastest.
        return this._countInIndex(contextItem.objects, object, subject, predicate);
      else
        // If only subject and possibly predicate are given, the subject index will be the fastest.
        return this._countInIndex(contextItem.subjects, subject, predicate, object);
    }
    else if (predicate) {
      // If only predicate and possibly object are given, the predicate index will be the fastest.
      return this._countInIndex(contextItem.predicates, predicate, object, subject);
    }
    else {
      // If only object is possibly given, the object index will be the fastest.
      return this._countInIndex(contextItem.objects, object, subject, predicate);
    }
  },

  // ### `createBlankNode` creates a new blank node, returning its name.
  createBlankNode: function (suggestedName) {
    var name;
    if (suggestedName) {
      name = suggestedName = '_:' + suggestedName;
      var index = 1;
      while (this._entities[name])
        name = suggestedName + index++;
    }
    else {
      do {
        name = '_:b' + this._blankNodeIndex++;
      }
      while (this._entities[name]);
    }
    this._entities[name] = this._entityCount++;
    return name;
  },
};

// ## Exports

// Export the `N3Store` class as a whole.
module.exports = N3Store;
<commit_msg>Speed up store searching.<commit_after>// **N3Store** objects store N3 triples with an associated context in memory.

var expandPrefixedName = require('./N3Util').expandPrefixedName;

// ## Constructor
function N3Store(triples, prefixes) {
  if (!(this instanceof N3Store))
    return new N3Store(triples, prefixes);

  // The number of triples is initially zero.
  this._size = 0;
  // `_contexts` contains subject, predicate, and object indexes per context.
  this._contexts = Object.create(null);
  // `_entities` maps entities such as `http://xmlns.com/foaf/0.1/name` to numbers.
  // This saves memory, since only the numbers have to be stored in `_contexts`.
  this._entities = Object.create(null);
  this._entities['>>____unused_item_to_make_first_entity_key_non-falsy____<<'] = 0;
  this._entityCount = 0;
  // `_blankNodeIndex` is the index of the last created blank node that was automatically named
  this._blankNodeIndex = 0;

  // Shift parameters if `triples` is not given
  if (!prefixes && triples && !triples[0])
    prefixes = triples, triples = null;

  // Add triples and prefixes if passed
  this._prefixes = Object.create(null);
  triples && this.addTriples(triples);
  prefixes && this.addPrefixes(prefixes);
}

N3Store.prototype = {
  // ## Public properties

  // `defaultContext` is the default context wherein triples are stored.
  get defaultContext() {
    return 'n3/contexts#default';
  },

  // ### `size` returns the number of triples in the store.
  get size() {
    // Return the triple count if if was cached.
    var size = this._size;
    if (size !== null)
      return size;

    // Calculate the number of triples by counting to the deepest level.
    var contexts = this._contexts, subjects, subject;
    for (var contextKey in contexts)
      for (var subjectKey in (subjects = contexts[contextKey].subjects))
        for (var predicateKey in (subject = subjects[subjectKey]))
          size += Object.keys(subject[predicateKey]).length;
    return this._size = size;
  },

  // ## Private methods

  // ### `_addToIndex` adds a triple to a three-layered index.
  _addToIndex: function (index0, key0, key1, key2) {
    // Create layers as necessary.
    var index1 = index0[key0] || (index0[key0] = {});
    var index2 = index1[key1] || (index1[key1] = {});
    // Setting the key to _any_ value signalizes the presence of the triple.
    index2[key2] = null;
  },

  // ### `_removeFromIndex` removes a triple from a three-layered index.
  _removeFromIndex: function (index0, key0, key1, key2) {
    // Remove the triple from the index.
    var index1 = index0[key0], index2 = index1[key1], key;
    delete index2[key2];

    // Remove intermediary index layers if they are empty.
    for (key in index2) return;
    delete index1[key1];
    for (key in index1) return;
    delete index0[key0];
  },

  // ### `_findInIndex` finds a set of triples in a three-layered index.
  // The index base is `index0` and the keys at each level are `key0`, `key1`, and `key2`.
  // Any of these keys can be `null`, which is interpreted as a wildcard.
  // `name0`, `name1`, and `name2` are the names of the keys at each level,
  // used when reconstructing the resulting triple
  // (for instance: _subject_, _predicate_, and _object_).
  // Finally, `context` will be the context of the created triples.
  _findInIndex: function (index0, key0, key1, key2, name0, name1, name2, context) {
    var results = [], entityKeys = Object.keys(this._entities), tmp, index1, index2;

    // If a key is specified, use only that part of index 0.
    if (key0) (tmp = index0, index0 = {})[key0] = tmp[key0];
    for (var value0 in index0) {
      var entity0 = entityKeys[value0];

      if (index1 = index0[value0]) {
        // If a key is specified, use only that part of index 1.
        if (key1) (tmp = index1, index1 = {})[key1] = tmp[key1];
        for (var value1 in index1) {
          var entity1 = entityKeys[value1];

          if (index2 = index1[value1]) {
            // If a key is specified, use only that part of index 2, if it exists.
            var values = key2 ? (key2 in index2 ? [key2] : []) : Object.keys(index2);
            // Create triples for all items found in index 2.
            for (var l = values.length - 1; l >= 0; l--) {
              var result = { context: context };
              result[name0] = entity0;
              result[name1] = entity1;
              result[name2] = entityKeys[values[l]];
              results.push(result);
            }
          }
        }
      }
    }
    return results;
  },

  // ### `_countInIndex` counts matching triples in a three-layered index.
  // The index base is `index0` and the keys at each level are `key0`, `key1`, and `key2`.
  // Any of these keys can be `null`, which is interpreted as a wildcard.
  _countInIndex: function (index0, key0, key1, key2) {
    var count = 0, tmp, index1, index2;

    // If a key is specified, count only that part of index 0.
    if (key0) (tmp = index0, index0 = {})[key0] = tmp[key0];
    for (var value0 in index0) {
      if (index1 = index0[value0]) {

        // If a key is specified, count only that part of index 1.
        if (key1) (tmp = index1, index1 = {})[key1] = tmp[key1];
        for (var value1 in index1) {
          if (index2 = index1[value1]) {
            // If a key is specified, count the triple if it exists.
            if (key2) (key2 in index2) && count++;
            // Otherwise, count all triples.
            else count += Object.keys(index2).length;
          }
        }
      }
    }
    return count;
  },

  // ## Public methods

  // ### `addTriple` adds a new N3 triple to the store.
  addTriple: function (subject, predicate, object, context) {
    // Shift arguments if a triple object is given instead of components
    if (!predicate)
      context = subject.context, object = subject.object,
        predicate = subject.predicate, subject = subject.subject;

    // Find the context that will contain the triple.
    context = context || this.defaultContext;
    var contextItem = this._contexts[context];
    // Create the context if it doesn't exist yet.
    if (!contextItem) {
      contextItem = this._contexts[context] = {
        subjects: {},
        predicates: {},
        objects: {}
      };
      // Freezing a context helps subsequent `add` performance,
      // and properties will never be modified anyway.
      Object.freeze(contextItem);
    }

    // Since entities can often be long URIs, we avoid storing them in every index.
    // Instead, we have a separate index that maps entities to numbers,
    // which are then used as keys in the other indexes.
    var entities = this._entities;
    subject   = entities[subject]   || (entities[subject]   = ++this._entityCount);
    predicate = entities[predicate] || (entities[predicate] = ++this._entityCount);
    object    = entities[object]    || (entities[object]    = ++this._entityCount);

    this._addToIndex(contextItem.subjects,   subject,   predicate, object);
    this._addToIndex(contextItem.predicates, predicate, object,    subject);
    this._addToIndex(contextItem.objects,    object,    subject,   predicate);

    // The cached triple count is now invalid.
    this._size = null;
  },

  // ### `addTriples` adds multiple N3 triples to the store.
  addTriples: function (triples) {
    for (var i = triples.length - 1; i >= 0; i--)
      this.addTriple(triples[i]);
  },

  // ### `addPrefix` adds support for querying with the given prefix
  addPrefix: function (prefix, uri) {
    this._prefixes[prefix] = uri;
  },

  // ### `addPrefixex` adds support for querying with the given prefixes
  addPrefixes: function (prefixes) {
    for (var prefix in prefixes)
      this.addPrefix(prefix, prefixes[prefix]);
  },

  // ### `removeTriple` removes an N3 triple from the store if it exists.
  removeTriple: function (subject, predicate, object, context) {
    // Shift arguments if a triple object is given instead of components.
    if (!predicate)
      context = subject.context, object = subject.object,
        predicate = subject.predicate, subject = subject.subject;
    context = context || this.defaultContext;

    // Find internal identifiers for all components.
    var contextItem, entities = this._entities, contexts = this._contexts;
    if (!(subject     = entities[subject]))   return;
    if (!(predicate   = entities[predicate])) return;
    if (!(object      = entities[object]))    return;
    if (!(contextItem = contexts[context]))   return;

    // Verify that the triple exists.
    var subjects, predicates;
    if (!(subjects   = contextItem.subjects[subject])) return;
    if (!(predicates = subjects[predicate])) return;
    if (!(object in predicates)) return;

    // Remove it from all indexes.
    this._removeFromIndex(contextItem.subjects,   subject,   predicate, object);
    this._removeFromIndex(contextItem.predicates, predicate, object,    subject);
    this._removeFromIndex(contextItem.objects,    object,    subject,   predicate);
    if (this._size !== null) this._size--;

    // Remove the context if it is empty.
    for (subject in contextItem.subjects) return;
    delete contexts[context];
  },

  // ### `removeTriples` removes multiple N3 triples from the store.
  removeTriples: function (triples) {
    for (var i = triples.length - 1; i >= 0; i--)
      this.removeTriple(triples[i]);
  },

  // ### `find` finds a set of triples matching a pattern, expanding prefixes as necessary.
  // Setting `subject`, `predicate`, or `object` to `null` means an _anything_ wildcard.
  // Setting `context` to `null` means the default context.
  find: function (subject, predicate, object, context) {
    var prefixes = this._prefixes;
    return this.findByUri(
      expandPrefixedName(subject,   prefixes),
      expandPrefixedName(predicate, prefixes),
      expandPrefixedName(object,    prefixes),
      expandPrefixedName(context,   prefixes)
    );
  },

  // ### `findByUri` finds a set of triples matching a pattern.
  // Setting `subject`, `predicate`, or `object` to `null` means an _anything_ wildcard.
  // Setting `context` to `null` means the default context.
  findByUri: function (subject, predicate, object, context) {
    context = context || this.defaultContext;
    var contextItem = this._contexts[context], entities = this._entities;

    // If the specified context contain no triples, there are no results.
    if (!contextItem) return [];

    // Translate URIs to internal index keys.
    // Optimization: if the entity doesn't exist, no triples with it exist.
    if (subject   && !(subject   = entities[subject]))   return [];
    if (predicate && !(predicate = entities[predicate])) return [];
    if (object    && !(object    = entities[object]))    return [];

    // Choose the optimal index, based on what fields are present
    if (subject) {
      if (object)
        // If subject and object are given, the object index will be the fastest.
        return this._findInIndex(contextItem.objects, object, subject, predicate,
                                 'object', 'subject', 'predicate', context);
      else
        // If only subject and possibly predicate are given, the subject index will be the fastest.
        return this._findInIndex(contextItem.subjects, subject, predicate, object,
                                 'subject', 'predicate', 'object', context);
    }
    else if (predicate) {
      // If only predicate and possibly object are given, the predicate index will be the fastest.
      return this._findInIndex(contextItem.predicates, predicate, object, subject,
                               'predicate', 'object', 'subject', context);
    }
    else {
      // If only object is possibly given, the object index will be the fastest.
      return this._findInIndex(contextItem.objects, object, subject, predicate,
                               'object', 'subject', 'predicate', context);
    }
  },

  // ### `count` returns the number of triples matching a pattern, expanding prefixes as necessary.
  // Setting `subject`, `predicate`, or `object` to `null` means an _anything_ wildcard.
  // Setting `context` to `null` means the default context.
  count: function (subject, predicate, object, context) {
    var prefixes = this._prefixes;
    return this.countByUri(
      expandPrefixedName(subject,   prefixes),
      expandPrefixedName(predicate, prefixes),
      expandPrefixedName(object,    prefixes),
      expandPrefixedName(context,   prefixes)
    );
  },

  // ### `countByUri` returns the number of triples matching a pattern.
  // Setting `subject`, `predicate`, or `object` to `null` means an _anything_ wildcard.
  // Setting `context` to `null` means the default context.
  countByUri: function (subject, predicate, object, context) {
    context = context || this.defaultContext;
    var contextItem = this._contexts[context], entities = this._entities;

    // If the specified context contain no triples, there are no results.
    if (!contextItem) return 0;

    // Translate URIs to internal index keys.
    // Optimization: if the entity doesn't exist, no triples with it exist.
    if (subject   && !(subject   = entities[subject]))   return 0;
    if (predicate && !(predicate = entities[predicate])) return 0;
    if (object    && !(object    = entities[object]))    return 0;

    // Choose the optimal index, based on what fields are present
    if (subject) {
      if (object)
        // If subject and object are given, the object index will be the fastest.
        return this._countInIndex(contextItem.objects, object, subject, predicate);
      else
        // If only subject and possibly predicate are given, the subject index will be the fastest.
        return this._countInIndex(contextItem.subjects, subject, predicate, object);
    }
    else if (predicate) {
      // If only predicate and possibly object are given, the predicate index will be the fastest.
      return this._countInIndex(contextItem.predicates, predicate, object, subject);
    }
    else {
      // If only object is possibly given, the object index will be the fastest.
      return this._countInIndex(contextItem.objects, object, subject, predicate);
    }
  },

  // ### `createBlankNode` creates a new blank node, returning its name.
  createBlankNode: function (suggestedName) {
    var name;
    if (suggestedName) {
      name = suggestedName = '_:' + suggestedName;
      var index = 1;
      while (this._entities[name])
        name = suggestedName + index++;
    }
    else {
      do {
        name = '_:b' + this._blankNodeIndex++;
      }
      while (this._entities[name]);
    }
    this._entities[name] = this._entityCount++;
    return name;
  },
};

// ## Exports

// Export the `N3Store` class as a whole.
module.exports = N3Store;
<|endoftext|>


<commit_before>"use strict";

const Promise = require("bluebird");
const { fork } = require("child_process");
const EventEmitter = require("events");
const path = require("path");
const fs = require("fs");
const uuid = require("uuid");

const FORK_OPTIONS = {
    detached: true,
    stdio: "ignore"
};

class Process extends EventEmitter {

    constructor(logger) {
        super();
        this.logger = logger;
        this.child = null;
        this.data = null;
        this.isConnected = false;
        this.stack = {};
        this.forkId = uuid.v4();
    }

    spawn(sourceFile, data = {}) {
        this.data = data;

        if (!path.isAbsolute(sourceFile)) {
            sourceFile = path.join(path.dirname(process.argv[1]), sourceFile);
        }

        const exists = fs.existsSync(sourceFile);
        if (!exists) {
            this.logger.error(`module ${sourceFile} does not exist, cannot start process for job as fork: ${this.forkId}.`);
            process.nextTick(() => {
                super.emit("close", true); //ends running queue-job
            });
            return;
        }

        this.logger.info(`spawning process ${this.forkId} with module: ${sourceFile}.`);
        this.child = fork(sourceFile, [this.forkId], FORK_OPTIONS);

        this.child.on("error", error => {
            this.logger.error(`${this.forkId} child error ${error}.`);
        });

        this.child.on("disconnect", () => {
            this.logger.warn(`${this.forkId} child disconnected.`);
        });

        this.child.on("exit", () => {
            this.logger.warn(`${this.forkId} child exited.`);
        });

        this.child.on("close", () => {
            this.logger.warn(`${this.forkId} child closed.`);
            this.emit("close", true);
        });

        this.child.on("message", message => {
            this.emit("message", message);
            this._handleMessage(message);
        });

        this.child.unref();
    }

    _handleMessage(message) {

        if (typeof message !== "object") {
            return;
        }

        if (typeof message.type === "undefined" ||
            typeof message.content === "undefined") {
            return;
        }

        switch (message.type) {

            case "id":
                if (this.forkId === message.content) {
                    this.logger.info(`forked process ${message.content} is connected.`);
                    this.isConnected = true;
                    this.send("data", this.data);
                    this.emit("ready", true);
                } else {
                    this.logger.error(`forked process ${this.forkId} send bad forkId: ${message.content}.`);
                }
                break;

            case "log":
                this.logger.info(`f-ipc-log:${this.forkId}: ${message.content}.`);
                break;

            case "metrics":
                super.emit("metrics", message.content);
                break;

            case "error":
                this.logger.error(`error in fork process: ${this.forkId}, ${message.content}.`);
                break;

            case "task":
                this._handleTaskResult(message.content);
                break;

            default:
                this.logger.warn(`received unknown message type: ${message.type} from f-ipc: ${this.forkId}.`);
                break;
        }
    }

    send(type, content) {

        if (this.child) {
            this.child.send({ type, content });
        }
    }

    pullMetrics(description = {}, timeout = 2000) {
        return new Promise((resolve, reject) => {

            let received = false;
            const _t = setTimeout(() => {
                if (!received) {
                    received = true;
                    reject(new Error(`took to long to retrieve metrics for fork ${this.forkId}.`));
                }
            }, timeout);

            this.send("metrics", description);
            super.once("metrics", metrics => {
                if (!received) {
                    received = true;
                    clearTimeout(_t);
                    this.logger.debug(`received metrics for fork ${this.forkId}.`);
                    resolve(metrics);
                }
            });
        });
    }

    runTask(name, args = {}){
        return new Promise((resolve, reject) => {

            const task = {
                task: name,
                identifier: uuid.v4(),
                args
            };

            let received = false;
            const _t = setTimeout(() => {
                if (!received) {
                    received = true;
                    reject(new Error(`took to long to run task for fork ${this.forkId}.`));
                }
            }, timeout);

            this.stack[task.identifier] = (error, result) => {

                if (!received) {
                    received = true;
                    clearTimeout(_t);
                    this.logger.debug(`received task result for fork ${this.forkId} and task ${task.identifier}.`);

                    if(error){
                        return reject(error);
                    }

                    resolve(result);
                }
            };

            this.logger.debug(`sending task for fork ${this.forkId} and task ${task.identifier}.`);
            this.send("task", task);
        });
    }

    _handleTaskResult(data){

        if(!this.stack[data.identifier]){
            return this.logger.error(`received task result ${data.identifier}, but task is not in stack.`);
        }

        this.stack[data.identifier](data.error, data.result);
        delete this.stack[data.identifier];
    }

    kill() {

        if (this.child) {
            this.logger.warn(`killing fork process ${this.forkId}.`);
            this.child.kill("SIGINT");
        }
    }
}

module.exports = Process;
<commit_msg>Update Process.js<commit_after>"use strict";

const Promise = require("bluebird");
const { fork } = require("child_process");
const EventEmitter = require("events");
const path = require("path");
const fs = require("fs");
const uuid = require("uuid");

const FORK_OPTIONS = {
    detached: true,
    stdio: "ignore"
};

class Process extends EventEmitter {

    constructor(logger) {
        super();
        this.logger = logger;
        this.child = null;
        this.data = null;
        this.isConnected = false;
        this.stack = {};
        this.forkId = uuid.v4();
    }

    spawn(sourceFile, data = {}) {
        this.data = data;

        if (!path.isAbsolute(sourceFile)) {
            sourceFile = path.join(path.dirname(process.argv[1]), sourceFile);
        }

        const exists = fs.existsSync(sourceFile);
        if (!exists) {
            this.logger.error(`module ${sourceFile} does not exist, cannot start process for job as fork: ${this.forkId}.`);
            process.nextTick(() => {
                super.emit("close", true); //ends running queue-job
            });
            return;
        }

        this.logger.info(`spawning process ${this.forkId} with module: ${sourceFile}.`);
        this.child = fork(sourceFile, [this.forkId], FORK_OPTIONS);

        this.child.on("error", error => {
            this.logger.error(`${this.forkId} child error ${error}.`);
        });

        this.child.on("disconnect", () => {
            this.logger.warn(`${this.forkId} child disconnected.`);
        });

        this.child.on("exit", () => {
            this.logger.warn(`${this.forkId} child exited.`);
        });

        this.child.on("close", () => {
            this.logger.warn(`${this.forkId} child closed.`);
            this.emit("close", true);
        });

        this.child.on("message", message => {
            this.emit("message", message);
            this._handleMessage(message);
        });

        this.child.unref();
    }

    _handleMessage(message) {

        if (typeof message !== "object") {
            return;
        }

        if (typeof message.type === "undefined" ||
            typeof message.content === "undefined") {
            return;
        }

        switch (message.type) {

            case "id":
                if (this.forkId === message.content) {
                    this.logger.info(`forked process ${message.content} is connected.`);
                    this.isConnected = true;
                    this.send("data", this.data);
                    this.emit("ready", true);
                } else {
                    this.logger.error(`forked process ${this.forkId} send bad forkId: ${message.content}.`);
                }
                break;

            case "log":
                this.logger.info(`f-ipc-log:${this.forkId}: ${message.content}.`);
                break;

            case "metrics":
                super.emit("metrics", message.content);
                break;

            case "error":
                this.logger.error(`error in fork process: ${this.forkId}, ${message.content}.`);
                break;

            case "task":
                this._handleTaskResult(message.content);
                break;

            default:
                this.logger.warn(`received unknown message type: ${message.type} from f-ipc: ${this.forkId}.`);
                break;
        }
    }

    send(type, content) {

        if (this.child) {
            this.child.send({ type, content });
        }
    }

    pullMetrics(description = {}, timeout = 2000) {
        return new Promise((resolve, reject) => {

            let received = false;
            const _t = setTimeout(() => {
                if (!received) {
                    received = true;
                    reject(new Error(`took to long to retrieve metrics for fork ${this.forkId}.`));
                }
            }, timeout);

            this.send("metrics", description);
            super.once("metrics", metrics => {
                if (!received) {
                    received = true;
                    clearTimeout(_t);
                    this.logger.debug(`received metrics for fork ${this.forkId}.`);
                    resolve(metrics);
                }
            });
        });
    }

    runTask(name, args = {}, timeout = 100){
        return new Promise((resolve, reject) => {

            const task = {
                task: name,
                identifier: uuid.v4(),
                args
            };

            let received = false;
            const _t = setTimeout(() => {
                if (!received) {
                    received = true;
                    reject(new Error(`took to long to run task for fork ${this.forkId}.`));
                }
            }, timeout);

            this.stack[task.identifier] = (error, result) => {

                if (!received) {
                    received = true;
                    clearTimeout(_t);
                    this.logger.debug(`received task result for fork ${this.forkId} and task ${task.identifier}.`);

                    if(error){
                        return reject(error);
                    }

                    resolve(result);
                }
            };

            this.logger.debug(`sending task for fork ${this.forkId} and task ${task.identifier}.`);
            this.send("task", task);
        });
    }

    _handleTaskResult(data){

        if(!this.stack[data.identifier]){
            return this.logger.error(`received task result ${data.identifier}, but task is not in stack.`);
        }

        this.stack[data.identifier](data.error, data.result);
        delete this.stack[data.identifier];
    }

    kill() {

        if (this.child) {
            this.logger.warn(`killing fork process ${this.forkId}.`);
            this.child.kill("SIGINT");
        }
    }
}

module.exports = Process;
<|endoftext|>


<commit_before>'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _assign;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _pathToRegexp = require('path-to-regexp');

var _pathToRegexp2 = _interopRequireDefault(_pathToRegexp);

var _utils = require('./utils');

var _RouteUtils = require('./RouteUtils');

var _componentUtils = require('./componentUtils');

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }

function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

// Definitions：
// route: oneOf(<Route />, element, string)
// routes: arrayOf(route)
// routing: new Routing()
// routings: arrayOf(routing)

var __PRELOADED__ = '__PRELOADED__';
var __MATCHED__ = '__MATCHED__';

var lutings = (0, _utils.gen)();
var cached = (0, _utils.gen)();
var preloadQueue = (0, _utils.gen)();

var Routing = function () {
  // config = { originalPath, path, component, loading, preload, props }
  function Routing(config) {
    _classCallCheck(this, Routing);

    (0, _utils.assign)(this, config);
  }

  _createClass(Routing, [{
    key: 'load',
    value: function load() {
      var _this = this;

      if (typeof this.component !== 'string') return true;
      (0, _componentUtils.loadComponent)(this.component, function () {
        return _this.constructor.deleteRoutings(_this.component);
      }, false);
    }
  }, {
    key: 'preLoad',
    value: function preLoad() {
      var _this2 = this;

      if (typeof this.component !== 'string') return true;
      (0, _componentUtils.loadComponent)(this.component, function () {
        delete _this2.preload;
        _this2.constructor.dequeuePreload(_this2);
      }, true);
    }
  }]);

  return Routing;
}();

(0, _utils.assign)(Routing, (_assign = {}, _defineProperty(_assign, lutings, []), _defineProperty(_assign, cached, {}), _defineProperty(_assign, preloadQueue, []), _defineProperty(_assign, 'compile', function compile(routes) {
  var parent = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : { originalPath: '/' };
  var name = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;

  var routings = createRoutings(routes, parent);
  if (!this[lutings].length || !name) mergeRoutings(routings);else this[cached][name] = routings;
}), _defineProperty(_assign, 'deleteRoutings', function deleteRoutings(key) {
  var routings = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this[lutings];

  if (!key || !routings) return true;
  var r = null;
  for (var k = routings.length; k--;) {
    var routing = routings[k];
    routing.component === key ? routings.slice(k, 1) : this.deleteRoutings(key, routing.childRoutings);
  }
}), _defineProperty(_assign, 'match', function match(path) {
  var routings = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this[lutings];

  return matchRoutings(path, routings);
}), _defineProperty(_assign, 'queuePreload', function queuePreload(routing) {
  var p = void 0;
  (p = this[preloadQueue]).indexOf(routing) === -1 && p.push(routing);
}), _defineProperty(_assign, 'dequeuePreload', function dequeuePreload(routing) {
  var p = void 0;
  (p = this[preloadQueue]).splice(p.indexOf(routing), 1);
}), _defineProperty(_assign, 'handlePreload', function handlePreload() {
  var queue = this[preloadQueue];
  for (var k = queue.length; k--;) {
    queue[k].preLoad();
  }
}), _assign));

function createRoutingsFromChildren(children, parentRouting) {
  var routings = [];
  // child = <Route path='/about' component={About} />
  (0, _RouteUtils.EachReactChildren)(children, function (child) {
    if ((0, _RouteUtils.isValidReactElement)(child)) {
      var type = child.type;
      var props = (0, _utils.merge)(type.defaultProps, child.props);
      var routing = createRouting(props, parentRouting, child);
      if (routing) {
        routing.childRoutings = createRoutings(props.children, {
          originalPath: routing.originalPath
        });
        routings.push(routing);
      }
    }
  });
  return routings;
}

function createRouting(props, _ref, route) {
  var originalPath = _ref.originalPath;

  var path = props.path,
      component = props.component,
      loading = props.loading,
      preload = props.preload,
      others = _objectWithoutProperties(props, ['path', 'component', 'loading', 'preload']);
  // [string]component & no path is not allowed

  if (typeof component === 'string' && !path) {
    return null;
  }
  delete others.children;
  var _originalPath = (0, _utils.pathJoin)(originalPath, path || '');
  var routing = new Routing({
    originalPath: _originalPath,
    path: (0, _pathToRegexp2.default)(_originalPath),
    component: (0, _RouteUtils.isRoute)(route) ? component : route,
    loading: loading,
    preload: preload,
    props: others
  });
  component && preload && typeof component === 'string' && Routing.queuePreload(routing);
  return routing;
}

function createRoutings(routes) {
  var parentRouting = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : new Routing({ originalPath: '/' });

  return (0, _RouteUtils.isValidChildren)(routes) ? createRoutingsFromChildren(routes, parentRouting) : [];
}

// Routing handler: root level matching; delete directly from leaves.
// Rule for new adding: inexistence or [!string]component
function disposeRouting(routing, routings) {
  var isExisted = false;

  var originalPath = routing.originalPath;
  for (var k = routings.length; k--;) {
    var _routings$k = routings[k],
        oPath = _routings$k.originalPath,
        component = _routings$k.component,
        path = _routings$k.path,
        childRoutings = _routings$k.childRoutings;

    var isSame = originalPath === oPath || oPath.indexOf('*') === -1 && path.exec(originalPath);
    isExisted = isExisted || isSame;
    if (isSame && typeof component === 'string') {
      routings.splice(k, 1, routing);
    } else {
      isExisted = isExisted || disposeRouting(routing, childRoutings || []);
    }
    if (isSame && typeof component !== 'string') {
      var c = routing.component;
      c && typeof c === 'string' && routing.preload && Routing.dequeuePreload(routing);
    }
  }
  return isExisted;
}

// Routing merger
function mergeRoutings(newRoutings) {
  var routings = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : Routing[lutings];

  var L = newRoutings.length;
  var newAdded = [];
  for (var k = 0; k < L; k++) {
    var newRouting = newRoutings[k];
    if (!disposeRouting(newRouting, routings)) {
      // does not exist in old routings
      newAdded.push(newRouting);
    }
  }
  routings.push.apply(routings, newAdded);
}

// match routings
function matchRoutings(path, routings) {
  if (!(0, _utils.isArray)(routings)) return null;
  var matches = [];
  var kached = Routing[cached];
  var k = routings.length;

  while (k--) {
    var routing = routings[k];
    var m = routing.path.exec(path);
    if (m && typeof routing.component === 'string') {
      var kachedRoutings = kached[(0, _utils.jsSuffix)(routing.component)];
      if (kachedRoutings) {
        var pos = cleanRoutings(kachedRoutings, routings, k);
        routings.splice.apply(routings, [pos, 1].concat(_toConsumableArray(kachedRoutings)));
        k += kachedRoutings.length + k - pos;
        continue;
      }
    }
    var children = matchRoutings(path, routing.childRoutings);
    if (children || m) {
      matches.unshift({
        root: routing,
        childRoutings: children
      });
    }
  }
  return matches.length ? matches : null;
}

function cleanRoutings(srcRoutings, targetRoutings, pos) {
  for (var k = srcRoutings.length; k--;) {
    var routing = srcRoutings[k];
    var deleted = false;
    for (var j = targetRoutings.length; j--;) {
      if (pos === j) continue;
      var _targetRoutings$j = targetRoutings[j],
          originalPath = _targetRoutings$j.originalPath,
          component = _targetRoutings$j.component;

      var isSame = originalPath === routing.originalPath || routing.path.test(originalPath);
      if (isSame) {
        if (isStringComponent(component)) {
          targetRoutings.splice(j, 1);
          if (j < pos) --pos;
        } else if (isStringComponent(routing.component) && !deleted) {
          srcRoutings.splice(k, 1);
          deleted = true;
        }
      }
    }
  }
  return pos;
}

function isStringComponent(component) {
  return typeof component === 'string';
}

exports.default = Routing;<commit_msg>fix sub-routes merging bug<commit_after>'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _assign;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _pathToRegexp = require('path-to-regexp');

var _pathToRegexp2 = _interopRequireDefault(_pathToRegexp);

var _utils = require('./utils');

var _RouteUtils = require('./RouteUtils');

var _componentUtils = require('./componentUtils');

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }

function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

// Definitions：
// route: oneOf(<Route />, element, string)
// routes: arrayOf(route)
// routing: new Routing()
// routings: arrayOf(routing)

var __PRELOADED__ = '__PRELOADED__';
var __MATCHED__ = '__MATCHED__';

var lutings = (0, _utils.gen)();
var cached = (0, _utils.gen)();
var preloadQueue = (0, _utils.gen)();

var Routing = function () {
  // config = { originalPath, path, component, loading, preload, props }
  function Routing(config) {
    _classCallCheck(this, Routing);

    (0, _utils.assign)(this, config);
  }

  _createClass(Routing, [{
    key: 'load',
    value: function load() {
      var _this = this;

      if (typeof this.component !== 'string') return true;
      (0, _componentUtils.loadComponent)(this.component, function () {
        return _this.constructor.deleteRoutings(_this.component);
      }, false);
    }
  }, {
    key: 'preLoad',
    value: function preLoad() {
      var _this2 = this;

      if (typeof this.component !== 'string') return true;
      (0, _componentUtils.loadComponent)(this.component, function () {
        delete _this2.preload;
        _this2.constructor.dequeuePreload(_this2);
      }, true);
    }
  }]);

  return Routing;
}();

(0, _utils.assign)(Routing, (_assign = {}, _defineProperty(_assign, lutings, []), _defineProperty(_assign, cached, {}), _defineProperty(_assign, preloadQueue, []), _defineProperty(_assign, 'compile', function compile(routes) {
  var parent = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : { originalPath: '/' };
  var name = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;

  var routings = createRoutings(routes, parent);
  if (!this[lutings].length || !name) mergeRoutings(routings);else this[cached][name] = routings;
}), _defineProperty(_assign, 'deleteRoutings', function deleteRoutings(key) {
  var routings = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this[lutings];

  if (!key || !routings) return true;
  var r = null;
  for (var k = routings.length; k--;) {
    var routing = routings[k];
    routing.component === key ? routings.slice(k, 1) : this.deleteRoutings(key, routing.childRoutings);
  }
}), _defineProperty(_assign, 'match', function match(path) {
  var routings = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this[lutings];

  return matchRoutings(path, routings);
}), _defineProperty(_assign, 'queuePreload', function queuePreload(routing) {
  var p = void 0;
  (p = this[preloadQueue]).indexOf(routing) === -1 && p.push(routing);
}), _defineProperty(_assign, 'dequeuePreload', function dequeuePreload(routing) {
  var p = void 0;
  (p = this[preloadQueue]).splice(p.indexOf(routing), 1);
}), _defineProperty(_assign, 'handlePreload', function handlePreload() {
  var queue = this[preloadQueue];
  for (var k = queue.length; k--;) {
    queue[k].preLoad();
  }
}), _assign));

function createRoutingsFromChildren(children, parentRouting) {
  var routings = [];
  // child = <Route path='/about' component={About} />
  (0, _RouteUtils.EachReactChildren)(children, function (child) {
    if ((0, _RouteUtils.isValidReactElement)(child)) {
      var type = child.type;
      var props = (0, _utils.merge)(type.defaultProps, child.props);
      var routing = createRouting(props, parentRouting, child);
      if (routing) {
        routing.childRoutings = createRoutings(props.children, {
          originalPath: routing.originalPath
        });
        routings.push(routing);
      }
    }
  });
  return routings;
}

function createRouting(props, _ref, route) {
  var originalPath = _ref.originalPath;

  var path = props.path,
      component = props.component,
      loading = props.loading,
      preload = props.preload,
      others = _objectWithoutProperties(props, ['path', 'component', 'loading', 'preload']);
  // [string]component & no path is not allowed

  if (typeof component === 'string' && !path) {
    return null;
  }
  delete others.children;
  var _originalPath = (0, _utils.pathJoin)(originalPath, path || '');
  var routing = new Routing({
    originalPath: _originalPath,
    path: (0, _pathToRegexp2.default)(_originalPath),
    component: (0, _RouteUtils.isRoute)(route) ? component : route,
    loading: loading,
    preload: preload,
    props: others
  });
  component && preload && typeof component === 'string' && Routing.queuePreload(routing);
  return routing;
}

function createRoutings(routes) {
  var parentRouting = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : new Routing({ originalPath: '/' });

  return (0, _RouteUtils.isValidChildren)(routes) ? createRoutingsFromChildren(routes, parentRouting) : [];
}

// Routing handler: root level matching; delete directly from leaves.
// Rule for new adding: inexistence or [!string]component
function disposeRouting(routing, routings) {
  var isExisted = false;

  var originalPath = routing.originalPath;
  for (var k = routings.length; k--;) {
    var _routings$k = routings[k],
        oPath = _routings$k.originalPath,
        component = _routings$k.component,
        path = _routings$k.path,
        childRoutings = _routings$k.childRoutings;

    var isSame = originalPath === oPath || oPath.indexOf('*') === -1 && path.exec(originalPath);
    isExisted = isExisted || isSame;
    if (isSame && typeof component === 'string') {
      routings.splice(k, 1, routing);
    } else {
      isExisted = isExisted || disposeRouting(routing, childRoutings || []);
    }
    if (isSame && typeof component !== 'string') {
      var c = routing.component;
      c && typeof c === 'string' && routing.preload && Routing.dequeuePreload(routing);
    }
  }
  return isExisted;
}

// Routing merger
function mergeRoutings(newRoutings) {
  var routings = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : Routing[lutings];

  var L = newRoutings.length;
  var newAdded = [];
  for (var k = 0; k < L; k++) {
    var newRouting = newRoutings[k];
    if (!disposeRouting(newRouting, routings)) {
      // does not exist in old routings
      newAdded.push(newRouting);
    }
  }
  routings.push.apply(routings, newAdded);
}

// match routings
function matchRoutings(path, routings) {
  if (!(0, _utils.isArray)(routings)) return null;
  var matches = [];
  var kached = Routing[cached];
  var k = routings.length;

  while (k--) {
    var routing = routings[k];
    var m = routing.path.exec(path);
    if (m && typeof routing.component === 'string') {
      var kachedRoutings = kached[(0, _utils.jsSuffix)(routing.component)];
      if (kachedRoutings) {
        var pos = cleanRoutings(kachedRoutings, routings, k);
        routings.splice.apply(routings, [pos, 1].concat(_toConsumableArray(kachedRoutings)));
        k = kachedRoutings.length + pos;
        continue;
      }
    }
    var children = matchRoutings(path, routing.childRoutings);
    if (children || m) {
      matches.unshift({
        root: routing,
        childRoutings: children
      });
    }
  }
  return matches.length ? matches : null;
}

function cleanRoutings(srcRoutings, targetRoutings, pos) {
  for (var k = srcRoutings.length; k--;) {
    var routing = srcRoutings[k];
    var deleted = false;
    for (var j = targetRoutings.length; j--;) {
      if (pos === j) continue;
      var _targetRoutings$j = targetRoutings[j],
          originalPath = _targetRoutings$j.originalPath,
          component = _targetRoutings$j.component;

      var isSame = originalPath === routing.originalPath || routing.path.test(originalPath);
      if (isSame) {
        if (isStringComponent(component)) {
          targetRoutings.splice(j, 1);
          if (j < pos) --pos;
        } else if (isStringComponent(routing.component) && !deleted) {
          srcRoutings.splice(k, 1);
          deleted = true;
        }
      }
    }
  }
  return pos;
}

function isStringComponent(component) {
  return typeof component === 'string';
}

exports.default = Routing;<|endoftext|>