text:
#include "MemoryPowerModel.h"

#include <stdint.h>

#include <cmath>  // For pow
#include <iostream>  // fmtflags

using namespace std;
using namespace Data;

// Calculate energy and average power consumption for the given command trace

void MemoryPowerModel::power_calc(const MemorySpecification& memSpec,
                                  const CommandAnalysis& c,
                                  int term)
{
  const MemTimingSpec& t                 = memSpec.memTimingSpec;
  const MemArchitectureSpec& memArchSpec = memSpec.memArchSpec;
  const MemPowerSpec&  mps               = memSpec.memPowerSpec;

  energy.act_energy          = 0.0;
  energy.pre_energy          = 0.0;
  energy.read_energy         = 0.0;
  energy.write_energy        = 0.0;
  energy.ref_energy          = 0.0;
  energy.act_stdby_energy    = 0.0;
  energy.pre_stdby_energy    = 0.0;
  energy.idle_energy_act     = 0.0;
  energy.idle_energy_pre     = 0.0;
  energy.total_energy        = 0.0;
  energy.f_act_pd_energy     = 0.0;
  energy.f_pre_pd_energy     = 0.0;
  energy.s_act_pd_energy     = 0.0;
  energy.s_pre_pd_energy     = 0.0;
  energy.sref_energy         = 0.0;
  energy.sref_ref_energy     = 0.0;
  energy.sref_ref_act_energy = 0.0;
  energy.sref_ref_pre_energy = 0.0;
  energy.spup_energy         = 0.0;
  energy.spup_ref_energy     = 0.0;
  energy.spup_ref_act_energy = 0.0;
  energy.spup_ref_pre_energy = 0.0;
  energy.pup_act_energy      = 0.0;
  energy.pup_pre_energy      = 0.0;
  power.IO_power             = 0.0;
  power.WR_ODT_power         = 0.0;
  power.TermRD_power         = 0.0;
  power.TermWR_power         = 0.0;
  energy.read_io_energy      = 0.0;
  energy.write_term_energy   = 0.0;
  energy.read_oterm_energy   = 0.0;
  energy.write_oterm_energy  = 0.0;
  energy.io_term_energy      = 0.0;

  // How long a single burst takes, measured in command-clock cycles.
  int64_t burstCc = memArchSpec.burstLength / memArchSpec.dataRate;

  // IO and Termination Power measures are included, if required.
  if (term) {
    io_term_power(memSpec);

    // memArchSpec.width represents the number of data (dq) pins.
    // 1 DQS pin is associated with every data byte
    int64_t dqPlusDqsBits = memArchSpec.width + memArchSpec.width / 8;
    // 1 DQS and 1 DM pin is associated with every data byte
    int64_t dqPlusDqsPlusMaskBits = memArchSpec.width + memArchSpec.width / 8 + memArchSpec.width / 8;
    // Size of one clock period for the data bus.
    double ddrPeriod = t.clkPeriod / static_cast<double>(memArchSpec.dataRate);

    // Read IO power is consumed by each DQ (data) and DQS (data strobe) pin
    energy.read_io_energy = calcIoTermEnergy(c.numberofreads * memArchSpec.burstLength,
                                             ddrPeriod,
                                             power.IO_power,
                                             dqPlusDqsBits);

    // Write ODT power is consumed by each DQ (data), DQS (data strobe) and DM
    energy.write_term_energy = calcIoTermEnergy(c.numberofwrites * memArchSpec.burstLength,
                                                ddrPeriod,
                                                power.WR_ODT_power,
                                                dqPlusDqsPlusMaskBits);

    if (memArchSpec.nbrOfRanks > 1) {
      // Termination power consumed in the idle rank during reads on the active
      // rank by each DQ (data) and DQS (data strobe) pin.
      energy.read_oterm_energy = calcIoTermEnergy(c.numberofreads * memArchSpec.burstLength,
                                                  ddrPeriod,
                                                  power.TermRD_power,
                                                  dqPlusDqsBits);

      // Termination power consumed in the idle rank during writes on the active
      // rank by each DQ (data), DQS (data strobe) and DM (data mask) pin.
      energy.write_oterm_energy = calcIoTermEnergy(c.numberofwrites * memArchSpec.burstLength,
                                                   ddrPeriod,
                                                   power.TermWR_power,
                                                   dqPlusDqsPlusMaskBits);
    }

    // Sum of all IO and termination energy
    energy.io_term_energy = energy.read_io_energy + energy.write_term_energy
                            + energy.read_oterm_energy + energy.write_oterm_energy;
  }

  total_cycles = c.actcycles + c.precycles +
                 c.f_act_pdcycles + c.f_pre_pdcycles +
                 c.s_act_pdcycles + c.s_pre_pdcycles + c.sref_cycles
                 + c.sref_ref_act_cycles + c.sref_ref_pre_cycles +
                 c.spup_ref_act_cycles + c.spup_ref_pre_cycles;

  EnergyDomain vdd0Domain(mps.vdd, t.clkPeriod);

  energy.act_energy       = vdd0Domain.calcTivEnergy(c.numberofacts   * t.RAS          , mps.idd0 - mps.idd3n);
  energy.pre_energy       = vdd0Domain.calcTivEnergy(c.numberofpres   * (t.RC - t.RAS) , mps.idd0 - mps.idd2n);
  energy.read_energy      = vdd0Domain.calcTivEnergy(c.numberofreads  * burstCc        , mps.idd4r - mps.idd3n);
  energy.write_energy     = vdd0Domain.calcTivEnergy(c.numberofwrites * burstCc        , mps.idd4w - mps.idd3n);
  energy.ref_energy       = vdd0Domain.calcTivEnergy(c.numberofrefs   * t.RFC          , mps.idd5 - mps.idd3n);
  energy.pre_stdby_energy = vdd0Domain.calcTivEnergy(c.precycles, mps.idd2n);
  energy.act_stdby_energy = vdd0Domain.calcTivEnergy(c.actcycles, mps.idd3n);
  // Idle energy in the active standby clock cycles
  energy.idle_energy_act  = vdd0Domain.calcTivEnergy(c.idlecycles_act, mps.idd3n);
  // Idle energy in the precharge standby clock cycles
  energy.idle_energy_pre  = vdd0Domain.calcTivEnergy(c.idlecycles_pre, mps.idd2n);
  // fast-exit active power-down cycles energy
  energy.f_act_pd_energy  = vdd0Domain.calcTivEnergy(c.f_act_pdcycles, mps.idd3p1);
  // fast-exit precharged power-down cycles energy
  energy.f_pre_pd_energy  = vdd0Domain.calcTivEnergy(c.f_pre_pdcycles, mps.idd2p1);
  // slow-exit active power-down cycles energy
  energy.s_act_pd_energy  = vdd0Domain.calcTivEnergy(c.s_act_pdcycles, mps.idd3p0);
  // slow-exit precharged power-down cycles energy
  energy.s_pre_pd_energy  = vdd0Domain.calcTivEnergy(c.s_pre_pdcycles, mps.idd2p0);

  // self-refresh cycles energy including a refresh per self-refresh entry
  energy.sref_energy = engy_sref(mps.idd6, mps.idd3n,
                                 mps.idd5, mps.vdd,
                                 static_cast<double>(c.sref_cycles), static_cast<double>(c.sref_ref_act_cycles),
                                 static_cast<double>(c.sref_ref_pre_cycles), static_cast<double>(c.spup_ref_act_cycles),
                                 static_cast<double>(c.spup_ref_pre_cycles), t.clkPeriod);

  // background energy during active auto-refresh cycles in self-refresh
  energy.sref_ref_act_energy = vdd0Domain.calcTivEnergy(c.sref_ref_act_cycles, mps.idd3p0);
  // background energy during precharged auto-refresh cycles in self-refresh
  energy.sref_ref_pre_energy = vdd0Domain.calcTivEnergy(c.sref_ref_pre_cycles, mps.idd2p0);
  // background energy during active auto-refresh cycles in self-refresh exit
  energy.spup_ref_act_energy = vdd0Domain.calcTivEnergy(c.spup_ref_act_cycles, mps.idd3n);
  // background energy during precharged auto-refresh cycles in self-refresh exit
  energy.spup_ref_pre_energy = vdd0Domain.calcTivEnergy(c.spup_ref_pre_cycles, mps.idd2n);
  // self-refresh power-up cycles energy -- included
  energy.spup_energy         = vdd0Domain.calcTivEnergy(c.spup_cycles, mps.idd2n);
  // active power-up cycles energy - same as active standby -- included
  energy.pup_act_energy      = vdd0Domain.calcTivEnergy(c.pup_act_cycles, mps.idd3n);
  // precharged power-up cycles energy - same as precharged standby -- included
  energy.pup_pre_energy      = vdd0Domain.calcTivEnergy(c.pup_pre_cycles, mps.idd2n);

  // similar equations as before to support multiple voltage domains in LPDDR2
  // and WIDEIO memories
  if (memArchSpec.twoVoltageDomains) {
    EnergyDomain vdd2Domain(mps.vdd2, t.clkPeriod);

    energy.act_energy       += vdd2Domain.calcTivEnergy(c.numberofacts   * t.RAS          , mps.idd02 - mps.idd3n2);
    energy.pre_energy       += vdd2Domain.calcTivEnergy(c.numberofpres   * (t.RC - t.RAS) , mps.idd02 - mps.idd2n2);
    energy.read_energy      += vdd2Domain.calcTivEnergy(c.numberofreads  * burstCc        , mps.idd4r2 - mps.idd3n2);
    energy.write_energy     += vdd2Domain.calcTivEnergy(c.numberofwrites * burstCc        , mps.idd4w2 - mps.idd3n2);
    energy.ref_energy       += vdd2Domain.calcTivEnergy(c.numberofrefs   * t.RFC          , mps.idd52 - mps.idd3n2);
    energy.pre_stdby_energy += vdd2Domain.calcTivEnergy(c.precycles, mps.idd2n2);
    energy.act_stdby_energy += vdd2Domain.calcTivEnergy(c.actcycles, mps.idd3n2);
    // Idle energy in the active standby clock cycles
    energy.idle_energy_act  += vdd2Domain.calcTivEnergy(c.idlecycles_act, mps.idd3n2);
    // Idle energy in the precharge standby clock cycles
    energy.idle_energy_pre  += vdd2Domain.calcTivEnergy(c.idlecycles_pre, mps.idd2n2);
    // fast-exit active power-down cycles energy
    energy.f_act_pd_energy  += vdd2Domain.calcTivEnergy(c.f_act_pdcycles, mps.idd3p12);
    // fast-exit precharged power-down cycles energy
    energy.f_pre_pd_energy  += vdd2Domain.calcTivEnergy(c.f_pre_pdcycles, mps.idd2p12);
    // slow-exit active power-down cycles energy
    energy.s_act_pd_energy  += vdd2Domain.calcTivEnergy(c.s_act_pdcycles, mps.idd3p02);
    // slow-exit precharged power-down cycles energy
    energy.s_pre_pd_energy  += vdd2Domain.calcTivEnergy(c.s_pre_pdcycles, mps.idd2p02);

    energy.sref_energy      += engy_sref(mps.idd62, mps.idd3n2,
                                         mps.idd52, mps.vdd2,
                                         static_cast<double>(c.sref_cycles), static_cast<double>(c.sref_ref_act_cycles),
                                         static_cast<double>(c.sref_ref_pre_cycles), static_cast<double>(c.spup_ref_act_cycles),
                                         static_cast<double>(c.spup_ref_pre_cycles), t.clkPeriod);

    // background energy during active auto-refresh cycles in self-refresh
    energy.sref_ref_act_energy += vdd2Domain.calcTivEnergy(c.sref_ref_act_cycles, mps.idd3p02);
    // background energy during precharged auto-refresh cycles in self-refresh
    energy.sref_ref_pre_energy += vdd2Domain.calcTivEnergy(c.sref_ref_pre_cycles, mps.idd2p02);
    // background energy during active auto-refresh cycles in self-refresh exit
    energy.spup_ref_act_energy += vdd2Domain.calcTivEnergy(c.spup_ref_act_cycles, mps.idd3n2);
    // background energy during precharged auto-refresh cycles in self-refresh exit
    energy.spup_ref_pre_energy += vdd2Domain.calcTivEnergy(c.spup_ref_pre_cycles, mps.idd2n2);
    // self-refresh power-up cycles energy -- included
    energy.spup_energy         += vdd2Domain.calcTivEnergy(c.spup_cycles, mps.idd2n2);
    // active power-up cycles energy - same as active standby -- included
    energy.pup_act_energy      += vdd2Domain.calcTivEnergy(c.pup_act_cycles, mps.idd3n2);
    // precharged power-up cycles energy - same as precharged standby -- included
    energy.pup_pre_energy      += vdd2Domain.calcTivEnergy(c.pup_pre_cycles, mps.idd2n2);
  }

  // auto-refresh energy during self-refresh cycles
  energy.sref_ref_energy = energy.sref_ref_act_energy + energy.sref_ref_pre_energy;

  // auto-refresh energy during self-refresh exit cycles
  energy.spup_ref_energy = energy.spup_ref_act_energy + energy.spup_ref_pre_energy;

  // adding all energy components for the active rank and all background and idle
  // energy components for both ranks (in a dual-rank system)
  energy.total_energy = energy.act_energy + energy.pre_energy + energy.read_energy +
                        energy.write_energy + energy.ref_energy + energy.io_term_energy +
                        static_cast<double>(memArchSpec.nbrOfRanks) * (energy.act_stdby_energy +
                                                  energy.pre_stdby_energy + energy.sref_energy +
                                                  energy.f_act_pd_energy + energy.f_pre_pd_energy + energy.s_act_pd_energy
                                                  + energy.s_pre_pd_energy + energy.sref_ref_energy + energy.spup_ref_energy);

  // Calculate the average power consumption
  power.average_power = energy.total_energy / (static_cast<double>(total_cycles) * t.clkPeriod);
} // MemoryPowerModel::power_calc

