text:
#include "BFForwardModel.h"

// C Includes
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>

// C++ Includes
#include <limits>
#include <iostream>

// MXA includes
#include "MXA/Utilities/MXADir.h"
#include "MXA/Utilities/MXAFileInfo.h"

// Our own includes
#include "MBIRLib/Common/EIMMath.h"
#include "MBIRLib/Common/EIMTime.h"

//#include "MBIRLib/GenericFilters/MRCSinogramInitializer.h"

#include "MBIRLib/BrightField/BFForwardProject.h"
#include "MBIRLib/BrightField/BFUpdateYSlice.h"
#include "MBIRLib/IOFilters/NuisanceParamWriter.h"
#include "MBIRLib/IOFilters/NuisanceParamReader.h"
#include "MBIRLib/GenericFilters/ComputeInitialOffsets.h"
#include "MBIRLib/IOFilters/SinogramBinWriter.h"

#if defined (OpenMBIR_USE_PARALLEL_ALGORITHMS)
#include <tbb/task_scheduler_init.h>
#include <tbb/task_group.h>
#include <tbb/task.h>
#endif

#define MAKE_OUTPUT_FILE(Fp, outdir, filename)\
  {\
    std::string filepath(outdir);\
    filepath = filepath.append(MXADir::getSeparator()).append(filename);\
    errno = 0;\
    Fp = fopen(filepath.c_str(),"wb");\
    if (Fp == NULL || errno > 0) { std::cout << "Error " << errno << " Opening Output file " << filepath << std::endl;}\
  }

#define START_TIMER uint64_t startm = EIMTOMO_getMilliSeconds();
#define STOP_TIMER uint64_t stopm = EIMTOMO_getMilliSeconds();
#define PRINT_TIME(msg)\
  std::cout << indent << msg << ": " << ((double)stopm-startm)/1000.0 << " seconds" << std::endl;

// -----------------------------------------------------------------------------
// Contains all the computations and initializations related to forward model
// -----------------------------------------------------------------------------
BFForwardModel::BFForwardModel() :
  m_Verbose(false), m_VeryVerbose(false), m_ErrorCondition(0), m_Cancel(false), m_UseDefaultOffset(false)
{

  //Hamming Window here
  k_HammingWindow[0][0] = 0.0013;
  k_HammingWindow[0][1] = 0.0086;
  k_HammingWindow[0][2] = 0.0159;
  k_HammingWindow[0][3] = 0.0086;
  k_HammingWindow[0][4] = 0.0013;
  k_HammingWindow[1][0] = 0.0086;
  k_HammingWindow[1][1] = 0.0581;
  k_HammingWindow[1][2] = 0.1076;
  k_HammingWindow[1][3] = 0.0581;
  k_HammingWindow[1][4] = 0.0086;
  k_HammingWindow[2][0] = 0.0159;
  k_HammingWindow[2][1] = 0.1076;
  k_HammingWindow[2][2] = 0.1993;
  k_HammingWindow[2][3] = 0.1076;
  k_HammingWindow[2][4] = 0.0159;
  k_HammingWindow[3][0] = 0.0013;
  k_HammingWindow[3][1] = 0.0086;
  k_HammingWindow[3][2] = 0.0159;
  k_HammingWindow[3][3] = 0.0086;
  k_HammingWindow[3][4] = 0.0013;
  k_HammingWindow[4][0] = 0.0086;
  k_HammingWindow[4][1] = 0.0581;
  k_HammingWindow[4][2] = 0.1076;
  k_HammingWindow[4][3] = 0.0581;
  k_HammingWindow[4][4] = 0.0086;

  m_TargetGain = 0.0;
  m_InitialGain = RealArrayType::NullPointer();
  m_InitialOffset = RealArrayType::NullPointer();
}

// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
BFForwardModel::~BFForwardModel()
{

}

// -----------------------------------------------------------------------------
// Project the object in 3-D
// -----------------------------------------------------------------------------
int BFForwardModel::forwardProject(SinogramPtr sinogram,
                                   GeometryPtr geometry,
                                   std::vector<AMatrixCol::Pointer>& tempCol,
                                   std::vector<AMatrixCol::Pointer>& voxelLineResponse,
                                   RealVolumeType::Pointer yEstimate,
                                   RealVolumeType::Pointer errorSinogram)
{
  std::string indent("  ");

#if defined (OpenMBIR_USE_PARALLEL_ALGORITHMS)
  tbb::task_scheduler_init init;
  //   int m_NumThreads = init.default_num_threads();
#else
  //   int m_NumThreads = 1;
#endif

  notify("Starting Forward Projection", 10, Observable::UpdateProgressValueAndMessage);
  START_TIMER;
  // This next section looks crazy with all the #if's but this makes sure we are
  // running the exact same code whether in parallel or serial.

#if OpenMBIR_USE_PARALLEL_ALGORITHMS
  tbb::task_group* g = new tbb::task_group;
  if(getVerbose())
  {
    std::cout << "Default Number of Threads to Use: " << init.default_num_threads() << std::endl;
    std::cout << "Forward Projection Running in Parallel." << std::endl;
  }
#else
  if(getVerbose())
  {
    std::cout << "Forward Projection Running in Serial." << std::endl;
  }
#endif
  // Queue up a thread for each z layer of the Geometry. The threads will only be
  // run as hardware resources open up so this will not just fire up a gazillion
  // threads.
  for (uint16_t t = 0; t < geometry->N_z; t++)
  {
#if OpenMBIR_USE_PARALLEL_ALGORITHMS
    g->run(BFForwardProject(sinogram.get(), geometry.get(), tempCol, voxelLineResponse, yEstimate, this, t, this));
#else
    // BFForwardProject fp(sinogram.get(), geometry.get(), tempCol, voxelLineResponse, yEstimate, NuisanceParams.get(), t, this);
    BFForwardProject fp(sinogram.get(), geometry.get(), tempCol, voxelLineResponse, yEstimate, this, t, this);
    //fp.setObservers(getObservers());
    fp();
#endif
  }
#if OpenMBIR_USE_PARALLEL_ALGORITHMS
  g->wait(); // Wait for all the threads to complete before moving on.
  delete g;
#endif

  STOP_TIMER;
  PRINT_TIME("Forward Project Time");

  //Calculate Error Sinogram - Can this be combined with previous loop?
  //Also compute weights of the diagonal covariance matrix
  //Calculate Error Sinogram - Can this be combined with previous loop?
  //Also compute weights of the diagonal covariance matrix
  calculateMeasurementWeight(sinogram, errorSinogram, yEstimate);
  return 0;
}

// -----------------------------------------------------------------------------
// Set the prior model parameters
// -----------------------------------------------------------------------------
void BFForwardModel::setQGGMRFValues(QGGMRF::QGGMRF_Values* qggmrf_values)
{
  m_QGGMRF_Values = qggmrf_values;
}

// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void BFForwardModel::printNuisanceParameters(SinogramPtr sinogram)
{
  if(getVeryVerbose())
  {
    // Print out the Initial Gains, Offsets, Variances
    std::cout << "---------------- Initial Gains, Offsets, Variances -------------------" << std::endl;
    std::cout << "Tilt\tGain\tOffset";

    if(NULL != m_InitialVariance.get())
    {
      std::cout << "\tVariance";
    }
    std::cout << std::endl;

    for (uint16_t i_theta = 0; i_theta < sinogram->N_theta; i_theta++)
    {
      std::cout << i_theta << "\t" << m_InitialGain->d[i_theta] << "\t" << m_InitialOffset->d[i_theta];
      if(NULL != m_InitialVariance.get())
      {
        std::cout << "\t" << m_InitialVariance->d[i_theta];
      }
      std::cout << std::endl;
    }
  }
}

// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void BFForwardModel::resetNuisanceParameters()
{
  m_I_0 = RealArrayType::NullPointer();
  m_Mu = RealArrayType::NullPointer();
  m_Alpha = RealArrayType::NullPointer();
}

// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void BFForwardModel::allocateNuisanceParameters(SinogramPtr sinogram)
{
  //Gain, Offset and Variance Parameter Structures
  size_t dims[3];
  dims[1] = sinogram->N_t;
  dims[0] = sinogram->N_theta;
  m_I_0 = RealArrayType::New(dims, "HAADF::NuisanceParams->I_0");
  m_Mu = RealArrayType::New(dims, "HAADF::NuisanceParams->mu");
  if(m_AdvParams->NOISE_ESTIMATION)
  {
    //alpha is the noise variance adjustment factor
    m_Alpha = RealArrayType::New(dims, "HAADF::NuisanceParams->alpha");
  }
  else
  {
    m_Alpha = RealArrayType::NullPointer();
  }
}

// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void BFForwardModel::gainAndOffsetInitialization(uint16_t nTheta)
{
  Real_t sum = 0;
  Real_t temp = 0;
  for (uint16_t k = 0; k < nTheta; k++)
  {
    // Gains
    m_I_0->d[k] = m_InitialGain->d[k];
    // Offsets
    m_Mu->d[k] = m_InitialOffset->d[k];

    sum += m_I_0->d[k];

  }
  sum /= nTheta;

  if(getVerbose())
  {
    printf("The Arithmetic mean of the constraint is %lf\n", sum);
  }
  if(sum - m_TargetGain > 1e-5)
  {
    if(getVerbose())
    {
      printf("Arithmetic Mean Constraint not met..renormalizing\n");
    }
    temp = m_TargetGain / sum;
    for (uint16_t k = 0; k < nTheta; k++)
    {
      m_I_0->d[k] = m_InitialGain->d[k] * temp;
    }
  }

}

// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void BFForwardModel::weightInitialization(size_t dims[3])
{
  m_Weight = RealVolumeType::New(dims, "Weight");
  //This variable selects which entries to retain in the sinogram
  m_Selector = UInt8VolumeType::New(dims, "Selector");

}

// -----------------------------------------------------------------------------
// Calculate Error Sinogram
// Also compute weights of the diagonal covariance matrix
// -----------------------------------------------------------------------------
void BFForwardModel::calculateMeasurementWeight(SinogramPtr sinogram, RealVolumeType::Pointer errorSinogram, RealVolumeType::Pointer yEstimate)
{

  std::cout << "Starting weight assignment" << std::endl;
  std::string indent("  ");
  Real_t checksum = 0;
  START_TIMER;
  for (int16_t i_theta = 0; i_theta < sinogram->N_theta; i_theta++) //slice index
  {
    if(m_AdvParams->NOISE_ESTIMATION)
    {
      m_Alpha->d[i_theta] = m_InitialVariance->d[i_theta]; //Initialize the refinement parameters from any previous run
    } //Noise model

    checksum = 0;
    for (int16_t i_r = 0; i_r < sinogram->N_r; i_r++)
    {
      for (uint16_t i_t = 0; i_t < sinogram->N_t; i_t++)
      {
        size_t counts_idx = sinogram->counts->calcIndex(i_theta, i_r, i_t);
        size_t weight_idx = m_Weight->calcIndex(i_theta, i_r, i_t);
        size_t yest_idx = yEstimate->calcIndex(i_theta, i_r, i_t);
        size_t error_idx = errorSinogram->calcIndex(i_theta, i_r, i_t);

        errorSinogram->d[error_idx] = sinogram->counts->d[counts_idx] - yEstimate->d[yest_idx] - m_Mu->d[i_theta];

#ifndef IDENTITY_NOISE_MODEL
        //If its a bright field recon just over ride the weights
        m_Weight->d[weight_idx] = BF_MAX / exp(sinogram->counts->d[counts_idx]);
#else
        m_Weight->d[weight_idx] = 1.0;
#endif //IDENTITY_NOISE_MODEL endif

        m_Selector->d[weight_idx] = 1; //By default all enties are chosen

#ifdef FORWARD_PROJECT_MODE
        temp = yEstimate->d[i_theta][i_r][i_t] / m_I_0->d[i_theta];
        fwrite(&temp, sizeof(Real_t), 1, Fp6);
#endif

        if(m_AdvParams->NOISE_ESTIMATION)
        {
          m_Weight->d[weight_idx] /= m_Alpha->d[i_theta];
        } // NOISE_MODEL

        checksum += m_Weight->d[weight_idx];
      }
    }
    if(getVerbose())
    {
      printf("Check sum of Diagonal Covariance Matrix= %lf\n", checksum);
    }
  }
  STOP_TIMER;
  PRINT_TIME("Computing Weights");
}

