<commit_before>/*
 * Copyright (C) 2005-2020 Centre National d'Etudes Spatiales (CNES)
 *
 * This file is part of Orfeo Toolbox
 *
 *     https://www.orfeo-toolbox.org/
 *
 * 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.
 */

#ifndef otbDEMToImageGenerator_hxx
#define otbDEMToImageGenerator_hxx

#include "otbDEMToImageGenerator.h"
#include "otbMacro.h"
#include "itkProgressReporter.h"

namespace otb
{

template <class TDEMImage>
DEMToImageGenerator<TDEMImage>::DEMToImageGenerator()
{
  m_OutputSpacing[0]    = 0.0001;
  m_OutputSpacing[1]    = -0.0001;
  m_OutputSize[0]       = 1;
  m_OutputSize[1]       = 1;
  m_OutputOrigin[0]     = 0;
  m_OutputOrigin[1]     = 0;
  m_DefaultUnknownValue = itk::NumericTraits<PixelType>::ZeroValue();
  m_AboveEllipsoid      = false;

  m_Transform = GenericRSTransformType::New();
}

// GenerateOutputInformation method
template <class TDEMImage>
void DEMToImageGenerator<TDEMImage>::GenerateOutputInformation()
{
  DEMImageType* output;
  output = this->GetOutput(0);

  IndexType start;
  start[0] = 0;
  start[1] = 0;

  // Specify region parameters
  OutputImageRegionType largestPossibleRegion;
  largestPossibleRegion.SetSize(m_OutputSize);
  largestPossibleRegion.SetIndex(start);

  output->SetLargestPossibleRegion(largestPossibleRegion);
  output->SetSignedSpacing(m_OutputSpacing);
  output->SetOrigin(m_OutputOrigin);

  // Add the metadata set by the user to the output
  output->m_Imd.Add(MDGeom::ProjectionProj, m_Transform->GetInputProjectionRef());
  if (m_Transform->GetInputImageMetadata() != nullptr)
    output->m_Imd.Merge(*m_Transform->GetInputImageMetadata());
}

// InstantiateTransform method
template <class TDEMImage>
void DEMToImageGenerator<TDEMImage>::InstantiateTransform()
{
  m_Transform->InstantiateTransform();
}

template <class TDEMImage>
void DEMToImageGenerator<TDEMImage>::BeforeThreadedGenerateData()
{
  InstantiateTransform();
  DEMImagePointerType DEMImage = this->GetOutput();

  // allocate the output buffer
  DEMImage->SetBufferedRegion(DEMImage->GetRequestedRegion());
  DEMImage->Allocate();
  DEMImage->FillBuffer(0);
}

template <class TDEMImage>
void DEMToImageGenerator<TDEMImage>::ThreadedGenerateData(const OutputImageRegionType& outputRegionForThread, itk::ThreadIdType threadId)
{
  DEMImagePointerType DEMImage = this->GetOutput();

  // Create an iterator that will walk the output region
  ImageIteratorType outIt = ImageIteratorType(DEMImage, outputRegionForThread);

  // support progress methods/callbacks
  itk::ProgressReporter progress(this, threadId, outputRegionForThread.GetNumberOfPixels());

  // Walk the output image, evaluating the height at each pixel
  IndexType currentindex;
  PointType phyPoint;
  double    height;
  PointType geoPoint;

  for (outIt.GoToBegin(); !outIt.IsAtEnd(); ++outIt)
  {
    currentindex = outIt.GetIndex();
    DEMImage->TransformIndexToPhysicalPoint(currentindex, phyPoint);

    if (m_Transform.IsNotNull())
    {
      geoPoint = m_Transform->TransformPoint(phyPoint);
      if (m_AboveEllipsoid)
      {
        height = DEMHandler::GetInstance().GetHeightAboveEllipsoid(geoPoint); // Altitude
                                                                  // calculation
      }
      else
      {
        height = DEMHandler::GetInstance().GetHeightAboveMSL(geoPoint); // Altitude
                                                            // calculation
      }
    }
    else
    {
      if (m_AboveEllipsoid)
      {
        height = DEMHandler::GetInstance().GetHeightAboveEllipsoid(phyPoint); // Altitude
                                                                  // calculation
      }
      else
      {
        height = DEMHandler::GetInstance().GetHeightAboveMSL(phyPoint); // Altitude
                                                            // calculation
      }
    }
    /*    otbMsgDevMacro(<< "Index : (" << currentindex[0]<< "," << currentindex[1] << ") -> PhyPoint : ("
                       << phyPoint[0] << "," << phyPoint[1] << ") -> GeoPoint: ("
                       << geoPoint[0] << "," << geoPoint[1] << ") -> height" << height);
    */
    //       otbMsgDevMacro(<< "height" << height);
    // DEM sets a default value (-32768) at point where it doesn't have altitude information.
    // OSSIM has chosen to change this default value in OSSIM_DBL_NAN (-4.5036e15).
    if (!vnl_math_isnan(height))
    {
      // Fill the image
      DEMImage->SetPixel(currentindex, static_cast<PixelType>(height));
    }
    else
    {
      // Back to the MNT default value
      DEMImage->SetPixel(currentindex, m_DefaultUnknownValue);
    }
    progress.CompletedPixel();
  }
}

template <class TDEMImage>
void DEMToImageGenerator<TDEMImage>::PrintSelf(std::ostream& os, itk::Indent indent) const
{
  Superclass::PrintSelf(os, indent);

  os << indent << "Output Spacing:" << m_OutputSpacing[0] << "," << m_OutputSpacing[1] << std::endl;
  os << indent << "Output Origin:" << m_OutputOrigin[0] << "," << m_OutputOrigin[1] << std::endl;
  os << indent << "Output Size:" << m_OutputSize[0] << "," << m_OutputSize[1] << std::endl;
}

} // namespace otb

#endif
<commit_msg>FIX: Set ProjectionProj as std::string before storing as boost::any<commit_after>/*
 * Copyright (C) 2005-2020 Centre National d'Etudes Spatiales (CNES)
 *
 * This file is part of Orfeo Toolbox
 *
 *     https://www.orfeo-toolbox.org/
 *
 * 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.
 */

#ifndef otbDEMToImageGenerator_hxx
#define otbDEMToImageGenerator_hxx

#include "otbDEMToImageGenerator.h"
#include "otbMacro.h"
#include "itkProgressReporter.h"

namespace otb
{

template <class TDEMImage>
DEMToImageGenerator<TDEMImage>::DEMToImageGenerator()
{
  m_OutputSpacing[0]    = 0.0001;
  m_OutputSpacing[1]    = -0.0001;
  m_OutputSize[0]       = 1;
  m_OutputSize[1]       = 1;
  m_OutputOrigin[0]     = 0;
  m_OutputOrigin[1]     = 0;
  m_DefaultUnknownValue = itk::NumericTraits<PixelType>::ZeroValue();
  m_AboveEllipsoid      = false;

  m_Transform = GenericRSTransformType::New();
}

// GenerateOutputInformation method
template <class TDEMImage>
void DEMToImageGenerator<TDEMImage>::GenerateOutputInformation()
{
  DEMImageType* output = this->GetOutput(0);

  IndexType start;
  start[0] = 0;
  start[1] = 0;

  // Specify region parameters
  OutputImageRegionType largestPossibleRegion;
  largestPossibleRegion.SetSize(m_OutputSize);
  largestPossibleRegion.SetIndex(start);

  output->SetLargestPossibleRegion(largestPossibleRegion);
  output->SetSignedSpacing(m_OutputSpacing);
  output->SetOrigin(m_OutputOrigin);

  // Add the metadata set by the user to the output
  output->m_Imd.Add(MDGeom::ProjectionProj, std::string(m_Transform->GetInputProjectionRef()));
  if (m_Transform->GetInputImageMetadata() != nullptr)
    output->m_Imd.Merge(*m_Transform->GetInputImageMetadata());
}

// InstantiateTransform method
template <class TDEMImage>
void DEMToImageGenerator<TDEMImage>::InstantiateTransform()
{
  m_Transform->InstantiateTransform();
}

template <class TDEMImage>
void DEMToImageGenerator<TDEMImage>::BeforeThreadedGenerateData()
{
  InstantiateTransform();
  DEMImagePointerType DEMImage = this->GetOutput();

  // allocate the output buffer
  DEMImage->SetBufferedRegion(DEMImage->GetRequestedRegion());
  DEMImage->Allocate();
  DEMImage->FillBuffer(0);
}

template <class TDEMImage>
void DEMToImageGenerator<TDEMImage>::ThreadedGenerateData(const OutputImageRegionType& outputRegionForThread, itk::ThreadIdType threadId)
{
  DEMImagePointerType DEMImage = this->GetOutput();

  // Create an iterator that will walk the output region
  ImageIteratorType outIt = ImageIteratorType(DEMImage, outputRegionForThread);

  // support progress methods/callbacks
  itk::ProgressReporter progress(this, threadId, outputRegionForThread.GetNumberOfPixels());

  // Walk the output image, evaluating the height at each pixel
  IndexType currentindex;
  PointType phyPoint;
  double    height;
  PointType geoPoint;

  for (outIt.GoToBegin(); !outIt.IsAtEnd(); ++outIt)
  {
    currentindex = outIt.GetIndex();
    DEMImage->TransformIndexToPhysicalPoint(currentindex, phyPoint);

    if (m_Transform.IsNotNull())
    {
      geoPoint = m_Transform->TransformPoint(phyPoint);
      if (m_AboveEllipsoid)
      {
        height = DEMHandler::GetInstance().GetHeightAboveEllipsoid(geoPoint); // Altitude
                                                                  // calculation
      }
      else
      {
        height = DEMHandler::GetInstance().GetHeightAboveMSL(geoPoint); // Altitude
                                                            // calculation
      }
    }
    else
    {
      if (m_AboveEllipsoid)
      {
        height = DEMHandler::GetInstance().GetHeightAboveEllipsoid(phyPoint); // Altitude
                                                                  // calculation
      }
      else
      {
        height = DEMHandler::GetInstance().GetHeightAboveMSL(phyPoint); // Altitude
                                                            // calculation
      }
    }
    /*    otbMsgDevMacro(<< "Index : (" << currentindex[0]<< "," << currentindex[1] << ") -> PhyPoint : ("
                       << phyPoint[0] << "," << phyPoint[1] << ") -> GeoPoint: ("
                       << geoPoint[0] << "," << geoPoint[1] << ") -> height" << height);
    */
    //       otbMsgDevMacro(<< "height" << height);
    // DEM sets a default value (-32768) at point where it doesn't have altitude information.
    // OSSIM has chosen to change this default value in OSSIM_DBL_NAN (-4.5036e15).
    if (!vnl_math_isnan(height))
    {
      // Fill the image
      DEMImage->SetPixel(currentindex, static_cast<PixelType>(height));
    }
    else
    {
      // Back to the MNT default value
      DEMImage->SetPixel(currentindex, m_DefaultUnknownValue);
    }
    progress.CompletedPixel();
  }
}

template <class TDEMImage>
void DEMToImageGenerator<TDEMImage>::PrintSelf(std::ostream& os, itk::Indent indent) const
{
  Superclass::PrintSelf(os, indent);

  os << indent << "Output Spacing:" << m_OutputSpacing[0] << "," << m_OutputSpacing[1] << std::endl;
  os << indent << "Output Origin:" << m_OutputOrigin[0] << "," << m_OutputOrigin[1] << std::endl;
  os << indent << "Output Size:" << m_OutputSize[0] << "," << m_OutputSize[1] << std::endl;
}

} // namespace otb

#endif
<|endoftext|>


<commit_before>/*=========================================================================
 *
 *  Copyright Insight Software Consortium
 *
 *  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.txt
 *
 *  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.
 *
 *=========================================================================*/

//
//  This example illustrates how to read a DICOM series into a volume
//  and then save this volume into another DICOM series using the
//  exact same name.
//  It makes use of the GDCM library
//

#include "itkImageSeriesReader.h"
#include "itkImageSeriesWriter.h"
#include "itkRescaleIntensityImageFilter.h"
#include "itkGDCMImageIO.h"
#include "itkGDCMSeriesFileNames.h"

