<commit_before>#include "mitkPAIOUtil.h"

#include "mitkIOUtil.h"
#include "mitkImageReadAccessor.h"

#include <string>
#include <sstream>
#include <vector>

#include "mitkPAComposedVolume.h"
#include "mitkPASlicedVolumeGenerator.h"
#include "mitkPANoiseGenerator.h"
#include "mitkPAVolumeManipulator.h"
#include <mitkProperties.h>
#include <itkDirectory.h>
#include <itksys/SystemTools.hxx>

static std::vector<int> splitString(const std::string &s, const char* delim) {
  std::vector<int> elems;
  std::stringstream ss(s);
  std::string item;
  while (std::getline(ss, item, *delim))
  {
    int numb;
    std::stringstream(item) >> numb;
    elems.push_back(numb);
  }
  return elems;
}

bool mitk::pa::IOUtil::DoesFileHaveEnding(std::string const &fullString, std::string const &ending) {
  if (fullString.length() == 0 || ending.length() == 0 || fullString.length() < ending.length())
    return false;

  return (0 == fullString.compare(fullString.length() - ending.length(), ending.length(), ending));
}

mitk::pa::IOUtil::IOUtil() {}

mitk::pa::IOUtil::~IOUtil() {}

mitk::pa::Volume::Pointer mitk::pa::IOUtil::LoadNrrd(std::string filename, double blur)
{
  if (filename.empty() || filename == "")
    return nullptr;

  mitk::Image::Pointer inputImage = mitk::IOUtil::LoadImage(filename);

  if (inputImage.IsNull())
    return nullptr;

  auto returnImage = Volume::New(inputImage);

  VolumeManipulator::GaussianBlur3D(returnImage, blur);

  return returnImage;
}

std::map<mitk::pa::IOUtil::Position, mitk::pa::Volume::Pointer>
mitk::pa::IOUtil::LoadFluenceContributionMaps(std::string foldername, double blur, int* progress, bool doLog10)
{
  std::map<IOUtil::Position, Volume::Pointer> resultMap;

  itk::Directory::Pointer directoryHandler = itk::Directory::New();
  directoryHandler->Load(foldername.c_str());
  for (unsigned int fileIndex = 0, numFiles = directoryHandler->GetNumberOfFiles(); fileIndex < numFiles; ++fileIndex)
  {
    std::string filename = std::string(directoryHandler->GetFile(fileIndex));
    if (itksys::SystemTools::FileIsDirectory(filename))
      continue;

    if (!DoesFileHaveEnding(filename, ".nrrd"))
      continue;

    size_t s = filename.find("_p");
    size_t e = filename.find("Fluence", s);
    std::string sub = filename.substr(s + 2, e - s - 2);
    std::vector<int> coords = splitString(sub, ",");

    if (coords.size() != 3)
    {
      MITK_ERROR << "Some of the data to read was corrupted or did not match the " <<
        "naming pattern *_pN,N,NFluence*.nrrd";
      mitkThrow() << "Some of the data to read was corrupted or did not match the" <<
        " naming pattern *_pN,N,NFluence*.nrrd";
    }
    else
    {
      MITK_DEBUG << "Extracted coords: " << coords[0] << "|" << coords[1] << "|" << coords[2] << " from string " << sub;
      Volume::Pointer nrrdFile = LoadNrrd(foldername + filename, blur);
      if (doLog10)
        VolumeManipulator::Log10Image(nrrdFile);
      resultMap[Position{ coords[0], coords[2] }] = nrrdFile;
      *progress = *progress + 1;
    }
  }

  return resultMap;
}

int mitk::pa::IOUtil::GetNumberOfNrrdFilesInDirectory(std::string directory)
{
  return GetListOfAllNrrdFilesInDirectory(directory).size();
}

std::vector<std::string> mitk::pa::IOUtil::GetListOfAllNrrdFilesInDirectory(std::string directory, bool keepFileFormat)
{
  std::vector<std::string> filenames;
  itk::Directory::Pointer directoryHandler = itk::Directory::New();
  directoryHandler->Load(directory.c_str());
  for (unsigned int fileIndex = 0, numFiles = directoryHandler->GetNumberOfFiles(); fileIndex < numFiles; ++fileIndex)
  {
    std::string filename = std::string(directoryHandler->GetFile(fileIndex));
    if (itksys::SystemTools::FileIsDirectory(filename))
      continue;

    if (!DoesFileHaveEnding(filename, ".nrrd"))
      continue;

    if (keepFileFormat)
    {
      filenames.push_back(filename);
    }
    else
    {
      filenames.push_back(filename.substr(0, filename.size() - 5));
    }
  }

  return filenames;
}

std::vector<std::string> mitk::pa::IOUtil::GetAllChildfoldersFromFolder(std::string folderPath)
{
  std::vector<std::string> returnVector;

  itksys::Directory directoryHandler;
  directoryHandler.Load(folderPath.c_str());
  for (unsigned int fileIndex = 0, numFiles = directoryHandler.GetNumberOfFiles(); fileIndex < numFiles; ++fileIndex)
  {
    std::string foldername = std::string(directoryHandler.GetFile(fileIndex));
    std::string filename = folderPath + "/" + foldername;
    if (itksys::SystemTools::FileIsDirectory(filename))
    {
      if (foldername != std::string(".") && foldername != std::string(".."))
      {
        MITK_INFO << filename;
        returnVector.push_back(filename);
      }
      continue;
    }

    //If there is a nrrd file in the directory we assume that a bottom level directory was chosen.
    if (DoesFileHaveEnding(filename, ".nrrd"))
    {
      returnVector.clear();
      returnVector.push_back(folderPath);
      return returnVector;
    }
  }

  return returnVector;
}

mitk::pa::InSilicoTissueVolume::Pointer mitk::pa::IOUtil::LoadInSilicoTissueVolumeFromNrrdFile(std::string nrrdFile)
{
  MITK_INFO << "Initializing ComposedVolume by nrrd...";
  auto inputImage = mitk::IOUtil::Load<mitk::Image>(nrrdFile);

  auto tissueParameters = TissueGeneratorParameters::New();

  unsigned int xDim = inputImage->GetDimensions()[1];
  unsigned int yDim = inputImage->GetDimensions()[0];
  unsigned int zDim = inputImage->GetDimensions()[2];
  tissueParameters->SetXDim(xDim);
  tissueParameters->SetYDim(yDim);
  tissueParameters->SetZDim(zDim);

  double xSpacing = inputImage->GetGeometry(0)->GetSpacing()[1];
  double ySpacing = inputImage->GetGeometry(0)->GetSpacing()[0];
  double zSpacing = inputImage->GetGeometry(0)->GetSpacing()[2];

  if ((xSpacing - ySpacing) > mitk::eps || (xSpacing - zSpacing) > mitk::eps || (ySpacing - zSpacing) > mitk::eps)
  {
    throw mitk::Exception("Cannot handle unequal spacing.");
  }

  tissueParameters->SetVoxelSpacingInCentimeters(xSpacing);

  mitk::PropertyList::Pointer propertyList = inputImage->GetPropertyList();

  mitk::ImageReadAccessor readAccess0(inputImage, inputImage->GetVolumeData(0));
  auto* m_AbsorptionArray = new double[xDim*yDim*zDim];
  memcpy(m_AbsorptionArray, readAccess0.GetData(), xDim*yDim*zDim * sizeof(double));
  auto absorptionVolume = Volume::New(m_AbsorptionArray, xDim, yDim, zDim, xSpacing);

  mitk::ImageReadAccessor readAccess1(inputImage, inputImage->GetVolumeData(1));
  auto*  m_ScatteringArray = new double[xDim*yDim*zDim];
  memcpy(m_ScatteringArray, readAccess1.GetData(), xDim*yDim*zDim * sizeof(double));
  auto scatteringVolume = Volume::New(m_ScatteringArray, xDim, yDim, zDim, xSpacing);

  mitk::ImageReadAccessor readAccess2(inputImage, inputImage->GetVolumeData(2));
  auto*  m_AnisotropyArray = new double[xDim*yDim*zDim];
  memcpy(m_AnisotropyArray, readAccess2.GetData(), xDim*yDim*zDim * sizeof(double));
  auto anisotropyVolume = Volume::New(m_AnisotropyArray, xDim, yDim, zDim, xSpacing);

  Volume::Pointer segmentationVolume;

  if (inputImage->GetDimension() == 4)
  {
    mitk::ImageReadAccessor readAccess3(inputImage, inputImage->GetVolumeData(3));
    auto*  m_SegmentationArray = new double[xDim*yDim*zDim];
    memcpy(m_SegmentationArray, readAccess3.GetData(), xDim*yDim*zDim * sizeof(double));
    segmentationVolume = Volume::New(m_SegmentationArray, xDim, yDim, zDim, xSpacing);
  }

  return mitk::pa::InSilicoTissueVolume::New(absorptionVolume, scatteringVolume,
    anisotropyVolume, segmentationVolume, tissueParameters, propertyList);
}

mitk::pa::FluenceYOffsetPair::Pointer mitk::pa::IOUtil::LoadFluenceSimulation(std::string fluenceSimulation)
{
  MITK_INFO << "Adding slice...";

  mitk::Image::Pointer inputImage = mitk::IOUtil::LoadImage(fluenceSimulation);

  auto yOffsetProperty = inputImage->GetProperty("y-offset");

  if (yOffsetProperty.IsNull())
    mitkThrow() << "No \"y-offset\" property found in fluence file!";

  std::string yOff = yOffsetProperty->GetValueAsString();
  MITK_INFO << "Reading y Offset: " << yOff;
#ifdef __linux__
  std::replace(yOff.begin(), yOff.end(), '.', ',');
#endif // __linux__
  double yOffset = std::stod(yOff);
  MITK_INFO << "Converted offset " << yOffset;
  return FluenceYOffsetPair::New(Volume::New(inputImage), yOffset);
}
<commit_msg>fix mitkIOUtil call<commit_after>#include "mitkPAIOUtil.h"

#include "mitkIOUtil.h"
#include "mitkImageReadAccessor.h"

#include <string>
#include <sstream>
#include <vector>

#include "mitkPAComposedVolume.h"
#include "mitkPASlicedVolumeGenerator.h"
#include "mitkPANoiseGenerator.h"
#include "mitkPAVolumeManipulator.h"
#include <mitkProperties.h>
#include <itkDirectory.h>
#include <itksys/SystemTools.hxx>

static std::vector<int> splitString(const std::string &s, const char* delim) {
  std::vector<int> elems;
  std::stringstream ss(s);
  std::string item;
  while (std::getline(ss, item, *delim))
  {
    int numb;
    std::stringstream(item) >> numb;
    elems.push_back(numb);
  }
  return elems;
}

bool mitk::pa::IOUtil::DoesFileHaveEnding(std::string const &fullString, std::string const &ending) {
  if (fullString.length() == 0 || ending.length() == 0 || fullString.length() < ending.length())
    return false;

  return (0 == fullString.compare(fullString.length() - ending.length(), ending.length(), ending));
}

mitk::pa::IOUtil::IOUtil() {}

