text:
using MathNet.Numerics.LinearAlgebra;
using MathNet.Numerics.LinearAlgebra.Double;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using RecSys;
using RecSys.Core;
using RecSys.Evaluation;
using RecSys.Numerical;
using RecSys.Ordinal;
using System;
using System.Collections.Generic;
using System.Diagnostics;

namespace RecSysUnitTest
{
    [TestClass]
    public class RecSysTests
    {
        #region Data for testing
        private static DataMatrix GetSampleRatingMatrix()
        {
            /*
             * 5  3  0  1
             * 4  0  0  1
             * 1  1  0  5
             * 1  0  0  4
             * 0  1  5  4
             */
            DataMatrix R = new DataMatrix(new SparseMatrix(5, 4));
            R[0, 0] = 5;
            R[0, 1] = 3;
            R[0, 3] = 1;
            R[1, 0] = 4;
            R[1, 3] = 1;
            R[2, 0] = 1;
            R[2, 1] = 1;
            R[2, 3] = 5;
            R[3, 0] = 1;
            R[3, 3] = 4;
            R[4, 1] = 1;
            R[4, 2] = 5;
            R[4, 3] = 4;

            return R;
        }
        #endregion

        #region Tests on Evaluation package
        [TestClass]
        public class EvaluationTest
        {
            #region RMSETest()
            [TestMethod]
            public void RMSETest()
            {
                /*
                 * 5  3  0  1
                 * 4  0  0  1
                 * 1  1  0  5
                 * 1  0  0  4
                 * 0  1  5  4
                 */
                DataMatrix R = GetSampleRatingMatrix();

                /*
                 * 3  3  0  1
                 * 4  0  0  5
                 * 1  2  0  5
                 * 1  0  0  4
                 * 0  1  5  4
                 */
                DataMatrix R_predicted = GetSampleRatingMatrix();
                R_predicted[0, 0] = 3;  // was 5
                R_predicted[2, 1] = 2;  // was 1
                R_predicted[1, 3] = 5;  // was 1

                double debug1 = RMSE.Evaluate(R, R_predicted);
                double debug2 = Math.Sqrt(21.0 / 13.0);
                Debug.Assert(debug1 == debug2);
            }
            #endregion
        }
        #endregion

        #region Tests on PreferenceRelations class
        [TestClass]
        public class PreferenceRelationnsTest
        {
            #region Create discrete preference relations using rating matrix
            [TestMethod]
            public void CreateDiscrete()
            {
                /*
                 * 5  3  0  1
                 * 4  0  0  1
                 * 1  1  0  5
                 * 1  0  0  4
                 * 0  1  5  4
                 */
                DataMatrix R = GetSampleRatingMatrix();

                // act
                PrefRelations PR = PrefRelations.CreateDiscrete(R);

                // assert
                foreach (KeyValuePair<int, SparseMatrix> user in PR.PreferenceRelationsByUser)
                {
                    int indexOfUser = user.Key;
                    SparseMatrix preferencesOfUser = user.Value;

                    // Note that the diagonal (item compares to itsself) is elft empty
                    Debug.Assert(preferencesOfUser.Trace() == 0);

                    // Check if the correct number of preference relations have been created
                    Debug.Assert((Math.Pow(R.GetNonZerosCountOfRow(indexOfUser), 2)
                        - R.GetNonZerosCountOfRow(indexOfUser))
                        == preferencesOfUser.NonZerosCount);
                }

                // Check if the first user's preferences are correct
                Debug.WriteLine("PR[0][0, 0]=" + PR[0][0, 0]);
                Debug.Assert(PR[0][0, 0] == SparseMatrix.Zero);
                Debug.Assert(PR[0][0, 1] == Config.Preferences.Preferred);
                Debug.Assert(PR[0][1, 0] == Config.Preferences.LessPreferred);
                Debug.Assert(PR[0][0, 2] == SparseMatrix.Zero);
                Debug.Assert(PR[0][2, 0] == SparseMatrix.Zero);
                Debug.Assert(PR[0][1, 2] == SparseMatrix.Zero);
                Debug.Assert(PR[0][2, 1] == SparseMatrix.Zero);
                Debug.Assert(PR[0][1, 3] == Config.Preferences.Preferred);
                Debug.Assert(PR[0][3, 1] == Config.Preferences.LessPreferred);

                // Check if the last user's preferences are correct
                Debug.Assert(PR[4][1, 1] == SparseMatrix.Zero);
                Debug.Assert(PR[4][0, 1] == SparseMatrix.Zero);
                Debug.Assert(PR[4][1, 0] == SparseMatrix.Zero);
                Debug.Assert(PR[4][0, 2] == SparseMatrix.Zero);
                Debug.Assert(PR[4][2, 0] == SparseMatrix.Zero);
                Debug.Assert(PR[4][1, 2] == Config.Preferences.LessPreferred);
                Debug.Assert(PR[4][2, 1] == Config.Preferences.Preferred);
                Debug.Assert(PR[4][1, 3] == Config.Preferences.LessPreferred);
                Debug.Assert(PR[4][3, 1] == Config.Preferences.Preferred);
            }
            #endregion
        }
        #endregion

        #region Tests on RatingMatrix class
        [TestClass]
        public class RatingMatrixTest
        {
            [TestMethod]
            public void GetTopNItemsByUser()
            {
                /*
                 * 5  3  0  1
                 * 4  0  0  1
                 * 1  1  0  5
                 * 1  0  0  4
                 * 0  1  5  4
                 */
                DataMatrix R = GetSampleRatingMatrix();

                // act
                Dictionary<int, List<int>> topNItemsByUser = ItemRecommendationCore.GetTopNItemsByUser(R, 2);

                // assert
                Debug.Assert(topNItemsByUser[0].Count == 2);
                Debug.Assert(topNItemsByUser[0][0] == 0);
                Debug.Assert(topNItemsByUser[0][1] == 1);
                Debug.Assert(topNItemsByUser[1][0] == 0);
                Debug.Assert(topNItemsByUser[1][1] == 3);
                Debug.Assert(topNItemsByUser[4][0] == 2);
                Debug.Assert(topNItemsByUser[4][1] == 3);
            }
        }
        #endregion

        #region Tests on Utilities class
        [TestClass]
        public class UtilitiesTest
        {
            [TestMethod]
            public void LoadMovieLens()
            {
                // act
                DataMatrix R_train;
                DataMatrix R_test;
                Utils.LoadMovieLensSplitByCount("ua.test", out R_train, out R_test, 9, 7);
                // 1	265	4	878542441
                // assert
                Debug.Assert(R_train.GetNonZerosCountOfRow(0) == 7);
                Debug.Assert(R_train.GetNonZerosCountOfRow(1) == 7);
                Debug.Assert(R_train.GetNonZerosCountOfRow(2) == 7);

                Debug.Assert(R_test.GetNonZerosCountOfRow(0) == 2);
                Debug.Assert(R_test.GetNonZerosCountOfRow(1) == 3);
                Debug.Assert(R_test.GetNonZerosCountOfRow(2) == 3);

                Debug.Assert(R_train.GetRow(0)[6] == 5);
                Debug.Assert(R_test.GetRow(0)[6] == SparseMatrix.Zero);
                Debug.Assert(R_test.GetRow(0)[7] == 3);
                Debug.Assert(R_train.GetRow(0)[7] == SparseMatrix.Zero);
                Debug.Assert(R_test.GetRow(0)[8] == 5);
            }
        }
        #endregion

        #region Tests on PrefUserKNN
        [TestClass]
        public class PrefUserKNNTest
        {
            #region Convert one user's preference relations into positions
            [TestMethod]
            public void PreferencesToPositions()
            {
                /*
                 * 5  3  0  1
                 * 4  0  0  1
                 * 1  1  0  5
                 * 1  0  0  4
                 * 0  1  5  4
                 */
                DataMatrix R = GetSampleRatingMatrix();
                PrefRelations PR = PrefRelations.CreateDiscrete(R);

                // act
                // Convert first, Third, and last users' preferences to positions
                Vector<double> positionsOfUserFirst = PR.PreferencesToPositions(PR[0]);
                Vector<double> positionsOfUserThird = PR.PreferencesToPositions(PR[2]);
                Vector<double> positionsOfUserLast = PR.PreferencesToPositions(PR[4]);

                // assert
                // Check first user
                Debug.Assert(positionsOfUserFirst[0] == 1+Config.Preferences.PositionShift);
                Debug.Assert(positionsOfUserFirst[1] == 0+Config.Preferences.PositionShift);
                Debug.Assert(positionsOfUserFirst[2] == SparseMatrix.Zero);
                Debug.Assert(positionsOfUserFirst[3] == -1 + Config.Preferences.PositionShift);

                // Check third user
                Debug.Assert(positionsOfUserThird[0] == -0.5 + Config.Preferences.PositionShift);
                Debug.Assert(positionsOfUserThird[1] == -0.5 + Config.Preferences.PositionShift);
                Debug.Assert(positionsOfUserThird[2] == SparseMatrix.Zero);
                Debug.Assert(positionsOfUserThird[3] == 1 + Config.Preferences.PositionShift);

                // Check second last user
                Debug.Assert(positionsOfUserLast[0] == SparseMatrix.Zero);
                Debug.Assert(positionsOfUserLast[1] == -1 + Config.Preferences.PositionShift);
                Debug.Assert(positionsOfUserLast[2] == 1 + Config.Preferences.PositionShift);
                Debug.Assert(positionsOfUserLast[3] == 0 + Config.Preferences.PositionShift);

                // The number of positions should match the number of ratings by each user
                Debug.Assert(positionsOfUserFirst.GetNonZerosCount()
                    == R.GetNonZerosCountOfRow(0), String.Format("{0}=={1}",
                    positionsOfUserFirst.GetNonZerosCount(), R.GetNonZerosCountOfRow(0)));

                Debug.Assert(positionsOfUserThird.GetNonZerosCount()
                    == R.GetNonZerosCountOfRow(2), String.Format("{0}=={1}",
                    positionsOfUserThird.GetNonZerosCount(), R.GetNonZerosCountOfRow(2)));

                Debug.Assert(positionsOfUserLast.GetNonZerosCount()
                    == R.GetNonZerosCountOfRow(4), String.Format("{0}=={1}",
                    positionsOfUserLast.GetNonZerosCount(), R.GetNonZerosCountOfRow(4)));
            }
            #endregion