// -----------------------------------------------------------------------------
// Estimation of the unknown dosage parameter
// -----------------------------------------------------------------------------
void BFForwardModel::jointEstimation(SinogramPtr sinogram, RealVolumeType::Pointer errorSinogram, RealVolumeType::Pointer yEstimate, CostData::Pointer cost)
{
  std::stringstream ss;
  std::string indent("  ");

  for (uint16_t i_theta = 0; i_theta < sinogram->N_theta; i_theta++)
  {
    //Estimate unknown offset (log{dosage}) parameter
    Real_t num_sum = 0;
    Real_t den_sum = 0;
    Real_t alpha = 0;
    for (uint16_t i_r = 0; i_r < sinogram->N_r; i_r++)
    {
      for (uint16_t i_t = 0; i_t < sinogram->N_t; i_t++)
      {
        if(m_Selector->getValue(i_theta, i_r, i_t) == 1)
        {
          num_sum += (errorSinogram->getValue(i_theta, i_r, i_t) * m_Weight->getValue(i_theta, i_r, i_t));
          den_sum += m_Weight->getValue(i_theta, i_r, i_t);
        }
        else
        {
          num_sum += (m_BraggThreshold * m_BraggDelta * errorSinogram->getValue(i_theta, i_r, i_t) / fabs(errorSinogram->getValue(i_theta, i_r, i_t))) * sqrt(m_Weight->getValue(i_theta, i_r, i_t));
          den_sum += ((m_BraggThreshold * m_BraggDelta * sqrt(m_Weight->getValue(i_theta, i_r, i_t))) / fabs(errorSinogram->getValue(i_theta, i_r, i_t)));
        }

      }
    }
    //}
    alpha = num_sum / den_sum;

    //Update error sinogram
    //for (uint16_t i_theta = 0; i_theta < sinogram->N_theta; i_theta++)
    //{
    for (uint16_t i_r = 0; i_r < sinogram->N_r; i_r++)
    {
      for (uint16_t i_t = 0; i_t < sinogram->N_t; i_t++)
      {
        errorSinogram->deleteFromValue(alpha, i_theta, i_r, i_t);
      }
    }
    m_Mu->d[i_theta] += alpha;

    if(getVeryVerbose()) //Display the estimated offset
    {
      std::cout << " Mu: " << m_Mu->d[i_theta] << std::endl;
    }
  }

}

// -----------------------------------------------------------------------------
// Updating the Weights for Noise Model
// -----------------------------------------------------------------------------
void BFForwardModel::updateWeights(SinogramPtr sinogram, RealVolumeType::Pointer ErrorSino)
{
  for (uint16_t i_theta = 0; i_theta < sinogram->N_theta; i_theta++)
  {
    //Factoring out the variance parameter from the Weight matrix
    for (uint16_t i_r = 0; i_r < sinogram->N_r; i_r++)
    {
      for (uint16_t i_t = 0; i_t < sinogram->N_t; i_t++)
      {
        size_t weight_idx = m_Weight->calcIndex(i_theta, i_r, i_t);
#ifndef IDENTITY_NOISE_MODEL
        //TODO Just assign this once
        m_Weight->d[weight_idx] *= m_Alpha->d[i_theta];
        //m_Weight->d[weight_idx] = BF_MAX/exp(sinogram->counts->d[counts_idx]);
#else
        m_Weight->d[weight_idx] = 1.0;
#endif//Identity noise Model
      }
    }
  }

  Real_t sum1 = 0, sum2 = 0, update;
  for (uint16_t i_theta = 0; i_theta < sinogram->N_theta; i_theta++)
    for (uint16_t i_r = 0; i_r < sinogram->N_r; i_r++)
      for (uint16_t i_t = 0; i_t < sinogram->N_t; i_t++)
      {
        size_t weight_idx = m_Weight->calcIndex(i_theta, i_r, i_t);
        if(m_Selector->d[weight_idx] == 1)
        { sum1 += (ErrorSino->d[weight_idx] * ErrorSino->d[weight_idx] * m_Weight->d[weight_idx]); }
        else
        { sum2 += fabs(ErrorSino->d[weight_idx]) * sqrt(m_Alpha->d[i_theta] * m_Weight->d[weight_idx]); }
      }
  update = (sum1 + (m_BraggDelta * m_BraggThreshold) * sum2) / (sinogram->N_theta * sinogram->N_r * sinogram->N_t);

  for (uint16_t i_theta = 0; i_theta < sinogram->N_theta; i_theta++)
  {
    m_Alpha->d[i_theta] = update;
  }

  //Update the weights back for future iterations by appropriately scaling it
  //by m_Alpha's
  for (uint16_t i_theta = 0; i_theta < sinogram->N_theta; i_theta++)
    for (uint16_t i_r = 0; i_r < sinogram->N_r; i_r++)
      for (uint16_t i_t = 0; i_t < sinogram->N_t; i_t++)
      {
        size_t weight_idx = m_Weight->calcIndex(i_theta, i_r, i_t);
#ifndef IDENTITY_NOISE_MODEL
        m_Weight->d[weight_idx] /= m_Alpha->d[i_theta]; //Scales the weight appropriately
#else
        m_Weight->d[weight_idx] = 1.0 / m_Alpha->d[i_theta];
#endif //IDENTITY_NOISE_MODEL
      }

  if(getVeryVerbose())
  {
    std::cout << "Noise Model Weights:" << std::endl;
    std::cout << "Tilt\tWeight" << std::endl;
    for (uint16_t i_theta = 0; i_theta < sinogram->N_theta; i_theta++)
    {
      std::cout << i_theta << "\t" << m_Alpha->d[i_theta] << std::endl;
    }
  }

  notify("Update Weights Complete", 0, Observable::UpdateProgressMessage);
}

// -----------------------------------------------------------------------------
// Updating the boolean selector based on the error and weights
// -----------------------------------------------------------------------------
void BFForwardModel::updateSelector(SinogramPtr sinogram,
                                    RealVolumeType::Pointer ErrorSino)
{
  for (uint16_t i_theta = 0; i_theta < sinogram->N_theta; i_theta++)
    for (uint16_t i_r = 0; i_r < sinogram->N_r; i_r++)
      for (uint16_t i_t = 0; i_t < sinogram->N_t; i_t++)
      {
        size_t idx = m_Weight->calcIndex(i_theta, i_r, i_t);
        if(ErrorSino->d[idx] * ErrorSino->d[idx] * m_Weight->d[idx] < m_BraggThreshold * m_BraggThreshold)
        { m_Selector->d[idx] = 1; }
        else
        { m_Selector->d[idx] = 0; }
      }

}

// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void BFForwardModel::writeNuisanceParameters(SinogramPtr sinogram)
{
  NuisanceParamWriter::Pointer nuisanceBinWriter = NuisanceParamWriter::New();
  nuisanceBinWriter->setNtheta(sinogram->N_theta);

  if(m_AdvParams->JOINT_ESTIMATION)
  {
    nuisanceBinWriter->setFileName(m_TomoInputs->gainsOutputFile);
    nuisanceBinWriter->setDataToWrite(NuisanceParamWriter::Nuisance_I_O);
    nuisanceBinWriter->setData(m_I_0);
    nuisanceBinWriter->execute();
    if(nuisanceBinWriter->getErrorCondition() < 0)
    {
      setErrorCondition(-1);
      notify(nuisanceBinWriter->getErrorMessage().c_str(), 100, Observable::UpdateErrorMessage);
    }

    nuisanceBinWriter->setFileName(m_TomoInputs->offsetsOutputFile);
    nuisanceBinWriter->setDataToWrite(NuisanceParamWriter::Nuisance_mu);
    nuisanceBinWriter->setData(m_Mu);
    nuisanceBinWriter->execute();
    if(nuisanceBinWriter->getErrorCondition() < 0)
    {
      setErrorCondition(-1);
      notify(nuisanceBinWriter->getErrorMessage().c_str(), 100, Observable::UpdateErrorMessage);
    }
  }

  if(m_AdvParams->NOISE_ESTIMATION)
  {
    nuisanceBinWriter->setFileName(m_TomoInputs->varianceOutputFile);
    nuisanceBinWriter->setDataToWrite(NuisanceParamWriter::Nuisance_alpha);
    nuisanceBinWriter->setData(m_Alpha);
    nuisanceBinWriter->execute();
    if(nuisanceBinWriter->getErrorCondition() < 0)
    {
      setErrorCondition(-1);
      notify(nuisanceBinWriter->getErrorMessage().c_str(), 100, Observable::UpdateErrorMessage);
    }
  } //Noise Model

  if(getVerbose())
  {
    std::cout << "Tilt\tFinal Gains\tFinal Offsets\tFinal Variances" << std::endl;
    for (uint16_t i_theta = 0; i_theta < sinogram->N_theta; i_theta++)
    {

      if(m_AdvParams->NOISE_ESTIMATION)
      {
        std::cout << i_theta << "\t" << m_I_0->d[i_theta] << "\t" << m_Mu->d[i_theta] << "\t" << m_Alpha->d[i_theta] << std::endl;
      }
      else
      {
        std::cout << i_theta << "\t" << m_I_0->d[i_theta] << "\t" << m_Mu->d[i_theta] << std::endl;
      }
    }
  }

}

// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void BFForwardModel::writeSinogramFile(SinogramPtr sinogram, RealVolumeType::Pointer finalSinogram)
{
  // Write the Sinogram out to a file
  SinogramBinWriter::Pointer sinogramWriter = SinogramBinWriter::New();
  sinogramWriter->setSinogram(sinogram);
  sinogramWriter->setTomoInputs(m_TomoInputs);
  sinogramWriter->setAdvParams(m_AdvParams);
  sinogramWriter->setObservers(getObservers());
  sinogramWriter->setI_0(m_I_0);
  sinogramWriter->setMu(m_Mu);
  sinogramWriter->setData(finalSinogram);
  sinogramWriter->execute();
  if(sinogramWriter->getErrorCondition() < 0)
  {
    setErrorCondition(-1);
    notify(sinogramWriter->getErrorMessage().c_str(), 100, Observable::UpdateErrorMessage);
  }
}

// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
int BFForwardModel::createNuisanceParameters(SinogramPtr sinogram)
{
  int err = 0;
  err |= createInitialGainsData(sinogram);
  err |= createInitialOffsetsData(sinogram);
  err |= createInitialVariancesData(sinogram);
  return err;
}

// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
int BFForwardModel::createInitialGainsData(SinogramPtr sinogram)
{
  std::stringstream ss;
  /* ********************* Initialize the Gains Array **************************/
  size_t gains_dims[1] =
  { sinogram->N_theta };
  m_InitialGain = RealArrayType::New(gains_dims, "sinogram->InitialGain");
  if(m_TomoInputs->gainsInputFile.empty() == false)
  {
    // Read the initial Gains from a File
    NuisanceParamReader::Pointer gainsInitializer = NuisanceParamReader::New();
    gainsInitializer->setFileName(m_TomoInputs->gainsInputFile);
    gainsInitializer->setData(m_InitialGain);
    gainsInitializer->setSinogram(sinogram);
    gainsInitializer->setAdvParams(m_AdvParams);
    gainsInitializer->setTomoInputs(m_TomoInputs);
    //   gainsInitializer->setGeometry(geometry);
    gainsInitializer->setObservers(getObservers());
    gainsInitializer->execute();
    if(gainsInitializer->getErrorCondition() < 0)
    {
      notify("Error initializing Input Gains from Data file", 100, Observable::UpdateErrorMessage);
      setErrorCondition(gainsInitializer->getErrorCondition());
      return -1;
    }
  }
  else
  {
    // Set the values to the target gain value set by the user
    for (uint16_t i_theta = 0; i_theta < sinogram->N_theta; i_theta++)
    {
      m_InitialGain->d[i_theta] = m_TargetGain;
    }
  }
  /********************REMOVE************************/
  ss << "HARD WIRED TARGET GAIN" << std::endl;
  ss << "Target Gain: " << m_TargetGain << std::endl;
  /*************************************************/

  if(getVeryVerbose())
  {
    std::cout << ss.str() << std::endl;
  }
  return 0;
}

// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
int BFForwardModel::createInitialOffsetsData(SinogramPtr sinogram)
{
  std::stringstream ss;
  /* ********************* Initialize the Offsets Array **************************/
  size_t offsets_dims[1] =
  { sinogram->N_theta };
  m_InitialOffset = RealArrayType::New(offsets_dims, "sinogram->InitialOffset");
  if(m_TomoInputs->offsetsInputFile.empty() == false)
  {
    // Read the initial offsets from a File
    NuisanceParamReader::Pointer offsetsInitializer = NuisanceParamReader::New();
    offsetsInitializer->setFileName(m_TomoInputs->offsetsInputFile);
    offsetsInitializer->setData(m_InitialOffset);
    offsetsInitializer->setSinogram(sinogram);
    offsetsInitializer->setAdvParams(m_AdvParams);
    offsetsInitializer->setTomoInputs(m_TomoInputs);
    //    offsetsInitializer->setGeometry(geometry);
    offsetsInitializer->setObservers(getObservers());
    offsetsInitializer->execute();
    if(offsetsInitializer->getErrorCondition() < 0)
    {
      notify("Error initializing Input Offsets from Data file", 100, Observable::UpdateErrorMessage);
      setErrorCondition(offsetsInitializer->getErrorCondition());
      return -1;
    }
  }
  else if(m_UseDefaultOffset == true)
  {
    // Set the values to the default offset value set by the user
    for (uint16_t i_theta = 0; i_theta < sinogram->N_theta; i_theta++)
    {
      m_InitialOffset->d[i_theta] = m_DefaultOffset;
    }
  }
  else
  {
    // Compute the initial offset values from the data
    ComputeInitialOffsets::Pointer initializer = ComputeInitialOffsets::New();
    initializer->setSinogram(sinogram);
    initializer->setTomoInputs(m_TomoInputs);
    initializer->setAdvParams(m_AdvParams);
    initializer->setInitialOffset(m_InitialOffset);
    initializer->setObservers(getObservers());
    initializer->setVerbose(getVerbose());
    initializer->setVeryVerbose(getVeryVerbose());
    initializer->execute();
    if(initializer->getErrorCondition() < 0)
    {
      notify("Error initializing Input Offsets Data file", 100, Observable::UpdateErrorMessage);
      setErrorCondition(initializer->getErrorCondition());
      return -1;
    }

    //TODO : HACK to just read offsets from a initial file
    FILE* fp;
    char PathStr[] = "AlTEMOffsets.bin";
    fp = fopen(PathStr, "rb");
    if(fp == NULL)
    {
      std::cout << "File not found '" << PathStr << "'" << std::endl;
    }
    else
    {
      Real_t temp;
      std::cout << "------ Printing Tilt Angles --------" << std::endl;
      for(uint16_t i_theta = 0; i_theta < sinogram->N_theta; i_theta++)
      {
        std::cout << i_theta << std::endl;
        fread(&temp, sizeof(Real_t), 1, fp);
        m_InitialOffset->d[i_theta] = -temp;
      }
      fclose(fp);
    }
  }

  return 0;
}

// -----------------------------------------------------------------------------
// Initialize the variance parameter
// -----------------------------------------------------------------------------
int BFForwardModel::createInitialVariancesData(SinogramPtr sinogram)
{

  /* ********************* Initialize the Variances Array **************************/
  size_t variance_dims[1] =
  { sinogram->N_theta };
  m_InitialVariance = RealArrayType::New(variance_dims, "sinogram->InitialVariance");
  if(m_TomoInputs->varianceInputFile.empty() == false)
  {
    // Read the initial variances from a File
    NuisanceParamReader::Pointer variancesInitializer = NuisanceParamReader::New();
    variancesInitializer->setFileName(m_TomoInputs->varianceInputFile);
    variancesInitializer->setData(m_InitialVariance);
    variancesInitializer->setSinogram(sinogram);
    variancesInitializer->setTomoInputs(m_TomoInputs);

    variancesInitializer->setAdvParams(m_AdvParams);
    variancesInitializer->setObservers(getObservers());
    variancesInitializer->setVerbose(getVerbose());
    variancesInitializer->setVeryVerbose(getVeryVerbose());
    variancesInitializer->execute();
    if(variancesInitializer->getErrorCondition() < 0)
    {
      notify("Error initializing Input Variances from Data file", 100, Observable::UpdateErrorMessage);
      setErrorCondition(variancesInitializer->getErrorCondition());
      return -1;
    }
  }
  else
  {
    std::stringstream ss;
    for (uint16_t i_theta = 0; i_theta < sinogram->N_theta; i_theta++)
    {
      m_InitialVariance->d[i_theta] = m_DefaultVariance;
      ss << "Tilt: " << i_theta << "  Variance: " << m_InitialVariance->d[i_theta] << std::endl;
    }
    if(getVeryVerbose())
    {
      std::cout << ss.str() << std::endl;
    }
  }

  return 0;
}

// -----------------------------------------------------------------------------
// Compute forward model cost
// -----------------------------------------------------------------------------
Real_t BFForwardModel::forwardCost(SinogramPtr sinogram, RealVolumeType::Pointer ErrorSino)
{
  Real_t cost = 0, temp = 0;
  Real_t errSinoValue = 0.0;

  //Data Mismatch Error

  for (int16_t i = 0; i < sinogram->N_theta; i++)
  {
    for (int16_t j = 0; j < sinogram->N_r; j++)
    {
      for (int16_t k = 0; k < sinogram->N_t; k++)
      {
        errSinoValue = ErrorSino->getValue(i, j, k);
        if(m_Selector->getValue(i, j, k) == 1)
        { cost += (errSinoValue * errSinoValue * m_Weight->getValue(i, j, k)); }
        else
        { cost += (2 * m_BraggThreshold * m_BraggDelta * fabs(errSinoValue) * sqrt(m_Weight->getValue(i, j, k)) + m_BraggThreshold * m_BraggThreshold * (1 - 2 * m_BraggDelta)); }
      }
    }
  }

  cost /= 2;

  //Noise Error
  if(m_AdvParams->NOISE_ESTIMATION)
  {
    temp = (sinogram->N_theta * sinogram->N_r * sinogram->N_t / 2) * log(m_Alpha->d[0]);
    //TODO : This assume a single parameter for the variance. Hence the use of m_Alpha->d[0]. Fix
    cost += temp;
  }
  //NOISE_MODEL

  return cost;
}
// -----------------------------------------------------------------------------
// Compute the theta1 and theta2 for a single voxel update - Computataionally
// intensive
// -----------------------------------------------------------------------------
void BFForwardModel::computeTheta(size_t Index,
                                  std::vector<AMatrixCol::Pointer>& TempCol,
                                  int32_t xzSliceIdx,
                                  std::vector<AMatrixCol::Pointer>& VoxelLineResponse,
                                  RealVolumeType::Pointer ErrorSino,
                                  SinogramPtr sinogram,
                                  RealArrayType::Pointer Thetas)
{

  Thetas->d[0] = 0;
  Thetas->d[1] = 0;

  for (uint32_t q = 0; q < TempCol[Index]->count; q++)
  {
    uint16_t i_theta = floor(static_cast<float>(TempCol[Index]->index[q] / (sinogram->N_r)));
    uint16_t i_r = (TempCol[Index]->index[q] % (sinogram->N_r));
    Real_t kConst0 = m_I_0->d[i_theta] * (TempCol[Index]->values[q]);
    uint16_t VoxelLineAccessCounter = 0;
    uint32_t vlrCount = VoxelLineResponse[xzSliceIdx]->index[0] + VoxelLineResponse[xzSliceIdx]->count;
    for (uint32_t i_t = VoxelLineResponse[xzSliceIdx]->index[0]; i_t < vlrCount; i_t++)
    {

      size_t error_idx = ErrorSino->calcIndex(i_theta, i_r, i_t);
      if(m_Selector->d[error_idx] == 1)
      {
        Real_t ProjectionEntry = kConst0 * VoxelLineResponse[xzSliceIdx]->values[VoxelLineAccessCounter];
        Thetas->d[1] += (ProjectionEntry * ProjectionEntry * m_Weight->d[error_idx]);
        Thetas->d[0] += (ErrorSino->d[error_idx] * ProjectionEntry * m_Weight->d[error_idx]);
        VoxelLineAccessCounter++;
      }
      else
      {
        Real_t QuadCoeff = (m_BraggDelta * m_BraggThreshold) / (fabs(ErrorSino->d[error_idx]) * sqrt(m_Weight->d[error_idx]));
        Real_t ProjectionEntry = kConst0 * VoxelLineResponse[xzSliceIdx]->values[VoxelLineAccessCounter];
        Thetas->d[1] += QuadCoeff * (ProjectionEntry * ProjectionEntry * m_Weight->d[error_idx]);
        Thetas->d[0] += QuadCoeff * (ErrorSino->d[error_idx] * ProjectionEntry * m_Weight->d[error_idx]);
        VoxelLineAccessCounter++;
      }
    }
  }
  Thetas->d[0] *= -1;
}

// -----------------------------------------------------------------------------
// Updates the error sinogram after a single voxel update; Also updates
// the selector variable simultaneously
// -----------------------------------------------------------------------------
void BFForwardModel::updateErrorSinogram(Real_t ChangeInVoxelValue,
                                         size_t Index,
                                         std::vector<AMatrixCol::Pointer>& TempCol,
                                         int32_t xzSliceIdx,
                                         std::vector<AMatrixCol::Pointer>& VoxelLineResponse,
                                         RealVolumeType::Pointer ErrorSino,
                                         SinogramPtr sinogram)
{
  Real_t kConst2 = 0.0;
  //Update the ErrorSinogram
  for (uint32_t q = 0; q < TempCol[Index]->count; q++)
  {
    uint16_t i_theta = floor(static_cast<float>(TempCol[Index]->index[q] / (sinogram->N_r)));
    uint16_t i_r = (TempCol[Index]->index[q] % (sinogram->N_r));
    uint16_t VoxelLineAccessCounter = 0;
    for (uint32_t i_t = VoxelLineResponse[xzSliceIdx]->index[0]; i_t < VoxelLineResponse[xzSliceIdx]->index[0] + VoxelLineResponse[xzSliceIdx]->count; i_t++)
    {
      size_t error_idx = ErrorSino->calcIndex(i_theta, i_r, i_t);
      kConst2 = (m_I_0->d[i_theta]
                 * (TempCol[Index]->values[q] * VoxelLineResponse[xzSliceIdx]->values[VoxelLineAccessCounter] * (ChangeInVoxelValue)));

      ErrorSino->d[error_idx] -= kConst2;

      VoxelLineAccessCounter++;
      // Update the selector variable
      if(fabs(ErrorSino->d[error_idx]*sqrt(m_Weight->d[error_idx])) < m_BraggThreshold)
      { m_Selector->d[error_idx] = 1; }
      else
      {
        m_Selector->d[error_idx] = 0;
      }
    }
  }
}

// -----------------------------------------------------------------------------
// Process the input counts and compute the sinogram
// -----------------------------------------------------------------------------
void BFForwardModel::processRawCounts(SinogramPtr sinogram)
{
  Real_t mean = 0, maxval = -std::numeric_limits<Real_t>::infinity(); // -INFINITY;
  for (int16_t i_theta = 0; i_theta < sinogram->N_theta; i_theta++) //slice index
  {
    for (int16_t i_r = 0; i_r < sinogram->N_r; i_r++)
    {
      for (uint16_t i_t = 0; i_t < sinogram->N_t; i_t++)
      {
        size_t counts_idx = sinogram->counts->calcIndex(i_theta, i_r, i_t);
        sinogram->counts->d[counts_idx] += m_BfOffset;//;BF_OFFSET;

        if(sinogram->counts->d[counts_idx] < 0)
        {
          std::cout << "Error: Negative counts! The offset value is not correctly set" << std::endl;
          break;
        }

        sinogram->counts->d[counts_idx] = -log(sinogram->counts->d[counts_idx] / BF_MAX);

        // if(sinogram->counts->d[counts_idx] < 0 ) //Clip the log data to be positive
        //     sinogram->counts->d[counts_idx] = 0;

        //Debug/Sanity checks
        mean += sinogram->counts->d[counts_idx];
        if(fabs(sinogram->counts->d[counts_idx]) > maxval)
        { maxval = sinogram->counts->d[counts_idx]; }
      }
    }
  }
  mean /= (sinogram->N_theta * sinogram->N_r * sinogram->N_t);
  std::cout << "Mean log value =" << mean << std::endl;
  std::cout << "Max -log value =" << maxval << std::endl;
}

// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void BFForwardModel::printRatioSelected(SinogramPtr sinogram)
{
  Real_t sum = 0;
  for (int16_t i_theta = 0; i_theta < sinogram->N_theta; i_theta++) //slice index
  {
    Real_t sum_k = 0; //Sum for each tilt
    for (int16_t i_r = 0; i_r < sinogram->N_r; i_r++)
    {
      for (uint16_t i_t = 0; i_t < sinogram->N_t; i_t++)
      {
        size_t counts_idx = sinogram->counts->calcIndex(i_theta, i_r, i_t);
        sum_k += m_Selector->d[counts_idx];
      }
    }
    if(getVeryVerbose())
    {
      std::cout << "Ratio of sinogram at tilt :" << i_theta << " " << sum_k / (sinogram->N_r * sinogram->N_t) << std::endl;
    }
    sum += sum_k;
  }

  if(getVeryVerbose()) {std::cout << "Ratio of singoram entries used=" << sum / (sinogram->N_theta * sinogram->N_r * sinogram->N_t) << std::endl;}
}