int itkGDCMSeriesReadImageWriteTest( int argc, char* argv[] )
{
  if( argc < 3 )
    {
    std::cerr << "Usage: " << argv[0] <<
      " DicomDirectory  outputFile OutputDicomDirectory" << std::endl;
    return EXIT_FAILURE;
    }

  typedef itk::Image<unsigned short,3>            ImageType;
  typedef itk::ImageSeriesReader< ImageType >     ReaderType;
  typedef itk::GDCMImageIO                        ImageIOType;
  typedef itk::GDCMSeriesFileNames                SeriesFileNames;

  ImageIOType::Pointer gdcmIO = ImageIOType::New();
  SeriesFileNames::Pointer it = SeriesFileNames::New();

  // Get the DICOM filenames from the directory
  // First add a restriction *before* selecting the input directory
  // since SetInputDirectory has a side effect of executing
  gdcm::SerieHelper *sh = it->GetSeriesHelper( );
  sh->AddRestriction(0x0010, 0x0010, "Wes Turner", gdcm::GDCM_EQUAL);
  sh->AddRestriction(0x0020, 0x0013, "75", gdcm::GDCM_GREATEROREQUAL);
  sh->AddRestriction(0x0020, 0x0013, "77", gdcm::GDCM_LESSOREQUAL);
  it->SetInputDirectory( argv[1] );

  ReaderType::Pointer reader = ReaderType::New();

  const ReaderType::FileNamesContainer & filenames = it->GetInputFileNames();
  unsigned int numberOfFilenames =  filenames.size();
  std::cout << numberOfFilenames << std::endl;
  for(unsigned int fni = 0; fni<numberOfFilenames; fni++)
    {
    std::cout << "filename # " << fni << " = ";
    std::cout << filenames[fni] << std::endl;
    }

  reader->SetFileNames( filenames );
  reader->SetImageIO( gdcmIO );

  try
    {
    reader->Update();
    }
  catch (itk::ExceptionObject &excp)
    {
    std::cerr << "Exception thrown while writing the image" << std::endl;
    std::cerr << excp << std::endl;

    return EXIT_FAILURE;
    }

  typedef itk::ImageFileWriter< ImageType > WriterType;
  WriterType::Pointer writer = WriterType::New();

  writer->SetFileName( argv[2] );
  writer->SetInput( reader->GetOutput() );

  try
    {
    writer->Update();
    }
  catch (itk::ExceptionObject &excp)
    {
    std::cerr << "Exception thrown while writing the image" << std::endl;
    std::cerr << excp << std::endl;

    return EXIT_FAILURE;
    }

  // Writing image afer downscaling to 8bits (unsigned char)

  typedef itk::Image< unsigned short, 3>            Image3DType;
  typedef itk::Image< unsigned char,  3>            RescaleImageType;
  typedef itk::Image< unsigned char,  2>            OutputImageType;
  typedef itk::RescaleIntensityImageFilter<
               Image3DType, RescaleImageType > RescaleFilterType;

  RescaleFilterType::Pointer rescaler = RescaleFilterType::New();
    rescaler->SetInput( reader->GetOutput() );
    rescaler->SetOutputMinimum(   0 );
    rescaler->SetOutputMaximum( 255 );

  typedef itk::ImageSeriesWriter< RescaleImageType, OutputImageType > SeriesWriterRescaleType;

  SeriesWriterRescaleType::Pointer swriter2 = SeriesWriterRescaleType::New();

  it->SetOutputDirectory( argv[3] );
  swriter2->SetInput( rescaler->GetOutput() );
  swriter2->SetImageIO( gdcmIO );

  swriter2->SetFileNames( it->GetOutputFileNames() );
  swriter2->SetMetaDataDictionaryArray( reader->GetMetaDataDictionaryArray() );

  try
    {
    swriter2->Update();
    }
  catch (itk::ExceptionObject & e)
    {
    std::cerr << "exception in file writer " << std::endl;
    std::cerr << e << std::endl;
    return EXIT_FAILURE;
    }
  return EXIT_SUCCESS;
}
<commit_msg>BUG: Set output type to unsigned char when writing uchar in GDCMIO test.<commit_after>/*=========================================================================
 *
 *  Copyright Insight Software Consortium
 *
 *  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.txt
 *
 *  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.
 *
 *=========================================================================*/

//
//  This example illustrates how to read a DICOM series into a volume
//  and then save this volume into another DICOM series using the
//  exact same name.
//  It makes use of the GDCM library
//

#include "itkImageSeriesReader.h"
#include "itkImageSeriesWriter.h"
#include "itkRescaleIntensityImageFilter.h"
#include "itkGDCMImageIO.h"
#include "itkGDCMSeriesFileNames.h"