void MemoryPowerModel::power_print(const MemorySpecification& memSpec, int term, const CommandAnalysis& c) const
{
  const MemTimingSpec& memTimingSpec     = memSpec.memTimingSpec;
  const MemArchitectureSpec& memArchSpec = memSpec.memArchSpec;
  const uint64_t nRanks = static_cast<uint64_t>(memArchSpec.nbrOfRanks);
  const char eUnit[] = " pJ";

  ios_base::fmtflags flags = cout.flags();
  streamsize precision = cout.precision();
  cout.precision(0);
  cout << "* Trace Details:" << fixed << endl
       << endl << "#ACT commands: "                 << c.numberofacts
       << endl << "#RD + #RDA commands: "           << c.numberofreads
       << endl << "#WR + #WRA commands: "           << c.numberofwrites
  /* #PRE commands (precharge all counts a number of #PRE commands equal to the number of active banks) */
       << endl << "#PRE (+ PREA) commands: "        << c.numberofpres
       << endl << "#REF commands: "                 << c.numberofrefs
       << endl << "#Active Cycles: "                << c.actcycles
       << endl << "  #Active Idle Cycles: "         << c.idlecycles_act
       << endl << "  #Active Power-Up Cycles: "     << c.pup_act_cycles
       << endl << "    #Auto-Refresh Active cycles during Self-Refresh Power-Up: " << c.spup_ref_act_cycles
       << endl << "#Precharged Cycles: "            << c.precycles
       << endl << "  #Precharged Idle Cycles: "     << c.idlecycles_pre
       << endl << "  #Precharged Power-Up Cycles: " << c.pup_pre_cycles
       << endl << "    #Auto-Refresh Precharged cycles during Self-Refresh Power-Up: " << c.spup_ref_pre_cycles
       << endl << "  #Self-Refresh Power-Up Cycles: "                          << c.spup_cycles
       << endl << "Total Idle Cycles (Active + Precharged): "                  << c.idlecycles_act + c.idlecycles_pre
       << endl << "#Power-Downs: "                                             << c.f_act_pdns +  c.s_act_pdns + c.f_pre_pdns + c.s_pre_pdns
       << endl << "  #Active Fast-exit Power-Downs: "                          << c.f_act_pdns
       << endl << "  #Active Slow-exit Power-Downs: "                          << c.s_act_pdns
       << endl << "  #Precharged Fast-exit Power-Downs: "                      << c.f_pre_pdns
       << endl << "  #Precharged Slow-exit Power-Downs: "                      << c.s_pre_pdns
       << endl << "#Power-Down Cycles: "                                       << c.f_act_pdcycles + c.s_act_pdcycles + c.f_pre_pdcycles + c.s_pre_pdcycles
       << endl << "  #Active Fast-exit Power-Down Cycles: "                    << c.f_act_pdcycles
       << endl << "  #Active Slow-exit Power-Down Cycles: "                    << c.s_act_pdcycles
       << endl << "    #Auto-Refresh Active cycles during Self-Refresh: "      << c.sref_ref_act_cycles
       << endl << "  #Precharged Fast-exit Power-Down Cycles: "                << c.f_pre_pdcycles
       << endl << "  #Precharged Slow-exit Power-Down Cycles: "                << c.s_pre_pdcycles
       << endl << "    #Auto-Refresh Precharged cycles during Self-Refresh: "  << c.sref_ref_pre_cycles
       << endl << "#Auto-Refresh Cycles: "                                     << c.numberofrefs * memTimingSpec.RFC
       << endl << "#Self-Refreshes: "                                          << c.numberofsrefs
       << endl << "#Self-Refresh Cycles: "                                     << c.sref_cycles
       << endl << "----------------------------------------"
       << endl << "Total Trace Length (clock cycles): " << total_cycles
       << endl << "----------------------------------------" << endl;

  cout.precision(2);
  cout << endl << "* Trace Power and Energy Estimates:" << endl
       << endl << "ACT Cmd Energy: " << energy.act_energy   << eUnit
       << endl << "PRE Cmd Energy: " << energy.pre_energy   << eUnit
       << endl << "RD Cmd Energy: "  << energy.read_energy  << eUnit
       << endl << "WR Cmd Energy: "  << energy.write_energy << eUnit;

  if (term) {
    cout << "RD I/O Energy: " << energy.read_io_energy << eUnit << endl;
    // No Termination for LPDDR/2/3 and DDR memories
    if (memSpec.memArchSpec.termination) {
      cout << "WR Termination Energy: " << energy.write_term_energy << eUnit << endl;
    }

    if (nRanks > 1 && memSpec.memArchSpec.termination) {
      cout <<         "RD Termination Energy (Idle rank): " << energy.read_oterm_energy << eUnit
           << endl << "WR Termination Energy (Idle rank): " << energy.write_oterm_energy << eUnit << endl;
    }
  }

  double nRanksDouble = static_cast<double>(nRanks);

  cout <<         "ACT Stdby Energy: "                                                                      << nRanksDouble * energy.act_stdby_energy << eUnit
       << endl << "  Active Idle Energy: "                                                                  << nRanksDouble * energy.idle_energy_act << eUnit
       << endl << "  Active Power-Up Energy: "                                                              << nRanksDouble * energy.pup_act_energy << eUnit
       << endl << "    Active Stdby Energy during Auto-Refresh cycles in Self-Refresh Power-Up: "           << nRanksDouble * energy.spup_ref_act_energy << eUnit
       << endl << "PRE Stdby Energy: "                                                                      << nRanksDouble * energy.pre_stdby_energy << eUnit
       << endl << "  Precharge Idle Energy: "                                                               << nRanksDouble * energy.idle_energy_pre << eUnit
       << endl << "  Precharged Power-Up Energy: "                                                          << nRanksDouble * energy.pup_pre_energy << eUnit
       << endl << "    Precharge Stdby Energy during Auto-Refresh cycles in Self-Refresh Power-Up: "        << nRanksDouble * energy.spup_ref_pre_energy << eUnit
       << endl << "  Self-Refresh Power-Up Energy: "                                                        << nRanksDouble * energy.spup_energy << eUnit
       << endl << "Total Idle Energy (Active + Precharged): "                                               << nRanksDouble * (energy.idle_energy_act + energy.idle_energy_pre) << eUnit
       << endl << "Total Power-Down Energy: "                                                               << nRanksDouble * (energy.f_act_pd_energy + energy.f_pre_pd_energy + energy.s_act_pd_energy + energy.s_pre_pd_energy) << eUnit
       << endl << "  Fast-Exit Active Power-Down Energy: "                                                  << nRanksDouble * energy.f_act_pd_energy << eUnit
       << endl << "  Slow-Exit Active Power-Down Energy: "                                                  << nRanksDouble * energy.s_act_pd_energy << eUnit
       << endl << "    Slow-Exit Active Power-Down Energy during Auto-Refresh cycles in Self-Refresh: "     << nRanksDouble * energy.sref_ref_act_energy << eUnit
       << endl << "  Fast-Exit Precharged Power-Down Energy: "                                              << nRanksDouble * energy.f_pre_pd_energy << eUnit
       << endl << "  Slow-Exit Precharged Power-Down Energy: "                                              << nRanksDouble * energy.s_pre_pd_energy << eUnit
       << endl << "    Slow-Exit Precharged Power-Down Energy during Auto-Refresh cycles in Self-Refresh: " << nRanksDouble * energy.sref_ref_pre_energy << eUnit
       << endl << "Auto-Refresh Energy: "                                                                   << energy.ref_energy << eUnit
       << endl << "Self-Refresh Energy: "                                                                   << nRanksDouble * energy.sref_energy << eUnit
       << endl << "----------------------------------------"
       << endl << "Total Trace Energy: "                                                                    << energy.total_energy << eUnit
       << endl << "Average Power: "                                                                         << power.average_power << " mW"
       << endl << "----------------------------------------" << endl;

  cout.flags(flags);
  cout.precision(precision);
} // MemoryPowerModel::power_print

// Self-refresh active energy estimation (not including background energy)
double MemoryPowerModel::engy_sref(double idd6, double idd3n, double idd5,
                                   double vdd, double sref_cycles, double sref_ref_act_cycles,
                                   double sref_ref_pre_cycles, double spup_ref_act_cycles,
                                   double spup_ref_pre_cycles, double clk)
{
  double sref_energy;

  sref_energy = ((idd6 * sref_cycles) + ((idd5 - idd3n) * (sref_ref_act_cycles
                                                           + spup_ref_act_cycles + sref_ref_pre_cycles + spup_ref_pre_cycles)))
                * vdd * clk;
  return sref_energy;
}

// IO and Termination power calculation based on Micron Power Calculators
// Absolute power measures are obtained from Micron Power Calculator (mentioned in mW)
void MemoryPowerModel::io_term_power(const MemorySpecification& memSpec)
{
  const MemTimingSpec& memTimingSpec     = memSpec.memTimingSpec;
  const MemArchitectureSpec& memArchSpec = memSpec.memArchSpec;
  const MemPowerSpec&  memPowerSpec      = memSpec.memPowerSpec;

  power.IO_power     = memPowerSpec.ioPower;    // in mW
  power.WR_ODT_power = memPowerSpec.wrOdtPower; // in mW

  if (memArchSpec.nbrOfRanks > 1) {
    power.TermRD_power = memPowerSpec.termRdPower; // in mW
    power.TermWR_power = memPowerSpec.termWrPower; // in mW
  }

  if (memPowerSpec.capacitance != 0.0) {
    // If capacity is given, then IO Power depends on DRAM clock frequency.
    power.IO_power = memPowerSpec.capacitance * 0.5 * pow(memPowerSpec.vdd2, 2.0) * memTimingSpec.clkMhz * 1000000;
  }
} // MemoryPowerModel::io_term_power