mitk::pa::IOUtil::~IOUtil() {}

mitk::pa::Volume::Pointer mitk::pa::IOUtil::LoadNrrd(std::string filename, double blur)
{
  if (filename.empty() || filename == "")
    return nullptr;

  mitk::Image::Pointer inputImage = mitk::IOUtil::Load<mitk::Image>(filename);

  if (inputImage.IsNull())
    return nullptr;

  auto returnImage = Volume::New(inputImage);

  VolumeManipulator::GaussianBlur3D(returnImage, blur);

  return returnImage;
}

std::map<mitk::pa::IOUtil::Position, mitk::pa::Volume::Pointer>
mitk::pa::IOUtil::LoadFluenceContributionMaps(std::string foldername, double blur, int* progress, bool doLog10)
{
  std::map<IOUtil::Position, Volume::Pointer> resultMap;

  itk::Directory::Pointer directoryHandler = itk::Directory::New();
  directoryHandler->Load(foldername.c_str());
  for (unsigned int fileIndex = 0, numFiles = directoryHandler->GetNumberOfFiles(); fileIndex < numFiles; ++fileIndex)
  {
    std::string filename = std::string(directoryHandler->GetFile(fileIndex));
    if (itksys::SystemTools::FileIsDirectory(filename))
      continue;

    if (!DoesFileHaveEnding(filename, ".nrrd"))
      continue;

    size_t s = filename.find("_p");
    size_t e = filename.find("Fluence", s);
    std::string sub = filename.substr(s + 2, e - s - 2);
    std::vector<int> coords = splitString(sub, ",");

    if (coords.size() != 3)
    {
      MITK_ERROR << "Some of the data to read was corrupted or did not match the " <<
        "naming pattern *_pN,N,NFluence*.nrrd";
      mitkThrow() << "Some of the data to read was corrupted or did not match the" <<
        " naming pattern *_pN,N,NFluence*.nrrd";
    }
    else
    {
      MITK_DEBUG << "Extracted coords: " << coords[0] << "|" << coords[1] << "|" << coords[2] << " from string " << sub;
      Volume::Pointer nrrdFile = LoadNrrd(foldername + filename, blur);
      if (doLog10)
        VolumeManipulator::Log10Image(nrrdFile);
      resultMap[Position{ coords[0], coords[2] }] = nrrdFile;
      *progress = *progress + 1;
    }
  }

  return resultMap;
}

int mitk::pa::IOUtil::GetNumberOfNrrdFilesInDirectory(std::string directory)
{
  return GetListOfAllNrrdFilesInDirectory(directory).size();
}

std::vector<std::string> mitk::pa::IOUtil::GetListOfAllNrrdFilesInDirectory(std::string directory, bool keepFileFormat)
{
  std::vector<std::string> filenames;
  itk::Directory::Pointer directoryHandler = itk::Directory::New();
  directoryHandler->Load(directory.c_str());
  for (unsigned int fileIndex = 0, numFiles = directoryHandler->GetNumberOfFiles(); fileIndex < numFiles; ++fileIndex)
  {
    std::string filename = std::string(directoryHandler->GetFile(fileIndex));
    if (itksys::SystemTools::FileIsDirectory(filename))
      continue;

    if (!DoesFileHaveEnding(filename, ".nrrd"))
      continue;

    if (keepFileFormat)
    {
      filenames.push_back(filename);
    }
    else
    {
      filenames.push_back(filename.substr(0, filename.size() - 5));
    }
  }

  return filenames;
}

std::vector<std::string> mitk::pa::IOUtil::GetAllChildfoldersFromFolder(std::string folderPath)
{
  std::vector<std::string> returnVector;

  itksys::Directory directoryHandler;
  directoryHandler.Load(folderPath.c_str());
  for (unsigned int fileIndex = 0, numFiles = directoryHandler.GetNumberOfFiles(); fileIndex < numFiles; ++fileIndex)
  {
    std::string foldername = std::string(directoryHandler.GetFile(fileIndex));
    std::string filename = folderPath + "/" + foldername;
    if (itksys::SystemTools::FileIsDirectory(filename))
    {
      if (foldername != std::string(".") && foldername != std::string(".."))
      {
        MITK_INFO << filename;
        returnVector.push_back(filename);
      }
      continue;
    }

    //If there is a nrrd file in the directory we assume that a bottom level directory was chosen.
    if (DoesFileHaveEnding(filename, ".nrrd"))
    {
      returnVector.clear();
      returnVector.push_back(folderPath);
      return returnVector;
    }
  }

  return returnVector;
}

mitk::pa::InSilicoTissueVolume::Pointer mitk::pa::IOUtil::LoadInSilicoTissueVolumeFromNrrdFile(std::string nrrdFile)
{
  MITK_INFO << "Initializing ComposedVolume by nrrd...";
  auto inputImage = mitk::IOUtil::Load<mitk::Image>(nrrdFile);

  auto tissueParameters = TissueGeneratorParameters::New();

  unsigned int xDim = inputImage->GetDimensions()[1];
  unsigned int yDim = inputImage->GetDimensions()[0];
  unsigned int zDim = inputImage->GetDimensions()[2];
  tissueParameters->SetXDim(xDim);
  tissueParameters->SetYDim(yDim);
  tissueParameters->SetZDim(zDim);

  double xSpacing = inputImage->GetGeometry(0)->GetSpacing()[1];
  double ySpacing = inputImage->GetGeometry(0)->GetSpacing()[0];
  double zSpacing = inputImage->GetGeometry(0)->GetSpacing()[2];

  if ((xSpacing - ySpacing) > mitk::eps || (xSpacing - zSpacing) > mitk::eps || (ySpacing - zSpacing) > mitk::eps)
  {
    throw mitk::Exception("Cannot handle unequal spacing.");
  }

  tissueParameters->SetVoxelSpacingInCentimeters(xSpacing);

  mitk::PropertyList::Pointer propertyList = inputImage->GetPropertyList();

  mitk::ImageReadAccessor readAccess0(inputImage, inputImage->GetVolumeData(0));
  auto* m_AbsorptionArray = new double[xDim*yDim*zDim];
  memcpy(m_AbsorptionArray, readAccess0.GetData(), xDim*yDim*zDim * sizeof(double));
  auto absorptionVolume = Volume::New(m_AbsorptionArray, xDim, yDim, zDim, xSpacing);

  mitk::ImageReadAccessor readAccess1(inputImage, inputImage->GetVolumeData(1));
  auto*  m_ScatteringArray = new double[xDim*yDim*zDim];
  memcpy(m_ScatteringArray, readAccess1.GetData(), xDim*yDim*zDim * sizeof(double));
  auto scatteringVolume = Volume::New(m_ScatteringArray, xDim, yDim, zDim, xSpacing);

  mitk::ImageReadAccessor readAccess2(inputImage, inputImage->GetVolumeData(2));
  auto*  m_AnisotropyArray = new double[xDim*yDim*zDim];
  memcpy(m_AnisotropyArray, readAccess2.GetData(), xDim*yDim*zDim * sizeof(double));
  auto anisotropyVolume = Volume::New(m_AnisotropyArray, xDim, yDim, zDim, xSpacing);

  Volume::Pointer segmentationVolume;

  if (inputImage->GetDimension() == 4)
  {
    mitk::ImageReadAccessor readAccess3(inputImage, inputImage->GetVolumeData(3));
    auto*  m_SegmentationArray = new double[xDim*yDim*zDim];
    memcpy(m_SegmentationArray, readAccess3.GetData(), xDim*yDim*zDim * sizeof(double));
    segmentationVolume = Volume::New(m_SegmentationArray, xDim, yDim, zDim, xSpacing);
  }

  return mitk::pa::InSilicoTissueVolume::New(absorptionVolume, scatteringVolume,
    anisotropyVolume, segmentationVolume, tissueParameters, propertyList);
}

mitk::pa::FluenceYOffsetPair::Pointer mitk::pa::IOUtil::LoadFluenceSimulation(std::string fluenceSimulation)
{
  MITK_INFO << "Adding slice...";

  mitk::Image::Pointer inputImage = mitk::IOUtil::Load<mitk::Image>(fluenceSimulation);

  auto yOffsetProperty = inputImage->GetProperty("y-offset");

  if (yOffsetProperty.IsNull())
    mitkThrow() << "No \"y-offset\" property found in fluence file!";

  std::string yOff = yOffsetProperty->GetValueAsString();
  MITK_INFO << "Reading y Offset: " << yOff;
#ifdef __linux__
  std::replace(yOff.begin(), yOff.end(), '.', ',');
#endif // __linux__
  double yOffset = std::stod(yOff);
  MITK_INFO << "Converted offset " << yOffset;
  return FluenceYOffsetPair::New(Volume::New(inputImage), yOffset);
}
<|endoftext|>


<commit_before>/*
Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2.

For example,
Given:
s1 = "aabcc",
s2 = "dbbca",

When s3 = "aadbbcbcac", return true.
When s3 = "aadbbbaccc", return false.
*/

#include <vector>
#include <string>
#include <stdio.h>

using namespace std;

class Solution
{
public:
    bool isInterleave(const string& s1, const string& s2, const string& s3)
    {
        int size1 = s1.size();
        int size2 = s2.size();
        int size3 = s3.size();
        if (size1 + size2 != size3)
        {
            return false;
        }
        vector<vector<int> > dp(size1 + 1, vector<int>(size2 + 1, 0));
        dp[0][0] = 1;
        for (int i = 1; i <= size2; ++i)
        {
            if (s2[i - 1] == s3[i - 1])
            {
                dp[0][i] = 1;
            }
            else
            {
                break;
            }
        }
        for (int i = 1; i <= size1; ++i)
        {
            if (s1[i - 1] == s3[i - 1])
            {
                dp[i][0] = 1;
            }
            else
            {
                break;
            }
        }
        for (int i = 1; i <= size1; ++i)
        {
            for (int j = 1; j <= size2; ++j)
            {
                if (s1[i - 1] == s3[i + j - 1])
                {
                    dp[i][j] = dp[i - 1][j];
                }
                if (s2[j - 1] == s3[i + j - 1])
                {
                    dp[i][j] = dp[i][j] || dp[i][j - 1];
                }
            }
        }
        return dp[size1][size2];
    }
};

int main(int argc, char* argv[])
{
    Solution s;
    printf("%d\n", s.isInterleave("aabcc", "dbbca", "aadbbcbcac"));
    printf("%d\n", s.isInterleave("aabcc", "dbbca", "aadbbbaccc"));
    printf("%d\n", s.isInterleave("aabc", "abad", "aabadabc"));
    return 0;
}
<commit_msg>Add dp formula for InterleavingString<commit_after>/*
Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2.

For example,
Given:
s1 = "aabcc",
s2 = "dbbca",

When s3 = "aadbbcbcac", return true.
When s3 = "aadbbbaccc", return false.
*/

#include <vector>
#include <string>
#include <stdio.h>

using namespace std;

