text:
var util = require("util");
var choreography = require("temboo/core/choreography");

/*
    AddCollaboration
    Adds a collaboration for a single user to a specific folder.
*/

var AddCollaboration = function(session) {
    /*
        Create a new instance of the AddCollaboration Choreo. A TembooSession object, containing a valid
        set of Temboo credentials, must be supplied.
	*/
    var location = "/Library/Box/Collaborations/AddCollaboration"
    AddCollaboration.super_.call(this, session, location);

    /*
    Define a callback that will be used to appropriately format the results of this Choreo.
    */
    var newResultSet = function(resultStream) {
        return new AddCollaborationResultSet(resultStream);
    }

	/*
	Obtain a new InputSet object, used to specify the input values for an execution of this Choreo.
	*/
    this.newInputSet = function() {
        return new AddCollaborationInputSet();
    }

	/*
	Execute this Choreo with the specified inputs, calling the specified callback upon success,
	and the specified errorCallback upon error.
	*/
    this.execute = function(inputs, callback, errorCallback) {
        this._execute(inputs, newResultSet, callback, errorCallback);
    }
}

/*
An InputSet with methods appropriate for specifying the inputs to the AddCollaboration
Choreo. The InputSet object is used to specify input parameters when executing this Choreo.
*/

var AddCollaborationInputSet = function() {
    AddCollaborationInputSet.super_.call(this);
        /*
        Set the value of the AccessToken input for this Choreo. ((required, string) The access token retrieved during the OAuth2 process.)
        */
        this.set_AccessToken = function(value) {
            this.setInput("AccessToken", value);
        }

        /*
        Set the value of the Fields input for this Choreo. ((optional, string) A comma-separated list of fields to include in the response.)
        */
        this.set_Fields = function(value) {
            this.setInput("Fields", value);
        }

        /*
        Set the value of the FolderID input for this Choreo. ((required, string) The id of the folder that you want to create a collaboration for.)
        */
        this.set_FolderID = function(value) {
            this.setInput("FolderID", value);
        }

        /*
        Set the value of the Login input for this Choreo. ((conditional, string) The email address of someone who this collaboration applies to. Required unless providing the UserID. Note, this does not need to be a Box user.)
        */
        this.set_Login = function(value) {
            this.setInput("Login", value);
        }

        /*
        Set the value of the Role input for this Choreo. ((optional, string) The access level of the collaboration. Valid values are "viewer" or "editor". Defaults to "viewer".)
        */
        this.set_Role = function(value) {
            this.setInput("Role", value);
        }

        /*
        Set the value of the UserID input for this Choreo. ((conditional, string) The id of a Box user who this collaboration applies to. Required unless providing the EmailAddress.)
        */
        this.set_UserID = function(value) {
            this.setInput("UserID", value);
        }

        /*
        Set the value of the VaultFile input for this Choreo. ((optional, vault file) The path to a vault file that you want to upload. Required unless using the FileContents input.)
        */

}

/*
A ResultSet with methods tailored to the values returned by the AddCollaboration Choreo.
The ResultSet object is used to retrieve the results of a Choreo execution.
*/

var AddCollaborationResultSet = function(resultStream) {
    AddCollaborationResultSet.super_.call(this, resultStream);
        /*
        Retrieve the value for the "Response" output from this Choreo execution. ((json) The response from Box.)
        */
        this.get_Response = function() {
            return this.getResult("Response");
        }
}

util.inherits(AddCollaboration, choreography.Choreography);
util.inherits(AddCollaborationInputSet, choreography.InputSet);
util.inherits(AddCollaborationResultSet, choreography.ResultSet);
exports.AddCollaboration = AddCollaboration;

/*
    DeleteCollaboration
    Deletes a single collaboration.
*/

var DeleteCollaboration = function(session) {
    /*
        Create a new instance of the DeleteCollaboration Choreo. A TembooSession object, containing a valid
        set of Temboo credentials, must be supplied.
	*/
    var location = "/Library/Box/Collaborations/DeleteCollaboration"
    DeleteCollaboration.super_.call(this, session, location);

    /*
    Define a callback that will be used to appropriately format the results of this Choreo.
    */
    var newResultSet = function(resultStream) {
        return new DeleteCollaborationResultSet(resultStream);
    }

	/*
	Obtain a new InputSet object, used to specify the input values for an execution of this Choreo.
	*/
    this.newInputSet = function() {
        return new DeleteCollaborationInputSet();
    }

	/*
	Execute this Choreo with the specified inputs, calling the specified callback upon success,
	and the specified errorCallback upon error.
	*/
    this.execute = function(inputs, callback, errorCallback) {
        this._execute(inputs, newResultSet, callback, errorCallback);
    }
}

/*
An InputSet with methods appropriate for specifying the inputs to the DeleteCollaboration
Choreo. The InputSet object is used to specify input parameters when executing this Choreo.
*/

var DeleteCollaborationInputSet = function() {
    DeleteCollaborationInputSet.super_.call(this);
        /*
        Set the value of the AccessToken input for this Choreo. ((required, string) The access token retrieved during the OAuth2 process.)
        */
        this.set_AccessToken = function(value) {
            this.setInput("AccessToken", value);
        }

        /*
        Set the value of the CollaborationID input for this Choreo. ((required, string) The id of the collaboration to remove from a folder.)
        */
        this.set_CollaborationID = function(value) {
            this.setInput("CollaborationID", value);
        }

        /*
        Set the value of the VaultFile input for this Choreo. ((optional, vault file) The path to a vault file that you want to upload. Required unless using the FileContents input.)
        */

}

/*
A ResultSet with methods tailored to the values returned by the DeleteCollaboration Choreo.
The ResultSet object is used to retrieve the results of a Choreo execution.
*/

var DeleteCollaborationResultSet = function(resultStream) {
    DeleteCollaborationResultSet.super_.call(this, resultStream);
        /*
        Retrieve the value for the "Response" output from this Choreo execution. ((json) The response from Box.)
        */
        this.get_Response = function() {
            return this.getResult("Response");
        }
}

util.inherits(DeleteCollaboration, choreography.Choreography);
util.inherits(DeleteCollaborationInputSet, choreography.InputSet);
util.inherits(DeleteCollaborationResultSet, choreography.ResultSet);
exports.DeleteCollaboration = DeleteCollaboration;

/*
    GetCollaboration
    Retrieves an existing collaboration.
*/

var GetCollaboration = function(session) {
    /*
        Create a new instance of the GetCollaboration Choreo. A TembooSession object, containing a valid
        set of Temboo credentials, must be supplied.
	*/
    var location = "/Library/Box/Collaborations/GetCollaboration"
    GetCollaboration.super_.call(this, session, location);

    /*
    Define a callback that will be used to appropriately format the results of this Choreo.
    */
    var newResultSet = function(resultStream) {
        return new GetCollaborationResultSet(resultStream);
    }

	/*
	Obtain a new InputSet object, used to specify the input values for an execution of this Choreo.
	*/
    this.newInputSet = function() {
        return new GetCollaborationInputSet();
    }

	/*
	Execute this Choreo with the specified inputs, calling the specified callback upon success,
	and the specified errorCallback upon error.
	*/
    this.execute = function(inputs, callback, errorCallback) {
        this._execute(inputs, newResultSet, callback, errorCallback);
    }
}

/*
An InputSet with methods appropriate for specifying the inputs to the GetCollaboration
Choreo. The InputSet object is used to specify input parameters when executing this Choreo.
*/

var GetCollaborationInputSet = function() {
    GetCollaborationInputSet.super_.call(this);
        /*
        Set the value of the AccessToken input for this Choreo. ((required, string) The access token retrieved during the OAuth process.)
        */
        this.set_AccessToken = function(value) {
            this.setInput("AccessToken", value);
        }

        /*
        Set the value of the CollaborationID input for this Choreo. ((required, string) The id of the collaboration to retrieve.)
        */
        this.set_CollaborationID = function(value) {
            this.setInput("CollaborationID", value);
        }

        /*
        Set the value of the Fields input for this Choreo. ((optional, string) A comma-separated list of fields to include in the response.)
        */
        this.set_Fields = function(value) {
            this.setInput("Fields", value);
        }

        /*
        Set the value of the VaultFile input for this Choreo. ((optional, vault file) The path to a vault file that you want to upload. Required unless using the FileContents input.)
        */

}

/*
A ResultSet with methods tailored to the values returned by the GetCollaboration Choreo.
The ResultSet object is used to retrieve the results of a Choreo execution.
*/

var GetCollaborationResultSet = function(resultStream) {
    GetCollaborationResultSet.super_.call(this, resultStream);
        /*
        Retrieve the value for the "Response" output from this Choreo execution. ((json) The response from Box.)
        */
        this.get_Response = function() {
            return this.getResult("Response");
        }
}

util.inherits(GetCollaboration, choreography.Choreography);
util.inherits(GetCollaborationInputSet, choreography.InputSet);
util.inherits(GetCollaborationResultSet, choreography.ResultSet);
exports.GetCollaboration = GetCollaboration;

/*
    GetPendingCollaborations
    Retrieves all pending collaboration invites for a user.
*/

