text:
<?php

namespace MenUSACH\Bundle\BaseBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use MenUSACH\Bundle\BaseBundle\Entity\TipoPago;
use MenUSACH\Bundle\BaseBundle\Form\TipoPagoType;

/**
 * TipoPago controller.
 *
 * @Route("/")
 */
class TipoPagoController extends Controller
{
    /**
     * Lists all TipoPago entities.
     *
     * @Route("admin/tipopago", name="tipopago")
     * @Template()
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getManager();

        $entities = $em->getRepository('MenUSACHBaseBundle:TipoPago')->findAll();

        return array(
            'entities' => $entities,
        );
    }

    /**
     * Finds and displays a TipoPago entity.
     *
     * @Route("admin/tipopago/{id}/show", name="tipopago_show")
     * @Template()
     */
    public function showAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('MenUSACHBaseBundle:TipoPago')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find TipoPago entity.');
        }

        $deleteForm = $this->createDeleteForm($id);

        return array(
            'entity'      => $entity,
            'delete_form' => $deleteForm->createView(),
        );
    }

    /**
     * Displays a form to create a new TipoPago entity.
     *
     * @Route("admin/tipopago/new", name="tipopago_new")
     * @Template()
     */
    public function newAction()
    {
        $entity = new TipoPago();
        $form   = $this->createForm(new TipoPagoType(), $entity);

        return array(
            'entity' => $entity,
            'form'   => $form->createView(),
        );
    }

    /**
     * Creates a new TipoPago entity.
     *
     * @Route("admin/tipopago/create", name="tipopago_create")
     * @Method("POST")
     * @Template("MenUSACHBaseBundle:TipoPago:new.html.twig")
     */
    public function createAction(Request $request)
    {
        $entity  = new TipoPago();
        $form = $this->createForm(new TipoPagoType(), $entity);
        $form->bind($request);

//        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('tipopago'));
 //       }

        return array(
            'entity' => $entity,
            'form'   => $form->createView(),
        );
    }

    /**
     * Displays a form to edit an existing TipoPago entity.
     *
     * @Route("admin/tipopago/{id}/edit", name="tipopago_edit")
     * @Template()
     */
    public function editAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('MenUSACHBaseBundle:TipoPago')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find TipoPago entity.');
        }

        $editForm = $this->createForm(new TipoPagoType(), $entity);
        $deleteForm = $this->createDeleteForm($id);

        return array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        );
    }

    /**
     * Edits an existing TipoPago entity.
     *
     * @Route("admin/tipopago/{id}/update", name="tipopago_update")
     * @Method("POST")
     * @Template("MenUSACHBaseBundle:TipoPago:edit.html.twig")
     */
    public function updateAction(Request $request, $id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('MenUSACHBaseBundle:TipoPago')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find TipoPago entity.');
        }

        $deleteForm = $this->createDeleteForm($id);
        $editForm = $this->createForm(new TipoPagoType(), $entity);
        $editForm->bind($request);

    //    if ($editForm->isValid()) {
            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('tipopago'));
     //   }

        return array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        );
    }

    /**
     * Deletes a TipoPago entity.
     *
     * @Route("admin/tipopago/{id}/delete", name="tipopago_delete")
     * @Method("GET")
     */
    public function deleteAction(Request $request, $id)
    {
        $form = $this->createDeleteForm($id);
        $form->bind($request);

//        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $entity = $em->getRepository('MenUSACHBaseBundle:TipoPago')->find($id);

            if (!$entity) {
                throw $this->createNotFoundException('Unable to find TipoPago entity.');
            }

            $em->remove($entity);
            $em->flush();
 //       }

        return $this->redirect($this->generateUrl('tipopago'));
    }

    private function createDeleteForm($id)
    {
        return $this->createFormBuilder(array('id' => $id))
            ->add('id', 'hidden')
            ->getForm()
        ;
    }
}


text:
import React from 'react';
import { shallow } from 'enzyme';

import Informations from './../../components/Informations';

describe('<Informations />', () => {
  const state = { restaurant: { id: 1, location: { lat: 0, lng: 0 } } };

  it('should renders a div if a restaurant is present', () => {
    const wrapper = shallow(<Informations {...state} />);
    expect(wrapper.find('header.restaurant-header').length).toBeGreaterThan(0);
  });

  it('should renders a rating container if the restaurant has ratings', () => {
    const withRating = { ...state, ...{ restaurant: { rating: 5 } } };
    const wrapper = shallow(<Informations {...withRating} />);
    expect(wrapper.find('div.rating-block').length).toBeGreaterThan(0);
  });

  it('should renders a loading button if location is pending', () => {
    const withLoading = { ...state, ...{ radius: 800, retrievingLocation: true } };
    const wrapper = shallow(<Informations {...withLoading} />);
    expect(
      wrapper
        .find('div.actions .btn')
        .first()
        .props().className
    ).toEqual('btn btn-loading go');
  });

  it('should renders a reduce radius button if radius is not too low', () => {
    const withRadius = { ...state, ...{ radius: 800 } };
    process.env.REACT_APP_MINIMUM_RADIUS = 600;
    const wrapper = shallow(<Informations {...withRadius} />);
    expect(wrapper.find('button.reduce-radius').length).toBeGreaterThan(0);
  });
});

redpajama_set_name: RedPajamaGithub


text:
echo 'Installing Cloudera repositories...'

curl -s http://archive.cloudera.com/cdh5/ubuntu/trusty/amd64/cdh/archive.key | apt-key add -

echo 'deb [arch=amd64] http://archive.cloudera.com/cdh5/ubuntu/trusty/amd64/cdh trusty-cdh5 contrib' > /etc/apt/sources.list.d/cloudera.list
echo 'deb-src http://archive.cloudera.com/cdh5/ubuntu/trusty/amd64/cdh trusty-cdh5 contrib' >> /etc/apt/sources.list.d/cloudera.list

echo 'Cloudera repositories Installed.'


text:
package mesosphere.mesos.simulation

import java.util
import java.util.Collections

import akka.actor.{ActorRef, ActorSystem, Props}
import com.typesafe.config.{Config, ConfigFactory}
import com.typesafe.scalalogging.StrictLogging
import mesosphere.marathon.stream.Implicits._
import org.apache.mesos.Protos._
import org.apache.mesos.SchedulerDriver

import scala.concurrent.Await
import scala.concurrent.duration.Duration

/**
  * The facade to the mesos simulation.
  *
  * It starts/stops a new actor system for the simulation when the corresponding life-cycle methods of the
  * [[org.apache.mesos.SchedulerDriver]] interface are called.
  *
  * The implemented commands of the driver interface are forwarded as messages to the
  * [[mesosphere.mesos.simulation.DriverActor]].
  * Unimplemented methods throw [[scala.NotImplementedError]]s.
  */
class SimulatedDriver(driverProps: Props) extends SchedulerDriver with StrictLogging {

  private[this] def driverCmd(cmd: AnyRef): Status = {
    driverActorRefOpt match {
      case Some(driverActor) =>
        logger.debug(s"send driver cmd $cmd")
        driverActor ! cmd
      case None =>
        logger.debug("no driver actor configured")
    }
    status
  }

  override def declineOffer(offerId: OfferID): Status =
    driverCmd(DriverActor.DeclineOffer(offerId))

  override def launchTasks(offerIds: util.Collection[OfferID], tasks: util.Collection[TaskInfo]): Status =
    driverCmd(DriverActor.LaunchTasks(offerIds.toSeq, tasks.toSeq))

  // Mesos 0.23.x
  override def acceptOffers(
    offerIds: util.Collection[OfferID], ops: util.Collection[Offer.Operation], filters: Filters): Status =
    driverCmd(DriverActor.AcceptOffers(offerIds.toSeq, ops.toSeq, filters))

  override def killTask(taskId: TaskID): Status = driverCmd(DriverActor.KillTask(taskId))
  override def reconcileTasks(statuses: util.Collection[TaskStatus]): Status = {
    driverCmd(DriverActor.ReconcileTask(statuses.toSeq))
  }

  override def suppressOffers(): Status = driverCmd(DriverActor.SuppressOffers)

  override def reviveOffers(): Status = driverCmd(DriverActor.ReviveOffers)

  override def declineOffer(offerId: OfferID, filters: Filters): Status = Status.DRIVER_RUNNING

  override def launchTasks(offerIds: util.Collection[OfferID], tasks: util.Collection[TaskInfo],
    filters: Filters): Status = launchTasks(offerIds, tasks)
  override def launchTasks(offerId: OfferID, tasks: util.Collection[TaskInfo], filters: Filters): Status =
    launchTasks(Collections.singleton(offerId), tasks)
  override def launchTasks(offerId: OfferID, tasks: util.Collection[TaskInfo]): Status =
    launchTasks(Collections.singleton(offerId), tasks)
  override def requestResources(requests: util.Collection[Request]): Status = ???
  override def sendFrameworkMessage(executorId: ExecutorID, slaveId: SlaveID, data: Array[Byte]): Status = ???
  override def acknowledgeStatusUpdate(ackStatus: TaskStatus): Status = status

  // life cycle

  @volatile
  var system: Option[ActorSystem] = None
  @volatile
  var driverActorRefOpt: Option[ActorRef] = None

  private def status: Status = system match {
    case None => Status.DRIVER_STOPPED
    case Some(_) => Status.DRIVER_RUNNING
  }

  override def start(): Status = {
    logger.info("Starting simulated Mesos")
    val config: Config = ConfigFactory.load(getClass.getClassLoader, "mesos-simulation.conf")
    val sys: ActorSystem = ActorSystem("mesos-simulation", config)
    system = Some(sys)
    driverActorRefOpt = Some(sys.actorOf(driverProps, "driver"))
    driverCmd(this)

    Status.DRIVER_RUNNING
  }

  override def stop(failover: Boolean): Status = stop()
  override def stop(): Status = abort()
  override def abort(): Status = {
    system match {
      case None => Status.DRIVER_NOT_STARTED
      case Some(sys) =>
        sys.terminate()
        Status.DRIVER_ABORTED
    }
  }

  override def run(): Status = {
    start()
    join()
  }

  override def join(): Status = {
    system match {
      case None => Status.DRIVER_NOT_STARTED
      case Some(sys) =>
        Await.result(sys.whenTerminated, Duration.Inf)
        driverActorRefOpt = None
        system = None
        logger.info("Stopped simulated Mesos")
        Status.DRIVER_STOPPED
    }
  }
}


text:
<?php

session_start();
if(isset($_SESSION['nombre']))
{
	$id = $_GET['idausencia'];
	$mysqli = new mysqli("localhost", "root", "", "reloj");
	$sql = $mysqli->query("delete from ausencia where idausencia='$id'");
	echo "<script> alert('Desactivado Con Exito'); </script>";
	echo"<META HTTP-EQUIV='Refresh' CONTENT='0; URL=../Ausencias.php'>";
}
else
	{
			echo "<script language='javascript'> alert('No Tiene Permisos'); </script>";
			echo "<META HTTP-EQUIV='Refresh' CONTENT='0; URL=../Ausencias.php'>";
	}

?>


text:
//
// Path.hpp
//
// 20 May 2004 -- tds
//

#ifndef INDRI_PATH_HPP
#define INDRI_PATH_HPP

#include <string>
namespace indri
{
  namespace file
  {

    class Path {
    public:
      static void create( const std::string& path );
      static bool isFile( const std::string& path );
      static bool isDirectory( const std::string& path );
      static bool exists( const std::string& path );
      static void remove( const std::string& path );
      static void rename( const std::string& oldPath, const std::string& newPath );
      static void make( const std::string& path );

      static std::string trim( const std::string& path );
      static std::string relative( const std::string& basePath, const std::string absolutePath );

      static char pathSeparator();

      static std::string combine( const std::string& root, const std::string& addition );
      static std::string extension( const std::string& path );
      static std::string directory( const std::string& path );
      static std::string filename( const std::string& path );
      static std::string basename( const std::string& path );
    };
  }
}

#endif // INDRI_PATH_HPP