class Solution
{
public:
    //DP solution
    //
    //dp[i][j] means s1[0...i] and s2[0...j] match s3[0...i+j]
    //
    //formula:
    //
    //dp[i][j] = (s1[i-1] == s3[i+j-1] && dp[i-1][j]) ||
    //           (s2[j-1] == s3[i+j-1] && dp[i][j-1])
    //
    //dp[0][0] = 1
    bool isInterleave(const string& s1, const string& s2, const string& s3)
    {
        int size1 = s1.size();
        int size2 = s2.size();
        int size3 = s3.size();
        if (size1 + size2 != size3)
        {
            return false;
        }
        vector<vector<int> > dp(size1 + 1, vector<int>(size2 + 1, 0));
        dp[0][0] = 1;
        for (int i = 1; i <= size2; ++i)
        {
            if (s2[i - 1] == s3[i - 1])
            {
                dp[0][i] = 1;
            }
            else
            {
                break;
            }
        }
        for (int i = 1; i <= size1; ++i)
        {
            if (s1[i - 1] == s3[i - 1])
            {
                dp[i][0] = 1;
            }
            else
            {
                break;
            }
        }
        for (int i = 1; i <= size1; ++i)
        {
            for (int j = 1; j <= size2; ++j)
            {
                if (s1[i - 1] == s3[i + j - 1])
                {
                    dp[i][j] = dp[i - 1][j];
                }
                if (s2[j - 1] == s3[i + j - 1])
                {
                    dp[i][j] = dp[i][j] || dp[i][j - 1];
                }
            }
        }
        return dp[size1][size2];
    }
};

int main(int argc, char* argv[])
{
    Solution s;
    printf("%d\n", s.isInterleave("aabcc", "dbbca", "aadbbcbcac"));
    printf("%d\n", s.isInterleave("aabcc", "dbbca", "aadbbbaccc"));
    printf("%d\n", s.isInterleave("aabc", "abad", "aabadabc"));
    return 0;
}
<|endoftext|>


<commit_before><commit_msg>`SettingMaster::set_and_print`: add checks for `nullptr`.<commit_after><|endoftext|>


<commit_before>//________________________________________________________________________
void demoInteractive() {
  //____________________________________________//
  AliTagAnalysis *TagAna = new AliTagAnalysis();

  AliRunTagCuts *RunCuts = new AliRunTagCuts();
  AliEventTagCuts *EvCuts = new AliEventTagCuts();
  EvCuts->SetMultiplicityRange(11,12);
  //grid tags
  TAlienCollection* coll = TAlienCollection::Open("tag.xml");
  TGridResult* TagResult = coll->GetGridResult("");
  TagAna->ChainGridTags(TagResult);
  TChain* chain = 0x0;
  chain = TagAna->QueryTags(RunCuts,EvCuts);

  //____________________________________________//
  // Make the analysis manager
  AliAnalysisManager *mgr = new AliAnalysisManager("TestManager");
  //____________________________________________//
  // 1st Pt task
  AliAnalysisTaskPt *task1 = new AliAnalysisTaskPt("TaskPt");
  mgr->AddTask(task1);
  // Create containers for input/output
  AliAnalysisDataContainer *cinput1 = mgr->CreateContainer("cchain1",TChain::Class(),AliAnalysisManager::kInputContainer);
  AliAnalysisDataContainer *coutput1 = mgr->CreateContainer("chist1", TH1::Class(),AliAnalysisManager::kOutputContainer,"Pt.ESD.root");

  //____________________________________________//
  mgr->ConnectInput(task1,0,cinput1);
  mgr->ConnectOutput(task1,0,coutput1);
  cinput1->SetData(chain);

  if (mgr->InitAnalysis()) {
    mgr->PrintStatus();
    mgr->StartAnalysis("local",chain);
  }
}

<commit_msg>Adding the 0,0 option in the TGridResult<commit_after>//________________________________________________________________________
void demoInteractive() {
  //____________________________________________//
  AliTagAnalysis *TagAna = new AliTagAnalysis();

  AliRunTagCuts *RunCuts = new AliRunTagCuts();
  AliEventTagCuts *EvCuts = new AliEventTagCuts();
  EvCuts->SetMultiplicityRange(11,12);
  //grid tags
  TAlienCollection* coll = TAlienCollection::Open("tag.xml");
  TGridResult* TagResult = coll->GetGridResult("",0,0);
  TagAna->ChainGridTags(TagResult);
  TChain* chain = 0x0;
  chain = TagAna->QueryTags(RunCuts,EvCuts);

  //____________________________________________//
  // Make the analysis manager
  AliAnalysisManager *mgr = new AliAnalysisManager("TestManager");
  //____________________________________________//
  // 1st Pt task
  AliAnalysisTaskPt *task1 = new AliAnalysisTaskPt("TaskPt");
  mgr->AddTask(task1);
  // Create containers for input/output
  AliAnalysisDataContainer *cinput1 = mgr->CreateContainer("cchain1",TChain::Class(),AliAnalysisManager::kInputContainer);
  AliAnalysisDataContainer *coutput1 = mgr->CreateContainer("chist1", TH1::Class(),AliAnalysisManager::kOutputContainer,"Pt.ESD.root");

  //____________________________________________//
  mgr->ConnectInput(task1,0,cinput1);
  mgr->ConnectOutput(task1,0,coutput1);
  cinput1->SetData(chain);

  if (mgr->InitAnalysis()) {
    mgr->PrintStatus();
    mgr->StartAnalysis("local",chain);
  }
}

<|endoftext|>


<commit_before>#include "../../testing/testing.hpp"

#include "../bit_streams.hpp"
#include "../reader.hpp"
#include "../writer.hpp"

#include "../../base/pseudo_random.hpp"

#include "../../std/utility.hpp"
#include "../../std/vector.hpp"

using namespace rnd;

UNIT_TEST(BitStream_ReadWrite)
{
  uint32_t const NUMS_CNT = 1000;
  vector< pair<uint64_t, uint32_t> > nums;
  for (uint32_t i = 0; i < NUMS_CNT; ++i)
  {
    uint32_t numBits = GetRand64() % 65;
    uint64_t num = GetRand64() & (uint64_t(-1) >> (64 - numBits));
    // Right bit shift by 64 doesn't always work correctly,
    // this is a workaround.
    if (numBits == 0) num = 0;
    nums.push_back(make_pair(num, numBits));
  }

  vector<uint8_t> encodedBits;
  {
    MemWriter< vector<uint8_t> > encodedBitsWriter(encodedBits);
    BitSink bitsSink(encodedBitsWriter);
    for (uint32_t i = 0; i < nums.size(); ++i) bitsSink.Write(nums[i].first, nums[i].second);
  }
  MemReader encodedBitsReader(encodedBits.data(), encodedBits.size());
  BitSource bitsSource(encodedBitsReader);
  for (uint32_t i = 0; i < nums.size(); ++i)
  {
    uint64_t num = bitsSource.Read(nums[i].second);
    TEST_EQUAL(num, nums[i].first, ());
  }
}

<commit_msg>[coding_tests] Correctly compute mask in Bit Streams test.<commit_after>#include "../../testing/testing.hpp"

#include "../bit_streams.hpp"
#include "../reader.hpp"
#include "../writer.hpp"

#include "../../base/pseudo_random.hpp"

#include "../../std/utility.hpp"
#include "../../std/vector.hpp"

using namespace rnd;

UNIT_TEST(BitStream_ReadWrite)
{
  uint32_t const NUMS_CNT = 1000;
  vector< pair<uint64_t, uint32_t> > nums;
  for (uint32_t i = 0; i < NUMS_CNT; ++i)
  {
    uint32_t numBits = GetRand64() % 65;
    uint64_t num = GetRand64() & ((uint64_t(1) << numBits) - 1);
    nums.push_back(make_pair(num, numBits));
  }

  vector<uint8_t> encodedBits;
  {
    MemWriter< vector<uint8_t> > encodedBitsWriter(encodedBits);
    BitSink bitsSink(encodedBitsWriter);
    for (uint32_t i = 0; i < nums.size(); ++i) bitsSink.Write(nums[i].first, nums[i].second);
  }
  MemReader encodedBitsReader(encodedBits.data(), encodedBits.size());
  BitSource bitsSource(encodedBitsReader);
  for (uint32_t i = 0; i < nums.size(); ++i)
  {
    uint64_t num = bitsSource.Read(nums[i].second);
    TEST_EQUAL(num, nums[i].first, ());
  }
}

<|endoftext|>


<commit_before>
// ProxyPlayer.hpp
// This will invoke another process and waits for a return code.

#ifndef __PROXY_PLAYER_HPP__
#define __PROXY_PLAYER_HPP__

#include "Player.hpp"
#include <string>
#include <sstream>

#ifdef _WIN32
#undef UNICODE
#define NOMINMAX 1
#include <windows.h>
#define EXE_SUFFIX ".exe"
#else
#include <cstdlib>
#define EXE_SUFFIX ""
#endif

class ProxyPlayer : public Player
{
public:
	// Initialize with process (without .exe) and identifier of opponent.
	ProxyPlayer(std::string const &process, std::string const &script = "", size_t opponent = -1)
		: mProcess(process), mScript(script), Player(opponent) {}

public:
	// Invoke other process.
	virtual Action fight()
	{
		unsigned choice = executeWithArguments(getArguments(3));
		switch (choice)
		{
		case 48: return load();
		case 49: return bullet();
		case 50: return plasma();
		case 45: return metal();
		case 61: return thermal();
		default: return (Action)(-1);
		}
	}

	// Notify external program of result.
	virtual void declared(Result result)
	{
		std::string arguments;
		switch (result)
		{
		case WIN:  arguments = getArguments(1);
		case LOSS: arguments = getArguments(2);
		default:   arguments = getArguments(0);
		}
		executeWithArguments(arguments);
	};

private:
	// External process name
	std::string mProcess;

	// External script name (for non binary submissions)
	std::string mScript;

	// Generates argument given game status.
	std::string getArguments(size_t status)
	{
		std::stringstream sst;
		sst << getOpponent()
			<< " " << getTurn()
			<< " " << status
			<< " " << getAmmo()
			<< " " << getAmmoOpponent();
		if (getTurn() > 0)
		{
			sst << " " << toActionString(getHistory())
				<< " " << toActionString(getHistoryOpponent());
		};
		return sst.str();
	}

	// Execute process with given arguments.
	unsigned executeWithArguments(std::string const &arguments) const
	{
#ifdef _WIN32
		STARTUPINFO startup = { sizeof(startup) };
		PROCESS_INFORMATION process;
		LPSTR lpApplicationName;
		LPSTR lpCommandLine;

		lpApplicationName = const_cast<char *>(mProcess.c_str());
		if (mScript.length() == 0)
		{
			// Binary Proxy Player
			// name.exe arguments
			lpCommandLine = const_cast<char *>(arguments.c_str());
		}
		else
		{
			// Script Proxy Player
			// python.exe script.py arguments
			std::string actualArguments = mScript;
			actualArguments.append(1, ' ');
			actualArguments.append(arguments);
		}

		startup.cb = sizeof(startup);
		BOOL result = CreateProcess(lpApplicationName, lpCommandLine,
			NULL, NULL, TRUE, 0, NULL, NULL, &startup, &process);

		if (!result)
		{
			return -1;
		}
		else
		{
			// Wait for process to terminate and sanitize return code.
			DWORD exitCode;
			WaitForSingleObject(process.hProcess, INFINITE);
			GetExitCodeProcess(process.hProcess, &exitCode);
			return exitCode;
		}
#else
		return std::system((mProcess + " " + mScript + " " + arguments).c_str());
#endif
	}
};