int itkGDCMSeriesReadImageWriteTest( int argc, char* argv[] )
{
  if( argc < 3 )
    {
    std::cerr << "Usage: " << argv[0] <<
      " DicomDirectory  outputFile OutputDicomDirectory" << std::endl;
    return EXIT_FAILURE;
    }

  typedef itk::Image<unsigned short,3>            ImageType;
  typedef itk::ImageSeriesReader< ImageType >     ReaderType;
  typedef itk::GDCMImageIO                        ImageIOType;
  typedef itk::GDCMSeriesFileNames                SeriesFileNames;

  ImageIOType::Pointer gdcmIO = ImageIOType::New();
  SeriesFileNames::Pointer it = SeriesFileNames::New();

  // Get the DICOM filenames from the directory
  // First add a restriction *before* selecting the input directory
  // since SetInputDirectory has a side effect of executing
  gdcm::SerieHelper *sh = it->GetSeriesHelper( );
  sh->AddRestriction(0x0010, 0x0010, "Wes Turner", gdcm::GDCM_EQUAL);
  sh->AddRestriction(0x0020, 0x0013, "75", gdcm::GDCM_GREATEROREQUAL);
  sh->AddRestriction(0x0020, 0x0013, "77", gdcm::GDCM_LESSOREQUAL);
  it->SetInputDirectory( argv[1] );

  ReaderType::Pointer reader = ReaderType::New();

  const ReaderType::FileNamesContainer & filenames = it->GetInputFileNames();
  unsigned int numberOfFilenames =  filenames.size();
  std::cout << numberOfFilenames << std::endl;
  for(unsigned int fni = 0; fni<numberOfFilenames; fni++)
    {
    std::cout << "filename # " << fni << " = ";
    std::cout << filenames[fni] << std::endl;
    }

  reader->SetFileNames( filenames );
  reader->SetImageIO( gdcmIO );

  try
    {
    reader->Update();
    }
  catch (itk::ExceptionObject &excp)
    {
    std::cerr << "Exception thrown while writing the image" << std::endl;
    std::cerr << excp << std::endl;

    return EXIT_FAILURE;
    }

  typedef itk::ImageFileWriter< ImageType > WriterType;
  WriterType::Pointer writer = WriterType::New();

  writer->SetFileName( argv[2] );
  writer->SetInput( reader->GetOutput() );

  try
    {
    writer->Update();
    }
  catch (itk::ExceptionObject &excp)
    {
    std::cerr << "Exception thrown while writing the image" << std::endl;
    std::cerr << excp << std::endl;

    return EXIT_FAILURE;
    }

  // Writing image afer downscaling to 8bits (unsigned char)

  typedef itk::Image< unsigned short, 3>            Image3DType;
  typedef itk::Image< unsigned char,  3>            RescaleImageType;
  typedef itk::Image< unsigned char,  2>            OutputImageType;
  typedef itk::RescaleIntensityImageFilter<
               Image3DType, RescaleImageType > RescaleFilterType;

  RescaleFilterType::Pointer rescaler = RescaleFilterType::New();
    rescaler->SetInput( reader->GetOutput() );
    rescaler->SetOutputMinimum(   0 );
    rescaler->SetOutputMaximum( 255 );

  typedef itk::ImageSeriesWriter< RescaleImageType, OutputImageType > SeriesWriterRescaleType;

  SeriesWriterRescaleType::Pointer swriter2 = SeriesWriterRescaleType::New();

  it->SetOutputDirectory( argv[3] );
  swriter2->SetInput( rescaler->GetOutput() );
  swriter2->SetImageIO( gdcmIO );
  gdcmIO->SetInternalComponentType( itk::ImageIOBase::UCHAR );

  swriter2->SetFileNames( it->GetOutputFileNames() );
  swriter2->SetMetaDataDictionaryArray( reader->GetMetaDataDictionaryArray() );

  try
    {
    swriter2->Update();
    }
  catch (itk::ExceptionObject & e)
    {
    std::cerr << "exception in file writer " << std::endl;
    std::cerr << e << std::endl;
    return EXIT_FAILURE;
    }
  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: options.cxx,v $
 * $Revision: 1.17 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_idlc.hxx"

#include <stdio.h>
#include /*MSVC trouble: <cstring>*/ <string.h>
#include <idlc/options.hxx>

using namespace rtl;

Options::Options(): m_stdin(false)
{
}

Options::~Options()
{
}

sal_Bool Options::initOptions(int ac, char* av[], sal_Bool bCmdFile)
    throw( IllegalArgument )
{
    sal_Bool    ret = sal_True;
    sal_uInt16  j=0;

    if (!bCmdFile)
    {
        bCmdFile = sal_True;

        m_program = av[0];

        if (ac < 2)
        {
            fprintf(stderr, "%s", prepareHelp().getStr());
            ret = sal_False;
        }

        j = 1;
    } else
    {
        j = 0;
    }

    char    *s=NULL;
    for (; j < ac; j++)
    {
        if (av[j][0] == '-')
        {
            switch (av[j][1])
            {
            case 'O':
                if (av[j][2] == '\0')
                {
                    if (j < ac - 1 && av[j+1][0] != '-')
                    {
                        j++;
                        s = av[j];
                    } else
                    {
                        OString tmp("'-O', please check");
                        if (j <= ac - 1)
                        {
                            tmp += " your input '" + OString(av[j+1]) + "'";
                        }

                        throw IllegalArgument(tmp);
                    }
                } else
                {
                    s = av[j] + 2;
                }

                m_options["-O"] = OString(s);
                break;
            case 'I':
            {
                if (av[j][2] == '\0')
                {
                    if (j < ac - 1 && av[j+1][0] != '-')
                    {
                        j++;
                        s = av[j];
                    } else
                    {
                        OString tmp("'-I', please check");
                        if (j <= ac - 1)
                        {
                            tmp += " your input '" + OString(av[j+1]) + "'";
                        }

                        throw IllegalArgument(tmp);
                    }
                } else
                {
                    s = av[j] + 2;
                }

                OString inc(s);
                if ( inc.indexOf(';') > 0 )
                {
                    OString tmp(s);
                    sal_Int32 nIndex = 0;
                    inc = OString();
                    do inc = inc + " -I\"" + tmp.getToken( 0, ';', nIndex ) +"\""; while( nIndex != -1 );
                } else
                    inc = OString("-I\"") + s + "\"";

                if (m_options.count("-I") > 0)
                {
                    OString tmp(m_options["-I"]);
                    tmp = tmp + " " + inc;
                    m_options["-I"] = tmp;
                } else
                {
                    m_options["-I"] = inc;
                }
            }
            break;
            case 'D':
                if (av[j][2] == '\0')
                {
                    if (j < ac - 1 && av[j+1][0] != '-')
                    {
                        j++;
                        s = av[j];
                    } else
                    {
                        OString tmp("'-D', please check");
                        if (j <= ac - 1)
                        {
                            tmp += " your input '" + OString(av[j+1]) + "'";
                        }

                        throw IllegalArgument(tmp);
                    }
                } else
                {
                    s = av[j];
                }

                if (m_options.count("-D") > 0)
                {
                    OString tmp(m_options["-D"]);
                    tmp = tmp + " " + s;
                    m_options["-D"] = tmp;
                } else
                    m_options["-D"] = OString(s);
                break;
            case 'C':
                if (av[j][2] != '\0')
                {
                    throw IllegalArgument(OString(av[j]) + ", please check your input");
                }
                if (m_options.count("-C") == 0)
                    m_options["-C"] = OString(av[j]);
                break;
            case 'c':
                if (av[j][2] == 'i' && av[j][3] == 'd' && av[j][4] == '\0')
                {
                    if (m_options.count("-cid") == 0)
                        m_options["-cid"] = OString(av[j]);
                } else
                    throw IllegalArgument(OString(av[j]) + ", please check your input");
                break;
            case 'w':
                if (av[j][2] == 'e' && av[j][3] == '\0') {
                    if (m_options.count("-we") == 0)
                        m_options["-we"] = OString(av[j]);
                } else {
                    if (av[j][2] == '\0') {
                        if (m_options.count("-w") == 0)
                            m_options["-w"] = OString(av[j]);
                    } else
                        throw IllegalArgument(OString(av[j]) + ", please check your input");
                }
                break;
            case 'h':
            case '?':
                if (av[j][2] != '\0')
                {
                    throw IllegalArgument(OString(av[j]) + ", please check your input");
                } else
                {
                    fprintf(stdout, "%s", prepareHelp().getStr());
                    exit(0);
                }
            case 's':
                if (/*MSVC trouble: std::*/strcmp(&av[j][2], "tdin") == 0)
                {
                    m_stdin = true;
                    break;
                }
                // fall through
            default:
                throw IllegalArgument("the option is unknown" + OString(av[j]));
            }
        } else
        {
            if (av[j][0] == '@')
            {
                FILE* cmdFile = fopen(av[j]+1, "r");
                  if( cmdFile == NULL )
                  {
                    fprintf(stderr, "%s", prepareHelp().getStr());
                    ret = sal_False;
                } else
                {
                    int rargc=0;
                    char* rargv[512];
                    char  buffer[512]="";

                    int i=0;
                    int found = 0;
                    char c;
                    while ( fscanf(cmdFile, "%c", &c) != EOF )
                    {
                        if (c=='\"') {
                            if (found) {
                                found=0;
                            } else {
                                found=1;
                                continue;
                            }
                        } else {
                            if (c!=13 && c!=10) {
                                if (found || c!=' ') {
                                    buffer[i++]=c;
                                    continue;
                                }
                            }
                            if (i==0)
                                continue;
                        }
                        buffer[i]='\0';
                        found=0;
                        i=0;
                        rargv[rargc]= strdup(buffer);
                        rargc++;
                        buffer[0]='\0';
                    }
                    if (buffer[0] != '\0') {
                        buffer[i]='\0';
                        rargv[rargc]= strdup(buffer);
                        rargc++;
                    }
                    fclose(cmdFile);

                    ret = initOptions(rargc, rargv, bCmdFile);

                    long ii = 0;
                    for (ii=0; ii < rargc; ii++)
                    {
                        free(rargv[ii]);
                    }
                }
            } else
            {
                OString name(av[j]);
                name = name.toAsciiLowerCase();
                if ( name.lastIndexOf(".idl") != (name.getLength() - 4) )
                {
                    throw IllegalArgument("'" + OString(av[j]) +
                        "' is not a valid input file, only '*.idl' files will be accepted");
                }
                m_inputFiles.push_back(av[j]);
            }
        }
    }

    return ret;
}

OString Options::prepareHelp()
{
    OString help("\nusing: ");
    help += m_program
        + " [-options] <file_1> ... <file_n> | @<filename> | -stdin\n";
    help += "    <file_n>    = file_n specifies one or more idl files.\n";
    help += "                  Only files with the extension '.idl' are valid.\n";
    help += "    @<filename> = filename specifies the name of a command file.\n";
    help += "    -stdin      = read idl file from standard input.\n";
    help += "  Options:\n";
    help += "    -O<path>    = path specifies the output directory.\n";
    help += "                  The generated output is a registry file with\n";
    help += "                  the same name as the idl input file (or 'stdin'\n";
    help += "                  for -stdin).\n";
    help += "    -I<path>    = path specifies a directory where include\n";
    help += "                  files will be searched by the preprocessor.\n";
    help += "                  Multiple directories can be combined with ';'.\n";
    help += "    -D<name>    = name defines a macro for the preprocessor.\n";
    help += "    -C          = generate complete type information, including\n";
    help += "                  documentation.\n";
    help += "    -cid        = check if identifiers fulfill the UNO naming\n";
    help += "                  requirements.\n";
    help += "    -w          = display warning messages.\n";
    help += "    -we         = treat warnings as errors.\n";
    help += "    -h|-?       = print this help message and exit.\n";
    help += prepareVersion();

    return help;
}

OString Options::prepareVersion()
{
    OString version("\nSun Microsystems (R) ");
    version += m_program + " Version 1.1\n\n";
    return version;
}

const OString& Options::getProgramName() const
{
    return m_program;
}

sal_uInt16 Options::getNumberOfOptions() const
{
    return (sal_uInt16)(m_options.size());
}

sal_Bool Options::isValid(const OString& option)
{
    return (m_options.count(option) > 0);
}

const OString Options::getOption(const OString& option)
    throw( IllegalArgument )
{
    if (m_options.count(option) > 0)
    {
        return m_options[option];
    } else
    {
        throw IllegalArgument("Option is not valid or currently not set.");
    }
}

const OptionMap& Options::getOptions()
{
    return m_options;
}
<commit_msg>INTEGRATION: CWS jsc21 (1.17.4); FILE MERGED 2008/06/20 11:12:53 jsc 1.17.4.1: #i86349# remove unused methods<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: options.cxx,v $
 * $Revision: 1.18 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_idlc.hxx"

#include <stdio.h>
#include /*MSVC trouble: <cstring>*/ <string.h>
#include <idlc/options.hxx>

using namespace rtl;

Options::Options(): m_stdin(false)
{
}

Options::~Options()
{
}

sal_Bool Options::initOptions(int ac, char* av[], sal_Bool bCmdFile)
    throw( IllegalArgument )
{
    sal_Bool    ret = sal_True;
    sal_uInt16  j=0;

    if (!bCmdFile)
    {
        bCmdFile = sal_True;

        m_program = av[0];

        if (ac < 2)
        {
            fprintf(stderr, "%s", prepareHelp().getStr());
            ret = sal_False;
        }

        j = 1;
    } else
    {
        j = 0;
    }

    char    *s=NULL;
    for (; j < ac; j++)
    {
        if (av[j][0] == '-')
        {
            switch (av[j][1])
            {
            case 'O':
                if (av[j][2] == '\0')
                {
                    if (j < ac - 1 && av[j+1][0] != '-')
                    {
                        j++;
                        s = av[j];
                    } else
                    {
                        OString tmp("'-O', please check");
                        if (j <= ac - 1)
                        {
                            tmp += " your input '" + OString(av[j+1]) + "'";
                        }

                        throw IllegalArgument(tmp);
                    }
                } else
                {
                    s = av[j] + 2;
                }

                m_options["-O"] = OString(s);
                break;
            case 'I':
            {
                if (av[j][2] == '\0')
                {
                    if (j < ac - 1 && av[j+1][0] != '-')
                    {
                        j++;
                        s = av[j];
                    } else
                    {
                        OString tmp("'-I', please check");
                        if (j <= ac - 1)
                        {
                            tmp += " your input '" + OString(av[j+1]) + "'";
                        }

                        throw IllegalArgument(tmp);
                    }
                } else
                {
                    s = av[j] + 2;
                }

                OString inc(s);
                if ( inc.indexOf(';') > 0 )
                {
                    OString tmp(s);
                    sal_Int32 nIndex = 0;
                    inc = OString();
                    do inc = inc + " -I\"" + tmp.getToken( 0, ';', nIndex ) +"\""; while( nIndex != -1 );
                } else
                    inc = OString("-I\"") + s + "\"";

                if (m_options.count("-I") > 0)
                {
                    OString tmp(m_options["-I"]);
                    tmp = tmp + " " + inc;
                    m_options["-I"] = tmp;
                } else
                {
                    m_options["-I"] = inc;
                }
            }
            break;
            case 'D':
                if (av[j][2] == '\0')
                {
                    if (j < ac - 1 && av[j+1][0] != '-')
                    {
                        j++;
                        s = av[j];
                    } else
                    {
                        OString tmp("'-D', please check");
                        if (j <= ac - 1)
                        {
                            tmp += " your input '" + OString(av[j+1]) + "'";
                        }

                        throw IllegalArgument(tmp);
                    }
                } else
                {
                    s = av[j];
                }

                if (m_options.count("-D") > 0)
                {
                    OString tmp(m_options["-D"]);
                    tmp = tmp + " " + s;
                    m_options["-D"] = tmp;
                } else
                    m_options["-D"] = OString(s);
                break;
            case 'C':
                if (av[j][2] != '\0')
                {
                    throw IllegalArgument(OString(av[j]) + ", please check your input");
                }
                if (m_options.count("-C") == 0)
                    m_options["-C"] = OString(av[j]);
                break;
            case 'c':
                if (av[j][2] == 'i' && av[j][3] == 'd' && av[j][4] == '\0')
                {
                    if (m_options.count("-cid") == 0)
                        m_options["-cid"] = OString(av[j]);
                } else
                    throw IllegalArgument(OString(av[j]) + ", please check your input");
                break;
            case 'w':
                if (av[j][2] == 'e' && av[j][3] == '\0') {
                    if (m_options.count("-we") == 0)
                        m_options["-we"] = OString(av[j]);
                } else {
                    if (av[j][2] == '\0') {
                        if (m_options.count("-w") == 0)
                            m_options["-w"] = OString(av[j]);
                    } else
                        throw IllegalArgument(OString(av[j]) + ", please check your input");
                }
                break;
            case 'h':
            case '?':
                if (av[j][2] != '\0')
                {
                    throw IllegalArgument(OString(av[j]) + ", please check your input");
                } else
                {
                    fprintf(stdout, "%s", prepareHelp().getStr());
                    exit(0);
                }
            case 's':
                if (/*MSVC trouble: std::*/strcmp(&av[j][2], "tdin") == 0)
                {
                    m_stdin = true;
                    break;
                }
                // fall through
            default:
                throw IllegalArgument("the option is unknown" + OString(av[j]));
            }
        } else
        {
            if (av[j][0] == '@')
            {
                FILE* cmdFile = fopen(av[j]+1, "r");
                  if( cmdFile == NULL )
                  {
                    fprintf(stderr, "%s", prepareHelp().getStr());
                    ret = sal_False;
                } else
                {
                    int rargc=0;
                    char* rargv[512];
                    char  buffer[512]="";

                    int i=0;
                    int found = 0;
                    char c;
                    while ( fscanf(cmdFile, "%c", &c) != EOF )
                    {
                        if (c=='\"') {
                            if (found) {
                                found=0;
                            } else {
                                found=1;
                                continue;
                            }
                        } else {
                            if (c!=13 && c!=10) {
                                if (found || c!=' ') {
                                    buffer[i++]=c;
                                    continue;
                                }
                            }
                            if (i==0)
                                continue;
                        }
                        buffer[i]='\0';
                        found=0;
                        i=0;
                        rargv[rargc]= strdup(buffer);
                        rargc++;
                        buffer[0]='\0';
                    }
                    if (buffer[0] != '\0') {
                        buffer[i]='\0';
                        rargv[rargc]= strdup(buffer);
                        rargc++;
                    }
                    fclose(cmdFile);

                    ret = initOptions(rargc, rargv, bCmdFile);

                    long ii = 0;
                    for (ii=0; ii < rargc; ii++)
                    {
                        free(rargv[ii]);
                    }
                }
            } else
            {
                OString name(av[j]);
                name = name.toAsciiLowerCase();
                if ( name.lastIndexOf(".idl") != (name.getLength() - 4) )
                {
                    throw IllegalArgument("'" + OString(av[j]) +
                        "' is not a valid input file, only '*.idl' files will be accepted");
                }
                m_inputFiles.push_back(av[j]);
            }
        }
    }

    return ret;
}

OString Options::prepareHelp()
{
    OString help("\nusing: ");
    help += m_program
        + " [-options] <file_1> ... <file_n> | @<filename> | -stdin\n";
    help += "    <file_n>    = file_n specifies one or more idl files.\n";
    help += "                  Only files with the extension '.idl' are valid.\n";
    help += "    @<filename> = filename specifies the name of a command file.\n";
    help += "    -stdin      = read idl file from standard input.\n";
    help += "  Options:\n";
    help += "    -O<path>    = path specifies the output directory.\n";
    help += "                  The generated output is a registry file with\n";
    help += "                  the same name as the idl input file (or 'stdin'\n";
    help += "                  for -stdin).\n";
    help += "    -I<path>    = path specifies a directory where include\n";
    help += "                  files will be searched by the preprocessor.\n";
    help += "                  Multiple directories can be combined with ';'.\n";
    help += "    -D<name>    = name defines a macro for the preprocessor.\n";
    help += "    -C          = generate complete type information, including\n";
    help += "                  documentation.\n";
    help += "    -cid        = check if identifiers fulfill the UNO naming\n";
    help += "                  requirements.\n";
    help += "    -w          = display warning messages.\n";
    help += "    -we         = treat warnings as errors.\n";
    help += "    -h|-?       = print this help message and exit.\n";
    help += prepareVersion();

    return help;
}

OString Options::prepareVersion()
{
    OString version("\nSun Microsystems (R) ");
    version += m_program + " Version 1.1\n\n";
    return version;
}

const OString& Options::getProgramName() const
{
    return m_program;
}

sal_Bool Options::isValid(const OString& option)
{
    return (m_options.count(option) > 0);
}

const OString Options::getOption(const OString& option)
    throw( IllegalArgument )
{
    if (m_options.count(option) > 0)
    {
        return m_options[option];
    } else
    {
        throw IllegalArgument("Option is not valid or currently not set.");
    }
}
<|endoftext|>


<commit_before>#include "webcam.hpp"

using namespace cv;
using namespace std;

int main (int argc, char** argv) {

 CvCapture* capture = 0;
 int width, height, fps;

 capture = cvCaptureFromCAM(0);

 if (!capture) {
  printf("No camera detected!");
  return -1;
 }

 ifstream configFile (".config");

 if (configFile.is_open()) {

  //probably want to support corrupted .config
  string line;
  getline(configFile, line);
  istringstream(line)>>width;
  getline(configFile, line);
  istringstream(line)>>height;
  cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, width);
  cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, height);

  configFile.close();

 } else {

  initResolutions();

  for (int i=36; i<150; i++) {
   cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, resolutions[i].width);
   cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, resolutions[i].height);
  }

  width = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH);
  height = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT);

  ofstream configFileOut(".config");
  configFileOut << width;
  configFileOut << "\n";
  configFileOut << height;
  configFileOut << "\n";
  configFileOut.close();
 }

 bool keepGoing = true;