text:
package com.scintuitive.routinetimer;

import javax.crypto.spec.PSource;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

public class StepAdapter extends ArrayAdapter<Step>{

	private Context context;
	private int layoutResourceId;
	private Step[] data;
	private boolean isInRunningMode;

	class StepRecordHolder{
		ImageView logo;
		TextView name;
		ProgressBar completeMeter;
		TextView duration;
	}

	public StepAdapter(Context context, int layoutResourceId,Step[] data){
		super(context,layoutResourceId,data);
		this.context = context;
		this.layoutResourceId = layoutResourceId;
		this.data = data;
		this.isInRunningMode = false;
	}

	@Override
	public View getView(int position,View convertView,ViewGroup parent){
		View row = convertView;
		StepRecordHolder holder = null;
		if (row == null){
			 LayoutInflater inflater =  ((Activity)this.context).getLayoutInflater();
			 row = inflater.inflate(this.layoutResourceId ,parent,false);
			 holder = new StepRecordHolder();
			 holder.name = (TextView)row.findViewById(R.id.txtStepName);
			 holder.duration = (TextView)row.findViewById(R.id.txtStepDuration);
			 holder.logo = (ImageView)row.findViewById(R.id.ivwStepLogo);
			 holder.completeMeter = (ProgressBar)row.findViewById(R.id.prgComplete);
			 row.setTag(holder);
		}else{
			holder = (StepRecordHolder)row.getTag();
		}

		Log.i(ManageRoutines.TAG, "There are " + data.length + " setps in the list");
		Log.i(ManageRoutines.TAG, "was asked for step at position " + position);
		Step step = this.data[position];

		if(step.getRemainingDuartionSeconds() <= 0 && isInRunningMode){
			holder.logo.setImageResource(R.drawable.step_run_icon);
			holder.name.setTextColor(Color.parseColor("#cccccc"));
			holder.duration.setTextColor(Color.parseColor("#cccccc"));
		}else if (step.isExecuting()){
			holder.logo.setImageResource(R.drawable.step_not_run_icon);
			holder.name.setTextColor(Color.parseColor("#ff4d09"));
			holder.duration.setTextColor(Color.parseColor("#ff4d09"));
		}else{
			holder.logo.setImageResource(R.drawable.step_queued_icon);
			holder.name.setTextColor(Color.parseColor("#eeddaa"));
			holder.duration.setTextColor(Color.parseColor("#eeddaa"));
		}

		holder.name.setText(step.getName());
		if (!isInRunningMode){
			holder.duration.setText(RoutineTimerApplication.formatDuration(step.getDurationSeconds()));
			if (holder.completeMeter != null) {
			   holder.completeMeter.setProgress(0);
			}
		}else{
			long total = step.getDurationSeconds();
			long remaining = step.getRemainingDuartionSeconds();
			long spent = total - remaining;

			int pComplete =(int) (Math.round((spent/(double)total)* 100));
			Log.i("ROUTINE MINDER","Task is : " + pComplete + "% total = " + total + " remaining = " + remaining);
		    holder.duration.setText(RoutineTimerApplication.formatDuration(step.getRemainingDuartionSeconds()));
		    if (holder.completeMeter != null) {
		    	holder.completeMeter.setProgress(pComplete);
		    }
		}

		return row;
	}

	public void setRunningMode(boolean value){
		this.isInRunningMode = value;
	}

	public boolean getRunningMode(){
		return this.isInRunningMode;
	}

	public void toggelItem(int position){
		Step step = data[position];
		step.setExecuting(!step.isExecuting());
		data[position] = step;
		this.notifyDataSetChanged();
	}

	public void resetSteps() {
		if(this.isEmpty()) return;
		int count = this.getCount();
		for(int i= 0 ; i < count ; i ++) {
			Step nextStep = this.getItem(i);
			nextStep.setExecuting(false);
			nextStep.setRemainingDuartionSeconds(nextStep.getDurationSeconds());
		}
		this.notifyDataSetChanged();

	}

}


text:
package utils;

public class TestBean {

    private String Afield;

    private String BFiled;

    public String getAfield() {
        return Afield;
    }

    public void setAfield(String afield) {
        Afield = afield;
    }

    public String getBFiled() {
        return BFiled;
    }

    public void setBFiled(String BFiled) {
        this.BFiled = BFiled;
    }
}


text:
<title>Differential Amplifier</title>
<link rel="SHORTCUT ICON" href="favicon.ico">

<applet code=Circuit.class archive=circuit.jar width=640 height=450>
Sorry, you need a Java-enabled browser to see the simulation.
<param name=pause value=20>
<param name=startCircuit value="amp-diff.txt">
<param name=startLabel   value="Differential Amplifier">
<param name=useFrame     value="false">
</applet>

This circuit outputs the difference in voltage between two input
signals.  In this case, the first input is a 60 Hz signal, and the
second input is a 60 Hz signal with 120 Hz square wave added in.  (In
this simulation, the two signals are added simply by connecting the two
sources in series, which is convenient but not realistic.)

The second input signal is
driving two resistors, which act as a voltage divider, and the + input
of the op-amp is connected between them, where the voltage is equal to
half the second input signal.  The op-amp
attempts to keep its – input at the same voltage as the + input.  The two
resistors on top act as a voltage divider, making the – input
halfway between the first input signal and the op-amp output.

If V+ = 1/2 In2 = V– = 1/2
(In1 + output), then the output = In2 -
In1, or the difference between the two inputs.

Next: Summing Amplifier

Previous: Follower

Index

java@falstad.com

Generated Thu May 30 2013


text:
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function

import sys
from time import sleep

from proton.handlers import MessagingHandler
from proton.reactor import Container
from proton.reactor import LinkOption
from proton import Connection
from proton import Link
from proton import Message
from proton import Delivery
from qpid_dispatch.management.client import Node
from system_test import AsyncTestSender
from system_test import AsyncTestReceiver
from system_test import TestCase
from system_test import Qdrouterd
from system_test import main_module
from system_test import TIMEOUT
from system_test import TestTimeout
from system_test import unittest

MAX_FRAME=1023
LINK_CAPACITY=250
W_THREADS=2
LARGE_PAYLOAD = ("X" * MAX_FRAME) * 19

# check for leaks of the following entities
ALLOC_STATS=["qd_message_t",
             "qd_buffer_t",
             "qdr_delivery_t"]