#define STRINGIFY(x) #x

// Example: BINARY_PLAYER(CustomPlayer)
// Effects: Invoke CustomPlayer.exe <arguments>
#define BINARY_PLAYER(x)                                              \
	class x final : public ProxyPlayer                                \
	{                                                                 \
	public:                                                           \
	    x(size_t opponent = -1) : ProxyPlayer(#x EXE_SUFFIX, opponent) {} \
	};

// Example: SCRIPT_PLAYER(CustomPlayer, "python", "CustomScriptPlayer.py")
// Effects: Invoke python CustomScriptPlayer.py <arguments>
#define SCRIPT_PLAYER(x, y, z)                                        \
	class x final : public ProxyPlayer                                \
	{                                                                 \
	public:                                                           \
		x(size_t opponent = -1) : ProxyPlayer(y, z, opponent) {}      \
	};

#endif // !__CUSTOM_PLAYER_HPP__
<commit_msg>Fixing Proxy Player for script submissions.<commit_after>
// ProxyPlayer.hpp
// This will invoke another process and waits for a return code.

#ifndef __PROXY_PLAYER_HPP__
#define __PROXY_PLAYER_HPP__

#include "Player.hpp"
#include <string>
#include <sstream>

#ifdef _WIN32
#undef UNICODE
#define NOMINMAX 1
#include <windows.h>
#define EXE_SUFFIX ".exe"
#else
#include <cstdlib>
#define EXE_SUFFIX ""
#endif

class ProxyPlayer : public Player
{
public:
	// Initialize with process (without .exe) and identifier of opponent.
	ProxyPlayer(std::string const &process, std::string const &script = "", size_t opponent = -1)
		: mProcess(process), mScript(script), Player(opponent) {}

public:
	// Invoke other process.
	virtual Action fight()
	{
		unsigned choice = executeWithArguments(getArguments(3));
		switch (choice)
		{
		case 48: return load();
		case 49: return bullet();
		case 50: return plasma();
		case 45: return metal();
		case 61: return thermal();
		default: return (Action)(-1);
		}
	}

	// Notify external program of result.
	virtual void declared(Result result)
	{
		std::string arguments;
		switch (result)
		{
		case WIN:  arguments = getArguments(1);
		case LOSS: arguments = getArguments(2);
		default:   arguments = getArguments(0);
		}
		executeWithArguments(arguments);
	};

private:
	// External process name
	std::string mProcess;

	// External script name (for non binary submissions)
	std::string mScript;

	// Generates argument given game status.
	std::string getArguments(size_t status)
	{
		std::stringstream sst;
		sst << getOpponent()
			<< " " << getTurn()
			<< " " << status
			<< " " << getAmmo()
			<< " " << getAmmoOpponent();
		if (getTurn() > 0)
		{
			sst << " " << toActionString(getHistory())
				<< " " << toActionString(getHistoryOpponent());
		};
		return sst.str();
	}

	// Execute process with given arguments.
	unsigned executeWithArguments(std::string const &arguments) const
	{
#ifdef _WIN32
		STARTUPINFO startup = { sizeof(startup) };
		PROCESS_INFORMATION process;
		LPSTR lpApplicationName;
		LPSTR lpCommandLine;

		std::string actualArguments;
		if (mScript.length() == 0)
		{
			// Binary Proxy Player
			// name.exe arguments
			actualArguments = arguments;
		}
		else
		{
			// Script Proxy Player
			// python.exe script.py arguments
			actualArguments = mScript + ' ' + arguments;
		}

		lpApplicationName = const_cast<char *>(mProcess.c_str());
		lpCommandLine = const_cast<char *>(actualArguments.c_str());

		startup.cb = sizeof(startup);
		BOOL result = CreateProcess(lpApplicationName, lpCommandLine,
			NULL, NULL, TRUE, 0, NULL, NULL, &startup, &process);

		if (!result)
		{
			return -1;
		}
		else
		{
			// Wait for process to terminate and sanitize return code.
			DWORD exitCode;
			WaitForSingleObject(process.hProcess, INFINITE);
			GetExitCodeProcess(process.hProcess, &exitCode);
			return exitCode;
		}
#else
		return std::system((mProcess + " " + mScript + " " + arguments).c_str());
#endif
	}
};

#define STRINGIFY(x) #x

// Example: BINARY_PLAYER(CustomPlayer)
// Effects: Invoke CustomPlayer.exe <arguments>
#define BINARY_PLAYER(x)                                              \
	class x final : public ProxyPlayer                                \
	{                                                                 \
	public:                                                           \
	    x(size_t opponent = -1) : ProxyPlayer(#x EXE_SUFFIX, opponent) {} \
	};

// Example: SCRIPT_PLAYER(CustomPlayer, "python", "CustomScriptPlayer.py")
// Effects: Invoke python CustomScriptPlayer.py <arguments>
#define SCRIPT_PLAYER(x, y, z)                                        \
	class x final : public ProxyPlayer                                \
	{                                                                 \
	public:                                                           \
		x(size_t opponent = -1) : ProxyPlayer(y, z, opponent) {}      \
	};

#endif // !__CUSTOM_PLAYER_HPP__
<|endoftext|>


<commit_before>#include "wrapper.hh"
#include <stdexcept>

Wrapper::Wrapper(v8::Local<v8::Object> options) {
	Nan::HandleScope scope;

	v8::Local<v8::Value> options_device_value = Nan::Get(options, Nan::New("device").ToLocalChecked()).ToLocalChecked();
	if(!options_device_value->IsString()) {
		throw std::invalid_argument("Options should have string device property");
	}

	v8::Local<v8::Value> options_onRecv_value = Nan::Get(options, Nan::New("onRecv").ToLocalChecked()).ToLocalChecked();
	if(!options_onRecv_value->IsFunction()) {
		throw std::invalid_argument("Options should have callback onRecv property");
	}

	v8::Local<v8::Value> options_onSend_value = Nan::Get(options, Nan::New("onSend").ToLocalChecked()).ToLocalChecked();
	if(!options_onSend_value->IsFunction()) {
		throw std::invalid_argument("Options should have callback onSend property");
	}

	v8::Local<v8::Value> options_onError_value = Nan::Get(options, Nan::New("onError").ToLocalChecked()).ToLocalChecked();
	if(!options_onError_value->IsFunction()) {
		throw std::invalid_argument("Options should have callback onError property");
	}

	onRecvCallback.Reset(options_onRecv_value.As<v8::Function>());
	onSendCallback.Reset(options_onSend_value.As<v8::Function>());
	onSendCallback.Reset(options_onError_value.As<v8::Function>());

	Nan::Utf8String device_string(options_device_value);
	socket = new Socket(*device_string);
	poller = new Poller(socket->get_descriptor(),
		Wrapper::ReadReadyCallback,
		Wrapper::WriteReadyCallback,
		Wrapper::ErrorCallback,
		this);
}
Wrapper::~Wrapper() {
	onRecvCallback.Reset();
	onSendCallback.Reset();
	onErrorCallback.Reset();
	delete poller;
	delete socket;
}

Nan::Persistent<v8::Function> Wrapper::constructor;
#include <cstdio>
NAN_MODULE_INIT(Wrapper::Init) {
	v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New);
	tpl->SetClassName(Nan::New("Wrapper").ToLocalChecked());
	tpl->InstanceTemplate()->SetInternalFieldCount(1);

	Nan::SetPrototypeMethod(tpl, "AddMembership", AddMembership);
	Nan::SetPrototypeMethod(tpl, "DropMembership", DropMembership);
	Nan::SetPrototypeMethod(tpl, "Send", Send);
	Nan::SetPrototypeMethod(tpl, "Receive", Receive);

	Nan::SetPrototypeMethod(tpl, "PauseSending", PauseSending);
	Nan::SetPrototypeMethod(tpl, "ResumeSending", ResumeSending);

	constructor.Reset(Nan::GetFunction(tpl).ToLocalChecked());
	Nan::Set(target, Nan::New("Wrapper").ToLocalChecked(),
			Nan::GetFunction(tpl).ToLocalChecked());
}

NAN_METHOD(Wrapper::New) {
	if(info.IsConstructCall()) {
		Nan::MaybeLocal<v8::Object> options_object_maybe = Nan::To<v8::Object>(info[0]);
		if(options_object_maybe.IsEmpty())
			return Nan::ThrowError("Missing options object");

		v8::Local<v8::Object> options_object = options_object_maybe.ToLocalChecked();

		if(!Nan::HasOwnProperty(options_object, Nan::New("device").ToLocalChecked()).FromMaybe(false)) {
			return Nan::ThrowTypeError("Options should have device property");
		}

		if(!Nan::HasOwnProperty(options_object, Nan::New("onRecv").ToLocalChecked()).FromMaybe(false)) {
			return Nan::ThrowTypeError("Options should have onRecv property");
		}

		if(!Nan::HasOwnProperty(options_object, Nan::New("onSend").ToLocalChecked()).FromMaybe(false)) {
			return Nan::ThrowTypeError("Options should have onSend property");
		}

		if(!Nan::HasOwnProperty(options_object, Nan::New("onError").ToLocalChecked()).FromMaybe(false)) {
			return Nan::ThrowTypeError("Options should have onError property");
		}

		try {
			Wrapper *object = new Wrapper(options_object);
			object->Wrap(info.This());
		} catch(const std::exception &e) {
			return Nan::ThrowError(e.what());
		}
		info.GetReturnValue().Set(info.This());
	} else {
		const int argc = 1;
		v8::Local<v8::Value> argv[argc] = {info[0]};
		v8::Local<v8::Function> emulate_constructor = Nan::New(constructor);

		Nan::TryCatch trycatch;
		Nan::MaybeLocal<v8::Object> constructed_object =
				Nan::NewInstance(emulate_constructor, argc, argv);
		if(trycatch.HasCaught()) {
			trycatch.ReThrow();
			return;
		}
		info.GetReturnValue().Set(constructed_object.ToLocalChecked());
	}
}

void Wrapper::ReadReadyCallback(void *data) {
	Nan::HandleScope scope;
	Wrapper *wrap = reinterpret_cast<Wrapper *>(data);
	Nan::Callback callback(Nan::New<v8::Function>(wrap->onRecvCallback));
	callback.Call(0, 0);
}
void Wrapper::WriteReadyCallback(void *data) {
	Nan::HandleScope scope;
	Wrapper *wrap = reinterpret_cast<Wrapper *>(data);
	Nan::Callback callback(Nan::New<v8::Function>(wrap->onSendCallback));
	callback.Call(0, 0);
}

void Wrapper::ErrorCallback(void *data, const char *error) {
	Nan::HandleScope scope;
	Wrapper *wrap = reinterpret_cast<Wrapper *>(data);
	Nan::Callback callback(Nan::New<v8::Function>(wrap->onSendCallback));
	const int argc = 1;
	v8::Local<v8::Value> argv[argc] = {Nan::New(error).ToLocalChecked()};
	callback.Call(argc, argv);
}

void Wrapper::ParseMembershipArguments(
			Nan::NAN_METHOD_ARGS_TYPE info,
			Socket::MembershipType *type,
			unsigned char **address) {
	Nan::HandleScope scope;
	Nan::MaybeLocal<v8::Value> type_or_addr_maybe = info[0];

	if(info.Length() == 0 || type_or_addr_maybe.IsEmpty())
		throw std::invalid_argument("Missing type or address argument");
	v8::Local<v8::Value> type_or_addr = type_or_addr_maybe.ToLocalChecked();

	if(node::Buffer::HasInstance(type_or_addr)) {
		if(node::Buffer::Length(type_or_addr) < Socket::ADDRESS_LENGHT)
			throw std::invalid_argument("Invalid address length");
		*address = reinterpret_cast<unsigned char *>(node::Buffer::Data(type_or_addr));
	} else if(type_or_addr->IsNumber()) {
		*type = static_cast<Socket::MembershipType>(Nan::To<int>(type_or_addr).FromJust());
	} else {
		throw std::invalid_argument("Invalid address length");
	}
}

NAN_METHOD(Wrapper::AddMembership) {
	Wrapper *obj = Nan::ObjectWrap::Unwrap<Wrapper>(info.Holder());

	Socket::MembershipType type = Socket::MULTICAST;
	unsigned char *address = NULL;

	try {
		ParseMembershipArguments(info, &type, &address);
		obj->socket->add_membership(type, address);
	} catch(const std::exception &e) {
		return Nan::ThrowError(e.what());
	}
}

NAN_METHOD(Wrapper::DropMembership) {
	Wrapper *obj = Nan::ObjectWrap::Unwrap<Wrapper>(info.Holder());

	Socket::MembershipType type = Socket::MULTICAST;
	unsigned char *address = NULL;

	try {
		ParseMembershipArguments(info, &type, &address);
		obj->socket->drop_membership(type, address);
	} catch(const std::exception &e) {
		return Nan::ThrowError(e.what());
	}
}

NAN_METHOD(Wrapper::Receive) {
	Wrapper *obj = Nan::ObjectWrap::Unwrap<Wrapper>(info.Holder());

	if(info.Length() != 1)
		return Nan::ThrowError("One argument required");

	if(!info[0]->IsFunction())
		return Nan::ThrowTypeError("Callback argument has to be function");
	v8::Local<v8::Function> callback = info[0].As<v8::Function>();

	int received_bytes = -1;
	unsigned char *source_address = reinterpret_cast<unsigned char *>(malloc(Socket::ADDRESS_LENGHT));
	if(!source_address)
		return Nan::ThrowError("Memory allocation for source address failed");

	unsigned char *destination_address = reinterpret_cast<unsigned char *>(malloc(Socket::ADDRESS_LENGHT));
	if(!destination_address) {
		free(source_address);
		return Nan::ThrowError("Memory allocation for destination address failed");
	}

	char *message_buffer = reinterpret_cast<char *>(malloc(Wrapper::MAX_RECEIVE_BUFFER_SIZE));
	if(!message_buffer) {
		free(source_address);
		free(destination_address);
		return Nan::ThrowError("Memory allocation for buffer failed");
	}

	try {
		received_bytes = obj->socket->receive_message(
				source_address,
				destination_address,
				message_buffer,
				Wrapper::MAX_RECEIVE_BUFFER_SIZE);
	} catch(const std::exception &e) {
		free(destination_address);
		free(source_address);
		free(message_buffer);
		return Nan::ThrowError(e.what());
	}

	char *tmp_buff = reinterpret_cast<char *>(realloc(message_buffer, received_bytes));
	if(tmp_buff)
		message_buffer = tmp_buff;

	Nan::MaybeLocal<v8::Object> source_address_node_buffer = Nan::NewBuffer((char *)source_address, Socket::ADDRESS_LENGHT);
	Nan::MaybeLocal<v8::Object> destination_address_node_buffer = Nan::NewBuffer((char *)destination_address, Socket::ADDRESS_LENGHT);
	Nan::MaybeLocal<v8::Object> message_node_buffer = Nan::NewBuffer(message_buffer, received_bytes);
	if(source_address_node_buffer.IsEmpty() || destination_address_node_buffer.IsEmpty() || message_node_buffer.IsEmpty()) {
		return Nan::ThrowError("Failed to create buffer object");
	}

	const int argc = 3;
	v8::Local<v8::Value> argv[argc] = {
		source_address_node_buffer.ToLocalChecked(),
		destination_address_node_buffer.ToLocalChecked(),
		message_node_buffer.ToLocalChecked()
	};
	Nan::MakeCallback(Nan::GetCurrentContext()->Global(), callback, argc, argv);

}

NAN_METHOD(Wrapper::Send) {
	Wrapper *obj = Nan::ObjectWrap::Unwrap<Wrapper>(info.Holder());

	if(info.Length() != 3)
		return Nan::ThrowError("Three arguments required");

	v8::Local<v8::Value> message_to_send = info[0];
	if(!node::Buffer::HasInstance(message_to_send))
		return Nan::ThrowTypeError("Message argument has to be buffer");

	v8::Local<v8::Value> destination_address = info[1];
	if(!node::Buffer::HasInstance(destination_address))
		return Nan::ThrowTypeError("Address argument has to be buffer");
	if(node::Buffer::Length(destination_address) != Socket::ADDRESS_LENGHT)
		return Nan::ThrowTypeError("Address argument invalid length");

	if(!info[2]->IsFunction())
		return Nan::ThrowTypeError("Callback argument has to be function");
	v8::Local<v8::Function> callback = info[2].As<v8::Function>();

	int send_bytes = -1;
	try {
		send_bytes = obj->socket->send_message(
				reinterpret_cast<unsigned char *>(node::Buffer::Data(destination_address)),
				node::Buffer::Data(message_to_send),
				node::Buffer::Length(message_to_send));
	} catch(const std::exception &e) {
		return Nan::ThrowError(e.what());
	}

	const int argc = 1;
	v8::Local<v8::Value> argv[argc] = { Nan::New(send_bytes) };
	Nan::MakeCallback(Nan::GetCurrentContext()->Global(), callback, argc, argv);
}

NAN_METHOD(Wrapper::PauseSending) {
	Wrapper *obj = Nan::ObjectWrap::Unwrap<Wrapper>(info.Holder());
	obj->poller->set_events(Poller::WRITE_EVENT);
}

NAN_METHOD(Wrapper::ResumeSending) {
	Wrapper *obj = Nan::ObjectWrap::Unwrap<Wrapper>(info.Holder());
	obj->poller->set_events(Poller::RW_EVENT);
}

NODE_MODULE(packet_socket_addon, Wrapper::Init);
<commit_msg>Modify send to error variables in error callback<commit_after>#include "wrapper.hh"
#include <stdexcept>

Wrapper::Wrapper(v8::Local<v8::Object> options) {
	Nan::HandleScope scope;

	v8::Local<v8::Value> options_device_value = Nan::Get(options, Nan::New("device").ToLocalChecked()).ToLocalChecked();
	if(!options_device_value->IsString()) {
		throw std::invalid_argument("Options should have string device property");
	}

	v8::Local<v8::Value> options_onRecv_value = Nan::Get(options, Nan::New("onRecv").ToLocalChecked()).ToLocalChecked();
	if(!options_onRecv_value->IsFunction()) {
		throw std::invalid_argument("Options should have callback onRecv property");
	}

	v8::Local<v8::Value> options_onSend_value = Nan::Get(options, Nan::New("onSend").ToLocalChecked()).ToLocalChecked();
	if(!options_onSend_value->IsFunction()) {
		throw std::invalid_argument("Options should have callback onSend property");
	}

	v8::Local<v8::Value> options_onError_value = Nan::Get(options, Nan::New("onError").ToLocalChecked()).ToLocalChecked();
	if(!options_onError_value->IsFunction()) {
		throw std::invalid_argument("Options should have callback onError property");
	}

	onRecvCallback.Reset(options_onRecv_value.As<v8::Function>());
	onSendCallback.Reset(options_onSend_value.As<v8::Function>());
	onErrorCallback.Reset(options_onError_value.As<v8::Function>());

	Nan::Utf8String device_string(options_device_value);
	socket = new Socket(*device_string);
	poller = new Poller(socket->get_descriptor(),
		Wrapper::ReadReadyCallback,
		Wrapper::WriteReadyCallback,
		Wrapper::ErrorCallback,
		this);
}
Wrapper::~Wrapper() {
	onRecvCallback.Reset();
	onSendCallback.Reset();
	onErrorCallback.Reset();
	delete poller;
	delete socket;
}

Nan::Persistent<v8::Function> Wrapper::constructor;
#include <cstdio>
NAN_MODULE_INIT(Wrapper::Init) {
	v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New);
	tpl->SetClassName(Nan::New("Wrapper").ToLocalChecked());
	tpl->InstanceTemplate()->SetInternalFieldCount(1);

	Nan::SetPrototypeMethod(tpl, "AddMembership", AddMembership);
	Nan::SetPrototypeMethod(tpl, "DropMembership", DropMembership);
	Nan::SetPrototypeMethod(tpl, "Send", Send);
	Nan::SetPrototypeMethod(tpl, "Receive", Receive);

	Nan::SetPrototypeMethod(tpl, "PauseSending", PauseSending);
	Nan::SetPrototypeMethod(tpl, "ResumeSending", ResumeSending);

	constructor.Reset(Nan::GetFunction(tpl).ToLocalChecked());
	Nan::Set(target, Nan::New("Wrapper").ToLocalChecked(),
			Nan::GetFunction(tpl).ToLocalChecked());
}

