<commit_before>/**************************************************************************
 * This file is property of and copyright by the ALICE HLT Project        *
 * All rights reserved.                                                   *
 *                                                                        *
 * Primary Authors: Markus Fasel                                          *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/
#include "AliHLTCaloTriggerDataStruct.h"
#include "AliHLTCaloTriggerHeaderStruct.h"
#include "AliHLTCaloTriggerRawDigitDataStruct.h"
#include "AliEMCALTriggerSTURawStream.h"
#include "AliHLTEMCALDefinitions.h"
#include "AliHLTEMCALGeometry.h"
#include "AliHLTEMCALTriggerDataMakerComponent.h"

ClassImp(AliHLTEMCALTriggerDataMakerComponent)

AliHLTEMCALTriggerDataMakerComponent::AliHLTEMCALTriggerDataMakerComponent():
AliHLTCaloProcessor(),
AliHLTCaloConstantsHandler("EMCAL"),
fGeometry(NULL),
fSTUHeader(),
fNRawDigitsTRU(0),
fNRawDigitsSTU(0),
fMaxChannel(0)
{
  for(Short_t iter = 0; iter < kMaxChannels; iter++){
    fRawIndexesTRU[iter] = -1;
    fRawIndexesSTU[iter] = -1;
  }
}

AliHLTEMCALTriggerDataMakerComponent::~AliHLTEMCALTriggerDataMakerComponent() {
  if(fGeometry) delete fGeometry;
}

int AliHLTEMCALTriggerDataMakerComponent::DoInit(int argc, const char **argv){
  fGeometry = new AliHLTEMCALGeometry(GetRunNo());
  return 0;
}

int AliHLTEMCALTriggerDataMakerComponent::DoDeinit(){
  if(fGeometry) delete fGeometry;
  fGeometry = NULL;
  return 0;
}

const char* AliHLTEMCALTriggerDataMakerComponent::GetComponentID(){
  return "EmcalTriggerDataMaker";
}

void AliHLTEMCALTriggerDataMakerComponent::GetInputDataTypes( std::vector <AliHLTComponentDataType>& list){
  list.clear();
  list.push_back( AliHLTEMCALDefinitions::fgkTriggerRawDigitDataType   | kAliHLTDataOriginEMCAL );
  list.push_back( AliHLTEMCALDefinitions::fgkTriggerSTUDataType | kAliHLTDataOriginEMCAL );
}

AliHLTComponentDataType AliHLTEMCALTriggerDataMakerComponent::GetOutputDataType(){
  return kAliHLTDataTypeCaloTrigger | kAliHLTDataOriginEMCAL;
}

void AliHLTEMCALTriggerDataMakerComponent::GetOutputDataSize(unsigned long& constBase, double& inputMultiplier){
  constBase = sizeof(AliHLTCaloTriggerHeaderStruct);
  inputMultiplier = 1.5;
}

AliHLTComponent* AliHLTEMCALTriggerDataMakerComponent::Spawn(){
  return new AliHLTEMCALTriggerDataMakerComponent;
}

bool AliHLTEMCALTriggerDataMakerComponent::CheckInputDataType(const AliHLTComponentDataType &datatype) {
  //comment
  vector <AliHLTComponentDataType> validTypes;
  GetInputDataTypes(validTypes);

  for(UInt_t i=0; i < validTypes.size(); i++) {
    if ( datatype  ==  validTypes.at(i) ) {
      return true;
    }
  }

  HLTDebug("Invalid Datatype");
  return false;
}

int AliHLTEMCALTriggerDataMakerComponent::DoEvent( const AliHLTComponentEventData& evtData, const AliHLTComponentBlockData* blocks,
         AliHLTComponentTriggerData& trigData, AliHLTUInt8_t* outputPtr,
         AliHLTUInt32_t& size, std::vector<AliHLTComponentBlockData>& outputBlocks ){

  if(!IsDataEvent()) {
    size = 0;
    return 0;
  }

  UInt_t totSize            = 0;
  const AliHLTComponentBlockData* iter = NULL;

  // Get pointers to output buffer
  AliHLTCaloTriggerHeaderStruct *headerPtr = reinterpret_cast<AliHLTCaloTriggerHeaderStruct *>(outputPtr);
  AliHLTCaloTriggerDataStruct *dataIter = reinterpret_cast<AliHLTCaloTriggerDataStruct *>(outputPtr + sizeof(AliHLTCaloTriggerHeaderStruct));
  totSize += sizeof(AliHLTCaloTriggerHeaderStruct);

  Reset();
  AliHLTCaloTriggerRawDigitDataStruct *dataptr = NULL;
  for(ULong_t ndx = 0; ndx < evtData.fBlockCnt; ndx++){
    iter = blocks + ndx;

    if(!this->CheckInputDataType(iter->fDataType)){
      continue;
    }

    if(iter->fDataType == AliHLTEMCALDefinitions::fgkTriggerRawDigitDataType){
      // Handle TRU data
      Int_t ndigits = iter->fSize / sizeof(AliHLTCaloTriggerRawDigitDataStruct);
      HLTDebug("Data containing %d TRU digits", ndigits);
      dataptr = reinterpret_cast<AliHLTCaloTriggerRawDigitDataStruct *>(iter->fPtr);
      ReadTRUData(ndigits, dataptr);
    } else if(iter->fDataType == AliHLTEMCALDefinitions::fgkTriggerSTUDataType){
      // Handle STU data
      AliHLTEMCALSTUHeaderStruct *stuheader = reinterpret_cast<AliHLTEMCALSTUHeaderStruct *>(iter->fPtr);
      dataptr = reinterpret_cast<AliHLTCaloTriggerRawDigitDataStruct *>(reinterpret_cast<AliHLTUInt8_t*>(iter->fPtr) + sizeof(AliHLTEMCALSTUHeaderStruct));
      HLTDebug("Data containing %d STU digits", stuheader->fNRawDigits);
      ReadSTUData(stuheader, dataptr);
    }
  }

  // Write header
  memcpy(headerPtr->fL1Threshold, fSTUHeader.fL1Threshold, sizeof(Int_t) *4);
  memcpy(headerPtr->fL1V0, fSTUHeader.fL1V0, sizeof(Int_t) * 2);
  headerPtr->fL1FrameMask = fSTUHeader.fL1FrameMask;

  AliHLTUInt32_t availableSize = size - sizeof(AliHLTCaloTriggerHeaderStruct);

  // Write data
  Int_t dataSize = MakeTriggerData(dataIter, availableSize);
  totSize += dataSize;
  headerPtr->fNfastor = dataSize / sizeof(AliHLTCaloTriggerDataStruct);

  AliHLTComponentBlockData bdChannelData;
  FillBlockData( bdChannelData );
  bdChannelData.fOffset = 0; //FIXME
  bdChannelData.fSize = totSize;
  bdChannelData.fDataType = GetOutputDataType();
  outputBlocks.push_back(bdChannelData);
  outputPtr += totSize; //Updating position of the output buffer
  size = totSize;
  return 0;
}

void AliHLTEMCALTriggerDataMakerComponent::ReadSTUData(AliHLTEMCALSTUHeaderStruct *headerptr, AliHLTCaloTriggerRawDigitDataStruct *dataptr){
  fSTUHeader = *headerptr;
  for(UShort_t idig = 0; idig < headerptr->fNRawDigits; idig++){
	if(dataptr->fID > kMaxChannels || dataptr->fID < 0){
		HLTWarning("Invalid TRU index: %d", dataptr->fID);
		continue;
	}
    fRawIndexesSTU[dataptr->fID] = fNRawDigitsSTU;
    if(dataptr->fID > fMaxChannel) fMaxChannel = dataptr->fID;
    fSTURawDigitBuffer[fNRawDigitsSTU] = *dataptr;
    dataptr++;
    fNRawDigitsSTU++;
  }
  HLTDebug("Successfully read in %d STU digits", fNRawDigitsSTU);
}

void AliHLTEMCALTriggerDataMakerComponent::ReadTRUData(UShort_t ndigits, AliHLTCaloTriggerRawDigitDataStruct *triggerdata){
  for(UShort_t idig = 0; idig < ndigits; idig++){
    fRawIndexesTRU[triggerdata->fID] = fNRawDigitsTRU;
    if(triggerdata->fID > fMaxChannel) fMaxChannel = triggerdata->fID;
    fTRURawDigitBuffer[fNRawDigitsTRU] = *triggerdata;
    triggerdata++;
    fNRawDigitsTRU++;
  }
  HLTDebug("Successfully read in %d TRU digits", fNRawDigitsTRU);
}

Int_t AliHLTEMCALTriggerDataMakerComponent::MakeTriggerData(AliHLTCaloTriggerDataStruct *outputdata, AliHLTUInt32_t &availableSize) {
  if(availableSize < sizeof(AliHLTCaloTriggerDataStruct)){
	  HLTWarning("Not enough space in buffer to write triggers");
	  return 0;
  }
  Int_t outputsize = 0, col = 0, row = 0, ntriggers = 0 ;
  AliHLTCaloTriggerRawDigitDataStruct tmpdigit;
  for(UShort_t indcounter = 0; indcounter <= fMaxChannel; indcounter++){
	if(availableSize < sizeof(AliHLTCaloTriggerDataStruct)){
		HLTWarning("Buffer exceeded after %d triggers", ntriggers);
		break;
	}
    fGeometry->GetGeometryPtr()->GetPositionInEMCALFromAbsFastORIndex(indcounter, col, row);
    if(fRawIndexesTRU[indcounter] >= 0 && fRawIndexesSTU[indcounter] >=0){
      CombineTRUSTUDigit(tmpdigit, fTRURawDigitBuffer[fRawIndexesTRU[indcounter]], fSTURawDigitBuffer[fRawIndexesSTU[indcounter]]);
      ConvertRawDigit(outputdata, &tmpdigit, col, row);
      outputsize += sizeof(AliHLTCaloTriggerDataStruct);
      availableSize += sizeof(AliHLTCaloTriggerDataStruct);
      outputdata++;
      ntriggers++;
    } else if(fRawIndexesTRU[indcounter] >= 0){
      ConvertRawDigit(outputdata, &(fTRURawDigitBuffer[fRawIndexesTRU[indcounter]]), col, row);
      outputsize += sizeof(AliHLTCaloTriggerDataStruct);
      availableSize += sizeof(AliHLTCaloTriggerDataStruct);
      outputdata++;
      ntriggers++;
    } else if(fRawIndexesSTU[indcounter] >= 0){
      ConvertRawDigit(outputdata, &(fSTURawDigitBuffer[fRawIndexesSTU[indcounter]]), col, row);
      outputsize += sizeof(AliHLTCaloTriggerDataStruct);
      availableSize += sizeof(AliHLTCaloTriggerDataStruct);
      outputdata++;
      ntriggers++;
    }
  }
  return outputsize;
}

void AliHLTEMCALTriggerDataMakerComponent::CombineTRUSTUDigit(
    AliHLTCaloTriggerRawDigitDataStruct &target,
    const AliHLTCaloTriggerRawDigitDataStruct &trudigit,
    const AliHLTCaloTriggerRawDigitDataStruct &studigit){
  AliHLTCaloTriggerRawDigitDataStruct merged;
  target.fID = trudigit.fID;
  target.fNTimeSamples = trudigit.fNTimeSamples;
  memcpy(target.fTimeSamples, trudigit.fTimeSamples, sizeof(Int_t) * 15);
  target.fNL0Times = trudigit.fNL0Times;
  memcpy(target.fL0Times, trudigit.fL0Times, sizeof(UChar_t) * 10);
  target.fL1TimeSum = studigit.fL1TimeSum;
  target.fTriggerBits = trudigit.fTriggerBits | studigit.fTriggerBits;
}

void AliHLTEMCALTriggerDataMakerComponent::Reset(){
  for(Short_t iter = 0; iter < kMaxChannels; iter++){
    fRawIndexesTRU[iter] = -1;
    fRawIndexesSTU[iter] = -1;
  }
  fNRawDigitsTRU = 0;
  fNRawDigitsSTU = 0;
  fMaxChannel = 0;
}

void AliHLTEMCALTriggerDataMakerComponent::ConvertRawDigit(AliHLTCaloTriggerDataStruct *target, const AliHLTCaloTriggerRawDigitDataStruct *source, Int_t col, Int_t row) {
  target->fCol = col;
  target->fRow = row;
  Int_t amplitude, time;
  GetRawDigitMaximumAmplitude(*source, amplitude, time);
  target->fAmplitude = static_cast<Float_t>(amplitude);
  target->fTime = static_cast<Float_t>(time);
  target->fL1TimeSum = source->fL1TimeSum;
  target->fNL0Times = source->fNL0Times;
  memcpy(target->fL0Times, source->fL0Times, sizeof(UChar_t) * 10);
  target->fTriggerBits = source->fTriggerBits;
}
<commit_msg>Fix processing of TRU data in case an invalid TRU index was detected, improve copying of TRU Raw digits (do not use hardcoded size constatnts)<commit_after>/**************************************************************************
 * This file is property of and copyright by the ALICE HLT Project        *
 * All rights reserved.                                                   *
 *                                                                        *
 * Primary Authors: Markus Fasel                                          *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/
#include "AliHLTCaloTriggerDataStruct.h"
#include "AliHLTCaloTriggerHeaderStruct.h"
#include "AliHLTCaloTriggerRawDigitDataStruct.h"
#include "AliEMCALTriggerSTURawStream.h"
#include "AliHLTEMCALDefinitions.h"
#include "AliHLTEMCALGeometry.h"
#include "AliHLTEMCALTriggerDataMakerComponent.h"

ClassImp(AliHLTEMCALTriggerDataMakerComponent)

AliHLTEMCALTriggerDataMakerComponent::AliHLTEMCALTriggerDataMakerComponent():
AliHLTCaloProcessor(),
AliHLTCaloConstantsHandler("EMCAL"),
fGeometry(NULL),
fSTUHeader(),
fNRawDigitsTRU(0),
fNRawDigitsSTU(0),
fMaxChannel(0)
{
  for(Short_t iter = 0; iter < kMaxChannels; iter++){
    fRawIndexesTRU[iter] = -1;
    fRawIndexesSTU[iter] = -1;
  }
}

AliHLTEMCALTriggerDataMakerComponent::~AliHLTEMCALTriggerDataMakerComponent() {
  if(fGeometry) delete fGeometry;
}

int AliHLTEMCALTriggerDataMakerComponent::DoInit(int argc, const char **argv){
  fGeometry = new AliHLTEMCALGeometry(GetRunNo());
  return 0;
}

int AliHLTEMCALTriggerDataMakerComponent::DoDeinit(){
  if(fGeometry) delete fGeometry;
  fGeometry = NULL;
  return 0;
}

const char* AliHLTEMCALTriggerDataMakerComponent::GetComponentID(){
  return "EmcalTriggerDataMaker";
}

void AliHLTEMCALTriggerDataMakerComponent::GetInputDataTypes( std::vector <AliHLTComponentDataType>& list){
  list.clear();
  list.push_back( AliHLTEMCALDefinitions::fgkTriggerRawDigitDataType   | kAliHLTDataOriginEMCAL );
  list.push_back( AliHLTEMCALDefinitions::fgkTriggerSTUDataType | kAliHLTDataOriginEMCAL );
}

AliHLTComponentDataType AliHLTEMCALTriggerDataMakerComponent::GetOutputDataType(){
  return kAliHLTDataTypeCaloTrigger | kAliHLTDataOriginEMCAL;
}

void AliHLTEMCALTriggerDataMakerComponent::GetOutputDataSize(unsigned long& constBase, double& inputMultiplier){
  constBase = sizeof(AliHLTCaloTriggerHeaderStruct);
  inputMultiplier = 1.5;
}

AliHLTComponent* AliHLTEMCALTriggerDataMakerComponent::Spawn(){
  return new AliHLTEMCALTriggerDataMakerComponent;
}

bool AliHLTEMCALTriggerDataMakerComponent::CheckInputDataType(const AliHLTComponentDataType &datatype) {
  //comment
  vector <AliHLTComponentDataType> validTypes;
  GetInputDataTypes(validTypes);

  for(UInt_t i=0; i < validTypes.size(); i++) {
    if ( datatype  ==  validTypes.at(i) ) {
      return true;
    }
  }

  HLTDebug("Invalid Datatype");
  return false;
}

int AliHLTEMCALTriggerDataMakerComponent::DoEvent( const AliHLTComponentEventData& evtData, const AliHLTComponentBlockData* blocks,
         AliHLTComponentTriggerData& trigData, AliHLTUInt8_t* outputPtr,
         AliHLTUInt32_t& size, std::vector<AliHLTComponentBlockData>& outputBlocks ){

  if(!IsDataEvent()) {
    size = 0;
    return 0;
  }

  UInt_t totSize            = 0;
  const AliHLTComponentBlockData* iter = NULL;

  // Get pointers to output buffer
  AliHLTCaloTriggerHeaderStruct *headerPtr = reinterpret_cast<AliHLTCaloTriggerHeaderStruct *>(outputPtr);
  AliHLTCaloTriggerDataStruct *dataIter = reinterpret_cast<AliHLTCaloTriggerDataStruct *>(outputPtr + sizeof(AliHLTCaloTriggerHeaderStruct));
  totSize += sizeof(AliHLTCaloTriggerHeaderStruct);

  Reset();
  AliHLTCaloTriggerRawDigitDataStruct *dataptr = NULL;
  for(ULong_t ndx = 0; ndx < evtData.fBlockCnt; ndx++){
    iter = blocks + ndx;

    if(!this->CheckInputDataType(iter->fDataType)){
      continue;
    }

    if(iter->fDataType == AliHLTEMCALDefinitions::fgkTriggerRawDigitDataType){
      // Handle TRU data
      Int_t ndigits = iter->fSize / sizeof(AliHLTCaloTriggerRawDigitDataStruct);
      HLTDebug("Data containing %d TRU digits", ndigits);
      dataptr = reinterpret_cast<AliHLTCaloTriggerRawDigitDataStruct *>(iter->fPtr);
      ReadTRUData(ndigits, dataptr);
    } else if(iter->fDataType == AliHLTEMCALDefinitions::fgkTriggerSTUDataType){
      // Handle STU data
      AliHLTEMCALSTUHeaderStruct *stuheader = reinterpret_cast<AliHLTEMCALSTUHeaderStruct *>(iter->fPtr);
      dataptr = reinterpret_cast<AliHLTCaloTriggerRawDigitDataStruct *>(reinterpret_cast<AliHLTUInt8_t*>(iter->fPtr) + sizeof(AliHLTEMCALSTUHeaderStruct));
      HLTDebug("Data containing %d STU digits", stuheader->fNRawDigits);
      ReadSTUData(stuheader, dataptr);
    }
  }

  // Write header
  memcpy(headerPtr->fL1Threshold, fSTUHeader.fL1Threshold, sizeof(Int_t) *4);
  memcpy(headerPtr->fL1V0, fSTUHeader.fL1V0, sizeof(Int_t) * 2);
  headerPtr->fL1FrameMask = fSTUHeader.fL1FrameMask;

  AliHLTUInt32_t availableSize = size - sizeof(AliHLTCaloTriggerHeaderStruct);

  // Write data
  Int_t dataSize = MakeTriggerData(dataIter, availableSize);
  totSize += dataSize;
  headerPtr->fNfastor = dataSize / sizeof(AliHLTCaloTriggerDataStruct);

  AliHLTComponentBlockData bdChannelData;
  FillBlockData( bdChannelData );
  bdChannelData.fOffset = 0; //FIXME
  bdChannelData.fSize = totSize;
  bdChannelData.fDataType = GetOutputDataType();
  outputBlocks.push_back(bdChannelData);
  outputPtr += totSize; //Updating position of the output buffer
  size = totSize;
  return 0;
}

void AliHLTEMCALTriggerDataMakerComponent::ReadSTUData(AliHLTEMCALSTUHeaderStruct *headerptr, AliHLTCaloTriggerRawDigitDataStruct *dataptr){
  fSTUHeader = *headerptr;
  for(UShort_t idig = 0; idig < headerptr->fNRawDigits; idig++){
	if(dataptr->fID > kMaxChannels || dataptr->fID < 0){
		HLTWarning("Invalid TRU index: %d", dataptr->fID);
		dataptr++;
		continue;
	}
    fRawIndexesSTU[dataptr->fID] = fNRawDigitsSTU;
    if(dataptr->fID > fMaxChannel) fMaxChannel = dataptr->fID;
    fSTURawDigitBuffer[fNRawDigitsSTU] = *dataptr;
    dataptr++;
    fNRawDigitsSTU++;
  }
  HLTDebug("Successfully read in %d STU digits", fNRawDigitsSTU);
}

void AliHLTEMCALTriggerDataMakerComponent::ReadTRUData(UShort_t ndigits, AliHLTCaloTriggerRawDigitDataStruct *triggerdata){
  for(UShort_t idig = 0; idig < ndigits; idig++){
    fRawIndexesTRU[triggerdata->fID] = fNRawDigitsTRU;
    if(triggerdata->fID > fMaxChannel) fMaxChannel = triggerdata->fID;
    fTRURawDigitBuffer[fNRawDigitsTRU] = *triggerdata;
    triggerdata++;
    fNRawDigitsTRU++;
  }
  HLTDebug("Successfully read in %d TRU digits", fNRawDigitsTRU);
}

Int_t AliHLTEMCALTriggerDataMakerComponent::MakeTriggerData(AliHLTCaloTriggerDataStruct *outputdata, AliHLTUInt32_t &availableSize) {
  if(availableSize < sizeof(AliHLTCaloTriggerDataStruct)){
	  HLTWarning("Not enough space in buffer to write triggers");
	  return 0;
  }
  Int_t outputsize = 0, col = 0, row = 0, ntriggers = 0 ;
  AliHLTCaloTriggerRawDigitDataStruct tmpdigit;
  for(UShort_t indcounter = 0; indcounter <= fMaxChannel; indcounter++){
	if(availableSize < sizeof(AliHLTCaloTriggerDataStruct)){
		HLTWarning("Buffer exceeded after %d triggers", ntriggers);
		break;
	}
    fGeometry->GetGeometryPtr()->GetPositionInEMCALFromAbsFastORIndex(indcounter, col, row);
    if(fRawIndexesTRU[indcounter] >= 0 && fRawIndexesSTU[indcounter] >=0){
      CombineTRUSTUDigit(tmpdigit, fTRURawDigitBuffer[fRawIndexesTRU[indcounter]], fSTURawDigitBuffer[fRawIndexesSTU[indcounter]]);
      ConvertRawDigit(outputdata, &tmpdigit, col, row);
      outputsize += sizeof(AliHLTCaloTriggerDataStruct);
      availableSize += sizeof(AliHLTCaloTriggerDataStruct);
      outputdata++;
      ntriggers++;
    } else if(fRawIndexesTRU[indcounter] >= 0){
      ConvertRawDigit(outputdata, &(fTRURawDigitBuffer[fRawIndexesTRU[indcounter]]), col, row);
      outputsize += sizeof(AliHLTCaloTriggerDataStruct);
      availableSize += sizeof(AliHLTCaloTriggerDataStruct);
      outputdata++;
      ntriggers++;
    } else if(fRawIndexesSTU[indcounter] >= 0){
      ConvertRawDigit(outputdata, &(fSTURawDigitBuffer[fRawIndexesSTU[indcounter]]), col, row);
      outputsize += sizeof(AliHLTCaloTriggerDataStruct);
      availableSize += sizeof(AliHLTCaloTriggerDataStruct);
      outputdata++;
      ntriggers++;
    }
  }
  return outputsize;
}

void AliHLTEMCALTriggerDataMakerComponent::CombineTRUSTUDigit(
    AliHLTCaloTriggerRawDigitDataStruct &target,
    const AliHLTCaloTriggerRawDigitDataStruct &trudigit,
    const AliHLTCaloTriggerRawDigitDataStruct &studigit){
  AliHLTCaloTriggerRawDigitDataStruct merged;
  target.fID = trudigit.fID;
  target.fNTimeSamples = trudigit.fNTimeSamples;
  memcpy(target.fTimeSamples, trudigit.fTimeSamples, sizeof(AliHLTCaloTriggerRawDigitDataStruct::fTimeSamples));
  target.fNL0Times = trudigit.fNL0Times;
  memcpy(target.fL0Times, trudigit.fL0Times, sizeof(AliHLTCaloTriggerRawDigitDataStruct::fL0Times));
  target.fL1TimeSum = studigit.fL1TimeSum;
  target.fTriggerBits = trudigit.fTriggerBits | studigit.fTriggerBits;
}

void AliHLTEMCALTriggerDataMakerComponent::Reset(){
  for(Short_t iter = 0; iter < kMaxChannels; iter++){
    fRawIndexesTRU[iter] = -1;
    fRawIndexesSTU[iter] = -1;
  }
  fNRawDigitsTRU = 0;
  fNRawDigitsSTU = 0;
  fMaxChannel = 0;
}

void AliHLTEMCALTriggerDataMakerComponent::ConvertRawDigit(AliHLTCaloTriggerDataStruct *target, const AliHLTCaloTriggerRawDigitDataStruct *source, Int_t col, Int_t row) {
  target->fCol = col;
  target->fRow = row;
  Int_t amplitude, time;
  GetRawDigitMaximumAmplitude(*source, amplitude, time);
  target->fAmplitude = static_cast<Float_t>(amplitude);
  target->fTime = static_cast<Float_t>(time);
  target->fL1TimeSum = source->fL1TimeSum;
  target->fNL0Times = source->fNL0Times;
  memcpy(target->fL0Times, source->fL0Times, sizeof(UChar_t) * 10);
  target->fTriggerBits = source->fTriggerBits;
}
<|endoftext|>


<commit_before>// This file is part of the dune-stuff project:
//   https://users.dune-project.org/projects/dune-stuff/
// Copyright holders: Rene Milk, Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_STUFF_COMMON_PARALLEL_HELPER_HH
#define DUNE_STUFF_COMMON_PARALLEL_HELPER_HH

#include <type_traits>

#include <dune/common/parallel/collectivecommunication.hh>

#if HAVE_DUNE_ISTL
# include <dune/istl/paamg/pinfo.hh>
#endif

namespace Dune {
namespace Stuff {

//! marker for sequential in MPI-enabled solver stuffs
struct SequentialCommunication
#if HAVE_DUNE_ISTL
  : public Dune::Amg::SequentialInformation
#endif
{};

template <class GridCommImp>
struct UseParallelCommunication
{
#if HAVE_MPI && HAVE_DUNE_ISTL
  static constexpr bool value = std::is_same< GridCommImp, CollectiveCommunication< MPI_Comm > >::value;
#else
  static constexpr bool value = false;
#endif
};

} // namespace Stuff
} // namespace Dune

#endif // DUNE_STUFF_COMMON_PARALLEL_HELPER_HH
<commit_msg>[common.parallel.helper] disabled some external warnings<commit_after>// This file is part of the dune-stuff project:
//   https://users.dune-project.org/projects/dune-stuff/
// Copyright holders: Rene Milk, Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_STUFF_COMMON_PARALLEL_HELPER_HH
#define DUNE_STUFF_COMMON_PARALLEL_HELPER_HH

#include <type_traits>

#include <dune/common/parallel/collectivecommunication.hh>

#if HAVE_DUNE_ISTL
# include <dune/stuff/common/disable_warnings.hh>
#   include <dune/istl/paamg/pinfo.hh>
# include <dune/stuff/common/reenable_warnings.hh>
#endif

namespace Dune {
namespace Stuff {

//! marker for sequential in MPI-enabled solver stuffs
struct SequentialCommunication
#if HAVE_DUNE_ISTL
  : public Dune::Amg::SequentialInformation
#endif
{};

template <class GridCommImp>
struct UseParallelCommunication
{
#if HAVE_MPI && HAVE_DUNE_ISTL
  static constexpr bool value = std::is_same< GridCommImp, CollectiveCommunication< MPI_Comm > >::value;
#else
  static constexpr bool value = false;
#endif
};

} // namespace Stuff
} // namespace Dune

#endif // DUNE_STUFF_COMMON_PARALLEL_HELPER_HH
<|endoftext|>


<commit_before>/*
 *
 * Copyright 2016 gRPC authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

#include <stdbool.h>

#include <grpc/grpc.h>

#include <grpc/support/log.h>
#include "src/core/lib/iomgr/exec_ctx.h"
#include "src/core/lib/iomgr/load_file.h"

extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size);

extern bool squelch;
extern bool leak_check;

int main(int argc, char** argv) {
  grpc_slice buffer;
  squelch = false;
  leak_check = false;
  /* TODO(yashkt) Calling grpc_init breaks tests. Fix the tests and replace
   * grpc_core::ExecCtx::GlobalInit with grpc_init and GlobalShutdown with
   * grpc_shutdown */
  GPR_ASSERT(argc > 1);  /* Make sure that we have a filename argument */
  GPR_ASSERT(
      GRPC_LOG_IF_ERROR("load_file", grpc_load_file(argv[1], 0, &buffer)));
  LLVMFuzzerTestOneInput(GRPC_SLICE_START_PTR(buffer),
                         GRPC_SLICE_LENGTH(buffer));
  grpc_core::ExecCtx::GlobalInit();
  grpc_slice_unref(buffer);
  grpc_core::ExecCtx::GlobalShutdown();
  return 0;
}
<commit_msg>clang-format<commit_after>/*
 *
 * Copyright 2016 gRPC authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

#include <stdbool.h>

#include <grpc/grpc.h>

#include <grpc/support/log.h>
#include "src/core/lib/iomgr/exec_ctx.h"
#include "src/core/lib/iomgr/load_file.h"

extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size);

extern bool squelch;
extern bool leak_check;

int main(int argc, char** argv) {
  grpc_slice buffer;
  squelch = false;
  leak_check = false;
  /* TODO(yashkt) Calling grpc_init breaks tests. Fix the tests and replace
   * grpc_core::ExecCtx::GlobalInit with grpc_init and GlobalShutdown with
   * grpc_shutdown */
  GPR_ASSERT(argc > 1); /* Make sure that we have a filename argument */
  GPR_ASSERT(
      GRPC_LOG_IF_ERROR("load_file", grpc_load_file(argv[1], 0, &buffer)));
  LLVMFuzzerTestOneInput(GRPC_SLICE_START_PTR(buffer),
                         GRPC_SLICE_LENGTH(buffer));
  grpc_core::ExecCtx::GlobalInit();
  grpc_slice_unref(buffer);
  grpc_core::ExecCtx::GlobalShutdown();
  return 0;
}
<|endoftext|>