var GetPendingCollaborations = function(session) {
    /*
        Create a new instance of the GetPendingCollaborations Choreo. A TembooSession object, containing a valid
        set of Temboo credentials, must be supplied.
	*/
    var location = "/Library/Box/Collaborations/GetPendingCollaborations"
    GetPendingCollaborations.super_.call(this, session, location);

    /*
    Define a callback that will be used to appropriately format the results of this Choreo.
    */
    var newResultSet = function(resultStream) {
        return new GetPendingCollaborationsResultSet(resultStream);
    }

	/*
	Obtain a new InputSet object, used to specify the input values for an execution of this Choreo.
	*/
    this.newInputSet = function() {
        return new GetPendingCollaborationsInputSet();
    }

	/*
	Execute this Choreo with the specified inputs, calling the specified callback upon success,
	and the specified errorCallback upon error.
	*/
    this.execute = function(inputs, callback, errorCallback) {
        this._execute(inputs, newResultSet, callback, errorCallback);
    }
}

/*
An InputSet with methods appropriate for specifying the inputs to the GetPendingCollaborations
Choreo. The InputSet object is used to specify input parameters when executing this Choreo.
*/

var GetPendingCollaborationsInputSet = function() {
    GetPendingCollaborationsInputSet.super_.call(this);
        /*
        Set the value of the AccessToken input for this Choreo. ((required, string) The access token retrieved during the OAuth2 process.)
        */
        this.set_AccessToken = function(value) {
            this.setInput("AccessToken", value);
        }

        /*
        Set the value of the Fields input for this Choreo. ((optional, string) A comma-separated list of fields to include in the response.)
        */
        this.set_Fields = function(value) {
            this.setInput("Fields", value);
        }

        /*
        Set the value of the VaultFile input for this Choreo. ((optional, vault file) The path to a vault file that you want to upload. Required unless using the FileContents input.)
        */

}

/*
A ResultSet with methods tailored to the values returned by the GetPendingCollaborations Choreo.
The ResultSet object is used to retrieve the results of a Choreo execution.
*/

var GetPendingCollaborationsResultSet = function(resultStream) {
    GetPendingCollaborationsResultSet.super_.call(this, resultStream);
        /*
        Retrieve the value for the "Response" output from this Choreo execution. ((json) The response from Box.)
        */
        this.get_Response = function() {
            return this.getResult("Response");
        }
}

util.inherits(GetPendingCollaborations, choreography.Choreography);
util.inherits(GetPendingCollaborationsInputSet, choreography.InputSet);
util.inherits(GetPendingCollaborationsResultSet, choreography.ResultSet);
exports.GetPendingCollaborations = GetPendingCollaborations;

/*
    UpdateCollaboration
    Edits an existing collaboration.
*/

var UpdateCollaboration = function(session) {
    /*
        Create a new instance of the UpdateCollaboration Choreo. A TembooSession object, containing a valid
        set of Temboo credentials, must be supplied.
	*/
    var location = "/Library/Box/Collaborations/UpdateCollaboration"
    UpdateCollaboration.super_.call(this, session, location);

    /*
    Define a callback that will be used to appropriately format the results of this Choreo.
    */
    var newResultSet = function(resultStream) {
        return new UpdateCollaborationResultSet(resultStream);
    }

	/*
	Obtain a new InputSet object, used to specify the input values for an execution of this Choreo.
	*/
    this.newInputSet = function() {
        return new UpdateCollaborationInputSet();
    }

	/*
	Execute this Choreo with the specified inputs, calling the specified callback upon success,
	and the specified errorCallback upon error.
	*/
    this.execute = function(inputs, callback, errorCallback) {
        this._execute(inputs, newResultSet, callback, errorCallback);
    }
}

/*
An InputSet with methods appropriate for specifying the inputs to the UpdateCollaboration
Choreo. The InputSet object is used to specify input parameters when executing this Choreo.
*/

var UpdateCollaborationInputSet = function() {
    UpdateCollaborationInputSet.super_.call(this);
        /*
        Set the value of the AccessToken input for this Choreo. ((required, string) The access token retrieved during the OAuth2 process.)
        */
        this.set_AccessToken = function(value) {
            this.setInput("AccessToken", value);
        }

        /*
        Set the value of the CollaborationID input for this Choreo. ((required, string) The id of the collaboration to edit.)
        */
        this.set_CollaborationID = function(value) {
            this.setInput("CollaborationID", value);
        }

        /*
        Set the value of the Fields input for this Choreo. ((optional, string) A comma-separated list of fields to include in the response.)
        */
        this.set_Fields = function(value) {
            this.setInput("Fields", value);
        }

        /*
        Set the value of the Role input for this Choreo. ((conditional, string) The access level of the collaboration. Valid values are "viewer" or "editor". Defaults to "viewer". This value can only be updated by the owner of the folder.)
        */
        this.set_Role = function(value) {
            this.setInput("Role", value);
        }

        /*
        Set the value of the Status input for this Choreo. ((conditional, string) Whether this collaboration has been accepted. Valid values are: "accepted" or "rejected". This value can only be updated by the user who has been invited to the collaboration.)
        */
        this.set_Status = function(value) {
            this.setInput("Status", value);
        }

        /*
        Set the value of the VaultFile input for this Choreo. ((optional, vault file) The path to a vault file that you want to upload. Required unless using the FileContents input.)
        */

}

/*
A ResultSet with methods tailored to the values returned by the UpdateCollaboration Choreo.
The ResultSet object is used to retrieve the results of a Choreo execution.
*/

var UpdateCollaborationResultSet = function(resultStream) {
    UpdateCollaborationResultSet.super_.call(this, resultStream);
        /*
        Retrieve the value for the "Response" output from this Choreo execution. ((json) The response from Box.)
        */
        this.get_Response = function() {
            return this.getResult("Response");
        }
}

util.inherits(UpdateCollaboration, choreography.Choreography);
util.inherits(UpdateCollaborationInputSet, choreography.InputSet);
util.inherits(UpdateCollaborationResultSet, choreography.ResultSet);
exports.UpdateCollaboration = UpdateCollaboration;

/******************************************************************************
Begin output wrapper classes
******************************************************************************/

/**
 * Utility function, to retrieve the array-type sub-item specified by the key from the parent (array) specified by the item.
 * Returns an empty array if key is not present.
 */
function getSubArrayByKey(item, key) {
	var val = item[key];
	if(val == null) {
		val = new Array();
	}
	return val;
}


text:
<!DOCTYPE html>

		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, initial-scale=1">
		<title>jQuery Mobile Panel Integration Test</title>

		<link rel="stylesheet"  href="../../../css/themes/default/jquery.mobile.css" />
		<link rel="stylesheet" href="../../../external/qunit.css"/>

jQuery Mobile Panel Integration Test

Contents of a panel.

Contents of a panel.

Contents of a panel.

Contents of a panel.

Contents of a panel.

Contents of a panel.

Contents of a panel.

Contents of a panel.

Contents of a panel.

Contents of a panel.

				Close panel

Panel Test

Panels

				Open Panel
				Open Panel
				Open Panel
				Open Panel
				Open Panel
				Open Panel
				Open Panel
				Open Panel
				Open Panel
				Open Panel

redpajama_set_name: RedPajamaGithub


text:
package cinemovie.core;

import java.time.Year;

public class Filme {
  private int id;
  private String nome;
  private String capa;
  private Year anoLancamento;
  private String sinopse;
  private String autores;
  private String atores;
  private Genero genero;
  private int faixaEtaria;
  private int duracao;
  private Double avaliacao;
  public Filme() {}
  public Filme(int id, String nome, String capa, Year anoLancamento,
    String sinopse, String autores, String atores, Genero genero,
    int faixaEtaria, int duracao, Double avaliacao) {
    this.id = id;
    this.nome = nome;
    this.capa = capa;
    this.anoLancamento = anoLancamento;
    this.sinopse = sinopse;
    this.autores = autores;
    this.atores = atores;
    this.genero = genero;
    this.faixaEtaria = faixaEtaria;
    this.duracao = duracao;
    this.avaliacao = avaliacao;
  }
  public int getId() {
    return id;
  }
  public void setId(int id) {
    this.id = id;
  }
  public String getNome() {
    return nome;
  }
  public void setNome(String nome) {
    this.nome = nome;
  }
  public String getCapa() {
    return capa;
  }
  public void setCapa(String capa) {
    this.capa = capa;
  }
  public Year getAnoLancamento() {
    return anoLancamento;
  }
  public void setAnoLancamento(Year anoLancamento) {
    this.anoLancamento = anoLancamento;
  }
  public String getSinopse() {
    return sinopse;
  }
  public void setSinopse(String sinopse) {
    this.sinopse = sinopse;
  }
  public String getAutores() {
    return autores;
  }
  public void setAutores(String autores) {
    this.autores = autores;
  }
  public String getAtores() {
    return atores;
  }
  public void setAtores(String atores) {
    this.atores = atores;
  }
  public Genero getGenero() {
    return genero;
  }
  public void setGenero(Genero genero) {
    this.genero = genero;
  }
  public int getFaixaEtaria() {
    return faixaEtaria;
  }
  public void setFaixaEtaria(int faixaEtaria) {
    this.faixaEtaria = faixaEtaria;
  }
  public int getDuracao() {
    return duracao;
  }
  public void setDuracao(int duracao) {
    this.duracao = duracao;
  }
  public Double getAvaliacao() {
    return avaliacao;
  }
  public void setAvaliacao(Double avaliacao) {
    this.avaliacao = avaliacao;
  }
}


text:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using DG.Tweening;