NAN_METHOD(Wrapper::New) {
	if(info.IsConstructCall()) {
		Nan::MaybeLocal<v8::Object> options_object_maybe = Nan::To<v8::Object>(info[0]);
		if(options_object_maybe.IsEmpty())
			return Nan::ThrowError("Missing options object");

		v8::Local<v8::Object> options_object = options_object_maybe.ToLocalChecked();

		if(!Nan::HasOwnProperty(options_object, Nan::New("device").ToLocalChecked()).FromMaybe(false)) {
			return Nan::ThrowTypeError("Options should have device property");
		}

		if(!Nan::HasOwnProperty(options_object, Nan::New("onRecv").ToLocalChecked()).FromMaybe(false)) {
			return Nan::ThrowTypeError("Options should have onRecv property");
		}

		if(!Nan::HasOwnProperty(options_object, Nan::New("onSend").ToLocalChecked()).FromMaybe(false)) {
			return Nan::ThrowTypeError("Options should have onSend property");
		}

		if(!Nan::HasOwnProperty(options_object, Nan::New("onError").ToLocalChecked()).FromMaybe(false)) {
			return Nan::ThrowTypeError("Options should have onError property");
		}

		try {
			Wrapper *object = new Wrapper(options_object);
			object->Wrap(info.This());
		} catch(const std::exception &e) {
			return Nan::ThrowError(e.what());
		}
		info.GetReturnValue().Set(info.This());
	} else {
		const int argc = 1;
		v8::Local<v8::Value> argv[argc] = {info[0]};
		v8::Local<v8::Function> emulate_constructor = Nan::New(constructor);

		Nan::TryCatch trycatch;
		Nan::MaybeLocal<v8::Object> constructed_object =
				Nan::NewInstance(emulate_constructor, argc, argv);
		if(trycatch.HasCaught()) {
			trycatch.ReThrow();
			return;
		}
		info.GetReturnValue().Set(constructed_object.ToLocalChecked());
	}
}