void BFForwardModel::writeSelectorMrc(const std::string& file, SinogramPtr sinogram, GeometryPtr geometry, RealVolumeType::Pointer ErrorSino)
{
  //const std::string mrcFile="Selector.mrc";
  geometry->N_x = sinogram->N_r;
  geometry->N_y = sinogram->N_t;
  geometry->N_z = sinogram->N_theta;
  geometry->Object = sinogram->counts;
  for(uint32_t i_theta = 0; i_theta <  geometry->N_z; i_theta++)
  {
    for(uint32_t i_r = 0; i_r < geometry->N_x; i_r++)
      for(uint32_t i_t = 0; i_t < geometry->N_y; i_t++)
      {
        size_t counts_idx = sinogram->counts->calcIndex(i_theta, i_r, i_t);
        Real_t value = m_Selector->d[counts_idx];//exp(-sinogram->counts->d[counts_idx]+ErrorSino->d[counts_idx]);
        //value -= BF_OFFSET;
        counts_idx = sinogram->counts->calcIndex(i_theta, i_r, i_t);
        geometry->Object->d[counts_idx] = value;
      }
  }
  uint16_t cropStart = 0;
  uint16_t cropEnd = geometry->N_x;
  /* Write the output to the MRC File */
  std::stringstream ss;
  ss.str("");
  ss << "Writing selector MRC file to '" << file << "'";
  notify(ss.str(), 0, Observable::UpdateProgressMessage);

  MRCWriter::Pointer mrcWriter = MRCWriter::New();
  //  mrcWriter->setOutputFile(mrcFile);
  mrcWriter->setOutputFile(file);
  mrcWriter->setGeometry(geometry);
  mrcWriter->setAdvParams(m_AdvParams);
  mrcWriter->setXDims(cropStart, cropEnd);
  mrcWriter->setYDims(0, geometry->N_y);
  mrcWriter->setZDims(0, geometry->N_z);
  mrcWriter->setObservers(getObservers());
  mrcWriter->execute();
  if(mrcWriter->getErrorCondition() < 0)
  {
    ss.str("");
    ss << "Error writing Selector MRC file\n    '" << file << "'" << std::endl;
    setErrorCondition(mrcWriter->getErrorCondition());
    notify(ss.str(), 0, Observable::UpdateErrorMessage);
  }
}

//This function is REDUNDANT - Not used in current version
Real_t BFForwardModel::estimateBraggThreshold(SinogramPtr sinogram, RealVolumeType::Pointer ErrorSino, Real_t percentage)
{

  Real_t EstBraggThresh = 0.0;
  uint32_t NumElts = sinogram->N_theta * sinogram->N_r * sinogram->N_t;
  uint32_t NumEltsReject = percentage * NumElts; //Find the Error*Weight
  //corresponding to this order statistic
  RealArrayType::Pointer Ratio;
  size_t dims[1] = {NumElts};
  Ratio = RealArrayType::New(dims, "Ratio of error to noise variance");
  uint32_t counts = 0;
  for(uint32_t i_theta = 0; i_theta <  sinogram->N_theta; i_theta++)
    for(uint32_t i_r = 0; i_r < sinogram->N_r; i_r++)
      for(uint32_t i_t = 0; i_t < sinogram->N_t; i_t++)
      {
        size_t counts_idx = sinogram->counts->calcIndex(i_theta, i_r, i_t);
        Ratio->d[counts] = ErrorSino->d[counts_idx] * m_Weight->d[counts_idx];
        Ratio->d[counts] *= ErrorSino->d[counts_idx];
        counts++;
      }
  std::cout << "Num Elts" << counts << std::endl;
  std::cout << "Num Elts to reject =" << NumEltsReject << std::endl;

  std::cout << "Bragg Thresh estimated using Randomized select" << EstBraggThresh << std::endl;

  return EstBraggThresh;
}


text:
package org.apache.lens.cli.commands;

import com.google.common.base.Joiner;

import org.apache.lens.api.APIResult;
import org.springframework.shell.core.CommandMarker;
import org.springframework.shell.core.annotation.CliCommand;
import org.springframework.shell.core.annotation.CliOption;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * The Class LensDatabaseCommands.
 */
@Component
public class LensDatabaseCommands extends BaseLensCommand implements CommandMarker {

  /**
   * Show all databases.
   *
   * @return the string
   */
  @CliCommand(value = "show databases", help = "displays list of all databases")
  public String showAllDatabases() {
    List<String> databases = getClient().getAllDatabases();
    if (databases != null) {
      return Joiner.on("\n").join(databases);
    } else {
      return "No Dabases found";
    }
  }

  /**
   * Switch database.
   *
   * @param database
   *          the database
   * @return the string
   */
  @CliCommand(value = "use", help = "change to new database")
  public String switchDatabase(
      @CliOption(key = { "", "db" }, mandatory = true, help = "Database to change to") String database) {
    boolean status = getClient().setDatabase(database);
    if (status) {
      return "Successfully switched to " + database;
    } else {
      return "Failed to switch to " + database;
    }
  }

  /**
   * Creates the database.
   *
   * @param database
   *          the database
   * @param ignore
   *          the ignore
   * @return the string
   */
  @CliCommand(value = "create database", help = "create a database with specified name")
  public String createDatabase(
      @CliOption(key = { "", "db" }, mandatory = true, help = "Database to create") String database,
      @CliOption(key = { "ignore" }, mandatory = false, unspecifiedDefaultValue = "false") boolean ignore) {
    APIResult result = getClient().createDatabase(database, ignore);
    if (result.getStatus() == APIResult.Status.SUCCEEDED) {
      return ("Create database " + database + " successful");
    } else {
      return result.getMessage();
    }
  }

  /**
   * Drop database.
   *
   * @param database
   *          the database
   * @return the string
   */
  @CliCommand(value = "drop database", help = "drop a database with specified name")
  public String dropDatabase(@CliOption(key = { "", "db" }, mandatory = true, help = "Database to drop") String database) {
    APIResult result = getClient().dropDatabase(database);
    if (result.getStatus() == APIResult.Status.SUCCEEDED) {
      return ("drop database " + database + " successful");
    } else {
      return result.getMessage();
    }
  }

}

redpajama_set_name: RedPajamaGithub


text:
package jp.co.opentone.bsol.linkbinder.dao.mock;

import java.util.ArrayList;
import java.util.List;

import jp.co.opentone.bsol.framework.core.dao.KeyDuplicateException;
import jp.co.opentone.bsol.framework.core.dao.RecordNotFoundException;
import jp.co.opentone.bsol.framework.core.dao.StaleRecordException;
import jp.co.opentone.bsol.linkbinder.dao.AbstractDao;
import jp.co.opentone.bsol.linkbinder.dao.SiteDao;
import jp.co.opentone.bsol.linkbinder.dto.Site;
import jp.co.opentone.bsol.linkbinder.dto.User;
import jp.co.opentone.bsol.linkbinder.dto.condition.SearchSiteCondition;

/**
 *
 * @author opentone
 *
 */
public class SiteDaoMock extends AbstractDao<Site> implements SiteDao {

    /**
     * serialVersionUID.
     */
    private static final long serialVersionUID = -4997253313308856984L;

    public SiteDaoMock() {
        super("mock");
    }

    /*
     * (non-Javadoc)
     * @see
     * jp.co.opentone.bsol.linkbinder.dao.SiteDao#find(jp.co.opentone.bsol.linkbinder.dto.SearchSiteCondition
     * )
     */
    public List<Site> find(SearchSiteCondition condition) {
        User user = new User();
        user.setEmpNo("ZZA01");
        user.setNameE("Taro Yamada");
        List<Site> sites = new ArrayList<Site>();

        Site site = new Site();
        site.setId(1L);
        site.setSiteCd("YOC");
        site.setName("Yocohama");
        site.setDeleteNo(0L);
        site.setVersionNo(1L);
        site.setProjectId("PJ1");
        site.setProjectNameE("Test Project1");
        site.setCreatedBy(user);
        site.setUpdatedBy(user);

        sites.add(site);

        site = new Site();
        site.setId(2L);
        site.setSiteCd("SJK");
        site.setName("Shinjuku");
        site.setDeleteNo(0L);
        site.setVersionNo(1L);
        site.setProjectId("PJ1");
        site.setProjectNameE("Test Project1");
        site.setCreatedBy(user);
        site.setUpdatedBy(user);

        sites.add(site);

        site = new Site();
        site.setId(3L);
        site.setSiteCd("JOG");
        site.setName("Jogi");
        site.setDeleteNo(0L);
        site.setVersionNo(1L);
        site.setProjectId("PJ1");
        site.setProjectNameE("Test Project1");
        site.setCreatedBy(user);
        site.setUpdatedBy(user);

        sites.add(site);

        return sites;
    }

    @Override
    public Long create(Site entity) throws KeyDuplicateException {
        return null;
    }

    @Override
    public Integer delete(Site entity) throws KeyDuplicateException, StaleRecordException {
        return null;
    }

    /*
     * (.framework.core.dao * @see
     * GenericDao#findById(java.lang.Long)
     */
    @Override
    public Site findById(Long id) throws RecordNotFoundException {
        return null;
    }

    /*
     * .framework.core.daooc)
     * @see
     * GenericDao#findByIdForUpdate(java.lang.Long)
     */
    @Override
    public Site findByIdForUpdate(Long id) throws RecordNotFoundException {
        return null;
    }

    /*
     * .framework.core.daoJavadoc)
     * @see
     * jp.co..framework.core.daocore.dao.GenericDao#update(jp.co.opentone.bsol.framework
     * .core.dao.Entity)
     */
    @Override
    public Integer update(Site entity) throws KeyDuplicateException, StaleRecordException {
        return null;
    }

    /*
     * (non-Javadoc)
     * @see
     * jp.co.opentone.bsol.linkbinder.dao.SiteDao#count(jp.co.opentone.bsol.linkbinder.dto.SearchSiteCondition
     * )
     */
    public int count(SearchSiteCondition condition) {
        return 2;
    }

    /*
     * (non-Javadoc)
     * @see
     * jp.co.opentone.bsol.linkbinder.dao.SiteDao#countCheck(jp.co.opentone.bsol.linkbinder.dto.condition
     * .SearchSiteCondition)
     */
    public int countCheck(SearchSiteCondition condition) {
        return 1;
    }

}


text:
/*	$NetBSD: acpi_acad.c,v 1.2 2001/11/13 13:01:57 lukem Exp $	*/

/*
 * Copyright 2001 Wasabi Systems, Inc.
 * All rights reserved.
 *
 * Written by Jason R. Thorpe for Wasabi Systems, Inc.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *	This product includes software developed for the NetBSD Project by
 *	Wasabi Systems, Inc.
 * 4. The name of Wasabi Systems, Inc. may not be used to endorse
 *    or promote products derived from this software without specific prior
 *    written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY WASABI SYSTEMS, INC. ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL WASABI SYSTEMS, INC
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

/*
 * ACPI AC Adapter driver.
 */

#include <sys/cdefs.h>
__KERNEL_RCSID(0, "$NetBSD: acpi_acad.c,v 1.2 2001/11/13 13:01:57 lukem Exp $");

#include <sys/param.h>
#include <sys/systm.h>
#include <sys/device.h>

#include <dev/acpi/acpica.h>
#include <dev/acpi/acpireg.h>
#include <dev/acpi/acpivar.h>

struct acpiacad_softc {
	struct device sc_dev;		/* base device glue */
	struct acpi_devnode *sc_node;	/* our ACPI devnode */
	int sc_flags;			/* see below */
	int sc_status;			/* power status */
};

#define	AACAD_F_VERBOSE		0x01	/* verbose events */

int	acpiacad_match(struct device *, struct cfdata *, void *);
void	acpiacad_attach(struct device *, struct device *, void *);

struct cfattach acpiacad_ca = {
	sizeof(struct acpiacad_softc), acpiacad_match, acpiacad_attach,
};

void	acpiacad_get_status(void *);
void	acpiacad_notify_handler(ACPI_HANDLE, UINT32, void *context);

/*
 * acpiacad_match:
 *
 *	Autoconfiguration `match' routine.
 */