// srand(890);//not interested in good randomness

 Mat image;
 Mat channel[3];

 while (keepGoing) {

  image = cvQueryFrame(capture);
  //imshow("webcam", image);

// thresholds on dark regions

  Mat gray, blurred_gray, threshold_gray;
  cvtColor(image, gray, CV_BGR2GRAY);
  blur(gray, blurred_gray, Size(width/10,height/20));
  equalizeHist(blurred_gray, blurred_gray);
  bitwise_not(blurred_gray, blurred_gray);
  threshold(blurred_gray, threshold_gray, 210, 1, THRESH_BINARY);
  imshow("threshold", threshold_gray);

  Mat mask = threshold_gray.mul(gray);
  imshow("mask", mask);

  Moments lol = moments(mask, 1);
  circle(image, Point(lol.m10/lol.m00,lol.m01/lol.m00),20,Scalar(128),30);
  imshow("leimage", image);
  keepGoing = (waitKey(25)<0);

 }

 cvReleaseCapture(&capture);

 return 0;
}
<commit_msg>hacking<commit_after>#include "webcam.hpp"

using namespace cv;
using namespace std;

int main (int argc, char** argv) {

 CvCapture* capture = 0;
 int width, height, fps;

 capture = cvCaptureFromCAM(0);

 if (!capture) {
  printf("No camera detected!");
  return -1;
 }

 ifstream configFile (".config");

 if (configFile.is_open()) {

  //probably want to support corrupted .config
  string line;
  getline(configFile, line);
  istringstream(line)>>width;
  getline(configFile, line);
  istringstream(line)>>height;
  cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, width);
  cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, height);

  configFile.close();

 } else {

  initResolutions();

  for (int i=36; i<150; i++) {
   cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, resolutions[i].width);
   cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, resolutions[i].height);
  }

  width = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH);
  height = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT);

  ofstream configFileOut(".config");
  configFileOut << width;
  configFileOut << "\n";
  configFileOut << height;
  configFileOut << "\n";
  configFileOut.close();
 }

 bool keepGoing = true;

// srand(890);//not interested in good randomness

 Mat image;
 Mat channel[3];

 while (keepGoing) {

  image = cvQueryFrame(capture);
  //imshow("webcam", image);

// thresholds on dark regions

  Mat gray, blurred_gray, threshold_gray;
  cvtColor(image, gray, CV_BGR2GRAY);
  blur(gray, blurred_gray, Size(width/10,height/20));
  equalizeHist(blurred_gray, blurred_gray);
  bitwise_not(blurred_gray, blurred_gray);
  threshold(blurred_gray, threshold_gray, 210, 1, THRESH_BINARY);
  imshow("threshold", threshold_gray);

  Mat mask = threshold_gray.mul(gray);
  bitwise_not(mask, mask);
  imshow("mask", mask);

  Moments lol = moments(mask, 1);
  circle(image, Point(lol.m10/lol.m00,lol.m01/lol.m00),20,Scalar(128),30);
  imshow("leimage", image);
  keepGoing = (waitKey(25)<0);

 }

 cvReleaseCapture(&capture);

 return 0;
}
<|endoftext|>


<commit_before>/*
	Flexisip, a flexible SIP proxy server with media capabilities.
	Copyright (C) 2015  Belledonne Communications SARL.

	This program is free software: you can redistribute it and/or modify
	it under the terms of the GNU Affero General Public License as
	published by the Free Software Foundation, either version 3 of the
	License, or (at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU Affero General Public License for more details.

	You should have received a copy of the GNU Affero General Public License
	along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "configdumper.hh"
#include "module.hh"

using namespace std;

ostream &ConfigDumper::dump(ostream &ostr) const{
	return dump_recursive(ostr, mRoot, 0);
}

ostream& ConfigDumper::dump_recursive(std::ostream &ostr, const GenericEntry *entry, unsigned int level) const
{
	const GenericStruct *cs  = dynamic_cast<const GenericStruct*>(entry);
	const ConfigValue* value = dynamic_cast<const ConfigValue*>(entry);
	if( cs && shouldDumpModule(cs->getName()) ){

		dumpModuleHead(ostr, cs, level);

		for( auto it = cs->getChildren().begin(); it != cs->getChildren().end(); ++it ){
			GenericEntry* child = *it;
			dump_recursive(ostr, child, level+1);
		}

	} else if( value ){

		dumpModuleValue(ostr, value, level);

	}
	return ostr;
}

#define MODULE_PREFIX_LEN 8 /* strlen("module::") */
bool ConfigDumper::shouldDumpModule(const string& moduleName) const
{
	// When the dumpExperimental is activated, we should dump everything
	if( mDumpExperimental ) return true;

	string name = moduleName;
	if( name.find("module::") != name.npos ){
		name = moduleName.substr(MODULE_PREFIX_LEN);
	}
	auto moduleInfos = ModuleFactory::get()->moduleInfos();
	auto it = std::find_if(moduleInfos.begin(), moduleInfos.end(), [name](ModuleInfoBase* i){
			return i->getModuleName() == name;
	});

	ModuleInfoBase* moduleInfo = (it != moduleInfos.end()) ? *it : nullptr;
	if( moduleInfo != nullptr ){
		return moduleInfo->type() == ModuleTypeProduction;
	} else {
		return true;
	}

}

/* FILE CONFIG DUMPER */

ostream & FileConfigDumper::printHelp(ostream &os, const string &help, const string &comment_prefix) const {
	const char *p=help.c_str();
	const char *begin=p;
	const char *origin=help.c_str();

	for(;*p!=0;++p){
		if ((p-begin>60 && *p==' ') || *p=='\n'){
			os<<comment_prefix<<" "<<help.substr(begin-origin,p-begin)<<endl;
			p++;
			begin=p;
		}
	}
	os<<comment_prefix<<" "<<help.substr(begin-origin,p-origin)<<endl;
	return os;
}

ostream & FileConfigDumper::dumpModuleValue(std::ostream &ostr, const ConfigValue *val, int level) const {
	if (val && !val->getExportToConfigFile()) return ostr;
	if( !val->isDeprecated() ){

		printHelp(ostr,val->getHelp(),"#");
		ostr<<"#  Default value: "<<val->getDefault()<<endl;

		if (mDumpDefault) {
			ostr<<val->getName()<<"="<<val->getDefault()<<endl;
		} else {
			ostr<<val->getName()<<"="<<val->get()<<endl;
		}
		ostr << endl;
	}
	return ostr;
}

ostream & FileConfigDumper::dumpModuleHead(std::ostream &ostr, const GenericStruct *moduleHead, int level) const {
	if (moduleHead && !moduleHead->getExportToConfigFile()) return ostr;

	ostr<<"##"<<endl;

	printHelp(ostr,moduleHead->getHelp(),"##");

	ostr<<"##"<<endl;

	if (level>0){
		ostr<<"["<<moduleHead->getName()<<"]"<<endl;
	}
	else
		ostr<<endl;

	ostr << endl << endl << endl;

	return ostr;
}

/* TexFileComfigDumper */

static void escaper(string &str, char c, const string &replaced) {
	size_t i=0;
	while(string::npos != (i=str.find_first_of(c, i))) {
		str.erase(i, 1);
		str.insert(i, replaced);
		i+=replaced.length();
	}
}

static void string_escaper(string& str, const string &s, const string &replace){
	size_t i=0;
	while(string::npos != (i=str.find(s, i))) {
		str.erase(i, s.length());
		str.insert(i, replace);
		i+=replace.length();
	}
}

string TexFileConfigDumper::escape(const string &strc) const{
	std::string str(strc);
	escaper(str, '_', "\\_");
	escaper(str, '<', "\\textless{}");
	escaper(str, '>', "\\textgreater{}");

	return str;
}

ostream& TexFileConfigDumper::dumpModuleHead(std::ostream &ostr, const GenericStruct *cs, int level) const
{
	if (cs->getParent()) {
		string pn=escape(cs->getPrettyName());
		ostr<<"\\section{"<< pn << "}" << endl << endl;
		ostr<<"\\label{" << cs->getName() << "}" << endl;
		ostr<<"\\subsection{Description}"<< endl <<endl;
		ostr<<escape(cs->getHelp())<< endl <<endl;
		ostr<<"\\subsection{Parameters}"<< endl <<endl;
	}
	return ostr;
}

ostream& TexFileConfigDumper::dumpModuleValue(std::ostream &ostr, const ConfigValue *val, int level) const {

	if( !val->isDeprecated() ){
		ostr<<"\\subsubsection{"<<escape(val->getName())<<"}"<<endl;
		ostr<<escape(val->getHelp())<<endl;
		ostr<<"The default value is ``"<<escape(val->getDefault())<<"''."<<endl;
		ostr<<endl;
	}
	return ostr;
}

/* Dokuwiki */

ostream& DokuwikiConfigDumper::dumpModuleValue(std::ostream &ostr, const ConfigValue *val, int level) const {
	if(!val->isDeprecated()){

		// dokuwiki handles line breaks with double backspaces
		string help = val->getHelp();
		escaper(help, '\n', "\\\\ ");
		escaper(help, '`', "'' ");
		string_escaper(help, ". ", ".\\\\ ");

		ostr << "|" << "**" << val->getName() << "**"
		<< " | " << help
		<< " | " << "''" << val->getDefault() << "''"
		<< " | " << val->getTypeName()
		<< " | " << endl;

	}
	return ostr;
}

ostream& DokuwikiConfigDumper::dumpModuleHead(std::ostream &ostr, const GenericStruct *cs, int level) const {
	// we have a generic struc: we're on top level: get module name and description
	ostr << "====" << cs->getPrettyName() << "====" << endl;
	ostr << endl << cs->getHelp() << endl;
	ostr << endl << "Configuration options:" << endl;

	ostr << "^ Name ^ Description ^ Default value ^ Type ^" << endl;
	return ostr;
}

/* MIB */