void Wrapper::ReadReadyCallback(void *data) {
	Nan::HandleScope scope;
	Wrapper *wrap = reinterpret_cast<Wrapper *>(data);
	Nan::Callback callback(Nan::New<v8::Function>(wrap->onRecvCallback));
	callback.Call(0, 0);
}
void Wrapper::WriteReadyCallback(void *data) {
	Nan::HandleScope scope;
	Wrapper *wrap = reinterpret_cast<Wrapper *>(data);
	Nan::Callback callback(Nan::New<v8::Function>(wrap->onSendCallback));
	callback.Call(0, 0);
}

void Wrapper::ErrorCallback(void *data, const char *error) {
	Nan::HandleScope scope;
	Wrapper *wrap = reinterpret_cast<Wrapper *>(data);
	Nan::Callback callback(Nan::New<v8::Function>(wrap->onErrorCallback));
	const int argc = 1;
	v8::Local<v8::Value> argv[argc] = {Nan::New(error).ToLocalChecked()};
	callback.Call(argc, argv);
}

void Wrapper::ParseMembershipArguments(
			Nan::NAN_METHOD_ARGS_TYPE info,
			Socket::MembershipType *type,
			unsigned char **address) {
	Nan::HandleScope scope;
	Nan::MaybeLocal<v8::Value> type_or_addr_maybe = info[0];

	if(info.Length() == 0 || type_or_addr_maybe.IsEmpty())
		throw std::invalid_argument("Missing type or address argument");
	v8::Local<v8::Value> type_or_addr = type_or_addr_maybe.ToLocalChecked();

	if(node::Buffer::HasInstance(type_or_addr)) {
		if(node::Buffer::Length(type_or_addr) < Socket::ADDRESS_LENGHT)
			throw std::invalid_argument("Invalid address length");
		*address = reinterpret_cast<unsigned char *>(node::Buffer::Data(type_or_addr));
	} else if(type_or_addr->IsNumber()) {
		*type = static_cast<Socket::MembershipType>(Nan::To<int>(type_or_addr).FromJust());
	} else {
		throw std::invalid_argument("Invalid address length");
	}
}

NAN_METHOD(Wrapper::AddMembership) {
	Wrapper *obj = Nan::ObjectWrap::Unwrap<Wrapper>(info.Holder());

	Socket::MembershipType type = Socket::MULTICAST;
	unsigned char *address = NULL;

	try {
		ParseMembershipArguments(info, &type, &address);
		obj->socket->add_membership(type, address);
	} catch(const std::exception &e) {
		return Nan::ThrowError(e.what());
	}
}

NAN_METHOD(Wrapper::DropMembership) {
	Wrapper *obj = Nan::ObjectWrap::Unwrap<Wrapper>(info.Holder());

	Socket::MembershipType type = Socket::MULTICAST;
	unsigned char *address = NULL;

	try {
		ParseMembershipArguments(info, &type, &address);
		obj->socket->drop_membership(type, address);
	} catch(const std::exception &e) {
		return Nan::ThrowError(e.what());
	}
}

NAN_METHOD(Wrapper::Receive) {
	Wrapper *obj = Nan::ObjectWrap::Unwrap<Wrapper>(info.Holder());

	if(info.Length() != 1)
		return Nan::ThrowError("One argument required");

	if(!info[0]->IsFunction())
		return Nan::ThrowTypeError("Callback argument has to be function");
	v8::Local<v8::Function> callback = info[0].As<v8::Function>();

	int received_bytes = -1;
	unsigned char *source_address = reinterpret_cast<unsigned char *>(malloc(Socket::ADDRESS_LENGHT));
	if(!source_address)
		return Nan::ThrowError("Memory allocation for source address failed");

	unsigned char *destination_address = reinterpret_cast<unsigned char *>(malloc(Socket::ADDRESS_LENGHT));
	if(!destination_address) {
		free(source_address);
		return Nan::ThrowError("Memory allocation for destination address failed");
	}

	char *message_buffer = reinterpret_cast<char *>(malloc(Wrapper::MAX_RECEIVE_BUFFER_SIZE));
	if(!message_buffer) {
		free(source_address);
		free(destination_address);
		return Nan::ThrowError("Memory allocation for buffer failed");
	}

	try {
		received_bytes = obj->socket->receive_message(
				source_address,
				destination_address,
				message_buffer,
				Wrapper::MAX_RECEIVE_BUFFER_SIZE);
	} catch(const std::exception &e) {
		free(destination_address);
		free(source_address);
		free(message_buffer);
		return Nan::ThrowError(e.what());
	}

	char *tmp_buff = reinterpret_cast<char *>(realloc(message_buffer, received_bytes));
	if(tmp_buff)
		message_buffer = tmp_buff;

	Nan::MaybeLocal<v8::Object> source_address_node_buffer = Nan::NewBuffer((char *)source_address, Socket::ADDRESS_LENGHT);
	Nan::MaybeLocal<v8::Object> destination_address_node_buffer = Nan::NewBuffer((char *)destination_address, Socket::ADDRESS_LENGHT);
	Nan::MaybeLocal<v8::Object> message_node_buffer = Nan::NewBuffer(message_buffer, received_bytes);
	if(source_address_node_buffer.IsEmpty() || destination_address_node_buffer.IsEmpty() || message_node_buffer.IsEmpty()) {
		return Nan::ThrowError("Failed to create buffer object");
	}

	const int argc = 3;
	v8::Local<v8::Value> argv[argc] = {
		source_address_node_buffer.ToLocalChecked(),
		destination_address_node_buffer.ToLocalChecked(),
		message_node_buffer.ToLocalChecked()
	};
	Nan::MakeCallback(Nan::GetCurrentContext()->Global(), callback, argc, argv);

}

NAN_METHOD(Wrapper::Send) {
	Wrapper *obj = Nan::ObjectWrap::Unwrap<Wrapper>(info.Holder());

	if(info.Length() != 3)
		return Nan::ThrowError("Three arguments required");

	v8::Local<v8::Value> message_to_send = info[0];
	if(!node::Buffer::HasInstance(message_to_send))
		return Nan::ThrowTypeError("Message argument has to be buffer");

	v8::Local<v8::Value> destination_address = info[1];
	if(!node::Buffer::HasInstance(destination_address))
		return Nan::ThrowTypeError("Address argument has to be buffer");
	if(node::Buffer::Length(destination_address) != Socket::ADDRESS_LENGHT)
		return Nan::ThrowTypeError("Address argument invalid length");

	if(!info[2]->IsFunction())
		return Nan::ThrowTypeError("Callback argument has to be function");
	v8::Local<v8::Function> callback = info[2].As<v8::Function>();

	int send_bytes = -1;
	try {
		send_bytes = obj->socket->send_message(
				reinterpret_cast<unsigned char *>(node::Buffer::Data(destination_address)),
				node::Buffer::Data(message_to_send),
				node::Buffer::Length(message_to_send));
	} catch(const std::exception &e) {
		return Nan::ThrowError(e.what());
	}

	const int argc = 1;
	v8::Local<v8::Value> argv[argc] = { Nan::New(send_bytes) };
	Nan::MakeCallback(Nan::GetCurrentContext()->Global(), callback, argc, argv);
}

NAN_METHOD(Wrapper::PauseSending) {
	Wrapper *obj = Nan::ObjectWrap::Unwrap<Wrapper>(info.Holder());
	obj->poller->set_events(Poller::WRITE_EVENT);
}

NAN_METHOD(Wrapper::ResumeSending) {
	Wrapper *obj = Nan::ObjectWrap::Unwrap<Wrapper>(info.Holder());
	obj->poller->set_events(Poller::RW_EVENT);
}

NODE_MODULE(packet_socket_addon, Wrapper::Init);
<|endoftext|>


<commit_before><commit_msg>LowB cut var changes<commit_after><|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include "src/Options.hpp"
#include "src/Cluster.hpp"

using namespace std;
int main(int argc, char *argv[]){

    string path2data = "../data/";
/* norm of matrix is mofiedable by 'young_modulus' */
    double young_modulus = 10000;
//    double young_modulus = 2.1e9;
    double poissons_ratio = 0.4999;

/* ---------------------------------------------------------*/
/* ---------------------------------------------------------*/
/* ---------------------------------------------------------*/
/* ---------------------------------------------------------*/

    cout << argv[0] << endl;
    Options options;
    options.set_values(path2data, argc, argv, young_modulus, poissons_ratio);
    Cluster cluster(options);
    cout << "----------------- done -----------------\n" ;
    return 0;
}
<commit_msg>update<commit_after>#include <iostream>
#include <string>
#include "src/Options.hpp"
#include "src/Cluster.hpp"

using namespace std;
int main(int argc, char *argv[]){

    string path2data = "../data/";
/* norm of matrix can be changed by following 2 parameters */
    double young_modulus = 10000;
    double poissons_ratio = 0.3;

//    double young_modulus = 2.1e9;
//    double poissons_ratio = 0.4999;

/* ---------------------------------------------------------*/
/* ---------------------------------------------------------*/
/* ---------------------------------------------------------*/
/* ---------------------------------------------------------*/

    cout << argv[0] << endl;
    Options options;
    options.set_values(path2data, argc, argv, young_modulus, poissons_ratio);
    Cluster cluster(options);
    cout << "----------------- done -----------------\n" ;
    return 0;
}
<|endoftext|>


<commit_before><commit_msg>`Node::delete_bidirectional_link`: check `this->parent` for `nullptr`.<commit_after><|endoftext|>