<commit_before>// Day06.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

int main()
{
	auto Memory = GetValues<unsigned int>("Input.txt");
	std::set<std::vector<unsigned int>> Configurations = { Memory };
	size_t Steps = 0;

	for (; Steps == (Configurations.size() - 1); ++Steps)
	{
		auto Bank = std::max_element(Memory.begin(), Memory.end());
		unsigned int Blocks = *Bank;
		*Bank = 0;

		for (; Blocks > 0; --Blocks)
		{
			if(++Bank == Memory.end())
				Bank = Memory.begin();

			++(*Bank);
		}

		Configurations.insert(Memory);
	}

	std::cout << "Steps: " << Steps << std::endl;

	system("pause");
    return 0;
}

<commit_msg>Day 06 part two<commit_after>// Day06.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

int main()
{
	auto Memory = GetValues<unsigned int>("Input.txt");
	std::map<std::vector<unsigned int>, size_t> Configurations = { { Memory, 0 } };
	size_t Steps = 0;

	while(Steps == (Configurations.size() - 1))
	{
		auto Bank = std::max_element(Memory.begin(), Memory.end());
		unsigned int Blocks = *Bank;
		*Bank = 0;

		for (; Blocks > 0; --Blocks)
		{
			if(++Bank == Memory.end())
				Bank = Memory.begin();

			++(*Bank);
		}

		++Steps;
		Configurations.insert({ Memory, Steps});
	}

	std::cout << "Steps: " << Steps << std::endl;
	std::cout << "Cycle: " << (Steps - Configurations[Memory]) << std::endl;

	system("pause");
    return 0;
}