ostream &MibDumper::dump(ostream & ostr)const {
	const time_t t = getCurrentTime();
	char mbstr[100];
	strftime(mbstr, sizeof(mbstr), "%Y%m%d0000Z", localtime(&t));

	ostr << "FLEXISIP-MIB DEFINITIONS ::= BEGIN" << endl
			<< "IMPORTS" << endl
			<< "	OBJECT-TYPE, Integer32, MODULE-IDENTITY, enterprises," << endl
			<< "	Counter64,NOTIFICATION-TYPE							  	FROM SNMPv2-SMI" << endl
			<< "	MODULE-COMPLIANCE, OBJECT-GROUP       					FROM SNMPv2-CONF;" << endl
			<< endl

			<< "flexisipMIB MODULE-IDENTITY" << endl
			<< "	LAST-UPDATED \"" << mbstr <<"\"" << endl
			<< "	ORGANIZATION \"belledonne-communications\"" << endl
			<< "	CONTACT-INFO \"postal:   34 Avenue de L'europe 38 100 Grenoble France" << endl
			<< "		email:    contact@belledonne-communications.com\"" << endl
			<< "	DESCRIPTION  \"A Flexisip management tree.\"" << endl
			<< "	REVISION     \"" <<mbstr <<"\""<<endl
			<< "    DESCRIPTION  \"" PACKAGE_VERSION << "\"" << endl
			<< "::={ enterprises "<< company_id << " }" << endl
			<< endl;

	dump2(ostr,mRoot,0);
	ostr << "END" << endl;
	return ostr;
}

ostream &MibDumper::dump2(ostream & ostr, GenericEntry *entry, int level)const{
	GenericStruct *cs=dynamic_cast<GenericStruct*>(entry);
	ConfigValue *cVal;
	StatCounter64 *sVal;
	NotificationEntry *ne;
	string spacing="";
	while (level > 0) {
		spacing += "	";
		--level;
	}
	if (cs && shouldDumpModule(cs->getName())){
		cs->mibFragment(ostr, spacing);
		for(auto it=cs->getChildren().begin();it!=cs->getChildren().end();++it){
			if (!cs->isDeprecated()){
				dump2(ostr,*it,level+1);
				ostr<<endl;
			}
		}
	}else if ((cVal=dynamic_cast<ConfigValue*>(entry))!=NULL){
		cVal->mibFragment(ostr, spacing);
	}else if ((sVal=dynamic_cast<StatCounter64*>(entry))!=NULL){
		sVal->mibFragment(ostr, spacing);
	}else if ((ne=dynamic_cast<NotificationEntry*>(entry))!=NULL){
		ne->mibFragment(ostr,spacing);
	}
	return ostr;
}

<commit_msg>C++0x<commit_after>/*
	Flexisip, a flexible SIP proxy server with media capabilities.
	Copyright (C) 2015  Belledonne Communications SARL.

	This program is free software: you can redistribute it and/or modify
	it under the terms of the GNU Affero General Public License as
	published by the Free Software Foundation, either version 3 of the
	License, or (at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU Affero General Public License for more details.

	You should have received a copy of the GNU Affero General Public License
	along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "configdumper.hh"
#include "module.hh"

using namespace std;

ostream &ConfigDumper::dump(ostream &ostr) const{
	return dump_recursive(ostr, mRoot, 0);
}

ostream& ConfigDumper::dump_recursive(std::ostream &ostr, const GenericEntry *entry, unsigned int level) const
{
	const GenericStruct *cs  = dynamic_cast<const GenericStruct*>(entry);
	const ConfigValue* value = dynamic_cast<const ConfigValue*>(entry);
	if( cs && shouldDumpModule(cs->getName()) ){

		dumpModuleHead(ostr, cs, level);

		for( auto it = cs->getChildren().begin(); it != cs->getChildren().end(); ++it ){
			GenericEntry* child = *it;
			dump_recursive(ostr, child, level+1);
		}

	} else if( value ){

		dumpModuleValue(ostr, value, level);

	}
	return ostr;
}

struct matchModuleName
{
	const std::string& mName;
	matchModuleName(const std::string &name ) : mName(name) {}
	bool operator()(const ModuleInfoBase* mi) {
		return (mi->getModuleName() == mName);
	}
};

#define MODULE_PREFIX_LEN 8 /* strlen("module::") */
bool ConfigDumper::shouldDumpModule(const string& moduleName) const
{
	// When the dumpExperimental is activated, we should dump everything
	if( mDumpExperimental ) return true;

	string name = moduleName;
	if( name.find("module::") != name.npos ){
		name = moduleName.substr(MODULE_PREFIX_LEN);
	}
	auto moduleInfos = ModuleFactory::get()->moduleInfos();
	auto it = std::find_if(moduleInfos.begin(), moduleInfos.end(), matchModuleName(name));

	ModuleInfoBase* moduleInfo = (it != moduleInfos.end()) ? *it : NULL;
	if( moduleInfo != NULL ){
		return moduleInfo->type() == ModuleTypeProduction;
	} else {
		return true;
	}

}

/* FILE CONFIG DUMPER */

ostream & FileConfigDumper::printHelp(ostream &os, const string &help, const string &comment_prefix) const {
	const char *p=help.c_str();
	const char *begin=p;
	const char *origin=help.c_str();

	for(;*p!=0;++p){
		if ((p-begin>60 && *p==' ') || *p=='\n'){
			os<<comment_prefix<<" "<<help.substr(begin-origin,p-begin)<<endl;
			p++;
			begin=p;
		}
	}
	os<<comment_prefix<<" "<<help.substr(begin-origin,p-origin)<<endl;
	return os;
}

ostream & FileConfigDumper::dumpModuleValue(std::ostream &ostr, const ConfigValue *val, int level) const {
	if (val && !val->getExportToConfigFile()) return ostr;
	if( !val->isDeprecated() ){

		printHelp(ostr,val->getHelp(),"#");
		ostr<<"#  Default value: "<<val->getDefault()<<endl;

		if (mDumpDefault) {
			ostr<<val->getName()<<"="<<val->getDefault()<<endl;
		} else {
			ostr<<val->getName()<<"="<<val->get()<<endl;
		}
		ostr << endl;
	}
	return ostr;
}

ostream & FileConfigDumper::dumpModuleHead(std::ostream &ostr, const GenericStruct *moduleHead, int level) const {
	if (moduleHead && !moduleHead->getExportToConfigFile()) return ostr;

	ostr<<"##"<<endl;

	printHelp(ostr,moduleHead->getHelp(),"##");

	ostr<<"##"<<endl;

	if (level>0){
		ostr<<"["<<moduleHead->getName()<<"]"<<endl;
	}
	else
		ostr<<endl;

	ostr << endl << endl << endl;

	return ostr;
}

/* TexFileComfigDumper */

static void escaper(string &str, char c, const string &replaced) {
	size_t i=0;
	while(string::npos != (i=str.find_first_of(c, i))) {
		str.erase(i, 1);
		str.insert(i, replaced);
		i+=replaced.length();
	}
}

static void string_escaper(string& str, const string &s, const string &replace){
	size_t i=0;
	while(string::npos != (i=str.find(s, i))) {
		str.erase(i, s.length());
		str.insert(i, replace);
		i+=replace.length();
	}
}

string TexFileConfigDumper::escape(const string &strc) const{
	std::string str(strc);
	escaper(str, '_', "\\_");
	escaper(str, '<', "\\textless{}");
	escaper(str, '>', "\\textgreater{}");

	return str;
}

ostream& TexFileConfigDumper::dumpModuleHead(std::ostream &ostr, const GenericStruct *cs, int level) const
{
	if (cs->getParent()) {
		string pn=escape(cs->getPrettyName());
		ostr<<"\\section{"<< pn << "}" << endl << endl;
		ostr<<"\\label{" << cs->getName() << "}" << endl;
		ostr<<"\\subsection{Description}"<< endl <<endl;
		ostr<<escape(cs->getHelp())<< endl <<endl;
		ostr<<"\\subsection{Parameters}"<< endl <<endl;
	}
	return ostr;
}

ostream& TexFileConfigDumper::dumpModuleValue(std::ostream &ostr, const ConfigValue *val, int level) const {

	if( !val->isDeprecated() ){
		ostr<<"\\subsubsection{"<<escape(val->getName())<<"}"<<endl;
		ostr<<escape(val->getHelp())<<endl;
		ostr<<"The default value is ``"<<escape(val->getDefault())<<"''."<<endl;
		ostr<<endl;
	}
	return ostr;
}

/* Dokuwiki */

ostream& DokuwikiConfigDumper::dumpModuleValue(std::ostream &ostr, const ConfigValue *val, int level) const {
	if(!val->isDeprecated()){

		// dokuwiki handles line breaks with double backspaces
		string help = val->getHelp();
		escaper(help, '\n', "\\\\ ");
		escaper(help, '`', "'' ");
		string_escaper(help, ". ", ".\\\\ ");

		ostr << "|" << "**" << val->getName() << "**"
		<< " | " << help
		<< " | " << "''" << val->getDefault() << "''"
		<< " | " << val->getTypeName()
		<< " | " << endl;

	}
	return ostr;
}

ostream& DokuwikiConfigDumper::dumpModuleHead(std::ostream &ostr, const GenericStruct *cs, int level) const {
	// we have a generic struc: we're on top level: get module name and description
	ostr << "====" << cs->getPrettyName() << "====" << endl;
	ostr << endl << cs->getHelp() << endl;
	ostr << endl << "Configuration options:" << endl;

	ostr << "^ Name ^ Description ^ Default value ^ Type ^" << endl;
	return ostr;
}

/* MIB */

ostream &MibDumper::dump(ostream & ostr)const {
	const time_t t = getCurrentTime();
	char mbstr[100];
	strftime(mbstr, sizeof(mbstr), "%Y%m%d0000Z", localtime(&t));

	ostr << "FLEXISIP-MIB DEFINITIONS ::= BEGIN" << endl
			<< "IMPORTS" << endl
			<< "	OBJECT-TYPE, Integer32, MODULE-IDENTITY, enterprises," << endl
			<< "	Counter64,NOTIFICATION-TYPE							  	FROM SNMPv2-SMI" << endl
			<< "	MODULE-COMPLIANCE, OBJECT-GROUP       					FROM SNMPv2-CONF;" << endl
			<< endl

			<< "flexisipMIB MODULE-IDENTITY" << endl
			<< "	LAST-UPDATED \"" << mbstr <<"\"" << endl
			<< "	ORGANIZATION \"belledonne-communications\"" << endl
			<< "	CONTACT-INFO \"postal:   34 Avenue de L'europe 38 100 Grenoble France" << endl
			<< "		email:    contact@belledonne-communications.com\"" << endl
			<< "	DESCRIPTION  \"A Flexisip management tree.\"" << endl
			<< "	REVISION     \"" <<mbstr <<"\""<<endl
			<< "    DESCRIPTION  \"" PACKAGE_VERSION << "\"" << endl
			<< "::={ enterprises "<< company_id << " }" << endl
			<< endl;

	dump2(ostr,mRoot,0);
	ostr << "END" << endl;
	return ostr;
}

ostream &MibDumper::dump2(ostream & ostr, GenericEntry *entry, int level)const{
	GenericStruct *cs=dynamic_cast<GenericStruct*>(entry);
	ConfigValue *cVal;
	StatCounter64 *sVal;
	NotificationEntry *ne;
	string spacing="";
	while (level > 0) {
		spacing += "	";
		--level;
	}
	if (cs && shouldDumpModule(cs->getName())){
		cs->mibFragment(ostr, spacing);
		for(auto it=cs->getChildren().begin();it!=cs->getChildren().end();++it){
			if (!cs->isDeprecated()){
				dump2(ostr,*it,level+1);
				ostr<<endl;
			}
		}
	}else if ((cVal=dynamic_cast<ConfigValue*>(entry))!=NULL){
		cVal->mibFragment(ostr, spacing);
	}else if ((sVal=dynamic_cast<StatCounter64*>(entry))!=NULL){
		sVal->mibFragment(ostr, spacing);
	}else if ((ne=dynamic_cast<NotificationEntry*>(entry))!=NULL){
		ne->mibFragment(ostr,spacing);
	}
	return ostr;
}

<|endoftext|>


<commit_before>#include "SkyUtils.h"
#include "../Math/Constants.h"

#include "components/debug/Debug.h"

int SkyUtils::getOctantIndex(bool posX, bool posY, bool posZ)
{
	// Use lowest 3 bits to represent 0-7.
	const char xBit = posX ? 0 : (1 << 0);
	const char yBit = posY ? 0 : (1 << 1);
	const char zBit = posZ ? 0 : (1 << 2);
	return xBit | yBit | zBit;
}

