text:
package org.deeplearning4j.examples.rnn.strata.physionet.utils;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import org.deeplearning4j.examples.rnn.strata.physionet.PhysioNet_Vectorizer;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.factory.Nd4j;

public class PhysioNetVectorizationDebugTool {

	public static void triagePatientFile( String physioNetBaseDirectory, String physioSchemaFilePath, String physioLabelsFilePath, String patientFileFullPath ) {

		//PhysioNet_Vectorizer vec = new PhysioNet_Vectorizer("/tmp/set-a/", "src/test/resources/physionet_schema.txt", "src/test/resources/data/physionet/sample/set-a-labels/Outcomes-a.txt" );
		PhysioNet_Vectorizer vec = new PhysioNet_Vectorizer( physioNetBaseDirectory, physioSchemaFilePath, physioLabelsFilePath );
		vec.loadSchema();
		vec.loadLabels();

		vec.collectStatistics();

		String filename = patientFileFullPath; //vec.getFilenameForIndex( 0 );
//		if (filename.startsWith("/")) {
	//		filename = filename.replace("/", "");
		//}

		File f = new File(filename);
		String strippedFilename = f.getName().replace(".txt", "");

		BufferedWriter writer = null;
        try {
            //create a temporary file
            String timeLog = new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime());
            File logFile = new File("/tmp/" + strippedFilename + "_" + timeLog + ".txt");

            // This will output the full path where the file will be written to...
            System.out.println(logFile.getCanonicalPath());
            writer = new BufferedWriter(new FileWriter(logFile));

			// log this
			vec.schema.debugPrintDatasetStatistics();
			vec.schema.logDatasetStatistics(writer);
			vec.schema.logColumns(writer);

			// now write out the raw record data

			//System.out.println( "ND4J Input Size: " );
			//System.out.println( "Minibatch: 1" );
			writer.write( "\n\n" );
			writer.write( "Total Column Count: " + (vec.schema.getTransformedVectorSize() + 1) + "\n" );
			writer.write( "Total Timestep Count: " + vec.maxNumberTimeSteps + "\n" );
			writer.write( "\n\n" );

			vec.logTreeMapData(writer, filename);

			int timesteps = vec.maxNumberTimeSteps;

			INDArray input = Nd4j.zeros(new int[]{ 1, vec.schema.getTransformedVectorSize() + 1, timesteps });
			INDArray inputMask = Nd4j.zeros(new int[]{ 1, vec.schema.getTransformedVectorSize() + 1, timesteps });
			// 1 == mini-batch size
			// 2 == number of classes (0 -> no survive, 1 -> survival)
			INDArray labels = Nd4j.zeros(new int[]{ 1, 2 });
			INDArray labelsMask = Nd4j.ones(new int[]{ 1, 2 });

			vec.extractFileContentsAndVectorize( filename, 0, vec.schema.getTransformedVectorSize() + 1, timesteps, input, inputMask, labels, labelsMask);

			PhysioNet_Vectorizer.log_debug3D_Nd4J_Input( writer, input, 1, vec.schema.getTransformedVectorSize() + 1, timesteps );

			writer.write( "\n\nDebug Input Mask --------------- \n" );

			PhysioNet_Vectorizer.log_debug3D_Nd4J_Input( writer, inputMask, 1, vec.schema.getTransformedVectorSize() + 1, timesteps );

			//PhysioNet_Vectorizer.log_debug3D_Nd4J_Input( writer, d.getFeaturesMaskArray(), 1, 43, 202 );

			System.out.println( "> [ done ] ");

	    } catch (Exception e) {
	        e.printStackTrace();
	    } finally {
	        try {
	            // Close the writer regardless of what happens...
	            writer.close();
	        } catch (Exception e) {
	        }
	    }

	}

	public static void extractBalancedSubsetOfPhysioNet( int totalRecords ) {

		// "src/test/resources/physionet_schema.txt", "src/test/resources/data/physionet/sample/set-a-labels/Outcomes-a.txt"

		String physioNetBaseDirectory = "/tmp/set-a/";
		String physioSchemaFilePath = "src/test/resources/physionet_schema.txt";
		String physioLabelsFilePath = "src/test/resources/data/physionet/sample/set-a-labels/Outcomes-a.txt";

		PhysioNet_Vectorizer vec = new PhysioNet_Vectorizer( physioNetBaseDirectory, physioSchemaFilePath, physioLabelsFilePath );
		vec.loadSchema();
		vec.loadLabels();
		//vec.setupFileInputList(false, 0);
		vec.collectStatistics();
		/*
		// died
		List<String> negativeClassFiles = new ArrayList<>();

		// survived
		List<String> positiveClassFiles = new ArrayList<>();

		//for (int x = 0; x < 100; x++) {
		while (negativeClassFiles.size() + positiveClassFiles.size() < totalRecords) {

			int randomIndex = (int )(Math.random() * 4000);

			String filename = vec.getFilenameForIndex(randomIndex);

			String[] filenameParts = filename.split(".t");
			String patientID = filenameParts[ 0 ];

			//System.out.println( "" + patientID );

			if (0 == vec.labels.translateLabelEntry(patientID)) {

				// died
				if (negativeClassFiles.size() < totalRecords / 2) {
					negativeClassFiles.add( patientID );
				}

			} else {

				// survived
				if (positiveClassFiles.size() < totalRecords / 2) {
					positiveClassFiles.add( patientID );
				}

			}

		} // while

		System.out.println( "Classes: " );

		System.out.println( "Survived: " + positiveClassFiles.size() );
		System.out.println( "Died: " + negativeClassFiles.size() );

		File[] listOfFiles = new File[ totalRecords ];
		for ( int x = 0; x < totalRecords; x++) {

			String patientID = "";
			if (positiveClassFiles.size() > negativeClassFiles.size()) {

				patientID = positiveClassFiles.remove(0);
				String path = physioNetBaseDirectory + patientID + ".txt";
				listOfFiles[ x ] = new File( path );

				System.out.println( "pos: " + path );

			} else {

				patientID = negativeClassFiles.remove(0);
				String path = physioNetBaseDirectory + patientID + ".txt";
				listOfFiles[ x ] = new File( path );

				System.out.println( "neg: " + path );

			}

		}
		*/

	}

}


text:
FILTER=$(auto_filter Id DomainName Status "join(',',Aliases.Items||[''])" -- $@)

awscli cloudfront list-distributions --output table --query "DistributionList.Items[$FILTER].{ \
  \"1.Id\": Id, \
  \"2.DomainName\": DomainName, \
  \"3.Status\": Status, \
  \"4.Enabled\":Enabled, \
  \"5.PriceClass\": PriceClass, \
  \"6.Aliases\": (Aliases.Items||[''])|join(',',@), \
  \"7.Origins\": Origins.Quantity, \
  \"8.CacheBehaviors\": CacheBehaviors.Quantity}"

redpajama_set_name: RedPajamaGithub


text:
ACCEPTED

#### According to
World Register of Marine Species

#### Published in
Deep-Sea Res. (A) 30 (6): 611.

#### Original name
null

### Remarks
null


text:
using meshy::HttpRequest;

void HttpRequest::ParseStdString(std::string const& text) {
	StdStringList stringList = SplitString(text, '\n');
	for (auto& line : stringList)line.pop_back();
	ParseStdStringList(stringList);
}

void HttpRequest::ParseStdStringList(StdStringList const& stringList) {
	std::string requestLine = stringList.front();
	ParseRequestLine(requestLine);
	StdStringList contextLines = stringList;
	contextLines.erase(contextLines.begin());
	HttpContext::ParseStdStringList(contextLines);
}

void HttpRequest::ParseRequestLine(std::string const& requestLine) {
	StdStringList words = SplitString(requestLine, ' ');
	if (words.size() < 2 )return;
	method(words[0]);
	path(words[1]);
	if (words.size() < 3)return;
	version(words[2]);
}

HttpRequest HttpRequest::FromStdString(std::string const& text) {
	HttpRequest request;
	request.ParseStdString(text);
	return request;
}

HttpRequest HttpRequest::FromStdStringList(StdStringList const& stringList) {
	HttpRequest request;
	request.ParseStdStringList(stringList);
	return request;
}

std::string const& HttpRequest::method()const {
	return m_method;
}

std::string const& HttpRequest::path()const {
	return m_path;
}

void HttpRequest::method(std::string const& m) {
	m_method = m;
}

void HttpRequest::path(std::string const& p) {
	m_path = p;
}


text:
package com.unipad.brain.home.iview;

public interface ISidebar {
	/**
	 *
	 * @param isOpen  是否打开侧边栏
	 * @param position  项目所在位置
	 */
	public void onClickHelpButton(boolean isOpen, int position);
}


text:
"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon"));
var _jsxRuntime = require("react/jsx-runtime");
var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
  d: "M8.59 16.59 13.17 12 8.59 7.41 10 6l6 6-6 6-1.41-1.41z"
}), 'KeyboardArrowRight');
exports.default = _default;


text:
int rand_int()
{
    return static_cast<int>((rand() / double(RAND_MAX)) * 25.0);
}

int main(int argc, char *argv[])
{
    perf_parse_args(argc, argv);
    std::cout << "size: " << PERF_N << std::endl;

    // create vector of random numbers on the host
    std::vector<int> host_vector(PERF_N);
    std::generate(host_vector.begin(), host_vector.end(), rand_int);

    // count values equal to four in the vector
    size_t count = 0;
    perf_timer t;
    for(size_t trial = 0; trial < PERF_TRIALS; trial++){
        t.start();
        count = std::count(
            host_vector.begin(), host_vector.end(), 4
        );
        t.stop();
    }
    std::cout << "time: " << t.min_time() / 1e6 << " ms" << std::endl;
    std::cout << "count: " << count << std::endl;

    return 0;
}