<|endoftext|>


<commit_before>// Day18.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

constexpr size_t RegisterCount = 'z' - 'a';

struct State;

using RegisterType = int64_t;
using Instruction = std::function<size_t(State &)>;
using Registers = std::array<RegisterType, RegisterCount>;

struct State
{
	Registers Registers;
	int Frequency;
	bool RecoveryFlag;
};

RegisterType & FetchRegister(const std::string & Name, Registers & Regs);
std::function<const RegisterType()> FetchSecondArg(const std::string & String, Registers & Regs);

const std::unordered_map<std::string, std::function<Instruction(const StringVector &, Registers &)>> CompilerMap{
	{"set", [](const StringVector & Line, Registers & Regs)->Instruction
		{
			RegisterType & Arg1 = FetchRegister(Line[1], Regs);
			auto Arg2 = FetchSecondArg(Line[2], Regs);
			return [Arg2, &Arg1](State &)->size_t { Arg1 = Arg2(); return 1; };
		}
	},
	{"add", [](const StringVector & Line, Registers & Regs)->Instruction
		{
			RegisterType & Arg1 = FetchRegister(Line[1], Regs);
			auto Arg2 = FetchSecondArg(Line[2], Regs);
			return [Arg2, &Arg1](State &)->size_t { Arg1 += Arg2(); return 1; };
		}
	},
	{ "mul", [](const StringVector & Line, Registers & Regs)->Instruction
		{
			RegisterType & Arg1 = FetchRegister(Line[1], Regs);
			auto Arg2 = FetchSecondArg(Line[2], Regs);
			return [Arg2, &Arg1](State &)->size_t { Arg1 *= Arg2(); return 1; };
		}
	},
	{ "mod", [](const StringVector & Line, Registers & Regs)->Instruction
		{
			RegisterType & Arg1 = FetchRegister(Line[1], Regs);
			auto Arg2 = FetchSecondArg(Line[2], Regs);
			return [Arg2, &Arg1](State &)->size_t { Arg1 %= Arg2(); return 1; };
		}
	},
	{ "snd", [](const StringVector & Line, Registers & Regs)->Instruction
		{
			RegisterType & Arg1 = FetchRegister(Line[1], Regs);
			return [&Arg1](State & State)->size_t { State.Frequency = Arg1; return 1; };
		}
	},
	{ "rcv", [](const StringVector & Line, Registers & Regs)->Instruction
		{
			RegisterType & Arg1 = FetchRegister(Line[1], Regs);
			return [&Arg1](State & State)->size_t {
				if (Arg1 != 0)
				{
					Arg1 = State.Frequency;
					State.RecoveryFlag = true;
				}
				return 1;
			};
		}
	},
	{ "jgz", [](const StringVector & Line, Registers & Regs)->Instruction
		{
			auto Arg1 = FetchSecondArg(Line[1], Regs);
			auto Arg2 = FetchSecondArg(Line[2], Regs);
			return [Arg1, Arg2](State &)->size_t {
				if (Arg1() > 0)
					return Arg2();
				return 1;
			};
		}
	},
};

RegisterType & FetchRegister(const std::string & Name, Registers & Regs)
{
	return Regs[Name[0] - 'a'];
}

std::function<const RegisterType()> FetchSecondArg(const std::string & String, Registers & Regs)
{
	if (String[0] >= 'a')
	{
		const char Register = String[0] - 'a';
		return [Register, &Regs]()->const int { return Regs[Register]; };
	}
	else
	{
		const int Value = std::stoi(String);
		return [Value]()->const int { return Value; };
	}
}

int main()
{
	const StringVectorVector Lines = GetFileLineParts("Input.txt");

	State State{ 0 };
	size_t InstructionPointer = 0;
	std::vector<Instruction> Instructions;

	for (const auto & Line : Lines)
	{
		auto InstructionCompiler = CompilerMap.find(Line[0]);
		if (InstructionCompiler == CompilerMap.end())
		{
			std::cout << "Panic Alert: Unknown Opcode " << Line[0] << std::endl;
		}
		else
		{
			Instructions.emplace_back(InstructionCompiler->second(Line, State.Registers));
		}
	}

	while (InstructionPointer < Instructions.size())
	{
		InstructionPointer += Instructions[InstructionPointer](State);
		if (State.RecoveryFlag)
		{
			std::cout << "Last Frequency: " << State.Frequency << std::endl;
			break;
		}
	}

	system("pause");
    return 0;
}

<commit_msg>Day 18 part two<commit_after>// Day18.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

constexpr size_t RegisterCount = 'z' - 'a';

struct State;

using RegisterType = int64_t;
using Instruction = std::function<bool(State &)>;
using Registers = std::array<RegisterType, RegisterCount>;
using Queue = std::queue<RegisterType>;

struct State
{
	size_t InstructionPointer;
	Registers Registers;
	bool ReceiveFlag;
	RegisterType LastSendValue;
	size_t SendCounter;
	Queue SendBuffer;
	Queue * ReceiveBuffer;
};

std::function<RegisterType & (State &)> FetchRegisterReference(const std::string & Name)
{
	const char RegisterID = Name[0] - 'a';
	return [RegisterID](State & State)->RegisterType& { return State.Registers[RegisterID]; };
}

std::function<const RegisterType(State &)> FetchValue(const std::string & String)
{
	if (String[0] >= 'a')
	{
		const char RegisterID = String[0] - 'a';
		return [RegisterID](State & State)->const RegisterType { return State.Registers[RegisterID]; };
	}
	else
	{
		const int Value = std::stoi(String);
		return [Value](State &)->const RegisterType { return Value; };
	}
}