int
acpiacad_match(struct device *parent, struct cfdata *match, void *aux)
{
	struct acpi_attach_args *aa = aux;

	if (aa->aa_node->ad_type != ACPI_TYPE_DEVICE)
		return (0);

	if (strcmp(aa->aa_node->ad_devinfo.HardwareId, "ACPI0003") == 0)
		return (1);

	return (0);
}

/*
 * acpiacad_attach:
 *
 *	Autoconfiguration `attach' routine.
 */
void
acpiacad_attach(struct device *parent, struct device *self, void *aux)
{
	struct acpiacad_softc *sc = (void *) self;
	struct acpi_attach_args *aa = aux;
	ACPI_STATUS rv;

	printf(": ACPI AC Adapter\n");

	sc->sc_node = aa->aa_node;

	rv = AcpiInstallNotifyHandler(sc->sc_node->ad_handle,
	    ACPI_DEVICE_NOTIFY, acpiacad_notify_handler, sc);
	if (rv != AE_OK) {
		printf("%s: unable to register DEVICE NOTIFY handler: %d\n",
		    sc->sc_dev.dv_xname, rv);
		return;
	}

	/* XXX See acpiacad_notify_handler() */
	rv = AcpiInstallNotifyHandler(sc->sc_node->ad_handle,
	    ACPI_SYSTEM_NOTIFY, acpiacad_notify_handler, sc);
	if (rv != AE_OK) {
		printf("%s: unable to register SYSTEM NOTIFY handler: %d\n",
		    sc->sc_dev.dv_xname, rv);
		return;
	}

	/* Display the current state. */
	sc->sc_flags = AACAD_F_VERBOSE;
	acpiacad_get_status(sc);

	/*
	 * XXX Hook into sysmon here.
	 */
}

/*
 * acpiacad_get_status:
 *
 *	Get, and possibly display, the current AC line status.
 */
void
acpiacad_get_status(void *arg)
{
	struct acpiacad_softc *sc = arg;

	if (acpi_eval_integer(sc->sc_node->ad_handle, "_PSR",
	    &sc->sc_status) != AE_OK)
		return;

	if (sc->sc_flags & AACAD_F_VERBOSE)
		printf("%s: AC adapter %sconnected\n",
		    sc->sc_dev.dv_xname, sc->sc_status == 0 ? "not " : "");
}

/*
 * acpiacad_notify_handler:
 *
 *	Callback from ACPI interrupt handler to notify us of an event.
 */
void
acpiacad_notify_handler(ACPI_HANDLE handle, UINT32 notify, void *context)
{
	struct acpiacad_softc *sc = context;
	int rv;

	switch (notify) {
	/*
	 * XXX So, BusCheck is not exactly what I would expect,
	 * but at least my IBM T21 sends it on AC adapter status
	 * change.  --thorpej@wasabisystems.com
	 */
	case ACPI_NOTIFY_BusCheck:
	case ACPI_NOTIFY_PowerSourceStatusChanged:
#ifdef ACPI_ACAD_DEBUG
		printf("%s: received notify message: 0x%x\n",
		    sc->sc_dev.dv_xname, notify);
#endif
		rv = AcpiOsQueueForExecution(OSD_PRIORITY_LO,
		    acpiacad_get_status, sc);
		if (rv != AE_OK)
			printf("%s: unable to queue status check: %d\n",
			    sc->sc_dev.dv_xname, rv);
		break;

	default:
		printf("%s: received unknown notify message: 0x%x\n",
		    sc->sc_dev.dv_xname, notify);
	}
}


text:
process.env.NODE_ENV = 'test';

const chai = require('chai');
const should = chai.should();
const chaiHttp = require('chai-http');
const server = require('../app');
const { knex } = require('../db/database');
chai.use(chaiHttp);

describe('Restaurant routes', () => {

  // beforeEach( () => {
  //   return knex.migrate.rollback()
  //   .then( () => {
  //     return knex.migrate.latest()
  //   })
  //   .then( () => {
  //     return knex.seed.run()
  //   });
  // });

  describe('Get all the restaurants', () => {
    it('should get all restaurants', () => {
      return chai.request(server)
      .get('/api/v1/restaurants')
      .then( (res) => {
        res.should.have.status(200);
        res.should.be.json
        res.body.should.be.a('array');
        res.body[0].should.have.property('name');
        res.body[0].name.should.equal('The Catbird Seat');
      });
    });
  });

  describe('GET /api/v1/restaurants/:id', () => {
    it('should return a restaurant', () => {
     return chai.request(server)
     .get('/api/v1/restaurants/the-catbird-seat-nashville')
     .then( (res) => {
      res.should.have.status(200);
      res.should.be.json;
      res.body.should.be.a('object');
      res.body.should.have.property('name');
      res.body.name.should.equal('The Catbird Seat');
     });

    });
  });

});

// describe('User routes', () => {

//   describe('GET /api/v1/users/', () => {
//     it('should return users by restaurant', () => {
//      return chai.request(server)
//      .get('/api/v1/restaurants/the-catbird-seat-nashville')
//      .then( (res) => {
//       res.should.have.status(200);
//       res.should.be.json;
//       res.body.should.be.a('object');
//       res.body.should.have.property('name');
//       res.body.name.should.equal('The Catbird Seat');
//      });

//     });
//   });

// })


text:
package member

import (
	"github.com/watermint/toolbox/quality/recipe/qtr_endtoend"
	"testing"
)

func TestReplication_Exec(t *testing.T) {
	qtr_endtoend.TestRecipe(t, &Replication{})
}


text:
using safnet.iba.Business.Entities.Observations;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using safnet.iba.Business.Entities;

namespace safnet.iba.UnitTest
{

    ///
    ///This is a test class for tPointCountBeyond50 and is intended
    ///to contain all tPointCountBeyond50 Unit Tests
    ///
    [TestClass()]
    public class tPointCountBeyond50
    {

        ///
        ///A test for PointCountBeyond50 Constructor
        ///
        [TestMethod()]
        public void t_PointCountBeyond50Constructor()
        {
            PointCountBeyond50 target = new PointCountBeyond50();
            Assert.IsNotNull(target);
        }

        ///
        ///A test for CreateNewPointCountObservation
        ///
        [TestMethod()]
        [HostType("Moles")]
        public void t_CreateNewPointCountObservation()
        {
            safnet.iba.Business.Entities.Moles.MSafnetBaseEntity.AllInstances.SetNewId = (SafnetBaseEntity entity) => { return entity.Id = LookupConstants.LocationTypeParent; };

            Guid surveyId = LookupConstants.LocationTypePoint;

            PointCountBeyond50 actual = PointCountBeyond50.CreateNewPointCountObservation(surveyId);
            Assert.IsNotNull(actual, "object is null");
            Assert.AreEqual(0, actual.Id, "ID not assigned");
            Assert.AreEqual(surveyId, actual.EventId, "EventId not assigned");
        }

        ///
        ///A test for ObservationTypeId
        ///
        [TestMethod()]
        public void t_ObservationTypeId()
        {
            PointCountBeyond50 target = new PointCountBeyond50();

            Guid actual;
            actual = target.ObservationTypeId;
            Assert.AreEqual(LookupConstants.ObservationTypePointBeyond50m, actual);
        }
    }
}


text:
package org.apache.pulsar.client.api;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

import lombok.Cleanup;

import org.apache.pulsar.client.impl.ConsumerImpl;
import org.apache.pulsar.client.impl.MessageIdImpl;
import org.apache.pulsar.common.util.FutureUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

import com.google.common.collect.Sets;

import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertNull;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.assertEquals;

@Test(groups = "broker-api")
public class ConsumerRedeliveryTest extends ProducerConsumerBase {

    private static final Logger log = LoggerFactory.getLogger(ConsumerRedeliveryTest.class);

    @BeforeClass
    @Override
    protected void setup() throws Exception {
        conf.setManagedLedgerCacheEvictionIntervalMs(10000);
        super.internalSetup();
        super.producerBaseSetup();
    }

    @AfterClass(alwaysRun = true)
    @Override
    protected void cleanup() throws Exception {
        super.internalCleanup();
    }

    @DataProvider(name = "ackReceiptEnabled")
    public Object[][] ackReceiptEnabled() {
        return new Object[][] { { true }, { false } };
    }

    /**
     * It verifies that redelivered messages are sorted based on the ledger-ids.
     * <pre>
     * 1. client publishes 100 messages across 50 ledgers
     * 2. broker delivers 100 messages to consumer
     * 3. consumer ack every alternative message and doesn't ack 50 messages
     * 4. broker sorts replay messages based on ledger and redelivers messages ledger by ledger
     * </pre>
     * @throws Exception
     */
    @Test(dataProvider = "ackReceiptEnabled")
    public void testOrderedRedelivery(boolean ackReceiptEnabled) throws Exception {
        String topic = "persistent://my-property/my-ns/redelivery-" + System.currentTimeMillis();

        conf.setManagedLedgerMaxEntriesPerLedger(2);
        conf.setManagedLedgerMinLedgerRolloverTimeMinutes(0);

        @Cleanup
        Producer<byte[]> producer = pulsarClient.newProducer()
                .topic(topic)
                .producerName("my-producer-name")
                .create();
        ConsumerBuilder<byte[]> consumerBuilder = pulsarClient.newConsumer().topic(topic).subscriptionName("s1")
                .subscriptionType(SubscriptionType.Shared)
                .isAckReceiptEnabled(ackReceiptEnabled);
        ConsumerImpl<byte[]> consumer1 = (ConsumerImpl<byte[]>) consumerBuilder.subscribe();

        final int totalMsgs = 100;

        for (int i = 0; i < totalMsgs; i++) {
            String message = "my-message-" + i;
            producer.send(message.getBytes());
        }

        int consumedCount = 0;
        Set<MessageId> messageIds = Sets.newHashSet();
        for (int i = 0; i < totalMsgs; i++) {
            Message<byte[]> message = consumer1.receive(5, TimeUnit.SECONDS);
            if (message != null && (consumedCount % 2) == 0) {
                consumer1.acknowledge(message);
            } else {
                messageIds.add(message.getMessageId());
            }
            consumedCount += 1;
        }
        assertEquals(totalMsgs, consumedCount);

        // redeliver all unack messages
        consumer1.redeliverUnacknowledgedMessages(messageIds);

        MessageIdImpl lastMsgId = null;
        for (int i = 0; i < totalMsgs / 2; i++) {
            Message<byte[]> message = consumer1.receive(5, TimeUnit.SECONDS);
            MessageIdImpl msgId = (MessageIdImpl) message.getMessageId();
            if (lastMsgId != null) {
                assertTrue(lastMsgId.getLedgerId() <= msgId.getLedgerId(), "lastMsgId: " + lastMsgId + " -- msgId: " + msgId);
            }
            lastMsgId = msgId;
        }

        // close consumer so, this consumer's unack messages will be redelivered to new consumer
        consumer1.close();

        @Cleanup
        Consumer<byte[]> consumer2 = consumerBuilder.subscribe();
        lastMsgId = null;
        for (int i = 0; i < totalMsgs / 2; i++) {
            Message<byte[]> message = consumer2.receive(5, TimeUnit.SECONDS);
            MessageIdImpl msgId = (MessageIdImpl) message.getMessageId();
            if (lastMsgId != null) {
                assertTrue(lastMsgId.getLedgerId() <= msgId.getLedgerId());
            }
            lastMsgId = msgId;
        }
    }

    @Test(dataProvider = "ackReceiptEnabled")
    public void testUnAckMessageRedeliveryWithReceiveAsync(boolean ackReceiptEnabled) throws PulsarClientException, ExecutionException, InterruptedException {
        String topic = "persistent://my-property/my-ns/async-unack-redelivery";
        Consumer<String> consumer = pulsarClient.newConsumer(Schema.STRING)
                .topic(topic)
                .subscriptionName("s1")
                .isAckReceiptEnabled(ackReceiptEnabled)
                .enableBatchIndexAcknowledgment(ackReceiptEnabled)
                .ackTimeout(3, TimeUnit.SECONDS)
                .subscribe();

        Producer<String> producer = pulsarClient.newProducer(Schema.STRING)
                .topic(topic)
                .enableBatching(true)
                .batchingMaxMessages(5)
                .batchingMaxPublishDelay(1, TimeUnit.SECONDS)
                .create();

        final int messages = 10;
        List<CompletableFuture<Message<String>>> futures = new ArrayList<>(10);
        for (int i = 0; i < messages; i++) {
            futures.add(consumer.receiveAsync());
        }

        for (int i = 0; i < messages; i++) {
            producer.sendAsync("my-message-" + i);
        }

        int messageReceived = 0;
        for (CompletableFuture<Message<String>> future : futures) {
            Message<String> message = future.get();
            assertNotNull(message);
            messageReceived++;
            // Don't ack message, wait for ack timeout.
        }

        assertEquals(10, messageReceived);
        for (int i = 0; i < messages; i++) {
            Message<String> message = consumer.receive();
            assertNotNull(message);
            messageReceived++;
            consumer.acknowledge(message);
        }

        assertEquals(20, messageReceived);

        producer.close();
        consumer.close();
    }