Double3 SkyUtils::getSkyObjectDirection(Radians angleX, Radians angleY)
{
	// @todo: some sine and cosine functions
	DebugNotImplemented();
	return Double3();
}

void SkyUtils::getSkyObjectDimensions(int imageWidth, int imageHeight, double *outWidth, double *outHeight)
{
	DebugNotImplemented();
	// @todo: use ArenaSkyUtils constexpr values?
	*outWidth = 0;
	*outHeight = 0;
}

int SkyUtils::getStarCountFromDensity(int starDensity)
{
	if (starDensity == 0)
	{
		// Classic.
		return 40;
	}
	else if (starDensity == 1)
	{
		// Moderate.
		return 1000;
	}
	else if (starDensity == 2)
	{
		// High.
		return 8000;
	}
	else
	{
		DebugUnhandledReturnMsg(int, std::to_string(starDensity));
	}
}
<commit_msg>Implemented SkyUtils::getSkyObjectDirection().<commit_after>#include <cmath>

#include "SkyUtils.h"
#include "../Math/Constants.h"

#include "components/debug/Debug.h"

int SkyUtils::getOctantIndex(bool posX, bool posY, bool posZ)
{
	// Use lowest 3 bits to represent 0-7.
	const char xBit = posX ? 0 : (1 << 0);
	const char yBit = posY ? 0 : (1 << 1);
	const char zBit = posZ ? 0 : (1 << 2);
	return xBit | yBit | zBit;
}

VoxelDouble3 SkyUtils::getSkyObjectDirection(Radians angleX, Radians angleY)
{
	return VoxelDouble3(
		-std::sin(angleX),
		std::sin(angleY),
		-std::cos(angleX)).normalized();
}

void SkyUtils::getSkyObjectDimensions(int imageWidth, int imageHeight, double *outWidth, double *outHeight)
{
	DebugNotImplemented();
	// @todo: use ArenaSkyUtils constexpr values?
	*outWidth = 0;
	*outHeight = 0;
}

int SkyUtils::getStarCountFromDensity(int starDensity)
{
	if (starDensity == 0)
	{
		// Classic.
		return 40;
	}
	else if (starDensity == 1)
	{
		// Moderate.
		return 1000;
	}
	else if (starDensity == 2)
	{
		// High.
		return 8000;
	}
	else
	{
		DebugUnhandledReturnMsg(int, std::to_string(starDensity));
	}
}
<|endoftext|>


<commit_before>/*
    Persons Model Contact Item
    Represents person's contact item in the model
    Copyright (C) 2012  Martin Klapetek <martin.klapetek@gmail.com>
    Copyright (C) 2012  Aleix Pol Gonzalez <aleixpol@blue-systems.com>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2.1 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
*/

#include "contactitem.h"
#include "personpluginmanager.h"
#include "basepersonsdatasource.h"

#include "base-persons-data-source.h"

#include <QAction>

#include <KIcon>
#include <KDebug>
#include <KServiceTypeTrader>
#include <kdemacros.h>

#include <Nepomuk2/Resource>
#include <Nepomuk2/Variant>
#include <Nepomuk2/ResourceManager>

#include <Nepomuk2/Vocabulary/NCO>
#include <Nepomuk2/Vocabulary/NIE>
#include <Soprano/Vocabulary/NAO>
#include <Soprano/Model>
#include <Soprano/QueryResultIterator>

class ContactItemPrivate {
public:
    QUrl uri;
    QHash<int, QVariant> data;

    bool isBeingUpdated;

    ///@returns a list of the roles that we'll expect to be a QVariantList
    static QSet<int> listRoles() {
        static QSet<int> s_listRoles;
        if(s_listRoles.isEmpty()) {
            //TODO: document this in persons-model.h
            s_listRoles.insert(PersonsModel::PhotosRole);
            s_listRoles.insert(PersonsModel::EmailsRole);
            s_listRoles.insert(PersonsModel::PhonesRole);
        }
        return s_listRoles;
    }
};

ContactItem::ContactItem(const QUrl &uri)
    : d_ptr(new ContactItemPrivate)
{
//     setData(uri, PersonsModel::UriRole);
    d_ptr->uri = uri;
    d_ptr->isBeingUpdated = false;
}

ContactItem::~ContactItem()
{
    delete d_ptr;
}

void ContactItem::setContactData(int role, const QVariant &v)
{
    Q_D(ContactItem);

    if (v.isNull()) {
        //don't insert empty values, in case of list roles this
        //would insert QVariant(QVariantList(QVariant())),
        //empty QVariant will be returned from data(...) instead
        return;
    }

    QHash< int, QVariant >::iterator it = d->data.find(role);
    QVariant value = d->listRoles().contains(role) ? (QVariantList() << v) : v;
    if (it == d->data.end()) {
        d->data.insert(role, value);
        emitDataChanged();
    } else if (*it != value) {
        Q_ASSERT(value.type() == it->type());
        *it = value;
        emitDataChanged();
    }
}

//TODO update so value can be a list. This will then concat onto any existing list.

void ContactItem::addContactData(int role, const QVariant &value)
{
    Q_D(ContactItem);
    if (value.isNull()) {
        //don't insert empty values, in case of list roles this
        //would insert QVariant(QVariantList(QVariant())),
        //empty QVariant will be returned from data(...) instead
        return;
    }
    QHash<int, QVariant>::iterator it = d->data.find(role);
    if (!d->listRoles().contains(role)) {
        setContactData(role, value);
    } else {
        if (it == d->data.end()) {
            d->data.insert(role, QVariantList() << value);
            emitDataChanged();
        } else if (*it != value) {
            Q_ASSERT(it->type() == QVariant::List);
            QVariantList current = it->toList();
            Q_ASSERT(current.isEmpty() || current.first().type()==value.type());
            current.append(value);
            *it = current;
            emitDataChanged();
        }
    }
}

void ContactItem::removeData(int role)
{
    Q_D(ContactItem);
    if (d->data.remove(role)) {
        emitDataChanged();
    }
}

QUrl ContactItem::uri() const
{
    Q_D(const ContactItem);
    return d->uri;
}

QVariant ContactItem::data(int role) const
{
    Q_D(const ContactItem);

    QHash<int, QVariant>::const_iterator it = d->data.constFind(role);
    if (it!=d->data.constEnd()) {
        return *it;
    }

    switch(role) {
        case Qt::DisplayRole:
            if (!data(PersonsModel::NicknamesRole).isNull()) {
                return data(PersonsModel::NicknamesRole);
            }
            if (!data(PersonsModel::FullNamesRole).isNull()) {
                return data(PersonsModel::FullNamesRole);
            }
            if (!data(PersonsModel::EmailsRole).isNull()) {
                return data(PersonsModel::EmailsRole);
            }
            if (!data(PersonsModel::IMsRole).isNull()) {
                return data(PersonsModel::IMsRole);
            }
            if (!data(PersonsModel::PhonesRole).isNull()) {
                return data(PersonsModel::PhonesRole);
            }

            return QString("Unknown contact");
        case Qt::DecorationRole: {
            const QVariantList photos = d->data.value(PersonsModel::PhotosRole).toList();
            return photos.isEmpty() ? KIcon("im-user") : KIcon(photos.first().toUrl().toLocalFile());
        }
        case PersonsModel::UriRole: return d->uri; break;
        case PersonsModel::PresenceTypeRole:
        case PersonsModel::PresenceDisplayRole:
        case PersonsModel::PresenceDecorationRole:
            return PersonPluginManager::presencePlugin()->dataForContact(data(PersonsModel::IMsRole).toString(), role);
    }

    return QStandardItem::data(role);
}

void ContactItem::loadData()
{
    Q_D(ContactItem);

    if (d->isBeingUpdated) {
        kDebug() << "Contact already being updated";
        return;
    }

    d->data.clear();

    PersonsModel *m = qobject_cast<PersonsModel*>(model());

    if (m) {
        d->isBeingUpdated = true;
        m->updateContact(this);
    }
}

void ContactItem::finishLoadingData()
{
    Q_D(ContactItem);
    d->isBeingUpdated = false;
    emitDataChanged();
}
<commit_msg>Contact node can be updated only if there's valid PersonsModel pointer<commit_after>/*
    Persons Model Contact Item
    Represents person's contact item in the model
    Copyright (C) 2012  Martin Klapetek <martin.klapetek@gmail.com>
    Copyright (C) 2012  Aleix Pol Gonzalez <aleixpol@blue-systems.com>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2.1 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
*/

#include "contactitem.h"
#include "personpluginmanager.h"
#include "basepersonsdatasource.h"

#include "base-persons-data-source.h"

#include <QAction>

#include <KIcon>
#include <KDebug>
#include <KServiceTypeTrader>
#include <kdemacros.h>

#include <Nepomuk2/Resource>
#include <Nepomuk2/Variant>
#include <Nepomuk2/ResourceManager>

#include <Nepomuk2/Vocabulary/NCO>
#include <Nepomuk2/Vocabulary/NIE>
#include <Soprano/Vocabulary/NAO>
#include <Soprano/Model>
#include <Soprano/QueryResultIterator>

class ContactItemPrivate {
public:
    QUrl uri;
    QHash<int, QVariant> data;

    bool isBeingUpdated;

    ///@returns a list of the roles that we'll expect to be a QVariantList
    static QSet<int> listRoles() {
        static QSet<int> s_listRoles;
        if(s_listRoles.isEmpty()) {
            //TODO: document this in persons-model.h
            s_listRoles.insert(PersonsModel::PhotosRole);
            s_listRoles.insert(PersonsModel::EmailsRole);
            s_listRoles.insert(PersonsModel::PhonesRole);
        }
        return s_listRoles;
    }
};

ContactItem::ContactItem(const QUrl &uri)
    : d_ptr(new ContactItemPrivate)
{
//     setData(uri, PersonsModel::UriRole);
    d_ptr->uri = uri;
    d_ptr->isBeingUpdated = false;
}

ContactItem::~ContactItem()
{
    delete d_ptr;
}

void ContactItem::setContactData(int role, const QVariant &v)
{
    Q_D(ContactItem);

    if (v.isNull()) {
        //don't insert empty values, in case of list roles this
        //would insert QVariant(QVariantList(QVariant())),
        //empty QVariant will be returned from data(...) instead
        return;
    }

    QHash< int, QVariant >::iterator it = d->data.find(role);
    QVariant value = d->listRoles().contains(role) ? (QVariantList() << v) : v;
    if (it == d->data.end()) {
        d->data.insert(role, value);
        emitDataChanged();
    } else if (*it != value) {
        Q_ASSERT(value.type() == it->type());
        *it = value;
        emitDataChanged();
    }
}

//TODO update so value can be a list. This will then concat onto any existing list.

void ContactItem::addContactData(int role, const QVariant &value)
{
    Q_D(ContactItem);
    if (value.isNull()) {
        //don't insert empty values, in case of list roles this
        //would insert QVariant(QVariantList(QVariant())),
        //empty QVariant will be returned from data(...) instead
        return;
    }
    QHash<int, QVariant>::iterator it = d->data.find(role);
    if (!d->listRoles().contains(role)) {
        setContactData(role, value);
    } else {
        if (it == d->data.end()) {
            d->data.insert(role, QVariantList() << value);
            emitDataChanged();
        } else if (*it != value) {
            Q_ASSERT(it->type() == QVariant::List);
            QVariantList current = it->toList();
            Q_ASSERT(current.isEmpty() || current.first().type()==value.type());
            current.append(value);
            *it = current;
            emitDataChanged();
        }
    }
}

void ContactItem::removeData(int role)
{
    Q_D(ContactItem);
    if (d->data.remove(role)) {
        emitDataChanged();
    }
}

QUrl ContactItem::uri() const
{
    Q_D(const ContactItem);
    return d->uri;
}