double MemoryPowerModel::calcIoTermEnergy(int64_t cycles, double period, double power, int64_t numBits) const
{
  return static_cast<double>(cycles) * period * power * static_cast<double>(numBits);
}

// time (t) * current (I) * voltage (V) energy calculation
double EnergyDomain::calcTivEnergy(int64_t cycles, double current) const
{
  return static_cast<double>(cycles) * clkPeriod * current * voltage;
}


text:
package com.countrygamer.pvz.client.block.tile;

import net.minecraft.client.renderer.entity.RenderItem;
import net.minecraft.client.renderer.entity.RenderManager;
import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;

import org.lwjgl.opengl.GL11;

import com.countrygamer.core.Base.common.tileentity.TileEntityInventoryBase;
import com.countrygamer.core.common.lib.CoreUtil;
import com.countrygamer.pvz.PvZ;
import com.countrygamer.pvz.block.tile.TileEntityGreenhouse;
import com.countrygamer.pvz.lib.Resources;

import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;

public class RenderGreenhouse extends TileEntitySpecialRenderer {

	private ModelGreenhouse aModel;

	private final RenderItem inputRender, modify1Render, outputRender;

	public RenderGreenhouse() {
		this.aModel = new ModelGreenhouse();

		RenderItem basicRender = new RenderItem() {
			@Override
			public byte getMiniBlockCount(ItemStack stack, byte original) {
				return 1;
			}

			@Override
			public byte getMiniItemCount(ItemStack stack, byte original) {
				return 1;
			}

			@Override
			public boolean shouldBob() {
				return true;
			}
		};

		this.inputRender = basicRender;
		this.inputRender.setRenderManager(RenderManager.instance);
		this.modify1Render = basicRender;
		this.modify1Render.setRenderManager(RenderManager.instance);
		this.outputRender = basicRender;
		this.outputRender.setRenderManager(RenderManager.instance);

	}

	@SideOnly(Side.CLIENT)
	public void renderAModelAt(TileEntityGreenhouse tileEnt, double x,
			double y, double z, float f) {
		tileEnt.getWorldObj().scheduleBlockUpdate(tileEnt.xCoord,
				tileEnt.yCoord, tileEnt.zCoord, PvZ.greenhouse, 10);

		GL11.glPushMatrix();
		int metadata = tileEnt.getBlockMetadata();
		int rotationAngleModel = 0;
		if (metadata % 4 == 0) {
			rotationAngleModel = 0;
		}
		if (metadata % 4 == 1) {
			rotationAngleModel = 270;
		}
		if (metadata % 4 == 2) {
			rotationAngleModel = 180;
		}
		if (metadata % 4 == 3) {
			rotationAngleModel = 90;
		}
		GL11.glTranslatef((float) x + 0.5F, (float) y + 1.5F, (float) z + 0.5F);

		GL11.glRotatef(180.0F, 0.0F, 0.0F, 1.0F);
		GL11.glRotatef(rotationAngleModel, 0.0F, 1.0F, 0.0F);

		this.bindTexture(Resources.greenhouse);

		this.aModel.renderModel(0.0625F);
		GL11.glPopMatrix();

		/**
		 * Render the ghost item inside of the Block, slowly spinning Taken from
		 * Pahimar's EE3 Aludel model
		 */
		ItemStack input = tileEnt.getStackInSlot(0);
		ItemStack mod1 = tileEnt.getStackInSlot(1);
		ItemStack mod2 = tileEnt.getStackInSlot(2);
		ItemStack output = tileEnt.getStackInSlot(4);
		GL11.glPushMatrix();
		if (mod1 != null) {
			this.renderItem(tileEnt, this.modify1Render, mod1,
					(float) x + 0.5F, (float) y + 1.0F, (float) z + 0.5F);
		}
		GL11.glPopMatrix();
		GL11.glPushMatrix();
		if (output != null) {
			this.renderItem(tileEnt, this.outputRender, output,
					(float) x + 0.5F, (float) y + 0.5F, (float) z + 0.5F);
		}
		GL11.glPopMatrix();

	}

	@SideOnly(Side.CLIENT)
	public void renderTileEntityAt(TileEntity tileentity, double x, double y,
			double z, float f) {
		renderAModelAt((TileEntityGreenhouse) tileentity, x, y, z, f);
	}

	private void renderItem(TileEntityInventoryBase tileEnt,
			RenderItem itemRender, ItemStack stack, float x, float y, float z) {
		GL11.glPushMatrix();
		float scaleFactor = CoreUtil.getGhostItemScaleFactor(this.outputRender,
				stack);
		float rotationAngle = (float) (720.0 * (System.currentTimeMillis() & 0x3FFFL) / 0x3FFFL);

		EntityItem ghostEntityItem = new EntityItem(tileEnt.getWorldObj());
		ghostEntityItem.hoverStart = 0.0F;
		ghostEntityItem.setEntityItemStack(stack);

		GL11.glTranslatef(x, y, z);
		GL11.glScalef(scaleFactor, scaleFactor, scaleFactor);
		GL11.glRotatef(rotationAngle, 0.0F, 1.0F, 0.0F);

		itemRender.doRender(ghostEntityItem, 0, 0, 0, 0, 0);
		GL11.glPopMatrix();
	}

}

redpajama_set_name: RedPajamaGithub


text:
package org.openspaces.core.map;

import com.j_spaces.core.client.SpaceURL;
import com.j_spaces.javax.cache.EvictionStrategy;
import com.j_spaces.map.eviction.NoneEvictionStrategy;

/**
 * A bean holding local cache support (when using Map API) configuration.
 *
 * @author kimchy
 */
public class LocalCacheSupport {

    public static final String LOCAL_CACHE_UPDATE_MODE_PUSH = "push";

    public static final String LOCAL_CACHE_UPDATE_MODE_PULL = "pull";

    private int localCacheUpdateMode = SpaceURL.UPDATE_MODE_PULL;

    private boolean versioned = false;

    private EvictionStrategy evictionStrategy;

    private boolean putFirst = true;

    private int sizeLimit = 100000;

    /**
     * Controls if this local cache will be versioned or not. Note, when settings this to
     * true, make sure that the actual space is versioned as well.
     */
    public void setVersioned(boolean versioned) {
        this.versioned = versioned;
    }

    /**
     * Controls if this local cache will be versioned or not. Note, when settings this to
     * true, make sure that the actual space is versioned as well.
     */
    public boolean isVersioned() {
        return versioned;
    }

    /**
     * Sets the eviction strategy for the local cache.
     */
    public void setEvictionStrategy(EvictionStrategy evictionStrategy) {
        this.evictionStrategy = evictionStrategy;
    }

    /**
     * Sets the eviction strategy for the local cache.
     */
    public EvictionStrategy getEvictionStrategy() {
        if (evictionStrategy == null) {
            return new NoneEvictionStrategy();
        }
        return evictionStrategy;
    }

    /**
     * If set to {@link SpaceURL#UPDATE_MODE_PULL} (1) each update triggers an
     * invalidation event at every cache instance. The invalidate event marks the object in the
     * local cache instances as invalid. Therefore, an attempt to read this object triggers a reload
     * process in the master space. This configuration is useful in cases where objects are updated
     * frequently, but the updated value is required by the application less frequently.
     *
     *
If set to {@link SpaceURL#UPDATE_MODE_PUSH} (2) the master pushes the
     * updates to the local cache, which holds a reference to the same updated object.
     *
     * @see #setUpdateModeName(String)
     */
    public void setUpdateMode(int localCacheUpdateMode) {
        this.localCacheUpdateMode = localCacheUpdateMode;
    }

    /**
     * If set to {@link SpaceURL#UPDATE_MODE_PULL} (1) each update triggers an
     * invalidation event at every cache instance. The invalidate event marks the object in the
     * local cache instances as invalid. Therefore, an attempt to read this object triggers a reload
     * process in the master space. This configuration is useful in cases where objects are updated
     * frequently, but the updated value is required by the application less frequently.
     *
     *
If set to {@link SpaceURL#UPDATE_MODE_PUSH} (2) the master pushes the
     * updates to the local cache, which holds a reference to the same updated object.
     *
     * @see #setUpdateMode(int)
     */
    public int getLocalCacheUpdateMode() {
        return localCacheUpdateMode;
    }

    /**
     * Allows to set the local cache update mode using a descriptive name instead of integer
     * constants using {@link #setUpdateMode(int) localCacheUpdateMode}. Accepts either
     * push or pull.
     *
     * @see #setUpdateMode (int)
     */
    public void setUpdateModeName(String localCacheUpdateModeName) {
        if (LOCAL_CACHE_UPDATE_MODE_PULL.equalsIgnoreCase(localCacheUpdateModeName)) {
            setUpdateMode(SpaceURL.UPDATE_MODE_PULL);
        } else if (LOCAL_CACHE_UPDATE_MODE_PUSH.equalsIgnoreCase(localCacheUpdateModeName)) {
            setUpdateMode(SpaceURL.UPDATE_MODE_PUSH);
        } else {
            throw new IllegalArgumentException("Wrong localCacheUpdateModeName [" + localCacheUpdateModeName + "], "
                    + "should be either '" + LOCAL_CACHE_UPDATE_MODE_PULL + "' or '" + LOCAL_CACHE_UPDATE_MODE_PUSH
                    + "'");
        }
    }

    /**
     * When performing a put operation, you may perform the put operation both into the local cache and the master
     * space. This will speed up subsequent get operations. Default to true.
     */
    public void setPutFirst(boolean putFirst) {
        this.putFirst = putFirst;
    }

    /**
     * When performing a put operation, you may perform the put operation both into the local cache and the master
     * space. This will speed up subsequent get operations. Default to true.
     */
    public boolean isPutFirst() {
        return putFirst;
    }

    /**
     * Sets the size limit of the local cache. Default to 100000.
     */
    public void setSizeLimit(int sizeLimit) {
        this.sizeLimit = sizeLimit;
    }