class MulticastLinearTest(TestCase):
    """
    Verify the multicast forwarding logic across a multihop linear router
    configuration
    """
    @classmethod
    def setUpClass(cls):
        """Start a router"""
        super(MulticastLinearTest, cls).setUpClass()

        def router(name, mode, extra):
            config = [
                ('router', {'mode': mode,
                            'id': name,
                            'allowUnsettledMulticast': 'yes',
                            'workerThreads': W_THREADS}),
                ('listener', {'role': 'normal',
                              'port': cls.tester.get_port(),
                              'maxFrameSize': MAX_FRAME,
                              'linkCapacity': LINK_CAPACITY}),
                ('address', {'prefix': 'multicast', 'distribution': 'multicast'}),
            ]

            if extra:
                config.extend(extra)
            config = Qdrouterd.Config(config)
            cls.routers.append(cls.tester.qdrouterd(name, config, wait=True))
            return cls.routers[-1]

        # configuration:
        # two edge routers connected via 2 interior routers.
        #
        #  +-------+    +---------+    +---------+    +-------+
        #  |  EA1  |<==>|  INT.A  |<==>|  INT.B  |<==>|  EB1  |
        #  +-------+    +---------+    +---------+    +-------+
        #
        # Each router has 2 multicast consumers
        # EA1 and INT.A each have a multicast sender

        cls.routers = []

        interrouter_port = cls.tester.get_port()
        cls.INTA_edge_port   = cls.tester.get_port()
        cls.INTB_edge_port   = cls.tester.get_port()

        router('INT.A', 'interior',
               [('listener', {'role': 'inter-router',
                              'port': interrouter_port}),
                ('listener', {'role': 'edge', 'port': cls.INTA_edge_port})])
        cls.INT_A = cls.routers[0]
        cls.INT_A.listener = cls.INT_A.addresses[0]

        router('INT.B', 'interior',
               [('connector', {'name': 'connectorToA',
                               'role': 'inter-router',
                               'port': interrouter_port}),
                ('listener', {'role': 'edge',
                              'port': cls.INTB_edge_port})])

        cls.INT_B = cls.routers[1]
        cls.INT_B.listener = cls.INT_B.addresses[0]

        router('EA1', 'edge',
               [('listener', {'name': 'rc', 'role': 'route-container',
                              'port': cls.tester.get_port()}),
                ('connector', {'name': 'uplink', 'role': 'edge',
                               'port': cls.INTA_edge_port}),
                ('linkRoute', {'prefix': 'CfgLinkRoute1', 'containerId': 'FakeBroker', 'direction': 'in'}),
                ('linkRoute', {'prefix': 'CfgLinkRoute1', 'containerId': 'FakeBroker', 'direction': 'out'})])
        cls.EA1 = cls.routers[2]
        cls.EA1.listener = cls.EA1.addresses[0]
        cls.EA1.route_container = cls.EA1.addresses[1]

        router('EB1', 'edge',
               [('connector', {'name': 'uplink',
                               'role': 'edge',
                               'port': cls.INTB_edge_port,
                               'maxFrameSize': 1024}),
                ('listener', {'name': 'rc', 'role': 'route-container',
                              'port': cls.tester.get_port()}),
                ('linkRoute', {'pattern': '*.cfg.pattern.#', 'containerId': 'FakeBroker', 'direction': 'in'}),
                ('linkRoute', {'pattern': '*.cfg.pattern.#', 'containerId': 'FakeBroker', 'direction': 'out'})])
        cls.EB1 = cls.routers[3]
        cls.EB1.listener = cls.EB1.addresses[0]
        cls.EB1.route_container = cls.EB1.addresses[1]

        cls.INT_A.wait_router_connected('INT.B')
        cls.INT_B.wait_router_connected('INT.A')
        cls.EA1.wait_connectors()
        cls.EB1.wait_connectors()

        # Client topology:
        # all routes have 2 receivers
        # Edge router EA1 and interior INT_A have a sender each
        #
        cls.config = [
            # edge router EA1:
            {'router':      cls.EA1,
             'senders':     ['S-EA1-1'],
             'receivers':   ['R-EA1-1', 'R-EA1-2'],
             'subscribers': 2,
             'remotes':     0
            },
            # Interior router INT_A:
            {'router':      cls.INT_A,
             'senders':     ['S-INT_A-1'],
             'receivers':   ['R-INT_A-1', 'R-INT_A-2'],
             'subscribers': 3,
             'remotes':     1,
            },
            # Interior router INT_B:
            {'router':      cls.INT_B,
             'senders':     [],
             'receivers':   ['R-INT_B-1', 'R-INT_B-2'],
             'subscribers': 3,
             'remotes':     1,
            },
            # edge router EB1
            {'router':      cls.EB1,
             'senders':     [],
             'receivers':   ['R-EB1-1', 'R-EB1-2'],
             'subscribers': 2,
             'remotes':     0,
            }
        ]

    def _get_alloc_stats(self, router, stats):
        # return a map of the current allocator counters for each entity type
        # name in stats

        #
        # 57: END = [{u'heldByThreads': int32(384), u'typeSize': int32(536),
        # u'transferBatchSize': int32(64), u'globalFreeListMax': int32(0),
        # u'batchesRebalancedToGlobal': int32(774), u'typeName':
        # u'qd_buffer_t', u'batchesRebalancedToThreads': int32(736),
        # u'totalFreeToHeap': int32(0), u'totalAllocFromHeap': int32(2816),
        # u'localFreeListMax': int32(128), u'type':
        # u'org.apache.qpid.dispatch.allocator', u'identity':
        # u'allocator/qd_buffer_t', u'name': u'allocator/qd_buffer_t'}]

        d = dict()
        mgmt = router.management
        atype = 'org.apache.qpid.dispatch.allocator'
        q = mgmt.query(type=atype).get_dicts()
        for name in stats:
            d[name] = list(filter(lambda a: a['typeName'] == name, q))[0]
        return d

    def _check_for_leaks(self):
        for r in self.routers:
            stats = self._get_alloc_stats(r, ALLOC_STATS)
            for name in ALLOC_STATS:
                # ensure threads haven't leaked
                max_allowed  = ((W_THREADS + 1)
                                * stats[name]['localFreeListMax'])
                held = stats[name]['heldByThreads']
                if held >= (2 * max_allowed):
                    print("OOPS!!! %s: (%s) - held=%d max=%d\n   %s\n"
                          % (r.config.router_id,
                             name, held, max_allowed, stats))
                    sys.stdout.flush()
                    self.assertFalse(held >= (2 * max_allowed))

    #
    # run all the negative tests first so that if we screw up the internal
    # state of the brokers the positive tests will likely fail
    #

    def _presettled_large_msg_rx_detach(self, config, count, drop_clients):
        # detach receivers during receive
        body = " MCAST PRESETTLED LARGE RX DETACH " + LARGE_PAYLOAD
        test = MulticastPresettledRxFail(config, count,
                                         drop_clients,
                                         detach=True,
                                         body=body)
        test.run()
        self.assertEqual(None, test.error)

    def test_01_presettled_large_msg_rx_detach(self):
        self._presettled_large_msg_rx_detach(self.config, 10, ['R-EA1-1', 'R-EB1-2'])
        self._presettled_large_msg_rx_detach(self.config, 10, ['R-INT_A-2', 'R-INT_B-1'])

    def _presettled_large_msg_rx_close(self, config, count, drop_clients):
        # close receiver connections during receive
        body = " MCAST PRESETTLED LARGE RX CLOSE " + LARGE_PAYLOAD
        test = MulticastPresettledRxFail(config, count,
                                         drop_clients,
                                         detach=False,
                                         body=body)
        test.run()
        self.assertEqual(None, test.error)

    def test_02_presettled_large_msg_rx_close(self):
        self._presettled_large_msg_rx_close(self.config, 10, ['R-EA1-2', 'R-EB1-1'])
        self._presettled_large_msg_rx_close(self.config, 10, ['R-INT_A-1', 'R-INT_B-2'])

    def _unsettled_large_msg_rx_detach(self, config, count, drop_clients):
        # detach receivers during the test
        body = " MCAST UNSETTLED LARGE RX DETACH " + LARGE_PAYLOAD
        test = MulticastUnsettledRxFail(self.config, count, drop_clients, detach=True, body=body)
        test.run()
        self.assertEqual(None, test.error)

    def test_10_unsettled_large_msg_rx_detach(self):
        self._unsettled_large_msg_rx_detach(self.config, 10, ['R-EA1-1', 'R-EB1-2'])
        self._unsettled_large_msg_rx_detach(self.config, 10, ['R-INT_A-2', 'R-INT_B-1'])

    def _unsettled_large_msg_rx_close(self, config, count, drop_clients):
        # close receiver connections during test
        body = " MCAST UNSETTLED LARGE RX CLOSE " + LARGE_PAYLOAD
        test = MulticastUnsettledRxFail(self.config, count, drop_clients, detach=False, body=body)
        test.run()
        self.assertEqual(None, test.error)

    def test_11_unsettled_large_msg_rx_close(self):
        self._unsettled_large_msg_rx_close(self.config, 10, ['R-EA1-2', 'R-EB1-1', ])
        self._unsettled_large_msg_rx_close(self.config, 10, ['R-INT_A-1', 'R-INT_B-2'])

    #
    # now the positive tests
    #

    def test_50_presettled(self):
        # Simply send a bunch of pre-settled multicast messages
        body = " MCAST PRESETTLED "
        test = MulticastPresettled(self.config, 10, body, SendPresettled())
        test.run()

    def test_51_presettled_mixed_large_msg(self):
        # Same as above, but large message bodies (mixed sender settle mode)
        body = " MCAST MAYBE PRESETTLED LARGE " + LARGE_PAYLOAD
        test = MulticastPresettled(self.config, 11, body, SendMixed())
        test.run()
        self.assertEqual(None, test.error)

    def test_52_presettled_large_msg(self):
        # Same as above, (pre-settled sender settle mode)
        body = " MCAST PRESETTLED LARGE " + LARGE_PAYLOAD
        test = MulticastPresettled(self.config, 13, body, SendPresettled())
        test.run()
        self.assertEqual(None, test.error)

    def test_60_unsettled_3ack(self):
        # Sender sends unsettled, waits for Outcome from Receiver then settles
        # Expect all messages to be accepted
        body = " MCAST UNSETTLED "
        test = MulticastUnsettled3Ack(self.config, 10, body)
        test.run()
        self.assertEqual(None, test.error)
        self.assertEqual(test.n_outcomes[Delivery.ACCEPTED], test.n_sent)

    def test_61_unsettled_3ack_large_msg(self):
        # Same as above but with multiframe streaming
        body = " MCAST UNSETTLED LARGE " + LARGE_PAYLOAD
        test = MulticastUnsettled3Ack(self.config, 11, body=body)
        test.run()
        self.assertEqual(None, test.error)
        self.assertEqual(test.n_outcomes[Delivery.ACCEPTED], test.n_sent)

    def _unsettled_3ack_outcomes(self,
                                 config,
                                 count,
                                 outcomes,
                                 expected):
        body = " MCAST UNSETTLED 3ACK OUTCOMES " + LARGE_PAYLOAD
        test = MulticastUnsettled3Ack(self.config,
                                      count,
                                      body,
                                      outcomes=outcomes)
        test.run()
        self.assertEqual(None, test.error)
        self.assertEqual(test.n_outcomes[expected], test.n_sent)

    def test_63_unsettled_3ack_outcomes(self):
        # Verify the expected outcome is returned to the sender when the
        # receivers return different outcome values.  If no outcome is
        # specified for a receiver it will default to ACCEPTED

        # expect REJECTED if any reject:
        self._unsettled_3ack_outcomes(self.config, 3,
                                      {'R-EB1-1': Delivery.REJECTED,
                                       'R-EB1-2': Delivery.MODIFIED,
                                       'R-INT_B-2': Delivery.RELEASED},
                                      Delivery.REJECTED)
        self._unsettled_3ack_outcomes(self.config, 3,
                                      {'R-EB1-1': Delivery.REJECTED,
                                       'R-INT_B-2': Delivery.RELEASED},
                                      Delivery.REJECTED)
        # expect ACCEPT if no rejects
        self._unsettled_3ack_outcomes(self.config, 3,
                                      {'R-EB1-2': Delivery.MODIFIED,
                                       'R-INT_B-2': Delivery.RELEASED},
                                      Delivery.ACCEPTED)
        # expect MODIFIED over RELEASED
        self._unsettled_3ack_outcomes(self.config, 3,
                                      {'R-EA1-1': Delivery.RELEASED,
                                       'R-EA1-2': Delivery.RELEASED,
                                       'R-INT_A-1': Delivery.RELEASED,
                                       'R-INT_A-2': Delivery.RELEASED,
                                       'R-INT_B-1': Delivery.RELEASED,
                                       'R-INT_B-2': Delivery.RELEASED,
                                       'R-EB1-1': Delivery.RELEASED,
                                       'R-EB1-2': Delivery.MODIFIED},
                                      Delivery.MODIFIED)

        # and released only if all released
        self._unsettled_3ack_outcomes(self.config, 3,
                                      {'R-EA1-1': Delivery.RELEASED,
                                       'R-EA1-2': Delivery.RELEASED,
                                       'R-INT_A-1': Delivery.RELEASED,
                                       'R-INT_A-2': Delivery.RELEASED,
                                       'R-INT_B-1': Delivery.RELEASED,
                                       'R-INT_B-2': Delivery.RELEASED,
                                       'R-EB1-1': Delivery.RELEASED,
                                       'R-EB1-2': Delivery.RELEASED},
                                      Delivery.RELEASED)

    def test_70_unsettled_1ack(self):
        # Sender sends unsettled, expects both outcome and settlement from
        # receiver before sender settles locally
        body = " MCAST UNSETTLED 1ACK "
        test = MulticastUnsettled1Ack(self.config, 10, body)
        test.run()
        self.assertEqual(None, test.error)

    def test_71_unsettled_1ack_large_msg(self):
        # Same as above but with multiframe streaming
        body = " MCAST UNSETTLED 1ACK LARGE " + LARGE_PAYLOAD
        test = MulticastUnsettled1Ack(self.config, 10, body)
        test.run()
        self.assertEqual(None, test.error)

    def test_80_unsettled_3ack_message_annotations(self):
        body = " MCAST UNSETTLED 3ACK LARGE MESSAGE ANNOTATIONS " + LARGE_PAYLOAD
        test = MulticastUnsettled3AckMA(self.config, 10, body)
        test.run()
        self.assertEqual(None, test.error)

    def test_90_credit_no_subscribers(self):
        """
        Verify that multicast senders are blocked until a consumer is present.
        """
        test = MulticastCreditBlocked(address=self.EA1.listener,
                                      target='multicast/no/subscriber1')

        test.run()
        self.assertEqual(None, test.error)

        test = MulticastCreditBlocked(address=self.INT_A.listener,
                                      target='multicast/no/subscriber2')
        test.run()
        self.assertEqual(None, test.error)

    def test_91_anonymous_sender(self):
        """
        Verify that senders over anonymous links do not block waiting for
        consumers.
        """

        # no receiver - should not block, return RELEASED
        msg = Message(body="test_100_anonymous_sender")
        msg.address = "multicast/test_100_anonymous_sender"
        tx = AsyncTestSender(address=self.INT_B.listener,
                             count=5,
                             target=None,
                             message=msg,
                             container_id="test_100_anonymous_sender")
        tx.wait()
        self.assertEqual(5, tx.released)

        # now add a receiver:
        rx = AsyncTestReceiver(address=self.INT_A.listener,
                               source=msg.address)
        self.INT_B.wait_address(msg.address)
        tx = AsyncTestSender(address=self.INT_B.listener,
                             count=5,
                             target=None,
                             message=msg,
                             container_id="test_100_anonymous_sender")
        tx.wait()
        self.assertEqual(5, tx.accepted)
        rx.stop()

    def test_999_check_for_leaks(self):
        self._check_for_leaks()

#
# Settlement options for Link attach
#

class SendPresettled(LinkOption):
    """
    All messages are sent presettled
    """
    def apply(self, link):
        link.snd_settle_mode = Link.SND_SETTLED
        link.rcv_settle_mode = Link.RCV_FIRST

class SendMixed(LinkOption):
    """
    Messages may be sent unsettled or settled
    """
    def apply(self, link):
        link.snd_settle_mode = Link.SND_MIXED
        link.rcv_settle_mode = Link.RCV_FIRST

class Link1Ack(LinkOption):
    """
    Messages will be sent unsettled
    """
    def apply(self, link):
        link.snd_settle_mode = Link.SND_UNSETTLED
        link.rcv_settle_mode = Link.RCV_FIRST

class Link3Ack(LinkOption):
    """
    Messages will be sent unsettled and the receiver will wait for sender to
    settle first.
    """
    def apply(self, link):
        link.snd_settle_mode = Link.SND_UNSETTLED
        link.rcv_settle_mode = Link.RCV_SECOND