            #region Convert all users' preference relations into a single position matrix
            [TestMethod]
            public void GetPositionMatrix()
            {
                /*
                 * 5  3  0  1
                 * 4  0  0  1
                 * 1  1  0  5
                 * 1  0  0  4
                 * 0  1  5  4
                 */
                DataMatrix R = GetSampleRatingMatrix();
                PrefRelations PR = PrefRelations.CreateDiscrete(R);

                // act
                SparseMatrix positionMatrix = PR.GetPositionMatrix();

                // assert
                // How many ratings we have then how many positions we have
                Debug.Assert(positionMatrix.NonZerosCount == R.AsSparseMatrix.NonZerosCount);

                // Check if each rating has a corresponding position
                // we have check the count so don't need to check the oppsite
                foreach (Tuple<int, int, double> element in R.AsSparseMatrix.EnumerateIndexed(Zeros.AllowSkip))
                {
                    int indexOfUser = element.Item1;
                    int indexOfItem = element.Item2;
                    double rating = element.Item3;

                    Debug.Assert(positionMatrix[indexOfUser, indexOfItem] != SparseMatrix.Zero);
                }
            }
            #endregion

            /*
            #region Generate top N recommendation for each user
            [TestMethod]
            public void RecommendTopN()
            {
                //
                 // 5  3  0  1
                 // 4  0  0  1
                 // 1  1  0  5
                 // 1  0  0  4
                 // 0  1  5  4

                RatingMatrix R = GetSampleRatingMatrix();
                PrefRelations PR = PrefRelations.CreateDiscrete(R);
                List<int> targetUsers = new List<int> { 0, 1, 2, 3, 4 };

                //       1  1E-14  0     -1
                 //      1      0  0     -1
                 //   -0.5   -0.5  0      1
                 //     -1      0  0      1
                 //      0     -1  1  1E-14

                SparseMatrix positionMatrix = PR.GetPositionMatrix();

//1   0.774291  -0.186441  -0.178683  -0.978839
                //      0.774291          1  0.0198536   0.162791  -0.628768
                 //    -0.186441  0.0198536          1   0.972828   0.221028
                 //    -0.178683   0.162791   0.972828          1   0.258904
//-0.978839  -0.628768   0.221028   0.258904          1

                Matrix<double> userSimilarities = Metric.GetPearsonOfRows(R);

                // act
                PR.UserSimilarities = userSimilarities;
                Dictionary<int, List<int>> topNItemsByUser = PrefUserKNN.RecommendTopN(PR, 3, targetUsers, 4);

                // assert
                // Check the topN list of the first user
                // the top 3 neighbors of user index 0 are user indexes 1->3->2
                // so the predicted position of user index 0 on item 0 is = 0.774291 * positionMatrix[0,0] -0.178683 * positionMatrix[0,0]
                //double correctPositionOfItem0User0 = ((0.774291 * 1)+ (-0.178683 * -1) + (-0.186441 * -0.5)) / (0.774291 - 0.186441 - 0.178683);
                //double correctPositionOfItem1User0 = ((-0.186441 * -0.5)) / (- 0.178683);
                //double correctPositionOfItem2User0 = 0;
                //double correctPositionOfItem3User0 = ((0.774291 * -1)+ (-0.178683 * 1) + (-0.186441 * 1)) / (0.774291 - 0.186441 - 0.178683);
                Debug.Assert(topNItemsByUser[0][0] == 0);
                Debug.Assert(topNItemsByUser[0][1] == 2);
                Debug.Assert(topNItemsByUser[0][2] == 1);
                Debug.Assert(topNItemsByUser[0][3] == 3);
            }
            #endregion
             * */
    }
        #endregion

    }
}


text:
using namespace std::placeholders;

namespace df
{
TileInfo::TileInfo(drape_ptr<EngineContext> && engineContext)
  : m_context(std::move(engineContext))
  , m_isCanceled(false)
{}

m2::RectD TileInfo::GetGlobalRect() const
{
  return GetTileKey().GetGlobalRect();
}

void TileInfo::ReadFeatureIndex(MapDataProvider const & model)
{
  if (!DoNeedReadIndex())
    return;

  CheckCanceled();

  size_t const kAverageFeaturesCount = 256;
  m_featureInfo.reserve(kAverageFeaturesCount);

  MwmSet::MwmId lastMwm;
  model.ReadFeaturesID([this, &lastMwm](FeatureID const & id)
  {
    if (m_mwms.empty() || lastMwm != id.m_mwmId)
    {
      auto result = m_mwms.insert(id.m_mwmId);
      ASSERT(result.second, ());
      lastMwm = id.m_mwmId;
    }
    m_featureInfo.push_back(id);
  }, GetGlobalRect(), GetZoomLevel());
}

void TileInfo::ReadFeatures(MapDataProvider const & model)
{
#if defined(DRAPE_MEASURER) && defined(TILES_STATISTIC)
  DrapeMeasurer::Instance().StartTileReading();
#endif
  m_context->BeginReadTile();

  // Reading can be interrupted by exception throwing
  MY_SCOPE_GUARD(ReleaseReadTile, std::bind(&EngineContext::EndReadTile, m_context.get()));

  ReadFeatureIndex(model);
  CheckCanceled();

  m_context->GetMetalineManager()->Update(m_mwms);

  if (!m_featureInfo.empty())
  {
    auto const deviceLang = StringUtf8Multilang::GetLangIndex(languages::GetCurrentNorm());
    RuleDrawer drawer(std::bind(&TileInfo::InitStylist, this, deviceLang, _1, _2),
                      std::bind(&TileInfo::IsCancelled, this),
                      model.m_isCountryLoadedByName, make_ref(m_context));
    model.ReadFeatures(std::bind<void>(std::ref(drawer), _1), m_featureInfo);
  }
#if defined(DRAPE_MEASURER) && defined(TILES_STATISTIC)
  DrapeMeasurer::Instance().EndTileReading();
#endif
}

void TileInfo::Cancel()
{
  m_isCanceled = true;
}

bool TileInfo::IsCancelled() const
{
  return m_isCanceled;
}

void TileInfo::InitStylist(int8_t deviceLang, FeatureType const & f, Stylist & s)
{
  CheckCanceled();
  df::InitStylist(f, deviceLang, m_context->GetTileKey().m_zoomLevel,
                  m_context->Is3dBuildingsEnabled(), s);
}

bool TileInfo::DoNeedReadIndex() const
{
  return m_featureInfo.empty();
}

void TileInfo::CheckCanceled() const
{
  if (m_isCanceled)
    MYTHROW(ReadCanceledException, ());
}

int TileInfo::GetZoomLevel() const
{
  return ClipTileZoomByMaxDataZoom(m_context->GetTileKey().m_zoomLevel);
}
}  // namespace df

redpajama_set_name: RedPajamaGithub


text:
package dtm;

import java.io.IOException;
import java.lang.annotation.IncompleteAnnotationException;
import java.security.NoSuchAlgorithmException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.jms.DeliveryMode;
import javax.jms.ExceptionListener;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueReceiver;
import javax.jms.QueueSender;
import javax.jms.QueueSession;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.Topic;
import javax.jms.TopicConnection;
import javax.jms.TopicConnectionFactory;
import javax.jms.TopicPublisher;
import javax.jms.TopicSession;
import javax.jms.TopicSubscriber;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletContext;
import javax.ws.rs.core.Context;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

import com.rabbitmq.jms.admin.RMQConnectionFactory;
import com.rabbitmq.jms.admin.RMQDestination;

import jms.AllAbonamientosMDB;
import jms.AllFuncionesMDB;
import jms.AllRentabilidad2MDB;
import jms.AllRentabilidadMDB;
import jms.AllRetirarCompaniaMDB;
import jms.NonReplyException;
import tm.FestivAndesMaster;
import vos.CompaniaDeTeatro;
import vos.Funcion;
import vos.ListaAbonamientos;
import vos.ListaCompanias;
import vos.ListaFunciones;
import vos.ListaReporteRentabilidadC5;
import vos.ReporteRentabilidadC5;
import vos.ListaReporteRentabilidad2C5;

public class FestivAndesDistributed implements MessageListener, ExceptionListener
{

	/**
	 * Atributo tipo ListaVideos que va guardando todos los videos que llegan como respuesta de las otra aplicaciones
	 */
	private ListaReporteRentabilidadC5 respuesta;

	/**
	 * Atributo tipo TopicSession que se usa para la conexión a los topics
	 */
	private TopicSession topicSession;

	/**
	 * Atributo tipo Topic que maneja la conexión al topic de dar todos los videos
	 */
	private Topic topic;

	/**
	 * ArrayList que guarda todos los recursos que se usan para la conexión a las colas y topics
	 */
	private ArrayList<Object> recursos;

	/**
	 * boolean que dice si la aplicación esta a la espera de respuestas de las otras aplicaciones
	 */
	private boolean waiting;

	/**
	 * Numero de aplicaciones que hay en todo el sistema aparte de la propia.
	 * Esto se hace para saber cuantas respuestas se esperan
	 */
	private int numberAppsTotal;

	/**
	 * Numero de aplicaciones/respuestas que han llegado
	 */
	private int numberApps;

	/**
	 * Referencia a la clase principal VideoAndesMaster para su uso.
	 * Se usa para responder a requerimientos que llegan de otras aplicaciones
	 */
	private FestivAndesMaster master;

	/////Queues:

	/**
	 * Atributo que representa la cola personal de esta aplicación
	 */
	private String myQueue;

	/////Topics:

	/**
	 * Atributo que representa el topic: topicAllVideos
	 */
	private String topicAllRentabilidad;

	/////Protocol

	/**
	 * Atributo que representa el time out de el requerimiento de dar todos los videos
	 * 10 segundos
	 */
	public final static int TIME_OUT = 10;

	/**
	 * Ruta para la conexión al Remote Connection Factory
	 */
	public final static String REMOTE_CONNECTION_FACTORY = "java:jboss/exported/jms/RemoteConnectionFactory";

	/**
	 * Atributo que representa, dentro del mensaje, la solicitud de todos los videos de manera distribuida
	 */
	public final static String GET_ALL_VIDEO_ASK = "GETALLVIDEOS";

	/**
	 * Atributo que representa, dentro del mensaje, la respuesta del requerimiento dar todos los videos.
	 */
	public final static String GET_ALL_VIDEO_REPLY = "GETALLVIDEOSRES";

	/**
	 * Atributo que representa, dentro del mensaje, el conector para el formateo de todos los mensajes
	 */
	public final static String CONNECTOR = "@@@";

	private final static String QUEUE_NAME = "java:global/RMQAppQueue";
	private final static String MQ_CONNECTION_NAME = "java:global/RMQClient";

	private static FestivAndesDistributed instance;

	private FestivAndesMaster tm;

	private QueueConnectionFactory queueFactory;

	private TopicConnectionFactory factory;

	private AllRentabilidadMDB allRentabilidadMQ;

	private AllRentabilidad2MDB allRentabilidad2MQ;

	private AllFuncionesMDB allFuncionesMQ;