QVariant ContactItem::data(int role) const
{
    Q_D(const ContactItem);

    QHash<int, QVariant>::const_iterator it = d->data.constFind(role);
    if (it!=d->data.constEnd()) {
        return *it;
    }

    switch(role) {
        case Qt::DisplayRole:
            if (!data(PersonsModel::NicknamesRole).isNull()) {
                return data(PersonsModel::NicknamesRole);
            }
            if (!data(PersonsModel::FullNamesRole).isNull()) {
                return data(PersonsModel::FullNamesRole);
            }
            if (!data(PersonsModel::EmailsRole).isNull()) {
                return data(PersonsModel::EmailsRole);
            }
            if (!data(PersonsModel::IMsRole).isNull()) {
                return data(PersonsModel::IMsRole);
            }
            if (!data(PersonsModel::PhonesRole).isNull()) {
                return data(PersonsModel::PhonesRole);
            }

            return QString("Unknown contact");
        case Qt::DecorationRole: {
            const QVariantList photos = d->data.value(PersonsModel::PhotosRole).toList();
            return photos.isEmpty() ? KIcon("im-user") : KIcon(photos.first().toUrl().toLocalFile());
        }
        case PersonsModel::UriRole: return d->uri; break;
        case PersonsModel::PresenceTypeRole:
        case PersonsModel::PresenceDisplayRole:
        case PersonsModel::PresenceDecorationRole:
            return PersonPluginManager::presencePlugin()->dataForContact(data(PersonsModel::IMsRole).toString(), role);
    }

    return QStandardItem::data(role);
}

void ContactItem::loadData()
{
    Q_D(ContactItem);

    if (d->isBeingUpdated) {
        kDebug() << "Contact already being updated";
        return;
    }

    d->data.clear();

    PersonsModel *m = qobject_cast<PersonsModel*>(model());

    Q_ASSERT(m); //crash if this contact is not part of the model

    d->isBeingUpdated = true;
    m->updateContact(this);
}

void ContactItem::finishLoadingData()
{
    Q_D(ContactItem);
    d->isBeingUpdated = false;
    emitDataChanged();
}
<|endoftext|>


<commit_before>//_________________________________________________________________________
//  Utility Class for transverse energy studies
//  Task for analysis
//  - reconstruction and MC output
// implementation file
//
//*-- Authors: Oystein Djuvsland (Bergen), David Silvermyr (ORNL)
//_________________________________________________________________________
//Necessary to read config macros
#include <TROOT.h>
#include <TSystem.h>
#include <TInterpreter.h>

#include "TChain.h"
#include "TList.h"
#include "TFile.h"
#include "TH2F.h"
#include "THnSparse.h"

#include "AliESDEvent.h"
#include "AliMCEvent.h"
#include "AliESDtrackCuts.h"

#include "AliAnalysisTaskTotEt.h"
#include "AliAnalysisEtReconstructedPhos.h"
#include "AliAnalysisEtReconstructedEmcal.h"
#include "AliAnalysisEtMonteCarloPhos.h"
#include "AliAnalysisEtMonteCarloEmcal.h"
#include "AliAnalysisEmEtMonteCarlo.h"
#include "AliAnalysisEmEtReconstructed.h"

#include <iostream>
#include <AliCentrality.h>

using namespace std;

ClassImp(AliAnalysisTaskTotEt)

//________________________________________________________________________
AliAnalysisTaskTotEt::AliAnalysisTaskTotEt(const char *name, Bool_t isMc) :
AliAnalysisTaskTransverseEnergy(name, isMc)
,fRecAnalysis(0)
,fMCAnalysis(0)
,fSparseHistRecVsMc(0)
,fSparseRecVsMc(0)
{
    // Constructor

    // select if we should use EMCal or PHOS class
    // PHOS by default, EMCal if name string contains EMC
    TString t(name);
    //t.ToUpper();
    if (t.Contains("EMC")) {
		if (t.Contains("Detail")) {
			fMCAnalysis = new AliAnalysisEmEtMonteCarlo();
			fMCAnalysis->SetDataSet(2010);
			fMCAnalysis->Init();

			cout << "Instantiating AliAnalysisEmEtMonteCarlo class..."<< endl;
		}
        else if (fMCConfigFile.Length()) {
            cout<<"Rereading AliAnalysisEtMonteCarloEmcal configuration file..."<<endl;
            gROOT->LoadMacro(fMCConfigFile);
            fMCAnalysis = (AliAnalysisEtMonteCarloEmcal *) gInterpreter->ProcessLine("ConfigEtMonteCarlo()");
        }

		if (t.Contains("Detail")) {
			fRecAnalysis = new AliAnalysisEmEtReconstructed();
			fRecAnalysis->SetDataSet(2010);

			TFile *infile = new TFile("corrections.root");
			fRecAnalysis->SetCorrections((AliAnalysisHadEtCorrections *)infile->Get("hadCorrectionEMCAL"));

			fRecAnalysis->Init();

			cout << "Instantiating AliAnalysisEmEtReconstructed class..."<< endl;
		}
        else if (fRecoConfigFile.Length()) {
            cout<<"Rereading AliAnalysisEtReconstructedEmcal configuration file..."<<endl;
            gROOT->LoadMacro(fRecoConfigFile);
            fRecAnalysis = (AliAnalysisEtReconstructedEmcal *) gInterpreter->ProcessLine("ConfigEtReconstructed()");
        }
    }
    else {
        if (fMCConfigFile.Length()) {
            cout<<"Rereading AliAnalysisEtMonteCarloPhos configuration file..."<<endl;
            gROOT->LoadMacro(fMCConfigFile);

            fMCAnalysis = (AliAnalysisEtMonteCarloPhos *) gInterpreter->ProcessLine("ConfigEtMonteCarlo(false)");
			cout << fMCAnalysis << endl;
        }

        if (fRecoConfigFile.Length()) {
            cout<<"Rereading AliAnalysisEtReconstructedPhos configuration file..."<<endl;
            gROOT->LoadMacro(fRecoConfigFile);
            fRecAnalysis = (AliAnalysisEtReconstructedPhos *) gInterpreter->ProcessLine("ConfigEtReconstructed(false)");
        }
    }
    // Define input and output slots here
    // Input slot #0 works with a TChain
    DefineInput(0, TChain::Class());
    // Output slot #1 writes into a TH1 container

    DefineOutput(1, TList::Class());

}
AliAnalysisTaskTotEt::~AliAnalysisTaskTotEt() {//Destructor
	//    fOutputList->Clear();
    delete fRecAnalysis;
    delete fMCAnalysis;
}

//________________________________________________________________________
void AliAnalysisTaskTotEt::UserCreateOutputObjects()
{
    // Create histograms
    // Called once
	if (fMCAnalysis)
		fMCAnalysis->CreateHistograms();
    fRecAnalysis->CreateHistograms();
    fOutputList = new TList;
    fOutputList->SetOwner();
    fRecAnalysis->FillOutputList(fOutputList);
	if (fMCAnalysis)
		fMCAnalysis->FillOutputList(fOutputList);
    fHistEtRecvsEtMC = new TH2F("fHistEtRecvsEtMC", "Reconstructed E_{T} vs MC E_{T}", 1000, 0.000, 100, 1000, 0.0001, 100);
    fHistEtRecOverEtMC = new TH2F("fHistEtRecOverEtMC", "Reconstructed E_{T} over MC E_{T} vs centrality", 1000, 0.00, 2.0, 11, -0.5, 10.5);
    fHistDiffEtRecEtMCOverEtMC = new TH2F("fHistDiffEtRecEtMCOverEtMC", "fHistDiffEtRecEtMCOverEtMC", 10000, 0.0, 1000, 1000, -5, 5);
    fOutputList->Add(fHistEtRecvsEtMC);
    fOutputList->Add(fHistEtRecOverEtMC);
    fOutputList->Add(fHistDiffEtRecEtMCOverEtMC);

    Bool_t selectPrimaries=kTRUE;
    if (fRecAnalysis->DataSet()==2009) {
        cout<<"Setting track cuts for the 2009 p+p collisions at 900 GeV"<<endl;
        fEsdtrackCutsITSTPC = AliESDtrackCuts::GetStandardITSTPCTrackCuts2009(selectPrimaries);
        fEsdtrackCutsITSTPC->SetName("fEsdTrackCuts");
        fEsdtrackCutsTPC = AliESDtrackCuts::GetStandardTPCOnlyTrackCuts();
        fEsdtrackCutsTPC->SetName("fEsdTrackCutsTPCOnly");
        //ITS stand alone cuts - similar to 2009 cuts but with only ITS hits required
        fEsdtrackCutsITS =  AliESDtrackCuts::GetStandardITSPureSATrackCuts2009(kTRUE,kFALSE);//we do want primaries but we do not want to require PID info
        fEsdtrackCutsITS->SetName("fEsdTrackCutsITS");
    }
    if (fRecAnalysis->DataSet()==2010) {
        cout<<"Setting track cuts for the 2010 p+p collisions at 7 GeV"<<endl;
        //cout<<"Warning:  Have not set 2010 track cuts yet!!"<<endl;
        fEsdtrackCutsITSTPC = AliESDtrackCuts::GetStandardITSTPCTrackCuts2010(selectPrimaries);
        fEsdtrackCutsITSTPC->SetName("fEsdTrackCuts");
        fEsdtrackCutsTPC = AliESDtrackCuts::GetStandardTPCOnlyTrackCuts();
        fEsdtrackCutsTPC->SetName("fEsdTrackCutsTPCOnly");
        //ITS stand alone cuts - similar to 2009 cuts but with only ITS hits required
        fEsdtrackCutsITS =  AliESDtrackCuts::GetStandardITSPureSATrackCuts2010(kTRUE,kFALSE);//we do want primaries but we do not want to require PID info
        fEsdtrackCutsITS->SetName("fEsdTrackCutsITS");
    }

    fOutputList->Add(fEsdtrackCutsITSTPC);
    fOutputList->Add(fEsdtrackCutsTPC);
    fOutputList->Add(fEsdtrackCutsITS);
    if (fEsdtrackCutsITSTPC && fEsdtrackCutsTPC) {
        fRecAnalysis->SetITSTrackCuts( GetITSTrackCuts());
		if (fMCAnalysis)
			fMCAnalysis->SetITSTrackCuts( GetITSTrackCuts());
        fRecAnalysis->SetTPCITSTrackCuts( GetTPCITSTrackCuts());
		if (fMCAnalysis)
			fMCAnalysis->SetTPCITSTrackCuts( GetTPCITSTrackCuts());
        fRecAnalysis->SetTPCOnlyTrackCuts( GetTPCOnlyTrackCuts());
		if (fMCAnalysis)
			fMCAnalysis->SetTPCOnlyTrackCuts( GetTPCOnlyTrackCuts());
        //add ITS stuff!
    }
    else {
        Printf("Error: no track cuts!");
    }

}

//________________________________________________________________________
void AliAnalysisTaskTotEt::UserExec(Option_t *)
{ // execute method

    fESDEvent = dynamic_cast<AliESDEvent*>(InputEvent());
    if (!fESDEvent)
    {
        Printf("ERROR: Could not retrieve event");
        return;
    }

    //Int_t res = CheckPhysicsSelection(fESDEvent->GetRunNumber());

    AliCentrality *cent = GetCentralityObject();

    //if (res == 0 && cent)
    //{
	if (IsPhysicsSelected())
	{
		fRecAnalysis->SetCentralityObject(cent);
		fRecAnalysis->AnalyseEvent(fESDEvent);

		AliMCEvent* mcEvent = MCEvent();
		if (mcEvent)
		{
			fMCAnalysis->SetCentralityObject(cent);
			fMCAnalysis->AnalyseEvent(mcEvent, fESDEvent);
			//fMCAnalysis->AnalyseEvent(mcEvent);
		}
		if(fMCAnalysis)
	    {
			fHistEtRecvsEtMC->Fill(fRecAnalysis->GetTotNeutralEtAcc(), fMCAnalysis->GetTotNeutralEtAcc());
			if(fMCAnalysis->GetTotNeutralEtAcc()) fHistEtRecOverEtMC->Fill(fRecAnalysis->GetTotNeutralEt()/fMCAnalysis->GetTotNeutralEtAcc(), cent->GetCentralityClass10("V0M"));
			if(fMCAnalysis->GetTotNeutralEtAcc()) fHistDiffEtRecEtMCOverEtMC->Fill(fMCAnalysis->GetTotNeutralEt(), (fRecAnalysis->GetTotNeutralEt()-fMCAnalysis->GetTotNeutralEt())/fMCAnalysis->GetTotNeutralEt());
	    }
	}
    //}
    // Post output data.
    PostData(1, fOutputList);
}