class MulticastBase(MessagingHandler):
    """
    Common multicast boilerplate code
    """
    def __init__(self, config, count, body, topic=None, **handler_kwargs):
        super(MulticastBase, self).__init__(**handler_kwargs)
        self.msg_count = count
        self.config = config
        self.topic = topic or "multicast/test"
        self.body = body

        # totals
        self.n_senders = 0;
        self.n_receivers = 0;
        self.n_sent = 0
        self.n_received = 0
        self.n_settled = 0
        self.n_accepted = 0
        self.n_released = 0
        self.n_rejected = 0
        self.n_modified = 0
        self.n_partial = 0

        # all maps indexed by client name:
        self.receivers = {}
        self.senders = {}
        self.r_conns = {}
        self.s_conns = {}

        # per receiver
        self.c_received = {}

        # count per outcome
        self.n_outcomes = {}

        self.error = None
        self.timers = []
        self.reactor = None

    def done(self):
        # stop the reactor and clean up the test
        for t in self.timers:
            t.cancel()
        for c_dict in [self.r_conns, self.s_conns]:
            for conn in c_dict.values():
                conn.close()
        self.r_conns = {}
        self.s_conns = {}

    def timeout(self):
        self.error = "Timeout Expired"
        self.done()

    def create_receiver(self, container, conn, source, name):
        # must override in subclass
        assert(False)

    def create_sender(self, container, conn, target, name):
        # must override in subclass
        assert(False)

    def on_start(self, event):
        self.reactor = event.reactor
        self.timers.append(self.reactor.schedule(TIMEOUT, TestTimeout(self)))
        # first create all the receivers first
        for cfg in self.config:
            for name in cfg['receivers']:
                conn = event.container.connect(cfg['router'].listener)
                assert(name not in self.r_conns)
                self.r_conns[name] = conn
                self.create_receiver(event.container, conn, self.topic, name)
                self.n_receivers += 1
                self.c_received[name] = 0

    def on_link_opened(self, event):
        if event.receiver:
            r_name = event.receiver.name
            self.receivers[r_name] = event.receiver
            # create senders after all receivers are opened
            # makes it easy to check when the clients are ready
            if len(self.receivers) == self.n_receivers:
                for cfg in self.config:
                    for name in cfg['senders']:
                        conn = event.container.connect(cfg['router'].listener)
                        assert(name not in self.s_conns)
                        self.s_conns[name] = conn
                        self.create_sender(event.container, conn, self.topic, name)
                        self.n_senders += 1

    def on_sendable(self, event):
        s_name = event.sender.name
        if s_name not in self.senders:
            self.senders[s_name] = event.sender
            if len(self.senders) == self.n_senders:
                # all senders ready to send, now wait until the routes settle
                for cfg in self.config:
                    cfg['router'].wait_address(self.topic,
                                               subscribers=cfg['subscribers'],
                                               remotes=cfg['remotes'])
                for sender in self.senders.values():
                    self.do_send(sender)

    def on_message(self, event):
        if event.delivery.partial:
            self.n_partial += 1
        else:
            dlv = event.delivery
            self.n_received += 1
            name = event.link.name
            self.c_received[name] = 1 + self.c_received.get(name, 0)

    def on_accepted(self, event):
        self.n_accepted += 1
        name = event.link.name
        self.n_outcomes[Delivery.ACCEPTED] = 1 + self.n_outcomes.get(Delivery.ACCEPTED, 0)

    def on_released(self, event):
        # for some reason Proton 'helpfully' calls on_released even though the
        # delivery state is actually MODIFIED
        if event.delivery.remote_state == Delivery.MODIFIED:
            return self.on_modified(event)
        self.n_released += 1
        name = event.link.name
        self.n_outcomes[Delivery.RELEASED] = 1 + self.n_outcomes.get(Delivery.RELEASED, 0)

    def on_modified(self, event):
        self.n_modified += 1
        name = event.link.name
        self.n_outcomes[Delivery.MODIFIED] = 1 + self.n_outcomes.get(Delivery.MODIFIED, 0)

    def on_rejected(self, event):
        self.n_rejected += 1
        name = event.link.name
        self.n_outcomes[Delivery.REJECTED] = 1 + self.n_outcomes.get(Delivery.REJECTED, 0)

    def on_settled(self, event):
        self.n_settled += 1

    def run(self):
        Container(self).run()

        # wait until all routers have cleaned up the route tables
        clean = False
        while not clean:
            clean = True
            for cfg in self.config:
                mgmt = cfg['router'].management
                atype = 'org.apache.qpid.dispatch.router.address'
                addrs = mgmt.query(type=atype).get_dicts()
                if list(filter(lambda a: a['name'].find(self.topic) != -1, addrs)):
                    clean = False
                    break
            if not clean:
                sleep(0.1)

class MulticastPresettled(MulticastBase):
    """
    Test multicast forwarding for presettled transfers.
    Verifies that all messages are settled by the sender
    """
    def __init__(self, config, count, body, settlement_mode):
        # use a large prefetch to prevent drops
        super(MulticastPresettled, self).__init__(config,
                                                  count,
                                                  body,
                                                  prefetch=(count * 1024),
                                                  auto_accept=False,
                                                  auto_settle=False)
        self.settlement_mode = settlement_mode
        self.unexpected_unsettled = 0
        self.expected_settled = 0
        self.sender_settled = 0
        self.done_count = 0
        self.unsettled_deliveries = dict()

    def create_receiver(self, container, conn, source, name):
        return container.create_receiver(conn, source=source, name=name,
                                         options=self.settlement_mode)

    def create_sender(self, container, conn, target, name):
        return container.create_sender(conn, target=target, name=name,
                                       options=self.settlement_mode)

    def do_send(self, sender):
        for i in range(self.msg_count):
            msg = Message(body=" %s -> %s:%s" % (sender.name, i, self.body))
            dlv = sender.send(msg)
            # settled before sending out the message
            dlv.settle()
            self.n_sent += 1

    def check_if_done(self):
        # wait for all present receivers to receive all messages
        # and for all received messages to be settled by the
        # sender
        to_rcv = self.n_senders * self.msg_count * self.n_receivers
        if to_rcv == self.n_received and not self.unsettled_deliveries:
            self.done()

    def on_message(self, event):
        super(MulticastPresettled, self).on_message(event)
        if event.receiver:
            if not event.delivery.settled:
                # it may be that settle will come after on_message
                # so track that here
                event.delivery.update(Delivery.ACCEPTED)
                self.unexpected_unsettled += 1
                tag = str(event.delivery.tag)
                if tag not in self.unsettled_deliveries:
                    self.unsettled_deliveries[tag] = 1
                else:
                    self.unsettled_deliveries[tag] += 1
            else:
                self.expected_settled += 1
            event.receiver.flow(100)
        self.check_if_done()

    def on_settled(self, event):
        super(MulticastPresettled, self).on_settled(event)
        if event.receiver:
            self.sender_settled += 1
            tag = str(event.delivery.tag)
            try:
                # got a delayed settle
                self.unsettled_deliveries[tag] -= 1
                if self.unsettled_deliveries[tag] == 0:
                    del self.unsettled_deliveries[tag]
            except KeyError:
                pass
            self.check_if_done()

class MulticastPresettledRxFail(MulticastPresettled):
    """
    Spontaneously close a receiver or connection on message received
    """
    def __init__(self, config, count, drop_clients, detach, body):
        super(MulticastPresettledRxFail, self).__init__(config, count, body, SendPresettled())
        self.drop_clients = drop_clients
        self.detach = detach

    def check_if_done(self):
        # Verify each receiver got the expected number of messages.
        # Avoid waiting for dropped receivers.
        done = True
        to_rcv = self.n_senders * self.msg_count
        for name, count in self.c_received.items():
            if name not in self.drop_clients:
                if count != to_rcv:
                    done = False
        if done:
            self.done()

    def on_message(self, event):
        # close the receiver on arrival of the first message
        r_name = event.receiver.name
        if r_name in self.drop_clients:
            if self.detach:
                if event.receiver.state & Link.LOCAL_ACTIVE:
                    event.receiver.close()
            elif event.connection.state & Connection.LOCAL_ACTIVE:
                event.connection.close()
        super(MulticastPresettledRxFail, self).on_message(event)

class MulticastUnsettled3Ack(MulticastBase):
    """
    Send count messages per sender, senders wait for terminal outcome from
    receivers before settling
    """
    def __init__(self, config, count, body, outcomes=None):
        pfetch = int((count + 1)/2)
        super(MulticastUnsettled3Ack, self).__init__(config,
                                                     count,
                                                     body,
                                                     prefetch=pfetch,
                                                     auto_accept=False,
                                                     auto_settle=False)
        self.outcomes = outcomes or {}

    def create_receiver(self, container, conn, source, name):
        return container.create_receiver(conn, source=source, name=name,
                                         options=Link3Ack())

    def create_sender(self, container, conn, target, name):
        return container.create_sender(conn, target=target, name=name,
                                       options=Link3Ack())

    def do_send(self, sender):
        for i in range(self.msg_count):
            msg = Message(body=" %s -> %s:%s" % (sender.name, i, self.body))
            dlv = sender.send(msg)
            self.n_sent += 1

    def on_message(self, event):
        # receiver: send outcome do not settle
        super(MulticastUnsettled3Ack, self).on_message(event)
        if event.delivery.settled:
            self.error = "Unexpected pre-settled message received!"
            self.done()
            return
        r_name = event.receiver.name
        outcome = self.outcomes.get(r_name, Delivery.ACCEPTED)
        event.delivery.update(outcome)
        if event.receiver.credit == 0:
            event.receiver.flow(1)

    def on_settled(self, event):
        super(MulticastUnsettled3Ack, self).on_settled(event)
        event.delivery.settle()
        self.check_if_done()

    def on_accepted(self, event):
        super(MulticastUnsettled3Ack, self).on_accepted(event)
        event.delivery.settle()
        self.check_if_done()

    def on_released(self, event):
        super(MulticastUnsettled3Ack, self).on_released(event)
        event.delivery.settle()
        self.check_if_done()

    def on_modified(self, event):
        super(MulticastUnsettled3Ack, self).on_modified(event)
        event.delivery.settle()
        self.check_if_done()

    def on_rejected(self, event):
        super(MulticastUnsettled3Ack, self).on_rejected(event)
        event.delivery.settle()
        self.check_if_done()

    def check_if_done(self):
        to_send = self.msg_count * self.n_senders
        to_rcv = to_send * self.n_receivers

        n_outcomes = (self.n_accepted + self.n_rejected
                      + self.n_modified + self.n_released)

        # expect senders to see settlement
        if (self.n_sent == to_send
                and self.n_received == to_rcv
                and n_outcomes == to_send
                and self.n_settled == to_rcv):
            self.done()

class MulticastUnsettled1Ack(MulticastUnsettled3Ack):
    """
    Sender sends unsettled, the receiver sets outcome and immediately settles
    """
    def __init__(self, config, count, body, outcomes=None):
        super(MulticastUnsettled1Ack, self).__init__(config,
                                                     count,
                                                     outcomes)

    def create_receiver(self, container, conn, source, name):
        return container.create_receiver(conn, source=source, name=name,
                                         options=Link1Ack())

    def create_sender(self, container, conn, target, name):
        return container.create_sender(conn, target=target, name=name,
                                       options=Link1Ack())

    def on_message(self, event):
        # receiver: send outcome and settle
        super(MulticastUnsettled1Ack, self).on_message(event)
        event.delivery.settle()

    def check_if_done(self):
        to_send = self.msg_count * self.n_senders
        to_rcv = to_send * self.n_receivers

        n_outcomes = (self.n_accepted + self.n_rejected
                      + self.n_modified + self.n_released)

        # expect sender to see settlement
        if (self.n_received == to_rcv
                and n_outcomes == to_send
                and self.n_settled == to_send):
            self.done()

class MulticastUnsettledRxFail(MulticastUnsettled3Ack):
    """
    Spontaneously close a receiver or connection on message received
    """
    def __init__(self, config, count, drop_clients, detach, body):
        super(MulticastUnsettledRxFail, self).__init__(config, count, body)
        self.drop_clients = drop_clients
        self.detach = detach

    def check_if_done(self):
        # Verify each receiver got the expected number of messages.
        # Avoid waiting for dropped receivers.
        done = True
        to_rcv = self.n_senders * self.msg_count
        for name, count in self.c_received.items():
            if name not in self.drop_clients:
                if count != to_rcv:
                    done = False
        if done:
            self.done()

    def on_message(self, event):
        # close the receiver on arrival of the first message
        r_name = event.receiver.name
        if r_name in self.drop_clients:
            if self.detach:
                if event.receiver.state & Link.LOCAL_ACTIVE:
                    event.receiver.close()
            elif event.connection.state & Connection.LOCAL_ACTIVE:
                event.connection.close()
        super(MulticastUnsettledRxFail, self).on_message(event)