const std::unordered_map<std::string, std::function<Instruction(const StringVector &)>> CompilerMap{
	{"set", [](const StringVector & Line)->Instruction
		{
			auto Arg1 = FetchRegisterReference(Line[1]);
			auto Arg2 = FetchValue(Line[2]);
			return [=](State & State)->bool { Arg1(State) = Arg2(State); State.InstructionPointer++; return true; };
		}
	},
	{"add", [](const StringVector & Line)->Instruction
		{
			auto Arg1 = FetchRegisterReference(Line[1]);
			auto Arg2 = FetchValue(Line[2]);
			return [=](State & State)->bool { Arg1(State) += Arg2(State); State.InstructionPointer++; return true; };
		}
	},
	{ "mul", [](const StringVector & Line)->Instruction
		{
			auto Arg1 = FetchRegisterReference(Line[1]);
			auto Arg2 = FetchValue(Line[2]);
			return [=](State & State)->bool { Arg1(State) *= Arg2(State); State.InstructionPointer++; return true; };
		}
	},
	{ "mod", [](const StringVector & Line)->Instruction
		{
			auto Arg1 = FetchRegisterReference(Line[1]);
			auto Arg2 = FetchValue(Line[2]);
			return [=](State & State)->bool { Arg1(State) %= Arg2(State); State.InstructionPointer++; return true; };
		}
	},
	{ "snd", [](const StringVector & Line)->Instruction
		{
			auto Arg1 = FetchRegisterReference(Line[1]);
			return [=](State & State)->bool {
				State.LastSendValue = Arg1(State);
				State.SendBuffer.push(State.LastSendValue);
				State.SendCounter++;
				State.InstructionPointer++;
				return true;
			};
		}
	},
	{ "rcv", [](const StringVector & Line)->Instruction
		{
			auto Arg1 = FetchRegisterReference(Line[1]);
			return [=](State & State)->bool {
				RegisterType & Register = Arg1(State);

				if (State.ReceiveBuffer == nullptr)
				{
					if (Register != 0)
					{
						Register = State.LastSendValue;
						State.ReceiveFlag = true;
					}
				}
				else
				{
					if (State.ReceiveBuffer->size() <= 0)
						return false;

					Register = State.ReceiveBuffer->front();
					State.ReceiveBuffer->pop();
				}

				State.InstructionPointer++;
				return true;
			};
		}
	},
	{ "jgz", [](const StringVector & Line)->Instruction
		{
			auto Arg1 = FetchValue(Line[1]);
			auto Arg2 = FetchValue(Line[2]);
			return [=](State & State)->bool {
				State.InstructionPointer += (Arg1(State) > 0) ? Arg2(State) : 1;
				return true;
			};
		}
	},
};

void PartOne(const std::vector<Instruction> & Instructions)
{
	State PartOne{ 0 };

	while (PartOne.InstructionPointer < Instructions.size())
	{
		Instructions[PartOne.InstructionPointer](PartOne);
		if (PartOne.ReceiveFlag)
		{
			std::cout << "Last Frequency: " << PartOne.LastSendValue << std::endl;
			break;
		}
	}
}

void PartTwo(const std::vector<Instruction> & Instructions)
{
	State ThreadZero{ 0 };
	State ThreadOne{ 0 };
	ThreadZero.ReceiveBuffer = &ThreadOne.SendBuffer;
	ThreadOne.ReceiveBuffer = &ThreadZero.SendBuffer;

	ThreadZero.Registers['p' - 'a'] = 0;
	ThreadOne.Registers['p' - 'a'] = 1;

	while ((ThreadZero.InstructionPointer < Instructions.size()) && (ThreadOne.InstructionPointer < Instructions.size()))
	{
		bool ThradZeroAdvanced = Instructions[ThreadZero.InstructionPointer](ThreadZero);
		bool ThradOneAdvanced = Instructions[ThreadOne.InstructionPointer](ThreadOne);

		if (!(ThradZeroAdvanced || ThradOneAdvanced))
			break;
	}

	std::cout << "Thread 0: " << ThreadZero.SendCounter << std::endl;
	std::cout << "Thread 1: " << ThreadOne.SendCounter << std::endl;
}

int main()
{
	const StringVectorVector Lines = GetFileLineParts("Input.txt");

	std::vector<Instruction> Instructions;

	for (const auto & Line : Lines)
	{
		auto InstructionCompiler = CompilerMap.find(Line[0]);
		if (InstructionCompiler == CompilerMap.end())
		{
			std::cout << "Panic Alert: Unknown Opcode " << Line[0] << std::endl;
		}
		else
		{
			Instructions.emplace_back(InstructionCompiler->second(Line));
		}
	}

	PartOne(Instructions);
	PartTwo(Instructions);

	system("pause");
    return 0;
}

<|endoftext|>


<commit_before>#define ENUM_DECLARATION_CPP
#include "jaspObject.h"
#include "jaspJson.h"
#include <chrono>

#if defined(_WIN32) || !defined(JASP_R_INTERFACE_LIBRARY)
#include "lib_json/json_value.cpp" //hacky way to get libjson in the code ^^
#include "lib_json/json_reader.cpp"
#include "lib_json/json_writer.cpp"
#endif

jaspObjectType jaspObjectTypeStringToObjectType(std::string type)
{
	try			{ return jaspObjectTypeFromString(type); }
	catch(...)	{ return jaspObjectType::unknown; }
}

std::string stringExtend(std::string & str, size_t len, char kar)
{
	if(str.size() < len)
		str += std::string(len - str.size(), kar);

	return str;
}

std::string stringRemove(std::string str, char kar)
{
	for(size_t removeMe = str.find_first_of(kar); removeMe != std::string::npos; removeMe = str.find_first_of(kar))
		str.erase(removeMe, 1);
	return str;
}

std::vector<std::string> stringSplit(std::string str, char kar)
{
	std::vector<std::string> strs;

	strs.push_back("");
	for(char k : str)
		if(k == kar)
			strs.push_back("");
		else
			strs[strs.size() - 1].push_back(k);

	return strs;
}

void jaspPrint(std::string msg)
{
#ifdef JASP_R_INTERFACE_LIBRARY
	std::cout << msg << std::endl;
#else
	Rcpp::Rcout << msg << "\n";
	//Rprintf(msg.c_str());
#endif
}

std::set<jaspObject*> * jaspObject::allocatedObjects = new std::set<jaspObject*>();

jaspObject::~jaspObject()
{
	allocatedObjects->erase(this);

	if(parent != NULL)
		parent->removeChild(this);

	while (children.size() > 0)
	{
		jaspObject * p = *(children.begin());

		removeChild(p);

		delete p;
	}
}

void jaspObject::destroyAllAllocatedObjects()
{
	//std::cout << "destroyAllAllocatedObjects!\n"<<std::flush;
	while(allocatedObjects->size() > 0)
	{
		jaspObject * p = *(allocatedObjects->begin());

		//std::cout << "p == "<<p->objectTitleString()<<"!\n"<<std::flush;

		allocatedObjects->erase(allocatedObjects->begin());
		delete p;
	}
}

void jaspObject::addChild(jaspObject * child)
{
#ifdef JASP_RESULTS_DEBUG_TRACES
	std::cout << title << " adds Child " << child->title << "\n" << std::flush;
#endif

	if(child->parent == this)
		return;

	if(child == this || hasAncestor(child))
		throw std::logic_error("You cannot make someone their own descendant, this isn't back to the future..");

	if(child->parent != NULL)
		child->parent->children.erase(child);

	child->parent = this;

	children.insert(child);
}

void jaspObject::removeChild(jaspObject * child)
{
	if(child->parent != this || child == NULL)
		return;

	children.erase(child);

	child->parent = NULL;
}

void jaspObject::finalized()
{
	//std::cout << "jaspObject::finalized() called on "<<objectTitleString()<<" " << (_finalizedAlready ? "again!" :"") << "\n" << std::flush;
	//std::cout << "this: "<<this<<"\n"<<std::flush;

	if(_finalizedAlready)
		return;

	_finalizedAlready= true;

	if(parent != NULL)
		parent->childFinalized(this);

	finalizedHandler();

	for(auto child : children)
		child->finalized();
}

void jaspObject::childFinalized(jaspObject * child)
{
	finalized();

	childFinalizedHandler(child);
	removeChild(child);
}

void jaspObject::notifyParentOfChanges()
{
#ifdef JASP_RESULTS_DEBUG_TRACES
	std::cout << "notifyParentOfChanges()! parent is " << ( parent == NULL ? "NULL" : parent->title) << "\n" << std::flush;
#endif

	if(parent != NULL)
		parent->childrenUpdatedCallback();
}

void jaspObject::childrenUpdatedCallback()
{
#ifdef JASP_RESULTS_DEBUG_TRACES
	std::cout << "childrenUpdatedCallback()! parent is " << ( parent == NULL ? "NULL" : parent->title) << "\n" << std::flush;
#endif

	childrenUpdatedCallbackHandler();

	if(parent != NULL)
		parent->childrenUpdatedCallback();
}

std::string jaspObject::toString(std::string prefix)
{
	std::string dataString = dataToString(prefix + "\t");
	return objectTitleString(prefix) + (dataString == "" ? "\n" : ":\n" + dataString);
}

Rcpp::DataFrame jaspObject::convertFactorsToCharacters(Rcpp::DataFrame df)
{

	for(int col=0; col<df.length(); col++)
		if(Rf_isFactor(df[col]))
		{
			Rcpp::IntegerVector		originalColumn	= df[col];

			Rcpp::CharacterVector	factorLevels	= originalColumn.attr("levels");

/*#ifdef JASP_DEBUG
			//In ifdef because we dont really have access to log here.
			std::cout	<< "converting factors to characters for dataframe\n"
						<< "originalColumn: " << originalColumn << "\n"
						<< "factorLevels: " << factorLevels << std::endl;
#endif*/

			Rcpp::CharacterVector	charCol(originalColumn.size());

			for(int i=0; i<originalColumn.size(); i++)
				charCol[i] = Rcpp::as<std::string>(factorLevels[originalColumn[i] - 1]);

			df[col] = charCol;
		}

	return df;
}

Json::Value	jaspObject::constructMetaEntry(std::string type, std::string meta) const
{
	Json::Value obj(Json::objectValue);

	obj["name"] = getUniqueNestedName();
	obj["type"] = type;

	if(meta != "")
		obj["meta"] = meta;

	return obj;
}

std::string jaspObject::getUniqueNestedName() const
{
	std::string parent_prefix = parent == NULL || parent->getUniqueNestedName() == "" ? "" :  parent->getUniqueNestedName() + "_";

	return parent_prefix + (_name != "" ? _name : "");
}

void jaspObjectFinalizer(jaspObject * obj)
{
	if(obj == NULL)
		return;

#ifdef JASP_RESULTS_DEBUG_TRACES
	std::cout << "JASPobjectFinalizer is run on: " << obj->title << "\n" << std::flush;
#endif

	obj->finalized();
}

Json::Value jaspObject::convertToJSON() const
{
	Json::Value obj(Json::objectValue);

	obj["name"]			= _name;
	obj["title"]		= _title;
	obj["type"]			= jaspObjectTypeToString(_type);
	obj["error"]        = _error;
	obj["errorMessage"] = _errorMessage;
	obj["position"]		= _position;
	obj["citations"]	= Json::arrayValue;;
	obj["messages"]		= Json::arrayValue;

	for(auto c : _citations)
		obj["citations"].append(c);

	for(auto m : _messages)
		obj["messages"].append(m);

	obj["optionMustBe"]	= Json::objectValue;
	for(auto & keyval : _optionMustBe)
		obj["optionMustBe"][keyval.first] = keyval.second;

	obj["optionMustContain"]	= Json::objectValue;
	for(auto & keyval : _optionMustContain)
		obj["optionMustContain"][keyval.first] = keyval.second;

	return obj;
}

void jaspObject::convertFromJSON_SetFields(Json::Value in)
{
	_name			= in.get("name",			"null").asString();
	_title			= in.get("title",			"null").asString();
	_error			= in.get("error",			false).asBool();
	_errorMessage	= in.get("errorMessage",	"").asString();
	_position		= in.get("position",		JASPOBJECT_DEFAULT_POSITION).asInt();

	_citations.clear();
	for(auto & citation : in.get("citations", Json::nullValue))
		_citations.insert(citation.asString());

	_messages.clear();
	for(auto & msg : in.get("messages", Json::nullValue))
		_messages.push_back(msg.asString());

	_optionMustBe.clear();
	Json::Value mustBe(in.get("optionMustBe", Json::objectValue));
	for(auto & mustBeKey : mustBe.getMemberNames())
		_optionMustBe[mustBeKey] = mustBe[mustBeKey];

	_optionMustContain.clear();
	Json::Value mustContain(in.get("optionMustContain", Json::objectValue));
	for(auto & mustContainKey : mustContain.getMemberNames())
		_optionMustContain[mustContainKey] = mustContain[mustContainKey];

}

Json::Value jaspObject::currentOptions = Json::nullValue;

void jaspObject::dependOnOptions(Rcpp::CharacterVector listOptions)
{
	if(currentOptions.isNull()) Rf_error("No options known!");

	for(auto & nameOption : listOptions)
		_optionMustBe[Rcpp::as<std::string>(nameOption)] = currentOptions.get(nameOption, Json::nullValue);
}

void jaspObject::setOptionMustBeDependency(std::string optionName, Rcpp::RObject mustBeThis)
{
	_optionMustBe[optionName]	= jaspJson::RObject_to_JsonValue(mustBeThis);
}