/* This defines the ExampleGun as "inheriting" from Weapon.cs because we put
 *                       this \/   after the semicolon. That means we can "override" the functions inside Weapon with our own details of how they actually do stuff.*/
public class ExampleGun : Weapon
{
	 /*  Overrides of Weapon.cs  */

    public override void PrimaryFireStart()
    {
		Debug.Log("EXAMPLE GUN CLASS: PRIMARY FIRE START!");
		isPrimaryFiring = true;
		currentFiringTimer = nextPrimaryFireTime;
    }

	public override void PrimaryFireEnd()
	{
		Debug.Log("EXAMPLE GUN CLASS: PRIMARY FIRE END!");
		isPrimaryFiring = false;
		transform.DOLocalRotate(Vector3.zero, .5f, RotateMode.Fast);
		transform.DOLocalMove(Vector3.zero, .5f);
	}

	//we could still make an override function for the Reload() and SecondaryFireStart() and SecondaryFireEnd(), but we don't need them for this example

	/* End of Overrides */

	/* Custom fields for Example Gun */
	/* These are all specific to our gun, which is basically a machine gun that fires rigidbody bullets */

	public ParticleSystem muzzleFlashParticles;
	public Transform muzzlePoint;
	public Rigidbody bulletPrefab;
	public float bulletVelocity;
	public float recoilRotationAmount;
	public float recoilPositionAmount;
	public float primaryFireRepeatDelay;

	/* Start of custom functions for Example Gun */

	/* This is a new method that doesn't override anything in Weapon.cs
	 * Notice that PrimaryFireStart is able to call it though. */
	public void FireBullet()
	{
		muzzleFlashParticles.Emit(1);
		GameObject lastBullet = Instantiate(bulletPrefab.gameObject, muzzlePoint.transform.position, muzzlePoint.transform.rotation, null);
		Rigidbody lastBulletRB = lastBullet.GetComponent<Rigidbody>();
		lastBulletRB.velocity = muzzlePoint.forward * bulletVelocity;
		transform.DOPunchRotation(new Vector3(recoilRotationAmount, 0f, 0f), .25f);
		transform.DOPunchPosition(transform.forward * recoilPositionAmount, .25f);
	}

	//This section is for making the gun repeat fire, again not part of Weapon.cs
	//Not every gun should repeat fire the same way. Take a gravity gun for instance. It would just start and stop.
	private bool isPrimaryFiring = false;
	private float nextPrimaryFireTime = 0f;
	private float currentFiringTimer = 0f;

	public void Update()
	{
		if (isPrimaryFiring)
		{
			if (currentFiringTimer >= nextPrimaryFireTime)
			{
				FireBullet();
				nextPrimaryFireTime = primaryFireRepeatDelay;
				currentFiringTimer = 0f;
			}
			else
			{
				currentFiringTimer += Time.deltaTime;
			}
		}
	}
}


text:
confirmadon
========

A client site / ajax (backend agnostic) pagination system

### Basic Usage

````html
<a href="?remove=1" class="remove">Remove Me</a>
````

````javascript
$('.remove').confirmadon();
````

### Options / Defaults

````json
{
    bindTo: null,
    replacements: {
        title: 'Confirm',
        message: 'Are you sure you want to perform this action?',
        yes: 'Yes',
        no: 'No'
    },
    template:   '<div class="confirmadon-wrap" style="background:rgba(0,0,0,0.5); position: fixed; top: 0; left: 0; right: 0; bottom: 0; z-index: 20000;">'+
                    '<div class="confirmadon-modal" style="padding:20px; background:#fff; position: fixed; top: 50%; left: 50%; width: 240px; height: 140px; margin-top: -70px; margin left: -120px; z-index: 20001;">' +
                        '<h4>{{title}}</h4><p>{{message}}</p><a class="confirmadon-yes" href="">{{yes}}</a><a class="confirmadon-no" href="">{{no}}</a>' +
                    '</div>' +
                '</div>',
    noSelector: '.confirmadon-no',
    yesSelector: '.confirmadon-yes',
    visibleClass: 'confirmadon-visible',
    onBeforeShow: null,     // (confirmadon)          this = triggering elem
    onAfterShow: null,      // (confirmadon, $dialog) this = triggering elem
    onBeforeHide: null,     // (confirmadon, $dialog) this = triggering elem
    onAfterHide: null,      // (confirmadon)          this = triggering elem
    onAfterConfirm: null,   // (confirmadon)          this = triggering elem
    onAfterDeny: null,      // (confirmadon)          this = triggering elem
    fade: true,
    applyDefaultOnConfirm: true
};
````

### Attribute Based Overrides

- `data-template` - an html string or selector for the template
- `data-title` - the message that gets parsed out into the teplate's `{{title}}` token
- `data-message` - the message that gets parsed out into the teplate's `{{message}}` token
- `data-yes` - the message that gets parsed out into the teplate's `{{yes}}` token
- `data-no` - the message that gets parsed out into the teplate's `{{no}}` token

### Todo

- Finish docs
- Make more examples
- look at ordering of events - maybe use native events in order to ensure it fires before jquery handlers


text:
package org.apache.lucene.analysis.core;

import org.apache.lucene.analysis.Analyzer;

/**
 * "Tokenizes" the entire stream as a single token. This is useful
 * for data like zip codes, ids, and some product names.
 */
public final class KeywordAnalyzer extends Analyzer {
  public KeywordAnalyzer() {
  }

  @Override
  protected TokenStreamComponents createComponents(final String fieldName) {
    return new TokenStreamComponents(new KeywordTokenizer());
  }
}


text:
ACTUALDIR="./"

LOGFILEINS="install.log"
GRUPO="${1-$PWD/GRUPO07}" # usa el primer parámetro o el directorio actual
CONFDIRINSTALL="./conf"

CONFDIR="$GRUPO/config"
CONFIGFILE="$CONFDIR/CIPAK.cnf"
CONFIGFILETEMP="$CONFDIRINSTALL/CIPAK.temp"

pathResult=""
BINDIR="$GRUPO/binarios"
MAEDIR="$GRUPO/maestros"
ARRIDIR="$GRUPO/arribados"
#$GRUPO/datos #con los archivos de la catedra
BACKUPDIR="$GRUPO/respaldo"
OKDIR="$GRUPO/aceptados"
PROCDIR="$GRUPO/procesados"
INFODIR="$GRUPO/informes"
LOGDIR="$GRUPO/bitacoras"
NOKDIR="$GRUPO/rechazados"
DATOSDIR="./mae"
DATASIZE=100 #100Mb  #DATASIZE=104857600 #100Mb
LOGEXT=".log"
LOGSIZE=400 #400Kb #LOGSIZE=409600 #400Kb
LOGCOMMAND="./bin/GrabarBitacora.sh"
VERSIONPERL=5

SLEEPTIME=20
#*************************** Funciones ***************************
function pause() {
   read -p "$*"
}