class MulticastUnsettled3AckMA(MulticastUnsettled3Ack):
    """
    Try 3 Ack, but with a bunch of user Message Annotations (why not?)
    """
    def __init__(self, config, count, body, outcomes=None):
        super(MulticastUnsettled3AckMA, self).__init__(config,
                                                       count,
                                                       body,
                                                       outcomes=None)
        self._huge_ma = {
            "my-key": "my-data",
            "my-other-key": "my-other-data",
            "my-map": { "my-map-key1": "X",
                        "my-map-key2": 0x12,
                        "my-map-key3": "+0123456789" * 101,
                        "my-map-list": [i for i in range(97)]
            },
            "my-last-key": "so long, folks!"
        }

    def do_send(self, sender):
        for i in range(self.msg_count):
            msg = Message(body=" %s -> %s:%s" % (sender.name, i, self.body))
            msg.annotations = self._huge_ma
            dlv = sender.send(msg)
            self.n_sent += 1

    def on_message(self, event):
        msg = event.message
        if event.message.annotations != self._huge_ma:
            self.error = "forwarded message annotations mismatch original"
            self.done()
            return
        super(MulticastUnsettled3AckMA, self).on_message(event)

class MulticastCreditBlocked(MessagingHandler):
    """
    Ensure that credit is not provided when there are no consumers present.
    This client connects to 'address' and creates a sender to 'target'.  Once
    the sending link has opened a short timer is started.  It is expected that
    on_sendable() is NOT invoked before the timer expires.
    """
    def __init__(self, address, target=None, timeout=2, **handler_kwargs):
        super(MulticastCreditBlocked, self).__init__(**handler_kwargs)
        self.target = target
        self.address = address
        self.time_out = timeout

        self.conn = None
        self.sender = None
        self.timer = None
        self.error = "Timeout NOT triggered as expected!"

    def done(self):
        # stop the reactor and clean up the test
        if self.timer:
            self.timer.cancel()
        if self.conn:
            self.conn.close()

    def timeout(self):
        self.error = None
        self.done()

    def on_start(self, event):
        self.conn = event.container.connect(self.address)
        self.sender = event.container.create_sender(self.conn,
                                                    target=self.target,
                                                    name="McastBlocked")

    def on_link_opened(self, event):
        self.timer = event.reactor.schedule(self.time_out, TestTimeout(self))

    def on_sendable(self, event):
        self.error = "Unexpected call to on_sendable()!"
        self.done()

    def run(self):
        Container(self).run()

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


text:
require 'spec_helper'

describe 'building plans' do
  describe 'simply' do
    before do
      Stripe.plan :primo do |plan|
        plan.name = 'Acme as a service PRIMO'
        plan.amount = 699
        plan.interval = 'month'
        plan.interval_count = 3
        plan.trial_period_days = 30
        plan.metadata = {:number_of_awesome_things => 5}
        plan.statement_descriptor = 'Acme Primo'
        plan.active = true
        plan.nickname = 'primo'
        plan.usage_type = 'metered'
        plan.billing_scheme = 'per_unit'
        plan.aggregate_usage = 'sum'
        plan.tiers_mode = 'graduated'
      end
    end

    after { Stripe::Plans.send(:remove_const, :PRIMO) }

    it 'is accessible via id' do
      _(Stripe::Plans::PRIMO).wont_be_nil
    end

    it 'is accessible via collection' do
      _(Stripe::Plans.all).must_include Stripe::Plans::PRIMO
    end

    it 'is accessible via hash lookup (symbol/string agnostic)' do
      _(Stripe::Plans[:primo]).must_equal Stripe::Plans::PRIMO
      _(Stripe::Plans['primo']).must_equal Stripe::Plans::PRIMO
    end

    it 'accepts a billing interval of a day' do
      Stripe.plan :daily do |plan|
        plan.name = 'Acme as a service daily'
        plan.amount = 100
        plan.interval = 'day'
      end

      _(Stripe::Plans::DAILY).wont_be_nil
    end

    it 'accepts a billing interval of a week' do
      Stripe.plan :weekly do |plan|
        plan.name = 'Acme as a service weekly'
        plan.amount = 100
        plan.interval = 'week'
      end

      _(Stripe::Plans::WEEKLY).wont_be_nil
    end

    it 'accepts a billing interval of a month' do
      Stripe.plan :monthly do |plan|
        plan.name = 'Acme as a service monthly'
        plan.amount = 400
        plan.interval = 'month'
      end

      _(Stripe::Plans::MONTHLY).wont_be_nil
    end

    it 'accepts a billing interval of a year' do
      Stripe.plan :yearly do |plan|
        plan.name = 'Acme as a service yearly'
        plan.amount = 4800
        plan.interval = 'year'
      end

      _(Stripe::Plans::YEARLY).wont_be_nil
    end

    it 'denies arbitrary billing intervals' do
      _(lambda {
        Stripe.plan :broken do |plan|
          plan.name = 'Acme as a service BROKEN'
          plan.amount = 999
          plan.interval = 'anything'
        end
      }).must_raise Stripe::InvalidConfigurationError
    end

    it 'accepts a statement descriptor' do
      Stripe.plan :described do |plan|
        plan.name = 'Acme as a service'
        plan.amount = 999
        plan.interval = 'month'
        plan.statement_descriptor = 'ACME Monthly'
      end

      _(Stripe::Plans::DESCRIBED).wont_be_nil
    end

    it 'denies statement descriptors that are too long' do
      _(lambda {
        Stripe.plan :described do |plan|
          plan.name = 'Acme as a service'
          plan.amount = 999
          plan.interval = 'month'
          plan.statement_descriptor = 'ACME as a Service Monthly'
        end
      }).must_raise Stripe::InvalidConfigurationError
    end

    it 'denies invalid values for active' do
      _(lambda {
        Stripe.plan :broken do |plan|
          plan.name = 'Acme as a service'
          plan.amount = 999
          plan.interval = 'month'
          plan.active = 'whatever'
        end
      }).must_raise Stripe::InvalidConfigurationError
    end

    it 'denies invalid values for usage_type' do
      _(lambda {
        Stripe.plan :broken do |plan|
          plan.name = 'Acme as a service'
          plan.amount = 999
          plan.interval = 'month'
          plan.usage_type = 'whatever'
        end
      }).must_raise Stripe::InvalidConfigurationError
    end

    it 'denies invalid values for aggregate_usage' do
      _(lambda {
        Stripe.plan :broken do |plan|
          plan.name = 'Acme as a service'
          plan.amount = 999
          plan.interval = 'month'
          plan.aggregate_usage = 'whatever'
        end
      }).must_raise Stripe::InvalidConfigurationError
    end

    it 'denies aggregate_usage if usage type is liecensed' do
      _(lambda {
        Stripe.plan :broken do |plan|
          plan.name = 'Acme as a service'
          plan.amount = 999
          plan.interval = 'month'
          plan.usage_type = 'licensed'
          plan.aggregate_usage = 'sum'
        end
      }).must_raise Stripe::InvalidConfigurationError
    end

    it 'denies invalid values for billing_scheme' do
      _(lambda {
        Stripe.plan :broken do |plan|
          plan.name = 'Acme as a service'
          plan.amount = 999
          plan.interval = 'month'
          plan.billing_scheme = 'whatever'
        end
      }).must_raise Stripe::InvalidConfigurationError
    end

    it 'denies invalid values for tiers_mode' do
      _(lambda {
        Stripe.plan :broken do |plan|
          plan.name = 'Acme as a service'
          plan.amount = 999
          plan.interval = 'month'
          plan.tiers_mode = 'whatever'
        end
      }).must_raise Stripe::InvalidConfigurationError
    end

    describe 'name and product id validation' do
      it 'should be valid when using just the product id' do
        Stripe.plan :prodded do |plan|
          plan.product_id = 'acme'
          plan.amount = 999
          plan.interval = 'month'
        end
        _(Stripe::Plans::PRODDED).wont_be_nil
      end

      it 'should be invalid when using both name and product id' do
        _(lambda {
          Stripe.plan :broken do |plan|
            plan.name = 'Acme as a service'
            plan.product_id = 'acme'
            plan.amount = 999
            plan.interval = 'month'
          end
        }).must_raise Stripe::InvalidConfigurationError
      end
    end

    describe 'uploading' do
      include FixtureLoader

      describe 'when none exists on stripe.com' do
        let(:headers) { load_request_fixture('stripe_plans_headers_2017.json') }
        before do
          Stripe::Plan.stubs(:retrieve).raises(Stripe::InvalidRequestError.new("not found", "id"))

          stub_request(:get, "https://api.stripe.com/v1/plans").
            with(headers: { 'Authorization'=>'Bearer XYZ',}).
            to_return(status: 200, body: load_request_fixture('stripe_plans.json'), headers: JSON.parse(headers))
        end

        it 'creates the plan online' do
          Stripe::Plan.expects(:create).with(
            :id => :gold,
            :currency => 'usd',
            :name => 'Solid Gold',
            :amount => 699,
            :interval => 'month',
            :interval_count => 1,
            :trial_period_days => 0
          )
          Stripe::Plans::GOLD.put!
        end

        it 'creates a plan with an alternative currency' do
          Stripe::Plan.expects(:create).with(
            :id => :alternative_currency,
            :currency => 'cad',
            :name => 'Alternative Currency',
            :amount => 699,
            :interval => 'month',
            :interval_count => 1,
            :trial_period_days => 0
          )
          Stripe::Plans::ALTERNATIVE_CURRENCY.put!
        end

        describe 'when using the API version that supports products' do
          before { Stripe.api_version = '2018-02-05' }
          after  { Stripe.api_version = nil }

          it 'creates the plan online' do
            Stripe::Plan.expects(:create).with(
              :id => :gold,
              :currency => 'usd',
              :product => {
                :name => 'Solid Gold',
                :statement_descriptor => nil,
              },
              :amount => 699,
              :interval => 'month',
              :interval_count => 1,
              :trial_period_days => 0
            )
            Stripe::Plans::GOLD.put!
          end

          it 'creates a metered plan' do
            Stripe::Plan.expects(:create).with(
              :id => :metered,
              :currency => 'usd',
              :product => {
                :name => 'Metered',
                :statement_descriptor => nil,
              },
              :amount => 699,
              :interval => 'month',
              :interval_count => 1,
              :trial_period_days => 0,
              :usage_type => 'metered',
              :aggregate_usage => 'max',
              :billing_scheme => 'per_unit'
            )
            Stripe::Plans::METERED.put!
          end

          it 'creates a tiered plan' do
            Stripe::Plan.expects(:create).with(
              :id => :tiered,
              :currency => 'usd',
              :product => {
                :name => 'Tiered',
                :statement_descriptor => nil,
              },
              :interval => 'month',
              :interval_count => 1,
              :trial_period_days => 0,
              :usage_type => 'metered',
              :aggregate_usage => 'max',
              :billing_scheme => 'tiered',
              :tiers => [
                {
                  :unit_amount => 1500,
                  :up_to => 10
                },
                {
                  :unit_amount => 1000,
                  :up_to => 'inf'
                }
              ],
              :tiers_mode => 'graduated'
            )
            plan = Stripe::Plans::TIERED
            Stripe::Plans::TIERED.put!
          end

          describe 'when passed invalid arguments for tiered pricing' do
            it 'raises a Stripe::InvalidConfigurationError when billing tiers are invalid' do
              lambda {
                Stripe.plan "Bad Tiers".to_sym do |plan|
                  plan.name = 'Acme as a service BAD TIERS'
                  plan.constant_name = 'BAD_TIERS'
                  plan.interval = 'month'
                  plan.interval_count = 1
                  plan.trial_period_days = 30
                  plan.usage_type = 'metered'
                  plan.tiers_mode = 'graduated'
                  plan.billing_scheme = 'per_unit'
                  plan.aggregate_usage = 'sum'
                  plan.tiers = [
                    {
                      unit_amount: 1500,
                      up_to: 10
                    },
                    {
                      unit_amount: 1000,
                    }
                  ]
                end
              }.must_raise Stripe::InvalidConfigurationError
            end

            it 'raises a Stripe::InvalidConfigurationError when billing tiers is not an array' do
              lambda {
                Stripe.plan "Bad Tiers".to_sym do |plan|
                  plan.name = 'Acme as a service BAD TIERS'
                  plan.constant_name = 'BAD_TIERS'
                  plan.interval = 'month'
                  plan.interval_count = 1
                  plan.trial_period_days = 30
                  plan.usage_type = 'metered'
                  plan.tiers_mode = 'graduated'
                  plan.billing_scheme = 'per_unit'
                  plan.aggregate_usage = 'sum'
                  plan.tiers = {
                    unit_amount: 1500,
                    up_to: 10
                  }
                end
              }.must_raise Stripe::InvalidConfigurationError
            end
          end

          describe 'when using a product id' do
            before do
              Stripe::Plans::GOLD.product_id = 'prod_XXXXXXXXXXXXXX'
              Stripe::Plans::GOLD.name = nil
            end
            after do
              Stripe::Plans::GOLD.product_id = nil
              Stripe::Plans::GOLD.name = 'Solid Gold'
            end

            it 'creates the plan online with the product id' do
              Stripe::Plan.expects(:create).with(
                :id => :gold,
                :currency => 'usd',
                :product => 'prod_XXXXXXXXXXXXXX',
                :amount => 699,
                :interval => 'month',
                :interval_count => 1,
                :trial_period_days => 0
              )
              Stripe::Plans::GOLD.put!
            end
          end
        end

        describe 'when api_version is not set for api versions that support products' do
          before  { Stripe.api_version = nil }
          subject { Stripe::Plans::GOLD.put! }
          let(:headers) { load_request_fixture('stripe_plans_headers.json') }

          it 'creates the plan online' do
            Stripe::Plan.expects(:create).with(
              :id => :gold,
              :currency => 'usd',
              :product => {
                :name => 'Solid Gold',
                :statement_descriptor => nil,
              },
              :amount => 699,
              :interval => 'month',
              :interval_count => 1,
              :trial_period_days => 0
            )

            subject
          end
        end
      end

      describe 'when it is already present on stripe.com' do
        before do
          Stripe::Plan.stubs(:retrieve).returns(Stripe::Plan.construct_from({
            :id => :gold,
            :name => 'Solid Gold'
          }))
        end

        it 'is a no-op' do
          Stripe::Plan.expects(:create).never
          Stripe::Plans::GOLD.put!
        end
      end
    end
  end

  describe 'with missing mandatory values' do
    it 'raises an exception after configuring it' do
      _(-> { Stripe.plan(:bad) {} }).must_raise Stripe::InvalidConfigurationError
    end
  end

  describe 'with custom constant name' do
    before do
      Stripe.plan "Primo Plan".to_sym do |plan|
        plan.name = 'Acme as a service PRIMO'
        plan.constant_name = 'PRIMO_PLAN'
        plan.amount = 699
        plan.interval = 'month'
        plan.interval_count = 3
        plan.trial_period_days = 30
        plan.metadata = {:number_of_awesome_things => 5}
        plan.statement_descriptor = 'Acme Primo'
        plan.active = true
        plan.nickname = 'primo'
        plan.usage_type = 'metered'
        plan.billing_scheme = 'per_unit'
        plan.aggregate_usage = 'sum'
        plan.tiers_mode = 'graduated'
      end
    end

    after { Stripe::Plans.send(:remove_const, :PRIMO_PLAN) }

    it 'is accessible via upcased constant_name' do
      _(Stripe::Plans::PRIMO_PLAN).wont_be_nil
    end

    it 'is accessible via collection' do
      _(Stripe::Plans.all).must_include Stripe::Plans::PRIMO_PLAN
    end

    it 'is accessible via hash lookup (symbol/string agnostic)' do
      _(Stripe::Plans[:primo_plan]).must_equal Stripe::Plans::PRIMO_PLAN
      _(Stripe::Plans['primo_plan']).must_equal Stripe::Plans::PRIMO_PLAN
    end

    describe 'constant name validation' do
      it 'should be invalid when providing a constant name that can not be used for Ruby constant' do
        _(lambda {
          Stripe.plan "Primo Plan".to_sym do |plan|
            plan.name = 'Acme as a service PRIMO'
            plan.constant_name = 'PRIMO PLAN'
            plan.amount = 999
            plan.interval = 'month'
          end
        }).must_raise Stripe::InvalidConfigurationError
      end
    end

    describe 'uploading' do
      include FixtureLoader

      describe 'when none exists on stripe.com' do
        let(:headers) { load_request_fixture('stripe_plans_headers_2017.json') }
        before do
          Stripe::Plan.stubs(:retrieve).raises(Stripe::InvalidRequestError.new("not found", "id"))

          stub_request(:get, "https://api.stripe.com/v1/plans").
            with(headers: { 'Authorization'=>'Bearer XYZ',}).
            to_return(status: 200, body: load_request_fixture('stripe_plans.json'), headers: JSON.parse(headers))
        end

        it 'creates the plan online' do
          Stripe::Plan.expects(:create).with(
            :id => "Solid Gold".to_sym,
            :currency => 'usd',
            :name => 'Solid Gold',
            :amount => 699,
            :interval => 'month',
            :interval_count => 1,
            :trial_period_days => 0
          )
          Stripe::Plans::SOLID_GOLD.put!
        end
      end
    end
  end