    /**
     * Sets the size limit of the local cache. Default to 100000.
     */
    public int getSizeLimit() {
        return sizeLimit;
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="240dp"
    android:layout_height="wrap_content"
    android:background="@drawable/codess_update_dialog_bg">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="发现更新"
        android:textColor="@color/colorAccent"
        android:layout_margin="8dp"
        android:tag="beta_title"
        android:gravity="center_horizontal"
        android:textSize="18sp"/>

    <View
        android:layout_width="match_parent"
        android:layout_height="2px"
        android:background="@color/colorAccent" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="更新日志"
        android:textColor="#333333"
        android:layout_margin="8dp"
        android:tag="beta_upgrade_info" />

    <TextView
        android:id="@+id/update_detail"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="更新日志"
        android:textColor="#333333"
        android:layout_margin="8dp"
        android:tag="beta_upgrade_feature" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <Button
            android:id="@+id/cancel"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:background="@null"
            android:text="取消"
            android:tag="beta_cancel_button"
            android:textColor="#999999"
            style="@style/Base.Widget.AppCompat.ButtonBar"/>

        <Button
            android:id="@+id/ok"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:background="@null"
            android:text="确定"
            android:tag="beta_confirm_button"
            android:textColor="?attr/colorAccent"
            style="@style/Base.Widget.AppCompat.ButtonBar"/>
    </LinearLayout>
</LinearLayout>


text:
/**
 * isCall tells us if the string indicates a function call
 * @param {string} str
 * @return {boolean}
 */
'use strict';

Object.defineProperty(exports, '__esModule', {
    value: true
});
exports.isCall = isCall;

function isCall(str) {

    str = str || '';

    if (str.indexOf('(') > -1) if (str.indexOf(')') > -1) return true;
}
//# sourceMappingURL=index.js.map


text:
package com.google.android.demos.jamendo.widget;

import android.content.Context;
import android.database.DataSetObserver;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListAdapter;

/**
 * A {@link ListAdapter} that contains a single {@link View}.
 */
public class SingletonListAdapter implements ListAdapter {

    private final int mLayout;

    private final Object mItem;

    private final boolean mEnabled;

    private final long mItemId;

    /**
     * Constructor.
     *
     * @param layout the layout to inflate in
     *            {@link #getView(int, View, ViewGroup)}
     * @param data the {@link Object} to return from {@link #getItem(int)}
     * @param itemId the ID to return from {@link #getItemId(int)}
     * @param isSelectable {@code true} if the item can be selected, {@code
     *            false} otherwise.
     */
    public SingletonListAdapter(int layout, Object data, long itemId, boolean isSelectable) {
        mLayout = layout;
        mItem = data;
        mEnabled = isSelectable;
        mItemId = itemId;
    }

    /** {@inheritDoc} */
    public boolean areAllItemsEnabled() {
        return mEnabled;
    }

    /** {@inheritDoc} */
    public boolean isEnabled(int position) {
        return mEnabled;
    }

    /** {@inheritDoc} */
    public int getCount() {
        return 1;
    }

    /** {@inheritDoc} */
    public Object getItem(int position) {
        return mItem;
    }

    /** {@inheritDoc} */
    public long getItemId(int position) {
        return mItemId;
    }

    /** {@inheritDoc} */
    public int getItemViewType(int position) {
        // This class manages its own View instance
        return AdapterView.ITEM_VIEW_TYPE_IGNORE;
    }

    /** {@inheritDoc} */
    public View getView(int position, View convertView, ViewGroup parent) {
        Context context = parent.getContext();
        LayoutInflater inflater = LayoutInflater.from(context);
        return inflater.inflate(mLayout, parent, false);
    }

    /** {@inheritDoc} */
    public int getViewTypeCount() {
        return 1;
    }

    /** {@inheritDoc} */
    public boolean hasStableIds() {
        return mItemId > 0L;
    }

    /** {@inheritDoc} */
    public boolean isEmpty() {
        return false;
    }

    /** {@inheritDoc} */
    public void registerDataSetObserver(DataSetObserver observer) {
        // Data never changes
    }

    /** {@inheritDoc} */
    public void unregisterDataSetObserver(DataSetObserver observer) {
        // Data never changes
    }
}


text:
<?php
namespace Book\Form;

use Zend\Form\Form;

class SelectForm extends Form{
    public function __construct($name = null)
    {
        // We will ignore the name provided to the constructor
        parent::__construct('select');

    }
}


text:
package org.jetbrains.plugins.groovy.lang.resolve.processors;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrMethodCall;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression;
import org.jetbrains.plugins.groovy.lang.resolve.ResolveUtil;

import java.util.EnumSet;

import static org.jetbrains.plugins.groovy.lang.resolve.processors.GroovyResolveKind.*;

public final class GroovyResolverProcessorBuilder {

  private boolean myIncomplete = false;
  private boolean myAllVariants = false;
  private GrExpression myUpToArgument = null;
  private boolean myForceRValue = false;

  @NotNull
  public GroovyResolverProcessor build(GrReferenceExpression ref) {
    final EnumSet<GroovyResolveKind> kinds = myIncomplete ? EnumSet.allOf(GroovyResolveKind.class) : computeKinds(ref);
    if (myAllVariants) {
      return new GroovyAllVariantsProcessor(ref, kinds, myUpToArgument);
    }
    else {
      return new GroovyResolverProcessorImpl(ref, kinds, myForceRValue);
    }
  }

  @NotNull
  public static GroovyResolverProcessorBuilder builder() {
    return new GroovyResolverProcessorBuilder();
  }

  public GroovyResolverProcessorBuilder setIncomplete(boolean incomplete) {
    myIncomplete = incomplete;
    return this;
  }

  @NotNull
  public GroovyResolverProcessorBuilder setAllVariants(boolean allVariants) {
    myAllVariants = allVariants;
    return this;
  }

  @NotNull
  public GroovyResolverProcessorBuilder setUpToArgument(GrExpression upToArgument) {
    myUpToArgument = upToArgument;
    return this;
  }

  @NotNull
  public GroovyResolverProcessorBuilder setForceRValue(boolean forceRValue) {
    myForceRValue = forceRValue;
    return this;
  }

  @NotNull
  private static EnumSet<GroovyResolveKind> computeKinds(@NotNull GrReferenceExpression ref) {
    if (ref.hasAt()) return EnumSet.of(FIELD);
    if (ref.hasMemberPointer()) return EnumSet.of(METHOD);

    final EnumSet<GroovyResolveKind> result = EnumSet.allOf(GroovyResolveKind.class);

    if (!ResolveUtil.canBeClass(ref)) result.remove(CLASS);
    if (!ResolveUtil.canBePackage(ref)) result.remove(PACKAGE);
    if (ref.isQualified()) result.remove(BINDING);
    if (!(ref.getParent() instanceof GrMethodCall)) result.remove(METHOD);

    return result;
  }
}


text:
package org.knowm.xchange.bitmarket.service;

import static org.fest.assertions.api.Assertions.assertThat;
import static org.fest.assertions.api.Assertions.fail;
import static org.powermock.api.mockito.PowerMockito.mock;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.knowm.xchange.ExchangeFactory;
import org.knowm.xchange.ExchangeSpecification;
import org.knowm.xchange.bitmarket.BitMarketAssert;
import org.knowm.xchange.bitmarket.BitMarketAuthenticated;
import org.knowm.xchange.bitmarket.BitMarketExchange;
import org.knowm.xchange.bitmarket.BitMarketTestSupport;
import org.knowm.xchange.bitmarket.dto.BitMarketAPILimit;
import org.knowm.xchange.bitmarket.dto.account.BitMarketBalance;
import org.knowm.xchange.bitmarket.dto.trade.BitMarketCancelResponse;
import org.knowm.xchange.bitmarket.dto.trade.BitMarketHistoryOperationsResponse;
import org.knowm.xchange.bitmarket.dto.trade.BitMarketHistoryTradesResponse;
import org.knowm.xchange.bitmarket.dto.trade.BitMarketOrder;
import org.knowm.xchange.bitmarket.dto.trade.BitMarketOrdersResponse;
import org.knowm.xchange.bitmarket.dto.trade.BitMarketTrade;
import org.knowm.xchange.bitmarket.dto.trade.BitMarketTradeResponse;
import org.knowm.xchange.currency.Currency;
import org.knowm.xchange.currency.CurrencyPair;
import org.knowm.xchange.dto.Order;
import org.knowm.xchange.dto.trade.LimitOrder;
import org.knowm.xchange.dto.trade.MarketOrder;
import org.knowm.xchange.dto.trade.OpenOrders;
import org.knowm.xchange.dto.trade.UserTrade;
import org.knowm.xchange.dto.trade.UserTrades;
import org.knowm.xchange.exceptions.ExchangeException;
import org.knowm.xchange.exceptions.NotAvailableFromExchangeException;
import org.knowm.xchange.service.trade.params.DefaultTradeHistoryParamCurrencyPair;
import org.knowm.xchange.service.trade.params.DefaultTradeHistoryParamPaging;
import org.knowm.xchange.service.trade.params.TradeHistoryParams;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.reflect.Whitebox;

import si.mazi.rescu.ParamsDigest;
import si.mazi.rescu.SynchronizedValueFactory;

@RunWith(PowerMockRunner.class)
public class BitMarketTradeTest extends BitMarketTestSupport {

  private BitMarketTradeService tradeService;

  @Before
  public void setUp() {
    BitMarketExchange exchange = (BitMarketExchange) ExchangeFactory.INSTANCE.createExchange(BitMarketExchange.class.getCanonicalName());
    ExchangeSpecification specification = exchange.getExchangeSpecification();
    specification.setUserName(SPECIFICATION_USERNAME);
    specification.setApiKey(SPECIFICATION_API_KEY);
    specification.setSecretKey(SPECIFICATION_SECRET_KEY);

    tradeService = new BitMarketTradeService(exchange);
  }

  @Test
  public void constructor() {
    assertThat(Whitebox.getInternalState(tradeService, "apiKey")).isEqualTo(SPECIFICATION_API_KEY);
  }

  @Test(expected = NotAvailableFromExchangeException.class)
  public void shouldFailOnPlaceMarketOrder() throws IOException {
    // given
    MarketOrder marketOrder = new MarketOrder(Order.OrderType.ASK, BigDecimal.TEN, CurrencyPair.BTC_USD, new Date());

    // when
    tradeService.placeMarketOrder(marketOrder);

    // then
    fail("BitMarketTradeService should throw NotAvailableFromExchangeException when call placeMarketOrder");
  }

  // should be changed after order type convertion fix
  @Test
  public void shouldPlaceBuyLimitOrder() throws IOException {
    // given
    BitMarketTradeResponse responseBuy = new BitMarketTradeResponse(true,
        new BitMarketTrade(12345, new BitMarketOrder(12345, "BTCAUD", BigDecimal.ONE, new BigDecimal("1.1"), BigDecimal.ZERO, "BUY", 1234567890L),
            new BitMarketBalance(createAvailable(), createBlocked())),
        new BitMarketAPILimit(3, 100, 12345000L), 0, null);

    BitMarketAuthenticated bitMarketAuthenticated = mock(BitMarketAuthenticated.class);
    PowerMockito.when(bitMarketAuthenticated.trade(Mockito.eq(SPECIFICATION_API_KEY), Mockito.any(ParamsDigest.class),
        Mockito.any(SynchronizedValueFactory.class), Mockito.eq("BTCAUD"), Mockito.eq("buy"), Mockito.eq(BigDecimal.ONE), Mockito.eq(BigDecimal.TEN)))
        .thenReturn(responseBuy);
    Whitebox.setInternalState(tradeService, "bitMarketAuthenticated", bitMarketAuthenticated);

    // when
    String placedBuy = tradeService
        .placeLimitOrder(new LimitOrder(Order.OrderType.BID, BigDecimal.ONE, CurrencyPair.BTC_AUD, "12345", null, BigDecimal.TEN));

    // then
    assertThat(placedBuy).isEqualTo("12345");
  }

  // should be changed after order type convertion fix
  @Test
  public void shouldPlaceSellLimitOrder() throws IOException {
    // given
    BitMarketTradeResponse responseSell = new BitMarketTradeResponse(true,
        new BitMarketTrade(11111, new BitMarketOrder(11111, "BTCAUD", BigDecimal.ONE, new BigDecimal("2.2"), BigDecimal.TEN, "SELL", 1234567999L),
            new BitMarketBalance(createAvailable(), createBlocked())),
        new BitMarketAPILimit(3, 100, 12345000L), 0, null);

    BitMarketAuthenticated bitMarketAuthenticated = mock(BitMarketAuthenticated.class);
    PowerMockito.when(
        bitMarketAuthenticated.trade(Mockito.eq(SPECIFICATION_API_KEY), Mockito.any(ParamsDigest.class), Mockito.any(SynchronizedValueFactory.class),
            Mockito.eq("BTCAUD"), Mockito.eq("sell"), Mockito.eq(BigDecimal.ONE), Mockito.eq(BigDecimal.TEN)))
        .thenReturn(responseSell);
    Whitebox.setInternalState(tradeService, "bitMarketAuthenticated", bitMarketAuthenticated);

    // when
    String placedSell = tradeService
        .placeLimitOrder(new LimitOrder(Order.OrderType.ASK, BigDecimal.ONE, CurrencyPair.BTC_AUD, "11111", null, BigDecimal.TEN));

    // then
    assertThat(placedSell).isEqualTo("11111");
  }

  @Test(expected = ExchangeException.class)
  public void shouldFailOnUnsuccessfulLimitOrder() throws IOException {
    // given
    BitMarketTradeResponse response = new BitMarketTradeResponse(false, null, new BitMarketAPILimit(3, 100, 12345000L), 502, "Invalid message hash");

    BitMarketAuthenticated bitMarketAuthenticated = mock(BitMarketAuthenticated.class);
    PowerMockito.when(
        bitMarketAuthenticated.trade(Mockito.eq(SPECIFICATION_API_KEY), Mockito.any(ParamsDigest.class), Mockito.any(SynchronizedValueFactory.class),
            Mockito.eq("BTCAUD"), Mockito.eq("sell"), Mockito.eq(BigDecimal.ONE), Mockito.eq(BigDecimal.TEN)))
        .thenReturn(response);
    Whitebox.setInternalState(tradeService, "bitMarketAuthenticated", bitMarketAuthenticated);

    // when
    tradeService.placeLimitOrder(new LimitOrder(Order.OrderType.ASK, BigDecimal.ONE, CurrencyPair.BTC_AUD, "12345", null, BigDecimal.TEN));

    // then
    fail("BitMarketTradeService should throw ExchangeException when place limit order request was unsuccessful");
  }

  @Test
  public void shouldCancelOrder() throws IOException {
    // given
    BitMarketCancelResponse response = new BitMarketCancelResponse(true, new BitMarketBalance(createAvailable(), createBlocked()),
        new BitMarketAPILimit(3, 100, 12345000L), 0, null);

    BitMarketAuthenticated bitMarketAuthenticated = mock(BitMarketAuthenticated.class);
    PowerMockito.when(bitMarketAuthenticated.cancel(Mockito.eq(SPECIFICATION_API_KEY), Mockito.any(ParamsDigest.class),
        Mockito.any(SynchronizedValueFactory.class), Mockito.eq(12345L))).thenReturn(response);
    Whitebox.setInternalState(tradeService, "bitMarketAuthenticated", bitMarketAuthenticated);

    // when
    boolean cancelled = tradeService.cancelOrder("12345");

    // then
    assertThat(cancelled).isTrue();
  }

  @Test(expected = ExchangeException.class)
  public void shouldFailOnUnsuccessfulCancelOrder() throws IOException {
    // given
    BitMarketCancelResponse response = new BitMarketCancelResponse(false, null, new BitMarketAPILimit(3, 100, 12345000L), 502,
        "Invalid message hash");

    BitMarketAuthenticated bitMarketAuthenticated = mock(BitMarketAuthenticated.class);
    PowerMockito.when(bitMarketAuthenticated.cancel(Mockito.eq(SPECIFICATION_API_KEY), Mockito.any(ParamsDigest.class),
        Mockito.any(SynchronizedValueFactory.class), Mockito.eq(11111L))).thenReturn(response);
    Whitebox.setInternalState(tradeService, "bitMarketAuthenticated", bitMarketAuthenticated);

    // when
    tradeService.cancelOrder("11111");

    // then
    fail("BitMarketTradeService should throw ExchangeException when cancel order request was unsuccessful");
  }

  @Test
  public void shouldGetOpenOrders() throws IOException {
    // given
    final LimitOrder[] expectedOrders = expectedOrders();

    BitMarketOrdersResponse response = new BitMarketOrdersResponse(true, createOpenOrdersData(), new BitMarketAPILimit(3, 100, 12345000L), 0, null);

    BitMarketAuthenticated bitMarketAuthenticated = mock(BitMarketAuthenticated.class);
    PowerMockito.when(bitMarketAuthenticated.orders(Mockito.eq(SPECIFICATION_API_KEY), Mockito.any(ParamsDigest.class),
        Mockito.any(SynchronizedValueFactory.class))).thenReturn(response);
    Whitebox.setInternalState(tradeService, "bitMarketAuthenticated", bitMarketAuthenticated);

    // when
    OpenOrders orders = tradeService.getOpenOrders();
    List<LimitOrder> openOrders = orders.getOpenOrders();

    // then
    assertThat(openOrders).hasSize(2);
    for (int i = 0; i < openOrders.size(); i++) {
      BitMarketAssert.assertEquals(openOrders.get(i), expectedOrders[i]);
      assertThat(orders.toString()).contains(expectedOrders[i].toString());
    }
  }

  @Test(expected = ExchangeException.class)
  public void shouldFailOnUnsuccessfulOpenOrders() throws IOException {
    // given
    BitMarketOrdersResponse response = new BitMarketOrdersResponse(false, null, new BitMarketAPILimit(3, 100, 12345000L), 502,
        "Invalid message hash");

    BitMarketAuthenticated bitMarketAuthenticated = mock(BitMarketAuthenticated.class);
    PowerMockito.when(bitMarketAuthenticated.orders(Mockito.eq(SPECIFICATION_API_KEY), Mockito.any(ParamsDigest.class),
        Mockito.any(SynchronizedValueFactory.class))).thenReturn(response);
    Whitebox.setInternalState(tradeService, "bitMarketAuthenticated", bitMarketAuthenticated);

    // when
    tradeService.getOpenOrders();

    // then
    fail("BitMarketTradeService should throw ExchangeException when open orders request was unsuccessful");
  }

  @Test
  public void shouldGetPagingTradeHistory() throws IOException {
    // given
    final UserTrade[] expectedUserTrades = expectedUserTrades();

    BitMarketHistoryTradesResponse historyTradesResponse = parse("trade/example-history-trades-data", BitMarketHistoryTradesResponse.class);
    BitMarketHistoryOperationsResponse marketHistoryOperationsPlnResponse = parse("trade/example-history-operations-data",
        BitMarketHistoryOperationsResponse.class);
    BitMarketHistoryOperationsResponse marketHistoryOperationsBtcResponse = parse("trade/example-history-operations-btc-data",
        BitMarketHistoryOperationsResponse.class);

    BitMarketAuthenticated bitMarketAuthenticated = mock(BitMarketAuthenticated.class);
    PowerMockito.when(bitMarketAuthenticated.trades(Mockito.eq(SPECIFICATION_API_KEY), Mockito.any(ParamsDigest.class),
        Mockito.any(SynchronizedValueFactory.class), Mockito.eq("BTCPLN"), Mockito.eq(1000), Mockito.eq(0L))).thenReturn(historyTradesResponse);

    PowerMockito
        .when(bitMarketAuthenticated.history(Mockito.eq(SPECIFICATION_API_KEY), Mockito.any(ParamsDigest.class),
            Mockito.any(SynchronizedValueFactory.class), Mockito.eq(Currency.PLN.toString()), Mockito.anyInt(), Mockito.anyLong()))
        .thenReturn(marketHistoryOperationsPlnResponse);
    PowerMockito
        .when(bitMarketAuthenticated.history(Mockito.eq(SPECIFICATION_API_KEY), Mockito.any(ParamsDigest.class),
            Mockito.any(SynchronizedValueFactory.class), Mockito.eq(Currency.BTC.toString()), Mockito.anyInt(), Mockito.anyLong()))
        .thenReturn(marketHistoryOperationsBtcResponse);

    Whitebox.setInternalState(tradeService, "bitMarketAuthenticated", bitMarketAuthenticated);

    // when
    UserTrades tradesPaging = tradeService.getTradeHistory(new DefaultTradeHistoryParamPaging(150));
    List<UserTrade> userTrades = tradesPaging.getUserTrades();

    // then
    assertThat(userTrades).hasSize(5);
    for (int i = 0; i < userTrades.size(); i++) {
      BitMarketAssert.assertEquals(userTrades.get(i), expectedUserTrades[i]);
    }
  }

  @Test
  public void shouldGetCurrencyPairTradeHistory() throws IOException {
    // given
    final UserTrade[] expectedCpUserTrades = expectedCpUserTrades();

    BitMarketHistoryTradesResponse historyTradesCPResponse = parse("trade/example-history-trades-cp-data", BitMarketHistoryTradesResponse.class);
    BitMarketHistoryOperationsResponse marketHistoryOperationsEurResponse = parse("trade/example-history-operations-eur-data",
        BitMarketHistoryOperationsResponse.class);
    BitMarketHistoryOperationsResponse marketHistoryOperationsBtcResponse = parse("trade/example-history-operations-btc-data",
        BitMarketHistoryOperationsResponse.class);

    BitMarketAuthenticated bitMarketAuthenticated = mock(BitMarketAuthenticated.class);
    PowerMockito.when(bitMarketAuthenticated.trades(Mockito.eq(SPECIFICATION_API_KEY), Mockito.any(ParamsDigest.class),
        Mockito.any(SynchronizedValueFactory.class), Mockito.eq("BTCEUR"), Mockito.eq(1000), Mockito.eq(0L))).thenReturn(historyTradesCPResponse);

    PowerMockito
        .when(bitMarketAuthenticated.history(Mockito.eq(SPECIFICATION_API_KEY), Mockito.any(ParamsDigest.class),
            Mockito.any(SynchronizedValueFactory.class), Mockito.eq(Currency.EUR.toString()), Mockito.anyInt(), Mockito.anyLong()))
        .thenReturn(marketHistoryOperationsEurResponse);
    PowerMockito
        .when(bitMarketAuthenticated.history(Mockito.eq(SPECIFICATION_API_KEY), Mockito.any(ParamsDigest.class),
            Mockito.any(SynchronizedValueFactory.class), Mockito.eq(Currency.BTC.toString()), Mockito.anyInt(), Mockito.anyLong()))
        .thenReturn(marketHistoryOperationsBtcResponse);

    Whitebox.setInternalState(tradeService, "bitMarketAuthenticated", bitMarketAuthenticated);

    // when
    UserTrades tradesCP = tradeService.getTradeHistory(new DefaultTradeHistoryParamCurrencyPair(CurrencyPair.BTC_EUR));
    List<UserTrade> userTrades = tradesCP.getUserTrades();

    // then
    assertThat(userTrades).hasSize(2);
    for (int i = 0; i < userTrades.size(); i++) {
      BitMarketAssert.assertEquals(userTrades.get(i), expectedCpUserTrades[i]);
    }
  }

  @Test
  public void shouldGetTradeHistory() throws IOException {
    // given
    BitMarketHistoryTradesResponse historyTradesBMResponse = parse("trade/example-history-trades-bm-data", BitMarketHistoryTradesResponse.class);
    BitMarketHistoryOperationsResponse marketHistoryOperationsEurResponse = parse("trade/example-history-operations-eur-data",
        BitMarketHistoryOperationsResponse.class);
    BitMarketHistoryOperationsResponse marketHistoryOperationsBtcResponse = parse("trade/example-history-operations-btc-data",
        BitMarketHistoryOperationsResponse.class);

    BitMarketAuthenticated bitMarketAuthenticated = mock(BitMarketAuthenticated.class);
    PowerMockito
        .when(bitMarketAuthenticated.trades(Mockito.eq(SPECIFICATION_API_KEY), Mockito.any(ParamsDigest.class),
            Mockito.any(SynchronizedValueFactory.class), Mockito.eq("BTCEUR"), Mockito.eq(3500), Mockito.eq(500L)))
        .thenReturn(historyTradesBMResponse);

    PowerMockito
        .when(bitMarketAuthenticated.history(Mockito.eq(SPECIFICATION_API_KEY), Mockito.any(ParamsDigest.class),
            Mockito.any(SynchronizedValueFactory.class), Mockito.eq(Currency.EUR.toString()), Mockito.anyInt(), Mockito.anyLong()))
        .thenReturn(marketHistoryOperationsEurResponse);
    PowerMockito
        .when(bitMarketAuthenticated.history(Mockito.eq(SPECIFICATION_API_KEY), Mockito.any(ParamsDigest.class),
            Mockito.any(SynchronizedValueFactory.class), Mockito.eq(Currency.BTC.toString()), Mockito.anyInt(), Mockito.anyLong()))
        .thenReturn(marketHistoryOperationsBtcResponse);

    Whitebox.setInternalState(tradeService, "bitMarketAuthenticated", bitMarketAuthenticated);

    // when
    UserTrades tradesBM = tradeService.getTradeHistory(new BitMarketHistoryParams(CurrencyPair.BTC_EUR, 500L, 3500));
    List<UserTrade> userTrades = tradesBM.getUserTrades();

    // then
    assertThat(userTrades).hasSize(1);
    BitMarketAssert.assertEquals(userTrades.get(0), EXPECTED_BM_USER_TRADES);
  }

  @Test(expected = ExchangeException.class)
  public void shouldFailOnUnsuccessfulTradeHistory() throws IOException {
    // given
    BitMarketHistoryTradesResponse response = new BitMarketHistoryTradesResponse(false, null, new BitMarketAPILimit(3, 100, 12345000L), 502,
        "Invalid message hash");

    BitMarketHistoryOperationsResponse marketHistoryOperationsPlnResponse = parse("trade/example-history-operations-data",
        BitMarketHistoryOperationsResponse.class);
    BitMarketHistoryOperationsResponse marketHistoryOperationsBtcResponse = parse("trade/example-history-operations-btc-data",
        BitMarketHistoryOperationsResponse.class);

    BitMarketAuthenticated bitMarketAuthenticated = mock(BitMarketAuthenticated.class);
    PowerMockito.when(bitMarketAuthenticated.trades(Mockito.eq(SPECIFICATION_API_KEY), Mockito.any(ParamsDigest.class),
        Mockito.any(SynchronizedValueFactory.class), Mockito.eq("BTCPLN"), Mockito.eq(1000), Mockito.eq(0L))).thenReturn(response);
    PowerMockito
        .when(bitMarketAuthenticated.history(Mockito.eq(SPECIFICATION_API_KEY), Mockito.any(ParamsDigest.class),
            Mockito.any(SynchronizedValueFactory.class), Mockito.eq(Currency.PLN.toString()), Mockito.anyInt(), Mockito.anyLong()))
        .thenReturn(marketHistoryOperationsPlnResponse);
    PowerMockito
        .when(bitMarketAuthenticated.history(Mockito.eq(SPECIFICATION_API_KEY), Mockito.any(ParamsDigest.class),
            Mockito.any(SynchronizedValueFactory.class), Mockito.eq(Currency.BTC.toString()), Mockito.anyInt(), Mockito.anyLong()))
        .thenReturn(marketHistoryOperationsBtcResponse);

    Whitebox.setInternalState(tradeService, "bitMarketAuthenticated", bitMarketAuthenticated);

    // when
    tradeService.getTradeHistory(new DefaultTradeHistoryParamPaging(150));

    // then
    fail("BitMarketTradeService should throw ExchangeException when open orders request was unsuccessful");
  }

  @Test(expected = ExchangeException.class)
  public void shouldFailOnUnsuccessfulOperationsHistory1() throws IOException {
    // given
    BitMarketHistoryOperationsResponse errorResponse = new BitMarketHistoryOperationsResponse(false, null, new BitMarketAPILimit(3, 100, 12345000L),
        502, "Invalid message hash");

    BitMarketHistoryOperationsResponse marketHistoryOperationsBtcResponse = parse("trade/example-history-operations-btc-data",
        BitMarketHistoryOperationsResponse.class);

    BitMarketAuthenticated bitMarketAuthenticated = mock(BitMarketAuthenticated.class);
    PowerMockito
        .when(bitMarketAuthenticated.history(Mockito.eq(SPECIFICATION_API_KEY), Mockito.any(ParamsDigest.class),
            Mockito.any(SynchronizedValueFactory.class), Mockito.eq(Currency.PLN.toString()), Mockito.anyInt(), Mockito.anyLong()))
        .thenReturn(errorResponse);
    PowerMockito
        .when(bitMarketAuthenticated.history(Mockito.eq(SPECIFICATION_API_KEY), Mockito.any(ParamsDigest.class),
            Mockito.any(SynchronizedValueFactory.class), Mockito.eq(Currency.BTC.toString()), Mockito.anyInt(), Mockito.anyLong()))
        .thenReturn(marketHistoryOperationsBtcResponse);

    Whitebox.setInternalState(tradeService, "bitMarketAuthenticated", bitMarketAuthenticated);

    // when
    tradeService.getBitMarketOperationHistory(new DefaultTradeHistoryParamPaging(150));

    // then
    fail("BitMarketTradeService should throw ExchangeException when operations history request was unsuccessful");
  }

  @Test(expected = ExchangeException.class)
  public void shouldFailOnUnsuccessfulOperationsHistory2() throws IOException {
    // given
    BitMarketHistoryOperationsResponse errorResponse = new BitMarketHistoryOperationsResponse(false, null, new BitMarketAPILimit(3, 100, 12345000L),
        502, "Invalid message hash");

    BitMarketHistoryOperationsResponse marketHistoryOperationsPlnResponse = parse("trade/example-history-operations-data",
        BitMarketHistoryOperationsResponse.class);

    BitMarketAuthenticated bitMarketAuthenticated = mock(BitMarketAuthenticated.class);
    PowerMockito
        .when(bitMarketAuthenticated.history(Mockito.eq(SPECIFICATION_API_KEY), Mockito.any(ParamsDigest.class),
            Mockito.any(SynchronizedValueFactory.class), Mockito.eq(Currency.PLN.toString()), Mockito.anyInt(), Mockito.anyLong()))
        .thenReturn(marketHistoryOperationsPlnResponse);
    PowerMockito
        .when(bitMarketAuthenticated.history(Mockito.eq(SPECIFICATION_API_KEY), Mockito.any(ParamsDigest.class),
            Mockito.any(SynchronizedValueFactory.class), Mockito.eq(Currency.BTC.toString()), Mockito.anyInt(), Mockito.anyLong()))
        .thenReturn(errorResponse);

    Whitebox.setInternalState(tradeService, "bitMarketAuthenticated", bitMarketAuthenticated);

    // when
    tradeService.getBitMarketOperationHistory(new DefaultTradeHistoryParamPaging(150));

    // then
    fail("BitMarketTradeService should throw ExchangeException when operations history request was unsuccessful");
  }

  @Test
  public void shouldCreateParams() {
    // when
    TradeHistoryParams params = tradeService.createTradeHistoryParams();

    // then
    assertThat(params instanceof BitMarketHistoryParams).isTrue();
    assertThat(((BitMarketHistoryParams) params).getCount()).isEqualTo(1000);
    assertThat(((BitMarketHistoryParams) params).getCurrencyPair()).isEqualTo(CurrencyPair.BTC_PLN);
    assertThat(((BitMarketHistoryParams) params).getOffset()).isEqualTo(0L);
  }
}


text:
drop table if exists tz_test, numeric_types;

create table tz_test (id int auto_increment, ts timestamp, tsltz timestamp with local time zone, tstz timestamp with time zone);
set timezone '+10:00';
insert into tz_test(ts, tsltz, tstz) values (timestamp'1980-10-01 2:00:00', timestampltz'1980-10-01 2:00:00', timestamptz'1980-10-01 2:00:00 Asia/Yakutsk');

create table numeric_types (a smallint, b int, c bigint, d numeric(4, 2), e float, f double);

set timezone 'Asia/Seoul';
--test: [er] implicit conversion from ts constant value to numeric types
insert into numeric_types(a) values (timestamp'1980-10-01 2:00:00');
insert into numeric_types(b) values (timestamp'1980-10-01 2:00:00');
insert into numeric_types(c) values (timestamp'1980-10-01 2:00:00');
insert into numeric_types(d) values (timestamp'1980-10-01 2:00:00');
insert into numeric_types(e) values (timestamp'1980-10-01 2:00:00');
insert into numeric_types(f) values (timestamp'1980-10-01 2:00:00');
--test: [er] implicit conversion from ts column to numeric types
insert into numeric_types(a) values (select ts from tz_test);
insert into numeric_types(b) values (select ts from tz_test);
insert into numeric_types(c) values (select ts from tz_test);
insert into numeric_types(d) values (select ts from tz_test);
insert into numeric_types(e) values (select ts from tz_test);
insert into numeric_types(f) values (select ts from tz_test);

--test: [er] implicit conversion from tsltz constant value to numeric types
insert into numeric_types(a) values (timestampltz'1980-10-01 2:00:00 -5:00');
insert into numeric_types(b) values (timestampltz'1980-10-01 2:00:00 -5:00');
insert into numeric_types(c) values (timestampltz'1980-10-01 2:00:00 -5:00');
insert into numeric_types(d) values (timestampltz'1980-10-01 2:00:00 -5:00');
insert into numeric_types(e) values (timestampltz'1980-10-01 2:00:00 -5:00');
insert into numeric_types(f) values (timestampltz'1980-10-01 2:00:00 -5:00');
--test: [er] implicit conversion from tsltz column to numeric types
insert into numeric_types(a) values (select tsltz from tz_test);
insert into numeric_types(b) values (select tsltz from tz_test);
insert into numeric_types(c) values (select tsltz from tz_test);
insert into numeric_types(d) values (select tsltz from tz_test);
insert into numeric_types(e) values (select tsltz from tz_test);
insert into numeric_types(f) values (select tsltz from tz_test);

--test: [er] implicit conversion from tstz constant value to numeric types
insert into numeric_types(a) values (timestamptz'1980-10-01 2:00:00 America/Argentina/Jujuy');
insert into numeric_types(b) values (timestamptz'1980-10-01 2:00:00 America/Argentina/Jujuy');
insert into numeric_types(c) values (timestamptz'1980-10-01 2:00:00 America/Argentina/Jujuy');
insert into numeric_types(d) values (timestamptz'1980-10-01 2:00:00 America/Argentina/Jujuy');
insert into numeric_types(e) values (timestamptz'1980-10-01 2:00:00 America/Argentina/Jujuy');
insert into numeric_types(f) values (timestamptz'1980-10-01 2:00:00 America/Argentina/Jujuy');
--test: [er] implicit conversion from tstz column to numeric types
insert into numeric_types(a) values (select tstz from tz_test);
insert into numeric_types(b) values (select tstz from tz_test);
insert into numeric_types(c) values (select tstz from tz_test);
insert into numeric_types(d) values (select tstz from tz_test);
insert into numeric_types(e) values (select tstz from tz_test);
insert into numeric_types(f) values (select tstz from tz_test);

drop table tz_test, numeric_types;

set timezone 'Asia/Seoul';


text: Multipurpose login form with ajax for polymer


text:
/*
  see GenericCommunicator.h
*/

#include <../socket_comm/pal_socket.h>
#include "GenericCommunicator.h"
#include "ChannelInterface.h"
#include "ThreadExecuter.h"
#include "itac_internal.h"

#include <cnc/serializer.h>
#include <cnc/internal/dist/distributor.h>

#include <tbb/concurrent_queue.h>

#include <cstring> // memcmp
#include <cnc/internal/cnc_stddef.h>
#include <cnc/internal/tbbcompat.h>

#include <iostream>

/**
 * YIELD:
 */
#ifdef _WIN32
# include <windows.h>
static inline void YIELD() { Sleep( 0 ); }
#elif __APPLE__
#include <sched.h>
static inline void YIELD() { sched_yield(); }
#else
# include <pthread.h>
static inline void YIELD() { pthread_yield(); }
#endif

/**
 * Different compilation modes:
 */
//#define WITHOUT_SENDER_THREAD
//#define WITHOUT_SENDER_THREAD_TRACING

// Correction:
#ifdef WITHOUT_SENDER_THREAD
# define WITHOUT_SENDER_THREAD_TRACING
#endif

namespace CnC
{
    namespace Internal
    {
        // Tags for ITAC tracing:
        enum ITC_Tags{
            ITC_TAG_EXTERNAL,
            ITC_TAG_INTERNAL
        };

        //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

        //%%%%%%%%%%%%%%%
        //              %
        //  RecvThread  %
        //              %
        //%%%%%%%%%%%%%%%

        class GenericCommunicator::RecvThread : public ThreadExecuter
        {
        public:
            RecvThread( GenericCommunicator & instance )
                : m_instance( instance ), m_channel( *instance.m_channel ) {}

            /// ThreadExecuter's event loop:
            virtual void runEventLoop();

        private:
            /// Event loop for the host:
            void runRecvEventLoopHost();

            /// Event loop for the clients:
            void runRecvEventLoopClients();

            /// Receive the next message from any remote process.
            bool recv_msg( int & sender );

        private:
            /// A RecvThread belongs to a specific GenericCommunicator
            /// instance which it knows
            GenericCommunicator & m_instance;
            ChannelInterface & m_channel; // the channel of m_instance
            serializer m_ser1, m_ser2;
        };

        //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

        void GenericCommunicator::RecvThread::runEventLoop()
        {
            if ( m_instance.remote() ) {
                runRecvEventLoopClients();
            } else {
                runRecvEventLoopHost();
            }
        }

        //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

        void GenericCommunicator::RecvThread::runRecvEventLoopHost()
        {
            // Host expects one termination request from each client.
            // Clients expect two termination requests from the host.
            int nTerminationRequestsExpected = m_channel.numProcs() - 1;
            int nTerminationRequests = 0;
            bool done = false;
            do {
                int client;
                if(  ! recv_msg( client )  ) {
                    // normal message
                } else {
                    // wasTerminationRequest
                    ++nTerminationRequests;
                    if ( nTerminationRequests == nTerminationRequestsExpected ) {
                        done = true;
                    }
                }
            } while ( ! done );

            // All clients are shutting down. Send final termination requests:
            for ( int iClient = 1; iClient < m_channel.numProcs(); ++iClient ) {
                m_instance.send_termination_request( iClient, true ); // blocking send !!!
                // The communication with this client is over. Disable the channel:
                m_channel.deactivate( iClient );
            }
        }

        //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

        void GenericCommunicator::RecvThread::runRecvEventLoopClients()
        {
            // Host expects one termination request from each client.
            // Clients expect two termination requests from the host.
            int nTerminationRequestsExpected = 2;
            int nTerminationRequests = 0;
            bool done = false;
            do {
                int sender;
                if( ! recv_msg( sender ) ) {
                    // normal message
                } else {
                    // wasTerminationRequest
                    CNC_ASSERT( sender == 0 ); // termination request from host
                    ++nTerminationRequests;
                    if ( nTerminationRequests == 1 ) {
                        m_instance.send_termination_request( 0 ); // send back to the host
                    }
                    if ( nTerminationRequests == nTerminationRequestsExpected ) {
                        done = true;
                    }
                    // For the rest of this run, the clients can only communicate
                    // with the host. Disable all other client connections !!!
                    m_channel.invalidate_client_communication_channels();
                }
            } while ( ! done );
        }

        //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

        //        const int term_bits[4] = { 0, 0, 0, 0 };

        bool GenericCommunicator::RecvThread::recv_msg( int & sender )
        {
            VT_FUNC( "Dist::GenComm::recv_msg" );
            // ==> Wait for a client to send a message:

            // ==> Receive the message from a client:
            try {
                serializer * ser = m_channel.waitForAnyClient( sender );

                // Check:
                CNC_ASSERT( 0 <= sender && sender < m_channel.numProcs() );
                CNC_ASSERT( sender != m_channel.localId() );

                if( ser ) {
                    // Ok, there is body to it, that's why we got the serializer
                    // Call the recv callback of the communicator instance
                    m_instance.recv_msg_callback( *ser, sender );
                    return false;
                } else {
                    // ==> termination requested !!!
                    return true;
                }
            }
            catch ( ConnectionError ) {
                CNC_ABORT( "Connection Error" );
            }
            catch ( ... ) {
                //throw ClientId( sender );
            }
            return false;
        }

        //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

        //%%%%%%%%%%%%%%%
        //              %
        //  SendThread  %
        //              %
        //%%%%%%%%%%%%%%%

        class GenericCommunicator::SendThread : public ThreadExecuter
        {
        public:
            typedef scalable_vector< int > RcverArray;
            SendThread( ChannelInterface & channel ) : m_channel( channel ) {}

            /// ThreadExecuter interface:
            virtual void runEventLoop();
            virtual void stop();

            /// The following "push" methods are called from an
            /// "application thread" (not from the sender thread):
            void pushForSend( serializer * ser, int rcverLocalId );
            void pushForBcast( serializer * ser );
            bool pushForBcast( serializer * ser, const int * rcverArr, int n, int globalIdShift );
            void pushTerminationRequest( int rcverLocalId, volatile bool * indicator );
            void pushStopRequest();
            bool has_pending_messages();

        private:
            /// The following methods are called on the sender thread only:
            int send( serializer * ser, int rcverLocalId );
            void bcast( serializer * ser );
            void bcast( serializer * ser, const RcverArray & rcverArr );
            void sendTerminationRequest( int rcverLocalId, volatile bool * indicator );
            struct SendItem;
            void cleanupSerializer( serializer *& ser ) { delete ser; ser = 0; }
            void cleanupItemData( SendItem & item );

            /// A SendThread belongs to a specific GenericCommunicator.
            /// It uses the ChannelInterface of this instance.
            ChannelInterface & m_channel;

            /// Queue where send requests are put into.
            /// A separate sender thread pops the items from there
            /// and performs the actual send operation.
            struct SendItem {
                serializer * m_ser;
                int m_rcverLocalId;
                volatile bool * m_indicator; // if nonzero, this will be set to "true" if the
                                             // communication has been finished successfully
                RcverArray * m_rcverArr; // for bcast

                SendItem( serializer * ser = 0, int rcverLocalId = 0,
                          volatile bool * indicator = 0,
                          RcverArray * rcverArr = 0 )
                    : m_ser( ser ), m_rcverLocalId( rcverLocalId ),
                      m_indicator( indicator ), m_rcverArr( rcverArr ) {}
            };
            tbb::concurrent_bounded_queue< SendItem > m_sendQueue;
        };

        //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

        bool GenericCommunicator::SendThread::has_pending_messages()
        {
            return m_sendQueue.empty() == false;
        }

        //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

        void GenericCommunicator::SendThread::runEventLoop()
        {
            SendItem item;
            bool done = false;
            do
                {
                    // Wait for next item in the queue:
                    m_sendQueue.pop( item );
                    /*
                     *  Distinguish four cases:
                     *
                     *  ser != 0, rcver >= 0  ==> Send
                     *  ser != 0, rcver == -1 ==> Bcast
                     *  ser == 0, rcver >= 0  ==> SendTerminationRequest
                     *  ser == 0, rcver == -1 ==> local finish request
                     */

                    // Send/bcast this item:
                    if ( item.m_ser && item.m_rcverLocalId != -1 ) {
                        CNC_ASSERT( item.m_rcverArr == 0 );
#ifdef PRE_SEND_MSGS
                        m_channel.wait( &item.m_rcverLocalId, 1 );
#else
                        send( item.m_ser, item.m_rcverLocalId );
#endif
                    }
                    else if ( item.m_ser != 0 ) {
                        CNC_ASSERT( item.m_rcverLocalId == -1 );
                        if ( item.m_rcverArr == 0 ) {
                            bcast( item.m_ser );
                        } else {
#ifdef PRE_SEND_MSGS
                            m_channel.wait( &item.m_rcverArr->front(), item.m_rcverArr->size() );
#else
                            bcast( item.m_ser, *item.m_rcverArr );
#endif
                        }
                    }
                    else if ( item.m_rcverLocalId >= 0 ) {
                        CNC_ASSERT( item.m_rcverArr == 0 );
                        sendTerminationRequest( item.m_rcverLocalId, item.m_indicator );
                        // if nonzero, item.m_indicator will be set to true
                        // if the message has been sent successfully.
                    }
                    else {
                        CNC_ASSERT( item.m_rcverArr == 0 );
                        CNC_ASSERT( item.m_rcverLocalId == -1 );
                        done = true;
                    }

                    // Delete corresponding serializer:
                    cleanupItemData( item );
                } while ( ! done );
        }

        //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

        void GenericCommunicator::SendThread::cleanupItemData( SendItem & item )
        {
            cleanupSerializer( item.m_ser );
            delete item.m_rcverArr;
        }

        //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

        void GenericCommunicator::SendThread::pushForSend( serializer * ser, int rcverLocalId )
        {
            CNC_ASSERT( ser && rcverLocalId >= 0 );
#ifdef WITHOUT_SENDER_THREAD
            send( ser, rcverLocalId );
            cleanupSerializer( ser );
#else
# ifdef PRE_SEND_MSGS
            rcverLocalId = send( ser, rcverLocalId );
# endif
            m_sendQueue.push( SendItem( ser, rcverLocalId ) );
            // nonzero ser and rcver id >= 0 indicate Send
#endif
        }

        //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

        void GenericCommunicator::SendThread::pushForBcast( serializer * ser )
        {
# ifdef PRE_SEND_MSGS
            pushForBcast( ser, NULL, m_channel.numProcs(), 0 ); // FIXME m_globalIdShift );
#else
            CNC_ASSERT( ser != 0 );

# ifdef CNC_WITH_ITAC
            // ITAC logging of bcast messages:
            for ( int rcver = 0; rcver < m_channel.numProcs(); ++rcver ) {
                // skip inactive clients (especailly myself):
                if ( ! m_channel.isActive( rcver ) ) continue;
#   ifdef WITHOUT_SENDER_THREAD_TRACING
                VT_SEND( rcver, (int)ser->get_total_size(), ITC_TAG_EXTERNAL );
#   else
                VT_SEND( m_channel.localId(), (int)ser->get_total_size(), ITC_TAG_INTERNAL );
#   endif
            }
# endif // CNC_WITH_ITAC

# ifdef WITHOUT_SENDER_THREAD
            bcast( ser );
            cleanupSerializer( ser );
# else
            m_sendQueue.push( SendItem( ser, -1 ) );
            // nonzero ser and rcver id == -1 indicate Bcast
# endif
#endif // PRE_SEND_MSGS
        }

        //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

        bool GenericCommunicator::SendThread::pushForBcast( serializer * ser, const int * rcverArr, int n, int globalIdShift )
        {
            CNC_ASSERT( ser != 0 );

            // Allocate copy of the given rcverArr. Note that rcverArr
            // still contains global ids. They must be transformed into local ones
            // (using globalIdShift).
            RcverArray* myRcverArr = new RcverArray( n );
            RcverArray::iterator it = myRcverArr->begin();
            int _new_n = n;
            bool _self = false;
            for( int i = 0; i < n; ++ i ) {
                // Transform global id to local id:
                int localRecvId = rcverArr != NULL ? rcverArr[i] - globalIdShift : i;
                CNC_ASSERT( 0 <= localRecvId && localRecvId < m_channel.numProcs() );
                // Skip inactive clients (especailly myself):
                if ( ! m_channel.isActive( localRecvId ) ) {
                    if( localRecvId == m_channel.localId() && rcverArr != NULL ) _self = true;
                    --_new_n;
                    continue;
                }
                // ITAC tracing:
#ifdef WITHOUT_SENDER_THREAD_TRACING
                VT_SEND( localRecvId, (int)ser->get_total_size(), ITC_TAG_EXTERNAL );
#else
                VT_SEND( m_channel.localId(), (int)ser->get_total_size(), ITC_TAG_INTERNAL );
#endif
#ifdef PRE_SEND_MSGS
                *it = send( ser, localRecvId );
#else
                *it = localRecvId;
#endif
                ++it;
            }

            myRcverArr->resize( _new_n );

#ifdef WITHOUT_SENDER_THREAD
            bcast( ser, *myRcverArr );
            cleanupSerializer( ser );
            delete myRcverArr;
#else
            m_sendQueue.push( SendItem( ser, -1, 0, myRcverArr ) );
            // nonzero ser and rcver id == -1 indicate Bcast
            // myRcverArr will be deleted after bcast on the sender thread
#endif

            return _self;
        }

        //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

        void GenericCommunicator::SendThread::pushTerminationRequest( int rcverLocalId, volatile bool * indicator )
        {
            CNC_ASSERT( rcverLocalId >= 0 );
#ifdef WITHOUT_SENDER_THREAD
            sendTerminationRequest( rcverLocalId, indicator );
#else
            m_sendQueue.push( SendItem( 0, rcverLocalId, indicator ) );
            // zero ser and rcver id >= 0 indicate "send termination request"
#endif
        }

        //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

        void GenericCommunicator::SendThread::pushStopRequest()
        {
            m_sendQueue.push( SendItem( 0, -1 ) );
            // zero ser and rcver id == -1 indicates local finish request
        }

        //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

        void GenericCommunicator::SendThread::stop()
        {
            // This overwrites (extends) ThreadExecuter's virtual stop()
            // method. Before joining with sender thread (which is done by
            // the generic ThreadExecuter::stop()) we notify the sender
            // thread that it should finish.

            // Indicate to the sender thread that it should stop executing.
            // This is done by pushing a special item on the send queue.
            pushStopRequest();

            // Now join with the sender thread:
            ThreadExecuter::stop();
        }

        //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

        int GenericCommunicator::SendThread::send( serializer * ser, int rcverLocalId )
        {
            CNC_ASSERT( 0 <= rcverLocalId && rcverLocalId < m_channel.numProcs() );
            CNC_ASSERT( ser && m_channel.isActive( rcverLocalId ) );

#ifndef WITHOUT_SENDER_THREAD_TRACING
            // ITAC logging:
            VT_RECV( m_channel.localId(), (int)ser->get_total_size(), ITC_TAG_INTERNAL );
            VT_SEND( rcverLocalId, (int)ser->get_total_size(), ITC_TAG_EXTERNAL );
#endif

            size_type _bsz = ser->get_body_size();
            CNC_ASSERT( _bsz > 0 );
            // we send header and body at once:
            int ret = m_channel.sendBytes( ser->get_header(), ser->get_header_size(), _bsz, rcverLocalId );
            CNC_ASSERT( _bsz == ser->get_body_size() );
            CNC_ASSERT( ret != -1 );
            return ret;
        }

        //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

        void GenericCommunicator::SendThread::bcast( serializer * ser )
        {
            CNC_ASSERT( ser );

            // Send data. Protect access to sendSocket by mutex.
            int maxNumRecv = m_channel.numProcs();
            size_type _bsz = ser->get_body_size();
            for ( int rcver = 0; rcver < maxNumRecv; ++rcver ) {
                // skip inactive clients (especailly myself):
                if ( ! m_channel.isActive( rcver ) ) continue;

                // Send message to this receiver:
                send( ser, rcver );
                CNC_ASSERT( _bsz == ser->get_body_size() );
            }
        }

        //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

        void GenericCommunicator::SendThread::bcast( serializer * ser, const RcverArray & rcverArr )
        {
            CNC_ASSERT( ser );

            size_type _bsz = ser->get_body_size();
            // Send data. Protect access to sendSocket by mutex.
            for ( RcverArray::const_iterator it = rcverArr.begin(); it != rcverArr.end(); ++it ) {
                CNC_ASSERT( 0 <= *it && *it < m_channel.numProcs() );
                // must have elided inactive clients (especailly myself):
                CNC_ASSERT( m_channel.isActive( *it ) );

                // Send message to this receiver:
                send( ser, *it );
                CNC_ASSERT( _bsz == ser->get_body_size() );
            }
        }

        //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

        void GenericCommunicator::SendThread::sendTerminationRequest( int rcverLocalId, volatile bool * indicator )
        {
            CNC_ASSERT( 0 <= rcverLocalId && rcverLocalId < m_channel.numProcs() );
            CNC_ASSERT( m_channel.isActive( rcverLocalId ) );

            // Dummy serializer:
            serializer ser( m_useCRC, true );
            ser.set_mode_pack();

            // Prepare it for sending: set its header to NULL
            // which indicates the termination request.
            BufferAccess::finalizePack( ser );
            CNC_ASSERT( ser.get_body_size() == 0 );

            // Send only the zero'd header:
            m_channel.sendBytes( ser.get_header(), ser.get_header_size(), 0 /* body size */ , rcverLocalId );

            // Indicate that the message has been sent successfully:
            if ( indicator ) {
                *indicator = true;
            }
        }

        //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

        //%%%%%%%%%%%%%%%%%%%%%%%%
        //                       %
        //  GenericCommunicator  %
        //                       %
        //%%%%%%%%%%%%%%%%%%%%%%%%

        GenericCommunicator::GenericCommunicator( bool de )
            : m_channel( 0 ),
              m_sendThread( 0 ),
              m_recvThread( 0 ),
              m_globalIdShift( 0 ),
              m_hasBeenInitialized( false ),
              m_exit0CallOk( true )
        {}

        //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

        int GenericCommunicator::myPid()
        {
            return m_channel->localId() + m_globalIdShift;
        }

        //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

        int GenericCommunicator::numProcs()
        {
            return m_channel->numProcs();
        }

        //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

        bool GenericCommunicator::remote()
        {
            return ( m_channel->localId() != 0 ) ? true : false;
        }

        //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

        int GenericCommunicator::init( int minId, int /*flag*/ )
        {
            VT_FUNC_I( "Dist::GenComm::init" );

            // Already running?
            if ( m_hasBeenInitialized ) {
                return 0;
            } else {
                m_hasBeenInitialized = true;
            }

            // Initialize ids:
            m_globalIdShift = minId;

            /*
             * NOTE: This method will be called from init() of a derived class.
             *       The derived class must have instantiated m_channel
             *       accordingly. Therefore, we can use m_channel here.
             */

            // A process cannot send a message to itself.
            // Therefore, disable this channel:
            CNC_ASSERT( m_channel );
            m_channel->deactivate( m_channel->localId() );

            // Start sender loop (same on host and on client):
            CNC_ASSERT( m_sendThread == 0 );
            m_sendThread = new SendThread( *m_channel );
#ifndef WITHOUT_SENDER_THREAD
# ifndef WITHOUT_SENDER_THREAD_TRACING
            m_sendThread->defineThreadName( "SEND", m_channel->localId() );
# endif
            m_sendThread->start();
#endif

            // Start receiver loop:
            CNC_ASSERT( m_recvThread == 0 );
            m_recvThread = new RecvThread( *this ); // needs whole instance, not only the channel
            if ( ! remote() || distributor::distributed_env() ) {
                // Host(s) runs the receiver loop in a separate thread.
                // Prepare receiver thread:
                m_recvThread->defineThreadName( "RECV" );
                m_recvThread->start();
            } else {
                // clients run it in the main thread
                m_recvThread->runEventLoop();
                fini();

                // On certain OSes (such as MIC), a call to "exit" is
                // considered an abnormal termination, regarless of
                // the argument.
                if (m_exit0CallOk) exit( 0 );
            }

            return 0;
        }

        //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

        void GenericCommunicator::fini()
        {
            VT_FUNC_I( "Dist::GenComm::fini" );
            // Something to do at all?
            if ( ! m_hasBeenInitialized ) {
                return;
            } else {
                m_hasBeenInitialized = false;
            }

            // Host sends termination requests to the remote clients.
            // Each client will send a response.
            if( m_channel->localId() == 0 ) {
                for ( int client = 1; client < numProcs(); ++client ) {
                    send_termination_request( client );
                }
            }

            // Stop sender and receiver threads:
            if ( m_recvThread ) {
                m_recvThread->stop();
            }
            if ( m_sendThread ) {
                m_sendThread->stop();
            }

            // Cleanup:
            delete m_recvThread;
            m_recvThread = NULL;
            delete m_sendThread;
            m_sendThread = NULL;

            // Cleanup ITAC stuff:
            VT_FINALIZE();
        }

        //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

        void GenericCommunicator::send_msg( serializer * ser, int rcver )
        {
            VT_FUNC_I( "Dist::GenComm::send_msg" );

            // Transform id from global to local:
            rcver -= m_globalIdShift;

            // Check:
            CNC_ASSERT( 0 <= rcver && rcver < m_channel->numProcs() );
            CNC_ASSERT( rcver != m_channel->localId() ); // no message to self allowed
            CNC_ASSERT( m_channel->isActive( rcver ) );

            // Prepare the serializer for sending (add Size, CRC etc.)
            CNC_ASSERT( ser && ser->is_packing() );
            //BufferAccess::finalizePack( *ser );

            // ITAC logging:
#ifdef WITHOUT_SENDER_THREAD_TRACING
            VT_SEND( rcver, (int)ser->get_total_size(), ITC_TAG_EXTERNAL );
#else
            VT_SEND( m_channel->localId(), (int)ser->get_total_size(), ITC_TAG_INTERNAL );
#endif
            // Send data:
            m_sendThread->pushForSend( ser, rcver );
        }

        //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

        void GenericCommunicator::bcast_msg( serializer * ser )
        {
            VT_FUNC_I( "Dist::GenComm::bcast_msg" );

            // Prepare the serializer for sending (add Size, CRC etc.)
            CNC_ASSERT( ser && ser->is_packing() );
            //BufferAccess::finalizePack( *ser );

            // Bcast data:
            m_sendThread->pushForBcast( ser );
        }

        //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

        bool GenericCommunicator::bcast_msg( serializer * ser, const int * rcvers, int nrecvrs )
        {
            VT_FUNC_I( "Dist::GenComm::bcast_msg" );

            // Prepare the serializer for sending (add Size, CRC etc.)
            CNC_ASSERT( ser && ser->is_packing() );
            //BufferAccess::finalizePack( *ser );

            // Bcast data:
            return m_sendThread->pushForBcast( ser, rcvers, nrecvrs, m_globalIdShift );
        }

        //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

        void GenericCommunicator::send_termination_request( int rcverLocalId, bool isBlocking )
        {
            VT_FUNC_I( "Dist::GenComm::send_termination_request" );

            // Send data. No ITAC logging of termination message.
            if ( ! isBlocking ) {
                m_sendThread->pushTerminationRequest( rcverLocalId, 0 );
            }
            else {
                volatile bool myIndicator = false;
                m_sendThread->pushTerminationRequest( rcverLocalId, &myIndicator );
                // Blocking send: wait until the message has been sent successfully:
                while ( ! myIndicator ) {
                    YIELD();
                }
            }
        }

        //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

        void GenericCommunicator::recv_msg_callback( serializer & ser, int sender )
        {
            // ITAC logging:
            VT_RECV( sender, (int)ser.get_total_size(), ITC_TAG_EXTERNAL );

            // Prepare the serializer for unpacking:
            //BufferAccess::initUnpack( ser );

            // Delegate the message to the distributor:
            /*            int globalSenderId = sender + m_globalIdShift; uncomment this for the local tests */
            {
                VT_FUNC( "Dist::distributor::recv_msg" );
                distributor::recv_msg( &ser/*, globalSenderId uncomment this for the local tests */ );
            }
        }

        //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

        bool GenericCommunicator::has_pending_messages()
        {
            return m_sendThread->has_pending_messages();
        }

    } // namespace Internal
} // namespace CnC


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Linq;
using System.Xml.Linq;

namespace ODataReader.v4UnitTests
{
    public static class XElementExtensions
    {
        public static void AddAttribute(this XElement element, string name, object value)
        {
            element.Add(new XAttribute(name, value));
        }

        public static string GetAttribute(this XElement element, string name)
        {
            return element.Attribute(name).Value;
        }

        public static string GetName(this XElement element)
        {
            return element.GetAttribute("Name");
        }

        public static string GetAnnotationTerm(this XElement annotation)
        {
            string termName = string.Empty;
            if (annotation.Name.LocalName == "Annotation")
            {
                termName = annotation.GetAttribute("Term");
            }

            return termName;
        }

        public static void SetAnnotation(this XElement element, XElement annotation)
        {
            string term = annotation.GetAnnotationTerm();

            if (!string.IsNullOrEmpty(term))
            {
                var existing = element
                                .Elements()
                                .FirstOrDefault(e => e.GetAnnotationTerm() == term);

                if (existing != null)
                {
                    element.SetElementValue(existing.Name, null);
                }

                element.Add(annotation);
            }
        }
    }
}