text:
[![Build Status](https://travis-ci.org/dobrou/CsvLINQPadDriver.svg?branch=master)](https://travis-ci.org/dobrou/CsvLINQPadDriver)

CsvLINQPadDriver
==

CsvLINQPadDriver is LINQPad data context dynamic driver for querying CSV files.

You can query data in CSV files with LINQ, just like it would be regular database. No need to write custom data model, mappings etc.

Driver automatically generates new data types for every CSV file with corresponding properties and mappings for all columns.
Based on column and file names, possible relations between CSV tables are detected and generated.

Website
--
https://github.com/dobrou/CsvLINQPadDriver

Download
--
- v1.6
  - **[CsvLINQPadFileOpen.exe](https://goo.gl/mTvTSK)** - It's installer and CSV context loader in one package.
      - LINQPad **v4** only
      - Automatically installs CSV driver into LINQPad.
      - Loads new CSV context with files from command-line. You can associate this executable to open CSV files, so they will load directly into LINQPad.
  - [CsvLINQPadDriver.lpx](https://goo.gl/k9taJj) - Manual installation.
      - LINQPad **v4/v5** compatible

Example
--
Let's have 2 CSV files:
```
Lakes.csv:
LakeName,ID
lake1,1
etc.

Fishes.csv:
FishName,FishID,LakeID
xyz,1,1
etc.
```

CsvLINQPadDriver will generate data context similar to:
```csharp
public class CsvDataContext {
  public IEnumerable<Lakes> Lakes { get; set; }
  public IEnumerable<Fishes> Fishes { get; set; }
}
public class Lakes {
  public string LakeName { get; set; }
  public string ID { get; set; }
  public IEnumerable<Fishes> Fishes { get; set; } //All Fishes where Lakes.ID == Fishes.LakeID
}
public class Fishes {
  public string FishName { get; set; }
  public string FishID { get; set; }
  public string LakeID { get; set; }
  public IEnumerable<Lakes> Lakes { get; set; } //All Lakes where Lakes.ID == Fishes.LakeID
}
/// and mappings etc.
```

And you can query data with LINQ like:
```csharp
from lake in Lakes
where lake.LakeName.StartsWith("S") && lake.Fishes.Any()
select new { lake, fishes = lake.Fishes }
```

Prerequisites
--
- LINQPad 4
- .NET Framework 4.0/4.5

Installation
--
- Using CsvLINQPadFileOpen.exe:
  - Driver will be installed automatically on first run.
- Or driver can be installed manually:
  1. Get CsvLINQPadDriver.lpx file
  - Open LINQPad
  - Click `Add connection` main window
  - Click button `View more drivers...`
  - Click button `Browse` and select downloaded .lpx file

Usage
--
- CSV context can be added to LINQPad same way as any other context.
  - Click `Add connection`
  - Select `CSV Context Driver` and click `Next`
  - Enter CSV file names or Drag&Drop files from explorer.
    Optionally configure other options.
  - Query your data
- Or run `CsvLINQPadFileOpen.exe` with CSV files as arguments.
  - `CsvLINQPadFileOpen.exe mydata.csv`
  - New CSV data context will be created and loaded in LINQPad

Configuration Options
--
- **CSV Files** - list of CSV files and directories. Type one file/dir per line or Drag&Drop files from explorer. Supports special wildcards: `*` and `**`.
  - `c:\x\*.csv` - all files in folder `c:\x`
  - `c:\x\**.csv` - all files in folder `c:\x` and all sub-directories
- CSV Separator - character used to separate columns in files. Can be `,`,`\t`, etc. If empty, separator is auto-detected.
- Detect relations - if checked, driver will try to detect and generate relations between files.
- Hide relations from .Dump() - if checked - LINQPad will not show relations content in .Dump(). This prevents loading too many data.
- Cache CSV data in memory
  - if checked - parsed rows from file are cached in memory. This cache survives multiple query runs, even when query is changed. Cache is cleared as soon as LINQPad clears Application Domain of query.
  - if unchecked - disable cache. Multiple enumerations of file content results in multiple reads and parsing of file. Can be significantly slower for complex queries. Significantly reduces memory usage. Useful when reading very large files.
- Ignore files with invalid format - files with strange content not similar to CSV format will be ignored.
- Debug info - additional debug information will be available. For example generated Data Context source.
- Remember this connection - if checked, connection info will be saved and available after LINQPad restart.

Relations
--
There is no definion of relations between CSV files, but we can guess some relations from files and columns names.
Relations between `fileName.columnName` are detected in cases similar to following examples:
- `Fishes.LakeID` <-> `Lakes.ID`
- `Fishes.LakesID` <-> `Lakes.ID`
- `Fishes.LakeID` <-> `Lakes.LakeID`
- `Fishes.ID` <-> `Lakes.FishID`

Performance
--
When executing LINQ query on CSV context:
- Only files used in query are loaded from disk.
- As soon as any record from file is accessed, whole file is loaded into memory.
- Relations are lazy evaluated and retreived using cached Lookup tables.

Don't expect performance comparable with SQL server. But for reasonably sized CSV files there should not be any problem.

Data types
--
Everything is string. Because there is no data type info in CSV files, this is best we can do.
However, driver provides few extension methods providing easy conversion from string to nullable of common types:
`"123".ToInt()` , `"123".ToDouble()`, etc.

Known Issues / TODO
--
- Some strange Unicode chracters in column names may cause errors in generated data context source code.
- Writing changed objects back to CSV is not directly supported, there is no `.SubmitChanges()` . But you can use LINQPad's `Util.WriteCsv`.

Author
--
- Martin Dobroucký (dobrou@gmail.com)

Credits
--
- [LINQPad](http://www.linqpad.net/)
- [CsvHelper](https://github.com/JoshClose/CsvHelper) - CSV files parsing

License
--
[MIT](http://opensource.org/licenses/MIT), see LICENSE file for details.


text:
package mcp.mobius.waila.api;

import net.minecraft.block.Block;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.MovingObjectPosition;
import net.minecraft.util.Vec3;
import net.minecraft.world.World;
import net.minecraftforge.common.util.ForgeDirection;

/**
 * The Accessor is used to get some basic data out of the game without having to request direct access to the game engine.

 * It will also return things that are unmodified by the overriding systems (like getWailaStack).

 * An instance of this interface is passed to most of Waila Block/TileEntity callbacks.
 * @author ProfMobius
 *
 */

public interface IWailaDataAccessor{

	World        		 getWorld();
	EntityPlayer 		 getPlayer();
	Block        		 getBlock();
	int          		 getBlockID();
	String               getBlockQualifiedName();
	int          		 getMetadata();
	TileEntity           getTileEntity();
	MovingObjectPosition getPosition();
	Vec3                 getRenderingPosition();
	NBTTagCompound       getNBTData();
	int                  getNBTInteger(NBTTagCompound tag, String keyname);
	double               getPartialFrame();
	ForgeDirection       getSide();
	ItemStack            getStack();
}


text:
layout: default
published: true
---

{{ page.title }}

    {{ content }}

  {% include disqus.html %}


text:
"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon"));
var _jsxRuntime = require("react/jsx-runtime");
var _default = (0, _createSvgIcon.default)([/*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
  d: "M11 15h2v2h-2zm0-8h2v6h-2z"
}, "0"), /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
  d: "M5.01 1v22H19V1H5.01zM17 18H7V6h10v12z"
}, "1")], 'SecurityUpdateWarningSharp');
exports.default = _default;


text:
//============================================================================
//
//	Copyright (c) 1999-2015. All Rights Reserved.
//
//----------------------------------------------------------------------------
//
//	Fichero: TPDUDatosRtx.java  1.0 9/9/99
//
//	Descripción: Clase TPDUDatosRtx.
//
// 	Authors:
//		 Alejandro García-Domínguez (alejandro.garcia.dominguez@gmail.com)
//		 Antonio Berrocal Piris (antonioberrocalpiris@gmail.com)
//
//  Historial:
//  07.04.2015 Changed licence to Apache 2.0
//
//  This file is part of PTMF
//
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
//----------------------------------------------------------------------------

package ptmf;

import java.util.TreeMap;
import java.util.Iterator;
import java.util.Vector;

/**
 * Clase TPDU Datos Rtx.

 * Hereda de la clase TPDUDatos.

 *
 * Para crear un objeto de esta clase se tienen que usar los métodos estáticos.
 * Una vez creado no puede ser modicado.

 *
 * El formato completo del TPDU Datos Rtx es:

 *

 *                      1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3

 * +0-1-2-3-4-5-6-7-8-9-0-1-2-3-4-5-6-7-8-9-0-1-2-3-4-5-6-7-8-9-0-1

 * +---------------------------------------------------------------+

 * +      Puerto Mulitcast         |          Puerto Unicast       +

 * +---------------------------------------------------------------+

 * +                        ID_GRUPO_LOCAL                         +

 * +                      (4 bytes primeros)                       +

 * +---------------------------------------------------------------+

 * +      ID_GRUPO_LOCAL           |            Longitud           +

 * +    (2 bytes últimos)          |                               +

 * +---------------------------------------------------------------+

 * +                               |   | | | | | |A|I|F|F|         +

 * +           Cheksum             | V |0|1|0|0|1|C|R|I|I| / / / / +

 * +                               |   | | | | | |K| |N|N|         +

 * +                               |   | | | | | | | |C|T|         +

 * +---------------------------------------------------------------+

 * +        Tamaño Ventana Fuente  |     Número Ráfaga Fuente      +

 * +---------------------------------------------------------------+

 * +                     ID_GRUPO_LOCAL Fuente                     +

 * +                       (4 primeros bytes)                      +

 * +---------------------------------------------------------------+

 * +ID_GRUPO_LOCAL Fuente (2 bytes)| Dirección IP Fuente (2 bytes) +

 * +---------------------------------------------------------------+

 * +  Dirección IP Fuente (2 bytes)|  Puerto Unicast Fuente        +

 * +---------------------------------------------------------------+

 * +                    Número de Secuencia Fuente                 +

 * +---------------------------------------------------------------+

 * + Número de     |   Número de   |    Dirección IP 1 (2 bytes)   +

 * +   Socket      |    IDGLs      |    (no enviado asentimiento)  +

 * +---------------------------------------------------------------+

 * +    Dirección IP1   (2 bytes)  |         Puerto Unicast 1      +

 * +    no enviado asentimiento)   |                               +

 * +---------------------------------------------------------------+

 * +                              ....                             +

 * +---------------------------------------------------------------+

 * +                   IDGL Hijo 1   (4 primeros bytes)            +

 * +---------------------------------------------------------------+

 * + IDGL Hijo 1 (2 últimos bytes) | IDGL Hijo 2 (2 primeros bytes)+

 * +---------------------------------------------------------------+

 * +                  IDGL Hijo 2 (4 bytes últimos)                +

 * +---------------------------------------------------------------+

 * +                              ...                              +

 * +---------------------------------------------------------------+

 * +                            Datos                              +

 * +---------------------------------------------------------------+

 * +                              ...                              +

 * +---------------------------------------------------------------+

 *

 *

 * Esta clase no es thread-safe.

 * @see      Buffer
 * @version  1.0
 * @author M. Alejandro García Domínguez
 * (alejandro.garcia.dominguez@gmail.com)

 * Antonio Berrocal Piris
 * (AntonioBP@wanadoo.es)

 */
public class TPDUDatosRtx extends TPDUDatos
{
  // ATRIBUTOS

  /** Longitud de los datos comunes a todos los TPDUDatosRtx*/
  private static final int LONGHEADER = (9 * 4) +2;

  /**
   * Tamaño de ventana (16 bits):

   */

  int TAMAÑO_VENTANA = 0;

  /**
   * IR (1 bit): Inicio de ráfaga
   */
  private byte IR = 0;

  /**
   * FIN_CONEXION (1 bit): Fin de la conexión
   */
  byte FIN_CONEXION = 0;

  /**
   * FIN_TRANSMISION (1 bit): Fin de la transmisión
   */
  byte FIN_TRANSMISION = 0;

  /**
   * ACK (1 bit):
   */
  private byte ACK = 0;

  /**
   * Número de ID_Sockets (8 bits): número de id_sockets que contiene la lista
   * de no asentidos.
   */
  private byte NUMERO_DE_SOCKET = 0;

  /**
   * Número de IDGLS (8 bits):número de idgls que contiene la lista
   * de no asentidos.
   */
  private byte NUMERO_IDGL = 0;

  /**
   * IDGL Fuente (48 bits)
   */
  private IDGL IDGL_FUENTE = null;

  /**
   * ID TPDU Fuente : (10 bytes)
   *                    ID Socket Fuente (6 byte)
   *                            Dirección IP Fuente (4 byte)
   *                            Puerto Unicast Fuente (2 byte)
   *                    Número secuencia Fuente (4 bytes)
   */
   private ID_TPDU ID_TPDU_FUENTE = null;

   /**
    *  Número de ráfaga fuente (16 bits)
    */
   private int NUMERO_RAFAGA_FUENTE = 0;

   /**
    * Lista con los id_sockets de los que no ha recibido ACK.
    *

    *
  Key:
    *	    {@link ID_Socket}.
    *

    *
  Value:
    *	    NULL
    *

    *

    */
   private TreeMap LISTA_ORD_ID_SOCKET = null;

   /**
    * Lista con los idgls de los que no ha recibido HACK o HSACK.
    *

    *
  Key:
    *	    {@link IDGL}.
    *

    *
  Value:
    *	    NULL
    *

    *

    */
   private TreeMap LISTA_ORD_IDGL = null;

   /** Datos */
   private Buffer BUFFERDATOS = null;

  //==========================================================================
  /**
   * Constructor utilizado para crear un TPDUDatosRtx.
   * @param socketPTMFImp Objeto SocketPTMFImp del que obtiene el valor de los
   * campos de la cabecera común.
   * @exception PTMFExcepcion
   * @exception ParametroInvalidoExcepcion lanzada si socketPTMFImp es null
   */
  private TPDUDatosRtx (SocketPTMFImp socketPTMFImp)
    throws PTMFExcepcion,ParametroInvalidoExcepcion
  {
   super (socketPTMFImp);
  }

  //==========================================================================

  /**
   * Constructor por defecto.
   * Este constructor es para crear TPDUS a partir del parser de un Buffer
   * @exception PTMFExcepcion
   * @exception ParametroInvalido Se lanza en el constructor de la clase TPDU.
   */
  private TPDUDatosRtx ()

      throws ParametroInvalidoExcepcion,PTMFExcepcion

  {

   super();

  }

 //============================================================================
 /**
  * Crea un vector de TPDUDatosRtx con la información facilitada.
  * El buffer de datos tiene que caber en el TPDU Datos rtx.

  * Todos los TPDU Datos Rtx creados son iguales, excepto en la lista de
  * identificadores de id_socket e idgl que no han enviado asentimiento.

  * La unión de todas las listas de id_sockets e idgls de los TPDUDatosRtx del
  * vector creado es igual a las listas pasadas por argumentos, sin repeticiones.
  * @param socketPTMFImp utilzado para obtener información de la cabecera
  * común a todos los TPDU.

  * @param setIR

  * @param setACK
  * @param setFIN_CONEXION
  * @param setFIN_TRANSMISION
  * @param numeroRafagaFuente
  * @param idglFuente
  * @param id_tpduFuente
  * @param treeMapID_Socket contiene los id_sockets que no han enviado ACK
  * para el TPDU Datos Rtx.

  * @param treeMapIDGL contiene los idgls que no han enviado HACK o HSACK

  * para el TPDU Datos Rtx.

  * @param datos

  * @return vector con los TPDUDatosRtx formados

  * @exception ParametroInvalidoExcepcion si alguno de los parámetros es erróneo.

  * @exception PTMFExcepcion si hay un error al crear los TPDUDatosRtx a partir

  * de la información facilitada en los argumentos.

  */

 static Vector crearVectorTPDUDatosRtx (SocketPTMFImp socketPTMFImp,
                                        boolean setIR,
                                        boolean setACK,
                                        boolean setFIN_CONEXION,
                                        boolean setFIN_TRANSMISION,
                                        int numeroRafagaFuente,
                                        IDGL idglFuente,
                                        ID_TPDU id_tpduFuente,
                                        TreeMap treeMapID_Socket,
                                        TreeMap treeMapIDGL,
                                        Buffer datos)
   throws ParametroInvalidoExcepcion, PTMFExcepcion
 {
  final String mn = "TPDUDatosRtx.crearVectorTPDUDatosRtx (socketPTMFImp,...)";

   int capacidad = 0;

   Vector vectorTPDURtx = new Vector();
   Iterator iteradorID_Socket = null;
   Iterator iteradorIDGL = null;

   if (datos!=null)
     capacidad = PTMF.TPDU_MAX_SIZE - datos.getMaxLength() - TPDUDatosRtx.LONGHEADER;
   else capacidad = PTMF.TPDU_MAX_SIZE - TPDUDatosRtx.LONGHEADER;
   // Número de identificadores que caben.

   boolean incluirNoAsentido = false;

   if (treeMapID_Socket!=null)
       if (!treeMapID_Socket.isEmpty())
         {
          iteradorID_Socket = treeMapID_Socket.keySet().iterator();
          incluirNoAsentido = true;
         }

   if (treeMapIDGL!=null)
        if (!treeMapIDGL.isEmpty())
          {
           iteradorIDGL      = treeMapIDGL.keySet().iterator();
           incluirNoAsentido = true;
          }

   // Al menos capacidad deberá ser mayor o igual a 6 para que quepa un IDGL o
   // ID_Socket.
   if (incluirNoAsentido && (capacidad < 6))
     throw new PTMFExcepcion ("No hay espacio para añadir ningún identificador.");

   boolean finWhile = false;
   while (!finWhile)
   {
    TreeMap treeMapID_SocketAux = null;
    TreeMap treeMapIDGLAux = null;
    int numIDCaben = capacidad / 6;

    // Incluir todos los id_socket que quepan.
    if ((iteradorID_Socket!=null) && (numIDCaben > 0))
    {
     treeMapID_SocketAux = new TreeMap ();
     while (iteradorID_Socket.hasNext())
      {
       treeMapID_SocketAux.put (iteradorID_Socket.next(),null);
       numIDCaben --;
       if (numIDCaben <= 0)
           continue;
      } // Fin del while de iteradorID_Socket
    } // Fin del if iteradorID_Socket

    // Incluir todos los idgl que quepan.
    if (iteradorIDGL!=null && numIDCaben > 0)
     {
      treeMapIDGLAux = new TreeMap();
      while (iteradorIDGL.hasNext())
       {
        treeMapIDGLAux.put (iteradorIDGL.next(),null);
        numIDCaben --;
        if (numIDCaben <= 0)
            continue;
       } // Fin del while de iteradorIDGL
      } // Fin del if de iteradorIDGL

     // Formar el TPDU y añadirlo al vector
     TPDUDatosRtx tpduDatosRtx;

     // Crear el TPDUDatosRtx vacio
     tpduDatosRtx = new TPDUDatosRtx (socketPTMFImp);

     // Guardar los datos en la cabecera para cuando sean pedidos
     if (treeMapID_SocketAux!=null)
       {
        tpduDatosRtx.NUMERO_DE_SOCKET = (byte)treeMapID_SocketAux.size ();
        tpduDatosRtx.LISTA_ORD_ID_SOCKET = treeMapID_SocketAux;
       }
     else
         {
          tpduDatosRtx.NUMERO_DE_SOCKET = 0;
          tpduDatosRtx.LISTA_ORD_ID_SOCKET = null;
         }

     if (treeMapIDGLAux!=null)
      {
       tpduDatosRtx.NUMERO_IDGL = (byte)treeMapIDGLAux.size ();
       tpduDatosRtx.LISTA_ORD_IDGL = treeMapIDGLAux;
      }
     else
         {
          tpduDatosRtx.NUMERO_IDGL = 0;
          tpduDatosRtx.LISTA_ORD_IDGL = null;
         }

     tpduDatosRtx.IR  = (byte)(setIR  ? 1 : 0);
     tpduDatosRtx.ACK = (byte)(setACK ? 1 : 0);
     tpduDatosRtx.FIN_CONEXION = (byte)(setFIN_CONEXION ? 1 : 0);
     tpduDatosRtx.FIN_TRANSMISION = (byte)(setFIN_TRANSMISION ? 1 : 0);
     tpduDatosRtx.NUMERO_RAFAGA_FUENTE = numeroRafagaFuente;
     tpduDatosRtx.IDGL_FUENTE = idglFuente;

     tpduDatosRtx.ID_TPDU_FUENTE = id_tpduFuente; // No es necesario clonarlo,
                                                  // no puede ser modificado.

     tpduDatosRtx.BUFFERDATOS = (Buffer)datos;

     // Añadir al vector
     vectorTPDURtx.add (tpduDatosRtx);

     // Evaluar condición de finalización
     finWhile = (iteradorID_Socket == null || !iteradorID_Socket.hasNext())
                &&
                (iteradorIDGL == null || !iteradorIDGL.hasNext());
   } // Fin del while (true)

  return vectorTPDURtx;
 }

  //==========================================================================
  /**
   * Construir el TPDU Datos Rtx, devuelve un buffer con el contenido del TPDUDatosRtx,
   * según el formato especificado en el protocolo.
   * Este buffer no debe de ser modificado.
   * @return un buffer con el TPDUDatosRtx.
   * @exception PTMFExcepcion Se lanza si ocurre algún error en la construcción
   * del TPDU
   * @exception ParametroInvalidoExcepcion lanzada si ocurre algún error en la
   * construcción del TPDU
   */
 Buffer construirTPDUDatosRtx () throws PTMFExcepcion,ParametroInvalidoExcepcion
 {
  final String mn = "TPDU.construirTPDUDatosRtx";
  int offset = 14;

   int tamaño = TPDUDatosRtx.LONGHEADER + this.NUMERO_DE_SOCKET*6 + this.NUMERO_IDGL*6;
   if (this.BUFFERDATOS!=null)
      tamaño += this.BUFFERDATOS.getMaxLength();

   // Crear la cabecera común a todos los TPDU
   Buffer bufferResult = this.construirCabeceraComun (PTMF.SUBTIPO_TPDU_DATOS_RTX,tamaño);

   // 15º BYTE : ACK : (1 bit)
   short anterior = bufferResult.getByte (offset);
   // anterior : XXXX XXXX
   //      and : 1111 1110 = 0xFE
   //           ----------
   //            XXXX XXX0
   //   ACK    : 0000 000X = 0x01
   //           ----------
   //            XXXX XXXX
   anterior &= 0xFE;
   bufferResult.addByte((byte)((this.ACK & 0x01) | anterior),offset);
   offset++;

   // 16º BYTE : IR (1 bit) y FIN_CONEXION (1bit)

   //                   IR : X000  0000

   //          FIN_CONEXION: 0X00  0000

   //       FIN_TRANSMISION: 00X0  0000

   bufferResult.addByte ((byte)(((this.IR<<7)&0x80) | ((this.FIN_CONEXION<<6)&0x40)  | ((this.FIN_TRANSMISION<<5)&0x20)),offset);

   offset++;

   // 17º Y 18º BYTE : TAMAÑO VENTANA

   bufferResult.addShort (this.TAMAÑO_VENTANA,offset);
   offset+=2;

   // 19º Y 20º BYTE : Número de Ráfaga Fuente
   bufferResult.addShort (this.NUMERO_RAFAGA_FUENTE,offset);
   offset+=2;

   // 21º , 22º, 23º y 24º BYTE : IDGL Fuente
   if ( ( this.IDGL_FUENTE == null)
           || ( this.IDGL_FUENTE.id.getMaxLength() != 6))
      {
        bufferResult.addInt(0,offset);
        bufferResult.addShort(0,offset+4);
      }
      else
      {
        bufferResult.addBytes( this.IDGL_FUENTE.id,0,offset,6 /*longitud*/);
      }

   offset+=6;

   // 25º, 26º, 27º y 28º BYTE : Dirección IP Fuente
   bufferResult.addBytes (this.ID_TPDU_FUENTE.getID_Socket().getDireccion().ipv4,
                                                                    0,offset,4);
   offset+=4;

   // 29º y 30º BYTE : Puerto Unicast Fuente
   bufferResult.addShort (this.ID_TPDU_FUENTE.getID_Socket().getPuertoUnicast(),
                                                                        offset);
   offset+=2;

   // 31º, 32º, 33º y 34º BYTE : Número de Secuencia Fuente
   bufferResult.addInt (this.ID_TPDU_FUENTE.getNumeroSecuencia().tolong(),offset);
   offset+=4;

   // 35º BYTE : Número de socket
   bufferResult.addByte (this.NUMERO_DE_SOCKET,offset);
   offset++;

   // 36º BYTE : Número de IDGLs
   bufferResult.addByte (this.NUMERO_IDGL,offset);
   offset++;

   // [37º ...  this.NUMERO_DE_SOCKET] BYTE : [IP,Puerto Unicast]
   if (this.NUMERO_DE_SOCKET>0)
     {
      Iterator iteradorID_Socket = this.LISTA_ORD_ID_SOCKET.keySet().iterator();
      ID_Socket id_SocketNext = null;
      while (iteradorID_Socket.hasNext())
       {
        id_SocketNext = (ID_Socket)iteradorID_Socket.next();
        // Añadir IP
        bufferResult.addBytes (id_SocketNext.getDireccion().ipv4,0,offset,4);
        offset += 4;
        // Añadir Puerto Unicast
        bufferResult.addShort (id_SocketNext.getPuertoUnicast(),offset);
        offset += 2;
       } // Fin del while
     } // Fin del if

    // Añadir treeMapIDGL
    if((this.NUMERO_IDGL > 0) && (this.LISTA_ORD_IDGL!= null))
    {
      Iterator iterator = this.LISTA_ORD_IDGL.keySet().iterator();

      while(iterator.hasNext())
      {
         IDGL idgl = (IDGL)iterator.next();

         //Añadir idgl
         bufferResult.addBytes(idgl.id,0,offset,6);
         offset+=6;
      }
    }

   // Sucesivos BYTE : Datos
   // offset apunta al byte donde tienen que ir los datos
   if (this.BUFFERDATOS!=null)
      bufferResult.addBytes (this.BUFFERDATOS,0,offset,
                      this.BUFFERDATOS.getMaxLength());

   return bufferResult;
 }

  //==========================================================================
  /**
   * Parse un Buffer de datos recibidos y crea un TPDU Datos Rtx que lo encapsule.
   * El buffer debe de contener un TPDU Datos Rtx.
   * @param buf Un buffer que contiene el TPDU Datos Rtx recibido.
   * @param ipv4Emisor dirección IP unicast del emisor.
   * @exception PTMFExcepcion El buffer pasado no contiene una cabecera TPDU
   * correcta, el mensaje de la excepción especifica el tipo de error.
   * @exception ParametroInvalidoExcepcion Se lanza si el buffer pasado no
   * contiene un TPDUDatosRtx válido.
   */
 static  TPDUDatosRtx parserBuffer (Buffer buffer,IPv4 ipv4Emisor)
   throws PTMFExcepcion,ParametroInvalidoExcepcion
 {

  final String mn = "TPDUDatosRtx.parserBuffer (buffer,ipv4)";
  int aux;
  int offset = 14;

  if (buffer==null)
     throw new ParametroInvalidoExcepcion (mn + "Buffer nulo");

  // La longitud del buffer deberá ser al menos igual a LONGHEADER
  if (TPDUDatosRtx.LONGHEADER > buffer.getMaxLength())
    throw new ParametroInvalidoExcepcion (mn + "Buffer incorrecto");

  // Crear el TPDUDatosRtx.
  TPDUDatosRtx tpduDatosRtx = new TPDUDatosRtx ();

  // Analizar los datos comunes
  TPDUDatos.parseCabeceraComun (buffer,tpduDatosRtx,ipv4Emisor);

  // Comprobar si el subtipo es correcto
  if (tpduDatosRtx.SUBTIPO != PTMF.SUBTIPO_TPDU_DATOS_RTX)
     throw new PTMFExcepcion ("Subtipo del TPDU Datos no válido");

  // 15º BYTE : ACK (1 BIT)
  aux = buffer.getByte (offset);
  //     ACK:   XXXX XXXX
  //     And:   0000 0001 = 0x01
  //            ---------
  //            0000 000X
  tpduDatosRtx.ACK = (byte)(aux & 0x01);
  offset++;

  // 16º BYTE : IR (1 bit)  Número de IP (7 bits)
  aux = buffer.getByte (offset);
  //      IR:   XXXX XXXX
  //     And:   1000 0000 = 0x80
  //            ---------
  //            X000 0000
  //     >>>:   0000 000X
  tpduDatosRtx.IR = (byte) ((aux & 0x80) >>> 7);
  //     FIN_CONEXION:   XXXX XXXX
  //     And:   0100 0000 = 0x40
  //            ---------
  //            0X00 0000
  //     >>>:   0000 000X
  tpduDatosRtx.FIN_CONEXION = (byte) ((aux & 0x40) >>> 6);
  //     FIN_TRANSMISION:   XXXX XXXX
  //     And:   0100 0000 = 0x40
  //            ---------
  //            00X0 0000
  //     >>>:   0000 000X
  tpduDatosRtx.FIN_TRANSMISION = (byte) ((aux & 0x20) >>> 5);
  offset ++;

  //
  // 17º y 18º BYTE : Número de ráfaga Fuente
  //
  tpduDatosRtx.NUMERO_RAFAGA_FUENTE = buffer.getShort (offset);
  offset+=2;

  //
  // 17º y 18º BYTE : Número de ráfaga Fuente
  //
  tpduDatosRtx.NUMERO_RAFAGA_FUENTE = buffer.getShort (offset);
  offset+=2;

  // 19º, 20º, 21º ,22º, 23º y 24º BYTE : IDGL Fuente
  tpduDatosRtx.IDGL_FUENTE =
                   new IDGL (new Buffer(buffer.getBytes(offset,(byte) 6)),(byte)0);
  offset+=6;

  // 25º, 26º, 27º y 28º BYTE : Dirección IP Fuente
  IPv4 ipFuente = new IPv4 (new Buffer (buffer.getBytes(offset,4)));
  offset+=4;

  // 29º y 30º BYTE : Puerto Unicast Fuente
  int puertoUnicastFuente = buffer.getShort (offset);

  offset+=2;

  //
  // 31º, 32º, 33º y 34º BYTE : Número de Secuencia Fuente
  //
  NumeroSecuencia nSecFuente = new NumeroSecuencia (buffer.getInt (offset));
  offset+=4;

  // Construir el ID_TPDU_FUENTE
  tpduDatosRtx.ID_TPDU_FUENTE = new ID_TPDU (

                                new ID_Socket (ipFuente,puertoUnicastFuente),
                                nSecFuente);

  // 35º BYTE : Número de Socket
  tpduDatosRtx.NUMERO_DE_SOCKET = (byte)buffer.getByte (offset);
  offset++;

  // 36º BYTE : Número de IDGLs
  tpduDatosRtx.NUMERO_IDGL = (byte)buffer.getByte (offset);
  offset++;

  // [37º ...  tpduDatosRtx.NUMERO_DE_SOCKET] BYTE : [IP,Puerto Unicast]
  // Comprueba la longitud. Cada ID_Socket ocupa 6 bytes
  if (buffer.getMaxLength()<(tpduDatosRtx.LONGHEADER + tpduDatosRtx.NUMERO_DE_SOCKET*6))
        throw new PTMFExcepcion (mn+"Error en el parser");

  // Crear la lista
  if (tpduDatosRtx.NUMERO_DE_SOCKET>0)
       tpduDatosRtx.LISTA_ORD_ID_SOCKET = new TreeMap ();

  ID_Socket id_Socket = null;
  IPv4           ipv4 = null;
  for (int i=0;i<tpduDatosRtx.NUMERO_DE_SOCKET;i++)
   {
    ipv4 = new IPv4 (new Buffer (buffer.getBytes(offset,4)));
    offset += 4;
    id_Socket = new ID_Socket (ipv4,buffer.getShort (offset));
    offset += 2;

    tpduDatosRtx.LISTA_ORD_ID_SOCKET.put (id_Socket,null);
   }

  if( tpduDatosRtx.NUMERO_IDGL > 0)
   {
    tpduDatosRtx.LISTA_ORD_IDGL = new TreeMap();

    //Obtener IDGLs
    for(int i = 0 ; i < tpduDatosRtx.NUMERO_IDGL; i++)
     {
      tpduDatosRtx.LISTA_ORD_IDGL.put(new IDGL(new Buffer(buffer.getBytes(offset,6)),(byte)0) ,null);
      offset+=6;
     }
    }

  // tpduDatosRtx.NUMERO_DE_IP  y sucesivos BYTE : Datos
  // offset apunta al byte donde tienen que ir los datos
  int tamañoDatos = buffer.getMaxLength() - tpduDatosRtx.LONGHEADER -
                   tpduDatosRtx.NUMERO_DE_SOCKET*6 - tpduDatosRtx.NUMERO_IDGL*6;

  if (tamañoDatos>0)

     tpduDatosRtx.BUFFERDATOS = new Buffer (buffer.getBytes (offset,tamañoDatos));

  else tpduDatosRtx.BUFFERDATOS = null;

  return tpduDatosRtx;
 }

 //============================================================================

 /**

  * Construye un TPDUDatosNormal.

  */

 TPDUDatosNormal convertirATPDUDatosNormal ()

                             throws ParametroInvalidoExcepcion, PTMFExcepcion

 {

  final String mn = "TPDUDatosRtx.convertirATPDUDatosNormal()";

  return TPDUDatosNormal.crearTPDUDatosNormal (

                          this.PUERTO_MULTICAST,

                          this.ID_TPDU_FUENTE.getID_Socket().getPuertoUnicast(),

                          this.IDGL_FUENTE,

                          this.ID_TPDU_FUENTE.getID_Socket().getDireccion(),

                          ((this.IR  == 1) ? true : false),

                          ((this.ACK == 1) ? true : false),

                          ((this.FIN_CONEXION == 1) ? true : false),

                          ((this.FIN_TRANSMISION == 1) ? true : false),

                          this.NUMERO_RAFAGA_FUENTE,

                          this.ID_TPDU_FUENTE.getNumeroSecuencia(),

                          this.BUFFERDATOS);

 }

 //============================================================================

 /**

  * Devuelve el número de secuencia.

  */

 NumeroSecuencia getNumeroSecuencia()

 {
   return this.ID_TPDU_FUENTE.getNumeroSecuencia();
 }

 //============================================================================

 /**

  * Devuelve true si el bit IR vale 1.

  */

 boolean getIR ()

 {
   return (this.IR==1 ? true : false);
 }

 //============================================================================

 /**

  * Devuelve true si el bit ACK vale 1.

  */

 boolean getACK()

 {
   return (this.ACK==1 ? true:false);
 }

 //============================================================================

 /**

  * Devuelve true si el bit FIN_CONEXION vale 1.

  */

 boolean getFIN_CONEXION()

 {

   return (this.FIN_CONEXION==1 ? true:false);

 }

 //============================================================================
 /**

  * Devuelve true si el bit FIN_TRANSMISION vale 1.

  */

  boolean getFIN_TRANSMISION()

 {

   return (this.FIN_TRANSMISION==1 ? true:false);

 }

//===========================================================================
 /**
  * Devuelve el ID_TPDU del que mando originalmente los datos (la fuente).
  */
 ID_TPDU getID_TPDUFuente ()
 {
   return this.ID_TPDU_FUENTE;
 }

 //===========================================================================
 /**
  * Devuelve el número de ráfaga fuente.

  */

 int getNumeroRafagaFuente ()
 {
  return this.NUMERO_RAFAGA_FUENTE;
 }

 //===========================================================================
 /**
  * Devuelve la lista de id_socket que no han enviado ACK.

  * @return lista con id_Sockets que no han enviado ACK

  *

  *
  Key:
  *	    {@link ID_Socket}.
  *

  *
  Value:
  *	    NULL
  *

  *

  */

 TreeMap getListaID_Socket ()
 {
   if (this.LISTA_ORD_ID_SOCKET==null)
     return new TreeMap ();

   return this.LISTA_ORD_ID_SOCKET;
 }

 //===========================================================================
 /**
  * Devuelve la lista de idgls que no han enviado HACK o HSACK.

  * @return lista con id_Sockets que no han enviado HACK o HSACK.

  *

  *
  Key:
  *	    {@link IDGL}.
  *

  *
  Value:
  *	    NULL
  *

  *

  */

 TreeMap getListaIDGL ()
 {
  if (this.LISTA_ORD_IDGL==null)
        return new TreeMap();

  return this.LISTA_ORD_IDGL;
 }

 //===========================================================================
 /**
  * Devuelve el tamaño de ventana.

  */

 int getTamañoVentana ()
 {
  return PTMF.TAMAÑO_VENTANA_RECEPCION;
 }

 //===========================================================================
 /**
  * Devuelve el idgl al que pertenece el emisor fuente de los datos.

  * @return idgl fuente

  */

 IDGL getIDGLFuente ()
 {
  return this.IDGL_FUENTE;
 }

 //===========================================================================
 /**

  * Devuelve una cadena informativa del TPDU Datos

  */

 public String toString()

 {

   String result = new String (

          "Puerto Multicast: " + this.getPuertoMulticast() +

          "\nPuerto Unicast: " + this.getPuertoUnicast() +

          "\nIDGL: " + this.ID_GRUPO_LOCAL +

          "\nLongitud: " + this.LONGITUD +

          "\nCHECKSUM: " + this.CHEKSUM +

          "\nVersion: " + this.VERSION +

          "\nTipo: " + this.TIPO +

          "\nSubtipo: " + PTMF.SUBTIPO_TPDU_DATOS_RTX +

          "\nACK: " + this.ACK +

          "\nIR: " + this.IR +

          "\nFIN_CONEXION: " + this.FIN_CONEXION +

          "\nFIN_TRANSMISION: " + this.FIN_TRANSMISION +

          "\nNúmero Ráfaga Fuente: " + this.NUMERO_RAFAGA_FUENTE +

          "\nIDGL Fuente: " + this.IDGL_FUENTE +

          "\nID TPDU Fuente: " + this.ID_TPDU_FUENTE

         );

   // Añadir al String los id. socket

   if (this.LISTA_ORD_ID_SOCKET != null)

     result = result + "\nID_Sockets: " + this.LISTA_ORD_ID_SOCKET;

   // Añadir al String los IDGL

   if (this.LISTA_ORD_IDGL != null)

     result = result + "\nIDGLs: " + this.LISTA_ORD_IDGL;

   result += ("\nDatos: " + this.BUFFERDATOS);

   return result;

 }

} // Fin de la clase.


text:
layout: report
title: Match Racing - Announcements
type: news
grouped: 2012.matchracing
header_text:  New Year Announcements
subheader_text: Latest Happenings
author: The Match Racing Team
---
The New Year has kicked our program up a gear with the addition of a new bowman: Oliver Neal.

On top of our weekly strategy sessions and meetings, the team will be travelling to Bermuda over reading week for an intense five-day training session at their World Match Racing Tour Venue!

The Queen's female team will be joining us in Bermuda for the week, which will be a great addition to our training.

Meanwhile, our team resume has been submitted to CICSA for verification, and we are eagerly awaiting their decision.


text:
<?xml version="1.0" encoding="utf-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         version="2.5">

  <filter>
    <filter-name>LoginFilter</filter-name>
    <filter-class>com.tozny.sdk.example.secretmessage.LoginFilter</filter-class>
  </filter>

  <filter-mapping>
    <filter-name>LoginFilter</filter-name>
    <url-pattern>/protected/*</url-pattern>
  </filter-mapping>

  <filter>
    <filter-name>JerseyServletContainer</filter-name>
    <filter-class>org.glassfish.jersey.servlet.ServletContainer</filter-class>
    <init-param>
      <param-name>javax.ws.rs.Application</param-name>
      <param-value>com.tozny.sdk.example.secretmessage.Application</param-value>
    </init-param>
    <init-param>
      <param-name>jersey.config.servlet.filter.staticContentRegex</param-name>
      <param-value>.*\.(css|js)$</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </filter>

  <filter-mapping>
    <filter-name>JerseyServletContainer</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

</web-app>


text:
using Android.Content;
using Sunny.Core;
using Cirrious.CrossCore.Platform;
using Cirrious.MvvmCross.Droid.Platform;
using Cirrious.MvvmCross.ViewModels;
using System.Globalization;

namespace Sunny.Droid
{
    public class Setup : MvxAndroidSetup
    {
        public Setup(Context applicationContext) : base(applicationContext)
        {
        }

        protected override IMvxApplication CreateApp()
        {
			var culture = CultureInfo.CurrentCulture;
			return new Core.App(culture.Name);
        }

        protected override IMvxTrace CreateDebugTrace()
        {
            return new DebugTrace();
        }
    }
}


text:
layout: post
category: articles
tags: [ puppet, bugs, features, code ]
summary: An account of the creation of yet another long awaited feature. First part of two.
---

### Overview

One of the most requested capabilities for Puppet has been to support code
such as the following:

    file {
      '/opt/jdk.tar.gz':
        source => 'http://filerepo.local/java/jdk.tar.gz',
    }

Retrieving files (especially larger archives) via HTTP is a very convenient
practice. People have been doing it through custom `exec` resources and
defined types all over the place, for years. There are
[several](https://forge.puppetlabs.com/camptocamp/archive) sophisticated
[modules](https://forge.puppetlabs.com/nanliu/staging) that bring this
capability along.

Still, all these approaches lack some of the convenience that Puppet's `file`
type brings to the table.

 * The `file` type will use checksums or time stamps to decide whether
 a file needs downloading again.
 * With `file` resources, Puppet can back files up locally or to a master
 node prior to overwriting.

There may be more benefits of which I am not even aware.

Implementing this capability appears to be straight forward enough:

 1. Allow HTTP URLs for the `source` property
 2. Extract metadata from the HTTP headers
 3. Connect to a webserver in lieu of the Puppet fileserver for retrieval

I believe that it was primarily the second step that kept the Puppet Labs
engineers from just forking off some time at some point. HTTP headers don't
carry information that is quite as rich as Puppet's fileserver metadata.
Fortunately, this gap can be filled with a few compromises.

### Designing the semantics

The agent synchronizes local files with content from the master in two steps.
First, an API call is made to retrieve the master's file metadata. This data
is sufficient for the agent to decide whether it also needs to retrieve the
contents. If so, it makes a separate call to the master.

Allowing Puppet to download content through HTTP and HTTPS is simple to the
point of almost being trivial. Subsystems such as the Puppet Module Tool
(i.e., `puppet module install` and friends) already implement a client.
The file metadata portion is all the more challenging. The Puppet fileserver
presents the following aspects to the agent:

 * `path`
 * `owner`
 * `group`
 * `mode`
 * `file type`
 * `destination` (applicable to symbolic links)
 * `checksum` (along with the `checksum_type`)

The `path` is actually passed by the agent. It holds no information about the
server side file. `owner`, `group` and `mode` are typical file system attributes.
As for the `type` of files that Puppet will manage, there are but three
supported alternatives:

 * plain file
 * directory
 * symbolic link

Finally, there are a number of different `checksum` algorithms that Puppet supports:

 * `md5` (and `md5lite`)
 * `sha1` (and `sha1lite`)
 * `sha256` (and `sha256lite`)
 * `mtime` and `ctime`
 * `none`

The `md5`, `sha1` and `sha256` types are actual hash sums that can safely (and
in the case of `sha256`, securely) represent a whole file's content succinctly
and in an easily comparable fashion. The respective `lite` variant will only consider the first
half kilobyte (or rather, kibibyte) of data. This will safe some computing power
(lots of it in case of large files), but it leaves your agents prone to miss some
upstream changes such as appending new data to an old file.

Selecting `none` is usually not sensible for files that are getting synchronized
from any kind of fileserver, because each agent run will cause another download
of the whole file. `mtime` and `ctime` are more sensible: You get a light-weighed means
of estimating whether a file was changed upstream after downloading it. (General
piece of advice: You almost never want `ctime` for most practical queries. Just
stick to `mtime`.)

### Enter HTTP

So Puppet supports a rather rich set of file metadata. This is only natural,
given that file management is probably one of the most frequent activities
of the Puppet agent. Most of these properties are not represented in the
HTTP standard at all. Web servers can choose to include information beyond
the specification in custom headers. However, the currently predominant web servers
don't, for the most part.

Specifically, `owner`, `group` and `mode` are not *meant* to be communicated
to browsers and other HTTP clients. As for `file type`, its different valences
can, in theory, be mapped to different HTTP responses:

 * plain files, represented by regular old responses with code 200 and a body,
 which comprises the file content
 * directories, transferred in the form of directory indexes. Technically,
 these are plain resources that contain links to other resources (directory
 entries) in their body.
 * symbolic links, along with the `destination` attribute. Their HTTP equivalent
 is the 30X redirect. It carries a destination in the `Location` header.

However, actually mapping redirects to symlinks would be very awkward. First off,
the redirect location will point to a path that is only meaningful in the context of
the HTTP server it references. It cannot be safely assumed that the *path* portion
of the target URL can be used as a symlink target on the agent system.
What's more, the user will often expect Puppet to actually follow redirects,
so that "friendly" URLs, shortened URLs, and so forth, just work.

As for directory indexes, adding special handling for those would make Puppet
an actual web spider. I can see use cases for that, but then synchronizing
whole directory trees is not a very common nor commendable practice. For these
reasons, I settled for no special handling of neither directory indexes nor
redirects. All HTTP content is implicitly considered to represent plain files.

### Checksums from headers

We have discussed the mapping of almost all metadata fields to HTTP headers,
except the checksum. The good news is that `md5` sums at least
used to be supported in the form of the `Content-MD5` header. It was
[removed](http://tools.ietf.org/html/rfc7231#appendix-B) from the standard
because it was "inconsistently implemented with respect to partial responses",
but Apache will generate it for static resources when the `ContentDigest`
option is set. For generated content and alternate server software,
we're still stuck with relying on an alternative.

The `sha` variants are not provided by any HTTP standard. When push comes
to shove, metadata can always be construed as having a `none` type checksum
(i.e., there is no checksum whatsoever). However, most webservers include
`Last-Modified` headers in their responses if possible. As I mentioned earlier,
`ctime` is rarely appropriate. It is also a bad fit for the HTTP header, so
I opted to map it to the `mtime` checksum type. It is the most common type
of "checksum" that is extractable from HTTP headers.

Unfortunately, the `file` type is hardcoded to try and use an `md5` checksum
by default. It will not automatically fall back to a different type, even when
the server won't present a suitable checksum. In practice that means that
the following resource leads to a result that is less than desirable:

    file {
      '/opt/jdk.tar.gz':
        source => 'http://filerepo.local/java/jdk.tar.gz',
    }

Even when the `filerepo.local` server does not supply a `Content-MD5` header with
the requested resource, the Puppet agent will compute the `md5` sum of the local
file's content. It cannot possibly match the `mtime` type checksum that is
derived from the HTTP headers. Therefor, Puppet will insist in continuously
synchronizing the file with the upstream server, until the checksum type is
changed explicitly:

    file {
      '/opt/jdk.tar.gz':
        source   => 'http://filerepo.local/java/jdk.tar.gz',
        checksum => 'mtime',
    }

This effect is a little hard to explain, but will become more obvious during the
next part. This post is part one of two. The second installment is to appear
soon, and will deal with the technical details of the feature implementation.


text:
<?php
declare(strict_types=1);

namespace ManaPHP\Http;

interface UrlInterface
{
    public function get(string|array $args, bool|string $scheme = false): string;
}


text:
To test the database upgrade you have to build the SQL scripts

```
cd camunda-bpm-platform/distro/sql-script
mvn clean install
```

and the engine test jar

```
cd camunda-bpm-platform/engine
mvn clean install -Pcreate-test-jar
```

Then you can execute the test for the current major version (e.g. 72) and database (e.g. postgres)

```
mvn clean install -Pupgrade,${CURRENT_MAJOR_VERSION},${DATABASE}
```


text:
<?xml version="1.0" encoding="UTF-8"?>
<Form xmlns="http://v8.1c.ru/8.3/xcf/logform" xmlns:app="http://v8.1c.ru/8.2/managed-application/core" xmlns:cfg="http://v8.1c.ru/8.1/data/enterprise/current-config" xmlns:dcscor="http://v8.1c.ru/8.1/data-composition-system/core" xmlns:dcsset="http://v8.1c.ru/8.1/data-composition-system/settings" xmlns:ent="http://v8.1c.ru/8.1/data/enterprise" xmlns:lf="http://v8.1c.ru/8.2/managed-application/logform" xmlns:style="http://v8.1c.ru/8.1/data/ui/style" xmlns:sys="http://v8.1c.ru/8.1/data/ui/fonts/system" xmlns:v8="http://v8.1c.ru/8.1/data/core" xmlns:v8ui="http://v8.1c.ru/8.1/data/ui" xmlns:web="http://v8.1c.ru/8.1/data/ui/colors/web" xmlns:win="http://v8.1c.ru/8.1/data/ui/colors/windows" xmlns:xr="http://v8.1c.ru/8.3/xcf/readable" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
	<WindowOpeningMode>LockOwnerWindow</WindowOpeningMode>
	<VerticalScroll>useIfNecessary</VerticalScroll>
	<UseForFoldersAndItems>Items</UseForFoldersAndItems>
	<AutoCommandBar name="ФормаКоманднаяПанель" id="-1"/>
	<Events>
		<Event name="AfterWrite">ПослеЗаписи</Event>
		<Event name="OnReadAtServer">ПриЧтенииНаСервере</Event>
		<Event name="OnCreateAtServer">ПриСозданииНаСервере</Event>
		<Event name="BeforeWriteAtServer">ПередЗаписьюНаСервере</Event>
	</Events>
	<ChildItems>
		<InputField name="Код" id="1">
			<EditMode>EnterOnInput</EditMode>
			<ContextMenu name="КодКонтекстноеМеню" id="2"/>
			<ExtendedTooltip name="КодExtendedTooltip" id="9"/>
		</InputField>
		<InputField name="Наименование" id="3">
			<DataPath>Объект.Description</DataPath>
			<EditMode>EnterOnInput</EditMode>
			<ContextMenu name="НаименованиеКонтекстноеМеню" id="4"/>
			<ExtendedTooltip name="НаименованиеExtendedTooltip" id="10"/>
		</InputField>
		<Table name="КомпоновщикНастроекНастройкиОтбор" id="5">
			<Representation>Tree</Representation>
			<Autofill>true</Autofill>
			<InitialTreeView>ExpandAllLevels</InitialTreeView>
			<EnableStartDrag>true</EnableStartDrag>
			<EnableDrag>true</EnableDrag>
			<DataPath>КомпоновщикНастроек.Settings.Filter</DataPath>
			<SearchStringLocation>None</SearchStringLocation>
			<ViewStatusLocation>None</ViewStatusLocation>
			<SearchControlLocation>None</SearchControlLocation>
			<ViewMode>All</ViewMode>
			<SettingsNamedItemDetailedRepresentation>false</SettingsNamedItemDetailedRepresentation>
			<ContextMenu name="КомпоновщикНастроекНастройкиОтборКонтекстноеМеню" id="6"/>
			<AutoCommandBar name="КомпоновщикНастроекНастройкиОтборКоманднаяПанель" id="7">
				<ChildItems>
					<Button name="КомпоновщикНастроекНастройкиОтборСвойстваЭлементаПользовательскойНастройки" id="8">
						<Type>CommandBarButton</Type>
						<Visible>false</Visible>
						<CommandName>Form.Item.КомпоновщикНастроекНастройкиОтбор.StandardCommand.UserSettingItemProperties</CommandName>
						<Parameter xsi:nil="true"/>
						<ExtendedTooltip name="КомпоновщикНастроекНастройкиОтборСвойстваЭлементаПользовательскойНастройкиExtendedTooltip" id="11"/>
					</Button>
				</ChildItems>
			</AutoCommandBar>
			<ExtendedTooltip name="КомпоновщикНастроекНастройкиОтборExtendedTooltip" id="12"/>
			<SearchStringAddition name="КомпоновщикНастроекНастройкиОтборSearchString" id="13">
				<Source>
					<lf:elementId>5</lf:elementId>
					<lf:additionId>0</lf:additionId>
				</Source>
				<ContextMenu name="КомпоновщикНастроекНастройкиОтборSearchStringContextMenu" id="14"/>
				<ExtendedTooltip name="КомпоновщикНастроекНастройкиОтборSearchStringExtendedTooltip" id="15"/>
			</SearchStringAddition>
			<ViewStatusAddition name="КомпоновщикНастроекНастройкиОтборViewStatus" id="16">
				<Source>
					<lf:elementId>5</lf:elementId>
					<lf:additionId>1</lf:additionId>
				</Source>
				<ContextMenu name="КомпоновщикНастроекНастройкиОтборViewStatusContextMenu" id="17"/>
				<ExtendedTooltip name="КомпоновщикНастроекНастройкиОтборViewStatusExtendedTooltip" id="18"/>
			</ViewStatusAddition>
			<SearchControlAddition name="КомпоновщикНастроекНастройкиОтборSearchControl" id="19">
				<Source>
					<lf:elementId>5</lf:elementId>
					<lf:additionId>2</lf:additionId>
				</Source>
				<ContextMenu name="КомпоновщикНастроекНастройкиОтборSearchControlContextMenu" id="20"/>
				<ExtendedTooltip name="КомпоновщикНастроекНастройкиОтборSearchControlExtendedTooltip" id="21"/>
			</SearchControlAddition>
		</Table>
	</ChildItems>
	<Attributes>
		<Attribute name="Объект" id="1">
			<Type>
				<v8:Type>cfg:CatalogObject.ЗакладкиВзаимодействий</v8:Type>
			</Type>
			<MainAttribute>true</MainAttribute>
			<SavedData>true</SavedData>
		</Attribute>
		<Attribute name="КомпоновщикНастроек" id="2">
			<Title>
				<v8:item>
					<v8:lang>ru</v8:lang>
					<v8:content>Компоновщик настроек</v8:content>
				</v8:item>
			</Title>
			<Type>
				<v8:Type>dcsset:SettingsComposer</v8:Type>
			</Type>
		</Attribute>
	</Attributes>
</Form>


text:
"use strict";
import * as tl from 'azure-pipelines-task-lib/task';
import { HttpClientResponse } from "./mocks/mockedModels"
var mockery = require('mockery');

mockery.enable({
    useCleanCache: true,
    warnOnReplace: false,
    warnOnUnregistered: false
});

mockery.registerMock('typed-rest-client/HttpClient', {
    HttpClient: function () {
        return {
            get: function (url: string, headers) {
                if (url == DotNetCoreReleasesIndexUrl && process.env["__failat__"] == "versionnotfound") {
                    return new Promise((resolve, reject) => {
                        resolve(new HttpClientResponse(`{
                            "releases-index": [
                                {
                                    "channel-version": "2.2",
                                    "releases.json": "${ReleasesJsonUrl2}"
                                },
                                {
                                    "channel-version": "3.0",
                                    "releases.json": "${ReleasesJsonUrl3}",
                                    "support-phase": "preview"
                                },
                                {
                                    "channel-version": "4.0",
                                    "releases.json": "${ReleasesJsonUrl4}"
                                },
                                {
                                    "channel-version": "4.1",
                                    "releases.json": "${ReleasesJsonUrl5}",
                                    "support-phase": "preview"
                                }
                            ]
                        }`))
                    });
                }
                else if (url == DotNetCoreReleasesIndexUrl && process.env["__failat__"] == "channelfetch") {
                    return new Promise((resolve, reject) => {
                        reject("");
                    });
                }
                else if (url == ReleasesJsonUrl2) {
                    return new Promise((resolve, reject) => {
                        resolve(new HttpClientResponse(`{
                            "releases": [
                                {
                                    "version": "2.2.104",
                                    "files": [
                                        "rid": "winx64",
                                        "url": "https://dotnetWindowsDownloadUrl.com"
                                    ]
                                }
                            ]
                        }`));
                    });
                }
                else if (url == ReleasesJsonUrl3) {
                    return new Promise((resolve, reject) => {
                        resolve(new HttpClientResponse(`{
                            "releases": [
                                {
                                    "version": "3.0.104",
                                    "files": [
                                        "rid": "winx64",
                                        "url": "https://dotnetWindowsDownloadUrl.com"
                                    ]
                                }
                            ]
                        }`));
                    });
                }
                else if (url == ReleasesJsonUrl4) {
                    return new Promise((resolve, reject) => {
                        resolve(new HttpClientResponse(`{
                            "releases": [
                                {
                                    "version": "4.0.102",
                                    "files": [
                                        "rid": "winx64",
                                        "url": "https://dotnetWindowsDownloadUrl.com"
                                    ]
                                }
                            ]
                        }`));
                    });
                }
                else if (url == ReleasesJsonUrl5) {
                    return new Promise((resolve, reject) => {
                        resolve(new HttpClientResponse(`{
                            "releases": [
                                {
                                    "version": "4.1.100",
                                    "files": [
                                        "rid": "winx64",
                                        "url": "https://dotnetWindowsDownloadUrl.com"
                                    ]
                                }
                            ]
                        }`));
                    });
                }
            }
        }
    }
});

import { DotNetCoreVersionFetcher } from "../versionfetcher";

const DotNetCoreReleasesIndexUrl: string = "https://dotnetcli.blob.core.windows.net/dotnet/release-metadata/releases-index.json";
const ReleasesJsonUrl2: string = "https://releases.file.com/version2.2.json"
const ReleasesJsonUrl3: string = "https://releases.file.com/version3.0.json"
const ReleasesJsonUrl4: string = "https://releases.file.com/version4.0.json"
const ReleasesJsonUrl5: string = "https://releases.file.com/version4.1.json"

let versionFetcher = new DotNetCoreVersionFetcher();
versionFetcher.getVersionInfo(process.env["__versionspec__"], null, "sdk", process.env["__inlcudepreviewversion__"] == "true")
    .catch((ex) => {
        if (process.env["__versionspec__"] == "2.2.999-cantbefound-234") {
            tl.setResult(tl.TaskResult.Failed, "FailedAsExpected");
        }
        else if (process.env["__versionspec__"] == "3.x" && process.env["__inlcudepreviewversion__"] != "true") {
            tl.setResult(tl.TaskResult.Failed, "FailedAsExpected");
        }
        else if (process.env["__versionspec__"] == "4.40.x" && process.env["__inlcudepreviewversion__"] == "true") {
            tl.setResult(tl.TaskResult.Failed, "FailedAsExpected");
        }
        else {
            tl.setResult(tl.TaskResult.Succeeded, "succeeded");
        }
    });


text:
package net.runelite.api.queries;

import static java.lang.Math.abs;
import net.runelite.api.Actor;
import net.runelite.api.Query;
import net.runelite.api.coords.LocalPoint;

public abstract class ActorQuery<EntityType extends Actor, QueryType> extends Query<EntityType, QueryType>
{
	@SuppressWarnings("unchecked")
	public QueryType nameEquals(String... names)
	{
		predicate = and(actor ->
		{
			for (String name : names)
			{
				String actorName = actor.getName();
				if (actorName != null && actorName.equals(name))
				{
					return true;
				}
			}
			return false;
		});
		return (QueryType) this;
	}

	@SuppressWarnings("unchecked")
	public QueryType nameContains(String... names)
	{
		predicate = and(actor ->
		{
			for (String name : names)
			{
				String actorName = actor.getName();
				if (actorName != null && actorName.contains(name))
				{
					return true;
				}
			}
			return false;
		});
		return (QueryType) this;
	}

	@SuppressWarnings("unchecked")
	public QueryType atLocalLocation(LocalPoint location)
	{
		predicate = and(actor -> actor.getLocalLocation().equals(location));
		return (QueryType) this;
	}

	@SuppressWarnings("unchecked")
	public QueryType isLevel(int level)
	{
		predicate = and(actor -> actor.getCombatLevel() == level);
		return (QueryType) this;
	}

	@SuppressWarnings("unchecked")
	public QueryType animationEquals(int animation)
	{
		predicate = and(actor -> actor.getAnimation() == animation);
		return (QueryType) this;
	}

	@SuppressWarnings("unchecked")
	public QueryType isInteractingWith(Actor actor)
	{
		predicate = and(a -> a.getInteracting().equals(actor));
		return (QueryType) this;
	}

	@SuppressWarnings("unchecked")
	public QueryType isWithinDistance(LocalPoint to, int distance)
	{
		predicate = and(a -> a.getLocalLocation().distanceTo(to) <= distance);
		return (QueryType) this;
	}

	@SuppressWarnings("unchecked")
	public QueryType isWithinArea(LocalPoint from, int area)
	{
		predicate = and(a ->
		{
			LocalPoint localLocation = a.getLocalLocation();
			return abs(localLocation.getX() - from.getX()) < area
				&& abs(localLocation.getY() - from.getY()) < area;
		});
		return (QueryType) this;
	}
}


text:
from __future__ import absolute_import, division, print_function, unicode_literals
import unittest
import pandas as pd
import xgbmagic
import random

n=100
data_dict = {'id':[str(a) for a in range(n)], 'y': [random.randrange(x+10) for x in range(n)], 'x1': [random.randrange(20+x*2) for x in range(n)], 'x2': [random.randrange(11) for x in range(n)]}
train_df = pd.DataFrame.from_dict(data_dict, orient='columns')
test_dict = {'id':['12345','12021'], 'y':[22,21], 'x1':[11,11], 'x2':[34, 123]}
test_df = pd.DataFrame.from_dict(test_dict, orient='columns')

bin_data_dict = {'id':[str(a) for a in range(n)], 'y': [random.randint(0,1) for x in range(n)], 'x1': [random.randrange(20+x*2) for x in range(n)], 'x2': [random.randrange(11) for x in range(n)]}
bin_train_df = pd.DataFrame.from_dict(bin_data_dict, orient='columns')
bin_test_dict = {'id':['12345','12021'], 'y':[0,1], 'x1':[11,11], 'x2':[34, 123]}
bin_test_df = pd.DataFrame.from_dict(bin_test_dict, orient='columns')

class TestXGB(unittest.TestCase):
    def test_init(self):
        drop_list = []
        numeric_list = []
        cat_list = []
        xgb = xgbmagic.Xgb(train_df, target_column='y', id_column='id', numeric_columns=numeric_list, drop_columns=drop_list, categorical_columns=cat_list, num_training_rounds=100, target_type='linear', verbose=True, prefix='test', sample_fraction=0.01, n_samples=2)
        self.assertIsInstance(xgb, xgbmagic.Xgb)

    def test_random_sample(self):
        n_samples = 3
        fraction = 0.2
        drop_list = []
        numeric_list = []
        cat_list = []
        xgb = xgbmagic.Xgb(train_df, target_column='y', id_column='id', numeric_columns=numeric_list, drop_columns=drop_list, categorical_columns=cat_list, num_training_rounds=100, target_type='linear', verbose=True, prefix='test', sample_fraction=0.01, n_samples=2)
        samples = xgb.random_sample(train_df, fraction=fraction, n_samples=n_samples)
        self.assertTrue(len(samples)==n_samples)
        self.assertTrue(len(samples[0])==round(fraction*len(train_df)))

    def test_output(self):
        drop_list = []
        numeric_list = []
        cat_list = []
        xgb = xgbmagic.Xgb(train_df, target_column='y', id_column='id', numeric_columns=numeric_list, drop_columns=drop_list, categorical_columns=cat_list, num_training_rounds=100, target_type='linear', verbose=True, prefix='test', sample_fraction=0.3, n_samples=2)
        xgb.train()
        output = xgb.predict(test_df)
        print('OUTPUT', output)
        self.assertTrue(len(output) == len(test_dict['id']))
        multi_outputs = xgb.predict(test_df, return_multi_outputs=True)
        self.assertTrue(len(multi_outputs) == xgb.n_samples)

    def test_binary(self):
        print(bin_train_df.head())
        drop_list = []
        numeric_list = []
        cat_list = []
        xgb = xgbmagic.Xgb(bin_train_df, target_column='y', id_column='id', numeric_columns=numeric_list, drop_columns=drop_list, categorical_columns=cat_list, num_training_rounds=100, target_type='binary', verbose=True, prefix='test', sample_fraction=0.3, n_samples=2)
        xgb.train()
        output = xgb.predict(bin_test_df)
        print('OUTPUT', output)
        self.assertTrue(len(output) == len(bin_test_dict['id']))

if __name__ == '__main__':
    unittest.main()


text:
<?php

/**
 * @file
 * Contains \Drupal\filter\Plugin\Filter\FilterHtmlCorrector.
 */

namespace Drupal\filter\Plugin\Filter;

use Drupal\filter\Annotation\Filter;
use Drupal\Core\Annotation\Translation;
use Drupal\filter\Plugin\FilterBase;

/**
 * Provides a filter to correct faulty and chopped off HTML.
 *
 * @Filter(
 *   id = "filter_htmlcorrector",
 *   module = "filter",
 *   title = @Translation("Correct faulty and chopped off HTML"),
 *   type = FILTER_TYPE_HTML_RESTRICTOR,
 *   weight = 10
 * )
 */
class FilterHtmlCorrector extends FilterBase {

  /**
   * {@inheritdoc}
   */
  public function process($text, $langcode, $cache, $cache_id) {
    return _filter_htmlcorrector($text);
  }

}


text:
from skimage.data import astronaut
import skimage.io

if __name__ == '__main__':
    # Save local copy of the Astronaut test image for use in LaTeX
    skimage.io.imsave('./astronaut.png', astronaut())


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ReplaceTags
{
    class ReplaceTags
    {
        static void Main()
        {
            Console.WriteLine("write your text in html format");
             string text = Console.ReadLine();
             string replace = text.Replace("", "]");
             string fixedText = replace2.Replace(" ", "[/URL]");
             Console.WriteLine(fixedText);

        }
    }
}


text:
import SmartForm from './SmartForm';
import Error from './Error';

export default {
  SmartForm: SmartForm,
  Error: Error,
}


text:
from flask import request, current_app, g, url_for
from flask_login import login_required, current_user
from flask_restful import Resource, marshal_with, reqparse, abort
from atrium.schemas import Place
from .fields import event_fields
import arrow
import werkzeug.datastructures
from atrium import s3conn
from boto.s3.key import Key
import bleach
from .bleachconfig import ALLOWED_TAGS, ALLOWED_STYLES, ALLOWED_ATTRIBUTES
import requests
import pypandoc
from hashlib import sha256
import hmac
from helpers import pagination_helper

class EventListResource(Resource):
    @pagination_helper(event_fields)
    def get(self):
        query = g.Event.objects.no_dereference()
        if 'club' in request.args:
            query = query.filter(club=g.Club.objects.with_id(request.args['club']))

        return query

    @login_required
    @marshal_with(event_fields)
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('club', type=unicode, required=True)
        parser.add_argument('name', type=unicode, store_missing=False)
        parser.add_argument('description', type=unicode, store_missing=False)
        parser.add_argument('start_date', type=unicode, store_missing=False)
        parser.add_argument('end_date', type=unicode, store_missing=False)
        parser.add_argument('facebook_id', type=unicode, store_missing=False)
        parser.add_argument('place', type=dict, store_missing=False)
        args = parser.parse_args()

        if not current_user.is_admin() and not current_user.has_any_permission('club', args['club'], ['admin', 'events']):
            return abort(401)

        def event_from_args(args):
            event = g.Event(
                name=args['name'],
                club=args['club'],
                description=bleach.clean(args['description'], tags=ALLOWED_TAGS, styles=ALLOWED_STYLES, attributes=ALLOWED_ATTRIBUTES),
                start_date=arrow.get(args['start_date']).datetime,
                end_date=arrow.get(args['end_date']).datetime,
                facebook_id=args['facebook_id']
            )

            if 'place' in args.keys():
                event.place = Place(
                    name=args['place']['name'],
                    address=args['place']['address']
                )

            event.save()
            return event

        def event_from_facebook(args, data):
            event = g.Event(
                club=args['club'],
                facebook_id=data['id'],
                name=data['name'],
                start_date=arrow.get(data['start_time']).datetime,
            )

            if 'description' in data.keys():
                event.description = data['description'].replace('\n', '<br />')

            if 'end_time' in data.keys():
                event.end_date = arrow.get(data['end_time']).datetime
            else:
                event.end_date = arrow.get(data['start_time']).replace(hours=2).datetime

            if 'place' in data.keys():
                event.place = Place(
                    name=data['place']['name']
                )
                if 'location' in data['place'].keys():
                    event.address = data['place']['location']['street'] + ', ' + data['place']['location']['city'] \
                                  + ', ' + data['place']['location']['country']

            event.save()
            bucket = s3conn.get_bucket(current_app.config['AWS_S3_BUCKET'])
            key = Key(bucket)
            key.key = g.tenant + '/events/' + str(event.id)
            key.content_type = 'image/jpeg'
            key.set_contents_from_string(requests.get(data['cover']['source']).content)
            key.make_public()
            event.poster = 'https://' + current_app.config['AWS_S3_BUCKET'] + '.s3.amazonaws.com/' + g.tenant + '/events/' + str(event.id)
            event.save()

        if 'facebook_id' not in args.keys() or args['facebook_id'] is None:
            for key in ['name', 'description', 'start_date', 'end_date']:
                if key not in args.keys():
                    return abort(400)
            event = event_from_args(args)
        else:
            data = requests.get('https://graph.facebook.com/' + args['facebook_id'], params={
                'access_token': current_app.config['FACEBOOK_APPID'] + '|' + current_app.config['FACEBOOK_SECRET'],
                'fields': 'cover,name,description,place,start_time,end_time'
            }).json()
            event = event_from_facebook(args, data)

        return event

class EventResource(Resource):
    @marshal_with(event_fields)
    def get(self, event_id):
        return g.Event.objects.no_dereference().with_id(event_id)

    @login_required
    @marshal_with(event_fields)
    def put(self, event_id):
        event = g.Event.objects.with_id(event_id)

        if not current_user.is_admin() and not current_user.has_any_permission('club', event.club.id, ['admin', 'events']):
            return abort(401)

        parser = reqparse.RequestParser()
        parser.add_argument('name', type=unicode, store_missing=False)
        parser.add_argument('description', type=unicode, store_missing=False)
        parser.add_argument('start_date', type=unicode, store_missing=False)
        parser.add_argument('end_date', type=unicode, store_missing=False)
        parser.add_argument('place', type=dict, store_missing=False)
        parser.add_argument('facebook_id', type=unicode, store_missing=False)
        args = parser.parse_args()

        for field in ['name', 'club', 'facebook_id']:
            if field in args.keys():
                setattr(event, field, args[field])

        for field in ['start_date', 'end_date']:
            if field in args.keys():
                setattr(event, field, arrow.get(args[field]).naive)

        if 'description' in args.keys():
            event.description = bleach.clean(args['description'], tags=ALLOWED_TAGS, styles=ALLOWED_STYLES, attributes=ALLOWED_ATTRIBUTES)

        if 'place' in args.keys():
            event.place = Place(name=args['place']['name'], address=args['place']['address'])

        event.save()
        return event

    @login_required
    def delete(self, event_id):
        event = g.Event.objects.with_id(event_id)
        if not current_user.is_admin() and not current_user.has_any_permission('club', event.club.id, ['admin', 'events']):
            return abort(401)

        event.delete()
        return '', 204

class EventPoster(Resource):
    @login_required
    @marshal_with(event_fields)
    def post(self, event_id):
        event = g.Event.objects.with_id(event_id)

        if not current_user.is_admin() and not current_user.has_any_permission('club', event.club.id, ['admin', 'events']):
            return abort(401)

        parser = reqparse.RequestParser()
        parser.add_argument('poster', type=werkzeug.datastructures.FileStorage, location='files')
        args = parser.parse_args()

        bucket = s3conn.get_bucket(current_app.config['AWS_S3_BUCKET'])
        key = Key(bucket)
        key.key = g.tenant + '/events/' + str(event.id)
        key.content_type = args['poster'].mimetype
        key.set_contents_from_file(args['poster'].stream)
        key.make_public()

        event.poster = 'https://' + current_app.config['AWS_S3_BUCKET'] + '.s3.amazonaws.com/' + g.tenant + '/events/' + str(event.id)
        event.save()

        return event

    @login_required
    def delete(self, event_id):
        event = g.Event.objects.with_id(event_id)

        if not current_user.is_admin() and not current_user.has_any_permission('club', event.club.id, ['admin', 'events']):
            return abort(401)

        event.poster = None
        event.save()

        bucket = s3conn.get_bucket(current_app.config['AWS_S3_BUCKET'])
        key = bucket.get_key(g.tenant + '/events/' + str(event.id))
        key.delete()

        return '', 204

class EventFacebookPublish(Resource):
    @login_required
    def post(self, event_id):
        event = g.Event.objects.with_id(event_id)
        if not current_user.is_admin() and not current_user.has_any_permission('club', event.club.id, ['admin', 'events']):
            return abort(401)

        parser = reqparse.RequestParser()
        parser.add_argument('message', type=unicode, required=True)
        args = parser.parse_args()

        digest = hmac.new(current_app.config['FACEBOOK_SECRET'], msg=event.club.facebook_publish.access_token, digestmod=sha256).hexdigest()

        response = requests.post('https://graph.facebook.com/v2.5/' + event.club.facebook_publish.id + '/feed', params={
            'access_token': event.club.facebook_publish.access_token,
            'appsecret_proof': digest
        }, data={
            'message': args['message'],
            'link': url_for('events', event_id=event.id, _external=True)
        })

        return response.json()


text:
A Warm Welcome!

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ipsa, ipsam, eligendi, in quo sunt possimus non incidunt odit vero aliquid similique quaerat nam nobis illo aspernatur vitae fugiat numquam repellat.

                Call to action!

Latest Features

Feature Label

Lorem ipsum dolor sit amet, consectetur adipisicing elit.

                            Buy Now! More Info

Feature Label

Lorem ipsum dolor sit amet, consectetur adipisicing elit.

                            Buy Now! More Info

Feature Label

Lorem ipsum dolor sit amet, consectetur adipisicing elit.

                            Buy Now! More Info

Feature Label

Lorem ipsum dolor sit amet, consectetur adipisicing elit.

                            Buy Now! More Info

Copyright © Your Website 2014


text:
from __future__ import print_function
from vtk import *
import os.path
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()

data_dir = VTK_DATA_ROOT + "/Data/Infovis/SQLite/"
if not os.path.exists(data_dir):
  data_dir = VTK_DATA_ROOT + "/Data/Infovis/SQLite/"
if not os.path.exists(data_dir):
  data_dir = VTK_DATA_ROOT + "/Data/Infovis/SQLite/"
sqlite_file = data_dir + "temperatures.db"

# Pull the table from the database
databaseToTable = vtkSQLDatabaseTableSource()
databaseToTable.SetURL("sqlite://" + sqlite_file)
databaseToTable.SetQuery("select * from main_tbl")

# How many rows does the input table have?
databaseToTable.Update()
inputTable = databaseToTable.GetOutput()
numRows = inputTable.GetNumberOfRows()
print("Input Table Rows: " , numRows)

# Divide the table into 4
# Note1: using data specific method
subSize = numRows/4
leftOver = numRows - subSize*4
print("subSize: ", subSize)
print("leftOver: ", leftOver)

# Python knows nothing of enumerated types
# 6 = vtkDataObject::FIELD_ASSOCIATION_ROWS
# Mode = ACCEPT_LESS_THAN = 0, ACCEPT_GREATER_THAN = 1, ACCEPT_BETWEEN = 2, ACCEPT_OUTSIDE = 3
threshold = vtkThresholdTable()
threshold.SetInputConnection(databaseToTable.GetOutputPort())
threshold.SetInputArrayToProcess(0,0,0,6, "id")
threshold.SetMode(2)
threshold.SetMinValue(vtkVariant(0))
threshold.SetMaxValue(vtkVariant(subSize-1))
threshold.Update()
subTable1 = vtkTable()
subTable1.DeepCopy(threshold.GetOutput())
subTable1.Dump(10)

threshold.SetMinValue(vtkVariant(subSize))
threshold.SetMaxValue(vtkVariant(subSize*2-1))
threshold.Update()
subTable2 = vtkTable()
subTable2.DeepCopy(threshold.GetOutput())
subTable2.Dump(10)

threshold.SetMinValue(vtkVariant(subSize*2))
threshold.SetMaxValue(vtkVariant(subSize*3-1))
threshold.Update()
subTable3 = vtkTable()
subTable3.DeepCopy(threshold.GetOutput())

threshold.SetMinValue(vtkVariant(subSize*3))
threshold.SetMaxValue(vtkVariant(subSize*4+leftOver-1))
threshold.Update()
subTable4 = vtkTable()
subTable4.DeepCopy(threshold.GetOutput())
print("SubTable1 Rows: " , subTable1.GetNumberOfRows())
print("SubTable2 Rows: " , subTable2.GetNumberOfRows())
print("SubTable3 Rows: " , subTable3.GetNumberOfRows())
print("SubTable4 Rows: " , subTable4.GetNumberOfRows())

# Calculate offline(non-streaming) descriptive statistics
print("# Calculate offline descriptive statistics:")
ds = vtkDescriptiveStatistics()
ds.SetInputConnection(databaseToTable.GetOutputPort())
ds.AddColumn("Temp1")
ds.AddColumn("Temp2")
ds.Update()

dStats = ds.GetOutputDataObject( 1 )
dPrimary = dStats.GetBlock( 0 )
dDerived = dStats.GetBlock( 1 )
dPrimary.Dump( 15 )
dDerived.Dump( 15 )

inter = vtkDescriptiveStatistics()
inter.AddColumn("Temp1")
inter.AddColumn("Temp2")

# Calculate online(streaming) descriptive statistics
print("# Calculate online descriptive statistics:")
ss = vtkStreamingStatistics()
ss.SetStatisticsAlgorithm(inter)
ss.SetInputData(subTable1)
ss.Update()

ss.SetInputData(subTable2)
ss.Update()

ss.SetInputData(subTable3)
ss.Update()

ss.SetInputData(subTable4)
ss.Update()

sStats = ss.GetOutputDataObject( 1 )
sPrimary = sStats.GetBlock( 0 )
sDerived = sStats.GetBlock( 1 )
sPrimary.Dump( 15 )
sDerived.Dump( 15 )


text:
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Hed.Server.Request;
using Hed.Server.Response;
using Hed.Server.Utils;

namespace Hed.Server.Connection
{
    public class InboundConnection : HedConnection
    {
        private static long connectionCounter;
        protected static readonly Encoding headerEncoding = Encoding.GetEncoding("us-ascii");
        public override bool IsSecure { get { return false; } }

        public long ConnectionId;

        protected TcpClient connection;
        protected NetworkStream networkStream;

        public bool IsConnected
        {
            get
            {
                if (!connection.Connected)
                    return false;

                try
                {
                    return !(connection.Client.Poll(1, SelectMode.SelectRead) && connection.Client.Available == 0);
                }
                catch (SocketException) { return false; }
                //return connection.Connected;
            }
        }

        public IPEndPoint RemoteEndPoint { get; private set; }

        public InboundConnection(TcpClient connection)
        {
            this.connection = connection;
            this.networkStream = connection.GetStream();
            this.ConnectionId = Interlocked.Increment(ref connectionCounter);
            this.RemoteEndPoint = (IPEndPoint)connection.Client.RemoteEndPoint;
        }

        public virtual Task OpenAsync()
        {
            return this.OpenAsync(CancellationToken.None);
        }

        public virtual Task OpenAsync(CancellationToken ct)
        {
            return Task.FromResult<VoidTypeStruct>(default(VoidTypeStruct));
        }

        protected virtual Stream GetReadStream()
        {
            return this.networkStream;
        }

        protected virtual Stream GetWriteStream()
        {
            return this.networkStream;
        }

        public Task<HedRequest> ReadRequestAsync()
        {
            return ReadRequestAsync(CancellationToken.None);
        }

        public Task<HedRequest> ReadRequestAsync(CancellationToken ct)
        {
            var requestParser = new HedRequestParser();

            return requestParser.ParseAsync(this, this.GetReadStream());
        }

        public async Task WriteResponseAsync(HedResponse response)
        {
            await WriteResponseAsync(response, CancellationToken.None)
                .ConfigureAwait(false);
        }

        public async Task WriteResponseAsync(HedResponse response, CancellationToken ct)
        {
            var ms = new MemoryStream();
            var sw = new StreamWriter(ms, headerEncoding);

            sw.NewLine = "\r\n";
            sw.WriteLine("HTTP/{0} {1} {2}", response.ProtocolVersion, response.StatusCode, response.StatusDescription);

            for (int i = 0; i < response.Headers.Count; i++)
                sw.WriteLine("{0}: {1}", response.Headers.GetKey(i), response.Headers.Get(i));

            sw.WriteLine();
            sw.Flush();

            var writeStream = this.GetWriteStream();

            await writeStream.WriteAsync(ms.GetBuffer(), 0, (int)ms.Length, ct).ConfigureAwait(false);
            Debug.WriteLine("{0}: Wrote headers ({1}b)", this.RemoteEndPoint, ms.Length);

            if (response.ResponseBody != null && response.ResponseBody.CanRead)
            {
                byte[] buffer = new byte[8192];
                int read;
                long written = 0;

                while ((read = await response.ResponseBody.ReadAsync(buffer, 0, buffer.Length, ct).ConfigureAwait(false)) > 0)
                {
                    written += read;
                    Debug.WriteLine("{0}: Read {1:N0} bytes from response body", this.RemoteEndPoint, read);
                    await writeStream.WriteAsync(buffer, 0, read).ConfigureAwait(false);
                    Debug.WriteLine("{0}: Wrote {1:N0} bytes to client", this.RemoteEndPoint, read);
                }

                Debug.WriteLine("{0}: Wrote response body ({1:N0} bytes) to client", this.RemoteEndPoint, written);

            }

            await writeStream.FlushAsync(ct).ConfigureAwait(false);
        }

        public void Close()
        {
            connection.Close();
        }

    }
}


text:
Rails.application.config.assets.version = '1.0'

# Precompile additional assets.
# application.js, application.css, and all non-JS/CSS in app/assets folder are already added.
 Rails.application.config.assets.precompile += %w(layer-maps.js geosearch.js geosearch-map.js geosearch-layer.js warped.js align.js clip.js warp.js openlayers/2.8/OpenLayers-2.8/OpenLayers.js )

Rails.application.config.assets.precompile += %w(*.png *.jpg *.jpeg *.gif)

# Rails.application.config.assets.precompile += %w( iD.js iD.css )
# Rails.application.config.assets.precompile += %w( iD/img/*.svg iD/img/*.png iD/img/*.gif )
# Rails.application.config.assets.precompile += %w( iD/img/pattern/*.png )
# Rails.application.config.assets.precompile += %w( iD/locales/*.json )
Rails.application.config.assets.precompile += %w( select2/select2.min.js select2/select2.min.css select2/i18n/nl.js)
Rails.application.config.assets.precompile += %w( helmerttransform.js )


text:
This package requires `pip` to be installed:

    sudo easy_install pip


text:
package dk.philiphansen.basemod;

import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.Mod.EventHandler;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import org.apache.logging.log4j.Logger;

@Mod(modid = "basemod", name = "BaseMod", version = "${version}")
public class BaseMod {
	private static Logger logger;

	@EventHandler
	public void preInit(FMLPreInitializationEvent event) {
		logger = event.getModLog();
	}

	@EventHandler
	public void init(FMLInitializationEvent event) {
		logger.info("BaseMod has loaded!");
	}
}


text:
"""
Module provides a `PlayLists` class wich implemented MPRIS2 PlayLists interface:
http://specifications.freedesktop.org/mpris-spec/latest/Playlists_Interface.html

Class `PlaylistOrdering` uses as an enum for Ordering type.

Usage::
    from pympris import PlayLists

    pl = PlayLists('org.mpris.MediaPlayer2.rhythmbox')
    print(pl.PlaylistCount)
    print(pl.ActivePlaylist)

    items = pl.GetPlaylists(0, 100, PlaylistOrdering.Alphabetical, reversed=False)
    for uri, name, icon_uri in items:
        print(uri, name, icon_uri)
"""

from .common import convert2dbus
from .Base import Base

__all__ = ('PlayLists', 'PlaylistOrdering', )

class PlaylistOrdering(object):
    Alphabetical = 'Alphabetical'
    CreationDate = 'Created'
    ModifiedDate = 'Modified'
    LastPlayDate = 'Played'
    UserDefined = 'User'

class PlayLists(Base):

    """Class implements methods and properties
    to work with MPRIS2 Playlists interface.
    """

    IFACE = "org.mpris.MediaPlayer2.Playlists"
    """The D-Bus MediaPlayer2.Playlists interface name"""

    def __init__(self, name, bus=None, private=False):
        super(PlayLists, self).__init__(name, bus, private)

    def ActivatePlaylist(self, playlist_id):
        """Starts playing the given playlist.

        :param: str playlist_id: The id of the playlist to activate.
        """
        self.iface.ActivatePlaylist(playlist_id)

    def GetPlaylists(self, start, max_count, order, reversed):
        """Gets a set of playlists.

        :param int start: The index of the first playlist to be fetched
                           (according to the ordering).
        :param int max_count: The maximum number of playlists to fetch.
        :param str order: The ordering that should be used.
        :param bool reversed: Whether the order should be reversed.
        """
        cv = convert2dbus
        return self.iface.GetPlaylists(cv(start, 'u'),
                                       cv(max_count, 'u'),
                                       cv(order, 's'),
                                       cv(reversed, 'b'))

    @property
    def PlaylistCount(self):
        """The number of playlists available."""
        return self.get('PlaylistCount')

    @property
    def Orderings(self):
        """The available orderings. At least one must be offered."""
        return self.get('Orderings')

    @property
    def ActivePlaylist(self):
        """The currently-active playlist."""
        valid, info = tuple(self.get('ActivePlaylist'))
        if valid:
            return info


text:
<resources>
    <string name="app_name">AndroidScoreTracker</string>
    <string name="game_name_hint">Game name</string>
    <string name="game_session_name_hint">Session name</string>
    <string name="add">Add</string>
    <string name="update">Update</string>
    <string name="add_game">Add Game</string>
    <string name="add_game_session">Add Game Session</string>
    <string name="has_draw">Has draw</string>
    <string name="game_spinner_label">Choose a game</string>
    <string name="start_date_label">Start date</string>
    <string name="end_date_label">End date</string>
    <string name="label_win_button">Wins :</string>
    <string name="label_draw_button">Draws :</string>
    <string name="label_loose_button">Looses :</string>
    <string name="close_session">Close session</string>
    <string name="current_session">Current Sessions</string>
    <string name="title_comment_dialog">Add a comment</string>
    <string name="cancel">Cancel</string>
    <string name="win_rate">Win ratio:</string>
    <string name="last_five">Wins in last 5:</string>
    <string name="session_list">"Session List"</string>
    <string name="add_new_game">Add New Game</string>
    <string name="add_new_session">Add New Session</string>
    <string name="history_title">History</string>
</resources>


text:
package org.fujaba.graphengine;

import java.util.HashMap;

/**
 * The IdManager can track and create IDs for Objects to identify them later on.
 *
 * @author Philipp Kolodziej
 */
public class IdManager {

	private HashMap<Object, Long> idMap;
	private HashMap<Long, Object> objectMap;
	private long nextId = 0;

	public IdManager resetIds() {
		idMap = null;
		objectMap = null;
		nextId = 0;
		return this;
	}

	public IdManager tellId(Long id, Object o) {
		if (idMap == null) {
			idMap = new HashMap<Object, Long>();
		}
		if (objectMap == null) {
			objectMap = new HashMap<Long, Object>();
		}
		idMap.put(o, id);
		objectMap.put(id, o);
		nextId = id + 1;
		while (objectMap.containsKey(nextId)) {
			++nextId;
		}
		return this;
	}

	public long getId(Object o) {
		if (idMap == null) {
			idMap = new HashMap<Object, Long>();
		}
		if (objectMap == null) {
			objectMap = new HashMap<Long, Object>();
		}
		if (!idMap.containsKey(o)) {
			idMap.put(o, nextId);
			objectMap.put(nextId, o);
			while (objectMap.containsKey(nextId)) {
				++nextId;
			}
		}
		return idMap.get(o);
	}

	public Object getObject(long id) {
		if (objectMap == null) {
			return null;
		}
		return objectMap.get(id);
	}

}