end


text:
"""
This script serves a very specific purpose:
    Nullifying all non-end-dated status history objects that are not the latest value.
"""

from core.models import Provider, Instance, InstanceStatusHistory
import django
django.setup()
provs = Provider.get_active()
for instance in Instance.objects.filter(
        source__provider__in=provs).order_by('created_by'):
    prev_history = None
    try:
        last_history = instance.instancestatushistory_set.latest('pk')
    except InstanceStatusHistory.DoesNotExist:
        continue
    for history in instance.instancestatushistory_set.order_by('start_date'):
        if not history.end_date and history.id != last_history.id:
            print "Provider: %s" % instance.source.provider.location
            print "Owner: %s" % instance.created_by.username
            print "Instance: %s Bad History: %s" % (instance.provider_alias, history)
            history.end_date = history.start_date
            history.save()
    prev_history = None
    for history in instance.instancestatushistory_set.order_by('start_date'):
        if prev_history and prev_history.status.name == history.status.name\
                and history.end_date != history.start_date:
            print "Provider: %s" % instance.source.provider.location
            print "Owner: %s" % instance.created_by.username
            print "Instance: %s Duplicate History with status %s" %\
                (instance.provider_alias, history)
            history.end_date = history.start_date
            history.save()
        prev_history = history


text:
package org.jetbrains.plugins.scala.lang
package completion
package postfix
package templates

import com.intellij.psi.PsiElement
import org.jetbrains.plugins.scala.lang.completion.postfix.templates.selector.AncestorSelector._

/**
 * @author Roman.Shein
 * @since 09.09.2015.
 */
final class ScalaForEachPostfixTemplate extends ScalaStringBasedPostfixTemplate(
  "for",
  "for (elem: collection) {...}",
  SelectTopmostAncestors(isSameOrInheritor("scala.collection.GenTraversableOnce", "scala.Array"))
) {
  override def getTemplateString(element: PsiElement): String = "for (elem <- $expr$) {$END$}"
}


text:
<?php

use yii\helpers\Html;
use app\models\general\GeneralLabel;
/* @var $this yii\web\View */
/* @var $model app\models\RefKategoriMakananTambahan */

$this->title = GeneralLabel::updateTitle.' '.GeneralLabel::kategori_makanan_tambahan.': ' . ' ' . $model->id;
$this->params['breadcrumbs'][] = ['label' => GeneralLabel::kategori_makanan_tambahan, 'url' => ['index']];
$this->params['breadcrumbs'][] = ['label' => $model->id, 'url' => ['view', 'id' => $model->id]];
$this->params['breadcrumbs'][] = GeneralLabel::updateTitle;
?>

<?= Html::encode($this->title) ?>

    <?= $this->render('_form', [
        'model' => $model,
    ]) ?>


text:
import * as fs from 'fs';
import * as path from 'path';
import resolveFrom from 'resolve-from';
import * as os from 'os';
import resolveGlobal from 'resolve-global';

export interface ResolveFileResult {
    filename: string;
    relativeTo: string | undefined;
    found: boolean;
}

const testNodeModules = /^node_modules\//;

/**
 * Resolve filename to absolute paths.
 * It tries to look for local files as well as node_modules
 * @param filename an absolute path, relative path, `~` path, or a node_module.
 * @param relativeTo absolute path
 */
export function resolveFile(filename: string, relativeTo: string): ResolveFileResult {
    filename = filename.replace(/^~/, os.homedir());
    const steps: { filename: string; fn: (f: string, r: string) => ResolveFileResult }[] = [
        { filename: filename, fn: tryNodeResolve },
        { filename: path.resolve(relativeTo, filename), fn: tryResolveExists },
        { filename: path.resolve(filename), fn: tryResolveExists },
        { filename: filename, fn: tryNodeResolveDefaultPaths },
        { filename: filename, fn: tryResolveFrom },
        { filename: filename.replace(testNodeModules, ''), fn: tryResolveFrom },
        { filename: filename, fn: tryResolveGlobal },
    ];

    for (const step of steps) {
        const r = step.fn(step.filename, relativeTo);
        if (r.found) return r;
    }
    return { filename: path.resolve(relativeTo, filename), relativeTo, found: false };
}

function tryNodeResolveDefaultPaths(filename: string): ResolveFileResult {
    try {
        const r = require.resolve(filename);
        return { filename: r, relativeTo: undefined, found: true };
    } catch (_) {
        return { filename, relativeTo: undefined, found: false };
    }
}

function tryNodeResolve(filename: string, relativeTo: string): ResolveFileResult {
    const home = os.homedir();
    function calcPaths(p: string) {
        const paths = [p];
        // Do not progress towards the root if it is a relative filename.
        if (
            filename.startsWith('.') &&
            (filename.startsWith('./') || filename.startsWith('.' + path.sep) || filename.startsWith('..'))
        ) {
            return paths;
        }
        for (; p && path.dirname(p) !== p && p !== home; p = path.dirname(p)) {
            paths.push(p);
        }
        return paths;
    }
    const paths = calcPaths(path.resolve(relativeTo));
    try {
        const r = require.resolve(filename, { paths });
        return { filename: r, relativeTo, found: true };
    } catch (_) {
        return { filename, relativeTo, found: false };
    }
}

function tryResolveGlobal(filename: string): ResolveFileResult {
    const r = resolveGlobal.silent(filename);
    return { filename: r || filename, relativeTo: undefined, found: !!r };
}

function tryResolveExists(filename: string): ResolveFileResult {
    return { filename, relativeTo: undefined, found: fs.existsSync(filename) };
}

function tryResolveFrom(filename: string, relativeTo: string): ResolveFileResult {
    try {
        return { filename: resolveFrom(relativeTo, filename), relativeTo, found: true };
    } catch (error) {
        // Failed to resolve a relative module request
        return { filename: filename, relativeTo, found: false };
    }
}


text:
//----------------------------------*-C++-*----------------------------------//
/*!
 * \file   Alea/mc_solvers/LinearSystem.cc
 * \author Steven Hamilton
 * \brief  LinearSystem class definitions.
 */
//---------------------------------------------------------------------------//

#include <iterator>
#include <string>

#include "LinearSystem.hh"

namespace alea
{

//---------------------------------------------------------------------------//
/*!
 * \brief Constructor
 *
 * \param A  Problem matrix
 * \param b  Problem right hand side vector
 */
//---------------------------------------------------------------------------//
LinearSystem::LinearSystem(Teuchos::RCP<const MATRIX> A,
                           Teuchos::RCP<const MV>     b)
  : d_A(A)
  , d_b(b)
{
}

} // namespace alea