void jaspObject::setOptionMustContainDependency(std::string optionName, Rcpp::RObject mustContainThis)
{
	_optionMustContain[optionName] = jaspJson::RObject_to_JsonValue(mustContainThis);
}

void jaspObject::copyDependenciesFromJaspObject(jaspObject * other)
{
	for(auto fieldVal : other->_optionMustBe)
		_optionMustBe[fieldVal.first] = fieldVal.second;

	for(auto fieldVal : other->_optionMustContain)
		_optionMustContain[fieldVal.first] = fieldVal.second;
}

bool jaspObject::checkDependencies(Json::Value currentOptions)
{
	if((_optionMustBe.size() + _optionMustContain.size()) == 0)
	{

		for(auto & keyval : _optionMustBe)
			if(currentOptions.get(keyval.first, Json::nullValue) != keyval.second)
				return false;

		for(auto & keyval : _optionMustContain)
		{
			bool foundIt = false;

			for(auto & contains : currentOptions.get(keyval.first, Json::arrayValue))
				if(contains == keyval.second)
					foundIt = true;

			if(!foundIt)
				return false;
		}
	}

	checkDependenciesChildren(currentOptions);

	return true;
}

void jaspObject::addCitation(std::string fullCitation)
{
	bool citationAdded = _citations.insert(fullCitation).second;
	if (citationAdded)
		notifyParentOfChanges();
}

Json::Value	jaspObject::dataEntry(std::string & errorMessage) const
{
	Json::Value baseObject(dataEntryBase());

	//cascaded errorMessage supersedes _errorMessage
	if(canShowErrorMessage() && (errorMessage != "" || _errorMessage != "" || _error))
	{
		baseObject["error"]					= Json::objectValue;
		baseObject["error"]["type"]			= "badData"; // I guess?
		baseObject["error"]["errorMessage"] = errorMessage != "" ? errorMessage : _errorMessage; //I guess the errormessage will be blank if only _error is set somehow?

		errorMessage						= ""; //because this is a reference this will make sure it will not be added to the next child
	}

	return baseObject;
}

Json::Value	jaspObject::dataEntryBase() const
{
	Json::Value baseObject(Json::objectValue);
	for(auto c : _citations)
		baseObject["citation"].append(c);

	return baseObject;
}

int jaspObject::getCurrentTimeMs()
{
	return std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
}

<commit_msg>Ok, booleans are hard...<commit_after>#define ENUM_DECLARATION_CPP
#include "jaspObject.h"
#include "jaspJson.h"
#include <chrono>

#if defined(_WIN32) || !defined(JASP_R_INTERFACE_LIBRARY)
#include "lib_json/json_value.cpp" //hacky way to get libjson in the code ^^
#include "lib_json/json_reader.cpp"
#include "lib_json/json_writer.cpp"
#endif

jaspObjectType jaspObjectTypeStringToObjectType(std::string type)
{
	try			{ return jaspObjectTypeFromString(type); }
	catch(...)	{ return jaspObjectType::unknown; }
}

std::string stringExtend(std::string & str, size_t len, char kar)
{
	if(str.size() < len)
		str += std::string(len - str.size(), kar);

	return str;
}

std::string stringRemove(std::string str, char kar)
{
	for(size_t removeMe = str.find_first_of(kar); removeMe != std::string::npos; removeMe = str.find_first_of(kar))
		str.erase(removeMe, 1);
	return str;
}

std::vector<std::string> stringSplit(std::string str, char kar)
{
	std::vector<std::string> strs;

	strs.push_back("");
	for(char k : str)
		if(k == kar)
			strs.push_back("");
		else
			strs[strs.size() - 1].push_back(k);

	return strs;
}

void jaspPrint(std::string msg)
{
#ifdef JASP_R_INTERFACE_LIBRARY
	std::cout << msg << std::endl;
#else
	Rcpp::Rcout << msg << "\n";
	//Rprintf(msg.c_str());
#endif
}

std::set<jaspObject*> * jaspObject::allocatedObjects = new std::set<jaspObject*>();

jaspObject::~jaspObject()
{
	allocatedObjects->erase(this);

	if(parent != NULL)
		parent->removeChild(this);

	while (children.size() > 0)
	{
		jaspObject * p = *(children.begin());

		removeChild(p);

		delete p;
	}
}

void jaspObject::destroyAllAllocatedObjects()
{
	//std::cout << "destroyAllAllocatedObjects!\n"<<std::flush;
	while(allocatedObjects->size() > 0)
	{
		jaspObject * p = *(allocatedObjects->begin());

		//std::cout << "p == "<<p->objectTitleString()<<"!\n"<<std::flush;

		allocatedObjects->erase(allocatedObjects->begin());
		delete p;
	}
}

void jaspObject::addChild(jaspObject * child)
{
#ifdef JASP_RESULTS_DEBUG_TRACES
	std::cout << title << " adds Child " << child->title << "\n" << std::flush;
#endif

	if(child->parent == this)
		return;

	if(child == this || hasAncestor(child))
		throw std::logic_error("You cannot make someone their own descendant, this isn't back to the future..");

	if(child->parent != NULL)
		child->parent->children.erase(child);

	child->parent = this;

	children.insert(child);
}

void jaspObject::removeChild(jaspObject * child)
{
	if(child->parent != this || child == NULL)
		return;

	children.erase(child);

	child->parent = NULL;
}

void jaspObject::finalized()
{
	//std::cout << "jaspObject::finalized() called on "<<objectTitleString()<<" " << (_finalizedAlready ? "again!" :"") << "\n" << std::flush;
	//std::cout << "this: "<<this<<"\n"<<std::flush;

	if(_finalizedAlready)
		return;

	_finalizedAlready= true;

	if(parent != NULL)
		parent->childFinalized(this);

	finalizedHandler();

	for(auto child : children)
		child->finalized();
}

void jaspObject::childFinalized(jaspObject * child)
{
	finalized();

	childFinalizedHandler(child);
	removeChild(child);
}

void jaspObject::notifyParentOfChanges()
{
#ifdef JASP_RESULTS_DEBUG_TRACES
	std::cout << "notifyParentOfChanges()! parent is " << ( parent == NULL ? "NULL" : parent->title) << "\n" << std::flush;
#endif

	if(parent != NULL)
		parent->childrenUpdatedCallback();
}

void jaspObject::childrenUpdatedCallback()
{
#ifdef JASP_RESULTS_DEBUG_TRACES
	std::cout << "childrenUpdatedCallback()! parent is " << ( parent == NULL ? "NULL" : parent->title) << "\n" << std::flush;
#endif

	childrenUpdatedCallbackHandler();

	if(parent != NULL)
		parent->childrenUpdatedCallback();
}

std::string jaspObject::toString(std::string prefix)
{
	std::string dataString = dataToString(prefix + "\t");
	return objectTitleString(prefix) + (dataString == "" ? "\n" : ":\n" + dataString);
}

Rcpp::DataFrame jaspObject::convertFactorsToCharacters(Rcpp::DataFrame df)
{

	for(int col=0; col<df.length(); col++)
		if(Rf_isFactor(df[col]))
		{
			Rcpp::IntegerVector		originalColumn	= df[col];

			Rcpp::CharacterVector	factorLevels	= originalColumn.attr("levels");

/*#ifdef JASP_DEBUG
			//In ifdef because we dont really have access to log here.
			std::cout	<< "converting factors to characters for dataframe\n"
						<< "originalColumn: " << originalColumn << "\n"
						<< "factorLevels: " << factorLevels << std::endl;
#endif*/

			Rcpp::CharacterVector	charCol(originalColumn.size());

			for(int i=0; i<originalColumn.size(); i++)
				charCol[i] = Rcpp::as<std::string>(factorLevels[originalColumn[i] - 1]);

			df[col] = charCol;
		}

	return df;
}

Json::Value	jaspObject::constructMetaEntry(std::string type, std::string meta) const
{
	Json::Value obj(Json::objectValue);

	obj["name"] = getUniqueNestedName();
	obj["type"] = type;

	if(meta != "")
		obj["meta"] = meta;

	return obj;
}

std::string jaspObject::getUniqueNestedName() const
{
	std::string parent_prefix = parent == NULL || parent->getUniqueNestedName() == "" ? "" :  parent->getUniqueNestedName() + "_";

	return parent_prefix + (_name != "" ? _name : "");
}

void jaspObjectFinalizer(jaspObject * obj)
{
	if(obj == NULL)
		return;

#ifdef JASP_RESULTS_DEBUG_TRACES
	std::cout << "JASPobjectFinalizer is run on: " << obj->title << "\n" << std::flush;
#endif

	obj->finalized();
}

Json::Value jaspObject::convertToJSON() const
{
	Json::Value obj(Json::objectValue);

	obj["name"]			= _name;
	obj["title"]		= _title;
	obj["type"]			= jaspObjectTypeToString(_type);
	obj["error"]        = _error;
	obj["errorMessage"] = _errorMessage;
	obj["position"]		= _position;
	obj["citations"]	= Json::arrayValue;;
	obj["messages"]		= Json::arrayValue;

	for(auto c : _citations)
		obj["citations"].append(c);

	for(auto m : _messages)
		obj["messages"].append(m);

	obj["optionMustBe"]	= Json::objectValue;
	for(auto & keyval : _optionMustBe)
		obj["optionMustBe"][keyval.first] = keyval.second;

	obj["optionMustContain"]	= Json::objectValue;
	for(auto & keyval : _optionMustContain)
		obj["optionMustContain"][keyval.first] = keyval.second;

	return obj;
}

void jaspObject::convertFromJSON_SetFields(Json::Value in)
{
	_name			= in.get("name",			"null").asString();
	_title			= in.get("title",			"null").asString();
	_error			= in.get("error",			false).asBool();
	_errorMessage	= in.get("errorMessage",	"").asString();
	_position		= in.get("position",		JASPOBJECT_DEFAULT_POSITION).asInt();

	_citations.clear();
	for(auto & citation : in.get("citations", Json::nullValue))
		_citations.insert(citation.asString());

	_messages.clear();
	for(auto & msg : in.get("messages", Json::nullValue))
		_messages.push_back(msg.asString());

	_optionMustBe.clear();
	Json::Value mustBe(in.get("optionMustBe", Json::objectValue));
	for(auto & mustBeKey : mustBe.getMemberNames())
		_optionMustBe[mustBeKey] = mustBe[mustBeKey];

	_optionMustContain.clear();
	Json::Value mustContain(in.get("optionMustContain", Json::objectValue));
	for(auto & mustContainKey : mustContain.getMemberNames())
		_optionMustContain[mustContainKey] = mustContain[mustContainKey];

}

Json::Value jaspObject::currentOptions = Json::nullValue;

void jaspObject::dependOnOptions(Rcpp::CharacterVector listOptions)
{
	if(currentOptions.isNull()) Rf_error("No options known!");

	for(auto & nameOption : listOptions)
		_optionMustBe[Rcpp::as<std::string>(nameOption)] = currentOptions.get(nameOption, Json::nullValue);
}

void jaspObject::setOptionMustBeDependency(std::string optionName, Rcpp::RObject mustBeThis)
{
	_optionMustBe[optionName]	= jaspJson::RObject_to_JsonValue(mustBeThis);
}

void jaspObject::setOptionMustContainDependency(std::string optionName, Rcpp::RObject mustContainThis)
{
	_optionMustContain[optionName] = jaspJson::RObject_to_JsonValue(mustContainThis);
}

void jaspObject::copyDependenciesFromJaspObject(jaspObject * other)
{
	for(auto fieldVal : other->_optionMustBe)
		_optionMustBe[fieldVal.first] = fieldVal.second;

	for(auto fieldVal : other->_optionMustContain)
		_optionMustContain[fieldVal.first] = fieldVal.second;
}

bool jaspObject::checkDependencies(Json::Value currentOptions)
{
	if((_optionMustBe.size() + _optionMustContain.size()) != 0)
	{

		for(auto & keyval : _optionMustBe)
			if(currentOptions.get(keyval.first, Json::nullValue) != keyval.second)
				return false;

		for(auto & keyval : _optionMustContain)
		{
			bool foundIt = false;

			for(auto & contains : currentOptions.get(keyval.first, Json::arrayValue))
				if(contains == keyval.second)
					foundIt = true;

			if(!foundIt)
				return false;
		}
	}

	checkDependenciesChildren(currentOptions);

	return true;
}

void jaspObject::addCitation(std::string fullCitation)
{
	bool citationAdded = _citations.insert(fullCitation).second;
	if (citationAdded)
		notifyParentOfChanges();
}

Json::Value	jaspObject::dataEntry(std::string & errorMessage) const
{
	Json::Value baseObject(dataEntryBase());

	//cascaded errorMessage supersedes _errorMessage
	if(canShowErrorMessage() && (errorMessage != "" || _errorMessage != "" || _error))
	{
		baseObject["error"]					= Json::objectValue;
		baseObject["error"]["type"]			= "badData"; // I guess?
		baseObject["error"]["errorMessage"] = errorMessage != "" ? errorMessage : _errorMessage; //I guess the errormessage will be blank if only _error is set somehow?

		errorMessage						= ""; //because this is a reference this will make sure it will not be added to the next child
	}

	return baseObject;
}