//________________________________________________________________________
void AliAnalysisTaskTotEt::Terminate(Option_t *)
{
    // Draw result to the screen
    // Called once at the end of the query

    fOutputList = dynamic_cast<TList*> (GetOutputData(1));
    if (!fOutputList) {
        printf("ERROR: Output list not available\n");
        return;
    }
}

<commit_msg>Configuring AliAnalysisEmEtMonteCarlo and AliAnalysisEmEtReconstructed with config files instead of manually, fixing memory leaks, updating track cuts used to match proper analysis<commit_after>//_________________________________________________________________________
//  Utility Class for transverse energy studies
//  Task for analysis
//  - reconstruction and MC output
// implementation file
//
//*-- Authors: Oystein Djuvsland (Bergen), David Silvermyr (ORNL)
	       //_________________________________________________________________________
	       //Necessary to read config macros
#include <TROOT.h>
#include <TSystem.h>
#include <TInterpreter.h>

#include "TChain.h"
#include "TList.h"
#include "TFile.h"
#include "TH2F.h"
#include "THnSparse.h"

#include "AliESDEvent.h"
#include "AliMCEvent.h"
#include "AliESDtrackCuts.h"

#include "AliAnalysisTaskTotEt.h"
#include "AliAnalysisEtReconstructedPhos.h"
#include "AliAnalysisEtReconstructedEmcal.h"
#include "AliAnalysisEtMonteCarloPhos.h"
#include "AliAnalysisEtMonteCarloEmcal.h"
#include "AliAnalysisEmEtMonteCarlo.h"
#include "AliAnalysisEmEtReconstructed.h"

#include <iostream>
#include <AliCentrality.h>

  using namespace std;

ClassImp(AliAnalysisTaskTotEt)

//________________________________________________________________________
  AliAnalysisTaskTotEt::AliAnalysisTaskTotEt(const char *name, Bool_t isMc) :
    AliAnalysisTaskTransverseEnergy(name, isMc)
    ,fRecAnalysis(0)
    ,fMCAnalysis(0)
    ,fSparseHistRecVsMc(0)
    ,fSparseRecVsMc(0)
{
  // Constructor

  // select if we should use EMCal or PHOS class
  // PHOS by default, EMCal if name string contains EMC
  TString t(name);
  //t.ToUpper();
  if (t.Contains("EMC")) {
    if (t.Contains("Detail")) {

      cout<<"Rereading AliAnalysisEtMonteCarlo configuration file..."<<endl;
      gROOT->LoadMacro(fMCConfigFile);
      fMCAnalysis = (AliAnalysisEmEtMonteCarlo *) gInterpreter->ProcessLine("ConfigEtMonteCarlo(true,true)");

      cout << "Instantiating AliAnalysisEmEtMonteCarlo class..."<< endl;
    }
    else if (fMCConfigFile.Length()) {
      cout<<"Rereading AliAnalysisEtMonteCarloEmcal configuration file..."<<endl;
      gROOT->LoadMacro(fMCConfigFile);
      fMCAnalysis = (AliAnalysisEtMonteCarloEmcal *) gInterpreter->ProcessLine("ConfigEtMonteCarlo()");
    }

    if (t.Contains("Detail")) {
      cout<<"Rereading AliAnalysisEmEtReconstructed configuration file..."<<endl;
      gROOT->LoadMacro(fRecoConfigFile);
      fRecAnalysis = (AliAnalysisEmEtReconstructed *) gInterpreter->ProcessLine("ConfigEtReconstructed(true,true)");

    }
    else if (fRecoConfigFile.Length()) {
      cout<<"Rereading AliAnalysisEtReconstructedEmcal configuration file..."<<endl;
      gROOT->LoadMacro(fRecoConfigFile);
      fRecAnalysis = (AliAnalysisEtReconstructedEmcal *) gInterpreter->ProcessLine("ConfigEtReconstructed()");
    }
  }
  else {
    if (fMCConfigFile.Length()) {
      cout<<"Rereading AliAnalysisEtMonteCarloPhos configuration file..."<<endl;
      gROOT->LoadMacro(fMCConfigFile);

      fMCAnalysis = (AliAnalysisEtMonteCarloPhos *) gInterpreter->ProcessLine("ConfigEtMonteCarlo(false)");
      cout << fMCAnalysis << endl;
    }

    if (fRecoConfigFile.Length()) {
      cout<<"Rereading AliAnalysisEtReconstructedPhos configuration file..."<<endl;
      gROOT->LoadMacro(fRecoConfigFile);
      fRecAnalysis = (AliAnalysisEtReconstructedPhos *) gInterpreter->ProcessLine("ConfigEtReconstructed(false)");
    }
  }
  // Define input and output slots here
  // Input slot #0 works with a TChain
  DefineInput(0, TChain::Class());
  // Output slot #1 writes into a TH1 container

  DefineOutput(1, TList::Class());

}
AliAnalysisTaskTotEt::~AliAnalysisTaskTotEt() {//Destructor
  //    fOutputList->Clear();
  delete fRecAnalysis;
  delete fMCAnalysis;
  delete fSparseHistRecVsMc;
  delete fSparseRecVsMc;
}

//________________________________________________________________________
void AliAnalysisTaskTotEt::UserCreateOutputObjects()
{
  // Create histograms
  // Called once
  if (fMCAnalysis)
    fMCAnalysis->CreateHistograms();
  fRecAnalysis->CreateHistograms();
  fOutputList = new TList;
  fOutputList->SetOwner();
  fRecAnalysis->FillOutputList(fOutputList);
  if (fMCAnalysis)
    fMCAnalysis->FillOutputList(fOutputList);
  fHistEtRecvsEtMC = new TH2F("fHistEtRecvsEtMC", "Reconstructed E_{T} vs MC E_{T}", 1000, 0.000, 100, 1000, 0.0001, 100);
  fHistEtRecOverEtMC = new TH2F("fHistEtRecOverEtMC", "Reconstructed E_{T} over MC E_{T} vs centrality", 1000, 0.00, 2.0, 11, -0.5, 10.5);
  fHistDiffEtRecEtMCOverEtMC = new TH2F("fHistDiffEtRecEtMCOverEtMC", "fHistDiffEtRecEtMCOverEtMC", 10000, 0.0, 1000, 1000, -5, 5);
  fOutputList->Add(fHistEtRecvsEtMC);
  fOutputList->Add(fHistEtRecOverEtMC);
  fOutputList->Add(fHistDiffEtRecEtMCOverEtMC);

  Bool_t selectPrimaries=kTRUE;
  if(fRecAnalysis->DataSet()==2010 || fRecAnalysis->DataSet()==20111||fRecAnalysis->DataSet()==2009){
    if(fRecAnalysis->DataSet()==2010)cout<<"Setting track cuts for the 2010 p+p collisions at 7 TeV"<<endl;
    else{
      if(fRecAnalysis->DataSet()==2009){cout<<"Setting track cuts for the 2010 p+p collisions at 900 GeV"<<endl;}
      else{cout<<"Setting track cuts for the 2011 p+p collisions at 2.76 TeV"<<endl;}
    }
    //cout<<"Warning:  Have not set 2010 track cuts yet!!"<<endl;
    fEsdtrackCutsITSTPC = AliESDtrackCuts::GetStandardITSTPCTrackCuts2010(selectPrimaries);
    fEsdtrackCutsITSTPC->SetName("fEsdTrackCuts");
    fEsdtrackCutsTPC = AliESDtrackCuts::GetStandardTPCOnlyTrackCuts();
    fEsdtrackCutsTPC->SetName("fEsdTrackCutsTPCOnly");
    //ITS stand alone cuts - similar to 2009 cuts but with only ITS hits required
    fEsdtrackCutsITS =  AliESDtrackCuts::GetStandardITSPureSATrackCuts2010(kTRUE,kFALSE);//we do want primaries but we do not want to require PID info
    fEsdtrackCutsITS->SetName("fEsdTrackCutsITS");
  }
  if(fRecAnalysis->DataSet()==20100){
    cout<<"Setting track cuts for the 2010 Pb+Pb collisions at 2.76 TeV"<<endl;
    //cout<<"Warning:  Have not set 2010 track cuts yet!!"<<endl;
    fEsdtrackCutsITSTPC = AliESDtrackCuts::GetStandardITSTPCTrackCuts2010(selectPrimaries);
    fEsdtrackCutsITSTPC->SetName("fEsdTrackCuts");
    fEsdtrackCutsTPC = AliESDtrackCuts::GetStandardTPCOnlyTrackCuts();
    fEsdtrackCutsTPC->SetName("fEsdTrackCutsTPCOnly");
    //ITS stand alone cuts - similar to 2009 cuts but with only ITS hits required
    fEsdtrackCutsITS =  AliESDtrackCuts::GetStandardITSSATrackCutsPbPb2010(kTRUE,kFALSE);//we do want primaries but we do not want to require PID info
    // fEsdtrackCutsITS =  AliESDtrackCuts::GetStandardITSPureSATrackCuts2010(kTRUE,kFALSE);//we do want primaries but we do not want to require PID info
   fEsdtrackCutsITS->SetName("fEsdTrackCutsITS");
  }

  fOutputList->Add(fEsdtrackCutsITSTPC);
  fOutputList->Add(fEsdtrackCutsTPC);
  fOutputList->Add(fEsdtrackCutsITS);
  if (fEsdtrackCutsITSTPC && fEsdtrackCutsTPC) {
    fRecAnalysis->SetITSTrackCuts( GetITSTrackCuts());
    if (fMCAnalysis)
      fMCAnalysis->SetITSTrackCuts( GetITSTrackCuts());
    fRecAnalysis->SetTPCITSTrackCuts( GetTPCITSTrackCuts());
    if (fMCAnalysis)
      fMCAnalysis->SetTPCITSTrackCuts( GetTPCITSTrackCuts());
    fRecAnalysis->SetTPCOnlyTrackCuts( GetTPCOnlyTrackCuts());
    if (fMCAnalysis)
      fMCAnalysis->SetTPCOnlyTrackCuts( GetTPCOnlyTrackCuts());
    //add ITS stuff!
  }
  else {
    Printf("Error: no track cuts!");
  }

}

//________________________________________________________________________
void AliAnalysisTaskTotEt::UserExec(Option_t *)
{ // execute method

  fESDEvent = dynamic_cast<AliESDEvent*>(InputEvent());
  if (!fESDEvent)
    {
      Printf("ERROR: Could not retrieve event");
      return;
    }

  //Int_t res = CheckPhysicsSelection(fESDEvent->GetRunNumber());

  AliCentrality *cent = GetCentralityObject();

  //if (res == 0 && cent)
  //{
  if (IsPhysicsSelected())
    {
      fRecAnalysis->SetCentralityObject(cent);
      fRecAnalysis->AnalyseEvent(fESDEvent);

      AliMCEvent* mcEvent = MCEvent();
      if (mcEvent)
	{
	  fMCAnalysis->SetCentralityObject(cent);
	  fMCAnalysis->AnalyseEvent(mcEvent, fESDEvent);
	  //fMCAnalysis->AnalyseEvent(mcEvent);
	}
      if(fMCAnalysis)
	{
	  fHistEtRecvsEtMC->Fill(fRecAnalysis->GetTotNeutralEtAcc(), fMCAnalysis->GetTotNeutralEtAcc());
	  if(fMCAnalysis->GetTotNeutralEtAcc()) fHistEtRecOverEtMC->Fill(fRecAnalysis->GetTotNeutralEt()/fMCAnalysis->GetTotNeutralEtAcc(), cent->GetCentralityClass10("V0M"));
	  if(fMCAnalysis->GetTotNeutralEtAcc()) fHistDiffEtRecEtMCOverEtMC->Fill(fMCAnalysis->GetTotNeutralEt(), (fRecAnalysis->GetTotNeutralEt()-fMCAnalysis->GetTotNeutralEt())/fMCAnalysis->GetTotNeutralEt());
	}
    }
  //}
  // Post output data.
  PostData(1, fOutputList);
}

//________________________________________________________________________
void AliAnalysisTaskTotEt::Terminate(Option_t *)
{
  // Draw result to the screen
  // Called once at the end of the query

  fOutputList = dynamic_cast<TList*> (GetOutputData(1));
  if (!fOutputList) {
    printf("ERROR: Output list not available\n");
    return;
  }
}

<|endoftext|>