function log() {
	command=$1
	message=$2
	type=$3
	if [ $# -ge 2 ] && [ $# -le 3 ]
	then
		$LOGCOMMAND "$command" "$message" "$type"
	fi
}

function initInstalation(){
	while [ -z $optSelect ]
	do
		clear
	#Verifico version de perl instalada
	log "Installer" "Verificando versión de perl instalada" "I"

	PERLVERSION=$(perl -v | grep 'v[0-9]\.[0-9]\+\.[0-9]*' -o) #obtengo la version de perl
	NUMPERLVERSION=$(echo $PERLVERSION | cut -d"." -f1 | sed 's/^v\([0-9]\)$/\1/') #obtengo el primer numero

	if [ -z "$NUMPERLVERSION" ] || [ $NUMPERLVERSION -lt $VERSIONPERL ]
	then
		echo "Para ejecutar el sistema CIPAK es necesario contar con Perl $VERSIONPERL o superior."
		echo "Efectúe su instalación e inténtelo nuevamente."
		echo "Proceso de Instalación Cancelado"
		log  "Installer" "Para ejecutar el sistema CIPAK es necesario contar con Perl $VERSIONPERL o superior." "E"
		log  "Installer"  "Efectúe su instalación e inténtelo nuevamente." "E"
		log  "Installer"  "Proceso de Instalación Cancelado" "E"
		pause 'Press [Enter] key to continue...'
		exit 3;
	else
		echo ""
		echo "PERL Instalada, Version: $PERLVERSION"
		#echo "PERL Instalada, Version:" $(perl -v)
		echo ""
		log "Installer" "PERL instalado. Version:$PERLVERSION" "I"
	fi

		echo '
		*************************************************************
		*             Proceso de Instalación de "CIPAK"             *
		*   Tema K Copyright © Grupo 7 - Primer Cuatrimestre 2016   *
		*************************************************************
    A T E N C I O N: Al instalar UD. expresa aceptar los términos y condiciones
    del "ACUERDO DE LICENCIA DE SOFTWARE" incluido en este paquete.
    '

		read -p " Acepta?  Si – No: " optSelect
		optSelect=$(echo $optSelect | grep '^[Ss][Ii]$\|^[Nn][Oo]$' | tr '[:upper:]' '[:lower:]')
	done

	#si el usuario no acepta finalizo el script
	if [ $optSelect = "no" ]
	then
		log "Installer" "Usuario NO acepto ACUERDO DE LICENCIA DE SOFTWARE"
		pause 'Press [Enter] key to continue...'
		exit 2
	fi

	#Usuario Acepto los terminos
	log "Installer" "Usuario acepto ACUERDO DE LICENCIA DE SOFTWARE" "I"

	echo "configuracion temporal"
	#Si existe vuelvo a generar el archivo de configuracion temporal
	if [ -a $CONFIGFILETEMP ]
	then
		log "Installer" "Genero archivo de configuracion temporal" "I"
		echo "Genero archivo de configuracion temporal"
		rm $CONFIGFILETEMP
		#touch $CONFIGFILETEMP
	fi

	echo "GRUPO=$GRUPO=$USER=`date +'%d-%m-%Y %H:%M:%S'`" >> $CONFIGFILETEMP

	echo "CONFDIR=$CONFDIR=$USER=`date +'%d-%m-%Y %H:%M:%S'`" >> $CONFIGFILETEMP

	readNumber "Defina tiempo de espera entre ejecuciones de Procesar Ofertas ($SLEEPTIME)" "$SLEEPTIME"
	SLEEPTIME=$numberTemp
	echo "SLEEPTIME=$SLEEPTIME=$USER=`date +'%d-%m-%Y %H:%M:%S'`" >> $CONFIGFILETEMP

	getDirectoryPath "Defina el directorio de instalación de los ejecutables ($BINDIR):" "$BINDIR"
	BINDIR=$pathTemp
	echo "BINDIR=$pathTemp=$USER=`date +'%d-%m-%Y %H:%M:%S'`" >> $CONFIGFILETEMP

	getDirectoryPath "Defina directorio para maestros ($MAEDIR):" "$MAEDIR"
	MAEDIR=$pathTemp
	echo "MAEDIR=$pathTemp=$USER=`date +'%d-%m-%Y %H:%M:%S'`" >> $CONFIGFILETEMP

	getDirectoryPath "Defina el Directorio de recepción de los archivos de novedades ($ARRIDIR):" "$ARRIDIR"
	ARRIDIR=$pathTemp
	echo "ARRIDIR=$pathTemp=$USER=`date +'%d-%m-%Y %H:%M:%S'`" >> $CONFIGFILETEMP

	readNumber "Defina espacio mínimo libre para la recepción de archivos de novedades en Mbytes ($DATASIZE)" "$DATASIZE"
	DATASIZETEMP=$numberTemp
	DATASIZEDIR=$(df -B1024 "$ACTUALDIR" | tail -n1 | sed -e"s/\s\{1,\}/;/g" | cut -f4 -d';')
	DATASIZEDIR=$(echo "scale=0 ; $DATASIZEDIR/1024" | bc -l) #lo paso a Mb

	while [ $DATASIZEDIR -lt $DATASIZETEMP ]
	do
		echo "Insuficiente espacio en disco."
		echo "Espacio disponible: $DATASIZEDIR Mb."
		echo "Espacio requerido $DATASIZETEMP Mb"
		echo "Inténtelo nuevamente."
		echo ""
		readNumber "Defina espacio mínimo libre para la recepción de archivos de novedades en Mbytes ($DATASIZE)" "$DATASIZE"
		DATASIZETEMP=$numberTemp
	done
	DATASIZE=$DATASIZETEMP
	echo "DATASIZE=$DATASIZETEMP=$USER=`date +'%d-%m-%Y %H:%M:%S'`" >> $CONFIGFILETEMP

	getDirectoryPath "Defina el directorio de grabación de los archivos aceptados ($OKDIR):" "$OKDIR"
	OKDIR=$pathTemp
	echo "OKDIR=$pathTemp=$USER=`date +'%d-%m-%Y %H:%M:%S'`" >> $CONFIGFILETEMP

	#Ofertas procesadas -> PROCDIR
	getDirectoryPath "Defina el directorio de grabación de los registros ofertas procesadas ($PROCDIR):" "$PROCDIR"
	PROCDIR=$pathTemp
	echo "PROCDIR=$pathTemp=$USER=`date +'%d-%m-%Y %H:%M:%S'`" >> $CONFIGFILETEMP

	#Directorio de grabacion de los reportes
	getDirectoryPath "Defina el directorio de grabación los reportes ($INFODIR):" "$INFODIR"
	INFODIR=$pathTemp
	echo "INFODIR=$pathTemp=$USER=`date +'%d-%m-%Y %H:%M:%S'`" >> $CONFIGFILETEMP

	getDirectoryPath "Defina el directorio de logs ($LOGDIR):" "$LOGDIR"
	LOGDIR=$pathTemp
	echo "LOGDIR=$pathTemp=$USER=`date +'%d-%m-%Y %H:%M:%S'`" >> $CONFIGFILETEMP

	getExtension "Ingrese la extensión para los archivos de log ($LOGEXT): " "$LOGEXT"
	LOGEXT=$extDefault
	echo "LOGEXT=$extDefault=$USER=`date +'%d-%m-%Y %H:%M:%S'`" >> $CONFIGFILETEMP

	readNumber "Defina el tamaño máximo para los archivos $LOGEXT en Kbytes ($LOGSIZE)" "$LOGSIZE"
	LOGSIZETEMP=$numberTemp
	LOGSIZEDISP=$(df -B1024 "$ACTUALDIR" | tail -n1 | sed -e"s/\s\{1,\}/;/g" | cut -f4 -d';')

	while [ $LOGSIZEDISP -lt $LOGSIZETEMP ]
	do
		echo "Insuficiente espacio en disco."
		echo "Espacio disponible: $LOGSIZEDISP Kb."
		echo "Espacio requerido $LOGSIZETEMP Kb"
		echo "Cancele la instalación o inténtelo nuevamente."
		echo ""
		readNumber "Defina el tamaño máximo para los archivos $LOGEXT en Kbytes ($LOGSIZE)" "$LOGSIZE"
		LOGSIZETEMP=$numberTemp
	done
	LOGSIZE=$LOGSIZETEMP
	echo "LOGSIZE=$LOGSIZETEMP=$USER=`date +'%d-%m-%Y %H:%M:%S'`" >> $CONFIGFILETEMP

	getDirectoryPath "Defina el directorio de grabación los archivos rechazados ($NOKDIR):" "$NOKDIR"
	NOKDIR=$pathTemp
	echo "NOKDIR=$pathTemp=$USER=`date +'%d-%m-%Y %H:%M:%S'`" >> $CONFIGFILETEMP

	#Agrego directorio de Backup al archivo de configuracion
	echo "BACKUPDIR=$BACKUPDIR=$USER=`date +'%d-%m-%Y %H:%M:%S'`" >> $CONFIGFILETEMP

}

function getDirectoryPath(){
	# echo $1
	# echo $2
	msj=$1
	pathDefault=$2
	pathTemp=""

	while [ -z $pathTemp ]
	do
		read -p "$msj" pathTemp
		#echo "de nuevo: $pathTemp"
		if [ -z "$pathTemp" ]
		then
			pathTemp=$pathDefault
		else
			#pathTemp=$(echo $pathTemp | grep '^/.*$' )
			#Valido caracteres alfanumericos en path
			pathTemp=$(echo "$pathTemp" | grep '^/[a-zA-Z0-9]*$' )
			#valido que no se pueda seleccionar el directorio conf
			pathTemp=$(echo "$pathTemp" | grep -v '^/conf$' )
			if [ ! -z "$pathTemp" -a "$pathTemp" != " " ]
			then
				pathTemp=$GRUPO$pathTemp
			else
				echo 'Path invalido, ingrese nuevamente'
			fi
		fi
	done
}

function getExtension(){
	msj=$1
	extDefault=$2
	extTemp=""
	while [ -z $extTemp ]
		do
		read -p "$msj" extTemp
		if [ -z $extTemp ]
		then
			extDefault=$2
			extTemp=$2
		else
			extTemp=$(echo $extTemp | grep '^\..*$' )
			if [ ! -z "$extTemp" -a "$extTemp" != " " ]
			then
				extDefault=$extTemp
			fi
		fi
	done
}

function readNumber(){
	msj=$1
	numberDefault=$2
	numberTemp=""

	while [ -z $numberTemp ]
	do
		read -p "$msj: " result

		#Si pulso enter pongo el valor por defecto
		if [ -z $result ]
		then
			result=$numberDefault
		fi

		numberTemp=$(echo $result | grep '^[0-9]*$')
	done

	return $numberTemp
}

function executeInstaler(){
	STATUSINST=$1
	while [ -z $optIniciar ]
	do
		clear
		echo '
		*************************************************************
		*             Proceso de Instalación de "CIPAK"             *
		*   Tema K Copyright © Grupo 7 - Primer Cuatrimestre 2016   *
		*************************************************************
    '
    echo "
	Directorio de Configuracion: $CONFDIR
	Directorio de Ejecutables:   $BINDIR
	Directorio de  Maestros: $MAEDIR
	Directorio de recepción de archivos de novedades:  $ARRIDIR
	Espacio mínimo libre para arribos: $DATASIZE Mb
	Directorio de  archivos aceptados: $OKDIR
	Directorio de ofertas procesadas:  $PROCDIR
	Directorio de reportes: $INFODIR
	Directorio de Logs de Comandos: $LOGDIR/<comando>$LOGEXT
	Tamaño máximo para los archivos de log del sistema: $LOGSIZE Kb
	Directorio de archivos rechazados: $NOKDIR
	Estado de la instalación: $STATUSINST
		"

		read -p "Iniciando Instalación. Esta Ud. seguro? (Si - No): " optIniciar
		optIniciar=$(echo $optIniciar | grep '^[Ss][Ii]$\|^[Nn][Oo]$' | tr '[:upper:]' '[:lower:]')
	done

	#si el usuario no acepta finalizo el script
	if [ $optIniciar = "no" ]
	then
		clear
		log "Installer" "Usuario No Quiere realizar la instalacion"
		pause 'Press [Enter] key to continue...'
		exit 4
	fi

	if [ -d "$GRUPO" ]
	then
		deletDirOpt=""
		while [ -z $deletDirOpt ]
		do
			read -p "Existen una instalación en el directorio $GRUPO, se borraran todos los datos para realizar la nueva instalacion, esta seguro? (Si - No): " deletDirOpt
			optSelect=$(echo $deletDirOpt | grep '^[Ss][Ii]$\|^[Nn][Oo]$' | tr '[:upper:]' '[:lower:]')
		done

		if [ $deletDirOpt = "no" ]
		then
			log "Installer" "El usuario no quiere eliminar el directorio $GRUPO existente" "I"
			pause 'Press [Enter] key to continue...'
			exit 5
		else
			log "Installer" "Eliminando contenido de directorio $GRUPO" "I"
			rm -rf "$GRUPO"
		fi
	fi

	clear
	echo "Creando Estructuras de directorio. . . . "
	echo "$BINDIR"
	mkdir -p "$BINDIR"

	echo "$MAEDIR"
	mkdir -p "$MAEDIR"

	echo "$OKDIR"
	mkdir -p "$OKDIR"

	echo "$PROCDIR"
	mkdir -p "$PROCDIR"

	echo "$INFODIR"
	mkdir -p "$INFODIR"

	echo "$LOGDIR"
	mkdir -p "$LOGDIR"

	echo "$ARRIDIR"
	mkdir -p "$ARRIDIR"

	echo "$NOKDIR"
	mkdir -p "$NOKDIR"

	mkdir -p "$CONFDIR"

	#cp "MoverA.sh" "$BINDIR/MoverA.sh"
	#chmod +r+x "$BINDIR/MoverA.sh"

	#Mover los ejecutables y funciones al directorio BINDIR mostrando el siguiente mensaje
	echo "Instalando Programas y Funciones"
	#Muevo el script para mover archivos
	#for i in $(ls *.sh *.pl)
	for i in $(ls bin/*.sh)
	 do
		cp "$i" "$BINDIR/"
	done
	for i in $(ls bin/*.pl)
	 do
		cp "$i" "$BINDIR/"
	done

	for i in $(ls "$BINDIR")
	 do
		chmod u+x "$BINDIR/$i"
	done

	#Muevo la configuracion creada por el instalador.
	#for i in $(ls $CONFDIRINSTALL)
	#do
	#	cp "$CONFDIRINSTALL/$i" "$CONFDIR/$i"
	#done

	LOGCOMMAND="$BINDIR/GrabarBitacora.sh"

	#Mover los archivos maestros y tablas al directorio MAEDIR mostrando el siguiente mensaje
	echo "Instalando Archivos Maestros y Tablas"
	for i in $(ls $DATOSDIR/*)
	 do
		cp "$i" "$MAEDIR/"
	done

	#Actualizar el archivo de configuración mostrando el siguiente mensaje
	echo "Actualizando la configuración del sistema"
	log "Installer" "Actualizando la configuración del sistema" "I"

	log "Installer" "Convirtiendo $CONFDIR/  ->  $CONFIGFILE" "I"

	cp "$CONFIGFILETEMP" "$CONFIGFILE"

	#copiando log de instalacion a bitacoras.
	cp "$CONFDIRINSTALL/Installer.log" "$LOGDIR/Installer.log"

	echo "Instalación CONCLUIDA"
	log "Installer" "Instalación CONCLUIDA" "I"

	#Copio todo al directorio de respaldo
	mkdir -p $BACKUPDIR
  mkdir -p "$BACKUPDIR"/mae
  mkdir -p "$BACKUPDIR"/bin

	for i in $(ls bin)
	 do
		cp "bin/$i" "$BACKUPDIR/bin/$i"
	done

  for i in $(ls mae)
   do
    cp "mae/$i" "$BACKUPDIR/mae/$i"
  done

	#Elimino Archivos
	#rm -rf ./Datos
	rm -rf $CONFDIRINSTALL
	#rm *.sh
	#rm *.pl
	#rm *.md
}

#Si no existe la carpeta de configuracion la creo.
if [ ! -d $CONFDIRINSTALL ]
	then
	mkdir -p $CONFDIRINSTALL
fi

#Otorgo permisos a los comando que voy a utilizar
chmod u+r+x $LOGCOMMAND

#Inicio del instalador
log "Installer" "Inicio de Ejecución de Installer"

echo "Log de la instalación: $CONFDIRINSTALL/$LOGFILEINS"
log "Installer" "Log de la instalación: $CONFDIRINSTALL/$LOGFILEINS"

echo "Directorio predefinido de configuración: $CONFDIR"
log "Installer" "Directorio predefinido de configuración: $CONFDIR"

#Detecto si hay una instalacion previa
if [ -a $CONFIGFILETEMP ]
then
	#Hay una instalación previa
	log "Installer" "Hay una instalación" "I"

	BASEDIRTMP=$(grep '^GRUPO' $CONFIGFILETEMP | awk -F"=" '{print $2}')
	CONFIGDIRTMP=$(grep '^CONFDIR' $CONFIGFILETEMP | awk -F"=" '{print $2}')
	SLEEPTIMETMP=$(grep '^SLEEPTIME' $CONFIGFILETEMP | awk -F"=" '{print $2}')
	BINDIRTMP=$(grep '^BINDIR' $CONFIGFILETEMP | awk -F"=" '{print $2}' )
	MAEDIRTMP=$(grep '^MAEDIR' $CONFIGFILETEMP | awk -F"=" '{print $2}' )
	ARRIDIRTMP=$(grep '^ARRIDIR' $CONFIGFILETEMP | awk -F"=" '{print $2}' )
	DATASIZETMP=$(grep '^DATASIZE' $CONFIGFILETEMP | awk -F"=" '{print $2}' )
	OKDIRTMP=$(grep '^OKDIR' $CONFIGFILETEMP | awk -F"=" '{print $2}' )
	PROCDIRTMP=$(grep '^PROCDIR' $CONFIGFILETEMP | awk -F"=" '{print $2}' )
	INFODIRTMP=$(grep '^INFODIR' $CONFIGFILETEMP | awk -F"=" '{print $2}' )
	LOGDIRTMP=$(grep '^LOGDIR' $CONFIGFILETEMP | awk -F"=" '{print $2}' )
	LOGEXTTMP=$(grep '^LOGEXT' $CONFIGFILETEMP | awk -F"=" '{print $2}' )
	LOGSIZETMP=$(grep '^LOGSIZE' $CONFIGFILETEMP | awk -F"=" '{print $2}' )
	NOKDIRTMP=$(grep '^NOKDIR' $CONFIGFILETEMP | awk -F"=" '{print $2}' )
	BACKUPDIRTMP=$(grep '^BACKUPDIR' $CONFIGFILETEMP | awk -F"=" '{print $2}' )

	declare -a VAR_FALTANTES; #Array con los directorios que falta configurar
	declare -a VAR_COMPLETO; #Array con los directorios que falta configurar

	if [ -z $BASEDIRTMP ]
	then
		echo "GRUPO=$GRUPO=$USER=`date +'%d-%m-%Y %H:%M:%S'`" >> $CONFIGFILETEMP
	fi

	if [ -z $CONFIGDIRTMP ]
	then
		echo "CONFDIR=$CONFDIR=$USER=`date +'%d-%m-%Y %H:%M:%S'`" >> $CONFIGFILETEMP
	fi

	if [ -z $SLEEPTIMETMP ]
	then
		VAR_FALTANTES=( ${VAR_FALTANTES[*]} SLEEPTIME)
	fi

	if [ -z $BINDIRTMP ]
	then
		VAR_FALTANTES=( ${VAR_FALTANTES[*]} BINDIR)
	else
		BINDIR=$BINDIRTMP
		VAR_COMPLETO=( ${VAR_COMPLETO[*]} BINDIR)
	fi

	if [ -z $MAEDIRTMP ]
	then
		VAR_FALTANTES=( ${VAR_FALTANTES[*]} MAEDIR)
	else
		MAEDIR=$MAEDIRTMP
		VAR_COMPLETO=( ${VAR_COMPLETO[*]} MAEDIR)
	fi

	if [ -z $ARRIDIRTMP ]
	then
		VAR_FALTANTES=( ${VAR_FALTANTES[*]} ARRIDIR)
	else
		ARRIDIR=$ARRIDIRTMP
		VAR_COMPLETO=( ${VAR_COMPLETO[*]} ARRIDIR)
	fi

	if [ -z $DATASIZETMP ]
	then
		VAR_FALTANTES=( ${VAR_FALTANTES[*]} DATASIZE)
	else
		DATASIZE=$DATASIZETMP
		VAR_COMPLETO=( ${VAR_COMPLETO[*]} DATASIZE)
	fi

	if [ -z $OKDIRTMP ]
	then
		VAR_FALTANTES=( ${VAR_FALTANTES[*]} OKDIR)
	else
		OKDIR=$OKDIRTMP
		VAR_COMPLETO=( ${VAR_COMPLETO[*]} OKDIR)
	fi

	if [ -z $PROCDIRTMP ]
	then
		VAR_FALTANTES=( ${VAR_FALTANTES[*]} PROCDIR)
	else
		PROCDIR=$PROCDIRTMP
		VAR_COMPLETO=( ${VAR_COMPLETO[*]} PROCDIR)
	fi

	if [ -z $INFODIRTMP ]
	then
		VAR_FALTANTES=( ${VAR_FALTANTES[*]} INFODIR)
	else
		INFODIR=$INFODIRTMP
		VAR_COMPLETO=( ${VAR_COMPLETO[*]} INFODIR)
	fi

	if [ -z $LOGDIRTMP ]
	then
		VAR_FALTANTES=( ${VAR_FALTANTES[*]} LOGDIR)
	else
		LOGDIR=$LOGDIRTMP
		VAR_COMPLETO=( ${VAR_COMPLETO[*]} LOGDIR)
	fi

	if [ -z $LOGEXTTMP ]
	then
		VAR_FALTANTES=( ${VAR_FALTANTES[*]} LOGEXT)
	else
		LOGEXT=$LOGEXTTMP
		VAR_COMPLETO=( ${VAR_COMPLETO[*]} LOGEXT)
	fi

	if [ -z $LOGSIZETMP ]
	then
		VAR_FALTANTES=( ${VAR_FALTANTES[*]} LOGSIZE)
	else
		LOGSIZE=$LOGSIZETMP
		VAR_COMPLETO=( ${VAR_COMPLETO[*]} LOGSIZE)
	fi

	if [ -z $NOKDIRTMP ]
	then
		VAR_FALTANTES=( ${VAR_FALTANTES[*]} NOKDIR)
	else
		NOKDIR=$NOKDIRTMP
		VAR_COMPLETO=( ${VAR_COMPLETO[*]} NOKDIR)
	fi

	if [ ${#VAR_FALTANTES[@]} -eq 0 ] #No falta ninguna variable en el archivo temporal
	then
		initInstalation
	else
	echo "Direct. de Configuracion: $CONFDIR"

	for VARVALUE in "${VAR_COMPLETO[@]}"; do
		case $VARVALUE in
			SLEEPTIME )
				echo "tiempo de espera entre ejecuciones de Procesar Ofertas: $SLEEPTIME";;
			BINDIR )
				echo "Directorio Ejecutables:   $BINDIR";;
			MAEDIR )
				echo "Directorio de Maestros: $MAEDIR";;
			ARRIDIR )
				echo "Directorio de recepción de archivos de novedades:  $ARRIDIR";;
			DATASIZE )
				echo "Espacio mínimo libre para las novedades: $DATASIZE Mb";;
			OKDIR )
				echo "Directorio de archivos aceptados: $OKDIR";;
			PROCDIR )
				echo "Directorio de archivos de ofertas procesadas:  $PROCDIR";;
			INFODIR )
				echo "Directorio de Archivos de reportes: $INFODIR";;
			LOGDIR )
				echo "Directorio de Logs de Comandos: $LOGDIR/<comando>$LOGEXT";;
			#LOGEXT )
				#echo "LOGEXT: $LOGEXT";;
			LOGSIZE )
				echo "Tamaño máximo para los archivos de log del sistema: $LOGSIZE Kb";;
			NOKDIR )
				echo "Directorio de Archivos rechazados: $NOKDIR";;
			esac
	done

	echo ""
	echo "Componentes Faltantes: "
	for VARVALUE in "${VAR_FALTANTES[@]}"
	do
		case $VARVALUE in
			SLEEPTIME )
				echo "tiempo de espera entre ejecuciones de Procesar Ofertas";;
			BINDIR )
				echo "Directorio Ejecutables";;
			MAEDIR )
				echo "Directorio de Maestros";;
			ARRIDIR )
				echo "Directorio de recepción de archivos de novedades";;
			DATASIZE )
				echo "Espacio mínimo libre para novedades";;
			OKDIR )
				echo "Directorio de archivos aceptados";;
			PROCDIR )
				echo "Directorio de llamdas sospechosas";;
			INFODIR )
				echo "Directorio de Archivos de reportes";;
			LOGDIR )
				echo "Directorio de Logs de Comandos";;
			#LOGEXT )
				#echo "LOGEXT: $LOGEXT";;
			LOGSIZE )
				echo "Tamaño máximo para los archivos de log del sistema";;
			NOKDIR )
				echo "Directorio de Archivos rechazados";;
			esac
	done
	echo ""
	echo "Estado de la instalación: INCOMPLETA"

	while [ -z $optSelect ]
	do
		read -p " Desea completar la instalación? (Si - No): " optSelect
		optSelect=$(echo $optSelect | grep '^[Ss][Ii]$\|^[Nn][Oo]$' | tr '[:upper:]' '[:lower:]')
	done
		if [ $optSelect = "no" ]
	then
		log "Installer" "Usuario no quiere continuar con la instalación" "I"
		pause 'Press [Enter] key to continue...'
		exit 6
	fi

	for VARVALUE in "${VAR_FALTANTES[@]}"; do
		case $VARVALUE in
			SLEEPTIME )
				readNumber "Defina tiempo de espera entre ejecuciones de Procesar Ofertas SLEEPTIME ($SLEEPTIME)" "$SLEEPTIME"
				SLEEPTIME=$numberTemp
				echo "SLEEPTIME=$SLEEPTIME=$USER=`date +'%d-%m-%Y %H:%M:%S'`" >> $CONFIGFILETEMP;;
			BINDIR )
				getDirectoryPath "Defina el directorio de instalación de los ejecutables ($BINDIR):" "$BINDIR"
				BINDIR=$pathTemp
				echo "BINDIR=$pathTemp=$USER=`date +'%d-%m-%Y %H:%M:%S'`" >> $CONFIGFILETEMP;;
			MAEDIR )
				getDirectoryPath "Defina directorio para maestros ($MAEDIR):" "$MAEDIR"
				MAEDIR=$pathTemp
				echo "MAEDIR=$pathTemp=$USER=`date +'%d-%m-%Y %H:%M:%S'`" >> $CONFIGFILETEMP;;
			ARRIDIR )
				getDirectoryPath "Defina el Directorio de recepción de archivos de novedades ($ARRIDIR):" "$ARRIDIR"
				ARRIDIR=$pathTemp
				echo "ARRIDIR=$pathTemp=$USER=`date +'%d-%m-%Y %H:%M:%S'`" >> $CONFIGFILETEMP;;
			DATASIZE )
				readNumber "Defina espacio mínimo libre para el arribo de archivos de novedades en Mbytes ($DATASIZE)" "$DATASIZE"
				DATASIZETEMP=$numberTemp
				DATASIZEDIR=$(df -B1024 "$ACTUALDIR" | tail -n1 | sed -e"s/\s\{1,\}/;/g" | cut -f4 -d';')
				DATASIZEDIR=$(echo "scale=0 ; $DATASIZEDIR/1024" | bc -l) #lo paso a Mb

				while [ $DATASIZEDIR -lt $DATASIZETEMP ]
				do
					echo "Insuficiente espacio en disco."
					echo "Espacio disponible: $DATASIZEDIR Mb."
					echo "Espacio requerido $DATASIZETEMP Mb"
					echo "Inténtelo nuevamente."
					echo ""
					readNumber "Defina espacio mínimo libre para el arribo de archivos de novedades en Mbytes ($DATASIZE)" "$DATASIZE"
					DATASIZETEMP=$numberTemp
				done
				DATASIZE=$DATASIZETEMP
				echo "DATASIZE=$DATASIZETEMP=$USER=`date +'%d-%m-%Y %H:%M:%S'`" >> $CONFIGFILETEMP;;
			OKDIR )
				getDirectoryPath "Defina el directorio de grabación de los archivos aceptados ($OKDIR):" "$OKDIR"
				OKDIR=$pathTemp
				echo "OKDIR=$pathTemp=$USER=`date +'%d-%m-%Y %H:%M:%S'`" >> $CONFIGFILETEMP;;
			PROCDIR )
				getDirectoryPath "Defina el directorio de grabación de los registros de las ofertas procesadas ($PROCDIR):" "$PROCDIR"
				PROCDIR=$pathTemp
				echo "PROCDIR=$pathTemp=$USER=`date +'%d-%m-%Y %H:%M:%S'`" >> $CONFIGFILETEMP;;
			INFODIR )
				getDirectoryPath "Defina el directorio de grabación de los reportes ($INFODIR):" "$INFODIR"
				INFODIR=$pathTemp
				echo "INFODIR=$pathTemp=$USER=`date +'%d-%m-%Y %H:%M:%S'`" >> $CONFIGFILETEMP;;
			LOGDIR )
				getDirectoryPath "Defina el directorio de logs ($LOGDIR):" "$LOGDIR"
				LOGDIR=$pathTemp
				echo "LOGDIR=$pathTemp=$USER=`date +'%d-%m-%Y %H:%M:%S'`" >> $CONFIGFILETEMP;;
			LOGEXT )
				getExtension "Ingrese la extensión para los archivos de log ($LOGEXT): " "$LOGEXT"
				LOGEXT=$extDefault
				echo "LOGEXT=$extDefault=$USER=`date +'%d-%m-%Y %H:%M:%S'`" >> $CONFIGFILETEMP;;
			LOGSIZE )
				readNumber "Defina el tamaño máximo para los archivos $LOGEXT en Kbytes ($LOGSIZE)" "$LOGSIZE"
				LOGSIZETEMP=$numberTemp
				LOGSIZEDISP=$(df -B1024 "$ACTUALDIR" | tail -n1 | sed -e"s/\s\{1,\}/;/g" | cut -f4 -d';')
				#LOGSIZEDISP=$(echo "scale=0 ; $LOGSIZEDISP/1024" | bc -l) #lo paso a Mb

				while [ $LOGSIZEDISP -lt $LOGSIZETEMP ]
				do
					echo "Insuficiente espacio en disco."
					echo "Espacio disponible: $LOGSIZEDISP Kb."
					echo "Espacio requerido $LOGSIZETEMP Kb"
					echo "Inténtelo nuevamente."
					echo ""
					readNumber "Defina el tamaño máximo para los archivos $LOGEXT en Kbytes ($LOGSIZE)" "$LOGSIZE"
					LOGSIZETEMP=$numberTemp
				done
				LOGSIZE=$LOGSIZETEMP
				echo "LOGSIZE=$LOGSIZETEMP=$USER=`date +'%d-%m-%Y %H:%M:%S'`" >> $CONFIGFILETEMP;;
			NOKDIR )
				getDirectoryPath "Defina el directorio de grabación de los reportes ($NOKDIR):" "$NOKDIR"
				NOKDIR=$pathTemp
				echo "NOKDIR=$pathTemp=$USER=`date +'%d-%m-%Y %H:%M:%S'`" >> $CONFIGFILETEMP;;
		esac
	done
	fi

	if [ -z $BACKUPDIRTMP ]
	then
		echo "BACKUPDIR=$BACKUPDIR=$USER=`date +'%d-%m-%Y %H:%M:%S'`" >> $CONFIGFILETEMP
	fi
	executeInstaler "LISTA"

else
	#NO Hay una instalación previa
	log "Installer" "No hay instalación, mostrando aceptación de terminos y condiciones" "I"

	initInstalation

	executeInstaler "LISTA"
pause 'Press [Enter] key to continue...'
exit 0;
fi


text:
@import CoreLocation.CLLocation;

#import "PFGeoPoint.h"
#import "PFGeoPointPrivate.h"
#import "PFTestCase.h"

@interface GeoPointUnitTests : PFTestCase

@end

@implementation GeoPointUnitTests

- (void)testDefaults {
    PFGeoPoint *point = [PFGeoPoint geoPoint];

    // Check default values
    XCTAssertEqualWithAccuracy(point.latitude, 0.0, 0.00001, @"Latitude should be 0.0");
    XCTAssertEqualWithAccuracy(point.longitude, 0.0, 0.00001, @"Longitude should be 0.0");
}

- (void)testGeoPointFromLocation {
    CLLocation *location = [[CLLocation alloc] initWithLatitude:10.0 longitude:20.0];

    PFGeoPoint *geoPoint = [PFGeoPoint geoPointWithLocation:location];
    XCTAssertEqual(geoPoint.latitude, location.coordinate.latitude);
    XCTAssertEqual(geoPoint.longitude, location.coordinate.longitude);

    geoPoint = [PFGeoPoint geoPointWithLocation:nil];
    XCTAssertEqual(geoPoint.latitude, 0);
    XCTAssertEqual(geoPoint.longitude, 0);
}

- (void)testGeoPointDictionaryEncoding {
    PFGeoPoint *point = [PFGeoPoint geoPointWithLatitude:10 longitude:20];

    NSDictionary *dictionary = [point encodeIntoDictionary];
    XCTAssertNotNil(dictionary);

    PFGeoPoint *pointFromDictionary = [PFGeoPoint geoPointWithDictionary:dictionary];
    XCTAssertEqualObjects(pointFromDictionary, point);
    XCTAssertEqual(point.latitude, pointFromDictionary.latitude);
    XCTAssertEqual(point.longitude, pointFromDictionary.longitude);
}

- (void)testGeoExceptions {
    PFGeoPoint *point = [PFGeoPoint geoPointWithLatitude:34.0 longitude:24.0];

    // Setter exceptions
    PFAssertThrowsInvalidArgumentException([point setLatitude:90.001]);
    PFAssertThrowsInvalidArgumentException([point setLatitude:-90.001]);
    PFAssertThrowsInvalidArgumentException([point setLongitude:180.001]);
    PFAssertThrowsInvalidArgumentException([point setLongitude:-180.001]);
}

- (void)testGeoPointEquality {
    PFGeoPoint *pointA = [PFGeoPoint geoPointWithLatitude:10.2 longitude:11.3];
    PFGeoPoint *pointB = [PFGeoPoint geoPointWithLatitude:10.2 longitude:11.3];

    XCTAssertTrue([pointA isEqual:pointB]);
    XCTAssertTrue([pointB isEqual:pointA]);

    XCTAssertFalse([pointA isEqual:@YES]);
    XCTAssertTrue([pointA isEqual:pointA]);
}

- (void)testGeoPointHash {
    PFGeoPoint *pointA = [PFGeoPoint geoPointWithLatitude:10.2 longitude:11.3];
    PFGeoPoint *pointB = [PFGeoPoint geoPointWithLatitude:10.2 longitude:11.3];
    XCTAssertEqual([pointA hash], [pointB hash]);
}

- (void)testGeoUtilityDistance {
    double D2R = M_PI / 180.0;
    PFGeoPoint *pointA = [PFGeoPoint geoPoint];
    PFGeoPoint *pointB = [PFGeoPoint geoPoint];

    // Zero
    XCTAssertEqualWithAccuracy([pointA distanceInRadiansTo:pointB], 0.0, 0.000001,
                               @"Origin points with non-zero distance.");
    XCTAssertEqualWithAccuracy([pointB distanceInRadiansTo:pointA], 0.0, 0.000001,
                               @"Origin points with non-zero distance.");
    // Wrap Long
    [pointA setLongitude:179.0];
    [pointB setLongitude:-179.0];
    XCTAssertEqualWithAccuracy([pointA distanceInRadiansTo:pointB], 2.0 * D2R, 0.000001,
                               @"Long wrap angular distance error.");
    XCTAssertEqualWithAccuracy([pointB distanceInRadiansTo:pointA], 2.0 * D2R, 0.000001,
                               @"Long wrap angular distance error.");

    // North South Lat
    [pointA setLatitude:89.0];
    [pointA setLongitude:0.0];
    [pointB setLatitude:-89.0];
    [pointB setLongitude:0.0];

    XCTAssertEqualWithAccuracy([pointA distanceInRadiansTo:pointB], 178.0 * D2R, 0.000001,
                               @"NS pole wrap error");
    XCTAssertEqualWithAccuracy([pointB distanceInRadiansTo:pointA], 178.0 * D2R, 0.000001,
                               @"NS pole wrap error");

    // Long wrap Lat
    [pointA setLatitude:89.0];
    [pointA setLongitude:0.0];
    [pointB setLatitude:-89.0];
    [pointB setLongitude:179.9999];

    XCTAssertEqualWithAccuracy([pointA distanceInRadiansTo:pointB], 180 * D2R, 0.00001,
                               @"Lat wrap error.");
    XCTAssertEqualWithAccuracy([pointB distanceInRadiansTo:pointA], 180 * D2R, 0.00001,
                               @"Lat wrap error.");

    [pointA setLatitude:79.0];
    [pointA setLongitude:90.0];
    [pointB setLatitude:-79.0];
    [pointB setLongitude:-90.0];

    XCTAssertEqualWithAccuracy([pointA distanceInRadiansTo:pointB], 180.0 * D2R, 0.00001,
                               @"Lat long wrap");
    XCTAssertEqualWithAccuracy([pointB distanceInRadiansTo:pointA], 180.0 * D2R, 0.00001,
                               @"Lat long wrap");

    // Wrap near pole - somewhat ill conditioned case due to pole proximity
    [pointA setLatitude:85.0];
    [pointA setLongitude:90.0];
    [pointB setLatitude:85.0];
    [pointB setLongitude:-90.0];

    XCTAssertEqualWithAccuracy([pointA distanceInRadiansTo:pointB], 10.0 * D2R, 0.00001,
                               @"Pole proximity fail");
    XCTAssertEqualWithAccuracy([pointB distanceInRadiansTo:pointA], 10.0 * D2R, 0.00001,
                               @"Pole proximity fail");

    // Reference cities
    // Sydney Australia
    [pointA setLatitude:-34.0];
    [pointA setLongitude:151.0];

    // Buenos Aires
    [pointB setLatitude:-34.5];
    [pointB setLongitude:-58.35];

    XCTAssertEqualWithAccuracy([pointA distanceInRadiansTo:pointB], 1.85, 0.01,
                               @"Sydney to Buenos Aires Fail");
    XCTAssertEqualWithAccuracy([pointB distanceInRadiansTo:pointA], 1.85, 0.01,
                               @"Sydney to Buenos Aires Fail");

    // [SAC]  38.52  -121.50  Sacramento,CA
    PFGeoPoint *sacramento = [PFGeoPoint geoPointWithLatitude:38.52 longitude:-121.50];

    // [HNL]  21.35  -157.93  Honolulu Int,HI
    PFGeoPoint *honolulu = [PFGeoPoint geoPointWithLatitude:21.35 longitude:-157.93];

    // [51Q]  37.75  -122.68  San Francisco,CA
    PFGeoPoint *sanfran = [PFGeoPoint geoPointWithLatitude:37.75 longitude:-122.68];

    // Vorkuta 67.509619,64.085999
    PFGeoPoint *vorkuta = [PFGeoPoint geoPointWithLatitude:67.509619 longitude:64.085999];

    // London
    PFGeoPoint *london = [PFGeoPoint geoPointWithLatitude:51.501904 longitude:-0.115356];

    // Northampton
    PFGeoPoint *northampton = [PFGeoPoint geoPointWithLatitude:52.241256 longitude:-0.895386];

    // Powell St BART station
    PFGeoPoint *powell = [PFGeoPoint geoPointWithLatitude:37.78507 longitude:-122.407007];

    // Apple store
    PFGeoPoint *astore = [PFGeoPoint geoPointWithLatitude:37.785809 longitude:-122.406363];

    // Self
    XCTAssertEqualWithAccuracy([honolulu distanceInKilometersTo:honolulu], 0.0, 0.000001, @"Self distance");

    // SAC to HNL
    XCTAssertEqualWithAccuracy([sacramento distanceInKilometersTo:honolulu], 3964.8, 10.0, @"SAC to HNL");
    XCTAssertEqualWithAccuracy([sacramento distanceInMilesTo:honolulu], 2463.6, 10.0, @"SAC to HNL");

    // Semi-local
    XCTAssertEqualWithAccuracy([london distanceInKilometersTo:northampton], 98.4, 1.0, @"London Northampton");
    XCTAssertEqualWithAccuracy([london distanceInMilesTo:northampton], 61.2, 1.0, @"London Northampton");

    XCTAssertEqualWithAccuracy([london distanceInKilometersTo:northampton], 98.4, 1.0, @"London Northampton");
    XCTAssertEqualWithAccuracy([london distanceInMilesTo:northampton], 61.2, 1.0, @"London Northampton");

    XCTAssertEqualWithAccuracy([sacramento distanceInKilometersTo:sanfran], 134.5, 2.0, @"Sacramento San Fran");
    XCTAssertEqualWithAccuracy([sacramento distanceInMilesTo:sanfran], 84.8, 2.0, @"Sacramento San Fran");

    // Very local
    XCTAssertEqualWithAccuracy([powell distanceInKilometersTo:astore], 0.1, 0.05, @"Powell station and Apple store");

    // Far (for error tolerance's sake)
    XCTAssertEqualWithAccuracy([sacramento distanceInKilometersTo:vorkuta], 8303.8, 100.0, @"Sacramento to Vorkuta");
    XCTAssertEqualWithAccuracy([sacramento distanceInMilesTo:vorkuta], 5159.7, 100.0, @"Sacramento to Vorkuta");
}

- (void)testNSCopying {
    PFGeoPoint *geoPoint = [PFGeoPoint geoPointWithLatitude:10.0 longitude:20.0];
    PFGeoPoint *geoPointCopy = [geoPoint copy];

    XCTAssertEqual(geoPointCopy.latitude, geoPoint.latitude, @"Latitude should be the same.");
    XCTAssertEqual(geoPointCopy.longitude, geoPoint.longitude, @"Longitude should be the same.");
}

- (void)testNSCoding {
    PFGeoPoint *geoPoint = [PFGeoPoint geoPointWithLatitude:10.0 longitude:20.0];

    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:geoPoint];
    XCTAssertTrue([data length] > 0, @"Encoded data should not be empty");

    PFGeoPoint *decodedGeoPoint = [NSKeyedUnarchiver unarchiveObjectWithData:data];
    XCTAssertEqual(decodedGeoPoint.latitude, geoPoint.latitude, @"Latitude should be the same.");
    XCTAssertEqual(decodedGeoPoint.longitude, geoPoint.longitude, @"Longitude should be the same.");
}

- (void)testGeoPointDescription {
    PFGeoPoint *point = [PFGeoPoint geoPoint];
    XCTAssertNotNil([point description]);

    point = [PFGeoPoint geoPointWithLatitude:10 longitude:20];
    NSString *description = [point description];
    XCTAssertNotNil(description);

    point.latitude = 20;
    XCTAssertNotNil([point description]);
    XCTAssertNotEqualObjects(description, [point description]);
}

- (void)testGeoPointForCurrentLocation {
    // Make sure we don't crash on nil block
    [PFGeoPoint geoPointForCurrentLocationInBackground:nil];
}

@end


text:
<?php

declare(strict_types=1);

namespace Atk4\Ui\Demos;

use Atk4\Ui\Button;
use Atk4\Ui\Crud;
use Atk4\Ui\Exception;
use Atk4\Ui\Header;
use Atk4\Ui\Loader;
use Atk4\Ui\UserAction\ExecutorFactory;

/** @var \Atk4\Ui\App $app */
require_once __DIR__ . '/../init-app.php';

$m = (new Country($app->db))->setLimit(5);
$app->getExecutorFactory()->registerTrigger(
    ExecutorFactory::TABLE_BUTTON,
    [Button::class, 'ui' => 'atk-test button', 'icon' => 'pencil'],
    $m->getUserAction('edit')
);

$loader = Loader::addTo($app);
$loader->cb->setUrlTrigger('trigger_main_loader');
$loader->loadEvent = false;

$loader->set(function (Loader $p) use ($m) {
    Header::addTo($p, ['Loader-1', 'size' => 4]);

    if (isset($_GET['err_main_loader'])) {
        throw new Exception('Exception from Main Loader');
    }

    $loaderSub = Loader::addTo($p);
    $loaderSub->cb->setUrlTrigger('trigger_sub_loader');
    $loaderSub->loadEvent = false;

    $loaderSub->set(function (Loader $p) use ($m) {
        Header::addTo($p, ['Loader-2', 'size' => 4]);

        if (isset($_GET['err_sub_loader'])) {
            throw new Exception('Exception from Sub Loader');
        } elseif (isset($_GET['err_sub_loader2'])) {
            throw new \Error('Exception II from Sub Loader');
        }

        $loaderSubSub = Loader::addTo($p);

        $loaderSubSub->set(function (Loader $p) use ($m) {
            Header::addTo($p, ['Loader-3', 'size' => 4]);

            $c = Crud::addTo($p, ['ipp' => 4]);
            $c->setModel($m, [$m->fieldName()->name]);
        });
    });
    Button::addTo($p, ['Load2'])->js('click', $loaderSub->jsLoad());
});

Button::addTo($app, ['Load1'])->js('click', $loader->jsLoad());


text:
"""Algorithms to calculate reciprocity in a directed graph."""
from networkx import NetworkXError
from ..utils import not_implemented_for

__author__ = """\n""".join(['Haochen Wu <wuhaochen42@gmail.com>'])

__all__= ['reciprocity','overall_reciprocity']

@not_implemented_for('undirected','multigraph')
def reciprocity(G, nodes=None):
    """Compute the reciprocity in a directed graph.

    The reciprocity of a directed graph is defined as the ratio
    of the number of edges pointing in both directions to the total
    number of edges in the graph.
    Formally, :math:`r = |{(u,v) \in G|(v,u) \in G}| / |{(u,v) \in G}|`.

    The reciprocity of a single node u is defined similarly,
    it is the ratio of the number of edges in both directions to
    the total number of edges attached to node u.

    Parameters
    ----------
    G : graph
       A networkx directed graph
    nodes : container of nodes, optional (default=whole graph)
       Compute reciprocity for nodes in this container.

    Returns
    -------
    out : dictionary
       Reciprocity keyed by node label.

    Notes
    -----
    The reciprocity is not defined for isolated nodes.
    In such cases this function will return None.

    """
    # If `nodes` is not specified, calculate the reciprocity of the graph.
    if nodes is None:
        return overall_reciprocity(G)

    # If `nodes` represents a single node in the graph, return only its
    # reciprocity.
    if nodes in G:
        reciprocity = next(_reciprocity_iter(G,nodes))[1]
        if reciprocity is None:
            raise NetworkXError('Not defined for isolated nodes.')
        else:
            return reciprocity

    # Otherwise, `nodes` represents an iterable of nodes, so return a
    # dictionary mapping node to its reciprocity.
    return dict(_reciprocity_iter(G,nodes))

def _reciprocity_iter(G,nodes):
    """ Return an iterator of (node, reciprocity).

    """
    n = G.nbunch_iter(nodes)
    for node in n:
        pred = set(G.predecessors(node))
        succ = set(G.successors(node))
        overlap = pred & succ
        n_total = len(pred) + len(succ)

        # Reciprocity is not defined for isolated nodes.
        # Return None.
        if n_total == 0:
            yield (node,None)
        else:
            reciprocity = 2.0*float(len(overlap))/float(n_total)
            yield (node,reciprocity)

@not_implemented_for('undirected','multigraph')
def overall_reciprocity(G):
    """Compute the reciprocity for the whole graph.

    See the doc of reciprocity for the definition.

    Parameters
    ----------
    G : graph
       A networkx graph

    """
    n_all_edge = G.number_of_edges()
    n_overlap_edge = (n_all_edge - G.to_undirected().number_of_edges()) *2

    if n_all_edge == 0:
        raise NetworkXError("Not defined for empty graphs")

    return float(n_overlap_edge)/float(n_all_edge)