Json::Value	jaspObject::dataEntryBase() const
{
	Json::Value baseObject(Json::objectValue);
	for(auto c : _citations)
		baseObject["citation"].append(c);

	return baseObject;
}

int jaspObject::getCurrentTimeMs()
{
	return std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
}

<|endoftext|>


<commit_before>#include <string>
using namespace std;

class Nome {
        string nome;
        string sobreNome;
    public:
        Nome(string nome, string sobreNome);
        void exibirNome();
        virtual ~Nome(); //espero que vá usar, senão não tem porque criar isto
};

int main() {}

//https://pt.stackoverflow.com/q/120211/101
<commit_msg>delete<commit_after><|endoftext|>


<commit_before>/*
 * Copyright 2012, 2013 Esrille Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "CanvasGL.h"
#include <boost/concept_check.hpp>

#include <assert.h>

GLuint Canvas::Impl::currentFrameBuffer = 0;

void Canvas::Impl::setup(int w, int h)
{
    if (width != 0 || height != 0 || w < 0 || h < 0)
        return;

    width = w;
    height = h;

    // Setup texture
    glGenTextures(1, &texture);
    glBindTexture(GL_TEXTURE_2D, texture);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);

    if (GLEW_ARB_framebuffer_object) {
        // Setup renderBuffer
        glGenRenderbuffers(1, &renderBuffer);
        glBindRenderbuffer(GL_RENDERBUFFER, renderBuffer);
        glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_STENCIL, width, height);

        // Setup frameBuffer
        glGenFramebuffers(1, &frameBuffer);
        glBindFramebuffer(GL_FRAMEBUFFER, frameBuffer);
        glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture, 0);
        glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, renderBuffer);
        glBindFramebuffer(GL_FRAMEBUFFER, 0);
    } else {
        // Setup renderBuffer
        glGenRenderbuffersEXT(1, &renderBuffer);
        glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, renderBuffer);
        glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_DEPTH_STENCIL_EXT, width, height);

        // Setup frameBuffer
        glGenFramebuffersEXT(1, &frameBuffer);
        glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, frameBuffer);
        glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, texture, 0);
        glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, renderBuffer);
        glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, renderBuffer);
        glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
    }
}

void Canvas::Impl::shutdown()
{
    if (width == 0 && height == 0)
        return;

    if (GLEW_ARB_framebuffer_object) {
        glDeleteFramebuffers(1, &frameBuffer);
        glDeleteRenderbuffers(1, &renderBuffer);
    } else {
        glDeleteFramebuffersEXT(1, &frameBuffer);
        glDeleteRenderbuffersEXT(1, &renderBuffer);
    }
    if (texture) {
        glDeleteTextures(1, &texture);
        texture = 0;
    }
    while (!translucents.empty()) {
        GLuint tex = translucents.back();
        glDeleteTextures(1, &tex);
        translucents.pop_back();
    }
    frameBuffer = 0;
    renderBuffer = 0;
    width = height = 0;
}

void Canvas::Impl::beginRender(unsigned backgroundColor)
{
    GLint v[4];
    glGetIntegerv(GL_VIEWPORT, v);
    GLint viewportHeight = v[3];

    savedFrameBuffer = currentFrameBuffer;
    currentFrameBuffer = frameBuffer;
    if (GLEW_ARB_framebuffer_object)
        glBindFramebuffer(GL_FRAMEBUFFER, currentFrameBuffer);
    else
        glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, currentFrameBuffer);

    GLfloat m[16];
    glGetFloatv(GL_MODELVIEW_MATRIX, m);
    x = m[12];
    y = m[13];

    glMatrixMode(GL_PROJECTION);
    glPushMatrix();
    glTranslatef(-x, viewportHeight - (y + height), 0.0f);

    glMatrixMode(GL_MODELVIEW);
    glPushMatrix();

    glClearColor(((backgroundColor >> 16) & 255) / 255.0f,
                 ((backgroundColor >> 8) & 255) / 255.0f,
                 (backgroundColor & 255) / 255.0f,
                 ((backgroundColor >> 24) & 255) / 255.0f);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
}

void Canvas::Impl::endRender()
{
    glMatrixMode(GL_PROJECTION);
    glPopMatrix();

    glMatrixMode(GL_MODELVIEW);
    glPopMatrix();

    currentFrameBuffer = savedFrameBuffer;
    if (GLEW_ARB_framebuffer_object)
        glBindFramebuffer(GL_FRAMEBUFFER, currentFrameBuffer);
    else
        glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, currentFrameBuffer);
}

void Canvas::Impl::beginTranslucent()
{
    GLuint tex;
    glGenTextures(1, &tex);
    glBindTexture(GL_TEXTURE_2D, tex);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
    translucents.push_back(tex);

    glFlush();
    if (GLEW_ARB_framebuffer_object)
        glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, tex, 0);
    else
        glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, tex, 0);
    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
    glClear(GL_COLOR_BUFFER_BIT);
    glClearColor(1.0, 1.0, 1.0, 1.0);
}

void Canvas::Impl::endTranslucent(float alpha)
{
    glFlush();

    assert(!translucents.empty());
    GLuint tex = translucents.back();
    translucents.pop_back();

    GLuint next = translucents.empty() ? texture : translucents.back();
    if (GLEW_ARB_framebuffer_object)
        glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, next, 0);
    else
        glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, next, 0);

    glPushMatrix();
    glLoadIdentity();
    glTranslatef(x, y, 0.0f);
    alphaBlend(width, height, alpha, tex);
    glPopMatrix();

    glDeleteTextures(1, &tex);
}

void Canvas::Impl::render(int w, int h)
{
    if (texture == 0)
        return;

    glMatrixMode(GL_TEXTURE);
    glLoadIdentity();
    glScalef(1.0f / width, 1.0f / height, 0.0f);
    glMatrixMode(GL_MODELVIEW);

    glEnable(GL_TEXTURE_2D);
    glBindTexture(GL_TEXTURE_2D, texture);
    glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
    glBegin(GL_QUADS);
        glTexCoord2f(0, h);
        glVertex2f(0, 0);
        glTexCoord2f(w, h);
        glVertex2f(w, 0);
        glTexCoord2f(w, 0);
        glVertex2f(w, h);
        glTexCoord2f(0, 0);
        glVertex2f(0, h);
    glEnd();
    glDisable(GL_TEXTURE_2D);
    glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
}

void Canvas::Impl::alphaBlend(int w, int h, float alpha, GLuint tex)
{
    if (tex == 0)
        return;

    glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);

    glMatrixMode(GL_TEXTURE);
    glLoadIdentity();
    glScalef(1.0f / width, 1.0f / height, 0.0f);
    glMatrixMode(GL_MODELVIEW);

    glEnable(GL_TEXTURE_2D);
    glBindTexture(GL_TEXTURE_2D, tex);
    glColor4f(alpha, alpha, alpha, alpha);
    glBegin(GL_QUADS);
        glTexCoord2f(0, h);
        glVertex2f(0, 0);
        glTexCoord2f(w, h);
        glVertex2f(w, 0);
        glTexCoord2f(w, 0);
        glVertex2f(w, h);
        glTexCoord2f(0, 0);
        glVertex2f(0, h);
    glEnd();
    glDisable(GL_TEXTURE_2D);

    glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
}

Canvas::Canvas() :
    pimpl(new Impl())
{
}

Canvas::~Canvas()
{
}

void Canvas::setup(int width, int height)
{
    pimpl->setup(width, height);
}

void Canvas::shutdown()
{
    pimpl->shutdown();
}

void Canvas::beginRender(unsigned backgroundColor)
{
    pimpl->beginRender(backgroundColor);
}

void Canvas::endRender()
{
    pimpl->endRender();
}

void Canvas::beginTranslucent()
{
    pimpl->beginTranslucent();
}

void Canvas::endTranslucent(float alpha)
{
    pimpl->endTranslucent(alpha);
}

int Canvas::getWidth() const
{
    return pimpl->getWidth();
}

int Canvas::getHeight() const
{
    return pimpl->getHeight();
}

void Canvas::render(int width, int height)
{
    return pimpl->render(width, height);
}

void Canvas::alphaBlend(int width, int height, float alpha)
{
    return pimpl->alphaBlend(width, height, alpha, pimpl->getTexture());
}
<commit_msg>(Canvas::Impl::setup) : Fix a bug; cf. html4/absolute-replaced-height-014.htm<commit_after>/*
 * Copyright 2012, 2013 Esrille Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "CanvasGL.h"
#include <boost/concept_check.hpp>

#include <assert.h>

GLuint Canvas::Impl::currentFrameBuffer = 0;

void Canvas::Impl::setup(int w, int h)
{
    if (width != 0 || height != 0 || w <= 0 || h <= 0)
        return;

    width = w;
    height = h;

    // Setup texture
    glGenTextures(1, &texture);
    glBindTexture(GL_TEXTURE_2D, texture);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);

    if (GLEW_ARB_framebuffer_object) {
        // Setup renderBuffer
        glGenRenderbuffers(1, &renderBuffer);
        glBindRenderbuffer(GL_RENDERBUFFER, renderBuffer);
        glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_STENCIL, width, height);

        // Setup frameBuffer
        glGenFramebuffers(1, &frameBuffer);
        glBindFramebuffer(GL_FRAMEBUFFER, frameBuffer);
        glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture, 0);
        glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, renderBuffer);
        glBindFramebuffer(GL_FRAMEBUFFER, 0);
    } else {
        // Setup renderBuffer
        glGenRenderbuffersEXT(1, &renderBuffer);
        glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, renderBuffer);
        glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_DEPTH_STENCIL_EXT, width, height);

        // Setup frameBuffer
        glGenFramebuffersEXT(1, &frameBuffer);
        glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, frameBuffer);
        glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, texture, 0);
        glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, renderBuffer);
        glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, renderBuffer);
        glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
    }
}

void Canvas::Impl::shutdown()
{
    if (width == 0 && height == 0)
        return;

    if (GLEW_ARB_framebuffer_object) {
        glDeleteFramebuffers(1, &frameBuffer);
        glDeleteRenderbuffers(1, &renderBuffer);
    } else {
        glDeleteFramebuffersEXT(1, &frameBuffer);
        glDeleteRenderbuffersEXT(1, &renderBuffer);
    }
    if (texture) {
        glDeleteTextures(1, &texture);
        texture = 0;
    }
    while (!translucents.empty()) {
        GLuint tex = translucents.back();
        glDeleteTextures(1, &tex);
        translucents.pop_back();
    }
    frameBuffer = 0;
    renderBuffer = 0;
    width = height = 0;
}

void Canvas::Impl::beginRender(unsigned backgroundColor)
{
    GLint v[4];
    glGetIntegerv(GL_VIEWPORT, v);
    GLint viewportHeight = v[3];

    savedFrameBuffer = currentFrameBuffer;
    currentFrameBuffer = frameBuffer;
    if (GLEW_ARB_framebuffer_object)
        glBindFramebuffer(GL_FRAMEBUFFER, currentFrameBuffer);
    else
        glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, currentFrameBuffer);

    GLfloat m[16];
    glGetFloatv(GL_MODELVIEW_MATRIX, m);
    x = m[12];
    y = m[13];

    glMatrixMode(GL_PROJECTION);
    glPushMatrix();
    glTranslatef(-x, viewportHeight - (y + height), 0.0f);

    glMatrixMode(GL_MODELVIEW);
    glPushMatrix();

    glClearColor(((backgroundColor >> 16) & 255) / 255.0f,
                 ((backgroundColor >> 8) & 255) / 255.0f,
                 (backgroundColor & 255) / 255.0f,
                 ((backgroundColor >> 24) & 255) / 255.0f);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
}

void Canvas::Impl::endRender()
{
    glMatrixMode(GL_PROJECTION);
    glPopMatrix();

    glMatrixMode(GL_MODELVIEW);
    glPopMatrix();

    currentFrameBuffer = savedFrameBuffer;
    if (GLEW_ARB_framebuffer_object)
        glBindFramebuffer(GL_FRAMEBUFFER, currentFrameBuffer);
    else
        glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, currentFrameBuffer);
}

void Canvas::Impl::beginTranslucent()
{
    GLuint tex;
    glGenTextures(1, &tex);
    glBindTexture(GL_TEXTURE_2D, tex);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
    translucents.push_back(tex);

    glFlush();
    if (GLEW_ARB_framebuffer_object)
        glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, tex, 0);
    else
        glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, tex, 0);
    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
    glClear(GL_COLOR_BUFFER_BIT);
    glClearColor(1.0, 1.0, 1.0, 1.0);
}

void Canvas::Impl::endTranslucent(float alpha)
{
    glFlush();

    assert(!translucents.empty());
    GLuint tex = translucents.back();
    translucents.pop_back();

    GLuint next = translucents.empty() ? texture : translucents.back();
    if (GLEW_ARB_framebuffer_object)
        glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, next, 0);
    else
        glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, next, 0);

    glPushMatrix();
    glLoadIdentity();
    glTranslatef(x, y, 0.0f);
    alphaBlend(width, height, alpha, tex);
    glPopMatrix();

    glDeleteTextures(1, &tex);
}

void Canvas::Impl::render(int w, int h)
{
    if (texture == 0)
        return;

    glMatrixMode(GL_TEXTURE);
    glLoadIdentity();
    glScalef(1.0f / width, 1.0f / height, 0.0f);
    glMatrixMode(GL_MODELVIEW);

    glEnable(GL_TEXTURE_2D);
    glBindTexture(GL_TEXTURE_2D, texture);
    glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
    glBegin(GL_QUADS);
        glTexCoord2f(0, h);
        glVertex2f(0, 0);
        glTexCoord2f(w, h);
        glVertex2f(w, 0);
        glTexCoord2f(w, 0);
        glVertex2f(w, h);
        glTexCoord2f(0, 0);
        glVertex2f(0, h);
    glEnd();
    glDisable(GL_TEXTURE_2D);
    glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
}

void Canvas::Impl::alphaBlend(int w, int h, float alpha, GLuint tex)
{
    if (tex == 0)
        return;

    glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);

    glMatrixMode(GL_TEXTURE);
    glLoadIdentity();
    glScalef(1.0f / width, 1.0f / height, 0.0f);
    glMatrixMode(GL_MODELVIEW);

    glEnable(GL_TEXTURE_2D);
    glBindTexture(GL_TEXTURE_2D, tex);
    glColor4f(alpha, alpha, alpha, alpha);
    glBegin(GL_QUADS);
        glTexCoord2f(0, h);
        glVertex2f(0, 0);
        glTexCoord2f(w, h);
        glVertex2f(w, 0);
        glTexCoord2f(w, 0);
        glVertex2f(w, h);
        glTexCoord2f(0, 0);
        glVertex2f(0, h);
    glEnd();
    glDisable(GL_TEXTURE_2D);

    glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
}

Canvas::Canvas() :
    pimpl(new Impl())
{
}

Canvas::~Canvas()
{
}

void Canvas::setup(int width, int height)
{
    pimpl->setup(width, height);
}

void Canvas::shutdown()
{
    pimpl->shutdown();
}

void Canvas::beginRender(unsigned backgroundColor)
{
    pimpl->beginRender(backgroundColor);
}

void Canvas::endRender()
{
    pimpl->endRender();
}

void Canvas::beginTranslucent()
{
    pimpl->beginTranslucent();
}

void Canvas::endTranslucent(float alpha)
{
    pimpl->endTranslucent(alpha);
}

int Canvas::getWidth() const
{
    return pimpl->getWidth();
}

int Canvas::getHeight() const
{
    return pimpl->getHeight();
}

void Canvas::render(int width, int height)
{
    return pimpl->render(width, height);
}

void Canvas::alphaBlend(int width, int height, float alpha)
{
    return pimpl->alphaBlend(width, height, alpha, pimpl->getTexture());
}
<|endoftext|>


<commit_before>//
// Created by boltz_j on 06/08/14.
// Copyright (c) 2014 bLabs. All rights reserved.
//

#include "CardDeck.h"
#include <deque>

CardDeck::CardDeck(int size_of_deck)
{
    // Two decks to compute the lookup table
    std::deque<int>* deck;
    std::deque<int>* table_deck;

    // Save the number of cards in the deck
    this->size_of_deck = size_of_deck;

    // Init the main deck
    deck = new std::deque<int>();
    for (int i = 0; i < size_of_deck; i++)
    {
        deck->push_front(i);
    }

    // Compute the Lookup Table as a table deck
    table_deck = new std::deque<int>();
    while (!deck->empty())
    {
        // Step 1 : Take the top card off the deck and set it on the table
        table_deck->push_back(deck->front());
        deck->pop_front();

        // Step 2 : Take the next card off the top of desk and put it on
        // the bottom of the deck in your hand.
        if (!deck->empty())
        {
            deck->push_back(deck->front());
            deck->pop_front();
        }
    }

    // Store the position of the card after one round as the lookup table
    this->shuffle_table = new int [size_of_deck];
    for (int i = 0; i < size_of_deck; ++i)
    {
        this->shuffle_table[i] = table_deck->front();
        table_deck->pop_front();
    }
}

CardDeck::~CardDeck()
{
    delete this->shuffle_table;
}

int CardDeck::compute()
{
    int result = 0;
    int** decks;

    // Using two decks alternatively
    decks = new int* [2];
    decks[0] = new int [this->size_of_deck];
    decks[1] = new int [this->size_of_deck];

    // Init the first deck
    for (int i = 0; i < this->size_of_deck; ++i)
    {
        decks[0][i] = i;
    }

    while (42)
    {
        // Select decks
        int* deck = decks[result % 2];
        int* new_deck = decks[(result + 1) % 2];

        // Shuffle the cards using the LUT
        for (int i = 0; i < this->size_of_deck; ++i)
        {
            new_deck[i] = deck[this->shuffle_table[i]];
        }

        // Increment the number of round
        ++result;

        // Stop if the deck is ordered
        if (this->is_over(new_deck))
            break;
    }

    // release decks
    delete (decks[0]);
    delete (decks[1]);
    delete (decks);

    // Return the number of rounds
    return result;
}

bool CardDeck::is_over(int* deck)
{
    // If one of the cards if not ordered return false
    for (int i = 0; i < this->size_of_deck; ++i)
        if (deck[i] != i)
            return false;

    // Else the game is over :)
    return true;
}<commit_msg>Use uint64_t for the number of rounds<commit_after>//
// Created by boltz_j on 06/08/14.
// Copyright (c) 2014 bLabs. All rights reserved.
//

#include "CardDeck.h"
#include <deque>

CardDeck::CardDeck(int size_of_deck)
{
    // Two decks to compute the lookup table
    std::deque<int>* deck;
    std::deque<int>* table_deck;

    // Save the number of cards in the deck
    this->size_of_deck = size_of_deck;

    // Init the main deck
    deck = new std::deque<int>();
    for (int i = 0; i < size_of_deck; i++)
        deck->push_front(i);

    // Compute the Lookup Table as a table deck
    table_deck = new std::deque<int>();
    while (!deck->empty())
    {
        // Step 1 : Take the top card off the deck and set it on the table
        table_deck->push_back(deck->front());
        deck->pop_front();

        // Step 2 : Take the next card off the top of desk and put it on
        // the bottom of the deck in your hand.
        if (!deck->empty())
        {
            deck->push_back(deck->front());
            deck->pop_front();
        }
    }

    // Store the position of the card after one round as the lookup table
    this->shuffle_table = new int [size_of_deck];
    for (int i = 0; i < size_of_deck; ++i)
    {
        this->shuffle_table[i] = table_deck->front();
        table_deck->pop_front();
    }
}

CardDeck::~CardDeck()
{
    delete this->shuffle_table;
}

int CardDeck::compute()
{
    uint64_t result = 0;
    int** decks;

    // Using two decks alternatively
    decks    = new int* [2];
    decks[0] = new int[this->size_of_deck];
    decks[1] = new int[this->size_of_deck];

    // Init the first deck
    for (int i = 0; i < this->size_of_deck; ++i)
        decks[0][i] = i;

    while (42)
    {
        // Select decks
        int* deck = decks[result % 2];
        int* new_deck = decks[(result + 1) % 2];

        // Shuffle the cards using the LUT
        for (int i = 0; i < this->size_of_deck; ++i)
            new_deck[i] = deck[this->shuffle_table[i]];

        // Increment the number of round
        ++result;

        // Stop if the deck is ordered
        if (this->is_over(new_deck))
            break;
    }

    // release decks
    delete (decks[0]);
    delete (decks[1]);
    delete (decks);

    // Return the number of rounds
    return result;
}

bool CardDeck::is_over(int* deck)
{
    // If one of the cards if not ordered return false
    for (int i = 0; i < this->size_of_deck; ++i)
        if (deck[i] != i)
            return false;

    // Else the game is over :)
    return true;
}<|endoftext|>


<commit_before>/*
 * serial.cpp
 *
 *  Created on: June 10, 2013
 *      Author: Ryler Hockenbury
 *
 * Create and send a serial frame of data over
 * USB or 3DR radio.
 *
 */