    /**
     * Validates broker should dispatch messages to consumer which still has the permit to consume more messages.
     *
     * @throws Exception
     */
    @Test
    public void testConsumerWithPermitReceiveBatchMessages() throws Exception {

        log.info("-- Starting {} test --", methodName);

        final int queueSize = 10;
        int batchSize = 100;
        String subName = "my-subscriber-name";
        String topicName = "permitReceiveBatchMessages"+(UUID.randomUUID().toString());
        ConsumerImpl<byte[]> consumer1 = (ConsumerImpl<byte[]>) pulsarClient.newConsumer().topic(topicName)
                .receiverQueueSize(queueSize).subscriptionType(SubscriptionType.Shared).subscriptionName(subName)
                .subscribe();

        ProducerBuilder<byte[]> producerBuilder = pulsarClient.newProducer().topic(topicName);

        producerBuilder.enableBatching(true);
        producerBuilder.batchingMaxPublishDelay(2000, TimeUnit.MILLISECONDS);
        producerBuilder.batchingMaxMessages(100);

        Producer<byte[]> producer = producerBuilder.create();
        for (int i = 0; i < batchSize; i++) {
            String message = "my-message-" + i;
            producer.sendAsync(message.getBytes());
        }
        producer.flush();

        for (int i = 0; i < queueSize; i++) {
            String message = "my-message-" + i;
            producer.sendAsync(message.getBytes());
        }
        producer.flush();

        retryStrategically((test) -> {
            return consumer1.getTotalIncomingMessages() == batchSize;
        }, 5, 2000);

        assertEquals(consumer1.getTotalIncomingMessages(), batchSize);

        ConsumerImpl<byte[]> consumer2 = (ConsumerImpl<byte[]>) pulsarClient.newConsumer().topic(topicName)
                .receiverQueueSize(queueSize).subscriptionType(SubscriptionType.Shared).subscriptionName(subName)
                .subscribe();

        retryStrategically((test) -> {
            return consumer2.getTotalIncomingMessages() == queueSize;
        }, 5, 2000);
        assertEquals(consumer2.getTotalIncomingMessages(), queueSize);
        log.info("-- Exiting {} test --", methodName);
    }

    @Test(timeOut = 30000)
    public void testMessageRedeliveryAfterUnloadedWithEarliestPosition() throws Exception {

        final String subName = "my-subscriber-name";
        final String topicName = "testMessageRedeliveryAfterUnloadedWithEarliestPosition" + UUID.randomUUID();
        final int messages = 100;

        Producer<String> producer = pulsarClient.newProducer(Schema.STRING)
                .topic(topicName)
                .enableBatching(false)
                .create();

        List<CompletableFuture<MessageId>> sendResults = new ArrayList<>(messages);
        for (int i = 0; i < messages; i++) {
            sendResults.add(producer.sendAsync("Hello - " + i));
        }
        producer.flush();

        FutureUtil.waitForAll(sendResults).get();

        Consumer<String> consumer = pulsarClient.newConsumer(Schema.STRING)
                .topic(topicName)
                .subscriptionType(SubscriptionType.Shared)
                .subscriptionName(subName)
                .subscriptionInitialPosition(SubscriptionInitialPosition.Earliest)
                .subscribe();

        List<Message<String>> received = new ArrayList<>(messages);
        for (int i = 0; i < messages; i++) {
            received.add(consumer.receive());
        }

        assertEquals(received.size(), messages);
        assertNull(consumer.receive(1, TimeUnit.SECONDS));

        admin.topics().unload(topicName);

        // The consumer does not ack any messages, so after unloading the topic,
        // the consumer should get the unacked messages again

        received.clear();
        for (int i = 0; i < messages; i++) {
            received.add(consumer.receive());
        }

        assertEquals(received.size(), messages);
        assertNull(consumer.receive(1, TimeUnit.SECONDS));

        consumer.close();
        producer.close();
    }
}


text:
package extracells.item.storage;

import java.util.Locale;

import net.minecraft.item.EnumRarity;

public enum CellDefinition {
	PHYSICAL(EnumRarity.EPIC) {
		@Override
		protected void create(StorageRegistry.Builder components, StorageRegistry.Builder cells) {
			components.add(this, 256, 1024, 4096, 16384);
			cells.add(this, 256, 1024, 4096, 16384, 65536);
		}
	},
	FLUID(EnumRarity.RARE),
	GAS(EnumRarity.UNCOMMON);

	public static StorageRegistry components;
	public int componentMetaStart;
	public StorageRegistry cells;

	EnumRarity rarity;

	CellDefinition(EnumRarity rarity) {
		this.rarity = rarity;
	}

	public static void create() {
		StorageRegistry.Builder componentBuilder = new StorageRegistry.Builder("components");
		for (CellDefinition definition : values()) {
			definition.componentMetaStart = componentBuilder.size();
			StorageRegistry.Builder cellBuilder = new StorageRegistry.Builder("cells");
			definition.create(componentBuilder, cellBuilder);
			definition.cells = cellBuilder.build();
		}
		components = componentBuilder.build();
	}

	protected void create(StorageRegistry.Builder components, StorageRegistry.Builder cells) {
		components.add(this, 1, 4, 16, 64, 256, 1024, 4096);
		cells.add(this, 1, 4, 16, 64, 256, 1024, 4096);
	}

	public static CellDefinition get(int index) {
		if (values().length <= index) {
			return values()[0];
		}
		return values()[index];
	}

	public EnumRarity getRarity() {
		return rarity;
	}

	@Override
	public String toString() {
		return name().toLowerCase(Locale.ENGLISH);
	}
}


text:
package org.red5.io.sctp.packet.chunks;

public enum ChunkType {

	DATA(0), // Payload Data
	INIT(1), // Initiation
	INIT_ACK(2), // Initiation Acknowledgement
	SACK(3), // Selective Acknowledgement
	HEARTBEAT(4), // Heartbeat Request
	HEARTBEAT_ACK(5), // Heartbeat Acknowledgement
	ABORT(6), // Abort
	SHUTDOWN(7), // Shutdown
	SHUTDOWN_ACK(8), // Shutdown Acknowledgement
	ERROR(9), // Operation Error
	COOKIE_ECHO(10), // State Cookie
	COOKIE_ACK(11), // Cookie Acknowledgement
	ECNE(12), // Reserved for Explicit Congestion Notification Echo
	CWR(13), // Reserved for Congestion Window Reduced
	SHUTDOWN_COMPLETE(14);

	private int value;

	private ChunkType(final int value) {
		this.value = value;
	}

	public int getValue() {
		return value;
	}
}


text:
namespace TicketingSystem.Web.ViewModels.Comments
{
    using System;
    using System.ComponentModel.DataAnnotations;
    using System.Linq;
    using TicketingSystem.Data.Models;
    using TicketingSystem.Web.Infrastructure.Mapping;

    public class PostCommentViewModel : IMapFrom<Comment>
    {
        public PostCommentViewModel()
        {
        }

        public PostCommentViewModel(int ticketId)
        {
            this.TicketId = ticketId;
        }

        public int TicketId { get; set; }

        [Required]
        [MinLength(100), MaxLength(1000)]
        [UIHint("MultiLineText")]
        public string Content { get; set; }
    }
}


text:
package org.apache.sling.commons.log.internal;

import java.util.Dictionary;
import java.util.Hashtable;

import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.osgi.service.log.LogReaderService;
import org.osgi.service.log.LogService;

/**
 * The Activator class is the BundleActivator for
 * the log service bundle. This activator sets up logging in NLog4J and
 * registers the LogService and LogReaderService.
 * When the bundle is stopped, the NLog4J subsystem is simply shutdown.
 */
public class Activator implements BundleActivator {

    private LogManager logManager;

    private LogSupport logSupport;

    public void start(BundleContext context) throws Exception {
        logManager = new LogManager(context);

        logSupport = new LogSupport();
        context.addBundleListener(logSupport);
        context.addFrameworkListener(logSupport);
        context.addServiceListener(logSupport);

        LogServiceFactory lsf = new LogServiceFactory(logSupport);
        Dictionary<String, String> props = new Hashtable<String, String>();
        props.put(Constants.SERVICE_PID, lsf.getClass().getName());
        props.put(Constants.SERVICE_DESCRIPTION,
            "Apache Sling LogService implementation");
        props.put(Constants.SERVICE_VENDOR, "The Apache Software Foundation");
        context.registerService(LogService.class.getName(), lsf, props);

        LogReaderServiceFactory lrsf = new LogReaderServiceFactory(logSupport);
        props = new Hashtable<String, String>();
        props.put(Constants.SERVICE_PID, lrsf.getClass().getName());
        props.put(Constants.SERVICE_DESCRIPTION,
            "Apache Sling LogReaderService implementation");
        props.put(Constants.SERVICE_VENDOR, "The Apache Software Foundation");
        context.registerService(LogReaderService.class.getName(), lrsf, props);
    }

    public void stop(BundleContext context) throws Exception {
        if (logSupport != null) {
            logSupport.shutdown();
            logSupport = null;
        }

        if (logManager != null) {
            logManager.shutdown();
            logManager = null;
        }
    }
}