text:
package com.palantir.atlasdb.jackson;

import java.io.IOException;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import com.google.common.base.Preconditions;
import com.palantir.atlasdb.api.TableCell;
import com.palantir.atlasdb.encoding.PtBytes;
import com.palantir.atlasdb.impl.TableMetadataCache;
import com.palantir.atlasdb.keyvalue.api.Cell;
import com.palantir.atlasdb.table.description.ColumnMetadataDescription;
import com.palantir.atlasdb.table.description.DynamicColumnDescription;
import com.palantir.atlasdb.table.description.NamedColumnDescription;
import com.palantir.atlasdb.table.description.TableMetadata;

public class TableCellSerializer extends StdSerializer<TableCell> {
    private static final long serialVersionUID = 1L;
    private final TableMetadataCache metadataCache;

    public TableCellSerializer(TableMetadataCache metadataCache) {
        super(TableCell.class);
        this.metadataCache = metadataCache;
    }

    @Override
    public void serialize(TableCell value,
                          JsonGenerator jgen,
                          SerializerProvider provider) throws IOException, JsonGenerationException {
        TableMetadata metadata = metadataCache.getMetadata(value.getTableName());
        Preconditions.checkNotNull(metadata, "Unknown table %s", value.getTableName());
        jgen.writeStartObject(); {
            jgen.writeStringField("table", value.getTableName());
            jgen.writeArrayFieldStart("data"); {
                for (Cell cell : value.getCells()) {
                    serialize(jgen, metadata, cell);
                }
            } jgen.writeEndArray();
        } jgen.writeEndObject();
    }

    private static void serialize(JsonGenerator jgen,
                                  TableMetadata metadata,
                                  Cell cell) throws IOException, JsonGenerationException {
        byte[] row = cell.getRowName();
        byte[] col = cell.getColumnName();

        jgen.writeStartObject(); {
            AtlasSerializers.serializeRow(jgen, metadata.getRowMetadata(), row);

            ColumnMetadataDescription columns = metadata.getColumns();
            if (columns.hasDynamicColumns()) {
                DynamicColumnDescription dynamicColumn = columns.getDynamicColumn();
                AtlasSerializers.serializeDynamicColumn(jgen, dynamicColumn, col);
            } else {
                String shortName = PtBytes.toString(col);
                jgen.writeStringField("col", getLongColumnName(columns, shortName));
            }
        } jgen.writeEndObject();
    }

    private static String getLongColumnName(ColumnMetadataDescription colDescription,
                                            String shortName) {
        for (NamedColumnDescription description : colDescription.getNamedColumns()) {
            if (shortName.equals(description.getShortName())) {
                return description.getLongName();
            }
        }
        throw new IllegalArgumentException("Unknown column with short name " + shortName);
    }
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Core.TestFramework;
using NUnit.Framework;

namespace Azure.Security.Attestation.Tests
{
    public class AttestationTests : RecordedTestBase<AttestationClientTestEnvironment>
    {
        private readonly string _openEnclaveReport = "AQAAAAIAAADoEQAAAAAAAAMAAgAAAAAABQAKAJOacjP3nEyplAoNs5V_Bgfl_L18zrEJejtqk6RDB0IzAAAAABERAwX_gAYAAAAAAAAAAA" +
                                                    "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAcAAAAAAAAABwAAAAAAAAApKh9LUZ5GYn6yR4o9mFFAVlPFtLCmkl3oQ4NNkhaF" +
                                                    "DgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAASupfmg7QSxH4iarf5qHTdiE6Kalahc5zN65vf-zmYQwAAAAAAAAAAAAAAAAAAA" +
                                                    "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" +
                                                    "AAABAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAKFQuRP5-c_ZhD2sxrn" +
                                                    "V2kl8JzNu0xWRlg-zBVhM3qP8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADQQAACJx8e27oQ0pijs3lXQ9HfKWP9NMqVHQFL9" +
                                                    "SOjC_KGDcbv-I2fCafTHJ__AmNqVXy7XTXnzmLp1HhUCy1_9AORSATqGZ1PtvBf4Q2NfNxqVkNrGJAjYuqMPStdg0MuM21nN-Qc9BWNycR" +
                                                    "MMsU7YfHSzmw7eGjBb_Ewfb3k6N4ZYRhERAwX_gAYAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABUAAAAAAAAA" +
                                                    "BwAAAAAAAAA_sKzghp0uMPKOhtcMdmQDpU-7zWWO7ODhuUipFVkXQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAjE9XddeWUD" +
                                                    "6WE393xoqCmgBWrI3tcBQLCBsJRJDFe_8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" +
                                                    "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" +
                                                    "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAH_mzVQFF8XbJCRGdNkA3SPx9ZUPgtx3874VyDYQnFRIAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" +
                                                    "AAAAAAAAAAAAAEUP2-pxe7LoyevtN5BdE4KKikxKK6-hwG0xCDmxmfLphcnrVskSbKmiKUfzkWUBehrF8gHCGNGIPX3QQDwmtZ4gAAABAg" +
                                                    "MEBQYHCAkKCwwNDg8QERITFBUWFxgZGhscHR4fBQDMDQAALS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSUVnVENDQkNhZ0F3SUJB" +
                                                    "Z0lVU3I5VmRiSnFWbzVyZzRadUpCRWo2SjNoak9jd0NnWUlLb1pJemowRUF3SXcKY1RFak1DRUdBMVVFQXd3YVNXNTBaV3dnVTBkWUlGQk" +
                                                    "RTeUJRY205alpYTnpiM0lnUTBFeEdqQVlCZ05WQkFvTQpFVWx1ZEdWc0lFTnZjbkJ2Y21GMGFXOXVNUlF3RWdZRFZRUUhEQXRUWVc1MFlT" +
                                                    "QkRiR0Z5WVRFTE1Ba0dBMVVFCkNBd0NRMEV4Q3pBSkJnTlZCQVlUQWxWVE1CNFhEVEl4TURNeE9UQTBOVEl3T0ZvWERUSTRNRE14T1RBME" +
                                                    "5USXcKT0Zvd2NERWlNQ0FHQTFVRUF3d1pTVzUwWld3Z1UwZFlJRkJEU3lCRFpYSjBhV1pwWTJGMFpURWFNQmdHQTFVRQpDZ3dSU1c1MFpX" +
                                                    "d2dRMjl5Y0c5eVlYUnBiMjR4RkRBU0JnTlZCQWNNQzFOaGJuUmhJRU5zWVhKaE1Rc3dDUVlEClZRUUlEQUpEUVRFTE1Ba0dBMVVFQmhNQ1" +
                                                    "ZWTXdXVEFUQmdjcWhrak9QUUlCQmdncWhrak9QUU1CQndOQ0FBUlQKVGRNNVhTMGFiRTA2ZUdVTVU3S1JOQXJlRGRtTWJHK25KVHlucDZX" +
                                                    "ankyeXJ6NmlEa3h1R1F3WGZ1b25uUVBuZApjdHgwbHIyR3I0WjF1YXNsQjM2Vm80SUNtekNDQXBjd0h3WURWUjBqQkJnd0ZvQVUwT2lxMm" +
                                                    "5YWCtTNUpGNWc4CmV4UmwwTlh5V1Uwd1h3WURWUjBmQkZnd1ZqQlVvRktnVUlaT2FIUjBjSE02THk5aGNHa3VkSEoxYzNSbFpITmwKY25a" +
                                                    "cFkyVnpMbWx1ZEdWc0xtTnZiUzl6WjNndlkyVnlkR2xtYVdOaGRHbHZiaTkyTWk5d1kydGpjbXcvWTJFOQpjSEp2WTJWemMyOXlNQjBHQT" +
                                                    "FVZERnUVdCQlRMejZNQ3VHcVZobFYrR2Q0ZGtacmx4YndCV2pBT0JnTlZIUThCCkFmOEVCQU1DQnNBd0RBWURWUjBUQVFIL0JBSXdBREND" +
                                                    "QWRRR0NTcUdTSWI0VFFFTkFRU0NBY1V3Z2dIQk1CNEcKQ2lxR1NJYjRUUUVOQVFFRUVMOEhhRExXWWdVUFUzU3c3Tm1Ibkhrd2dnRmtCZ2" +
                                                    "9xaGtpRytFMEJEUUVDTUlJQgpWREFRQmdzcWhraUcrRTBCRFFFQ0FRSUJFVEFRQmdzcWhraUcrRTBCRFFFQ0FnSUJFVEFRQmdzcWhraUcr" +
                                                    "RTBCCkRRRUNBd0lCQWpBUUJnc3Foa2lHK0UwQkRRRUNCQUlCQkRBUUJnc3Foa2lHK0UwQkRRRUNCUUlCQVRBUkJnc3EKaGtpRytFMEJEUU" +
                                                    "VDQmdJQ0FJQXdFQVlMS29aSWh2aE5BUTBCQWdjQ0FRWXdFQVlMS29aSWh2aE5BUTBCQWdnQwpBUUF3RUFZTEtvWklodmhOQVEwQkFna0NB" +
                                                    "UUF3RUFZTEtvWklodmhOQVEwQkFnb0NBUUF3RUFZTEtvWklodmhOCkFRMEJBZ3NDQVFBd0VBWUxLb1pJaHZoTkFRMEJBZ3dDQVFBd0VBWU" +
                                                    "xLb1pJaHZoTkFRMEJBZzBDQVFBd0VBWUwKS29aSWh2aE5BUTBCQWc0Q0FRQXdFQVlMS29aSWh2aE5BUTBCQWc4Q0FRQXdFQVlMS29aSWh2" +
                                                    "aE5BUTBCQWhBQwpBUUF3RUFZTEtvWklodmhOQVEwQkFoRUNBUW93SHdZTEtvWklodmhOQVEwQkFoSUVFQkVSQWdRQmdBWUFBQUFBCkFBQU" +
                                                    "FBQUF3RUFZS0tvWklodmhOQVEwQkF3UUNBQUF3RkFZS0tvWklodmhOQVEwQkJBUUdBSkJ1MVFBQU1BOEcKQ2lxR1NJYjRUUUVOQVFVS0FR" +
                                                    "QXdDZ1lJS29aSXpqMEVBd0lEU1FBd1JnSWhBSzZPMS9GNy80NFprcWhUN2FhNgp5QVh6QlltRWxUVHRvL25rVUd4N1BtUktBaUVBMXliSW" +
                                                    "t6SjVwcXR1L21jOW5DUWNwRUJOdk5KZFNIcW1jc04rCkV2dWJ3WlU9Ci0tLS0tRU5EIENFUlRJRklDQVRFLS0tLS0KLS0tLS1CRUdJTiBD" +
                                                    "RVJUSUZJQ0FURS0tLS0tCk1JSUNsekNDQWo2Z0F3SUJBZ0lWQU5Eb3F0cDExL2t1U1JlWVBIc1VaZERWOGxsTk1Bb0dDQ3FHU000OUJBTU" +
                                                    "MKTUdneEdqQVlCZ05WQkFNTUVVbHVkR1ZzSUZOSFdDQlNiMjkwSUVOQk1Sb3dHQVlEVlFRS0RCRkpiblJsYkNCRApiM0p3YjNKaGRHbHZi" +
                                                    "akVVTUJJR0ExVUVCd3dMVTJGdWRHRWdRMnhoY21FeEN6QUpCZ05WQkFnTUFrTkJNUXN3CkNRWURWUVFHRXdKVlV6QWVGdzB4T0RBMU1qRX" +
                                                    "hNRFExTURoYUZ3MHpNekExTWpFeE1EUTFNRGhhTUhFeEl6QWgKQmdOVkJBTU1Ha2x1ZEdWc0lGTkhXQ0JRUTBzZ1VISnZZMlZ6YzI5eUlF" +
                                                    "TkJNUm93R0FZRFZRUUtEQkZKYm5SbApiQ0JEYjNKd2IzSmhkR2x2YmpFVU1CSUdBMVVFQnd3TFUyRnVkR0VnUTJ4aGNtRXhDekFKQmdOVk" +
                                                    "JBZ01Ba05CCk1Rc3dDUVlEVlFRR0V3SlZVekJaTUJNR0J5cUdTTTQ5QWdFR0NDcUdTTTQ5QXdFSEEwSUFCTDlxK05NcDJJT2cKdGRsMWJr" +
                                                    "L3VXWjUrVEdRbThhQ2k4ejc4ZnMrZktDUTNkK3VEelhuVlRBVDJaaERDaWZ5SXVKd3ZOM3dOQnA5aQpIQlNTTUpNSnJCT2pnYnN3Z2Jnd0" +
                                                    "h3WURWUjBqQkJnd0ZvQVVJbVVNMWxxZE5JbnpnN1NWVXI5UUd6a25CcXd3ClVnWURWUjBmQkVzd1NUQkhvRVdnUTRaQmFIUjBjSE02THk5" +
                                                    "alpYSjBhV1pwWTJGMFpYTXVkSEoxYzNSbFpITmwKY25acFkyVnpMbWx1ZEdWc0xtTnZiUzlKYm5SbGJGTkhXRkp2YjNSRFFTNWpjbXd3SF" +
                                                    "FZRFZSME9CQllFRk5EbwpxdHAxMS9rdVNSZVlQSHNVWmREVjhsbE5NQTRHQTFVZER3RUIvd1FFQXdJQkJqQVNCZ05WSFJNQkFmOEVDREFH" +
                                                    "CkFRSC9BZ0VBTUFvR0NDcUdTTTQ5QkFNQ0EwY0FNRVFDSUMvOWorODRUK0h6dFZPL3NPUUJXSmJTZCsvMnVleEsKNCthQTBqY0ZCTGNwQW" +
                                                    "lBM2RoTXJGNWNENTJ0NkZxTXZBSXBqOFhkR215MmJlZWxqTEpLK3B6cGNSQT09Ci0tLS0tRU5EIENFUlRJRklDQVRFLS0tLS0KLS0tLS1C" +
                                                    "RUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSUNqakNDQWpTZ0F3SUJBZ0lVSW1VTTFscWROSW56ZzdTVlVyOVFHemtuQnF3d0NnWUlLb1pJem" +
                                                    "owRUF3SXcKYURFYU1CZ0dBMVVFQXd3UlNXNTBaV3dnVTBkWUlGSnZiM1FnUTBFeEdqQVlCZ05WQkFvTUVVbHVkR1ZzSUVOdgpjbkJ2Y21G" +
                                                    "MGFXOXVNUlF3RWdZRFZRUUhEQXRUWVc1MFlTQkRiR0Z5WVRFTE1Ba0dBMVVFQ0F3Q1EwRXhDekFKCkJnTlZCQVlUQWxWVE1CNFhEVEU0TU" +
                                                    "RVeU1URXdOREV4TVZvWERUTXpNRFV5TVRFd05ERXhNRm93YURFYU1CZ0cKQTFVRUF3d1JTVzUwWld3Z1UwZFlJRkp2YjNRZ1EwRXhHakFZ" +
                                                    "QmdOVkJBb01FVWx1ZEdWc0lFTnZjbkJ2Y21GMAphVzl1TVJRd0VnWURWUVFIREF0VFlXNTBZU0JEYkdGeVlURUxNQWtHQTFVRUNBd0NRME" +
                                                    "V4Q3pBSkJnTlZCQVlUCkFsVlRNRmt3RXdZSEtvWkl6ajBDQVFZSUtvWkl6ajBEQVFjRFFnQUVDNm5Fd01ESVlaT2ovaVBXc0N6YUVLaTcK" +
                                                    "MU9pT1NMUkZoV0dqYm5CVkpmVm5rWTR1M0lqa0RZWUwwTXhPNG1xc3lZamxCYWxUVll4RlAyc0pCSzV6bEtPQgp1ekNCdURBZkJnTlZIU0" +
                                                    "1FR0RBV2dCUWlaUXpXV3AwMGlmT0R0SlZTdjFBYk9TY0dyREJTQmdOVkhSOEVTekJKCk1FZWdSYUJEaGtGb2RIUndjem92TDJObGNuUnBa" +
                                                    "bWxqWVhSbGN5NTBjblZ6ZEdWa2MyVnlkbWxqWlhNdWFXNTAKWld3dVkyOXRMMGx1ZEdWc1UwZFlVbTl2ZEVOQkxtTnliREFkQmdOVkhRNE" +
                                                    "VGZ1FVSW1VTTFscWROSW56ZzdTVgpVcjlRR3prbkJxd3dEZ1lEVlIwUEFRSC9CQVFEQWdFR01CSUdBMVVkRXdFQi93UUlNQVlCQWY4Q0FR" +
                                                    "RXdDZ1lJCktvWkl6ajBFQXdJRFNBQXdSUUlnUVFzLzA4cnljZFBhdUNGazhVUFFYQ01BbHNsb0JlN053YVFHVGNkcGEwRUMKSVFDVXQ4U0" +
                                                    "d2eEttanBjTS96MFdQOUR2bzhoMms1ZHUxaVdEZEJrQW4rMGlpQT09Ci0tLS0tRU5EIENFUlRJRklDQVRFLS0tLS0KAA";