#include "serial.h"

unsigned int serialCounter = 1;

void serialOpen()
{
  Serial.print(millis());
  serialCounter++;

  #ifdef SERIAL_CHART
    Serial.print(",");
  #endif

  #ifdef SERIAL_MONITOR
    Serial.print("\t\t");
  #endif
}

void serialPrint(float value)
{
  serialPrint(&value, 1);

}

void serialPrint(float values[], int numValues)
{
  //Format for processing or serial chart (comma delimited)
  #ifdef SERIAL_CHART
  for(uint8_t count = 0; count < numValues; count++)
  {
    Serial.print(values[count]);
    if(count < numValues) Serial.print(",");
  }

  #endif

  //Format for serial monitor (tab delimited)
  #ifdef SERIAL_MONITOR
  for(uint8_t count = 0; count < numValues; count++)
  {
    if(values[count] >= 0) Serial.print(" ");
    Serial.print(values[count]);
    if(count < numValues-1) Serial.print("\t\t");
  }

  #endif

}

void serialClose()
{
  // newline character indicates frame is closed
  Serial.print("\n");
}
<commit_msg>added status to serial stream<commit_after>/*
 * serial.cpp
 *
 *  Created on: June 10, 2013
 *      Author: Ryler Hockenbury
 *
 * Create and send a serial frame of data over
 * USB or 3DR radio.
 *
 */

#include "serial.h"
#include "../Quad_Defines/globals.h"

unsigned int serialCounter = 1;

void serialOpen()
{
  Serial.print(millis());
  serialCounter++;

  #ifdef SERIAL_CHART
    Serial.print(",");
  #endif

  #ifdef SERIAL_MONITOR
    Serial.print("\t\t");
  #endif

  Serial.print(vehicleStatus, BIN);

#ifdef SERIAL_CHART
    Serial.print(",");
  #endif

  #ifdef SERIAL_MONITOR
    Serial.print("\t\t");
  #endif
}

void serialPrint(float value)
{
  serialPrint(&value, 1);

}

void serialPrint(float values[], int numValues)
{
  //Format for processing or serial chart (comma delimited)
  #ifdef SERIAL_CHART
  for(uint8_t count = 0; count < numValues; count++)
  {
    Serial.print(values[count]);
    if(count < numValues) Serial.print(",");
  }

  #endif

  //Format for serial monitor (tab delimited)
  #ifdef SERIAL_MONITOR
  for(uint8_t count = 0; count < numValues; count++)
  {
    if(values[count] >= 0) Serial.print(" ");
    Serial.print(values[count]);
    if(count < numValues-1) Serial.print("\t\t");
  }

  #endif

}

void serialClose()
{
  // newline character indicates frame is closed
  Serial.print("\n");
}
<|endoftext|>


<commit_before>#include "RBDyn/Coriolis.h"