<commit_before>AliAnalysisTaskSEDvsMultiplicity *AddTaskDvsMultiplicity(Int_t system=0,
							 Bool_t readMC=kFALSE,
							 Int_t MCOption=0,
							 Int_t pdgMeson=411,
							 TString finDirname="Loose",
							 TString filename="",
							 TString finAnObjname="AnalysisCuts",
							 TString estimatorFilename="")
{
  //
  // Test macro for the AliAnalysisTaskSE for D+ candidates
  //Invariant mass histogram and
  // association with MC truth (using MC info in AOD)
  //  R. Bala, bala@to.infn.it
  // Get the pointer to the existing analysis manager via the static access method.
  //==============================================================================

  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    ::Error("AddTaskDvsMultiplicity", "No analysis manager to connect to.");
  }

  Bool_t stdcuts=kFALSE;
  TFile* filecuts;
  if( filename.EqualTo("") ) {
    stdcuts=kTRUE;
  } else {
    filecuts=TFile::Open(filename.Data());
    if(!filecuts ||(filecuts&& !filecuts->IsOpen())){
      AliFatal("Input file not found : check your cut object");
    }
  }

  //Analysis Task
  AliRDHFCuts *analysiscuts=0x0;

  TString Name="";
  if(pdgMeson==411){
    if(stdcuts) {
      analysiscuts = new AliRDHFCutsDplustoKpipi();
      if (system == 0) analysiscuts->SetStandardCutsPP2010();
      else analysiscuts->SetStandardCutsPbPb2011();
    }
    else analysiscuts = (AliRDHFCutsDplustoKpipi*)filecuts->Get(finAnObjname);
    Name="Dplus";
   }else if(pdgMeson==421){
    if(stdcuts) {
      analysiscuts = new AliRDHFCutsD0toKpi();
      if (system == 0) analysiscuts->SetStandardCutsPP2010();
      else analysiscuts->SetStandardCutsPbPb2011();
    }
    else analysiscuts = (AliRDHFCutsD0toKpi*)filecuts->Get(finAnObjname);
    Name="D0";
  }else if(pdgMeson==413){
    if(stdcuts) {
      analysiscuts = new AliRDHFCutsDStartoKpipi();
      if (system == 0) analysiscuts->SetStandardCutsPP2010();
      else analysiscuts->SetStandardCutsPbPb2011();
    }
    else analysiscuts = (AliRDHFCutsDStartoKpipi*)filecuts->Get(finAnObjname);
    Name="DStar";
  }

  AliAnalysisTaskSEDvsMultiplicity *dMultTask = new AliAnalysisTaskSEDvsMultiplicity("dMultAnalysis",pdgMeson,analysiscuts);
  dMultTask->SetReadMC(readMC);
  dMultTask->SetDebugLevel(0);
  dMultTask->SetUseBit(kTRUE);
  dMultTask->SetDoImpactParameterHistos(kFALSE);

  if(pdgMeson==421) {
    dMultTask->SetMassLimits(1.5648,2.1648);
    dMultTask->SetMassBins(300);
  }else if(pdgmeson==411)dMultTask->SetMassLimits(pdgmeson,0.2);

  if(estimatorFilename.EqualTo("") ) {
    printf("Estimator file not provided, multiplcity corrected histograms will not be filled\n");
  } else{
    const Char_t* periodNames[4] = {"LHC10b", "LHC10c", "LHC10d", "LHC10e"};
    TProfile* multEstimatorAvg[4];
    TFile* fileEstimator=TFile::Open(estimatorFilename.Data());
    if(!fileEstimator)  {
      AliFatal("File with multiplicity estimator not found\n");
      return;
    }
    for(Int_t ip=0; ip<4; ip++) {
      multEstimatorAvg[ip] = (TProfile*)(fileEstimator->Get(Form("SPDmult10_%s",periodNames[ip]))->Clone(Form("SPDmult10_%s_clone",periodNames[ip])));
    }
    dMultTask->SetMultiplVsZProfileLHC10b(multEstimatorAvg[0]);
    dMultTask->SetMultiplVsZProfileLHC10c(multEstimatorAvg[1]);
    dMultTask->SetMultiplVsZProfileLHC10d(multEstimatorAvg[2]);
    dMultTask->SetMultiplVsZProfileLHC10e(multEstimatorAvg[3]);
  }
  mgr->AddTask(dMultTask);

  // Create containers for input/output

  TString inname = "cinput";
  TString outname = "coutput";
  TString cutsname = "coutputCuts";
  TString normname = "coutputNorm";

  inname += Name.Data();
  outname += Name.Data();
  cutsname += Name.Data();
  normname += Name.Data();
  inname += finDirname.Data();
  outname += finDirname.Data();
  cutsname += finDirname.Data();
  normname += finDirname.Data();

  AliAnalysisDataContainer *cinput = mgr->CreateContainer(inname,TChain::Class(),AliAnalysisManager::kInputContainer);

  TString outputfile = AliAnalysisManager::GetCommonFileName();
  outputfile += ":PWG3_D2H_DMult_";
  outputfile += Name.Data();
  outputfile += finDirname.Data();

  AliAnalysisDataContainer *coutputCuts = mgr->CreateContainer(cutsname,TList::Class(),AliAnalysisManager::kOutputContainer,outputfile.Data());
  AliAnalysisDataContainer *coutput = mgr->CreateContainer(outname,TList::Class(),AliAnalysisManager::kOutputContainer,outputfile.Data());
  AliAnalysisDataContainer *coutputNorm = mgr->CreateContainer(normname,TList::Class(),AliAnalysisManager::kOutputContainer,outputfile.Data());

  mgr->ConnectInput(dMultTask,0,mgr->GetCommonInputContainer());

  mgr->ConnectOutput(dMultTask,1,coutput);

  mgr->ConnectOutput(dMultTask,2,coutputCuts);

  mgr->ConnectOutput(dMultTask,3,coutputNorm);

  return dMultTask;
}
<commit_msg>Fix typo<commit_after>AliAnalysisTaskSEDvsMultiplicity *AddTaskDvsMultiplicity(Int_t system=0,
							 Bool_t readMC=kFALSE,
							 Int_t MCOption=0,
							 Int_t pdgMeson=411,
							 TString finDirname="Loose",
							 TString filename="",
							 TString finAnObjname="AnalysisCuts",
							 TString estimatorFilename="")
{
  //
  // Test macro for the AliAnalysisTaskSE for D+ candidates
  //Invariant mass histogram and
  // association with MC truth (using MC info in AOD)
  //  R. Bala, bala@to.infn.it
  // Get the pointer to the existing analysis manager via the static access method.
  //==============================================================================

  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    ::Error("AddTaskDvsMultiplicity", "No analysis manager to connect to.");
  }

  Bool_t stdcuts=kFALSE;
  TFile* filecuts;
  if( filename.EqualTo("") ) {
    stdcuts=kTRUE;
  } else {
    filecuts=TFile::Open(filename.Data());
    if(!filecuts ||(filecuts&& !filecuts->IsOpen())){
      AliFatal("Input file not found : check your cut object");
    }
  }

  //Analysis Task
  AliRDHFCuts *analysiscuts=0x0;

  TString Name="";
  if(pdgMeson==411){
    if(stdcuts) {
      analysiscuts = new AliRDHFCutsDplustoKpipi();
      if (system == 0) analysiscuts->SetStandardCutsPP2010();
      else analysiscuts->SetStandardCutsPbPb2011();
    }
    else analysiscuts = (AliRDHFCutsDplustoKpipi*)filecuts->Get(finAnObjname);
    Name="Dplus";
   }else if(pdgMeson==421){
    if(stdcuts) {
      analysiscuts = new AliRDHFCutsD0toKpi();
      if (system == 0) analysiscuts->SetStandardCutsPP2010();
      else analysiscuts->SetStandardCutsPbPb2011();
    }
    else analysiscuts = (AliRDHFCutsD0toKpi*)filecuts->Get(finAnObjname);
    Name="D0";
  }else if(pdgMeson==413){
    if(stdcuts) {
      analysiscuts = new AliRDHFCutsDStartoKpipi();
      if (system == 0) analysiscuts->SetStandardCutsPP2010();
      else analysiscuts->SetStandardCutsPbPb2011();
    }
    else analysiscuts = (AliRDHFCutsDStartoKpipi*)filecuts->Get(finAnObjname);
    Name="DStar";
  }

  AliAnalysisTaskSEDvsMultiplicity *dMultTask = new AliAnalysisTaskSEDvsMultiplicity("dMultAnalysis",pdgMeson,analysiscuts);
  dMultTask->SetReadMC(readMC);
  dMultTask->SetDebugLevel(0);
  dMultTask->SetUseBit(kTRUE);
  dMultTask->SetDoImpactParameterHistos(kFALSE);

  if(pdgMeson==421) {
    dMultTask->SetMassLimits(1.5648,2.1648);
    dMultTask->SetMassBins(300);
  }else if(pdgMeson==411)dMultTask->SetMassLimits(pdgMeson,0.2);

  if(estimatorFilename.EqualTo("") ) {
    printf("Estimator file not provided, multiplcity corrected histograms will not be filled\n");
  } else{
    const Char_t* periodNames[4] = {"LHC10b", "LHC10c", "LHC10d", "LHC10e"};
    TProfile* multEstimatorAvg[4];
    TFile* fileEstimator=TFile::Open(estimatorFilename.Data());
    if(!fileEstimator)  {
      AliFatal("File with multiplicity estimator not found\n");
      return;
    }
    for(Int_t ip=0; ip<4; ip++) {
      multEstimatorAvg[ip] = (TProfile*)(fileEstimator->Get(Form("SPDmult10_%s",periodNames[ip]))->Clone(Form("SPDmult10_%s_clone",periodNames[ip])));
    }
    dMultTask->SetMultiplVsZProfileLHC10b(multEstimatorAvg[0]);
    dMultTask->SetMultiplVsZProfileLHC10c(multEstimatorAvg[1]);
    dMultTask->SetMultiplVsZProfileLHC10d(multEstimatorAvg[2]);
    dMultTask->SetMultiplVsZProfileLHC10e(multEstimatorAvg[3]);
  }
  mgr->AddTask(dMultTask);

  // Create containers for input/output

  TString inname = "cinput";
  TString outname = "coutput";
  TString cutsname = "coutputCuts";
  TString normname = "coutputNorm";

  inname += Name.Data();
  outname += Name.Data();
  cutsname += Name.Data();
  normname += Name.Data();
  inname += finDirname.Data();
  outname += finDirname.Data();
  cutsname += finDirname.Data();
  normname += finDirname.Data();

  AliAnalysisDataContainer *cinput = mgr->CreateContainer(inname,TChain::Class(),AliAnalysisManager::kInputContainer);

  TString outputfile = AliAnalysisManager::GetCommonFileName();
  outputfile += ":PWG3_D2H_DMult_";
  outputfile += Name.Data();
  outputfile += finDirname.Data();

  AliAnalysisDataContainer *coutputCuts = mgr->CreateContainer(cutsname,TList::Class(),AliAnalysisManager::kOutputContainer,outputfile.Data());
  AliAnalysisDataContainer *coutput = mgr->CreateContainer(outname,TList::Class(),AliAnalysisManager::kOutputContainer,outputfile.Data());
  AliAnalysisDataContainer *coutputNorm = mgr->CreateContainer(normname,TList::Class(),AliAnalysisManager::kOutputContainer,outputfile.Data());

  mgr->ConnectInput(dMultTask,0,mgr->GetCommonInputContainer());

  mgr->ConnectOutput(dMultTask,1,coutput);

  mgr->ConnectOutput(dMultTask,2,coutputCuts);

  mgr->ConnectOutput(dMultTask,3,coutputNorm);

  return dMultTask;
}
<|endoftext|>