text:
libten [![Build Status](https://travis-ci.org/toffaletti/libten.png)](https://travis-ci.org/toffaletti/libten)
======

C++11 library for network services on modern x86-64 Linux.

Features
--------

  * lightweight cooperative tasks (using boost.context)
  * typed channels for communicating between threads and tasks
  * http client and server
  * fast uri parser
  * JSON parser (wrapper around jansson)
  * logging (glog)
  * rpc (using msgpack)
  * epoll event loop

Why
---
Or rather why not libevent, libev, or boost.asio? libten is designed
around the concept of task-based concurrency, while the other
libraries are designed for event driven concurrency with callbacks.
They are not entirely at odds, libten's event loop could be built on
any of these libraries. However, another major difference is that
other libraries strive to provide a cross platform solution to event
driven network programming. They are great if you need portable
code that works across many versions and platforms. libten's approach
is to focus only on modern Linux, modern compilers, and performance.
This makes libten's code base smaller and easier to maintain, with
very minimal abstraction. libten uses epoll, timerfd, and signalfd.
In addition to networking and concurrency it provides logging, JSON,
URI, http client and server, rpc, zookeeper and more.

API Stability
-------------
libten is not a stable API yet. Don't let this scare you away though.
Most changes at this point are minor and incremental.

Dependencies
------------

  * cmake >= 2.8
  * g++ >= 4.7.0
  * libssl-dev >= 0.9.8
  * libboost-dev >= 1.51
  * libboost-date-time-dev >= 1.51
  * libboost-program-options-dev >= 1.51
  * libboost-context-dev >= 1.51
  * ragel >= 6.5
  * libjansson-dev >= 2.3
  * libc-ares-dev

Bundled 3rd-party components
____________________________

  * http_parser v2 from https://github.com/joyent/http-parser
  * glog-0.3.2 from http://code.google.com/p/google-glog/
  * stlencoders 1.1.1 from http://code.google.com/p/stlencoders/
  * msgpack-0.5.7 from http://msgpack.org/
  * miniz v1.14 from http://code.google.com/p/miniz/


text:
"""Checks for if statements containing too many boolean expressions"""

# pylint: disable=invalid-name

x = y = z = 5
if x > -5 and x < 5 and y > -5 and y < 5 and z > -5 and z < 5:  # [too-many-boolean-expressions]
    pass
elif True and False and 1 and 2 and 3:
    pass
elif True and False and 1 and 2 and 3 and 4 and 5: # [too-many-boolean-expressions]
    pass
elif True and (True and True) and (x == 5 or True or True): # [too-many-boolean-expressions]
    pass
elif True and (True or (x > -5 and x < 5 and (z > -5 or z < 5))): # [too-many-boolean-expressions]
    pass
elif True == True == True == True == True == True:
    pass

if True and False and 1 and 2 and 3:
    pass


text:
from setuptools import setup

setup(name='c3_utils',
      version='0.1',
      description='utilities to run C3 cloud API',
      url='http://github.com/bioliyezhang/c3_utils',
      author='liye zhang',
      author_email='bioliyezhang@gmail.com',
      license='MIT',
      packages=['c3_utils'],
      zip_safe=False)


text:
'use strict';

/*

    To add a listener, please add a listener object to
    the {listeners} array below.

    // {listener} type
    {

        // REQUIRED
        // A name that uniquely identifies this listener
        // This name is used to load
        name: string,

        // REQUIRED
        // A factory to create the Listener
        // The dependencies are specified below
        factory: (...dependencies): Listener,

        // REQUIRED
        // These specify what the listener listens for
        // and where to send each type of event
        // See: https://github.com/slackhq/node-slack-client/blob/master/lib/clients/events/rtm.js
        // And see: https://api.slack.com/events
        // The EventSelector type should implement:
        //      name: string,
        //      invoker: (listener: Listener, eventData: any): void
        // Where:
        //      {name}: is the event name (see links above)
        //      {invoker}: is a function to invoke when the event is fired.
        //          The invoker will be given {listener} as the Listener
        //          provided by the factory.
        //      {eventData}: is the event data from the specified event
        events: EventSelector[]

        // Optional
        // Default: [] (no dependencies)
        // The name(s) of the dependencies to inject into
        // the listener
        dependencies: string[],

        // Optional
        author: string
    }

*/

const listeners = [

    require('../listeners/karmaTracker'),
    require('../listeners/karmaChecker'),
    require('../listeners/statTracker'),
    require('../listeners/statChecker'),
    require('../listeners/autoResponder')

];

depend.factory('listeners', [], () => listeners);


text:
<?php

use Ouzo\Config;
use Ouzo\Db\Dialect\MySqlDialect;
use Ouzo\Db\Dialect\PostgresDialect;
use Ouzo\Db\StatementExecutor;
use Ouzo\DbConnectionException;
use Ouzo\DbException;
use Ouzo\Tests\CatchException;
use Ouzo\Tests\Mock\Mock;
use Ouzo\Tests\Mock\SimpleMock;
use PHPUnit\Framework\TestCase;

class StatementExecutorTest extends TestCase
{
    private PDOStatement|SimpleMock $pdoMock;
    private PDO|SimpleMock $dbMock;

    protected function setUp(): void
    {
        parent::setUp();

        $this->pdoMock = Mock::mock(PDOStatement::class);
        $this->dbMock = Mock::mock(PDO::class);
        Mock::when($this->pdoMock)->execute()->thenReturn(false);
        Mock::when($this->dbMock)->prepare('SELECT 1', [])->thenReturn($this->pdoMock);
    }

    /**
     * @test
     */
    public function shouldThrowExceptionOnExecutionError()
    {
        //given
        Mock::when($this->pdoMock)->errorInfo()->thenReturn(['HY000', '20102', 'Execution error']);
        $executor = StatementExecutor::prepare($this->dbMock, 'SELECT 1', [], []);

        //when
        CatchException::when($executor)->execute();

        //then
        CatchException::assertThat()->isInstanceOf(DbException::class);
    }

    /**
     * @test
     */
    public function shouldThrowConnectionExceptionForMySQL()
    {
        //given
        Config::overrideProperty('sql_dialect')->with(MySqlDialect::class);
        Mock::when($this->pdoMock)->errorInfo()->thenReturn(['HY000', 2003, 'Execution error']);
        $executor = StatementExecutor::prepare($this->dbMock, 'SELECT 1', [], []);

        //when
        CatchException::when($executor)->execute();

        //then
        CatchException::assertThat()->isInstanceOf(DbConnectionException::class);
        Config::revertProperty('sql_dialect');
    }

    /**
     * @test
     */
    public function shouldThrowConnectionExceptionForPostgres()
    {
        //given
        Config::overrideProperty('sql_dialect')->with(PostgresDialect::class);
        Mock::when($this->pdoMock)->errorInfo()->thenReturn(['57P01', 7, 'Execution error']);
        $executor = StatementExecutor::prepare($this->dbMock, 'SELECT 1', [], []);

        //when
        CatchException::when($executor)->execute();

        //then
        CatchException::assertThat()->isInstanceOf(DbConnectionException::class);
        Config::revertProperty('sql_dialect');
    }
}


text:
import * as React from 'react';
import { IconBaseProps } from 'react-icon-base';
export default class MdVideoLabel extends React.Component<IconBaseProps> { }


text:
//=================================================================================================

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

//*************************************************************************************************
// Includes
//*************************************************************************************************

#include <iostream>
#include <blaze/math/DynamicMatrix.h>
#include <blaze/util/Timing.h>
#include <blazemark/blaze/Complex5.h>
#include <blazemark/blaze/init/DynamicMatrix.h>
#include <blazemark/system/Config.h>

namespace blazemark {

namespace blaze {

//=================================================================================================
//
//  KERNEL FUNCTIONS
//
//=================================================================================================

//*************************************************************************************************
/*!\brief Blaze kernel for the complex expression D = ( A * B ) + C.
//
// \param N The number of rows and columns of the matrices.
// \param steps The number of iteration steps to perform.
// \return Minimum runtime of the kernel function.
//
// This kernel function implements the complex expression D = ( A * B ) + C by means of the
// Blaze functionality.
*/
double complex5( size_t N, size_t steps )
{
   using ::blazemark::element_t;
   using ::blaze::columnMajor;

   ::blaze::setSeed( seed );

   ::blaze::DynamicMatrix<element_t,columnMajor> A( N, N ), B( N, N ), C( N, N ), D( N, N );
   ::blaze::timing::WcTimer timer;

   init( A );
   init( B );
   init( C );

   D = ( A * B ) + C;

   for( size_t rep=0UL; rep<reps; ++rep )
   {
      timer.start();
      for( size_t step=0UL; step<steps; ++step ) {
         D = ( A * B ) + C;
      }
      timer.end();

      if( D.rows() != N )
         std::cerr << " Line " << __LINE__ << ": ERROR detected!!!\n";

      if( timer.last() > maxtime )
         break;
   }

   const double minTime( timer.min()     );
   const double avgTime( timer.average() );

   if( minTime * ( 1.0 + deviation*0.01 ) < avgTime )
      std::cerr << " Blaze kernel 'complex5': Time deviation too large!!!\n";

   return minTime;
}
//*************************************************************************************************

} // namespace blaze

} // namespace blazemark


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>nedtries Readme</title>

nedtries v1.02 Final (9th July 2012)

by Niall Douglas

Web site: http://www.nedprod.com/programs/portable/nedtries/

Enclosed is nedtries, an in-place bitwise binary Fredkin trie algorithm which allows for near
constant time insertions, deletions, finds,
 closest fit finds
and iteration. On modern hardware it is approximately 50-100% faster than
red-black binary trees, it handily beats even the venerable O(1) hash table for
less than 3000 objects and it is barely slower than the hash table for 10000
objects. Past 10000 objects you probably ought to use a hash table though, and
if you need nearest fit rather than close fit
then red-black trees are still optimal.

It is licensed under the
Boost Software License
which basically means you can do anything you like with it. Commercial support is
available from ned
Productions Limited.

Its advantages over other algorithms are sizeable:

It has all the advantages of red-black trees such as close-fit finds
	(i.e. find an item which is similar but not exact to the search term) without
	anything like the impact on memory bandwidth as red-black trees because it
	doesn't have to rebalance itself when adding new items (i.e. it
	scales far better with memory pressure than red-black trees).

It doesn't require dynamic memory like hash tables, so it can be used in
	a bounded environment such as a bootstrapper or a tiny embedded systems
	kernel. It is also a lot faster than hash tables for less than a few
	thousand items.

Unlike either red-black trees or most hash tables, nedtries can store as
	many items with identical keys as you like.

Its performance is nearly perfectly stable over time and number of
	contents N with a worst case complexity of O(M) following a mostly linear
	degradation with increasing M average where 1 <= M <= 8*sizeof(void *). M is a measure
	of the entropy between differing keys, so where keys are very similar at the
	bit level M is
	higher than where keys are very dissimilar. This leads to an unusual
	complexity where it can be like O(log N) for some distributions of key, and
	like O(1) for other distributions of key. The scaling graphs below are for
	completely random keys.

Its complexities for find and insert are identical, whereas for deletion
	it is slightly more constant. Unlike almost any other algorithm, bitwise binary tries
	have nearly identical real world speeds for ALL its operations rather than
	being fast at one thing but slow at the others. In other words, if your code
	equally inserts, deletes and finds with no preference for which then 	this algorithm will
	typically beat all others
	in the general purpose situation.

Its two primary disadvantages are that (i) it can only key upon a size_t (i.e. the size
of a void *), so it cannot make use of an arbitrarily large key like a hash
table can (though of course one could hash the large key into a size_t sized
key) and (ii) it is lousy at guaranteed nearest fit finds. It also runs fastest when the key is as unique
from other keys as possible, so if you wish
to replace a red-black tree which has a complex left-right comparison function
which cannot be converted into a stable size_t value then you will need to stick
with red-black trees. In other words, it is ideal when you are keying on pointer
sized keys where each item has a definitive non-changing key.

Have a look at the scaling graphs below to decide if your software could
benefit. Note for non-random key distributions you may get significantly better
or worse performance than shown. If you're interested, read on for how to add them to your software.

A. Breaking changes since previous versions:

In v1.02 a breaking change in what NEDTRIE_NFIND means and does was
introduced, and the version was bumped to v1.02 to warn users of the
change. The problem in v1.01 and earlier was that I had incorrectly
documented what NEDTRIE_NFIND does: I said that it found the nearest item to the
search term when this was patently untrue (thanks to smilingthax for reporting
this). In fact, NEDTRIE_NFIND used to return a matching item, if there was one,
but if there was no matching item, it returned any larger item rather
than the next largest item. I do apologise to the users of nedtries for
this documentation error, and for the lost productivity it surely must have
caused some of you.

The good news is that NEDTRIE_NFIND now guarantees to return the next largest
item, and it therefore now matches BSD's red-black Nfind. The bad news is that
bitwise tries are really not ideal for guaranteed nearest matching, and
performance is terrible as you can see via the purple line in the graphs above.
If you can put up with non-guaranteed nearest matching, NEDTRIE_CFIND offers
much better performance. NEDTRIE_CFIND takes a rounds parameter which
indicates how hard the routine should try to return a close item: rounds=0 means
to return the first item encountered which is equal or larger to search key,
rounds=1 means try one level down, rounds=2 means try two levels down and so on.
rounds=INT_MAX means try hardest, and guarantees that any item with a matching
key will be found and that if not matching, any item returned will have a very
close key (those not necessarily the closest).

For a summary of the differences between Nfind and Cfind,
see this useful table. Note that if you just
want any item with a key larger or equal to the search key,
NEDTRIE_CFIND(rounds=0|1|2) is extremely swift and has O(1) complexity as shown
in the graphs above.

B. Implementation:

The source makes use of C macros on C and C++ templates on C++ - therefore,
unlike typical C-macro-based algorithms it is easy to debug and in fact, the improved
metadata specified by the templates lets a modern C++ compiler produce 5-15%
faster code through PGO guided selective inlining. The code is 100% standard C and C++, so it should run on any
platform or architecture though you may need to implement your own nedtriebitscanr()
function if you're not using GCC nor MSVC and want to keep performance high. If
you are building debug, NEDTRIEDEBUG is by default turned on: this causes a
complete state validation check to be performed after each and every change to
the trie which tends to be very good at catching bugs early, but can make debug
builds a little slow.

So what is "an in-place bitwise binary Fredkin trie algorithm" then?
Well you ought to start by reading and fully digesting
the Wikipedia page
on Fredkin tries as what comes won't make much sense otherwise. The
Wikipedia page describes a non-inplace trie which uses dynamic memory to store
each consecutive non-differing section of a string, and indeed this is how tries
are normally described in algorithm theory and classes. nedtries obviously
enough selects on individual bits rather than substrings, and it uses an inplace
instead of dynamically allocated implementation.

Here is how nedtries performs an indexation: firstly, the most significant
set bit X is found using nedtriebitscanr() which is no more than one to three
CPU cycles on modern processors. This is used to index an array of
bins. Each bin X contains a binary tree of items whose keys are (1<<X) <= key <
(1<<(X+1)), so what one does is to follow the tree downwards selecting left or
right based on whether the next bit downwards is 0 or 1. If an item has
children, its key is only guaranteed to be constrained to that of its bin,
whereas if an item does not have children then its key is guaranteed to match as
closely as possible its position in the tree.

If you insert an item, nedtries indexes as far as it can down the existing
tree where the new item ought to be and inserts it there. If you remove an item,
if that item has no children it is simply removed. If it has a child then a
nobble function is called to select the bias for how to select the childless
item to be nobbled and used as the replacement i.e. one either traverses down
preferentially 1 or preferentially 0 until you find a childless item, then you
delink it from there and link it in to replace the item being removed.

If you think about this hard enough, you realise that you will get a "nearly
sorted" binary tree i.e. one whose node keys are very nearly in order. In fact,
the more randomised the key, the more in order the tree becomes. The tree is
usually sufficiently ordered that one can assume it to be so for most
operations, but if you need to guarantee order then you can bubble sort per MSB
bin as bubble sort performs very well on nearly sorted data (as does
smooth sort if you have a very large set of data) .

The enclosed benchmark.cpp will run a series of scalability tests comparing the bitwise
binary trie implementation from nedtries with others outputting its results in
CSV format:

If compiled as C not C++, the C macro version of nedtries is compared to the red-black binary tree
implementation from FreeBSD and the O(1) hash table implementation from
	http://uthash.sourceforge.net/.

If compiled as C++, the C++ template version of nedtries is compared to
	all of the C tests above as well as the STL associative container classes
	std::map<> and std::unordered_map<>. NOTE THAT YOU NEED A TR1 SUPPORTING
	COMPILER FOR std::unordered_map<> SUPPORT!

You will also find enclosed a set of precomputed
Microsoft Excel spreadsheets which were generated on a 2.67Ghz Intel Core 2 Quad
Windows 7 x64 machine. They should be representative of performance on modern
hardware - though note that the Intel Atom has a 17 cycle nedtriebitscanr()
which is the only modern CPU to be so slow. See
http://gmplib.org/~tege/x86-timing.pdf for x86 and x64 instruction timings.

C. C Macro Usage:

Usage via C macros follows the FreeBSD rbtree.h
format. See the enclosed nedtries.chm  for detailed
API documentation. Here is some sample code which can be compiled cleanly using <tt>gcc -Wall -pedantic
-std=c99 test.c</tt> (or as C++ via <tt>g++ -Wall -pedantic test.c</tt>):

#include <stdio.h>
#include <string.h>
#include "nedtrie.h"

typedef struct foo_s foo_t;
struct foo_s {
  NEDTRIE_ENTRY(foo_s) link;
  size_t key;
};
typedef struct foo_tree_s foo_tree_t;
NEDTRIE_HEAD(foo_tree_s, foo_s);
static foo_tree_t footree;

size_t fookeyfunct(const foo_t *r)
{
  return r->key;
}

NEDTRIE_GENERATE(static, foo_tree_s, foo_s, link, fookeyfunct, NEDTRIE_NOBBLEZEROS(foo_tree_s))

int main(void)
{
  foo_t a, b, c, *r;
  NEDTRIE_INIT(&footree);
  a.key=2;
  NEDTRIE_INSERT(foo_tree_s, &footree, &a);
  b.key=6;
  NEDTRIE_INSERT(foo_tree_s, &footree, &b);
  r=NEDTRIE_FIND(foo_tree_s, &footree, &b);
  assert(r==&b);
  c.key=5;
  r=NEDTRIE_NFIND(foo_tree_s, &footree, &c);
  assert(r==&b); /* NFIND finds next largest. Invert the key function (i.e. 1-key) to find next smallest. */
  NEDTRIE_REMOVE(foo_tree_s, &footree, &a);
  NEDTRIE_FOREACH(r, foo_tree_s, &footree)
  {
    printf("%p, %u\n", (void *) r, (unsigned) r->key);
  }
  assert(!NEDTRIE_PREV(foo_tree_s, &footree, &b));
  assert(!NEDTRIE_NEXT(foo_tree_s, &footree, &b));
  return 0;
}

There isn't really much more to it - if you want to throw away the trie,
simply NEDTRIE_INIT() its head. As no dynamic memory is involved, nothing is
lost.

Choosing The Nobble Function

I should mention what the nobble function is for: you have three default
choices, NEDTRIE_NOBBLEZEROS, NEDTRIE_NOBBLEONES and NEDTRIE_NOBBLEEQUALLY
though you can of course also define your own. The nobble function contributes
to tree balance by working against bit bias in your keys, so if your
keys contain an excess of non-leading zeros then you should
preferentially nobble zeros. Equally if your keys contain an excess of ones,
then you should preferentially nobble ones and, as you might have guessed, if
your bits after the first set bit are completely random (which is rare)
then you should nobble equally.

Sounds complicated? In fact it's very easy if you simply use trial & error.
Start with nobble zeroes which tends to be right in most situations, and then
use benchmarking your code to determine the correct setting.

Nfind versus Cfind

Where the BSD red-black tree implementation has RB_NFIND() for finding items
which are nearest to the search term, nedtries provides NEDTRIE_CFIND() and
NEDTRIE_NFIND(). What's the difference? Here's a quick table:

		Nfind
		Cfind(rounds=INT_MAX)
		Cfind(rounds=0|1)

Returns an exact match if there is an exact match in the trie

If there is not an exact match, guarantees that the item
			returned is the next largest

Complexity: Somewhat worse than O(log N), as must perform a O(log N)
			search of the subtree returned by Cfind(rounds=INT_MAX).

Returns an exact match if there is an exact match in the trie

If there is not an exact match, item returned will be very close
			to the next largest

Complexity: Identical to Find i.e. O(1/DKL(key||average key)).
			However because it does much more work, it is approximately four
			times slower than a straight find.

Returns an item with a key no larger than the next power of two
			multiple higher than the search key

Complexity: approximately O(2^rounds) for small numbers of
			rounds, so approaches O(1).

D. C++ Usage:

C++ usage is even easier than the C macro usage thanks to nedtries::trie_map<>
and nedtries::trie_multimap<>
which is API compatible with the std::map<>, std::multimap<> and std::unordered_map<>
STL associative containers. trie_map<> and trie_multimap<>
makes full use of rvalue construction if either you are running on C++0x
according to the value of __cplusplus, or have
defined HAVE_CPP0X. In the general case, simply drop trie_map<> or
trie_multimap<> in where
your STL associative container used to be and enjoy the speed benefits!

Note that insertion and deletion speed in any STL container
is heavily bound by the speed of your memory allocator. You may wish to consider
employing

nedmalloc which can deliver some unholy speed benefits if you run it as
root, otherwise it will need some small source changes to employ its advanced v2
malloc API.

In case you are not familiar with STL associative containers, they are very
simple e.g.:

nedtries::trie_map<size_t, Foo> foomap;
foomap[5]=Foo();
foomap.erase(foomap.find(5));

You can of course iterate through them and do all the normal things you can
do with any STL container.

The trie_map<> and trie_multimap<> Implementation

trie_map<> and trie_multimap<> are actually a STL container wrappers rather than a proper STL
container in its own right i.e. it subclasses an existing STL container passing
through most of its API, but selectively overrides certain members. Its default
parameters point at std::list<> which is its most likely usage model for most
people.

The advantages are mainly that it is quick to implement and can be
theoretically applied to any arbitrary STL container, thus taking advantage of
that STL container's optimisations and customisations. The big disadvantage is
that it is hacky, dirty and prone to getting bugs into it, and if you look at
the source you'll see what I mean. There is after all a number of places where I
am doing a number of very illegal things in C++ which just happen to usually
work.

The chances are that this implementation will be good enough for most people.
If however you might like to sponsor the development of a full bitwise trie STL
associative container for submission to
the Boost C++ peer reviewed
libraries (and thereafter into the standard C++ language itself), I would be
very pleased to oblige.
Please contact ned Productions Consulting Ltd. for further details.

E. ChangeLog:

v1.02 Final (9th July 2012):

Due to the breaking
	change in what NEDTRIE_NFIND means and does, bumped version number.

[master 910ef60] Fixed the C++
	implementation causing memory corruption when built as 64 bit.

[master 0ea1327] Added some compile time
	checks to ensure C++
	implementation will never again cause memory corruption when built as 64 bit.

v1.01 RC2 (unreleased):

[master bd6f3e5] Fixed misc documentation errors.

[master 79efb3a] Fixed really obvious
	documentation bug in the example usage. Thanks to Fabian Holler for
	reporting this.

[master 99e67e3] Fixed that the example
	usage in the documentation spews warnings on GCC. Now compiles totally
	cleanly. Thanks to Fabian Holler for
	reporting this.

[master 537c27b] Added NEDTRIE_FOREACH_SAFE
	and NEDTRIE_FOREACH_REVERSE_SAFE. Thanks to Stephen Hemminger for contributing this.

[master 4b12a3c] Fixed the fact that I
	had forgotten to implement iterators for trie_map<>. Also added
	trie_multimap<>. Thanks to Ned for pointing out the problem.

[master 8b53224] Renamed Nfind to Cfind.

v1.01 RC1 (19th June 2011):

[master 30a440a] Fixed misc documentation errors.

[master 2103969] Fixed misoperation when trie key is
zero. Thanks to Andrea for reporting this.

[master 083d94b] Added support for MSVC's as old as 7.1.

[master f836319] Added Microsoft CLR target support.

[master 85abf67] I, being a muppet of the highest
order, was actually benchmarking the speed of the timing routines rather than much
else. Performance is now approx. 10x higher in the graphs ... I am a fool!

[master 6aa344e] Added check for key uniqueness
in benchmark test (hash tables suffer is key isn't unique). Added cube root averaging
to results output.

[master feb4f56] Replaced the use of rand()
with the Mersenne Twister (
http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/SFMT/index.html).

v1.00 beta 1 (18th June 2010):

[master e4d1245] First release.


text:
export R_LIBS_USER=~/R/Library
export workdir=$1
export recombdir=$1/recomb
for f in ${workdir}/*.fasta
do
   export removeDuplicateSequencesFromAlignedFasta_inputFilename=$f
   export removeDuplicateSequencesFromAlignedFasta_outputFastaFilename=`basename $f .fasta`.dedup.fasta
   export removeDuplicateSequencesFromAlignedFasta_outputDir=`dirname $f`/recomb
   export removeDuplicateSequencesFromAlignedFasta_outputTableFilename=`basename $f .fasta`.dedup.tab
   echo "source('removeDuplicateSequencesFromAlignedFasta.R')" | R --vanilla --slave
done
pushd .
cd $recombdir
ls -c1 *.dedup.fasta | nl -w3 -nrz | sed 's/^\([0-9][0-9][0-9]\)\s*\(.*\)/ln -s \2 \1\.fasta/' | sh
rm `grep -c ">" [0-9][0-9][0-9].fasta | egrep ':[1,2]$' | cut -d: -f1`
popd


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

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Java.Interop;
using Java.Lang;

namespace IParcelableSample
{
    public class TableItem
    {
        public string Name { get; set; }
        public DateTime Time { get; set; }
    }

    /// <summary>
    /// TableItemを継承したParcelableなアダプタークラス
    /// </summary>
    /// <remarks>
    /// 参考資料:Xamarin.Androidで画面遷移を行うには? - Build Insider http://www.buildinsider.net/mobile/xamarintips/0004
    /// </remarks>
    public class TableItemParcelable : Java.Lang.Object, IParcelable
    {
        public TableItem Item { get; set; } = new TableItem();

        public TableItemParcelable(string name, DateTime time)
        {
            Item.Name = name;
            Item.Time = time;
        }

        public int DescribeContents()
        {
            return 0;
        }

        // CreateFromParcelとCreateFromParcelで同じオブジェクトを扱うこと。
        public void WriteToParcel(Parcel dest, [GeneratedEnum] ParcelableWriteFlags flags)
        {
            dest.WriteString(Item.Name);
            dest.WriteString(Item.Time.ToString());
        }

        [ExportField("CREATOR")]
        public static IParcelableCreator GetCreator()
        {
            return new TableItemParcelableCreator();
        }

        class TableItemParcelableCreator : Java.Lang.Object, IParcelableCreator
        {
            // CreateFromParcelとCreateFromParcelで同じオブジェクトを扱うこと。
            public Java.Lang.Object CreateFromParcel(Parcel source)
            {
                TableItemParcelable item = new TableItemParcelable(
                    source.ReadString(),
                    DateTime.Parse(source.ReadString()));
                return item;
            }

            public Java.Lang.Object[] NewArray(int size)
            {
                return new Java.Lang.Object[size];
            }
        }
    }
}


text:
    <title>This page will be initially treated as unreachable</title>

PASS: Going back to a page that was previously treated as unreachable loads the actual page.