namespace rbd
{
Eigen::MatrixXd expand(const rbd::Jacobian& jac,
			const rbd::MultiBody& mb,
			const Eigen::MatrixXd& jacMat)
{
	Eigen::MatrixXd res = Eigen::MatrixXd::Zero(mb.nrDof(), mb.nrDof());
	int rowJac = 0;
	int colJac = 0;
	for(int i : jac.jointsPath())
	{
		colJac = 0;
		for(int j : jac.jointsPath())
		{
			res.block(mb.jointPosInDof(i), mb.jointPosInDof(j), mb.joint(i).dof(), mb.joint(j).dof())
				= jacMat.block(rowJac, colJac, mb.joint(i).dof(), mb.joint(j).dof());
			colJac += mb.joint(j).dof();
		}
		rowJac += mb.joint(i).dof();
	}
	return res;
}

void expandAdd(const rbd::Jacobian& jac,
			const rbd::MultiBody& mb,
			const Eigen::MatrixXd& jacMat,
			Eigen::MatrixXd& res)
{
	int rowJac = 0;
	int colJac = 0;
	for(int i : jac.jointsPath())
	{
		colJac = 0;
		for(int j : jac.jointsPath())
		{
			res.block(mb.jointPosInDof(i), mb.jointPosInDof(j), mb.joint(i).dof(), mb.joint(j).dof())
				+= jacMat.block(rowJac, colJac, mb.joint(i).dof(), mb.joint(j).dof());
			colJac += mb.joint(j).dof();
		}
		rowJac += mb.joint(i).dof();
	}
}

std::vector<std::array<int, 3>> compactPath(const rbd::Jacobian& jac,
						const rbd::MultiBody& mb)
{
	std::vector<std::array<int, 3>> res;
        std::array<int, 3> block;

	int start_block = mb.jointPosInDof(jac.jointsPath()[0]);
	int len_block = mb.joint(jac.jointsPath()[0]).dof();

	int start;
	int startJac = 0;

	for(int i : jac.jointsPath())
	{
		if(i == jac.jointsPath()[0])
		{
			continue;
		}

		start = mb.jointPosInDof(i);

		if(start != start_block + len_block)
		{
			res.push_back({{start_block, startJac, len_block}});
			start_block = start;
			startJac += len_block;
			len_block = 0;
		}
		len_block += mb.joint(i).dof();
	}
	res.push_back({{start_block, startJac, len_block}});
	return res;
}

void compactExpandAdd(const std::vector<std::array<int, 3>>& compactPath,
			const Eigen::MatrixXd& jacMat,
			Eigen::MatrixXd& res)
{
	for(const auto& b1 : compactPath)
	{
		for(const auto& b2 : compactPath)
		{
			res.block(b1[0], b2[0], b1[2], b2[2])
				+= jacMat.block(b1[1], b2[1], b1[2], b2[2]);
		}
	}
}

Coriolis::Coriolis(const rbd::MultiBody& mb)
{
	Eigen::Vector3d com;
	double mass;
	for(int i = 0; i < mb.nrBodies(); ++i)
	{
		mass = mb.body(i).inertia().mass();
		if(mass > 0)
		{
			com = mb.body(i).inertia().momentum()/mass;
		}
		else
		{
			com.setZero();
		}
		jacs_.push_back(rbd::Jacobian(mb, mb.body(i).name(), com));
		jacMats_.push_back(Eigen::MatrixXd(6, jacs_[i].dof()));
		jacDotMats_.push_back(Eigen::MatrixXd(6, jacs_[i].dof()));
		compactPaths_.push_back(compactPath(jacs_[i], mb));
	}
}

Eigen::MatrixXd Coriolis::coriolis(const rbd::MultiBody& mb, const rbd::MultiBodyConfig& mbc)
{
	Eigen::MatrixXd coriolis = Eigen::MatrixXd::Zero(mb.nrDof(), mb.nrDof());

	Eigen::Matrix3d rot;
	Eigen::Matrix3d rDot;

	Eigen::Matrix3d inertia;

	for(int i = 0; i < mb.nrBodies(); ++i)
	{
		jacMats_[i] = jacs_[i].jacobian(mb, mbc);

		jacDotMats_[i] = jacs_[i].jacobianDot(mb, mbc);

		rot = mbc.bodyPosW[i].rotation().transpose();
		rDot.noalias() = sva::vector3ToCrossMatrix(mbc.bodyVelW[i].angular())*rot;

		auto jvi = jacMats_[i].bottomRows<3>();
		auto jDvi = jacDotMats_[i].bottomRows<3>();

		auto jwi = jacMats_[i].topRows<3>();
		auto jDwi = jacDotMats_[i].topRows<3>();

		double mass = mb.body(i).inertia().mass();
		inertia = mb.body(i).inertia().inertia()
			- sva::vector3ToCrossMatrix<double>(mass*jacs_[i].point())*sva::vector3ToCrossMatrix(jacs_[i].point()).transpose();

		Eigen::Matrix3d ir = inertia*rot.transpose();

		/* C = \sum m_i J_{v_i}^T \dot{J}_{v_i}
		 *        + J_{w_i}^T R_i I_i R_i^T \dot{J}_{w_i}
		 *        + J_{w_i}^T \dot{R}_i I_i R_i^T J_{w_i} */

		Eigen::MatrixXd res = mass*jvi.transpose()*jDvi
				+ jwi.transpose()*((rot*ir)*jDwi
				+  (rDot*ir)*jwi);

		compactExpandAdd(compactPaths_[i], res, coriolis);
	}

	return coriolis;
}

} //ns rbd
<commit_msg>Remove unused variable<commit_after>#include "RBDyn/Coriolis.h"

namespace rbd
{
Eigen::MatrixXd expand(const rbd::Jacobian& jac,
			const rbd::MultiBody& mb,
			const Eigen::MatrixXd& jacMat)
{
	Eigen::MatrixXd res = Eigen::MatrixXd::Zero(mb.nrDof(), mb.nrDof());
	int rowJac = 0;
	int colJac = 0;
	for(int i : jac.jointsPath())
	{
		colJac = 0;
		for(int j : jac.jointsPath())
		{
			res.block(mb.jointPosInDof(i), mb.jointPosInDof(j), mb.joint(i).dof(), mb.joint(j).dof())
				= jacMat.block(rowJac, colJac, mb.joint(i).dof(), mb.joint(j).dof());
			colJac += mb.joint(j).dof();
		}
		rowJac += mb.joint(i).dof();
	}
	return res;
}

void expandAdd(const rbd::Jacobian& jac,
			const rbd::MultiBody& mb,
			const Eigen::MatrixXd& jacMat,
			Eigen::MatrixXd& res)
{
	int rowJac = 0;
	int colJac = 0;
	for(int i : jac.jointsPath())
	{
		colJac = 0;
		for(int j : jac.jointsPath())
		{
			res.block(mb.jointPosInDof(i), mb.jointPosInDof(j), mb.joint(i).dof(), mb.joint(j).dof())
				+= jacMat.block(rowJac, colJac, mb.joint(i).dof(), mb.joint(j).dof());
			colJac += mb.joint(j).dof();
		}
		rowJac += mb.joint(i).dof();
	}
}

std::vector<std::array<int, 3>> compactPath(const rbd::Jacobian& jac,
						const rbd::MultiBody& mb)
{
	std::vector<std::array<int, 3>> res;

	int start_block = mb.jointPosInDof(jac.jointsPath()[0]);
	int len_block = mb.joint(jac.jointsPath()[0]).dof();

	int start;
	int startJac = 0;

	for(int i : jac.jointsPath())
	{
		if(i == jac.jointsPath()[0])
		{
			continue;
		}

		start = mb.jointPosInDof(i);

		if(start != start_block + len_block)
		{
			res.push_back({{start_block, startJac, len_block}});
			start_block = start;
			startJac += len_block;
			len_block = 0;
		}
		len_block += mb.joint(i).dof();
	}
	res.push_back({{start_block, startJac, len_block}});
	return res;
}

void compactExpandAdd(const std::vector<std::array<int, 3>>& compactPath,
			const Eigen::MatrixXd& jacMat,
			Eigen::MatrixXd& res)
{
	for(const auto& b1 : compactPath)
	{
		for(const auto& b2 : compactPath)
		{
			res.block(b1[0], b2[0], b1[2], b2[2])
				+= jacMat.block(b1[1], b2[1], b1[2], b2[2]);
		}
	}
}

Coriolis::Coriolis(const rbd::MultiBody& mb)
{
	Eigen::Vector3d com;
	double mass;
	for(int i = 0; i < mb.nrBodies(); ++i)
	{
		mass = mb.body(i).inertia().mass();
		if(mass > 0)
		{
			com = mb.body(i).inertia().momentum()/mass;
		}
		else
		{
			com.setZero();
		}
		jacs_.push_back(rbd::Jacobian(mb, mb.body(i).name(), com));
		jacMats_.push_back(Eigen::MatrixXd(6, jacs_[i].dof()));
		jacDotMats_.push_back(Eigen::MatrixXd(6, jacs_[i].dof()));
		compactPaths_.push_back(compactPath(jacs_[i], mb));
	}
}

Eigen::MatrixXd Coriolis::coriolis(const rbd::MultiBody& mb, const rbd::MultiBodyConfig& mbc)
{
	Eigen::MatrixXd coriolis = Eigen::MatrixXd::Zero(mb.nrDof(), mb.nrDof());

	Eigen::Matrix3d rot;
	Eigen::Matrix3d rDot;

	Eigen::Matrix3d inertia;

	for(int i = 0; i < mb.nrBodies(); ++i)
	{
		jacMats_[i] = jacs_[i].jacobian(mb, mbc);

		jacDotMats_[i] = jacs_[i].jacobianDot(mb, mbc);

		rot = mbc.bodyPosW[i].rotation().transpose();
		rDot.noalias() = sva::vector3ToCrossMatrix(mbc.bodyVelW[i].angular())*rot;

		auto jvi = jacMats_[i].bottomRows<3>();
		auto jDvi = jacDotMats_[i].bottomRows<3>();

		auto jwi = jacMats_[i].topRows<3>();
		auto jDwi = jacDotMats_[i].topRows<3>();

		double mass = mb.body(i).inertia().mass();
		inertia = mb.body(i).inertia().inertia()
			- sva::vector3ToCrossMatrix<double>(mass*jacs_[i].point())*sva::vector3ToCrossMatrix(jacs_[i].point()).transpose();

		Eigen::Matrix3d ir = inertia*rot.transpose();

		/* C = \sum m_i J_{v_i}^T \dot{J}_{v_i}
		 *        + J_{w_i}^T R_i I_i R_i^T \dot{J}_{w_i}
		 *        + J_{w_i}^T \dot{R}_i I_i R_i^T J_{w_i} */

		Eigen::MatrixXd res = mass*jvi.transpose()*jDvi
				+ jwi.transpose()*((rot*ir)*jDwi
				+  (rDot*ir)*jwi);

		compactExpandAdd(compactPaths_[i], res, coriolis);
	}

	return coriolis;
}

} //ns rbd
<|endoftext|>


<commit_before>
struct aho_corasick_slow {

    vector<string> keywords;

    aho_corasick_slow(vector<string> keywords) : keywords(keywords) {
    }

    vector<string> search(string s) {
        vector<string> res;
        for (int i = 0; i < size(s); i++) {
            for (int j = 0; j < size(keywords); j++) {
                string kw = keywords[j];
                if (i + size(kw) - 1 >= size(s))
                    continue;

                bool ok = true;
                for (int k = 0; ok && k < size(kw); k++) {
                    ok = s[i + k] == kw[k];
                }

                if (ok)
                    res.push_back(kw);
            }
        }

        return res;
    }
};

string random_string(int n, int cc) {
    stringstream ss;
    for (int i = 0; i < n; i++) {
        ss << static_cast<char>(rand() % cc + 'a');
    }

    return ss.str();
}

void test() {
    int ts = 100,
        ts2 = 10;

    for (int t = 0; t < ts; t++) {
        int n = rand() % 1000;

        vector<string> kws;
        for (int i = 0; i < n; i++) {
            kws.push_back(random_string(rand() % 10 + 1, rand() % 5 + 1));
        }

        aho_corasick ac(kws);
        aho_corasick_slow ac2(kws);

        for (int p = 0; p < ts2; p++) {
            string s = random_string(rand() % 100, rand() % 5 + 1);
            vector<string> res = ac.search(s);
            vector<string> res2 = ac2.search(s);
            sort(res.begin(), res.end());
            sort(res2.begin(), res2.end());

            assert_equal(size(res2), size(res));

            for (int i = 0; i < size(res); i++) {
                assert_equal(res2[i], res[i]);
            }
        }
    }
}
<commit_msg>Added field testing for Aho-Corasick algorithm.<commit_after>
struct aho_corasick_slow {

    vector<string> keywords;

    aho_corasick_slow(vector<string> keywords) : keywords(keywords) {
    }

    vector<string> search(string s) {
        vector<string> res;
        for (int i = 0; i < size(s); i++) {
            for (int j = 0; j < size(keywords); j++) {
                string kw = keywords[j];
                if (i + size(kw) - 1 >= size(s))
                    continue;

                bool ok = true;
                for (int k = 0; ok && k < size(kw); k++) {
                    ok = s[i + k] == kw[k];
                }

                if (ok)
                    res.push_back(kw);
            }
        }

        return res;
    }
};

string random_string(int n, int cc) {
    stringstream ss;
    for (int i = 0; i < n; i++) {
        ss << static_cast<char>(rand() % cc + 'a');
    }

    return ss.str();
}

void test() {
    /* Field testing: Kattis stringmultimatching */

    int ts = 100,
        ts2 = 10;

    for (int t = 0; t < ts; t++) {
        int n = rand() % 1000;

        vector<string> kws;
        for (int i = 0; i < n; i++) {
            kws.push_back(random_string(rand() % 10 + 1, rand() % 5 + 1));
        }

        aho_corasick ac(kws);
        aho_corasick_slow ac2(kws);

        for (int p = 0; p < ts2; p++) {
            string s = random_string(rand() % 100, rand() % 5 + 1);
            vector<string> res = ac.search(s);
            vector<string> res2 = ac2.search(s);
            sort(res.begin(), res.end());
            sort(res2.begin(), res2.end());

            assert_equal(size(res2), size(res));

            for (int i = 0; i < size(res); i++) {
                assert_equal(res2[i], res[i]);
            }
        }
    }
}
<|endoftext|>