	private AllAbonamientosMDB allAbonamientosMQ;

	private AllRetirarCompaniaMDB allRetirarCompaniaMQ;

	private static String path;

	private FestivAndesDistributed() throws NamingException, JMSException
	{
		InitialContext ctx = new InitialContext();
		factory = (RMQConnectionFactory) ctx.lookup(MQ_CONNECTION_NAME);
		allRentabilidadMQ = new AllRentabilidadMDB(factory, ctx);

		allRentabilidadMQ.start();

	}

	public void stop() throws JMSException
	{
		allRentabilidadMQ.close();

	}

	/**
	 * Método que retorna el path de la carpeta WEB-INF/ConnectionData en el deploy actual dentro del servidor.
	 * @return path de la carpeta WEB-INF/ConnectionData en el deploy actual.
	 */
	public static void setPath(String p) {
		path = p;
	}

	public void setUpTransactionManager(FestivAndesMaster tm)
	{
		this.tm = tm;
	}

	private static FestivAndesDistributed getInst()
	{
		return instance;
	}

	public static FestivAndesDistributed getInstance(FestivAndesMaster tm)
	{
		if(instance == null)
		{
			try {
				instance = new FestivAndesDistributed();
			} catch (NamingException e) {
				e.printStackTrace();
			} catch (JMSException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		instance.setUpTransactionManager(tm);
		return instance;
	}

	public static FestivAndesDistributed getInstance()
	{
		if(instance == null)
		{
			FestivAndesMaster tm = new FestivAndesMaster(path);
			return getInstance(tm);
		}
		if(instance.tm != null)
		{
			return instance;
		}
		FestivAndesMaster tm = new FestivAndesMaster(path);
		return getInstance(tm);
	}

	/**
	public ListaVideos getLocalVideos() throws Exception
	{
		return tm.darVideosLocal();
	}

	public List<Videos> getRemoteVideos() throws JsonGenerationException, JsonMappingException, JMSException, IOException, NonReplyException, InterruptedException, NoSuchAlgorithmException
	{
		return allVideosMQ.getRemoteVideos();
	}
	 * @throws Exception

	*/

	public ReporteRentabilidadC5 getLocalRentabilidades(int idSitio) throws Exception {
		return tm.darRentabilidadesLocal(idSitio);
	}

	public ListaReporteRentabilidad2C5 getLocalRentabilidades2() throws SQLException {
		return tm.darRentabilidades2Local();
	}

	public ListaCompanias deleteLocalCompanias() throws SQLException, Exception{

		return tm.retirarCompaniasLocal();
	}

	public ListaFunciones getLocalFunciones() throws SQLException, Exception{

		return tm.darFuncionesLocal();
	}

	public ListaAbonamientos getLocalAbonamientos() throws SQLException, Exception{

		return tm.darAbonamientosLocal();
	}

	//TODO

	/**
	 * Método que inicializa la clase JMSManager
	 * @param numerApps - numero de aplicaciones totales
	 * @param myQueue - ruta de la cola personal de la aplicación
	 * @param topicAllVideos - ruta del topic topicAllVideos
	 * <b>post: </b> se han inicializado los atributos de la clase y
	 * se han generado la suscripciones y publicaciones a las colas y topics
	 */
	public void setUpJMSManager(int numerApps, String myQueue, String topicAllRentabilidad){
		try {
			this.numberAppsTotal = numerApps - 1;
			this.myQueue = myQueue;
			this.topicAllRentabilidad = topicAllRentabilidad;
			setupMyQueue();
			setupSubscriptions();
			waiting = false;
			respuesta = new ListaReporteRentabilidadC5(null);
			this.recursos = new ArrayList<Object>();
		} catch (JMSException e) {
			e.printStackTrace();
		} catch (NamingException e) {
			e.printStackTrace();
		}
	}

	/**
	 * Método que retorna la respuesta a requerimiento de dar todos los videos.
	 * @return ListaVideos - Objeto ListaVideos con los videos de la respuesta del requerimiento
	 * @throws IncompleteReplyException - Caso de IncompleteReplyException
	 * @throws NonReplyException - Caso de NonReplyException
	 * @throws JMSException - Caso de JMSException
	 */
	public ListaReporteRentabilidadC5 getResponse() throws IncompleteAnnotationException, JMSException, NamingException, InterruptedException, NonReplyException {
		sendMessage(); // manda el mensaje de solicitud del requerimiento al topic
		waiting = true; // Lo hace para< indicar que si esta esperando respuestas
		this.numberApps = 0; // Pone en 0 el numero de respuestas que han llegado

		int count = 0;
		while(TIME_OUT != count && this.numberApps != this.numberAppsTotal){
			TimeUnit.SECONDS.sleep(1); // espera activa que termina cuando se ha cumplido el time out o cuando han llegado todas las respuestas esperadas
			count++;
		}

		if(count == TIME_OUT){ // Verifica si se cumplió el time out
			if(this.respuesta.getRentabilidades().isEmpty()){
				waiting = false;
				this.numberApps = 0;
				throw new NonReplyException("Time Out - No Reply"); // Exception que indica que se cumplido el time out y nadie respondido
			}
			waiting = false;
			this.numberApps = 0;
		//	throw new IncompleteReplyException("Time out ",respuesta); // Exception que indica que se cumplido el time out pero algunos respondieron
		}
		waiting = false;
		this.numberApps = 0;
		if(respuesta.getRentabilidades().isEmpty())
			throw new NonReplyException("Got all responses but no videos were detected"); // Exception que indica que todos respondieron pero no llegaron videos
		ListaReporteRentabilidadC5 res = respuesta;
		respuesta = new ListaReporteRentabilidadC5(null);
		return res; // Retorna con la respuesta completa de todas las aplicaciones
	}

	/**
	 * Método que inicializa todas las suscripciones a los topics.
	 * En este caso solo al topic de topicAllVideos
	 * <b>post: </b> se han suscito al topic de dar todos los videos
	 */
	public void setupSubscriptions()
	{
		// init Topic para consumir donde llegan las peticiones
		try {
			InitialContext ctx = new InitialContext();
			this.topic = (Topic) ctx.lookup(topicAllRentabilidad);
			TopicConnectionFactory connFactory = (TopicConnectionFactory) ctx.lookup(REMOTE_CONNECTION_FACTORY);
			TopicConnection topicConn = connFactory.createTopicConnection();
			this.topicSession = topicConn.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
			TopicSubscriber topicSubscriber = topicSession.createSubscriber(topic);
			topicSubscriber.setMessageListener(this);
			topicConn.setExceptionListener(this);
			topicConn.start();
		} catch (NamingException e) {
			e.printStackTrace();
		} catch (JMSException e) {
			e.printStackTrace();
		}
	}

	/**
	 * Método que manda el mensaje para solicitar el requerimiento de las todos los videos
	 * <b>post: </b> se han mandado todos los mensaje
	 * @throws JMSException - Caso de JMSException
	 * @throws NamingException - Caso de NamingException
	 */
	public void sendMessage() throws JMSException, NamingException{
		// conecta al Topic para mandar la petición
		TopicPublisher topicPublisher = this.topicSession.createPublisher(this.topic);
		topicPublisher.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
		TextMessage message = topicSession.createTextMessage();
		message.setText(GET_ALL_VIDEO_ASK + CONNECTOR + this.myQueue);
		topicPublisher.publish(message);
		System.out.println("published: " + message.getText());
	}

	/**
	 * Método que publica y suscribe la cola personal de la aplicación
	 * <b>post: </b> se han publicado y suscrito a la cola personal
	 */
	public void setupMyQueue() throws NamingException, JMSException{
		// conecta a la cola para respuestas propias.
		InitialContext ctx = new InitialContext();
		Queue queue = (Queue) ctx.lookup(this.myQueue);
		QueueConnectionFactory connFactory = (QueueConnectionFactory) ctx. lookup(REMOTE_CONNECTION_FACTORY);
		QueueConnection queueConn = connFactory.createQueueConnection();
		QueueSession queueSession = queueConn.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
		QueueReceiver queueReceiver = queueSession.createReceiver(queue);
		queueReceiver.setMessageListener(this);
		queueConn.setExceptionListener(this);
		queueConn.start();
	}

	/**
	 * Método que manda el mensaje que llega como parámetro a la cola que llega como parámetro
	 * @param queueName - ruta de la cola
	 * @param response - mensaje a mandar
	 * <b>post: </b> se ha mandado el mensaje a la cola
	 */
	public void doResponseToQueue(String queueName , String response) throws NamingException, JMSException{
		// conecta a la cola de respuestas del que pidio
		InitialContext ctx = new InitialContext();
		Queue queue = (Queue) ctx.lookup(queueName);
		QueueConnectionFactory connFactory = (QueueConnectionFactory) ctx.lookup(REMOTE_CONNECTION_FACTORY);
		QueueConnection queueConn = connFactory.createQueueConnection();
		QueueSession queueSession = queueConn.createQueueSession(false,Session.DUPS_OK_ACKNOWLEDGE);
		QueueSender queueSender = queueSession.createSender(queue);
		queueSender.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
		TextMessage message = queueSession.createTextMessage(response);
		queueSender.send(message);
		System.out.println("sent: " + message.getText());
		queueConn.close();
	}

	/**
	 * Método listener que recibe los mensajes, lo formatea y  hace lo que corresponde en cada caso:
	 * - Caso 1: a[0].equals(GET_ALL_VIDEO_ASK): llega la petición del requerimiento dar todos los video por lo
	 * que pide todos los videos a la clase principal y manda un mensaje con la respuesta
	 * - Caso 2: a[0].equals(GET_ALL_VIDEO_REPLY): llega la respuesta de la petición del requerimiento por lo tanto
	 * Coge la respuesta y la guarda en respuesta
	 * @param message - mensaje que llego
	 * <b>post: </b> se ha mandado el mensaje a la cola
	 */
	public void onMessage(Message message)
	{
		TextMessage msg = (TextMessage) message;
		try
		{
			String mes = msg.getText();
			System.out.println("received: " + mes);
			String[] a = mes.split(CONNECTOR);
			if(a[0].equals(GET_ALL_VIDEO_ASK) && !a[1].equals(this.myQueue)){
				ReporteRentabilidadC5 videos = this.master.darRentabilidadesLocal(1);
				ObjectMapper mapper = new ObjectMapper();
				String jsonString = mapper.writeValueAsString(videos);
				doResponseToQueue(a[1], GET_ALL_VIDEO_REPLY + CONNECTOR + jsonString);
			}
			else if(a[0].equals(GET_ALL_VIDEO_REPLY)){
				ObjectMapper mapper = new ObjectMapper();
				if(waiting){
					ListaReporteRentabilidadC5 obj = mapper.readValue(a[1], ListaReporteRentabilidadC5.class);
					this.respuesta.addRentabilidad(obj);
					this.numberApps++;
				}
			}

		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	/**
	 * Método que se llama con el error cuando hay un error de JMS
	 */
	public void onException(JMSException exception)
	{
		System.err.println("something bad happended: " + exception);
	}
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Uses of Package java.text (Java Platform SE 8 )</title>
<meta name="date" content="2014-12-17">
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Java™ Platform
Standard Ed. 8

Prev

Next

Frames

No Frames

All Classes

Uses of Package
java.text

Packages that use java.text

Package
Description

java.awt

Contains all of the classes for creating user
interfaces and for painting graphics and images.

java.awt.event

Provides interfaces and classes for dealing with different
types of events fired by AWT components.

java.awt.font

Provides classes and interface relating to fonts.

java.awt.im

Provides classes and interfaces for the input method framework.

java.awt.im.spi

Provides interfaces that enable the development of input methods
that can be used with any Java runtime environment.

java.text

Provides classes and interfaces for handling text, dates, numbers, and messages
in a manner independent of natural languages.

java.text.spi

Service provider classes for the classes in the java.text package.

java.time.format

 Provides classes to print and parse dates and times.

javax.swing

Provides a set of "lightweight"
(all-Java language) components that,
to the maximum degree possible, work the same on all platforms.

javax.swing.plaf.synth

      Synth is a skinnable look and feel in which all painting is
      delegated.

javax.swing.text

Provides classes and interfaces that deal with editable
and noneditable text components.

Classes in java.text used by java.awt

Class and Description

AttributedCharacterIterator

An AttributedCharacterIterator allows iteration through both text and
 related attribute information.

AttributedCharacterIterator.Attribute

Defines attribute keys that are used to identify text attributes.

CharacterIterator

This interface defines a protocol for bidirectional iteration over text.

Classes in java.text used by java.awt.event

Class and Description

AttributedCharacterIterator

An AttributedCharacterIterator allows iteration through both text and
 related attribute information.

Classes in java.text used by java.awt.font

Class and Description

AttributedCharacterIterator

An AttributedCharacterIterator allows iteration through both text and
 related attribute information.

AttributedCharacterIterator.Attribute

Defines attribute keys that are used to identify text attributes.

BreakIterator

The BreakIterator class implements methods for finding
 the location of boundaries in text.

Classes in java.text used by java.awt.im

Class and Description

AttributedCharacterIterator

An AttributedCharacterIterator allows iteration through both text and
 related attribute information.

AttributedCharacterIterator.Attribute

Defines attribute keys that are used to identify text attributes.

Classes in java.text used by java.awt.im.spi

Class and Description

AttributedCharacterIterator

An AttributedCharacterIterator allows iteration through both text and
 related attribute information.

Classes in java.text used by java.text

Class and Description

AttributedCharacterIterator

An AttributedCharacterIterator allows iteration through both text and
 related attribute information.

AttributedCharacterIterator.Attribute

Defines attribute keys that are used to identify text attributes.

Bidi

This class implements the Unicode Bidirectional Algorithm.

BreakIterator

The BreakIterator class implements methods for finding
 the location of boundaries in text.

CharacterIterator

This interface defines a protocol for bidirectional iteration over text.

CollationElementIterator

The CollationElementIterator class is used as an iterator
 to walk through each character of an international string.

CollationKey

A CollationKey represents a String under the
 rules of a specific Collator object.

Collator

The Collator class performs locale-sensitive
 String comparison.

DateFormat

DateFormat is an abstract class for date/time formatting subclasses which
 formats and parses dates or time in a language-independent manner.

DateFormat.Field

Defines constants that are used as attribute keys in the
 AttributedCharacterIterator returned
 from DateFormat.formatToCharacterIterator and as
 field identifiers in FieldPosition.

DateFormatSymbols

DateFormatSymbols is a public class for encapsulating
 localizable date-time formatting data, such as the names of the
 months, the names of the days of the week, and the time zone data.

DecimalFormatSymbols

This class represents the set of symbols (such as the decimal separator,
 the grouping separator, and so on) needed by DecimalFormat
 to format numbers.

FieldPosition

FieldPosition is a simple class used by Format
 and its subclasses to identify fields in formatted output.

Format

Format is an abstract base class for formatting locale-sensitive
 information such as dates, messages, and numbers.

Format.Field

Defines constants that are used as attribute keys in the
 AttributedCharacterIterator returned
 from Format.formatToCharacterIterator and as
 field identifiers in FieldPosition.

MessageFormat.Field

Defines constants that are used as attribute keys in the
 AttributedCharacterIterator returned
 from MessageFormat.formatToCharacterIterator.

Normalizer.Form

This enum provides constants of the four Unicode normalization forms
 that are described in

 Unicode Standard Annex #15 — Unicode Normalization Forms
 and two methods to access them.

NumberFormat

NumberFormat is the abstract base class for all number
 formats.

NumberFormat.Field

Defines constants that are used as attribute keys in the
 AttributedCharacterIterator returned
 from NumberFormat.formatToCharacterIterator and as
 field identifiers in FieldPosition.

ParseException

Signals that an error has been reached unexpectedly
 while parsing.

ParsePosition

ParsePosition is a simple class used by Format
 and its subclasses to keep track of the current position during parsing.

Classes in java.text used by java.text.spi

Class and Description

BreakIterator

The BreakIterator class implements methods for finding
 the location of boundaries in text.

Collator

The Collator class performs locale-sensitive
 String comparison.

DateFormat

DateFormat is an abstract class for date/time formatting subclasses which
 formats and parses dates or time in a language-independent manner.

DateFormatSymbols

DateFormatSymbols is a public class for encapsulating
 localizable date-time formatting data, such as the names of the
 months, the names of the days of the week, and the time zone data.

DecimalFormatSymbols

This class represents the set of symbols (such as the decimal separator,
 the grouping separator, and so on) needed by DecimalFormat
 to format numbers.

NumberFormat

NumberFormat is the abstract base class for all number
 formats.

Classes in java.text used by java.time.format

Class and Description

Format

Format is an abstract base class for formatting locale-sensitive
 information such as dates, messages, and numbers.

ParsePosition

ParsePosition is a simple class used by Format
 and its subclasses to keep track of the current position during parsing.

Classes in java.text used by javax.swing

Class and Description

AttributedCharacterIterator

An AttributedCharacterIterator allows iteration through both text and
 related attribute information.

DecimalFormat

DecimalFormat is a concrete subclass of
 NumberFormat that formats decimal numbers.

Format

Format is an abstract base class for formatting locale-sensitive
 information such as dates, messages, and numbers.

MessageFormat

MessageFormat provides a means to produce concatenated
 messages in a language-neutral way.

ParseException

Signals that an error has been reached unexpectedly
 while parsing.

SimpleDateFormat

SimpleDateFormat is a concrete class for formatting and
 parsing dates in a locale-sensitive manner.

Classes in java.text used by javax.swing.plaf.synth

Class and Description

ParseException

Signals that an error has been reached unexpectedly
 while parsing.

Classes in java.text used by javax.swing.text

Class and Description

CharacterIterator

This interface defines a protocol for bidirectional iteration over text.

DateFormat

DateFormat is an abstract class for date/time formatting subclasses which
 formats and parses dates or time in a language-independent manner.

Format

Format is an abstract base class for formatting locale-sensitive
 information such as dates, messages, and numbers.

Format.Field

Defines constants that are used as attribute keys in the
 AttributedCharacterIterator returned
 from Format.formatToCharacterIterator and as
 field identifiers in FieldPosition.

MessageFormat

MessageFormat provides a means to produce concatenated
 messages in a language-neutral way.

NumberFormat

NumberFormat is the abstract base class for all number
 formats.

ParseException

Signals that an error has been reached unexpectedly
 while parsing.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Java™ Platform
Standard Ed. 8

Prev

Next

Frames

No Frames

All Classes

 Submit a bug or feature
For further API reference and developer documentation, see Java SE Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.
 Copyright © 1993, 2015, Oracle and/or its affiliates.  All rights reserved.


text:
/**
 * Spring Security configuration.
 */
package org.dictionary.security;


text:
Steel MQ
========

PHP HTTP REST Message Queue based on Symfony and MySQL

[![HuBoard badge](http://img.shields.io/badge/Hu-Board-7965cc.svg)](https://huboard.com/aerialship/steel-mq/)

[![Build Status](https://scrutinizer-ci.com/g/aerialship/steel-mq/badges/build.png?b=master)](https://scrutinizer-ci.com/g/aerialship/steel-mq/build-status/master)
[![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/aerialship/steel-mq/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/aerialship/steel-mq/?branch=master)
[![Code Coverage](https://img.shields.io/coveralls/aerialship/steel-mq.svg)](https://coveralls.io/r/aerialship/steel-mq)

[Technical Documentation](src/AerialShip/SteelMqBundle/Resources/doc/index.md)


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
SimpleTreeModelAggregator (Java Execution Measurement Library)
</TITLE>

<META NAME="date" CONTENT="2009-03-12">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

etm.contrib.aggregation.swing

Class SimpleTreeModelAggregator

java.lang.Object
  javax.swing.tree.DefaultTreeModel
      etm.contrib.aggregation.swing.SimpleTreeModelAggregator

All Implemented Interfaces:
Aggregator, java.io.Serializable, javax.swing.tree.TreeModel

Deprecated. Please don't use this aggregator any more. With JETM 1.3.0 this aggregator will be removed.

public class SimpleTreeModelAggregator
extends javax.swing.tree.DefaultTreeModel
implements Aggregator

 The SimpleTreeModelAggregator builds up a Swing TreeModel
 for all EtmPoints. Do not use anymore.

 Please note that the current implementation isn't very efficient, it definitly adds
 some overhead for every measurement.

Version:

$Revision: 150 $

Author:

void.fm

See Also:
Serialized Form

Field Summary

protected  Aggregator
delegate

          Deprecated.

Fields inherited from class javax.swing.tree.DefaultTreeModel

asksAllowsChildren, listenerList, root

Constructor Summary

SimpleTreeModelAggregator(java.lang.String aName)

          Deprecated. Creates a new SimpleTreeModelAggregator with a RootAggregator as
 backing aggregator instance.

SimpleTreeModelAggregator(java.lang.String aName,
                          Aggregator aDelegate)

          Deprecated. Creates a new SimpleTreeModelAggregator which delegates
 add(etm.core.monitor.EtmPoint) calls to the provided
 aggregator instances after altering the treemodel.

Method Summary

 void
add(EtmPoint point)

          Deprecated. Adds a new EtmPoint to the aggregator.

 void
flush()

          Deprecated. Flushes the current aggregation details.

 AggregatorMetaData
getMetaData()

          Deprecated. Returns detailed information about the aggregator chain.

 void
init(EtmMonitorContext ctx)

          Deprecated. Lifecycle Method, will be called before Aggregator.start(), after initalization of
 the current EtmMonitor runtime.

 void
render(MeasurementRenderer renderer)

          Deprecated. Renders the current state of the aggregator
 using the provided renderer instance.

 void
reset()

          Deprecated. Resets the internal aggregator state.

 void
reset(java.lang.String symbolicName)

          Deprecated. Resets the internal aggregator state for a etm point.

 void
start()

          Deprecated. Lifecycle method, will be called after all Aggregator instances are initialized
 by calling Aggregator.init(etm.core.monitor.EtmMonitorContext) and  before the
 EtmMonitor instance will becomes available.

 void
stop()

          Deprecated. Lifecycle method, will be called after the EtmMonitor instance
 was shutdown.

Methods inherited from class javax.swing.tree.DefaultTreeModel

addTreeModelListener, asksAllowsChildren, fireTreeNodesChanged, fireTreeNodesInserted, fireTreeNodesRemoved, fireTreeStructureChanged, getChild, getChildCount, getIndexOfChild, getListeners, getPathToRoot, getPathToRoot, getRoot, getTreeModelListeners, insertNodeInto, isLeaf, nodeChanged, nodesChanged, nodeStructureChanged, nodesWereInserted, nodesWereRemoved, reload, reload, removeNodeFromParent, removeTreeModelListener, setAsksAllowsChildren, setRoot, valueForPathChanged

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

delegate

protected Aggregator delegate

Deprecated.

Constructor Detail

SimpleTreeModelAggregator

public SimpleTreeModelAggregator(java.lang.String aName)

Deprecated.
Creates a new SimpleTreeModelAggregator with a RootAggregator as
 backing aggregator instance.

Parameters:
aName - The name of the root node.
See Also:
RootAggregator

SimpleTreeModelAggregator

public SimpleTreeModelAggregator(java.lang.String aName,
                                 Aggregator aDelegate)

Deprecated.
Creates a new SimpleTreeModelAggregator which delegates
 add(etm.core.monitor.EtmPoint) calls to the provided
 aggregator instances after altering the treemodel.

Parameters:
aName -
aDelegate -

Method Detail

add

public void add(EtmPoint point)

Deprecated.
Description copied from interface: Aggregator

Adds a new EtmPoint to the aggregator.

Specified by:
add in interface Aggregator

Parameters:
point - A new collected EtmPoint.

flush

public void flush()

Deprecated.
Description copied from interface: Aggregator

Flushes the current aggregation details.
 Buffering Aggragetors should clean up their process buffer.

Specified by:
flush in interface Aggregator

reset

public void reset()

Deprecated.
Description copied from interface: Aggregator

Resets the internal aggregator state. Persistent
 states usually aren't affected.

Specified by:
reset in interface Aggregator

reset

public void reset(java.lang.String symbolicName)

Deprecated.
Description copied from interface: Aggregator

Resets the internal aggregator state for a etm point.
 Persistent states usually aren't affected.

Specified by:
reset in interface Aggregator

Parameters:
symbolicName - The name of the etm point to be resetted.

render

public void render(MeasurementRenderer renderer)

Deprecated.
Description copied from interface: Aggregator

Renders the current state of the aggregator
 using the provided renderer instance.

Specified by:
render in interface Aggregator

Parameters:
renderer - The renderer.

getMetaData

public AggregatorMetaData getMetaData()

Deprecated.
Description copied from interface: Aggregator

Returns detailed information about the aggregator chain.

Specified by:
getMetaData in interface Aggregator

Returns:
The AggregatorMetaData.

init

public void init(EtmMonitorContext ctx)

Deprecated.
Description copied from interface: Aggregator

Lifecycle Method, will be called before Aggregator.start(), after initalization of
 the current EtmMonitor runtime. Be aware that Plugins are instantiated, but not
 started at this point.

Specified by:
init in interface Aggregator

Parameters:
ctx - The current EtmMonitor Context.

start

public void start()

Deprecated.
Description copied from interface: Aggregator

Lifecycle method, will be called after all Aggregator instances are initialized
 by calling Aggregator.init(etm.core.monitor.EtmMonitorContext) and  before the
 EtmMonitor instance will becomes available.

Specified by:
start in interface Aggregator

stop

public void stop()

Deprecated.
Description copied from interface: Aggregator

Lifecycle method, will be called after the EtmMonitor instance
 was shutdown.

Specified by:
stop in interface Aggregator

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

Copyright © 2004,2005, 2006, 2007 void.fm. All Rights Reserved.


text:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>Présentation on Datactivist</title>
    <link>https://datactivist.coop/fr/tags/presentation/</link>
    <description>Recent content in Présentation on Datactivist</description>
    <generator>Hugo -- gohugo.io</generator>
    <language>fr_FR</language>
    <lastBuildDate>Wed, 09 Dec 2020 00:00:00 +0100</lastBuildDate><atom:link href="https://datactivist.coop/fr/tags/presentation/index.xml" rel="self" type="application/rss+xml" />
    <item>
      <title>Ces 10 choses incroyables qui n'existeraient pas sans l'open data</title>
      <link>https://datactivist.coop/fr/ressources/lewagon/</link>
      <pubDate>Wed, 09 Dec 2020 00:00:00 +0100</pubDate>

      <guid>https://datactivist.coop/fr/ressources/lewagon/</guid>
      <description>Joël Gombin présente pour le Wagon des cas d&rsquo;usage de l&rsquo;open data. Une introduction pédagogique à l&rsquo;open data, dont on peut également récupérer le support.</description>
    </item>

  </channel>
</rss>


text:
export default function (value, inMin, inMax, outMin, outMax) {
  return (value - inMin) * (outMax - outMin) / (inMax - inMin) + outMin
}


text:
using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;

using System.IO;
using System.Security.Cryptography;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using GrowingData.Mung.Core;

namespace GrowingData.Mung.Relationizer {

	/// <summary>
	/// Holds the actual reference to a file which a RelationalEventWriter
	/// will write to.
	/// </summary>
	public class RelationalEventFile : IDisposable {
		public const string FilePrefixActive = "active";
		public const string FilePrefixComplete = "complete";

		private StreamWriter _currentStream;

		private string _basePath;
		private string _time;
		private string _eventName;
		private string _schemaHash;

		private SortedList<string, RelationalField> _schema;

		public string SchemaHash { get { return _schemaHash; } }
		public string TimeString { get { return _time; } }

		public string GetFilepath(string type) {
			return Path.Combine(_basePath, GetFilename(type));
		}

		public string GetFilename(string type) {

			var fileName = string.Format("{0}-{1}.{2}-{3}.tsv",
				type,
				_eventName,
				_time,
				_schemaHash);

			return fileName;
		}

		public RelationalEventFile(string basePath, string time, string eventName, SortedList<string, RelationalField> schema) {
			_basePath = basePath;
			_time = time;
			_eventName = eventName;
			_schema = new SortedList<string, RelationalField>(schema);

			_schemaHash = GetSchemaHash(schema);

			Open();
		}

		private void Open() {
			var fileStream = File.Open(GetFilepath(FilePrefixActive), FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read);
			_currentStream = new StreamWriter(fileStream);

			WriteHeader(_currentStream, _schema);
		}

		public void WriteRow(RelationalEvent evt) {
			WriteRow(_currentStream, _schema, evt);
		}

		public void Dispose() {
			if (_currentStream != null) {
				_currentStream.Close();
				_currentStream.Dispose();

				File.Move(GetFilepath(FilePrefixActive), GetFilepath(FilePrefixComplete));
			}
		}

		public static void WriteHeader(StreamWriter writer, SortedList<string, RelationalField> schema) {
			var columns = new string[] { "_Id_", "_ParentId_", "_At_" }
				.Concat(schema.Keys);

			var types = new DbType[] { DbType.Key, DbType.Key, DbType.DateTime }
				.Concat(schema.Values.Select(x => x.Type));

			writer.WriteLine(string.Join("\t", columns));
			writer.WriteLine(string.Join("\t", types.Select(x => x.ToString())));

		}

		public static void WriteRow(StreamWriter writer, SortedList<string, RelationalField> schema, RelationalEvent evt) {
			var values = new string[] {
				RelationalEvent.Serialize(evt._Id_),
				RelationalEvent.Serialize(evt._ParentId_),
				RelationalEvent.Serialize(evt._At_)
			}.Concat(
				schema.Select(x => evt[x.Key])
			);

			writer.WriteLine(string.Join("\t", values.Select(x => x)));
			writer.Flush();
		}

		public static string GetSchemaHash(SortedList<string, RelationalField> schema) {
			var schemaString = string.Join("|", schema.Values.Select(x => string.Format("{0}:{1}", x.ColumnName, x.Type)));
			return Hashing.HashStringMD5(schemaString);
		}

	}

}


text:
<?php

namespace Google\AdsApi\AdManager\v202202;

/**
 * This file was generated from WSDL. DO NOT EDIT.
 */
class SslManualOverride
{
    const UNKNOWN = 'UNKNOWN';
    const NO_OVERRIDE = 'NO_OVERRIDE';
    const SSL_COMPATIBLE = 'SSL_COMPATIBLE';
    const NOT_SSL_COMPATIBLE = 'NOT_SSL_COMPATIBLE';

}


text:
<?php

namespace Nails\Common\Console\Command\Database;

use Nails\Common\Console\Seed\DefaultSeed;
use Nails\Common\Helper\Directory;
use Nails\Components;
use Nails\Console\Command\Base;
use Nails\Environment;
use Nails\Factory;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

/**
 * Class Seed
 *
 * @package Nails\Common\Console\Command\Database
 */
class Seed extends Base
{
    /**
     * Configures the command
     *
     * @return void
     */
    protected function configure()
    {
        $this
            ->setName('db:seed')
            ->setDescription('Seed the database')
            ->addArgument(
                'component',
                InputArgument::OPTIONAL,
                'Filter by component'
            )
            ->addArgument(
                'class',
                InputArgument::OPTIONAL,
                'Filter by class name (comma separated)'
            )
            ->addOption(
                'list',
                'l',
                InputOption::VALUE_NONE,
                'List the seeders, rather than execute'
            )
            ->addOption(
                'fresh',
                'f',
                InputOption::VALUE_NONE,
                'Rebuild the database before seeding'
            );
    }

    // --------------------------------------------------------------------------

    /**
     * Executes the app
     *
     * @param InputInterface  $oInput  The Input Interface provided by Symfony
     * @param OutputInterface $oOutput The Output Interface provided by Symfony
     *
     * @return int
     * @throws \Exception
     */
    protected function execute(InputInterface $oInput, OutputInterface $oOutput)
    {
        parent::execute($oInput, $oOutput);

        $this->banner('Nails Database Seeder');

        // --------------------------------------------------------------------------

        $aSeeders = $this->filterSeeders(
            $this->getSeeders(),
            $oInput->getArgument('component'),
            $oInput->getArgument('class')
        );

        if (empty($aSeeders)) {
            $oOutput->writeln('No seeders were discovered. Make one using <comment>make:db:seed</comment>');
            $oOutput->writeln('');
            return static::EXIT_CODE_SUCCESS;
        }

        // --------------------------------------------------------------------------

        if ($oInput->getOption('list')) {

            $oOutput->writeln('The following seeders are available:');
            $this->listSeeders($aSeeders);

            return static::EXIT_CODE_SUCCESS;
        }

        // --------------------------------------------------------------------------

        //  Check environment
        if (Environment::is(Environment::ENV_PROD)) {

            $oOutput->writeln('');
            $oOutput->writeln('--------------------------------------');
            $oOutput->writeln('| <info>WARNING: The app is in PRODUCTION.</info> |');
            $oOutput->writeln('--------------------------------------');
            $oOutput->writeln('');
            $oOutput->writeln('Aborting seed.');

            return static::EXIT_CODE_FAILURE;
        }

        // --------------------------------------------------------------------------

        //  Get confirmation
        $oOutput->writeln('The following seeds will be executed in this order:');
        $this->listSeeders($aSeeders);

        $bDoSeed = $this->confirm('Does this look OK?', true);

        if ($bDoSeed) {

            if ($oInput->getOption('fresh')) {
                $oOutput->writeln('');
                $oOutput->write('Rebuilding database... ');

                $iExitCode = $this->callCommand(
                    'db:rebuild',
                    array_filter([
                        '-v'   => $oOutput->getVerbosity() === $oOutput::VERBOSITY_VERBOSE,
                        '-vv'  => $oOutput->getVerbosity() === $oOutput::VERBOSITY_VERY_VERBOSE,
                        '-vvv' => $oOutput->getVerbosity() === $oOutput::VERBOSITY_DEBUG,
                    ]),
                    false,
                    $oOutput->getVerbosity() <= $oOutput::VERBOSITY_NORMAL
                );

                if ($iExitCode !== static::EXIT_CODE_SUCCESS) {
                    return $this->abort(
                        static::EXIT_CODE_FAILURE,
                        ['Failed to reset database.']
                    );
                }
                $oOutput->writeln('<info>done!</info>');
            } else {
                $oOutput->writeln('');
            }

            $oOutput->writeln('Executing seeds...');
            $oOutput->writeln('');

            $oDb = Factory::service('PDODatabase');

            foreach ($aSeeders as $oSeeder) {

                $oOutput->write(
                    str_pad($this->renderLine($oSeeder) . '... ', 50, ' ')
                );

                $sClassName = $oSeeder->class;
                $oClass     = new $sClassName($oDb);

                $oClass->pre();
                $oClass->execute();
                $oClass->post();

                $oOutput->writeln('<info>done!</info>');
            }
            $oOutput->writeln('');

        } else {
            $oOutput->writeln('');
            $oOutput->writeln('No seeds were executed');
            $oOutput->writeln('');
        }

        // --------------------------------------------------------------------------

        //  Cleaning up
        $oOutput->writeln('<comment>Cleaning up...</comment>');

        // --------------------------------------------------------------------------

        //  And we're done
        $oOutput->writeln('');
        $oOutput->writeln('Complete!');

        return static::EXIT_CODE_SUCCESS;
    }

    // --------------------------------------------------------------------------

    /**
     * Returns the discovered seeders
     *
     * @return \stdClass[]
     */
    protected function getSeeders(): array
    {
        $aSeedClasses = [];
        foreach (Components::available() as $oComponent) {

            $aSeeds = $oComponent
                ->findClasses('Seed')
                ->whichExtend(DefaultSeed::class);

            foreach ($aSeeds as $sClass) {
                $aSeedClasses[] = (object) [
                    'component' => $oComponent,
                    'class'     => $sClass,
                    'priority'  => constant($sClass . '::CONFIG_PRIORITY'),
                ];
            }
        }

        //  Sort by priority, then class name
        array_multisort(
            array_column($aSeedClasses, 'priority'), SORT_ASC,
            array_column($aSeedClasses, 'class'), SORT_ASC,
            $aSeedClasses
        );

        return $aSeedClasses;
    }

    // --------------------------------------------------------------------------

    /**
     * Filters seeders by component and class
     *
     * @param array       $aSeeders   The seeders to filter
     * @param string|null $sComponent The component name to filter by
     * @param string|null $sClass     The classname to filter by
     *
     * @return \stdClass[]
     */
    protected function filterSeeders(array $aSeeders, string $sComponent = null, string $sClass = null): array
    {
        if ($sComponent) {
            $aSeeders = array_filter(
                $aSeeders,
                function ($oSeeder) use ($sComponent) {
                    return $sComponent === $oSeeder->component->slug;
                }
            );
        }

        if ($sClass) {

            $aClasses = array_filter(explode(',', $sClass));
            $aSeeders = array_filter(
                $aSeeders,
                function ($oSeeder) use ($aClasses) {
                    return in_array($this->stripNamespace($oSeeder), $aClasses);
                }
            );
        }

        return $aSeeders;
    }

    // --------------------------------------------------------------------------

    /**
     * Renders a styalized list of seeder class names
     *
     * @param \stdClass[] $aSeeders The seeders to render
     */
    protected function listSeeders(array $aSeeders): void
    {
        $this->oOutput->writeln('');
        foreach ($aSeeders as $oSeeder) {
            $this->oOutput->writeln(
                $this->renderLine($oSeeder)
            );
        }
        $this->oOutput->writeln('');
    }

    // --------------------------------------------------------------------------

    /**
     * Renders a single styalised line for a seeder
     *
     * @param \stdClass $oSeeder The seeder to rendered
     *
     * @return string
     */
    protected function renderLine($oSeeder): string
    {
        return sprintf(
            ' - [<comment>%s</comment>] <info>%s</info>',
            $oSeeder->component->slug,
            $this->stripNamespace($oSeeder)
        );
    }

    // --------------------------------------------------------------------------

    /**
     * Returns the seeder's class anme without the namespace prefix
     *
     * @param \stdClass $oSeeder The seeder to render
     *
     * @return string
     */
    protected function stripNamespace($oSeeder): string
    {
        return preg_replace(
            '/^' . preg_quote($oSeeder->component->namespace . 'Seed\\', '/') . '/',
            '',
            $oSeeder->class
        );
    }
}


text:
from office365.runtime.client_value import ClientValue

class PendingReviewItemsStatistics(ClientValue):

    def __init__(self, label_id=None, label_name=None):
        self.LabelId = label_id
        self.LabelName = label_name


text:
/** Automatically generated file. DO NOT MODIFY */
package com.holoware.aktp;

public final class BuildConfig {
    public final static boolean DEBUG = true;
}


text:
namespace uvkc {
namespace android {

namespace {

// The following structs are from:
// https://android.googlesource.com/platform/hardware/libhardware/+/master/include/hardware/hardware.h

const char kHalModuleInfo[] = "HMI";

typedef struct hw_module_t {
  uint32_t tag;
  uint16_t module_api_version;
  uint16_t hal_api_version;
  const char *id;
  const char *name;
  const char *author;
  struct hw_module_methods_t *methods;
  void *dso;
#ifdef __LP64__
  uint64_t reserved[32 - 7];
#else
  uint32_t reserved[32 - 7];
#endif
} hw_module_t;

typedef struct hw_module_methods_t {
  int (*open)(const struct hw_module_t *module, const char *id,
              struct hw_device_t **device);
} hw_module_methods_t;

typedef struct hw_device_t {
  uint32_t tag;
  uint32_t version;
  struct hw_module_t *module;
#ifdef __LP64__
  uint64_t reserved[12];
#else
  uint32_t reserved[12];
#endif
  int (*close)(struct hw_device_t *device);
} hw_device_t;

// The following structs are from:
// https://android.googlesource.com/platform/frameworks/native/+/refs/heads/master/vulkan/include/hardware/hwvulkan.h

const char kHwVulkanDevice0[] = "vk0";

typedef struct hwvulkan_device_t {
  struct hw_device_t common;
  PFN_vkEnumerateInstanceExtensionProperties
      EnumerateInstanceExtensionProperties;
  PFN_vkCreateInstance CreateInstance;
  PFN_vkGetInstanceProcAddr GetInstanceProcAddr;
} hwvulkan_device_t;

}  // namespace

absl::StatusOr<PFN_vkGetInstanceProcAddr> GetVulkanICDGetInstanceProceAddr(
    const DynamicLibrary &dylib) {
  // Mimicking the Android Vulkan loader to query vkGetInstanceProcAddr. See
  // https://source.android.com/devices/graphics/implement-vulkan#driver_emun
  // for more details.

  auto *module =
      reinterpret_cast<hw_module_t *>(dylib.GetSymbol(kHalModuleInfo));
  if (!module) {
    return absl::UnavailableError("cannot find the HMI symbol in Vulkan ICD");
  }

  hw_device_t *device = nullptr;
  if (module->methods->open(module, kHwVulkanDevice0, &device)) {
    return absl::UnavailableError("cannot open device from Vulkan ICD");
  }

  return reinterpret_cast<hwvulkan_device_t *>(device)->GetInstanceProcAddr;
}

}  // namespace android
}  // namespace uvkc


text:
package fileserver

import (
	"net/http"
	"strconv"

	"github.com/prasannavl/go-errors/errutils"

	"github.com/prasannavl/go-errors/httperror"
	"github.com/prasannavl/mchain"

	"github.com/prasannavl/go-gluons/log"
)

func New(root http.FileSystem) mchain.Handler {
	return &FileServer{root}
}

type FileServer struct {
	root http.FileSystem
}

func (f *FileServer) ServeHTTP(w http.ResponseWriter, r *http.Request) error {
	return ServeRequestPath(w, r, f.root)
}

func NewEx(root http.FileSystem, notFoundHandler mchain.Handler) mchain.Handler {
	return &FileServerEx{FileServer{root}, true, notFoundHandler}
}

type FileServerEx struct {
	FileServer
	RedirectsEnabled bool
	NotFoundHandler  mchain.Handler
}

func (f *FileServerEx) ServeHTTP(w http.ResponseWriter, r *http.Request) error {
	err := ServeRequestPath(w, r, f.root)
	if err != nil {
		e := err.(*Err)

		l := log.With("path", r.URL.Path).
			With("status", e.Code())
		if !errutils.HasMessage(e) {
			l = l.With("cause", e.Cause())
		}
		switch e.Kind {
		case ErrRedirect:
			if f.RedirectsEnabled {
				e.Headers().Write(w)
				w.WriteHeader(http.StatusMovedPermanently)
				return nil
			}
		case ErrFsOpen:
			l.Warnf("fileserver: kind: %d, %v", e.Kind, e)
			if f.NotFoundHandler != nil {
				return f.NotFoundHandler.ServeHTTP(w, r)
			}
		default:
			l.Warnf("fileserver: kind: %d, %v", e.Kind, e)
		}
	}
	return err
}

func statusCodeFromHint(hint int) string {
	return strconv.Itoa(httperror.ErrorCode(hint))
}


text:
![](http://cdn.devatrox.de/img/sunglass-logo.png)

[![Build Status](https://travis-ci.org/devatrox/sunglass-core.png?branch=master)](https://travis-ci.org/devatrox/sunglass-core) [![devDependency Status](https://david-dm.org/devatrox/sunglass-core/dev-status.png)](https://david-dm.org/devatrox/sunglass-core#info=devDependencies)

**A functions library for Sass. The successor to Sunglass**

## Installation

* Install with [Bower](http://bower.io/)

    `bower install sunglass-core --save-dev`

* Or Download the [latest release](https://github.com/devatrox/sunglass-core/releases) and put it wherever you like

* Import Sunglass into your Sass file

    `@import "path/to/sunglass";`


text:
package com.haulmont.cuba.web.widgets.client.aggregation;

import com.google.gwt.dom.client.*;
import com.google.gwt.dom.client.Style.Overflow;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.Widget;
import com.haulmont.cuba.web.widgets.client.Tools;
import com.haulmont.cuba.web.widgets.client.tableshared.TableWidget;
import com.haulmont.cuba.web.widgets.client.tableshared.TotalAggregationInputListener;
import com.vaadin.client.BrowserInfo;
import com.vaadin.client.ComputedStyle;
import com.vaadin.client.UIDL;
import com.vaadin.v7.client.ui.VScrollTable;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

/**
 * Special aggregation row for {@link com.haulmont.cuba.web.widgets.client.table.CubaScrollTableWidget} and
 * {@link com.haulmont.cuba.web.widgets.client.treetable.CubaTreeTableWidget}
 */
public class TableAggregationRow extends Panel {

    protected boolean initialized = false;

    protected char[] aligns;
    protected Element container;
    protected Element tr;

    protected TableWidget tableWidget;

    protected TotalAggregationInputListener totalAggregationInputHandler;
    protected List<AggregationInputFieldInfo> inputsList;

    public TableAggregationRow(TableWidget tableWidget) {
        this.tableWidget = tableWidget;

        String primaryStyleName = tableWidget.getStylePrimaryName();

        DivElement wrapElement = Document.get().createDivElement();
        wrapElement.setClassName(primaryStyleName + "-arow-wrap");
        setElement(wrapElement);

        container = Document.get().createDivElement();

        container.setClassName(primaryStyleName + "-arow");
        container.getStyle().setOverflow(Overflow.HIDDEN);

        wrapElement.appendChild(container);
    }

    @Override
    public Iterator<Widget> iterator() {
        return Collections.<Widget>emptyList().iterator();
    }

    @Override
    public boolean remove(Widget child) {
        return false;
    }

    @Override
    public void onBrowserEvent(Event event) {
        super.onBrowserEvent(event);

        final int type = DOM.eventGetType(event);
        Element sourceElement = Element.as(event.getEventTarget());

        if (type == Event.ONKEYDOWN
                && (event.getKeyCode() == KeyCodes.KEY_ENTER)) {
            AggregationInputFieldInfo info = getAggregationInputInfo(sourceElement);
            if (info != null) {
                String columnKey = info.getColumnKey();
                String value = info.getInputElement().getValue();
                info.setFocused(true);

                if (columnKey != null) {
                    totalAggregationInputHandler.onInputChange(columnKey, value, true);
                }
            }
        }

        if (type == Event.ONCHANGE && totalAggregationInputHandler != null) {
            AggregationInputFieldInfo info = getAggregationInputInfo(sourceElement);
            if (info != null) {
                String columnKey = info.getColumnKey();
                String value = info.getInputElement().getValue();
                // do not send event, cause it was sent with `ENTER` key event
                if (info.isFocused()) {
                    info.setFocused(false);
                    return;
                }

                if (columnKey != null) {
                    totalAggregationInputHandler.onInputChange(columnKey, value, false);
                }
            }
        }
    }

    public void updateFromUIDL(UIDL uidl) {
        if (container.hasChildNodes()) {
            container.removeAllChildren();
        }

        aligns = tableWidget.getHead().getColumnAlignments();

        if (uidl.getChildCount() > 0) {
            final Element table = DOM.createTable();
            table.setAttribute("cellpadding", "0");
            table.setAttribute("cellspacing", "0");

            final Element tBody = DOM.createTBody();
            tr = DOM.createTR();

            tr.setClassName(tableWidget.getStylePrimaryName() + "-arow-row");

            if (inputsList != null && !inputsList.isEmpty()) {
                inputsList.clear();
            }

            addCellsFromUIDL(uidl);

            tBody.appendChild(tr);
            table.appendChild(tBody);

            DivElement tableWrapper = Document.get().createDivElement();
            tableWrapper.appendChild(table);
            container.appendChild(tableWrapper);

            // set focus to input if we pressed `ENTER`
            String focusColumnKey = uidl.getStringAttribute("focusInput");
            if (focusColumnKey != null && inputsList != null) {
                for (AggregationInputFieldInfo info : inputsList) {
                    if (info.getColumnKey().equals(focusColumnKey)) {
                        info.getInputElement().focus();
                        break;
                    }
                }
            }
        }

        initialized = container.hasChildNodes();
    }

    public void setCellWidth(int cellIx, int width) {
        // CAUTION: copied from VScrollTableRow with small changes
        final Element cell = DOM.getChild(tr, cellIx);
        Style wrapperStyle = cell.getFirstChildElement().getStyle();
        int wrapperWidth = width;
        if (BrowserInfo.get().isWebkit()
                || BrowserInfo.get().isOpera10()) {
            /*
             * Some versions of Webkit and Opera ignore the width
             * definition of zero width table cells. Instead, use 1px
             * and compensate with a negative margin.
             */
            if (width == 0) {
                wrapperWidth = 1;
                wrapperStyle.setMarginRight(-1, Style.Unit.PX);
            } else {
                wrapperStyle.clearMarginRight();
            }
        }
        wrapperStyle.setPropertyPx("width", wrapperWidth);
        cell.getStyle().setPropertyPx("width", width);
    }

    public boolean isInitialized() {
        return initialized;
    }

    public void setHorizontalScrollPosition(int scrollLeft) {
        container.setScrollLeft(scrollLeft);
    }

    public void setTotalAggregationInputHandler(TotalAggregationInputListener totalAggregationInputHandler) {
        this.totalAggregationInputHandler = totalAggregationInputHandler;
    }

    public boolean isAggregationRowEditable() {
        return inputsList != null && !inputsList.isEmpty();
    }

    // CAUTION copied from com.vaadin.client.ui.VScrollTable.VScrollTableBody.VScrollTableRow.getRealCellWidth
    public double getRealCellWidth(int colIdx) {
        if (colIdx >= tr.getChildCount()) {
            return -1;
        }

        Element cell = DOM.getChild(tr, colIdx);
        ComputedStyle cs = new ComputedStyle(cell);

        return cs.getWidth() + cs.getPaddingWidth() + cs.getBorderWidth();
    }

    protected void addCellsFromUIDL(UIDL uidl) {
        int colIndex = 0;
        final Iterator cells = uidl.getChildIterator();
        while (cells.hasNext() && colIndex < tableWidget.getVisibleColOrder().length) {
            String columnId = tableWidget.getVisibleColOrder()[colIndex];

            if (addSpecificCell(columnId, colIndex)) {
                colIndex++;
                continue;
            }

            final Object cell = cells.next();

            String style = "";
            if (uidl.hasAttribute("style-" + columnId)) {
                style = uidl.getStringAttribute("style-" + columnId);
            }

            boolean sorted = tableWidget.getHead().getHeaderCell(colIndex).isSorted();

            if (isAggregationEditable(uidl, colIndex)) {
                addCellWithField((String) cell, aligns[colIndex], colIndex);
            } else if (cell instanceof String) {
                addCell((String) cell, aligns[colIndex], style, sorted);
            }

            final String colKey = tableWidget.getColKeyByIndex(colIndex);
            int colWidth;
            if ((colWidth = tableWidget.getColWidth(colKey)) > -1) {
                tableWidget.setColWidth(colIndex, colWidth, false);
            }

            colIndex++;
        }
    }

    protected boolean isAggregationEditable(UIDL uidl, int colIndex) {
        UIDL colUidl = uidl.getChildByTagName("editableAggregationColumns");
        if (colUidl == null) {
            return false;
        }
        String colKey = tableWidget.getColKeyByIndex(colIndex);
        Iterator iterator = colUidl.getChildIterator();
        while (iterator.hasNext()) {
            Object uidlKey = iterator.next();
            if (uidlKey.equals(colKey)) {
                return true;
            }
        }
        return false;
    }

    // Extension point for GroupTable divider column
    protected boolean addSpecificCell(String columnId, int colIndex) {
        return false;
    }

    protected void addCellWithField(String text, char align, int colIndex) {
        final TableCellElement td = DOM.createTD().cast();
        final DivElement container = DOM.createDiv().cast();
        container.setClassName(tableWidget.getStylePrimaryName() + "-cell-wrapper" + " " + "widget-container");

        setAlign(align, container);

        InputElement inputElement = DOM.createInputText().cast();
        inputElement.setValue(text);
        inputElement.addClassName("v-textfield v-widget");
        inputElement.addClassName("c-total-aggregation-textfield");
        Style elemStyle = inputElement.getStyle();
        elemStyle.setWidth(100, Style.Unit.PCT);

        container.appendChild(inputElement);

        if (inputsList == null) {
            inputsList = new ArrayList<>();
        }
        inputsList.add(new AggregationInputFieldInfo(text, tableWidget.getColKeyByIndex(colIndex), inputElement));

        DOM.sinkEvents(inputElement, Event.ONCHANGE | Event.ONKEYDOWN);

        td.setClassName(tableWidget.getStylePrimaryName() + "-cell-content");
        td.addClassName(tableWidget.getStylePrimaryName() + "-aggregation-cell");
        td.appendChild(container);
        tr.appendChild(td);
    }

    protected void addCell(String text, char align, String style, boolean sorted) {
        final TableCellElement td = DOM.createTD().cast();

        final Element container = DOM.createDiv();
        container.setClassName(tableWidget.getStylePrimaryName() + "-cell-wrapper");

        td.setClassName(tableWidget.getStylePrimaryName() + "-cell-content");

        td.addClassName(tableWidget.getStylePrimaryName() + "-aggregation-cell");

        if (style != null && !style.equals("")) {
            td.addClassName(tableWidget.getStylePrimaryName() + "-cell-content-" + style);
        }

        if (sorted) {
            td.addClassName(tableWidget.getStylePrimaryName() + "-cell-content-sorted");
        }

        container.setInnerText(text);

        setAlign(align, container);

        td.appendChild(container);
        tr.appendChild(td);

        Tools.textSelectionEnable(td, tableWidget.isTextSelectionEnabled());
    }

    protected void setAlign(char align, final Element container) {
        // CAUTION: copied from VScrollTableRow
        switch (align) {
            case VScrollTable.ALIGN_CENTER:
                container.getStyle().setProperty("textAlign", "center");
                break;
            case VScrollTable.ALIGN_LEFT:
                container.getStyle().setProperty("textAlign", "left");
                break;
            case VScrollTable.ALIGN_RIGHT:
            default:
                container.getStyle().setProperty("textAlign", "right");
                break;
        }
    }

    protected AggregationInputFieldInfo getAggregationInputInfo(Element input) {
        if (inputsList == null) {
            return null;
        }

        for (AggregationInputFieldInfo info : inputsList) {
            if (info.getInputElement().isOrHasChild(input)) {
                return info;
            }
        }
        return null;
    }
}


text:
package org.teavm.debugging.information;

import java.io.DataOutput;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.teavm.common.IntegerArray;
import org.teavm.common.RecordArray;
import org.teavm.debugging.information.DebugInformation.ClassMetadata;

class DebugInformationWriter {
    private DataOutput output;
    private int lastNumber;

    public DebugInformationWriter(DataOutput output) {
        this.output = output;
    }

    public void write(DebugInformation debugInfo) throws IOException {
        writeStringArray(debugInfo.fileNames);
        writeStringArray(debugInfo.classNames);
        writeStringArray(debugInfo.fields);
        writeStringArray(debugInfo.methods);
        writeStringArray(debugInfo.variableNames);
        writeExactMethods(debugInfo.exactMethods);

        writeMapping(debugInfo.fileMapping);
        writeMapping(debugInfo.lineMapping);
        writeMapping(debugInfo.classMapping);
        writeMapping(debugInfo.methodMapping);
        writeLinesAndColumns(debugInfo.statementStartMapping);
        writeCallSiteMapping(debugInfo.callSiteMapping);
        writeVariableMappings(debugInfo);
        writeClassMetadata(debugInfo.classesMetadata);
        writeCFGs(debugInfo);
    }

    private void writeVariableMappings(DebugInformation debugInfo) throws IOException {
        int lastVar = 0;
        writeUnsignedNumber(nonNullVariableMappings(debugInfo));
        for (int i = 0; i < debugInfo.variableMappings.length; ++i) {
            RecordArray mapping = debugInfo.variableMappings[i];
            if (mapping == null) {
                continue;
            }
            writeUnsignedNumber(i - lastVar);
            lastVar = i;
            writeMultiMapping(mapping);
        }
    }

    private void writeClassMetadata(List<ClassMetadata> classes) throws IOException {
        for (int i = 0; i < classes.size(); ++i) {
            ClassMetadata cls = classes.get(i);
            writeNullableString(cls.jsName);
            writeUnsignedNumber(cls.parentId != null ? cls.parentId + 1 : 0);
            writeUnsignedNumber(cls.fieldMap.size());
            List<Integer> keys = new ArrayList<>(cls.fieldMap.keySet());
            Collections.sort(keys);
            resetRelativeNumber();
            for (int key : keys) {
                writeRelativeNumber(key);
                writeUnsignedNumber(cls.fieldMap.get(key));
            }
        }
    }

    private int nonNullVariableMappings(DebugInformation debugInfo) {
        int count = 0;
        for (int i = 0; i < debugInfo.variableMappings.length; ++i) {
            if (debugInfo.variableMappings[i] != null) {
                ++count;
            }
        }
        return count;
    }

    private void writeStringArray(String[] array) throws IOException {
        writeUnsignedNumber(array.length);
        for (int i = 0; i < array.length; ++i) {
            writeString(array[i]);
        }
    }

    private void writeExactMethods(long[] array) throws IOException {
        int lastClass = 0;
        int lastMethod = 0;
        writeUnsignedNumber(array.length);
        for (int i = 0; i < array.length; ++i) {
            long item = array[i];
            int classIndex = (int) (item >> 32);
            int methodIndex = (int) item;
            writeNumber(classIndex - lastClass);
            lastClass = classIndex;
            writeNumber(methodIndex - lastMethod);
            lastMethod = methodIndex;
        }
    }

    private void writeMultiMapping(RecordArray mapping) throws IOException {
        writeLinesAndColumns(mapping);
        for (int i = 0; i < mapping.size(); ++i) {
            int[] array = mapping.get(i).getArray(0);
            writeUnsignedNumber(array.length);
            int lastNumber = 0;
            for (int elem : array) {
                writeNumber(elem - lastNumber);
                lastNumber = elem;
            }
        }
    }

    private void writeMapping(RecordArray mapping) throws IOException {
        writeLinesAndColumns(mapping);
        writeRle(packValues(mapping));
    }

    private void writeCallSiteMapping(RecordArray mapping) throws IOException {
        writeLinesAndColumns(mapping);
        writeRle(packValues(mapping));
        writeRle(packCallSites(mapping));
    }

    private void writeLinesAndColumns(RecordArray mapping) throws IOException {
        writeUnsignedNumber(mapping.size());
        writeRle(packLines(mapping));
        writeRle(packColumns(mapping));
    }

    private int[] packLines(RecordArray mapping) {
        int[] lines = mapping.cut(0);
        int last = 0;
        for (int i = 0; i < lines.length; ++i) {
            int next = lines[i];
            lines[i] -= last;
            last = next;
        }
        return lines;
    }

    private int[] packColumns(RecordArray mapping) {
        int[] columns = mapping.cut(1);
        int lastLine = -1;
        int lastColumn = 0;
        for (int i = 0; i < columns.length; ++i) {
            if (lastLine != mapping.get(i).get(0)) {
                lastColumn = 0;
                lastLine = mapping.get(i).get(0);
            }
            int column = columns[i];
            columns[i] = column - lastColumn;
            lastColumn = column;
        }
        return columns;
    }

    private int[] packValues(RecordArray mapping) {
        int[] values = mapping.cut(2);
        int last = 0;
        for (int i = 0; i < values.length; ++i) {
            int value = values[i];
            if (value == -1) {
                values[i] = 0;
            } else {
                values[i] = 1 + convertToSigned(value - last);
                last = value;
            }
        }
        return values;
    }

    private int[] packCallSites(RecordArray mapping) {
        int[] callSites = mapping.cut(3);
        int last = 0;
        int j = 0;
        for (int i = 0; i < callSites.length; ++i) {
            int type = mapping.get(i).get(2);
            if (type != 0) {
                int callSite = callSites[i];
                callSites[j++] = convertToSigned(callSite - last);
                last = callSite;
            }
        }
        return Arrays.copyOf(callSites, j);
    }

    private void writeCFGs(DebugInformation debugInfo) throws IOException {
        for (int i = 0; i < debugInfo.controlFlowGraphs.length; ++i) {
            writeCFG(debugInfo.controlFlowGraphs[i]);
        }
    }

    private void writeCFG(RecordArray mapping) throws IOException {
        if (mapping == null) {
            writeUnsignedNumber(0);
            return;
        }
        writeUnsignedNumber(mapping.size());
        writeRle(mapping.cut(0));
        IntegerArray sizes = new IntegerArray(1);
        IntegerArray files = new IntegerArray(1);
        IntegerArray lines = new IntegerArray(1);
        int lastFile = 0;
        int lastLine = 0;
        for (int i = 0; i < mapping.size(); ++i) {
            int type = mapping.get(i).get(0);
            if (type == 0) {
                continue;
            }
            int[] data = mapping.get(i).getArray(0);
            sizes.add(data.length / 2);
            for (int j = 0; j < data.length; j += 2) {
                int file = data[j];
                int line = data[j + 1];
                files.add(convertToSigned(file - lastFile));
                lines.add(convertToSigned(line - lastLine));
                lastFile = file;
                lastLine = line;
            }
        }
        writeRle(sizes.getAll());
        writeRle(files.getAll());
        writeRle(lines.getAll());
    }

    private void writeNumber(int number) throws IOException {
        writeUnsignedNumber(convertToSigned(number));
    }

    private int convertToSigned(int number) {
        return number < 0 ? (-number << 1) | 1 : number << 1;
    }

    private void writeUnsignedNumber(int number) throws IOException {
        do {
            byte b = (byte) (number & 0x7F);
            if ((number & 0xFFFFFF80) != 0) {
                b |= 0x80;
            }
            number >>>= 7;
            output.writeByte(b);
        } while (number != 0);
    }

    private void writeRle(int[] array) throws IOException {
        int last = 0;
        for (int i = 0; i < array.length;) {
            int e = array[i];
            int count = 1;
            int current = i;
            ++i;
            while (i < array.length && array[i] == e) {
                ++count;
                ++i;
            }
            if (count > 1) {
                if (current > last) {
                    writeUnsignedNumber((current - last) << 1);
                    while (last < current) {
                        writeUnsignedNumber(array[last++]);
                    }
                }
                writeUnsignedNumber((count << 1) | 1);
                writeUnsignedNumber(e);
                last = i;
            }
        }
        if (array.length > last) {
            writeUnsignedNumber((array.length - last) << 1);
            while (last < array.length) {
                writeUnsignedNumber(array[last++]);
            }
        }
    }

    private void writeRelativeNumber(int number) throws IOException {
        writeNumber(number - lastNumber);
        lastNumber = number;
    }

    private void resetRelativeNumber() {
        lastNumber = 0;
    }

    private void writeString(String str) throws IOException {
        byte[] bytes = str.getBytes(StandardCharsets.UTF_8);
        writeUnsignedNumber(bytes.length);
        output.write(bytes);
    }

    private void writeNullableString(String str) throws IOException {
        if (str == null) {
            writeUnsignedNumber(0);
            return;
        }
        byte[] bytes = str.getBytes(StandardCharsets.UTF_8);
        writeUnsignedNumber(bytes.length + 1);
        output.write(bytes);
    }
}