<commit_before>/*************************************************************************/
/*  editor_run_native.cpp                                                */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                      https://godotengine.org                          */
/*************************************************************************/
/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur.                 */
/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md)    */
/*                                                                       */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the       */
/* "Software"), to deal in the Software without restriction, including   */
/* without limitation the rights to use, copy, modify, merge, publish,   */
/* distribute, sublicense, and/or sell copies of the Software, and to    */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions:                                             */
/*                                                                       */
/* The above copyright notice and this permission notice shall be        */
/* included in all copies or substantial portions of the Software.       */
/*                                                                       */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
/*************************************************************************/

#include "editor_run_native.h"

#include "editor_export.h"
#include "editor_node.h"

void EditorRunNative::_notification(int p_what) {

	if (p_what == NOTIFICATION_ENTER_TREE) {

		for (int i = 0; i < EditorExport::get_singleton()->get_export_platform_count(); i++) {

			Ref<EditorExportPlatform> eep = EditorExport::get_singleton()->get_export_platform(i);
			if (eep.is_null())
				continue;
			Ref<ImageTexture> icon = eep->get_run_icon();
			if (!icon.is_null()) {
				Ref<Image> im = icon->get_data();
				im = im->duplicate();
				im->clear_mipmaps();
				if (!im->empty()) {

					im->resize(16, 16);
					Ref<ImageTexture> small_icon;
					small_icon.instance();
					small_icon->create_from_image(im, 0);
					MenuButton *mb = memnew(MenuButton);
					mb->get_popup()->connect("id_pressed", this, "_run_native", varray(i));
					//mb->connect("pressed", this, "_run_native", varray(-1, i));
					mb->set_icon(small_icon);
					add_child(mb);
					menus[i] = mb;
				}
			}
		}
	}

	if (p_what == NOTIFICATION_PROCESS) {

		bool changed = EditorExport::get_singleton()->poll_export_platforms() || first;

		if (changed) {

			for (Map<int, MenuButton *>::Element *E = menus.front(); E; E = E->next()) {

				Ref<EditorExportPlatform> eep = EditorExport::get_singleton()->get_export_platform(E->key());
				MenuButton *mb = E->get();
				int dc = eep->get_device_count();

				if (dc == 0) {
					mb->hide();
				} else {
					mb->get_popup()->clear();
					mb->show();
					mb->set_tooltip(TTR("Select device from the list"));
					for (int i = 0; i < dc; i++) {
						mb->get_popup()->add_icon_item(get_icon("Play", "EditorIcons"), eep->get_device_name(i));
						mb->get_popup()->set_item_tooltip(mb->get_popup()->get_item_count() - 1, eep->get_device_info(i).strip_edges());
					}
				}
			}

			first = false;
		}
	}
}

void EditorRunNative::_run_native(int p_idx, int p_platform) {

	Ref<EditorExportPlatform> eep = EditorExport::get_singleton()->get_export_platform(p_platform);
	ERR_FAIL_COND(eep.is_null());
	/*if (p_idx == -1) {
		if (eep->get_device_count() == 1) {
			menus[p_platform]->get_popup()->hide();
			p_idx = 0;
		} else {
			return;
		}
	}*/

	Ref<EditorExportPreset> preset;

	for (int i = 0; i < EditorExport::get_singleton()->get_export_preset_count(); i++) {

		Ref<EditorExportPreset> ep = EditorExport::get_singleton()->get_export_preset(i);
		if (ep->is_runnable() && ep->get_platform() == eep) {
			preset = ep;
			break;
		}
	}

	if (preset.is_null()) {
		EditorNode::get_singleton()->show_warning(TTR("No runnable export preset found for this platform.\nPlease add a runnable preset in the export menu."));
		return;
	}

	emit_signal("native_run");

	int flags = 0;
	if (deploy_debug_remote)
		flags |= EditorExportPlatform::DEBUG_FLAG_REMOTE_DEBUG;
	if (deploy_dumb)
		flags |= EditorExportPlatform::DEBUG_FLAG_DUMB_CLIENT;
	if (debug_collisions)
		flags |= EditorExportPlatform::DEBUG_FLAG_VIEW_COLLISONS;
	if (debug_navigation)
		flags |= EditorExportPlatform::DEBUG_FLAG_VIEW_NAVIGATION;

	eep->run(preset, p_idx, flags);
}

void EditorRunNative::_bind_methods() {

	ClassDB::bind_method("_run_native", &EditorRunNative::_run_native);

	ADD_SIGNAL(MethodInfo("native_run"));
}

void EditorRunNative::set_deploy_dumb(bool p_enabled) {

	deploy_dumb = p_enabled;
}

bool EditorRunNative::is_deploy_dumb_enabled() const {

	return deploy_dumb;
}

void EditorRunNative::set_deploy_debug_remote(bool p_enabled) {

	deploy_debug_remote = p_enabled;
}

bool EditorRunNative::is_deploy_debug_remote_enabled() const {

	return deploy_debug_remote;
}

void EditorRunNative::set_debug_collisions(bool p_debug) {

	debug_collisions = p_debug;
}

bool EditorRunNative::get_debug_collisions() const {

	return debug_collisions;
}

void EditorRunNative::set_debug_navigation(bool p_debug) {

	debug_navigation = p_debug;
}

bool EditorRunNative::get_debug_navigation() const {

	return debug_navigation;
}

EditorRunNative::EditorRunNative() {
	set_process(true);
	first = true;
	deploy_dumb = false;
	deploy_debug_remote = false;
	debug_collisions = false;
	debug_navigation = false;
}
<commit_msg>Resize native run button according to editor scale.<commit_after>/*************************************************************************/
/*  editor_run_native.cpp                                                */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                      https://godotengine.org                          */
/*************************************************************************/
/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur.                 */
/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md)    */
/*                                                                       */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the       */
/* "Software"), to deal in the Software without restriction, including   */
/* without limitation the rights to use, copy, modify, merge, publish,   */
/* distribute, sublicense, and/or sell copies of the Software, and to    */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions:                                             */
/*                                                                       */
/* The above copyright notice and this permission notice shall be        */
/* included in all copies or substantial portions of the Software.       */
/*                                                                       */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
/*************************************************************************/

#include "editor_run_native.h"

#include "editor_export.h"
#include "editor_node.h"
#include "editor_scale.h"

void EditorRunNative::_notification(int p_what) {

	if (p_what == NOTIFICATION_ENTER_TREE) {

		for (int i = 0; i < EditorExport::get_singleton()->get_export_platform_count(); i++) {

			Ref<EditorExportPlatform> eep = EditorExport::get_singleton()->get_export_platform(i);
			if (eep.is_null())
				continue;
			Ref<ImageTexture> icon = eep->get_run_icon();
			if (!icon.is_null()) {
				Ref<Image> im = icon->get_data();
				im = im->duplicate();
				im->clear_mipmaps();
				if (!im->empty()) {

					im->resize(16 * EDSCALE, 16 * EDSCALE);
					Ref<ImageTexture> small_icon;
					small_icon.instance();
					small_icon->create_from_image(im, 0);
					MenuButton *mb = memnew(MenuButton);
					mb->get_popup()->connect("id_pressed", this, "_run_native", varray(i));
					//mb->connect("pressed", this, "_run_native", varray(-1, i));
					mb->set_icon(small_icon);
					add_child(mb);
					menus[i] = mb;
				}
			}
		}
	}

	if (p_what == NOTIFICATION_PROCESS) {

		bool changed = EditorExport::get_singleton()->poll_export_platforms() || first;

		if (changed) {

			for (Map<int, MenuButton *>::Element *E = menus.front(); E; E = E->next()) {

				Ref<EditorExportPlatform> eep = EditorExport::get_singleton()->get_export_platform(E->key());
				MenuButton *mb = E->get();
				int dc = eep->get_device_count();

				if (dc == 0) {
					mb->hide();
				} else {
					mb->get_popup()->clear();
					mb->show();
					mb->set_tooltip(TTR("Select device from the list"));
					for (int i = 0; i < dc; i++) {
						mb->get_popup()->add_icon_item(get_icon("Play", "EditorIcons"), eep->get_device_name(i));
						mb->get_popup()->set_item_tooltip(mb->get_popup()->get_item_count() - 1, eep->get_device_info(i).strip_edges());
					}
				}
			}

			first = false;
		}
	}
}

void EditorRunNative::_run_native(int p_idx, int p_platform) {

	Ref<EditorExportPlatform> eep = EditorExport::get_singleton()->get_export_platform(p_platform);
	ERR_FAIL_COND(eep.is_null());
	/*if (p_idx == -1) {
		if (eep->get_device_count() == 1) {
			menus[p_platform]->get_popup()->hide();
			p_idx = 0;
		} else {
			return;
		}
	}*/

	Ref<EditorExportPreset> preset;

	for (int i = 0; i < EditorExport::get_singleton()->get_export_preset_count(); i++) {

		Ref<EditorExportPreset> ep = EditorExport::get_singleton()->get_export_preset(i);
		if (ep->is_runnable() && ep->get_platform() == eep) {
			preset = ep;
			break;
		}
	}

	if (preset.is_null()) {
		EditorNode::get_singleton()->show_warning(TTR("No runnable export preset found for this platform.\nPlease add a runnable preset in the export menu."));
		return;
	}

	emit_signal("native_run");

	int flags = 0;
	if (deploy_debug_remote)
		flags |= EditorExportPlatform::DEBUG_FLAG_REMOTE_DEBUG;
	if (deploy_dumb)
		flags |= EditorExportPlatform::DEBUG_FLAG_DUMB_CLIENT;
	if (debug_collisions)
		flags |= EditorExportPlatform::DEBUG_FLAG_VIEW_COLLISONS;
	if (debug_navigation)
		flags |= EditorExportPlatform::DEBUG_FLAG_VIEW_NAVIGATION;

	eep->run(preset, p_idx, flags);
}

void EditorRunNative::_bind_methods() {

	ClassDB::bind_method("_run_native", &EditorRunNative::_run_native);

	ADD_SIGNAL(MethodInfo("native_run"));
}

void EditorRunNative::set_deploy_dumb(bool p_enabled) {

	deploy_dumb = p_enabled;
}

bool EditorRunNative::is_deploy_dumb_enabled() const {

	return deploy_dumb;
}

void EditorRunNative::set_deploy_debug_remote(bool p_enabled) {

	deploy_debug_remote = p_enabled;
}

bool EditorRunNative::is_deploy_debug_remote_enabled() const {

	return deploy_debug_remote;
}

void EditorRunNative::set_debug_collisions(bool p_debug) {

	debug_collisions = p_debug;
}

bool EditorRunNative::get_debug_collisions() const {

	return debug_collisions;
}

void EditorRunNative::set_debug_navigation(bool p_debug) {

	debug_navigation = p_debug;
}

bool EditorRunNative::get_debug_navigation() const {

	return debug_navigation;
}

EditorRunNative::EditorRunNative() {
	set_process(true);
	first = true;
	deploy_dumb = false;
	deploy_debug_remote = false;
	debug_collisions = false;
	debug_navigation = false;
}
<|endoftext|>