        private readonly string _runtimeData = "CiAgICAgICAgewogICAgICAgICAgICAiandrIiA6IHsKICAgICAgICAgICAgICAgICJrdHkiOiJFQyI" +
                                                  "sCiAgICAgICAgICAgICAgICAidXNlIjoic2lnIiwKICAgICAgICAgICAgICAgICJjcnYiOiJQLTI1Ni" +
                                                  "IsCiAgICAgICAgICAgICAgICAieCI6IjE4d0hMZUlnVzl3Vk42VkQxVHhncHF5MkxzellrTWY2Sjhua" +
                                                  "lZBaWJ2aE0iLAogICAgICAgICAgICAgICAgInkiOiJjVjRkUzRVYUxNZ1BfNGZZNGo4aXI3Y2wxVFhs" +
                                                  "RmRBZ2N4NTVvN1RrY1NBIgogICAgICAgICAgICB9CiAgICAgICAgfQogICAgICAgIAA";

        public AttestationTests(bool isAsync) : base(isAsync)
        {
        }

        [RecordedTest]
        public async Task AttestSgxEnclaveShared()
        {
            // An SGX Quote is an OpenEnclave report with the first 16 bytes stripped from it.
            var report = Base64Url.Decode(_openEnclaveReport);
            var quoteList = report.ToList();
            quoteList.RemoveRange(0, 0x10);

            byte[] binaryQuote = quoteList.ToArray();
            byte[] binaryRuntimeData = Base64Url.Decode(_runtimeData);

            var client = TestEnvironment.GetSharedAttestationClient(this);

            IReadOnlyList<AttestationSigner> signingCertificates = (await client.GetSigningCertificatesAsync()).Value;
            {
                // Collect quote and enclave held data from an SGX enclave.

                var attestationResult = await client.AttestSgxEnclaveAsync(binaryQuote, null, false, BinaryData.FromBytes(binaryRuntimeData), false);

                // Confirm that the attestation token contains the enclave held data we specified.
                CollectionAssert.AreEqual(binaryRuntimeData, attestationResult.Value.DeprecatedEnclaveHeldData);
                // VERIFY ATTESTATIONRESULT.
                // Encrypt Data using DeprecatedEnclaveHeldData
                // Send to enclave.
            }
        }

        [RecordedTest]
        public async Task AttestSgxEnclaveSharedValidateCallback()
        {
            // An SGX Quote is an OpenEnclave report with the first 16 bytes stripped from it.
            var report = Base64Url.Decode(_openEnclaveReport);
            var quoteList = report.ToList();
            quoteList.RemoveRange(0, 0x10);

            byte[] binaryQuote = quoteList.ToArray();
            byte[] binaryRuntimeData = Base64Url.Decode(_runtimeData);

            bool callbackInvoked = false;

            var client = TestEnvironment.GetSharedAttestationClient(this, new TokenValidationOptions(
                validateExpirationTime: TestEnvironment.IsTalkingToLiveServer,
                validationCallback: (attestationToken, signer) =>
                {
                    // Verify that the callback can access the enclave held data field.
                    CollectionAssert.AreEqual(binaryRuntimeData, attestationToken.GetBody<AttestationResult>().EnclaveHeldData);

                    // The MAA service always sends a Key ID for the signer.
                    Assert.IsNotNull(signer.CertificateKeyId);
                    Assert.AreEqual(TestEnvironment.SharedAttestationUrl, attestationToken.Issuer);
                    callbackInvoked = true;
                    return true;
                }));

            IReadOnlyList<AttestationSigner> signingCertificates = (await client.GetSigningCertificatesAsync()).Value;
            {
                // Collect quote and enclave held data from an SGX enclave.

                var attestationResult = await client.AttestSgxEnclaveAsync(binaryQuote, null, false, BinaryData.FromBytes(binaryRuntimeData), false);

                // Confirm that the attestation token contains the enclave held data we specified.
                CollectionAssert.AreEqual(binaryRuntimeData, attestationResult.Value.DeprecatedEnclaveHeldData);
                // VERIFY ATTESTATIONRESULT.
                // Encrypt Data using DeprecatedEnclaveHeldData
                // Send to enclave.
                Assert.IsTrue(callbackInvoked);
            }
        }

        [RecordedTest]
        public async Task AttestOpenEnclaveShared()
        {
            byte[] binaryReport = Base64Url.Decode(_openEnclaveReport);
            byte[] binaryRuntimeData = Base64Url.Decode(_runtimeData);

            var client = TestEnvironment.GetSharedAttestationClient(this);

            IReadOnlyList<AttestationSigner> signingCertificates = (await client.GetSigningCertificatesAsync()).Value;
            {
                // Collect quote and enclave held data from an SGX enclave.

                var attestationResult = await client.AttestOpenEnclaveAsync(binaryReport, null, false, BinaryData.FromBytes(binaryRuntimeData), false);

                // Confirm that the attestation token contains the enclave held data we specified.
               CollectionAssert.AreEqual(binaryRuntimeData, attestationResult.Value.DeprecatedEnclaveHeldData);
                // VERIFY ATTESTATIONRESULT.
                // Encrypt Data using DeprecatedEnclaveHeldData
                // Send to enclave.
            }
        }

        [RecordedTest]
        public async Task AttestOpenEnclaveSharedValidateCallback()
        {
            byte[] binaryReport = Base64Url.Decode(_openEnclaveReport);
            byte[] binaryRuntimeData = Base64Url.Decode(_runtimeData);
            bool callbackInvoked = false;

            var client = TestEnvironment.GetSharedAttestationClient(this, new TokenValidationOptions(
                validateExpirationTime: TestEnvironment.IsTalkingToLiveServer,
                validationCallback: (attestationToken, signer) =>
            {
                // Verify that the callback can access the enclave held data field.
                CollectionAssert.AreEqual(binaryRuntimeData, attestationToken.GetBody<AttestationResult>().EnclaveHeldData);

                // The MAA service always sends a Key ID for the signer.
                Assert.IsNotNull(signer.CertificateKeyId);
                Assert.AreEqual(TestEnvironment.SharedAttestationUrl, attestationToken.Issuer);
                callbackInvoked = true;
                return true;
            }));

            IReadOnlyList<AttestationSigner> signingCertificates = (await client.GetSigningCertificatesAsync()).Value;
            {
                // Collect quote and enclave held data from an SGX enclave.

                var attestationResult = await client.AttestOpenEnclaveAsync(binaryReport, null, false, BinaryData.FromBytes(binaryRuntimeData), false);

                // Confirm that the attestation token contains the enclave held data we specified.
                CollectionAssert.AreEqual(binaryRuntimeData, attestationResult.Value.DeprecatedEnclaveHeldData);
                // VERIFY ATTESTATIONRESULT.
                // Encrypt Data using DeprecatedEnclaveHeldData
                // Send to enclave.
                Assert.IsTrue(callbackInvoked);
            }
        }
    }
}