{"text":"\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit (ITK)\n Module:\n Language: C++\n Date:\n Version:\n\n\nCopyright (c) 2000 National Library of Medicine\nAll rights reserved.\n\nSee COPYRIGHT.txt for copyright details.\n\n=========================================================================*\/\n#include \n\/\/ This file has been generated by BuildHeaderTest.tcl\n\/\/ Test to include each header file for Insight\n\n#include \"itkAcosImageAdaptor.h\"\n#include \"itkAffineRegistrationTransform.h\"\n#include \"itkAffineTransform.h\"\n#include \"itkAffineTransformation.h\"\n#include \"itkArray.h\"\n#include \"itkAsinImageAdaptor.h\"\n#include \"itkAtanImageAdaptor.h\"\n#include \"itkBackwardDifferenceOperator.h\"\n#include \"itkBlueDataAccessor.h\"\n#include \"itkBoundingBox.h\"\n#include \"itkByteSwapper.h\"\n#include \"itkCellBoundary.h\"\n#include \"itkCellInterface.h\"\n#include \"itkCellInterfaceVisitor.h\"\n#include \"itkCentralDerivativeImageFunction.h\"\n#include \"itkColorTable.h\"\n#include \"itkCommand.h\"\n#include \"itkConceptChecking.h\"\n#include \"itkConstSliceIterator.h\"\n#include \"itkConstantBoundaryCondition.h\"\n#include \"itkContinuousImageFunction.h\"\n#include \"itkContinuousIndex.h\"\n#include \"itkCosImageAdaptor.h\"\n#include \"itkCovariantVector.h\"\n#include \"itkCreateObjectFunction.h\"\n#include \"itkDataAccessor.h\"\n#include \"itkDataObject.h\"\n#include \"itkDefaultDataAccessor.h\"\n#include \"itkDefaultDynamicMeshTraits.h\"\n#include \"itkDefaultImageTraits.h\"\n#include \"itkDefaultStaticMeshTraits.h\"\n#include \"itkDerivativeOperator.h\"\n#include \"itkDirectory.h\"\n#include \"itkDynamicLoader.h\"\n#include \"itkElasticBodySplineKernelTransform.h\"\n#include \"itkEntropyPreservingGradientMagnitudeImageFunction.h\"\n#include \"itkExceptionObject.h\"\n#include \"itkExpImageAdaptor.h\"\n#include \"itkFastMutexLock.h\"\n#include \"itkForwardDifferenceOperator.h\"\n#include \"itkGaussianOperator.h\"\n#include \"itkGreenDataAccessor.h\"\n#include \"itkHexahedronCell.h\"\n#include \"itkImage.h\"\n#include \"itkImageAdaptor.h\"\n#include \"itkImageBase.h\"\n#include \"itkImageBoundaryCondition.h\"\n#include \"itkImageBufferIterator.h\"\n#include \"itkImageConstIteratorWithIndex.h\"\n#include \"itkImageContainerInterface.h\"\n#include \"itkImageFunction.h\"\n#include \"itkImageIO.h\"\n#include \"itkImageIOCommon.h\"\n#include \"itkImageIterator.h\"\n#include \"itkImageIteratorWithIndex.h\"\n#include \"itkImageLinearConstIterator.h\"\n#include \"itkImageLinearIterator.h\"\n#include \"itkImageRegion.h\"\n#include \"itkImageRegionIterator.h\"\n#include \"itkImageSliceConstIterator.h\"\n#include \"itkImageSliceIterator.h\"\n#include \"itkImageSource.h\"\n#include \"itkImageToImageFilter.h\"\n#include \"itkImportImageContainer.h\"\n#include \"itkIndent.h\"\n#include \"itkIndex.h\"\n#include \"itkIndexedContainerInterface.h\"\n#include \"itkIntTypes.h\"\n#include \"itkKernelTransform.h\"\n#include \"itkLevelSetCurvatureFunction.h\"\n#include \"itkLightObject.h\"\n#include \"itkLightProcessObject.h\"\n#include \"itkLineCell.h\"\n#include \"itkLinearInterpolateImageFunction.h\"\n#include \"itkLog10ImageAdaptor.h\"\n#include \"itkLogImageAdaptor.h\"\n#include \"itkMacro.h\"\n#include \"itkMapContainer.h\"\n#include \"itkMatrix.h\"\n#include \"itkMesh.h\"\n#include \"itkMeshRegion.h\"\n#include \"itkMultiThreader.h\"\n#include \"itkMutexLock.h\"\n#include \"itkNeighborhood.h\"\n#include \"itkNeighborhoodAlgorithm.h\"\n#include \"itkNeighborhoodAllocator.h\"\n#include \"itkNeighborhoodIterator.h\"\n#include \"itkNeighborhoodOperator.h\"\n#include \"itkNthElementDataAccessor.h\"\n#include \"itkNthElementImageAdaptor.h\"\n#include \"itkNumericTraits.h\"\n#include \"itkObject.h\"\n#include \"itkObjectFactory.h\"\n#include \"itkObjectFactoryBase.h\"\n#include \"itkOffset.h\"\n#include \"itkOutputWindow.h\"\n#include \"itkPhysicalImage.h\"\n#include \"itkPhysicalImageAdaptor.h\"\n#include \"itkPixelTraits.h\"\n#include \"itkPoint.h\"\n#include \"itkPointLocator.h\"\n#include \"itkPointSet.h\"\n#include \"itkProcessObject.h\"\n#include \"itkQuadrilateralCell.h\"\n#include \"itkRGBPixel.h\"\n#include \"itkRandomAccessNeighborhoodIterator.h\"\n#include \"itkRedDataAccessor.h\"\n#include \"itkRegion.h\"\n#include \"itkRegionBoundaryNeighborhoodIterator.h\"\n#include \"itkRegionNeighborhoodIterator.h\"\n#include \"itkRegionNonBoundaryNeighborhoodIterator.h\"\n#include \"itkRigid3DRegistrationTransform.h\"\n#include \"itkRigid3DTransform.h\"\n#include \"itkScalar.h\"\n#include \"itkScalarImageRegionIterator.h\"\n#include \"itkScalarVector.h\"\n#include \"itkSimpleImageRegionConstIterator.h\"\n#include \"itkSimpleImageRegionIterator.h\"\n#include \"itkSinImageAdaptor.h\"\n#include \"itkSize.h\"\n#include \"itkSliceIterator.h\"\n#include \"itkSmartPointer.h\"\n#include \"itkSmartPointerForwardReference.h\"\n#include \"itkSmartRegionNeighborhoodIterator.h\"\n#include \"itkSqrtImageAdaptor.h\"\n#include \"itkStatDenseHistogram.h\"\n#include \"itkStatHistogram.h\"\n#include \"itkStatSparseHistogram.h\"\n#include \"itkTanImageAdaptor.h\"\n#include \"itkTetrahedronCell.h\"\n#include \"itkThinPlateSplineKernelTransform.h\"\n#include \"itkTimeStamp.h\"\n#include \"itkTransformation.h\"\n#include \"itkTranslationRegistrationTransform.h\"\n#include \"itkTranslationTransform.h\"\n#include \"itkTriangleCell.h\"\n#include \"itkUpwindDerivativeImageFunction.h\"\n#include \"itkValarrayImageContainer.h\"\n#include \"itkVector.h\"\n#include \"itkVectorContainer.h\"\n#include \"itkVersion.h\"\n#include \"itkVertexCell.h\"\n#include \"itkWeakPointer.h\"\n#include \"itkWin32Header.h\"\n#include \"itkWin32OutputWindow.h\"\n#include \"itkZeroFluxNeumannBoundaryCondition.h\"\n#include \"itk_alloc.h\"\n#include \"itk_hash_map.h\"\n#include \"itk_hash_set.h\"\n#include \"itk_hashtable.h\"\n#include \"vcl_alloc.h\"\n\nint main ( int argc, char* argv )\n{\n \n return 0;\n}\n\nENH: Updated to latest headers\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit (ITK)\n Module:\n Language: C++\n Date:\n Version:\n\n\nCopyright (c) 2000 National Library of Medicine\nAll rights reserved.\n\nSee COPYRIGHT.txt for copyright details.\n\n=========================================================================*\/\n#include \n\/\/ This file has been generated by BuildHeaderTest.tcl\n\/\/ Test to include each header file for Insight\n\n#include \"itkAcosImageAdaptor.h\"\n#include \"itkAffineRegistrationTransform.h\"\n#include \"itkAffineTransform.h\"\n#include \"itkAffineTransformation.h\"\n#include \"itkArray.h\"\n#include \"itkAsinImageAdaptor.h\"\n#include \"itkAtanImageAdaptor.h\"\n#include \"itkBackwardDifferenceOperator.h\"\n#include \"itkBlueDataAccessor.h\"\n#include \"itkBoundingBox.h\"\n#include \"itkByteSwapper.h\"\n#include \"itkCellBoundary.h\"\n#include \"itkCellInterface.h\"\n#include \"itkCellInterfaceVisitor.h\"\n#include \"itkCentralDerivativeImageFunction.h\"\n#include \"itkColorTable.h\"\n#include \"itkCommand.h\"\n#include \"itkConceptChecking.h\"\n#include \"itkConstSliceIterator.h\"\n#include \"itkConstantBoundaryCondition.h\"\n#include \"itkContinuousImageFunction.h\"\n#include \"itkContinuousIndex.h\"\n#include \"itkCosImageAdaptor.h\"\n#include \"itkCovariantVector.h\"\n#include \"itkCreateObjectFunction.h\"\n#include \"itkDataAccessor.h\"\n#include \"itkDataObject.h\"\n#include \"itkDefaultDataAccessor.h\"\n#include \"itkDefaultDynamicMeshTraits.h\"\n#include \"itkDefaultImageTraits.h\"\n#include \"itkDefaultStaticMeshTraits.h\"\n#include \"itkDerivativeOperator.h\"\n#include \"itkDirectory.h\"\n#include \"itkDynamicLoader.h\"\n#include \"itkElasticBodySplineKernelTransform.h\"\n#include \"itkEntropyPreservingGradientMagnitudeImageFunction.h\"\n#include \"itkExceptionObject.h\"\n#include \"itkExpImageAdaptor.h\"\n#include \"itkFastMutexLock.h\"\n#include \"itkForwardDifferenceOperator.h\"\n#include \"itkGaussianOperator.h\"\n#include \"itkGreenDataAccessor.h\"\n#include \"itkHexahedronCell.h\"\n#include \"itkImage.h\"\n#include \"itkImageAdaptor.h\"\n#include \"itkImageBase.h\"\n#include \"itkImageBoundaryCondition.h\"\n#include \"itkImageBufferIterator.h\"\n#include \"itkImageConstIteratorWithIndex.h\"\n#include \"itkImageContainerInterface.h\"\n#include \"itkImageFunction.h\"\n#include \"itkImageIO.h\"\n#include \"itkImageIOCommon.h\"\n#include \"itkImageIterator.h\"\n#include \"itkImageIteratorWithIndex.h\"\n#include \"itkImageLinearConstIterator.h\"\n#include \"itkImageLinearIterator.h\"\n#include \"itkImageRegion.h\"\n#include \"itkImageRegionIterator.h\"\n#include \"itkImageSliceConstIterator.h\"\n#include \"itkImageSliceIterator.h\"\n#include \"itkImageSource.h\"\n#include \"itkImageToImageFilter.h\"\n#include \"itkImportImageContainer.h\"\n#include \"itkIndent.h\"\n#include \"itkIndex.h\"\n#include \"itkIndexedContainerInterface.h\"\n#include \"itkIntTypes.h\"\n#include \"itkKernelTransform.h\"\n#include \"itkLevelSetCurvatureFunction.h\"\n#include \"itkLightObject.h\"\n#include \"itkLightProcessObject.h\"\n#include \"itkLineCell.h\"\n#include \"itkLinearInterpolateImageFunction.h\"\n#include \"itkLog10ImageAdaptor.h\"\n#include \"itkLogImageAdaptor.h\"\n#include \"itkMacro.h\"\n#include \"itkMapContainer.h\"\n#include \"itkMatrix.h\"\n#include \"itkMesh.h\"\n#include \"itkMeshRegion.h\"\n#include \"itkMultiThreader.h\"\n#include \"itkMutexLock.h\"\n#include \"itkNeighborhood.h\"\n#include \"itkNeighborhoodAlgorithm.h\"\n#include \"itkNeighborhoodAllocator.h\"\n#include \"itkNeighborhoodIterator.h\"\n#include \"itkNeighborhoodOperator.h\"\n#include \"itkNthElementDataAccessor.h\"\n#include \"itkNthElementImageAdaptor.h\"\n#include \"itkNumericTraits.h\"\n#include \"itkObject.h\"\n#include \"itkObjectFactory.h\"\n#include \"itkObjectFactoryBase.h\"\n#include \"itkOffset.h\"\n#include \"itkOutputWindow.h\"\n#include \"itkPhysicalImage.h\"\n#include \"itkPhysicalImageAdaptor.h\"\n#include \"itkPixelTraits.h\"\n#include \"itkPoint.h\"\n#include \"itkPointLocator.h\"\n#include \"itkPointSet.h\"\n#include \"itkProcessObject.h\"\n#include \"itkQuadrilateralCell.h\"\n#include \"itkRGBPixel.h\"\n#include \"itkRandomAccessNeighborhoodIterator.h\"\n#include \"itkRedDataAccessor.h\"\n#include \"itkRegion.h\"\n#include \"itkRegionBoundaryNeighborhoodIterator.h\"\n#include \"itkRegionNeighborhoodIterator.h\"\n#include \"itkRegionNonBoundaryNeighborhoodIterator.h\"\n#include \"itkRigid3DRegistrationTransform.h\"\n#include \"itkRigid3DTransform.h\"\n#include \"itkScalar.h\"\n#include \"itkScalarImageRegionIterator.h\"\n#include \"itkScalarVector.h\"\n#include \"itkSimpleImageRegionConstIterator.h\"\n#include \"itkSimpleImageRegionIterator.h\"\n#include \"itkSinImageAdaptor.h\"\n#include \"itkSize.h\"\n#include \"itkSliceIterator.h\"\n#include \"itkSmartPointer.h\"\n#include \"itkSmartPointerForwardReference.h\"\n#include \"itkSmartRegionNeighborhoodIterator.h\"\n#include \"itkSqrtImageAdaptor.h\"\n#include \"itkStatDenseHistogram.h\"\n#include \"itkStatHistogram.h\"\n#include \"itkStatSparseHistogram.h\"\n#include \"itkTanImageAdaptor.h\"\n#include \"itkTetrahedronCell.h\"\n#include \"itkThinPlateSplineKernelTransform.h\"\n#include \"itkTimeStamp.h\"\n#include \"itkTransformation.h\"\n#include \"itkTranslationRegistrationTransform.h\"\n#include \"itkTranslationTransform.h\"\n#include \"itkTriangleCell.h\"\n#include \"itkUpwindDerivativeImageFunction.h\"\n#include \"itkValarrayImageContainer.h\"\n#include \"itkVector.h\"\n#include \"itkVectorContainer.h\"\n#include \"itkVersion.h\"\n#include \"itkVertexCell.h\"\n#include \"itkWeakPointer.h\"\n#include \"itkZeroFluxNeumannBoundaryCondition.h\"\n#include \"itk_alloc.h\"\n#include \"itk_hash_map.h\"\n#include \"itk_hash_set.h\"\n#include \"itk_hashtable.h\"\n#include \"vcl_alloc.h\"\n\nint main ( int argc, char* argv )\n{\n \n return 0;\n}\n\n<|endoftext|>"} {"text":"\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit (ITK)\n Module: itkSmartPointerTest.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\nCopyright (c) 2000 National Library of Medicine\nAll rights reserved.\n\nSee COPYRIGHT.txt for copyright details.\n\n=========================================================================*\/\n#include \n#include \"itkSmartPointer.h\"\n\nclass itkTestObject\n{\npublic:\n typedef itk::SmartPointer Pointer;\n static itkTestObject::Pointer New();\n virtual void Register()\n {\n std::cout << \"Register \" << *this << \" count:\" \n << (m_ReferenceCount+1) << \" \" << std::endl;\n m_ReferenceCount++;\n }\n virtual void UnRegister()\n {\n std::cout << \"UnRegister \" << this << \" count:\" \n << (m_ReferenceCount-1) << \" \" << std::endl;\n \n m_ReferenceCount--;\n if ( m_ReferenceCount == 0 )\n {\n delete this;\n }\n }\n inline friend std::ostream &operator << (std::ostream &os, \n itkTestObject const& o) \n {\n os << \"itkTestObject \" << (void*)&o << \" \" << o.m_ReferenceCount; \n return os;\n }\n \n std::ostream& Print(std::ostream& os) const\n {\n os << \"itkTestObject \" << (void*)this << \" \" << this->m_ReferenceCount; \n return os;\n } \n\nprotected:\n itkTestObject() \n {\n m_ReferenceCount = 0;\n std::cout << \"construct itkTestObject \" << *this << std::endl; \n }\n ~itkTestObject() \n {\n std::cout << \"destruct itkTestObject \" << *this << std::endl; \n }\n\nprivate:\n unsigned int m_ReferenceCount;\n};\n\nitkTestObject::Pointer itkTestObject::New()\n{\n return itkTestObject::Pointer(new itkTestObject);\n}\n\nclass itkTestObjectSubClass : public itkTestObject\n{\npublic:\n typedef itk::SmartPointer Pointer;\n static Pointer New();\n};\n\n\nitkTestObjectSubClass::Pointer itkTestObjectSubClass::New()\n{\n return itkTestObjectSubClass::Pointer(new itkTestObjectSubClass);\n}\n\nvoid TestUpCastPointer(itkTestObject::Pointer p)\n{\n}\n\nvoid TestUpCast(itkTestObject* p)\n{\n}\n\n\nint main()\n{\n itkTestObject::Pointer to(itkTestObjectSubClass::New());\n itkTestObjectSubClass::Pointer sc = dynamic_cast((itkTestObject*)to);\n TestUpCast(sc);\n TestUpCastPointer(sc.GetPointer());\n std::cout <<\"second test\" << std::endl;\n {\n itkTestObject::Pointer o1 = itkTestObject::New();\n std::cout << \"o1 \" << &o1 << std::endl;\n itkTestObject::Pointer o2 = itkTestObject::New();\n std::cout << \"o2 \" << &o2 << std::endl;\n itkTestObject::Pointer o3 = itkTestObject::New();\n std::cout << \"o3 \" << &o3 << std::endl;\n itkTestObject::Pointer o4 = itkTestObject::New();\n std::cout << \"o4 \" << &o4 << std::endl;\n \n o1 = o2;\n o2 = o3;\n o4 = o1;\n if ( o1 < o2 )\n {\n std::cout << \"o1 is < o2 \" << o1 << \" \" << o2 << std::endl;\n }\n else\n {\n std::cout << \"o1 is not < o2 \" << &o1 << \" \" << &o2 << std::endl;\n }\n }\n std::cout <<\"end second test\" << std::endl << std::endl;\n\n std::cout <<\"first test\" << std::endl;\n {\n itkTestObject::Pointer o1 = itkTestObject::New();\n }\n std::cout <<\"end first test\" << std::endl << std::endl;\n return 0;\n}\n\n\nENH: better comments\/examples on smart pointer usage\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit (ITK)\n Module: itkSmartPointerTest.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\nCopyright (c) 2000 National Library of Medicine\nAll rights reserved.\n\nSee COPYRIGHT.txt for copyright details.\n\n=========================================================================*\/\n#include \n#include \"itkSmartPointer.h\"\n\nclass itkTestObject\n{\npublic:\n typedef itk::SmartPointer Pointer;\n static itkTestObject::Pointer New();\n virtual void Register()\n {\n std::cout << \"Register \" << *this << \" count:\" \n << (m_ReferenceCount+1) << \" \" << std::endl;\n m_ReferenceCount++;\n }\n virtual void UnRegister()\n {\n std::cout << \"UnRegister \" << this << \" count:\" \n << (m_ReferenceCount-1) << \" \" << std::endl;\n \n m_ReferenceCount--;\n if ( m_ReferenceCount == 0 )\n {\n delete this;\n }\n }\n inline friend std::ostream &operator << (std::ostream &os, \n itkTestObject const& o) \n {\n os << \"itkTestObject \" << (void*)&o << \" \" << o.m_ReferenceCount; \n return os;\n }\n \n std::ostream& Print(std::ostream& os) const\n {\n os << \"itkTestObject \" << (void*)this << \" \" << this->m_ReferenceCount; \n return os;\n } \n\nprotected:\n itkTestObject() \n {\n m_ReferenceCount = 0;\n std::cout << \"construct itkTestObject \" << *this << std::endl; \n }\n ~itkTestObject() \n {\n std::cout << \"destruct itkTestObject \" << *this << std::endl; \n }\n\nprivate:\n unsigned int m_ReferenceCount;\n};\n\nitkTestObject::Pointer itkTestObject::New()\n{\n return itkTestObject::Pointer(new itkTestObject);\n}\n\nclass itkTestObjectSubClass : public itkTestObject\n{\npublic:\n typedef itk::SmartPointer Pointer;\n static Pointer New();\n};\n\n\nitkTestObjectSubClass::Pointer itkTestObjectSubClass::New()\n{\n return itkTestObjectSubClass::Pointer(new itkTestObjectSubClass);\n}\n\n\/\/ This SHOULD NOT be used in ITK, all functions\n\/\/ should take raw pointers as arguments\nvoid TestUpCastPointer(itkTestObject::Pointer p)\n{\n}\n\n\/\/ Test a function that takes an itkTestObject raw pointer\nvoid TestUpCast(itkTestObject* p)\n{\n}\n\n\nint main()\n{\n \/\/ Create a base class pointer to a child class\n itkTestObject::Pointer to(itkTestObjectSubClass::New());\n \/\/ test the safe down cast and create a child class Pointer object\n itkTestObjectSubClass::Pointer sc \n = dynamic_cast(to.GetPointer());\n \/\/ Test the up cast with a function that takes a pointer\n TestUpCast(sc);\n \/\/ Test calling a function that takes a SmartPointer as\n \/\/ an argument, note, that you have to get the raw pointer\n \/\/ for this to work\n TestUpCastPointer(sc.GetPointer());\n\n \/\/ Test casting up the tree, note no explict cast is required\n itkTestObject::Pointer p = sc;\n \n std::cout <<\"second test\" << std::endl;\n {\n itkTestObject::Pointer o1 = itkTestObject::New();\n std::cout << \"o1 \" << &o1 << std::endl;\n itkTestObject::Pointer o2 = itkTestObject::New();\n std::cout << \"o2 \" << &o2 << std::endl;\n itkTestObject::Pointer o3 = itkTestObject::New();\n std::cout << \"o3 \" << &o3 << std::endl;\n itkTestObject::Pointer o4 = itkTestObject::New();\n std::cout << \"o4 \" << &o4 << std::endl;\n \n o1 = o2;\n o2 = o3;\n o4 = o1;\n if ( o1 < o2 )\n {\n std::cout << \"o1 is < o2 \" << o1 << \" \" << o2 << std::endl;\n }\n else\n {\n std::cout << \"o1 is not < o2 \" << &o1 << \" \" << &o2 << std::endl;\n }\n }\n std::cout <<\"end second test\" << std::endl << std::endl;\n\n std::cout <<\"first test\" << std::endl;\n {\n itkTestObject::Pointer o1 = itkTestObject::New();\n }\n std::cout <<\"end first test\" << std::endl << std::endl;\n return 0;\n}\n\n\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: thesdsp.cxx,v $\n *\n * $Revision: 1.12 $\n *\n * last change: $Author: obo $ $Date: 2006-09-17 03:56:17 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_linguistic.hxx\"\n\n#ifndef INCLUDED_I18NPOOL_LANG_H\n#include \n#endif\n#ifndef _TOOLS_DEBUG_HXX \/\/autogen wg. DBG_ASSERT\n#include \n#endif\n#ifndef _SVTOOLS_LNGMISC_HXX_\n#include \n#endif\n\n#include \/\/ helper for factories\n#include \n#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_\n#include \n#endif\n\n#ifndef _UNOTOOLS_PROCESSFACTORY_HXX_\n#include \n#endif\n#ifndef _OSL_MUTEX_HXX_\n#include \n#endif\n\n#include \"thesdsp.hxx\"\n#include \"lngprops.hxx\"\n\nusing namespace utl;\nusing namespace osl;\nusing namespace rtl;\nusing namespace com::sun::star;\nusing namespace com::sun::star::beans;\nusing namespace com::sun::star::lang;\nusing namespace com::sun::star::uno;\nusing namespace com::sun::star::linguistic2;\nusing namespace linguistic;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic BOOL SvcListHasLanguage(\n const Sequence< Reference< XThesaurus > > &rRefs,\n const Locale &rLocale )\n{\n BOOL bHasLanguage = FALSE;\n\n const Reference< XThesaurus > *pRef = rRefs.getConstArray();\n INT32 nLen = rRefs.getLength();\n for (INT32 k = 0; k < nLen && !bHasLanguage; ++k)\n {\n if (pRef[k].is())\n bHasLanguage = pRef[k]->hasLocale( rLocale );\n }\n\n return bHasLanguage;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nSeqLangSvcEntry_Thes::~SeqLangSvcEntry_Thes()\n{\n}\n\n\nSeqLangSvcEntry_Thes::SeqLangSvcEntry_Thes(\n const Sequence< OUString > &rSvcImplNames ) :\n aSvcImplNames ( rSvcImplNames ),\n aSvcRefs ( rSvcImplNames.getLength() )\n{\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nThesaurusDispatcher::ThesaurusDispatcher()\n{\n}\n\n\nThesaurusDispatcher::~ThesaurusDispatcher()\n{\n ClearSvcList();\n}\n\n\nvoid ThesaurusDispatcher::ClearSvcList()\n{\n \/\/ release memory for each table entry\n SeqLangSvcEntry_Thes *pItem = aSvcList.First();\n while (pItem)\n {\n SeqLangSvcEntry_Thes *pTmp = pItem;\n pItem = aSvcList.Next();\n delete pTmp;\n }\n}\n\n\nSequence< Locale > SAL_CALL\n ThesaurusDispatcher::getLocales()\n throw(RuntimeException)\n{\n MutexGuard aGuard( GetLinguMutex() );\n\n ULONG nCnt = aSvcList.Count();\n Sequence< Locale > aLocales( nCnt );\n Locale *pItem = aLocales.getArray();\n SeqLangSvcEntry_Thes *pEntry = aSvcList.First();\n for (ULONG i = 0; i < nCnt; i++)\n {\n DBG_ASSERT( pEntry, \"lng : pEntry is NULL pointer\" );\n pItem[i] = CreateLocale( (LanguageType) aSvcList.GetKey( pEntry ) );\n pEntry = aSvcList.Next();\n }\n return aLocales;\n}\n\n\nsal_Bool SAL_CALL\n ThesaurusDispatcher::hasLocale( const Locale& rLocale )\n throw(RuntimeException)\n{\n MutexGuard aGuard( GetLinguMutex() );\n return 0 != aSvcList.Get( LocaleToLanguage( rLocale ) );\n}\n\n\nSequence< Reference< XMeaning > > SAL_CALL\n ThesaurusDispatcher::queryMeanings(\n const OUString& rTerm, const Locale& rLocale,\n const PropertyValues& rProperties )\n throw(IllegalArgumentException, RuntimeException)\n{\n MutexGuard aGuard( GetLinguMutex() );\n\n Sequence< Reference< XMeaning > > aMeanings;\n\n INT16 nLanguage = LocaleToLanguage( rLocale );\n if (nLanguage == LANGUAGE_NONE || !rTerm.getLength())\n return aMeanings;\n\n \/\/ search for entry with that language\n SeqLangSvcEntry_Thes *pEntry = aSvcList.Get( nLanguage );\n\n if (!pEntry)\n {\n#ifdef LINGU_EXCEPTIONS\n throw IllegalArgumentException();\n#endif\n }\n else\n {\n OUString aChkWord( rTerm );\n aChkWord = aChkWord.replace( SVT_HARD_SPACE, ' ' );\n RemoveHyphens( aChkWord );\n if (IsIgnoreControlChars( rProperties, GetPropSet() ))\n RemoveControlChars( aChkWord );\n\n INT32 nLen = pEntry->aSvcRefs.getLength();\n DBG_ASSERT( nLen == pEntry->aSvcImplNames.getLength(),\n \"lng : sequence length mismatch\");\n DBG_ASSERT( pEntry->aFlags.nLastTriedSvcIndex < nLen,\n \"lng : index out of range\");\n\n INT32 i = 0;\n\n \/\/ try already instantiated services first\n {\n const Reference< XThesaurus > *pRef = pEntry->aSvcRefs.getConstArray();\n while (i <= pEntry->aFlags.nLastTriedSvcIndex\n && aMeanings.getLength() == 0)\n {\n if (pRef[i].is() && pRef[i]->hasLocale( rLocale ))\n aMeanings = pRef[i]->queryMeanings( aChkWord, rLocale, rProperties );\n ++i;\n }\n }\n\n \/\/ if still no result instantiate new services and try those\n if (aMeanings.getLength() == 0\n && pEntry->aFlags.nLastTriedSvcIndex < nLen - 1)\n {\n const OUString *pImplNames = pEntry->aSvcImplNames.getConstArray();\n Reference< XThesaurus > *pRef = pEntry->aSvcRefs.getArray();\n\n Reference< XMultiServiceFactory > xMgr( getProcessServiceFactory() );\n if (xMgr.is())\n {\n \/\/ build service initialization argument\n Sequence< Any > aArgs(1);\n aArgs.getArray()[0] <<= GetPropSet();\n\n while (i < nLen && aMeanings.getLength() == 0)\n {\n \/\/ create specific service via it's implementation name\n Reference< XThesaurus > xThes(\n xMgr->createInstanceWithArguments(\n pImplNames[i], aArgs ),\n UNO_QUERY );\n pRef[i] = xThes;\n\n if (xThes.is() && xThes->hasLocale( rLocale ))\n aMeanings = xThes->queryMeanings( aChkWord, rLocale, rProperties );\n\n pEntry->aFlags.nLastTriedSvcIndex = (INT16) i;\n ++i;\n }\n\n \/\/ if language is not supported by any of the services\n \/\/ remove it from the list.\n if (i == nLen && aMeanings.getLength() == 0)\n {\n if (!SvcListHasLanguage( pEntry->aSvcRefs, rLocale ))\n aSvcList.Remove( nLanguage );\n }\n }\n }\n }\n\n return aMeanings;\n}\n\n\nvoid ThesaurusDispatcher::SetServiceList( const Locale &rLocale,\n const Sequence< OUString > &rSvcImplNames )\n{\n MutexGuard aGuard( GetLinguMutex() );\n\n INT16 nLanguage = LocaleToLanguage( rLocale );\n\n if (0 == rSvcImplNames.getLength())\n \/\/ remove entry\n aSvcList.Remove( nLanguage );\n else\n {\n \/\/ modify\/add entry\n SeqLangSvcEntry_Thes *pEntry = aSvcList.Get( nLanguage );\n if (pEntry)\n {\n pEntry->aSvcImplNames = rSvcImplNames;\n pEntry->aSvcRefs = Sequence< Reference < XThesaurus > >(\n rSvcImplNames.getLength() );\n pEntry->aFlags = SvcFlags();\n }\n else\n {\n pEntry = new SeqLangSvcEntry_Thes( rSvcImplNames );\n aSvcList.Insert( nLanguage, pEntry );\n DBG_ASSERT( aSvcList.Get( nLanguage ), \"lng : Insert failed\" );\n }\n }\n}\n\n\nSequence< OUString >\n ThesaurusDispatcher::GetServiceList( const Locale &rLocale ) const\n{\n MutexGuard aGuard( GetLinguMutex() );\n\n Sequence< OUString > aRes;\n\n \/\/ search for entry with that language and use data from that\n INT16 nLanguage = LocaleToLanguage( rLocale );\n ThesaurusDispatcher *pThis = (ThesaurusDispatcher *) this;\n const SeqLangSvcEntry_Thes *pEntry = pThis->aSvcList.Get( nLanguage );\n if (pEntry)\n aRes = pEntry->aSvcImplNames;\n\n return aRes;\n}\n\n\nThesaurusDispatcher::DspType\n ThesaurusDispatcher::GetDspType() const\n{\n return DSP_THES;\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nINTEGRATION: CWS tl51_DEV300 (1.12.52); FILE MERGED 2007\/11\/15 12:53:37 tl 1.12.52.1: #150990# catch exception from createInstance(WithArguments) calls\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: thesdsp.cxx,v $\n *\n * $Revision: 1.13 $\n *\n * last change: $Author: obo $ $Date: 2008-03-26 09:06:37 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_linguistic.hxx\"\n\n#ifndef INCLUDED_I18NPOOL_LANG_H\n#include \n#endif\n#ifndef _TOOLS_DEBUG_HXX \/\/autogen wg. DBG_ASSERT\n#include \n#endif\n#ifndef _SVTOOLS_LNGMISC_HXX_\n#include \n#endif\n\n#include \/\/ helper for factories\n#include \n#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_\n#include \n#endif\n\n#ifndef _UNOTOOLS_PROCESSFACTORY_HXX_\n#include \n#endif\n#ifndef _OSL_MUTEX_HXX_\n#include \n#endif\n\n#include \"thesdsp.hxx\"\n#include \"lngprops.hxx\"\n\nusing namespace utl;\nusing namespace osl;\nusing namespace rtl;\nusing namespace com::sun::star;\nusing namespace com::sun::star::beans;\nusing namespace com::sun::star::lang;\nusing namespace com::sun::star::uno;\nusing namespace com::sun::star::linguistic2;\nusing namespace linguistic;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic BOOL SvcListHasLanguage(\n const Sequence< Reference< XThesaurus > > &rRefs,\n const Locale &rLocale )\n{\n BOOL bHasLanguage = FALSE;\n\n const Reference< XThesaurus > *pRef = rRefs.getConstArray();\n INT32 nLen = rRefs.getLength();\n for (INT32 k = 0; k < nLen && !bHasLanguage; ++k)\n {\n if (pRef[k].is())\n bHasLanguage = pRef[k]->hasLocale( rLocale );\n }\n\n return bHasLanguage;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nSeqLangSvcEntry_Thes::~SeqLangSvcEntry_Thes()\n{\n}\n\n\nSeqLangSvcEntry_Thes::SeqLangSvcEntry_Thes(\n const Sequence< OUString > &rSvcImplNames ) :\n aSvcImplNames ( rSvcImplNames ),\n aSvcRefs ( rSvcImplNames.getLength() )\n{\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nThesaurusDispatcher::ThesaurusDispatcher()\n{\n}\n\n\nThesaurusDispatcher::~ThesaurusDispatcher()\n{\n ClearSvcList();\n}\n\n\nvoid ThesaurusDispatcher::ClearSvcList()\n{\n \/\/ release memory for each table entry\n SeqLangSvcEntry_Thes *pItem = aSvcList.First();\n while (pItem)\n {\n SeqLangSvcEntry_Thes *pTmp = pItem;\n pItem = aSvcList.Next();\n delete pTmp;\n }\n}\n\n\nSequence< Locale > SAL_CALL\n ThesaurusDispatcher::getLocales()\n throw(RuntimeException)\n{\n MutexGuard aGuard( GetLinguMutex() );\n\n ULONG nCnt = aSvcList.Count();\n Sequence< Locale > aLocales( nCnt );\n Locale *pItem = aLocales.getArray();\n SeqLangSvcEntry_Thes *pEntry = aSvcList.First();\n for (ULONG i = 0; i < nCnt; i++)\n {\n DBG_ASSERT( pEntry, \"lng : pEntry is NULL pointer\" );\n pItem[i] = CreateLocale( (LanguageType) aSvcList.GetKey( pEntry ) );\n pEntry = aSvcList.Next();\n }\n return aLocales;\n}\n\n\nsal_Bool SAL_CALL\n ThesaurusDispatcher::hasLocale( const Locale& rLocale )\n throw(RuntimeException)\n{\n MutexGuard aGuard( GetLinguMutex() );\n return 0 != aSvcList.Get( LocaleToLanguage( rLocale ) );\n}\n\n\nSequence< Reference< XMeaning > > SAL_CALL\n ThesaurusDispatcher::queryMeanings(\n const OUString& rTerm, const Locale& rLocale,\n const PropertyValues& rProperties )\n throw(IllegalArgumentException, RuntimeException)\n{\n MutexGuard aGuard( GetLinguMutex() );\n\n Sequence< Reference< XMeaning > > aMeanings;\n\n INT16 nLanguage = LocaleToLanguage( rLocale );\n if (nLanguage == LANGUAGE_NONE || !rTerm.getLength())\n return aMeanings;\n\n \/\/ search for entry with that language\n SeqLangSvcEntry_Thes *pEntry = aSvcList.Get( nLanguage );\n\n if (!pEntry)\n {\n#ifdef LINGU_EXCEPTIONS\n throw IllegalArgumentException();\n#endif\n }\n else\n {\n OUString aChkWord( rTerm );\n aChkWord = aChkWord.replace( SVT_HARD_SPACE, ' ' );\n RemoveHyphens( aChkWord );\n if (IsIgnoreControlChars( rProperties, GetPropSet() ))\n RemoveControlChars( aChkWord );\n\n INT32 nLen = pEntry->aSvcRefs.getLength();\n DBG_ASSERT( nLen == pEntry->aSvcImplNames.getLength(),\n \"lng : sequence length mismatch\");\n DBG_ASSERT( pEntry->aFlags.nLastTriedSvcIndex < nLen,\n \"lng : index out of range\");\n\n INT32 i = 0;\n\n \/\/ try already instantiated services first\n {\n const Reference< XThesaurus > *pRef = pEntry->aSvcRefs.getConstArray();\n while (i <= pEntry->aFlags.nLastTriedSvcIndex\n && aMeanings.getLength() == 0)\n {\n if (pRef[i].is() && pRef[i]->hasLocale( rLocale ))\n aMeanings = pRef[i]->queryMeanings( aChkWord, rLocale, rProperties );\n ++i;\n }\n }\n\n \/\/ if still no result instantiate new services and try those\n if (aMeanings.getLength() == 0\n && pEntry->aFlags.nLastTriedSvcIndex < nLen - 1)\n {\n const OUString *pImplNames = pEntry->aSvcImplNames.getConstArray();\n Reference< XThesaurus > *pRef = pEntry->aSvcRefs.getArray();\n\n Reference< XMultiServiceFactory > xMgr( getProcessServiceFactory() );\n if (xMgr.is())\n {\n \/\/ build service initialization argument\n Sequence< Any > aArgs(1);\n aArgs.getArray()[0] <<= GetPropSet();\n\n while (i < nLen && aMeanings.getLength() == 0)\n {\n \/\/ create specific service via it's implementation name\n Reference< XThesaurus > xThes;\n try\n {\n xThes = Reference< XThesaurus >(\n xMgr->createInstanceWithArguments(\n pImplNames[i], aArgs ), UNO_QUERY );\n }\n catch (uno::Exception &)\n {\n DBG_ERROR( \"createInstanceWithArguments failed\" );\n }\n pRef[i] = xThes;\n\n if (xThes.is() && xThes->hasLocale( rLocale ))\n aMeanings = xThes->queryMeanings( aChkWord, rLocale, rProperties );\n\n pEntry->aFlags.nLastTriedSvcIndex = (INT16) i;\n ++i;\n }\n\n \/\/ if language is not supported by any of the services\n \/\/ remove it from the list.\n if (i == nLen && aMeanings.getLength() == 0)\n {\n if (!SvcListHasLanguage( pEntry->aSvcRefs, rLocale ))\n aSvcList.Remove( nLanguage );\n }\n }\n }\n }\n\n return aMeanings;\n}\n\n\nvoid ThesaurusDispatcher::SetServiceList( const Locale &rLocale,\n const Sequence< OUString > &rSvcImplNames )\n{\n MutexGuard aGuard( GetLinguMutex() );\n\n INT16 nLanguage = LocaleToLanguage( rLocale );\n\n if (0 == rSvcImplNames.getLength())\n \/\/ remove entry\n aSvcList.Remove( nLanguage );\n else\n {\n \/\/ modify\/add entry\n SeqLangSvcEntry_Thes *pEntry = aSvcList.Get( nLanguage );\n if (pEntry)\n {\n pEntry->aSvcImplNames = rSvcImplNames;\n pEntry->aSvcRefs = Sequence< Reference < XThesaurus > >(\n rSvcImplNames.getLength() );\n pEntry->aFlags = SvcFlags();\n }\n else\n {\n pEntry = new SeqLangSvcEntry_Thes( rSvcImplNames );\n aSvcList.Insert( nLanguage, pEntry );\n DBG_ASSERT( aSvcList.Get( nLanguage ), \"lng : Insert failed\" );\n }\n }\n}\n\n\nSequence< OUString >\n ThesaurusDispatcher::GetServiceList( const Locale &rLocale ) const\n{\n MutexGuard aGuard( GetLinguMutex() );\n\n Sequence< OUString > aRes;\n\n \/\/ search for entry with that language and use data from that\n INT16 nLanguage = LocaleToLanguage( rLocale );\n ThesaurusDispatcher *pThis = (ThesaurusDispatcher *) this;\n const SeqLangSvcEntry_Thes *pEntry = pThis->aSvcList.Get( nLanguage );\n if (pEntry)\n aRes = pEntry->aSvcImplNames;\n\n return aRes;\n}\n\n\nThesaurusDispatcher::DspType\n ThesaurusDispatcher::GetDspType() const\n{\n return DSP_THES;\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n<|endoftext|>"} {"text":"\/**\n \\file\n Microscope task. Acquire stacks for each marked tile in a plane.\n\n \\author Nathan Clack \n\n \\copyright\n Copyright 2010 Howard Hughes Medical Institute.\n All rights reserved.\n Use is subject to Janelia Farm Research Campus Software Copyright 1.1\n license terms (http:\/\/license.janelia.org\/license\/jfrc_copyright_1_1.html).\n *\/\n\n\n#include \"common.h\"\n#include \"AdaptiveTiledAcquisition.h\"\n#include \"StackAcquisition.h\"\n#include \"Video.h\"\n#include \"frame.h\"\n#include \"devices\\digitizer.h\"\n#include \"devices\\Microscope.h\"\n#include \"devices\\tiling.h\"\n#include \"tasks\\SurfaceFind.h\"\n\n\n#if 1 \/\/ PROFILING\n#define TS_OPEN(name) timestream_t ts__=timestream_open(name)\n#define TS_TIC timestream_tic(ts__)\n#define TS_TOC timestream_toc(ts__)\n#define TS_CLOSE timestream_close(ts__)\n#else\n#define TS_OPEN(name)\n#define TS_TIC\n#define TS_TOC\n#define TS_CLOSE\n#endif\n\n#define CHKJMP(expr) if(!(expr)) {warning(\"%s(%d)\"ENDL\"\\tExpression indicated failure:\"ENDL\"\\t%s\"ENDL,__FILE__,__LINE__,#expr); goto Error;}\n\nnamespace fetch\n{\n\n namespace task\n {\n\n \/\/\n \/\/ AdaptiveTiledAcquisition - microscope task\n \/\/\n\n namespace microscope {\n\n \/\/Upcasting\n unsigned int AdaptiveTiledAcquisition::config(IDevice *d) {return config(dynamic_cast(d));}\n unsigned int AdaptiveTiledAcquisition::run (IDevice *d) {return run (dynamic_cast(d));}\n\n unsigned int AdaptiveTiledAcquisition::config(device::Microscope *d)\n {\n static task::scanner::ScanStack grabstack;\n std::string filename;\n\n Guarded_Assert(d);\n\n \/\/Assemble pipeline here\n IDevice *cur;\n cur = d->configPipeline();\n\n CHKJMP(d->file_series.ensurePathExists());\n d->file_series.inc();\n filename = d->stack_filename();\n IDevice::connect(&d->disk,0,cur,0);\n Guarded_Assert( d->disk.close()==0 );\n \/\/Guarded_Assert( d->disk.open(filename,\"w\")==0);\n\n d->__scan_agent.disarm(10000\/*timeout_ms*\/);\n int isok=d->__scan_agent.arm(&grabstack,&d->scanner)==0;\n d->stage()->tiling()->resetCursor(); \/\/ this is here so that run\/stop cycles will pick up where they left off\n\n return isok; \/\/success\nError:\n return 0;\n }\n\n static int _handle_wait_for_result(DWORD result, const char *msg)\n {\n return_val_if( result == WAIT_OBJECT_0 , 0 );\n return_val_if( result == WAIT_OBJECT_0+1, 1 );\n Guarded_Assert_WinErr( result != WAIT_FAILED );\n if(result == WAIT_ABANDONED_0) warning(\"%s(%d)\"ENDL \"\\tAdaptiveTiledAcquisition: Wait 0 abandoned\"ENDL \"\\t%s\"ENDL, __FILE__, __LINE__, msg);\n if(result == WAIT_ABANDONED_0+1) warning(\"%s(%d)\"ENDL \"\\tAdaptiveTiledAcquisition: Wait 1 abandoned\"ENDL \"\\t%s\"ENDL, __FILE__, __LINE__, msg);\n if(result == WAIT_TIMEOUT) warning(\"%s(%d)\"ENDL \"\\tAdaptiveTiledAcquisition: Wait timeout\"ENDL \"\\t%s\"ENDL, __FILE__, __LINE__, msg);\n\n Guarded_Assert_WinErr( result !=WAIT_FAILED );\n\n return -1;\n }\n\n unsigned int AdaptiveTiledAcquisition::run(device::Microscope *dc)\n {\n SurfaceFind surface_find;\n std::string filename;\n unsigned int eflag = 0; \/\/ success\n Vector3f tilepos;\n float tiling_offset_acc_mm=0.0f;\n float nsamp=0;\n int adapt_count=0;\n int adapt_thresh=dc->get_config().adaptive_tiling().every();\n int adapt_mindist=dc->get_config().adaptive_tiling().mindist();\n TS_OPEN(\"timer-tiles.f32\");\n CHKJMP(dc->__scan_agent.is_runnable());\n\n device::StageTiling* tiling = dc->stage()->tiling();\n\n\n \/\/ 1. iterate over tiles to measure the average tile offset\n tiling->resetCursor();\n while(eflag==0 && !dc->_agent->is_stopping() && tiling->nextInPlanePosition(tilepos))\n { \n if(adapt_mindist<=tiling->minDistTo( 0,0, \/\/ domain query -- do not restrict to a particular tile type\n device::StageTiling::Active,0)) \/\/ boundary query -- this is defines what is \"outside\"\n { \n if(++adapt_count>adapt_thresh) \/\/ is it time to try?\n { \n \/\/ M O V E\n Vector3f curpos = dc->stage()->getTarget(); \/\/ use current target z for tilepos z\n debug(\"%s(%d)\"ENDL \"\\t[Adaptive Tiling Task] curpos: %5.1f %5.1f %5.1f\"ENDL,__FILE__,__LINE__,curpos[0]*1000.0f,curpos[1]*1000.0f,curpos[2]*1000.0f); \n dc->stage()->setPos(0.001f*tilepos); \/\/ convert um to mm\n curpos = dc->stage()->getTarget(); \/\/ use current target z for tilepos z\n debug(\"%s(%d)\"ENDL \"\\t[Adaptive Tiling Task] curpos: %5.1f %5.1f %5.1f\"ENDL,__FILE__,__LINE__,curpos[0]*1000.0f,curpos[1]*1000.0f,curpos[2]*1000.0f);\n\n \/\/ A D A P T I V E \n#if 0\n if (adapt_count>2*adapt_thresh) \/\/ have too many detections been missed\n { warning(\"Could not track surface. Giving up.\\n\");\n goto Error;\n }\n#endif\n\n \/\/surface_find.config(); -- arms stack task as scan agent...redundant\n eflag |= surface_find.run(dc);\n if(surface_find.hit())\n { adapt_count=0;\n tiling_offset_acc_mm+=dc->stage()->tiling_z_offset_mm();\n ++nsamp;\n }\n\n \n }\n }\n }\n if(nsamp==0)\n { warning(\"Could not track surface. Giving up.\\n\");\n goto Error;\n }\n debug(\"%s(%d)\"ENDL \"\\t[Adaptive Tiling Task] Average tile offset (samples: %5d) %f\"ENDL,__FILE__,__LINE__,(int)nsamp,tiling_offset_acc_mm\/nsamp);\n dc->stage()->set_tiling_z_offset_mm(tiling_offset_acc_mm\/nsamp);\n\n \/\/ retore connection between end of pipeline and disk \n IDevice::connect(&dc->disk,0,dc->_end_of_pipeline,0);\n\n \/\/ 2. iterate over tiles to image\n tiling->resetCursor();\n while(eflag==0 && !dc->_agent->is_stopping() && tiling->nextInPlanePosition(tilepos))\n { TS_TIC;\n debug(\"%s(%d)\"ENDL \"\\t[Adaptive Tiling Task] tilepos: %5.1f %5.1f %5.1f\"ENDL,__FILE__,__LINE__,tilepos[0],tilepos[1],tilepos[2]);\n filename = dc->stack_filename();\n dc->file_series.ensurePathExists();\n dc->disk.set_nchan(dc->scanner.get2d()->digitizer()->nchan());\n eflag |= dc->disk.open(filename,\"w\");\n if(eflag)\n {\n warning(\"Couldn't open file: %s\"ENDL, filename.c_str());\n return eflag;\n }\n\n \/\/ Move stage\n Vector3f curpos = dc->stage()->getTarget(); \/\/ use current target z for tilepos z\n debug(\"%s(%d)\"ENDL \"\\t[Adaptive Tiling Task] curpos: %5.1f %5.1f %5.1f\"ENDL,__FILE__,__LINE__,curpos[0]*1000.0f,curpos[1]*1000.0f,curpos[2]*1000.0f); \n dc->stage()->setPos(0.001f*tilepos); \/\/ convert um to mm\n curpos = dc->stage()->getTarget(); \/\/ use current target z for tilepos z\n debug(\"%s(%d)\"ENDL \"\\t[Adaptive Tiling Task] curpos: %5.1f %5.1f %5.1f\"ENDL,__FILE__,__LINE__,curpos[0]*1000.0f,curpos[1]*1000.0f,curpos[2]*1000.0f);\n\n eflag |= dc->runPipeline();\n eflag |= dc->__scan_agent.run() != 1;\n\n { \/\/ Wait for stack to finish\n HANDLE hs[] = {\n dc->__scan_agent._thread,\n dc->__self_agent._notify_stop};\n DWORD res;\n int t;\n\n \/\/ wait for scan to complete (or cancel)\n res = WaitForMultipleObjects(2,hs,FALSE,INFINITE);\n t = _handle_wait_for_result(res,\"AdaptiveTiledAcquisition::run - Wait for scanner to finish.\");\n switch(t)\n {\n case 0: \/\/ in this case, the scanner thread stopped. Nothing left to do.\n eflag |= dc->__scan_agent.last_run_result(); \/\/ check the run result\n eflag |= dc->__io_agent.last_run_result();\n if(eflag==0) \/\/ remove this if statement to mark tiles as \"error\" tiles. In practice, it seems it's ok to go back and reimage, so the if statement stays\n tiling->markDone(eflag==0); \/\/ only mark the tile done if the scanner task completed normally\n case 1: \/\/ in this case, the stop event triggered and must be propagated.\n eflag |= dc->__scan_agent.stop(SCANNER2D_DEFAULT_TIMEOUT) != 1;\n break;\n default: \/\/ in this case, there was a timeout or abandoned wait\n eflag |= 1; \/\/ failure\n }\n } \/\/ end waiting block\n\n \/\/ Output and Increment files\n dc->write_stack_metadata(); \/\/ write the metadata\n eflag |= dc->disk.close();\n dc->file_series.inc(); \/\/ increment regardless of completion status\n eflag |= dc->stopPipeline(); \/\/ wait till everything stops\n\n TS_TOC; \n } \/\/ end loop over tiles\n eflag |= dc->stopPipeline(); \/\/ wait till the pipeline stops\n TS_CLOSE;\n return eflag;\nError:\n TS_CLOSE;\n return 1;\n }\n\n } \/\/ namespace microscope\n\n } \/\/ namespace task\n} \/\/ namespace fetch\n[AdaptiveTiling] bug fix. retries to much on miss.\/**\n \\file\n Microscope task. Acquire stacks for each marked tile in a plane.\n\n \\author Nathan Clack \n\n \\copyright\n Copyright 2010 Howard Hughes Medical Institute.\n All rights reserved.\n Use is subject to Janelia Farm Research Campus Software Copyright 1.1\n license terms (http:\/\/license.janelia.org\/license\/jfrc_copyright_1_1.html).\n *\/\n\n\n#include \"common.h\"\n#include \"AdaptiveTiledAcquisition.h\"\n#include \"StackAcquisition.h\"\n#include \"Video.h\"\n#include \"frame.h\"\n#include \"devices\\digitizer.h\"\n#include \"devices\\Microscope.h\"\n#include \"devices\\tiling.h\"\n#include \"tasks\\SurfaceFind.h\"\n\n\n#if 1 \/\/ PROFILING\n#define TS_OPEN(name) timestream_t ts__=timestream_open(name)\n#define TS_TIC timestream_tic(ts__)\n#define TS_TOC timestream_toc(ts__)\n#define TS_CLOSE timestream_close(ts__)\n#else\n#define TS_OPEN(name)\n#define TS_TIC\n#define TS_TOC\n#define TS_CLOSE\n#endif\n\n#define CHKJMP(expr) if(!(expr)) {warning(\"%s(%d)\"ENDL\"\\tExpression indicated failure:\"ENDL\"\\t%s\"ENDL,__FILE__,__LINE__,#expr); goto Error;}\n\nnamespace fetch\n{\n\n namespace task\n {\n\n \/\/\n \/\/ AdaptiveTiledAcquisition - microscope task\n \/\/\n\n namespace microscope {\n\n \/\/Upcasting\n unsigned int AdaptiveTiledAcquisition::config(IDevice *d) {return config(dynamic_cast(d));}\n unsigned int AdaptiveTiledAcquisition::run (IDevice *d) {return run (dynamic_cast(d));}\n\n unsigned int AdaptiveTiledAcquisition::config(device::Microscope *d)\n {\n static task::scanner::ScanStack grabstack;\n std::string filename;\n\n Guarded_Assert(d);\n\n \/\/Assemble pipeline here\n IDevice *cur;\n cur = d->configPipeline();\n\n CHKJMP(d->file_series.ensurePathExists());\n d->file_series.inc();\n filename = d->stack_filename();\n IDevice::connect(&d->disk,0,cur,0);\n Guarded_Assert( d->disk.close()==0 );\n \/\/Guarded_Assert( d->disk.open(filename,\"w\")==0);\n\n d->__scan_agent.disarm(10000\/*timeout_ms*\/);\n int isok=d->__scan_agent.arm(&grabstack,&d->scanner)==0;\n d->stage()->tiling()->resetCursor(); \/\/ this is here so that run\/stop cycles will pick up where they left off\n\n return isok; \/\/success\nError:\n return 0;\n }\n\n static int _handle_wait_for_result(DWORD result, const char *msg)\n {\n return_val_if( result == WAIT_OBJECT_0 , 0 );\n return_val_if( result == WAIT_OBJECT_0+1, 1 );\n Guarded_Assert_WinErr( result != WAIT_FAILED );\n if(result == WAIT_ABANDONED_0) warning(\"%s(%d)\"ENDL \"\\tAdaptiveTiledAcquisition: Wait 0 abandoned\"ENDL \"\\t%s\"ENDL, __FILE__, __LINE__, msg);\n if(result == WAIT_ABANDONED_0+1) warning(\"%s(%d)\"ENDL \"\\tAdaptiveTiledAcquisition: Wait 1 abandoned\"ENDL \"\\t%s\"ENDL, __FILE__, __LINE__, msg);\n if(result == WAIT_TIMEOUT) warning(\"%s(%d)\"ENDL \"\\tAdaptiveTiledAcquisition: Wait timeout\"ENDL \"\\t%s\"ENDL, __FILE__, __LINE__, msg);\n\n Guarded_Assert_WinErr( result !=WAIT_FAILED );\n\n return -1;\n }\n\n unsigned int AdaptiveTiledAcquisition::run(device::Microscope *dc)\n {\n SurfaceFind surface_find;\n std::string filename;\n unsigned int eflag = 0; \/\/ success\n Vector3f tilepos;\n float tiling_offset_acc_mm=0.0f;\n float nsamp=0;\n int adapt_count=0;\n int adapt_thresh=dc->get_config().adaptive_tiling().every();\n int adapt_mindist=dc->get_config().adaptive_tiling().mindist();\n TS_OPEN(\"timer-tiles.f32\");\n CHKJMP(dc->__scan_agent.is_runnable());\n\n device::StageTiling* tiling = dc->stage()->tiling();\n\n\n \/\/ 1. iterate over tiles to measure the average tile offset\n tiling->resetCursor();\n while(eflag==0 && !dc->_agent->is_stopping() && tiling->nextInPlanePosition(tilepos))\n { \n if(adapt_mindist<=tiling->minDistTo( 0,0, \/\/ domain query -- do not restrict to a particular tile type\n device::StageTiling::Active,0)) \/\/ boundary query -- this is defines what is \"outside\"\n { \n if(++adapt_count>adapt_thresh) \/\/ is it time to try?\n { adapt_count=0;\n \/\/ M O V E\n Vector3f curpos = dc->stage()->getTarget(); \/\/ use current target z for tilepos z\n debug(\"%s(%d)\"ENDL \"\\t[Adaptive Tiling Task] curpos: %5.1f %5.1f %5.1f\"ENDL,__FILE__,__LINE__,curpos[0]*1000.0f,curpos[1]*1000.0f,curpos[2]*1000.0f); \n dc->stage()->setPos(0.001f*tilepos); \/\/ convert um to mm\n curpos = dc->stage()->getTarget(); \/\/ use current target z for tilepos z\n debug(\"%s(%d)\"ENDL \"\\t[Adaptive Tiling Task] curpos: %5.1f %5.1f %5.1f\"ENDL,__FILE__,__LINE__,curpos[0]*1000.0f,curpos[1]*1000.0f,curpos[2]*1000.0f);\n\n \/\/ A D A P T I V E \n#if 0\n if (adapt_count>2*adapt_thresh) \/\/ have too many detections been missed\n { warning(\"Could not track surface. Giving up.\\n\");\n goto Error;\n }\n#endif\n \/\/surface_find.config(); -- arms stack task as scan agent...redundant\n eflag |= surface_find.run(dc);\n if(surface_find.hit())\n { tiling_offset_acc_mm+=dc->stage()->tiling_z_offset_mm();\n ++nsamp;\n }\n\n \n }\n }\n }\n if(nsamp==0)\n { warning(\"Could not track surface. Giving up.\\n\");\n goto Error;\n }\n debug(\"%s(%d)\"ENDL \"\\t[Adaptive Tiling Task] Average tile offset (samples: %5d) %f\"ENDL,__FILE__,__LINE__,(int)nsamp,tiling_offset_acc_mm\/nsamp);\n dc->stage()->set_tiling_z_offset_mm(tiling_offset_acc_mm\/nsamp);\n\n \/\/ retore connection between end of pipeline and disk \n IDevice::connect(&dc->disk,0,dc->_end_of_pipeline,0);\n\n \/\/ 2. iterate over tiles to image\n tiling->resetCursor();\n while(eflag==0 && !dc->_agent->is_stopping() && tiling->nextInPlanePosition(tilepos))\n { TS_TIC;\n debug(\"%s(%d)\"ENDL \"\\t[Adaptive Tiling Task] tilepos: %5.1f %5.1f %5.1f\"ENDL,__FILE__,__LINE__,tilepos[0],tilepos[1],tilepos[2]);\n filename = dc->stack_filename();\n dc->file_series.ensurePathExists();\n dc->disk.set_nchan(dc->scanner.get2d()->digitizer()->nchan());\n eflag |= dc->disk.open(filename,\"w\");\n if(eflag)\n {\n warning(\"Couldn't open file: %s\"ENDL, filename.c_str());\n return eflag;\n }\n\n \/\/ Move stage\n Vector3f curpos = dc->stage()->getTarget(); \/\/ use current target z for tilepos z\n debug(\"%s(%d)\"ENDL \"\\t[Adaptive Tiling Task] curpos: %5.1f %5.1f %5.1f\"ENDL,__FILE__,__LINE__,curpos[0]*1000.0f,curpos[1]*1000.0f,curpos[2]*1000.0f); \n dc->stage()->setPos(0.001f*tilepos); \/\/ convert um to mm\n curpos = dc->stage()->getTarget(); \/\/ use current target z for tilepos z\n debug(\"%s(%d)\"ENDL \"\\t[Adaptive Tiling Task] curpos: %5.1f %5.1f %5.1f\"ENDL,__FILE__,__LINE__,curpos[0]*1000.0f,curpos[1]*1000.0f,curpos[2]*1000.0f);\n\n eflag |= dc->runPipeline();\n eflag |= dc->__scan_agent.run() != 1;\n\n { \/\/ Wait for stack to finish\n HANDLE hs[] = {\n dc->__scan_agent._thread,\n dc->__self_agent._notify_stop};\n DWORD res;\n int t;\n\n \/\/ wait for scan to complete (or cancel)\n res = WaitForMultipleObjects(2,hs,FALSE,INFINITE);\n t = _handle_wait_for_result(res,\"AdaptiveTiledAcquisition::run - Wait for scanner to finish.\");\n switch(t)\n {\n case 0: \/\/ in this case, the scanner thread stopped. Nothing left to do.\n eflag |= dc->__scan_agent.last_run_result(); \/\/ check the run result\n eflag |= dc->__io_agent.last_run_result();\n if(eflag==0) \/\/ remove this if statement to mark tiles as \"error\" tiles. In practice, it seems it's ok to go back and reimage, so the if statement stays\n tiling->markDone(eflag==0); \/\/ only mark the tile done if the scanner task completed normally\n case 1: \/\/ in this case, the stop event triggered and must be propagated.\n eflag |= dc->__scan_agent.stop(SCANNER2D_DEFAULT_TIMEOUT) != 1;\n break;\n default: \/\/ in this case, there was a timeout or abandoned wait\n eflag |= 1; \/\/ failure\n }\n } \/\/ end waiting block\n\n \/\/ Output and Increment files\n dc->write_stack_metadata(); \/\/ write the metadata\n eflag |= dc->disk.close();\n dc->file_series.inc(); \/\/ increment regardless of completion status\n eflag |= dc->stopPipeline(); \/\/ wait till everything stops\n\n TS_TOC; \n } \/\/ end loop over tiles\n eflag |= dc->stopPipeline(); \/\/ wait till the pipeline stops\n TS_CLOSE;\n return eflag;\nError:\n TS_CLOSE;\n return 1;\n }\n\n } \/\/ namespace microscope\n\n } \/\/ namespace task\n} \/\/ namespace fetch\n<|endoftext|>"} {"text":"\/*\n * Copyright 2016 Couchbase, Inc\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"storeddockey.h\"\n#include \n#include \n#include \n#include \n\nStoredDocKey::StoredDocKey(const std::string& key, CollectionID cid) {\n cb::mcbp::unsigned_leb128 leb128(cid);\n keydata.resize(key.size() + leb128.size());\n std::copy(key.begin(),\n key.end(),\n std::copy(leb128.begin(), leb128.end(), keydata.begin()));\n}\n\nCollectionID StoredDocKey::getCollectionID() const {\n return cb::mcbp::decode_unsigned_leb128({data(), size()})\n .first;\n}\n\nDocKey StoredDocKey::makeDocKeyWithoutCollectionID() const {\n auto decoded = cb::mcbp::decode_unsigned_leb128(\n {data(), size()});\n return {decoded.second.data(),\n decoded.second.size(),\n DocKeyEncodesCollectionId::No};\n}\n\nstd::string StoredDocKey::to_string() const {\n std::stringstream ss;\n auto leb128 = cb::mcbp::decode_unsigned_leb128(\n {reinterpret_cast(keydata.data()), keydata.size()});\n ss << \"cid:0x\" << std::hex << leb128.first << \":\"\n << std::string(reinterpret_cast(leb128.second.data()),\n leb128.second.size());\n ss << \", size:\" << size();\n return ss.str();\n}\n\nconst char* StoredDocKey::c_str() const {\n \/\/ Locate the leb128 stop byte, and return pointer after that\n auto key = cb::mcbp::skip_unsigned_leb128(\n {reinterpret_cast(keydata.data()), keydata.size()});\n\n if (key.size()) {\n return &keydata.c_str()[keydata.size() - key.size()];\n }\n return nullptr;\n}\n\nstd::ostream& operator<<(std::ostream& os, const StoredDocKey& key) {\n return os << key.to_string();\n}\n\nCollectionID SerialisedDocKey::getCollectionID() const {\n return cb::mcbp::decode_unsigned_leb128({bytes, length})\n .first;\n}\n\nbool SerialisedDocKey::operator==(const DocKey& rhs) const {\n auto rhsIdAndData = rhs.getIdAndKey();\n auto lhsIdAndData = cb::mcbp::decode_unsigned_leb128(\n {data(), size()});\n return lhsIdAndData.first == rhsIdAndData.first &&\n lhsIdAndData.second.size() == rhsIdAndData.second.size() &&\n std::equal(lhsIdAndData.second.begin(),\n lhsIdAndData.second.end(),\n rhsIdAndData.second.begin());\n}\n\nSerialisedDocKey::SerialisedDocKey(cb::const_byte_buffer key,\n CollectionID cid) {\n cb::mcbp::unsigned_leb128 leb128(cid);\n length = gsl::narrow_cast(key.size() + leb128.size());\n std::copy(key.begin(),\n key.end(),\n std::copy(leb128.begin(), leb128.end(), bytes));\n}\n\nstd::ostream& operator<<(std::ostream& os, const SerialisedDocKey& key) {\n auto leb128 = cb::mcbp::decode_unsigned_leb128(\n {reinterpret_cast(key.data()), key.size()});\n os << \"cid:0x\" << std::hex << leb128.first << \":\"\n << std::string(reinterpret_cast(leb128.second.data()),\n leb128.second.size());\n os << \", size:\" << key.size();\n return os;\n}\nStoredDocKey::to_string: don't print size\/*\n * Copyright 2016 Couchbase, Inc\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"storeddockey.h\"\n#include \n#include \n#include \n#include \n\nStoredDocKey::StoredDocKey(const std::string& key, CollectionID cid) {\n cb::mcbp::unsigned_leb128 leb128(cid);\n keydata.resize(key.size() + leb128.size());\n std::copy(key.begin(),\n key.end(),\n std::copy(leb128.begin(), leb128.end(), keydata.begin()));\n}\n\nCollectionID StoredDocKey::getCollectionID() const {\n return cb::mcbp::decode_unsigned_leb128({data(), size()})\n .first;\n}\n\nDocKey StoredDocKey::makeDocKeyWithoutCollectionID() const {\n auto decoded = cb::mcbp::decode_unsigned_leb128(\n {data(), size()});\n return {decoded.second.data(),\n decoded.second.size(),\n DocKeyEncodesCollectionId::No};\n}\n\nstd::string StoredDocKey::to_string() const {\n std::stringstream ss;\n auto leb128 = cb::mcbp::decode_unsigned_leb128(\n {reinterpret_cast(keydata.data()), keydata.size()});\n ss << \"cid:0x\" << std::hex << leb128.first << std::dec << \":\"\n << std::string(reinterpret_cast(leb128.second.data()),\n leb128.second.size());\n return ss.str();\n}\n\nconst char* StoredDocKey::c_str() const {\n \/\/ Locate the leb128 stop byte, and return pointer after that\n auto key = cb::mcbp::skip_unsigned_leb128(\n {reinterpret_cast(keydata.data()), keydata.size()});\n\n if (key.size()) {\n return &keydata.c_str()[keydata.size() - key.size()];\n }\n return nullptr;\n}\n\nstd::ostream& operator<<(std::ostream& os, const StoredDocKey& key) {\n return os << key.to_string();\n}\n\nCollectionID SerialisedDocKey::getCollectionID() const {\n return cb::mcbp::decode_unsigned_leb128({bytes, length})\n .first;\n}\n\nbool SerialisedDocKey::operator==(const DocKey& rhs) const {\n auto rhsIdAndData = rhs.getIdAndKey();\n auto lhsIdAndData = cb::mcbp::decode_unsigned_leb128(\n {data(), size()});\n return lhsIdAndData.first == rhsIdAndData.first &&\n lhsIdAndData.second.size() == rhsIdAndData.second.size() &&\n std::equal(lhsIdAndData.second.begin(),\n lhsIdAndData.second.end(),\n rhsIdAndData.second.begin());\n}\n\nSerialisedDocKey::SerialisedDocKey(cb::const_byte_buffer key,\n CollectionID cid) {\n cb::mcbp::unsigned_leb128 leb128(cid);\n length = gsl::narrow_cast(key.size() + leb128.size());\n std::copy(key.begin(),\n key.end(),\n std::copy(leb128.begin(), leb128.end(), bytes));\n}\n\nstd::ostream& operator<<(std::ostream& os, const SerialisedDocKey& key) {\n auto leb128 = cb::mcbp::decode_unsigned_leb128(\n {reinterpret_cast(key.data()), key.size()});\n os << \"cid:0x\" << std::hex << leb128.first << \":\"\n << std::string(reinterpret_cast(leb128.second.data()),\n leb128.second.size());\n os << \", size:\" << key.size();\n return os;\n}\n<|endoftext|>"} {"text":"#ifndef STAN_MATH_OPENCL_KERNELS_DEVICE_FUNCTIONS_BINOMIAL_COEFFICIENT_LOG_HPP\n#define STAN_MATH_OPENCL_KERNELS_DEVICE_FUNCTIONS_BINOMIAL_COEFFICIENT_LOG_HPP\n#ifdef STAN_OPENCL\n\n#include \n#include \n\nnamespace stan {\nnamespace math {\nnamespace opencl_kernels {\n\n\/\/ \\cond\nstatic const char* binomial_coefficient_log_device_function\n = \"\\n\"\n \"#ifndef \"\n \"STAN_MATH_OPENCL_KERNELS_DEVICE_FUNCTIONS_BINOMIAL_COEFFICIENT_LOG\\n\"\n \"#define \"\n \"STAN_MATH_OPENCL_KERNELS_DEVICE_FUNCTIONS_BINOMIAL_COEFFICIENT_\"\n \"LOG\\n\" STRINGIFY(\n \/\/ \\endcond\n \/**\n * Return the log of the binomial coefficient for the specified\n * arguments.\n *\n * The binomial coefficient, \\f${n \\choose k}\\f$, read \"n choose k\",\n is\n * defined for \\f$0 \\leq k \\leq n\\f$ by\n *\n * \\f${n \\choose k} = \\frac{n!}{k! (n-k)!}\\f$.\n *\n * This function uses Gamma functions to define the log\n * and generalize the arguments to continuous n and k.\n *\n * \\f$ \\log {n \\choose k}\n * = \\log \\ \\Gamma(n+1) - \\log \\Gamma(k+1) - \\log \\Gamma(n-k+1)\\f$.\n *\n *\n \\f[\n \\mbox{binomial\\_coefficient\\_log}(x, y) =\n \\begin{cases}\n \\textrm{error} & \\mbox{if } y > x + 1 \\textrm{ or } y < -1\n \\textrm{ or } x\n < -1\\\\\n \\ln\\Gamma(x+1) & \\mbox{if } -1 < y < x + 1 \\\\\n \\quad -\\ln\\Gamma(y+1)& \\\\\n \\quad -\\ln\\Gamma(x-y+1)& \\\\[6pt]\n \\textrm{NaN} & \\mbox{if } x = \\textrm{NaN or } y = \\textrm{NaN}\n \\end{cases}\n \\f]\n\n \\f[\n \\frac{\\partial\\, \\mbox{binomial\\_coefficient\\_log}(x, y)}{\\partial\n x} = \\begin{cases} \\textrm{error} & \\mbox{if } y > x + 1 \\textrm{ or\n } y < -1 \\textrm{ or } x\n < -1\\\\\n \\Psi(x+1) & \\mbox{if } 0\\leq y \\leq x \\\\\n \\quad -\\Psi(x-y+1)& \\\\[6pt]\n \\textrm{NaN} & \\mbox{if } x = \\textrm{NaN or } y = \\textrm{NaN}\n \\end{cases}\n \\f]\n\n \\f[\n \\frac{\\partial\\, \\mbox{binomial\\_coefficient\\_log}(x, y)}{\\partial\n y} = \\begin{cases} \\textrm{error} & \\mbox{if } y > x + 1 \\textrm{ or\n } y < -1 \\textrm{ or } x\n < -1\\\\\n -\\Psi(y+1) & \\mbox{if } 0\\leq y \\leq x \\\\\n \\quad +\\Psi(x-y+1)& \\\\[6pt]\n \\textrm{NaN} & \\mbox{if } x = \\textrm{NaN or } y = \\textrm{NaN}\n \\end{cases}\n \\f]\n *\n * This function is numerically more stable than naive evaluation via\n lgamma.\n *\n * @param n total number of objects.\n * @param k number of objects chosen.\n * @return log (n choose k).\n *\/\n double binomial_coefficient_log(double n, double k) {\n if (isnan(n) || isnan(k)) {\n return NAN;\n }\n\n \/\/ Choosing the more stable of the symmetric branches\n if (n > -1 && k > n \/ 2.0 + 1e-8) {\n return binomial_coefficient_log(n, n - k);\n }\n\n double n_plus_1 = n + 1;\n double n_plus_1_mk = n_plus_1 - k;\n\n if (k == 0) {\n return 0;\n } else if (n_plus_1 < LGAMMA_STIRLING_DIFF_USEFUL) {\n return lgamma(n_plus_1) - lgamma(k + 1) - lgamma(n_plus_1_mk);\n } else {\n return -lbeta(n_plus_1_mk, k + 1) - log1p(n);\n }\n }\n \/\/ \\cond\n ) \"\\n#endif\\n\"; \/\/ NOLINT\n\/\/ \\endcond\n\n} \/\/ namespace opencl_kernels\n} \/\/ namespace math\n} \/\/ namespace stan\n\n#endif\n#endif \/\/ BINOMIAL_COEFFICIENT_LOG_HPP\nremove recursion#ifndef STAN_MATH_OPENCL_KERNELS_DEVICE_FUNCTIONS_BINOMIAL_COEFFICIENT_LOG_HPP\n#define STAN_MATH_OPENCL_KERNELS_DEVICE_FUNCTIONS_BINOMIAL_COEFFICIENT_LOG_HPP\n#ifdef STAN_OPENCL\n\n#include \n#include \n\nnamespace stan {\nnamespace math {\nnamespace opencl_kernels {\n\n\/\/ \\cond\nstatic const char* binomial_coefficient_log_device_function\n = \"\\n\"\n \"#ifndef \"\n \"STAN_MATH_OPENCL_KERNELS_DEVICE_FUNCTIONS_BINOMIAL_COEFFICIENT_LOG\\n\"\n \"#define \"\n \"STAN_MATH_OPENCL_KERNELS_DEVICE_FUNCTIONS_BINOMIAL_COEFFICIENT_\"\n \"LOG\\n\" STRINGIFY(\n \/\/ \\endcond\n \/**\n * Return the log of the binomial coefficient for the specified\n * arguments.\n *\n * The binomial coefficient, \\f${n \\choose k}\\f$, read \"n choose k\",\n is\n * defined for \\f$0 \\leq k \\leq n\\f$ by\n *\n * \\f${n \\choose k} = \\frac{n!}{k! (n-k)!}\\f$.\n *\n * This function uses Gamma functions to define the log\n * and generalize the arguments to continuous n and k.\n *\n * \\f$ \\log {n \\choose k}\n * = \\log \\ \\Gamma(n+1) - \\log \\Gamma(k+1) - \\log \\Gamma(n-k+1)\\f$.\n *\n *\n \\f[\n \\mbox{binomial\\_coefficient\\_log}(x, y) =\n \\begin{cases}\n \\textrm{error} & \\mbox{if } y > x + 1 \\textrm{ or } y < -1\n \\textrm{ or } x\n < -1\\\\\n \\ln\\Gamma(x+1) & \\mbox{if } -1 < y < x + 1 \\\\\n \\quad -\\ln\\Gamma(y+1)& \\\\\n \\quad -\\ln\\Gamma(x-y+1)& \\\\[6pt]\n \\textrm{NaN} & \\mbox{if } x = \\textrm{NaN or } y = \\textrm{NaN}\n \\end{cases}\n \\f]\n\n \\f[\n \\frac{\\partial\\, \\mbox{binomial\\_coefficient\\_log}(x, y)}{\\partial\n x} = \\begin{cases} \\textrm{error} & \\mbox{if } y > x + 1 \\textrm{ or\n } y < -1 \\textrm{ or } x\n < -1\\\\\n \\Psi(x+1) & \\mbox{if } 0\\leq y \\leq x \\\\\n \\quad -\\Psi(x-y+1)& \\\\[6pt]\n \\textrm{NaN} & \\mbox{if } x = \\textrm{NaN or } y = \\textrm{NaN}\n \\end{cases}\n \\f]\n\n \\f[\n \\frac{\\partial\\, \\mbox{binomial\\_coefficient\\_log}(x, y)}{\\partial\n y} = \\begin{cases} \\textrm{error} & \\mbox{if } y > x + 1 \\textrm{ or\n } y < -1 \\textrm{ or } x\n < -1\\\\\n -\\Psi(y+1) & \\mbox{if } 0\\leq y \\leq x \\\\\n \\quad +\\Psi(x-y+1)& \\\\[6pt]\n \\textrm{NaN} & \\mbox{if } x = \\textrm{NaN or } y = \\textrm{NaN}\n \\end{cases}\n \\f]\n *\n * This function is numerically more stable than naive evaluation via\n lgamma.\n *\n * @param n total number of objects.\n * @param k number of objects chosen.\n * @return log (n choose k).\n *\/\n double binomial_coefficient_log(double n, double k) {\n if (isnan(n) || isnan(k)) {\n return NAN;\n }\n\n \/\/ Choosing the more stable of the symmetric branches\n if (n > -1 && k > n \/ 2.0 + 1e-8) {\n k = n - k;\n }\n\n double n_plus_1 = n + 1;\n double n_plus_1_mk = n_plus_1 - k;\n\n if (k == 0) {\n return 0;\n } else if (n_plus_1 < LGAMMA_STIRLING_DIFF_USEFUL) {\n return lgamma(n_plus_1) - lgamma(k + 1) - lgamma(n_plus_1_mk);\n } else {\n return -lbeta(n_plus_1_mk, k + 1) - log1p(n);\n }\n }\n \/\/ \\cond\n ) \"\\n#endif\\n\"; \/\/ NOLINT\n\/\/ \\endcond\n\n} \/\/ namespace opencl_kernels\n} \/\/ namespace math\n} \/\/ namespace stan\n\n#endif\n#endif \/\/ BINOMIAL_COEFFICIENT_LOG_HPP\n<|endoftext|>"} {"text":"\/**\n * @file\n * @copyright defined in eos\/LICENSE.txt\n *\/\n#include \n#include \n\n#include \n\nnamespace eos {\n\nusing namespace eos;\n\nclass chain_api_plugin_impl {\npublic:\n chain_api_plugin_impl(chain_controller& db)\n : db(db) {}\n\n chain_controller& db;\n};\n\n\nchain_api_plugin::chain_api_plugin(){}\nchain_api_plugin::~chain_api_plugin(){}\n\nvoid chain_api_plugin::set_program_options(options_description&, options_description&) {}\nvoid chain_api_plugin::plugin_initialize(const variables_map&) {}\n\n#define CALL(api_name, api_handle, api_namespace, call_name) \\\n{std::string(\"\/v1\/\" #api_name \"\/\" #call_name), \\\n [this, api_handle](string, string body, url_response_callback cb) mutable { \\\n try { \\\n if (body.empty()) body = \"{}\"; \\\n auto result = api_handle.call_name(fc::json::from_string(body).as()); \\\n cb(201, fc::json::to_string(result)); \\\n } catch (chain::tx_missing_sigs& e) { \\\n error_results results{401, \"UnAuthorized\", e.to_string()}; \\\n cb(401, fc::json::to_string(results)); \\\n } catch (chain::tx_duplicate& e) { \\\n error_results results{409, \"Conflict\", e.to_string()}; \\\n cb(409, fc::json::to_string(results)); \\\n } catch (chain::transaction_exception& e) { \\\n error_results results{400, \"Bad Request\", e.to_string()}; \\\n cb(400, fc::json::to_string(results)); \\\n } catch (fc::eof_exception& e) { \\\n error_results results{400, \"Bad Request\", e.to_string()}; \\\n cb(400, fc::json::to_string(results)); \\\n elog(\"Unable to parse arguments: ${args}\", (\"args\", body)); \\\n } catch (fc::exception& e) { \\\n error_results results{500, \"Internal Service Error\", e.to_detail_string()}; \\\n cb(500, fc::json::to_string(results)); \\\n elog(\"Exception encountered while processing ${call}: ${e}\", (\"call\", #api_name \".\" #call_name)(\"e\", e)); \\\n } \\\n }}\n\n#define CHAIN_RO_CALL(call_name) CALL(chain, ro_api, chain_apis::read_only, call_name)\n#define CHAIN_RW_CALL(call_name) CALL(chain, rw_api, chain_apis::read_write, call_name)\n\nvoid chain_api_plugin::plugin_startup() {\n ilog( \"starting chain_api_plugin\" );\n my.reset(new chain_api_plugin_impl(app().get_plugin().chain()));\n auto ro_api = app().get_plugin().get_read_only_api();\n auto rw_api = app().get_plugin().get_read_write_api();\n\n app().get_plugin().add_api({\n CHAIN_RO_CALL(get_info),\n CHAIN_RO_CALL(get_block),\n CHAIN_RO_CALL(get_account),\n CHAIN_RO_CALL(get_code),\n CHAIN_RO_CALL(get_table_rows),\n CHAIN_RO_CALL(abi_json_to_bin),\n CHAIN_RO_CALL(abi_bin_to_json),\n CHAIN_RO_CALL(get_required_keys),\n CHAIN_RW_CALL(push_block),\n CHAIN_RW_CALL(push_transaction),\n CHAIN_RW_CALL(push_transactions)\n });\n}\n\nvoid chain_api_plugin::plugin_shutdown() {}\n\n}\nRevise chain API to return http response 200 or 202, as appropriate.\/**\n * @file\n * @copyright defined in eos\/LICENSE.txt\n *\/\n#include \n#include \n\n#include \n\nnamespace eos {\n\nusing namespace eos;\n\nclass chain_api_plugin_impl {\npublic:\n chain_api_plugin_impl(chain_controller& db)\n : db(db) {}\n\n chain_controller& db;\n};\n\n\nchain_api_plugin::chain_api_plugin(){}\nchain_api_plugin::~chain_api_plugin(){}\n\nvoid chain_api_plugin::set_program_options(options_description&, options_description&) {}\nvoid chain_api_plugin::plugin_initialize(const variables_map&) {}\n\n#define CALL(api_name, api_handle, api_namespace, call_name, http_response_code) \\\n{std::string(\"\/v1\/\" #api_name \"\/\" #call_name), \\\n [this, api_handle](string, string body, url_response_callback cb) mutable { \\\n try { \\\n if (body.empty()) body = \"{}\"; \\\n auto result = api_handle.call_name(fc::json::from_string(body).as()); \\\n cb(http_response_code, fc::json::to_string(result)); \\\n } catch (chain::tx_missing_sigs& e) { \\\n error_results results{401, \"UnAuthorized\", e.to_string()}; \\\n cb(401, fc::json::to_string(results)); \\\n } catch (chain::tx_duplicate& e) { \\\n error_results results{409, \"Conflict\", e.to_string()}; \\\n cb(409, fc::json::to_string(results)); \\\n } catch (chain::transaction_exception& e) { \\\n error_results results{400, \"Bad Request\", e.to_string()}; \\\n cb(400, fc::json::to_string(results)); \\\n } catch (fc::eof_exception& e) { \\\n error_results results{400, \"Bad Request\", e.to_string()}; \\\n cb(400, fc::json::to_string(results)); \\\n elog(\"Unable to parse arguments: ${args}\", (\"args\", body)); \\\n } catch (fc::exception& e) { \\\n error_results results{500, \"Internal Service Error\", e.to_detail_string()}; \\\n cb(500, fc::json::to_string(results)); \\\n elog(\"Exception encountered while processing ${call}: ${e}\", (\"call\", #api_name \".\" #call_name)(\"e\", e)); \\\n } \\\n }}\n\n#define CHAIN_RO_CALL(call_name, http_response_code) CALL(chain, ro_api, chain_apis::read_only, call_name, http_response_code)\n#define CHAIN_RW_CALL(call_name, http_response_code) CALL(chain, rw_api, chain_apis::read_write, call_name, http_response_code)\n\nvoid chain_api_plugin::plugin_startup() {\n ilog( \"starting chain_api_plugin\" );\n my.reset(new chain_api_plugin_impl(app().get_plugin().chain()));\n auto ro_api = app().get_plugin().get_read_only_api();\n auto rw_api = app().get_plugin().get_read_write_api();\n\n app().get_plugin().add_api({\n CHAIN_RO_CALL(get_info, 200),\n CHAIN_RO_CALL(get_block, 200),\n CHAIN_RO_CALL(get_account, 200),\n CHAIN_RO_CALL(get_code, 200),\n CHAIN_RO_CALL(get_table_rows, 200),\n CHAIN_RO_CALL(abi_json_to_bin, 200),\n CHAIN_RO_CALL(abi_bin_to_json, 200),\n CHAIN_RO_CALL(get_required_keys, 200),\n CHAIN_RW_CALL(push_block, 202),\n CHAIN_RW_CALL(push_transaction, 202),\n CHAIN_RW_CALL(push_transactions, 202)\n });\n}\n\nvoid chain_api_plugin::plugin_shutdown() {}\n\n}\n<|endoftext|>"} {"text":"\/*\nCopyright (c) 2016 Barrett Adair\n\nDistributed under the Boost Software License, Version 1.0.\n(See accompanying file LICENSE.md or copy at http:\/\/boost.org\/LICENSE_1_0.txt)\n\nHEADER GUARDS INTENTIONALLY OMITTED\nDO NOT INCLUDE THIS HEADER DIRECTLY\n\nBOOST_CLBL_TRTS_INCLUDE_QUALIFIERS - the function-level qualifiers for the\n current inclusion (combinations of `const` `volatile` `&` `&&`, or nothing)\n\nBOOST_CLBL_TRTS_INCLUDE_TRANSACTION_SAFE - the transaction_safe specifier for\n the current include (`transaction_safe` or nothing)\n\nBOOST_CLBL_TRTS_IS_TRANSACTION_SAFE - `std::true_type` or `std::false_type`,\n tied on whether BOOST_CLBL_TRTS_INCLUDE_TRANSACTION_SAFE is `transaction_safe`\n\nBOOST_CLBL_TRTS_TRANSACTION_SAFE_SPECIFIER - `transaction_safe` when\n BOOST_CLBL_TRTS_ENABLE_TRANSACTION_SAFE is defined, otherwise nothing\n\nBOOST_CLBL_TRTS_NOEXCEPT_SPEC - the noexcept specifier for\n the current include (`noexcept` or nothing)\n\nBOOST_CLBL_TRTS_IS_NOEXCEPT - `std::true_type` or `std::false_type`,\n tied on whether BOOST_CLBL_TRTS_NOEXCEPT_SPEC is `noexcept`\n\nBOOST_CLBL_TRTS_NOEXCEPT_SPECIFIER - `noexcept` if\n BOOST_CLBL_TRTS_ENABLE_NOEXCEPT_TYPES is defined, otherwise nothing\n*\/\n\ntemplate\nstruct pmf\n : default_callable_traits {\n \n static constexpr bool value = true;\n \n using traits = pmf;\n\n using return_type = Return;\n\n using type = Return(BOOST_CLBL_TRTS_CC T::*)(Args...)\n BOOST_CLBL_TRTS_INCLUDE_QUALIFIERS\n BOOST_CLBL_TRTS_INCLUDE_TRANSACTION_SAFE\n BOOST_CLBL_TRTS_NOEXCEPT_SPEC;\n\n using invoke_type = typename std::conditional<\n std::is_rvalue_reference::value,\n T BOOST_CLBL_TRTS_INCLUDE_QUALIFIERS,\n typename std::add_lvalue_reference::type\n >::type;\n \n using arg_types = std::tuple;\n using non_invoke_arg_types = std::tuple;\n\n using function_object_signature = Return(Args...);\n\n using function_type = Return(invoke_type, Args...);\n\n using qualified_function_type = Return(Args...)\n BOOST_CLBL_TRTS_INCLUDE_ABOMINABLE_QUALIFIERS\n BOOST_CLBL_TRTS_INCLUDE_TRANSACTION_SAFE\n BOOST_CLBL_TRTS_NOEXCEPT_SPEC;\n\n using remove_varargs = type;\n \n using add_varargs =\n Return(BOOST_CLBL_TRTS_VARARGS_CC T::*)(Args..., ...)\n BOOST_CLBL_TRTS_INCLUDE_QUALIFIERS\n BOOST_CLBL_TRTS_INCLUDE_TRANSACTION_SAFE\n BOOST_CLBL_TRTS_NOEXCEPT_SPEC;\n \n using is_noexcept = BOOST_CLBL_TRTS_IS_NOEXCEPT;\n\n using remove_noexcept = Return(BOOST_CLBL_TRTS_CC T::*)(Args...)\n BOOST_CLBL_TRTS_INCLUDE_QUALIFIERS\n BOOST_CLBL_TRTS_INCLUDE_TRANSACTION_SAFE;\n\n using add_noexcept = Return(BOOST_CLBL_TRTS_CC T::*)(Args...)\n BOOST_CLBL_TRTS_INCLUDE_QUALIFIERS\n BOOST_CLBL_TRTS_INCLUDE_TRANSACTION_SAFE\n BOOST_CLBL_TRTS_NOEXCEPT_SPECIFIER;\n\n using is_transaction_safe = BOOST_CLBL_TRTS_IS_TRANSACTION_SAFE;\n\n using remove_transaction_safe = Return(BOOST_CLBL_TRTS_CC T::*)(Args...)\n BOOST_CLBL_TRTS_INCLUDE_QUALIFIERS\n BOOST_CLBL_TRTS_NOEXCEPT_SPEC;\n\n using add_transaction_safe = Return(BOOST_CLBL_TRTS_CC T::*)(Args...)\n BOOST_CLBL_TRTS_INCLUDE_QUALIFIERS\n BOOST_CLBL_TRTS_TRANSACTION_SAFE_SPECIFIER\n BOOST_CLBL_TRTS_NOEXCEPT_SPEC;\n\n using class_type = T;\n\n using qualifiers = default_callable_traits;\n \n template\n using set_qualifiers = set_member_function_qualifiers<\n Flags, is_transaction_safe::value, is_noexcept::value,\n BOOST_CLBL_TRTS_CC_TAG, T, Return, Args...>;\n \n using remove_member_reference = set_qualifiers;\n \n using add_member_lvalue_reference = set_qualifiers<\n collapse_flags::value>;\n \n using add_member_rvalue_reference = set_qualifiers<\n collapse_flags::value>;\n \n using add_member_const = set_qualifiers;\n\n using add_member_volatile = set_qualifiers;\n\n using add_member_cv = set_qualifiers;\n \n using remove_member_const = set_qualifiers<\n qualifiers::ref_flags | remove_const_flag::value>;\n \n using remove_member_volatile = set_qualifiers<\n qualifiers::ref_flags | remove_volatile_flag::value>;\n \n using remove_member_cv = set_qualifiers;\n \n template\n using apply_member_pointer =\n Return(BOOST_CLBL_TRTS_CC U::*)(Args...)\n BOOST_CLBL_TRTS_INCLUDE_QUALIFIERS\n BOOST_CLBL_TRTS_INCLUDE_TRANSACTION_SAFE\n BOOST_CLBL_TRTS_NOEXCEPT_SPEC;\n \n template\n using apply_return =\n NewReturn(BOOST_CLBL_TRTS_CC T::*)(Args...)\n BOOST_CLBL_TRTS_INCLUDE_QUALIFIERS\n BOOST_CLBL_TRTS_INCLUDE_TRANSACTION_SAFE\n BOOST_CLBL_TRTS_NOEXCEPT_SPEC;\n \n template class Container>\n using expand_args = Container;\n\n using is_member_pointer = std::true_type;\n};\nDelete pmf_4.hpp<|endoftext|>"} {"text":"\/*\n\n@Copyright Barrett Adair 2015-2017\nDistributed under the Boost Software License, Version 1.0.\n(See accompanying file LICENSE.md or copy at http:\/\/boost.org\/LICENSE_1_0.txt)\n\n*\/\n\n#ifndef BOOST_CLBL_TRTS_REMOVE_MEMBER_VOLATILE_HPP\n#define BOOST_CLBL_TRTS_REMOVE_MEMBER_VOLATILE_HPP\n\n#include \n\nnamespace boost { namespace callable_traits {\n\n\/\/[ remove_member_volatile_hpp\n\/*`\n[section:ref_remove_member_volatile remove_member_volatile]\n[heading Header]\n``#include ``\n[heading Definition]\n*\/\n\ntemplate\nusing remove_member_volatile_t = \/\/see below\n\/\/<-\n detail::try_but_fail_if_invalid<\n typename detail::traits::remove_member_volatile,\n member_qualifiers_are_illegal_for_this_type>;\n\nnamespace detail {\n\n template\n struct remove_member_volatile_impl {};\n\n template\n struct remove_member_volatile_impl , detail::dummy>::type>\n {\n using type = remove_member_volatile_t;\n };\n}\n\n\/\/->\n\ntemplate\nstruct remove_member_volatile : detail::remove_member_volatile_impl {};\n\n\/\/<-\n}} \/\/ namespace boost::callable_traits\n\/\/->\n\n\/*`\n[heading Constraints]\n* `T` must be a function type or a member function pointer type\n* If `T` is a pointer, it may not be cv\/ref qualified\n\n[heading Behavior]\n* A substitution failure occurs if the constraints are violated.\n* Removes the member `volatile` qualifier from `T`, if present.\n\n[heading Input\/Output Examples]\n[table\n [[`T`] [`remove_member_volatile_t`]]\n [[`int() volatile`] [`int()`]]\n [[`int(foo::*)() volatile`] [`int(foo::*)()`]]\n [[`int(foo::*)() volatile &`] [`int(foo::*)() &`]]\n [[`int(foo::*)() volatile &&`] [`int(foo::*)() &&`]]\n [[`int(foo::*)() volatile`] [`int(foo::*)()`]]\n [[`int(foo::*)() const volatile`] [`int(foo::*)() const`]]\n [[`int`] [(substitution failure)]]\n [[`int (&)()`] [(substitution failure)]]\n [[`int (*)()`] [(substitution failure)]]\n [[`int foo::*`] [(substitution failure)]]\n [[`int (foo::* const)()`] [(substitution failure)]]\n]\n\n[heading Example Program]\n[import ..\/example\/remove_member_volatile.cpp]\n[remove_member_volatile]\n[endsect]\n*\/\n\/\/]\n\n#endif \/\/ #ifndef BOOST_CLBL_TRTS_REMOVE_MEMBER_VOLATILE_HPP\nDelete remove_member_volatile.hpp<|endoftext|>"} {"text":"\/\/ Python module for playing audio\n\/\/ part of MusicPlayer, https:\/\/github.com\/albertz\/music-player\n\/\/ Copyright (c) 2012, Albert Zeyer, www.az2000.de\n\/\/ All rights reserved.\n\/\/ This code is under the 2-clause BSD license, see License.txt in the root directory of this project.\n\n\/\/ compile:\n\/\/ gcc -c musicplayer*.{c,cpp} -I \/System\/Library\/Frameworks\/Python.framework\/Headers\/\n\/\/ libtool -dynamic -o musicplayer.so musicplayer*.o -framework Python -lavformat -lavutil -lavcodec -lswresample -lportaudio -lc\n\n\/\/ loosely based on ffplay.c\n\/\/ https:\/\/github.com\/FFmpeg\/ffmpeg\/blob\/master\/ffplay.c\n\n\/\/ Similar to PyFFmpeg. http:\/\/code.google.com\/p\/pyffmpeg\/\n\/\/ This module is intended to be much simpler\/high-level, though.\n\n\/\/ Pyton interface:\n\/\/\tcreatePlayer() -> player object with:\n\/\/\t\tqueue: song generator\n\/\/\t\tpeekQueue(n): list of upcoming songs. this should not change the queue. this also might not be accurate but that doesn't matter. it might also return less. it is used for caching and gapless playback. if the queue returns other songs later, it will just ignore these peeked songs. otherwise, it will use these caches.\n\/\/\t\tplaying: True or False, initially False\n\/\/\t\tvolume: 1.0 is norm; this is just a factor to each sample. default is 0.9\n\/\/\t\tvolumeSmoothClip: smooth clipping, see below. set to (1,1) to disable. default is (0.95,10)\n\/\/\t\tcurSong: current song (read only)\n\/\/\t\tcurSongPos: current song pos (read only)\n\/\/\t\tcurSongLen: current song len (read only)\n\/\/\t\tcurSongGainFactor: current song gain. read from song.gain (see below). can also be written\n\/\/\t\tseekAbs(t) \/ seekRel(t): seeking functions (t in seconds, accepts float)\n\/\/\t\tnextSong(): skip to next song function\n\/\/\tsong object expected interface:\n\/\/\t\treadPacket(bufSize): should return some string\n\/\/\t\tseekRaw(offset, whence): should seek and return the current pos\n\/\/\t\tgain: some gain in decible, e.g. calculated by calcReplayGain. if not present, is ignored\n\/\/\t\turl: some url, can be anything printable (not used at the moment)\n\/\/\tand other functions, see their embedded doc ...\n\n\n#include \"musicplayer.h\"\n\n\n\n\n\n\n\n\n\nstatic PyMethodDef module_methods[] = {\n\t{\"createPlayer\",\t(PyCFunction)pyCreatePlayer,\tMETH_NOARGS,\t\"creates new player\"},\n\t{\"getSoundDevices\", (PyCFunction)pyGetSoundDevices, METH_NOARGS,\t\"get list of sound device names\"},\n\t{\"getMetadata\",\t\tpyGetMetadata,\tMETH_VARARGS,\t\"get metadata for Song\"},\n\t{\"calcAcoustIdFingerprint\",\t\tpyCalcAcoustIdFingerprint,\tMETH_VARARGS,\t\"calculate AcoustID fingerprint for Song\"},\n\t{\"calcBitmapThumbnail\",\t\t(PyCFunction)pyCalcBitmapThumbnail,\tMETH_VARARGS|METH_KEYWORDS,\t\"calculate bitmap thumbnail for Song\"},\n\t{\"calcReplayGain\",\t\t(PyCFunction)pyCalcReplayGain,\tMETH_VARARGS|METH_KEYWORDS,\t\"calculate ReplayGain for Song\"},\n\t{\"setFfmpegLogLevel\",\t\tpySetFfmpegLogLevel,\tMETH_VARARGS,\t\"set FFmpeg log level (av_log_set_level)\"},\n\t{\"enableDebugLog\",\t(PyCFunction)pyEnableDebugLog,\tMETH_VARARGS,\t\"enable\/disable debug log\"},\n\t{NULL,\t\t\t\tNULL}\t\/* sentinel *\/\n};\n\nPyDoc_STRVAR(module_doc,\n\"Music player.\");\n\nstatic PyObject* EventClass = NULL;\n\nstatic void init() {\n\tPyEval_InitThreads(); \/* Start the interpreter's thread-awareness *\/\n\tinitPlayerOutput();\n\tinitPlayerDecoder();\n}\n\n\nPyMODINIT_FUNC\ninitmusicplayer(void)\n{\n\t\/\/printf(\"initmusicplayer\\n\");\n\tinit();\n\tif (PyType_Ready(&Player_Type) < 0)\n\t\tPy_FatalError(\"Can't initialize player type\");\n\tPyObject* m = Py_InitModule3(\"musicplayer\", module_methods, module_doc);\n\tif(!m) {\n\t\tPy_FatalError(\"Can't initialize musicplayer module\");\n\t\treturn;\n\t}\n\t\n\tif(EventClass == NULL) {\n\t\tPyObject* classDict = PyDict_New();\n\t\tassert(classDict);\n\t\tPyObject* className = PyString_FromString(\"Event\");\n\t\tassert(className);\n\t\tEventClass = PyClass_New(NULL, classDict, className);\n\t\tassert(EventClass);\n\t\tPy_XDECREF(classDict); classDict = NULL;\n\t\tPy_XDECREF(className); className = NULL;\n\t}\n\t\n\tif(EventClass) {\n\t\tPy_INCREF(EventClass);\n\t\tPyModule_AddObject(m, \"Event\", EventClass); \/\/ takes the ref\n\t}\n}\ncomment update\/\/ Python module for playing audio\n\/\/ part of MusicPlayer, https:\/\/github.com\/albertz\/music-player\n\/\/ Copyright (c) 2012, Albert Zeyer, www.az2000.de\n\/\/ All rights reserved.\n\/\/ This code is under the 2-clause BSD license, see License.txt in the root directory of this project.\n\n\/\/ compile:\n\/\/ gcc -c musicplayer*.cpp -I \/System\/Library\/Frameworks\/Python.framework\/Headers\/\n\/\/ libtool -dynamic -o musicplayer.so musicplayer*.o -framework Python -lavformat -lavutil -lavcodec -lswresample -lportaudio -lc\n\n\/\/ loosely based on ffplay.c\n\/\/ https:\/\/github.com\/FFmpeg\/ffmpeg\/blob\/master\/ffplay.c\n\n\/\/ Similar to PyFFmpeg. http:\/\/code.google.com\/p\/pyffmpeg\/\n\/\/ This module is intended to be much simpler\/high-level, though.\n\n\/\/ Pyton interface:\n\/\/\tcreatePlayer() -> player object with:\n\/\/\t\tqueue: song generator\n\/\/\t\tpeekQueue(n): list of upcoming songs. this should not change the queue. this also might not be accurate but that doesn't matter. it might also return less. it is used for caching and gapless playback. if the queue returns other songs later, it will just ignore these peeked songs. otherwise, it will use these caches.\n\/\/\t\tplaying: True or False, initially False\n\/\/\t\tvolume: 1.0 is norm; this is just a factor to each sample. default is 0.9\n\/\/\t\tvolumeSmoothClip: smooth clipping, see below. set to (1,1) to disable. default is (0.95,10)\n\/\/\t\tcurSong: current song (read only)\n\/\/\t\tcurSongPos: current song pos (read only)\n\/\/\t\tcurSongLen: current song len (read only)\n\/\/\t\tcurSongGainFactor: current song gain. read from song.gain (see below). can also be written\n\/\/\t\tseekAbs(t) \/ seekRel(t): seeking functions (t in seconds, accepts float)\n\/\/\t\tnextSong(): skip to next song function\n\/\/\tsong object expected interface:\n\/\/\t\treadPacket(bufSize): should return some string\n\/\/\t\tseekRaw(offset, whence): should seek and return the current pos\n\/\/\t\tgain: some gain in decible, e.g. calculated by calcReplayGain. if not present, is ignored\n\/\/\t\turl: some url, can be anything printable (not used at the moment)\n\/\/\tand other functions, see their embedded doc ...\n\n\n#include \"musicplayer.h\"\n\n\n\n\n\n\n\n\n\nstatic PyMethodDef module_methods[] = {\n\t{\"createPlayer\",\t(PyCFunction)pyCreatePlayer,\tMETH_NOARGS,\t\"creates new player\"},\n\t{\"getSoundDevices\", (PyCFunction)pyGetSoundDevices, METH_NOARGS,\t\"get list of sound device names\"},\n\t{\"getMetadata\",\t\tpyGetMetadata,\tMETH_VARARGS,\t\"get metadata for Song\"},\n\t{\"calcAcoustIdFingerprint\",\t\tpyCalcAcoustIdFingerprint,\tMETH_VARARGS,\t\"calculate AcoustID fingerprint for Song\"},\n\t{\"calcBitmapThumbnail\",\t\t(PyCFunction)pyCalcBitmapThumbnail,\tMETH_VARARGS|METH_KEYWORDS,\t\"calculate bitmap thumbnail for Song\"},\n\t{\"calcReplayGain\",\t\t(PyCFunction)pyCalcReplayGain,\tMETH_VARARGS|METH_KEYWORDS,\t\"calculate ReplayGain for Song\"},\n\t{\"setFfmpegLogLevel\",\t\tpySetFfmpegLogLevel,\tMETH_VARARGS,\t\"set FFmpeg log level (av_log_set_level)\"},\n\t{\"enableDebugLog\",\t(PyCFunction)pyEnableDebugLog,\tMETH_VARARGS,\t\"enable\/disable debug log\"},\n\t{NULL,\t\t\t\tNULL}\t\/* sentinel *\/\n};\n\nPyDoc_STRVAR(module_doc,\n\"Music player.\");\n\nstatic PyObject* EventClass = NULL;\n\nstatic void init() {\n\tPyEval_InitThreads(); \/* Start the interpreter's thread-awareness *\/\n\tinitPlayerOutput();\n\tinitPlayerDecoder();\n}\n\n\nPyMODINIT_FUNC\ninitmusicplayer(void)\n{\n\t\/\/printf(\"initmusicplayer\\n\");\n\tinit();\n\tif (PyType_Ready(&Player_Type) < 0)\n\t\tPy_FatalError(\"Can't initialize player type\");\n\tPyObject* m = Py_InitModule3(\"musicplayer\", module_methods, module_doc);\n\tif(!m) {\n\t\tPy_FatalError(\"Can't initialize musicplayer module\");\n\t\treturn;\n\t}\n\t\n\tif(EventClass == NULL) {\n\t\tPyObject* classDict = PyDict_New();\n\t\tassert(classDict);\n\t\tPyObject* className = PyString_FromString(\"Event\");\n\t\tassert(className);\n\t\tEventClass = PyClass_New(NULL, classDict, className);\n\t\tassert(EventClass);\n\t\tPy_XDECREF(classDict); classDict = NULL;\n\t\tPy_XDECREF(className); className = NULL;\n\t}\n\t\n\tif(EventClass) {\n\t\tPy_INCREF(EventClass);\n\t\tPyModule_AddObject(m, \"Event\", EventClass); \/\/ takes the ref\n\t}\n}\n<|endoftext|>"} {"text":"\/**************************************************************************\n * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *\n * *\n * Author: The ALICE Off-line Project. *\n * Contributors are mentioned in the code where appropriate. *\n * *\n * Permission to use, copy, modify and distribute this software and its *\n * documentation strictly for non-commercial purposes is hereby granted *\n * without fee, provided that the above copyright notice appears in all *\n * copies and that both the copyright notice and this permission notice *\n * appear in the supporting documentation. The authors make no claims *\n * about the suitability of this software for any purpose. It is *\n * provided \"as is\" without express or implied warranty. *\n **************************************************************************\/\n\n\/\/ $Id$\n\/\/ Category: management\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Class AliMpManuStore\n\/\/ --------------------\n\/\/ The container class for manu serial numbersd\n\/\/ Authors: Ivana Hrivnacova, IPN Orsay\n\/\/ Christian Finck, SUBATECH Nantes\n\/\/-----------------------------------------------------------------------------\n\n#include \"AliMpManuStore.h\"\n\n#include \"AliMpDEStore.h\"\n#include \"AliMpDEManager.h\"\n#include \"AliMpDetElement.h\"\n#include \"AliMpConstants.h\"\n#include \"AliMpDataStreams.h\"\n#include \"AliMpFiles.h\"\n#include \"AliMpHelper.h\"\n#include \"AliMpConstants.h\"\n#include \"AliMpEncodePair.h\"\n\n#include \"AliLog.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n\/\/\/ \\cond CLASSIMP\nClassImp(AliMpManuStore)\n\/\/\/ \\endcond\n\nAliMpManuStore* AliMpManuStore::fgInstance = 0;\nBool_t AliMpManuStore::fgWarnIfDoublon = kFALSE;\n\n\/\/\n\/\/ static methods\n\/\/\n\n\/\/______________________________________________________________________________\nAliMpManuStore* AliMpManuStore::Instance(Bool_t warn) \n{\n \/\/\/ Create the DDL store if it does not yet exist\n \/\/\/ and return its instance\n\n if ( ! fgInstance && warn ) {\n AliWarningClass(\"Manu Store has not been loaded\");\n }\n\n return fgInstance;\n}\n\n\/\/______________________________________________________________________________\nAliMpManuStore* AliMpManuStore::ReadData(const AliMpDataStreams& dataStreams, \n Bool_t warn) \n{\n \/\/\/ Load the DDL store from ASCII data files\n \/\/\/ and return its instance\n\n if ( fgInstance ) {\n if ( warn )\n AliWarningClass(\"DDL Store has been already loaded\");\n return fgInstance;\n }\n\n if ( dataStreams.GetReadFromFiles() )\n AliInfoClass(\"Reading Manu Store from ASCII files.\");\n\n fgInstance = new AliMpManuStore(dataStreams);\n return fgInstance;\n}\n\n\/\/\n\/\/ ctors, dtor\n\/\/\n\n\n\/\/______________________________________________________________________________\nAliMpManuStore::AliMpManuStore(const AliMpDataStreams& dataStreams)\n: TObject(),\n fkDataStreams(dataStreams),\n fManuToSerialNbs(),\n fSerialNbToManus(),\n fNofManusInDE(),\n fNofManus(0)\n{ \n\/\/\/ Standard constructor\n\n AliDebug(1,\"\");\n\n \/\/ Check if DE store is loaded\n if ( ! AliMpDEStore::Instance(false) ) {\n AliErrorStream()\n << \"Mapping segmentation has not be loaded. Cannont load Manu store\"\n << endl;\n return;\n } \n\n ReadManuSerial();\n}\n\n\/\/______________________________________________________________________________\nAliMpManuStore::AliMpManuStore(TRootIOCtor* ioCtor)\n: TObject(),\n fkDataStreams(ioCtor),\n fManuToSerialNbs(),\n fSerialNbToManus(),\n fNofManusInDE(),\n fNofManus(0)\n{ \n\/\/\/ Constructor for IO\n\n AliDebug(1,\"\");\n}\n\n\n\/\/______________________________________________________________________________\nAliMpManuStore::~AliMpManuStore()\n{\n\/\/\/ Destructor\n\n AliDebug(1,\"\");\n}\n\n\/\/\n\/\/ private methods\n\/\/\n\n\/\/______________________________________________________________________________\nBool_t AliMpManuStore::ReadData(const AliMpDetElement* de, Int_t& nofManus)\n{\n\/\/\/ Read manu serial numbers for the given detection element\n\n Int_t deId = de->GetId();\n TString deName = de->GetDEName();\n AliMp::StationType stationType \n = AliMpDEManager::GetStationType(de->GetId());\n AliMq::Station12Type station12Type \n = AliMpDEManager::GetStation12Type(de->GetId());\n\n \/\/ Nothing to be done for trigger\n if ( stationType == AliMp::kStationTrigger ) {\n nofManus = 0;\n return kTRUE;\n } \n\n static Int_t manuMask = AliMpConstants::ManuMask(AliMp::kNonBendingPlane);\n\n istream& in \n = fkDataStreams.\n CreateDataStream(\n AliMpFiles::ManuToSerialPath(deName, stationType, station12Type));\n\n char line[80];\n\n nofManus = 0;\n while ( in.getline(line,80) ) {\n\n if ( line[0] == '#' ) continue;\n\n TString tmp(AliMpHelper::Normalize(line));\n\n TObjArray* stringList = tmp.Tokenize(TString(\" \"));\n\n Int_t manuId = atoi( ((TObjString*)stringList->At(0))->GetName());\n Int_t manuSerial = atoi( ((TObjString*)stringList->At(2))->GetName());\n \n TString sPlane = ((TObjString*)stringList->At(1))->GetString();\n\n \/\/ filling manuId <> manuSerial\n if (!sPlane.CompareTo(PlaneTypeName(AliMp::kBendingPlane)))\n\tAddManu(deId, manuId, manuSerial);\n else \n\tAddManu(deId, manuId + manuMask, manuSerial);\n \n ++nofManus; \n\n delete stringList;\n }\n \n return kTRUE;\n}\n\n\/\/______________________________________________________________________________\nBool_t AliMpManuStore::ReadManuSerial()\n{\n\/\/\/ Read data files for all detection elements.\n\/\/\/ Return true if reading was successful.\n\n Bool_t isOk = kTRUE;\n\n \/\/ Loop over DE\n AliMpDEIterator it;\n for ( it.First(); ! it.IsDone(); it.Next() ) {\n\n AliMpDetElement* detElement = it.CurrentDE();\n\n Int_t nofManus;\n Bool_t result = ReadData(detElement, nofManus); \n fNofManusInDE.Add(detElement->GetId(), nofManus);\n fNofManus += nofManus;\n \n AliDebugStream(2) \n << \"Adding \" << nofManus << \" manus for de \" \n << detElement->GetId() << endl;\n \n isOk = isOk && result;\n }\n \n return isOk; \n} \n\n\/\/______________________________________________________________________________\nvoid AliMpManuStore::ReplaceManu(Int_t detElemId, Int_t manuId, Int_t serialNb) \n{\n\/\/\/ Replace manu in the map.\n\/\/\/ As TExMap has no replcae function, we have to rebuild map once again.\n\/\/\/ Not yet in use, declared private.\n\n Long_t index = AliMp::Pair(detElemId, manuId);\n\n TExMap newManuToSerialNbs;\n \/\/ Loop over map\n TExMapIter it(&fManuToSerialNbs);\n\n#if ROOT_SVN_REVISION >= 29598\n Long64_t key;\n Long64_t value;\n#else\n Long_t key;\n Long_t value;\n#endif\n while ( ( it.Next(key, value) ) ) {\n\n if ( key != index ) \n newManuToSerialNbs.Add(key, value);\n else\n newManuToSerialNbs.Add(index, Long_t(serialNb));\n }\n \n TExMap newSerialNbToManus;\n \/\/ Loop over map\n TExMapIter it2(&fSerialNbToManus);\n while ( ( it2.Next(key, value) ) ) {\n\n if ( value != index ) \n newSerialNbToManus.Add(key, value);\n else\n newSerialNbToManus.Add(Long_t(serialNb), index);\n }\n\n \/\/ And now replace the maps\n fManuToSerialNbs = newManuToSerialNbs;\n fSerialNbToManus = newManuToSerialNbs;\n} \n\n\n\/\/______________________________________________________________________________\nBool_t AliMpManuStore::WriteData(const TString& outDir)\n{\n\/\/\/ Write data files for all detection elements.\n\/\/\/ Return true if reading was successful.\n\/\/\/ Not yet in use, declared private.\n\n TString curDir = gSystem->pwd();\n\n \/\/ Create top directory\n \/\/\n if ( gSystem->OpenDirectory(outDir.Data()) ) {\n AliErrorStream() \n << \"Directory \" << outDir.Data() << \" already exists\" << endl;\n return kFALSE;\n }\n else {\n AliDebugStream(2) << \"Making directory \" << outDir.Data() << endl;\n gSystem->mkdir(outDir.Data());\n } \n\n \/\/ Loop over DE\n AliMpDEIterator it;\n for ( it.First(); ! it.IsDone(); it.Next() ) {\n \n AliMpDetElement* detElement = it.CurrentDE();\n Int_t detElemId = detElement->GetId();\n TString deName = detElement->GetDEName();\n AliMp::StationType stationType \n = AliMpDEManager::GetStationType(detElemId);\n AliMq::Station12Type station12Type \n = AliMpDEManager::GetStation12Type(detElemId);\n \n if ( stationType == AliMp::kStationTrigger ) continue; \n\n \/\/ Create directory if it does not yet exist\n \/\/\n TString dirPath = outDir + AliMpFiles::StationDataDir(stationType, station12Type);\n if ( ! gSystem->OpenDirectory(dirPath.Data()) ) {\n AliDebugStream(2) << \"Making directory \" << dirPath.Data() << endl;\n gSystem->mkdir(dirPath.Data());\n } \n\n \/\/ Compose output file path \n \/\/\n string dataPath = AliMpFiles::ManuToSerialPath(deName, stationType, station12Type).Data();\n string top = AliMpFiles::GetTop().Data();\n if ( dataPath.find(top) != string::npos ) dataPath.erase(0, top.size()+1);\n dataPath.erase(0,dataPath.find('\/')+1);\n TString dataPath1 = dataPath;\n TString filePath = outDir + \"\/\" + dataPath1; \n\n \/\/ Open file\n \/\/\n ofstream out(filePath.Data());\n if ( ! out.good() ) {\n AliErrorStream() \n << \"Cannot open output file \" << filePath.Data() << endl;\n return kFALSE; \n }\n \n \/\/ Loop over map\n TExMapIter it2(&fManuToSerialNbs);\n#if ROOT_SVN_REVISION >= 29598\n Long64_t key;\n Long64_t value;\n#else\n Long_t key;\n Long_t value;\n#endif\n while ( ( it2.Next(key, value) ) ) {\n Int_t pairFirst = AliMp::PairFirst(key);\n \n if ( pairFirst != detElemId ) continue;\n \n Int_t manuId = AliMp::PairSecond(key);\n\n AliDebugStream(3) \n << \"Go to write \" << key << \" \" \n << pairFirst << \" \" << manuId << \" \" << value << endl;\n\n static Int_t manuMask = AliMpConstants::ManuMask(AliMp::kNonBendingPlane);\n\n TString planeName = PlaneTypeName(AliMp::kBendingPlane);\n if ( manuId> manuMask ) {\n planeName = PlaneTypeName(AliMp::kNonBendingPlane);\n manuId -= manuMask;\n } \n out << manuId << \" \" << planeName.Data() << \" \" << value << endl;\n \n AliDebugStream(3) \n << manuId << \" \" << planeName.Data() << \" \" << value << endl;\n } \n out.close();\n } \n gSystem->cd(curDir); \n return kTRUE; \n} \n\n\/\/\n\/\/ public methods\n\/\/\n\n\n\/\/______________________________________________________________________________\nInt_t AliMpManuStore::NofManus() const\n{ \n\/\/\/ Return total number of manus in the store\n\n return fNofManus;\n} \n \n\n\/\/______________________________________________________________________________\nInt_t AliMpManuStore::NofManus(Int_t detElemId) const \n{ \n\/\/\/ Return number of manus in given detection element\n\n if ( ! AliMpDEManager::IsValidDetElemId(detElemId, kTRUE) ) return 0; \n\n return fNofManusInDE.GetValue(detElemId); \n}\n\n\/\/______________________________________________________________________________\nBool_t AliMpManuStore::AddManu(Int_t detElemId, Int_t manuId, Int_t serialNb) \n{\n\/\/\/ Add manu to the map\n\n Long_t index = AliMp::Pair(detElemId, manuId);\n \n AliDebugStream(2)\n << \"Adding (\" << detElemId << \",\" << manuId \n << \") as index=\" << index << \" and serialNb=\" << serialNb << endl;\n \n fManuToSerialNbs.Add(index, Long_t(serialNb));\n \n Long_t value = fSerialNbToManus.GetValue(Long_t(serialNb));\n if ( value ) {\n if ( fgWarnIfDoublon ) {\n AliWarningStream() \n << \"Serial number \" << serialNb \n << \" already present for (detElemId, manuId) = \" ;\n AliMp::PairPut(AliWarningStream(), (MpPair_t) value) << endl;\n }\n return kFALSE; \n }\n else {\n fSerialNbToManus.Add(Long_t(serialNb), index);\n return kTRUE;\n } \n} \n\n\n\/\/______________________________________________________________________________\nInt_t AliMpManuStore::GetManuSerial(Int_t detElemId, Int_t manuId) const\n{\n\/\/\/ Return manu serial number for given detElemId and manuId\n\n Long_t index = AliMp::Pair(detElemId, manuId);\n \/\/ cout << index << \" \" << fManuToSerialNbs.GetValue(index) << endl;\n \n return fManuToSerialNbs.GetValue(index);\n} \n\n\/\/______________________________________________________________________________\nMpPair_t AliMpManuStore::GetDetElemIdManu(Int_t manuSerial) const\n{\n\/\/\/ Return detElemId and manuId for given manu serial number \n\/\/\/ as encoded pair\n\n return fSerialNbToManus.GetValue(Long_t(manuSerial));\n} \n\nFixing memory leak in AliMpManuStore::ReadData (bug report #66668)\/**************************************************************************\n * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *\n * *\n * Author: The ALICE Off-line Project. *\n * Contributors are mentioned in the code where appropriate. *\n * *\n * Permission to use, copy, modify and distribute this software and its *\n * documentation strictly for non-commercial purposes is hereby granted *\n * without fee, provided that the above copyright notice appears in all *\n * copies and that both the copyright notice and this permission notice *\n * appear in the supporting documentation. The authors make no claims *\n * about the suitability of this software for any purpose. It is *\n * provided \"as is\" without express or implied warranty. *\n **************************************************************************\/\n\n\/\/ $Id$\n\/\/ Category: management\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Class AliMpManuStore\n\/\/ --------------------\n\/\/ The container class for manu serial numbersd\n\/\/ Authors: Ivana Hrivnacova, IPN Orsay\n\/\/ Christian Finck, SUBATECH Nantes\n\/\/-----------------------------------------------------------------------------\n\n#include \"AliMpManuStore.h\"\n\n#include \"AliMpDEStore.h\"\n#include \"AliMpDEManager.h\"\n#include \"AliMpDetElement.h\"\n#include \"AliMpConstants.h\"\n#include \"AliMpDataStreams.h\"\n#include \"AliMpFiles.h\"\n#include \"AliMpHelper.h\"\n#include \"AliMpConstants.h\"\n#include \"AliMpEncodePair.h\"\n\n#include \"AliLog.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n\/\/\/ \\cond CLASSIMP\nClassImp(AliMpManuStore)\n\/\/\/ \\endcond\n\nAliMpManuStore* AliMpManuStore::fgInstance = 0;\nBool_t AliMpManuStore::fgWarnIfDoublon = kFALSE;\n\n\/\/\n\/\/ static methods\n\/\/\n\n\/\/______________________________________________________________________________\nAliMpManuStore* AliMpManuStore::Instance(Bool_t warn) \n{\n \/\/\/ Create the DDL store if it does not yet exist\n \/\/\/ and return its instance\n\n if ( ! fgInstance && warn ) {\n AliWarningClass(\"Manu Store has not been loaded\");\n }\n\n return fgInstance;\n}\n\n\/\/______________________________________________________________________________\nAliMpManuStore* AliMpManuStore::ReadData(const AliMpDataStreams& dataStreams, \n Bool_t warn) \n{\n \/\/\/ Load the DDL store from ASCII data files\n \/\/\/ and return its instance\n\n if ( fgInstance ) {\n if ( warn )\n AliWarningClass(\"DDL Store has been already loaded\");\n return fgInstance;\n }\n\n if ( dataStreams.GetReadFromFiles() )\n AliInfoClass(\"Reading Manu Store from ASCII files.\");\n\n fgInstance = new AliMpManuStore(dataStreams);\n return fgInstance;\n}\n\n\/\/\n\/\/ ctors, dtor\n\/\/\n\n\n\/\/______________________________________________________________________________\nAliMpManuStore::AliMpManuStore(const AliMpDataStreams& dataStreams)\n: TObject(),\n fkDataStreams(dataStreams),\n fManuToSerialNbs(),\n fSerialNbToManus(),\n fNofManusInDE(),\n fNofManus(0)\n{ \n\/\/\/ Standard constructor\n\n AliDebug(1,\"\");\n\n \/\/ Check if DE store is loaded\n if ( ! AliMpDEStore::Instance(false) ) {\n AliErrorStream()\n << \"Mapping segmentation has not be loaded. Cannont load Manu store\"\n << endl;\n return;\n } \n\n ReadManuSerial();\n}\n\n\/\/______________________________________________________________________________\nAliMpManuStore::AliMpManuStore(TRootIOCtor* ioCtor)\n: TObject(),\n fkDataStreams(ioCtor),\n fManuToSerialNbs(),\n fSerialNbToManus(),\n fNofManusInDE(),\n fNofManus(0)\n{ \n\/\/\/ Constructor for IO\n\n AliDebug(1,\"\");\n}\n\n\n\/\/______________________________________________________________________________\nAliMpManuStore::~AliMpManuStore()\n{\n\/\/\/ Destructor\n\n AliDebug(1,\"\");\n}\n\n\/\/\n\/\/ private methods\n\/\/\n\n\/\/______________________________________________________________________________\nBool_t AliMpManuStore::ReadData(const AliMpDetElement* de, Int_t& nofManus)\n{\n\/\/\/ Read manu serial numbers for the given detection element\n\n Int_t deId = de->GetId();\n TString deName = de->GetDEName();\n AliMp::StationType stationType \n = AliMpDEManager::GetStationType(de->GetId());\n AliMq::Station12Type station12Type \n = AliMpDEManager::GetStation12Type(de->GetId());\n\n \/\/ Nothing to be done for trigger\n if ( stationType == AliMp::kStationTrigger ) {\n nofManus = 0;\n return kTRUE;\n } \n\n static Int_t manuMask = AliMpConstants::ManuMask(AliMp::kNonBendingPlane);\n\n istream& in \n = fkDataStreams.\n CreateDataStream(\n AliMpFiles::ManuToSerialPath(deName, stationType, station12Type));\n\n char line[80];\n\n nofManus = 0;\n while ( in.getline(line,80) ) {\n\n if ( line[0] == '#' ) continue;\n\n TString tmp(AliMpHelper::Normalize(line));\n\n TObjArray* stringList = tmp.Tokenize(TString(\" \"));\n\n Int_t manuId = atoi( ((TObjString*)stringList->At(0))->GetName());\n Int_t manuSerial = atoi( ((TObjString*)stringList->At(2))->GetName());\n \n TString sPlane = ((TObjString*)stringList->At(1))->GetString();\n\n \/\/ filling manuId <> manuSerial\n if (!sPlane.CompareTo(PlaneTypeName(AliMp::kBendingPlane)))\n\tAddManu(deId, manuId, manuSerial);\n else \n\tAddManu(deId, manuId + manuMask, manuSerial);\n \n ++nofManus; \n\n delete stringList;\n }\n \n delete ∈\n \n return kTRUE;\n}\n\n\/\/______________________________________________________________________________\nBool_t AliMpManuStore::ReadManuSerial()\n{\n\/\/\/ Read data files for all detection elements.\n\/\/\/ Return true if reading was successful.\n\n Bool_t isOk = kTRUE;\n\n \/\/ Loop over DE\n AliMpDEIterator it;\n for ( it.First(); ! it.IsDone(); it.Next() ) {\n\n AliMpDetElement* detElement = it.CurrentDE();\n\n Int_t nofManus;\n Bool_t result = ReadData(detElement, nofManus); \n fNofManusInDE.Add(detElement->GetId(), nofManus);\n fNofManus += nofManus;\n \n AliDebugStream(2) \n << \"Adding \" << nofManus << \" manus for de \" \n << detElement->GetId() << endl;\n \n isOk = isOk && result;\n }\n \n return isOk; \n} \n\n\/\/______________________________________________________________________________\nvoid AliMpManuStore::ReplaceManu(Int_t detElemId, Int_t manuId, Int_t serialNb) \n{\n\/\/\/ Replace manu in the map.\n\/\/\/ As TExMap has no replcae function, we have to rebuild map once again.\n\/\/\/ Not yet in use, declared private.\n\n Long_t index = AliMp::Pair(detElemId, manuId);\n\n TExMap newManuToSerialNbs;\n \/\/ Loop over map\n TExMapIter it(&fManuToSerialNbs);\n\n#if ROOT_SVN_REVISION >= 29598\n Long64_t key;\n Long64_t value;\n#else\n Long_t key;\n Long_t value;\n#endif\n while ( ( it.Next(key, value) ) ) {\n\n if ( key != index ) \n newManuToSerialNbs.Add(key, value);\n else\n newManuToSerialNbs.Add(index, Long_t(serialNb));\n }\n \n TExMap newSerialNbToManus;\n \/\/ Loop over map\n TExMapIter it2(&fSerialNbToManus);\n while ( ( it2.Next(key, value) ) ) {\n\n if ( value != index ) \n newSerialNbToManus.Add(key, value);\n else\n newSerialNbToManus.Add(Long_t(serialNb), index);\n }\n\n \/\/ And now replace the maps\n fManuToSerialNbs = newManuToSerialNbs;\n fSerialNbToManus = newManuToSerialNbs;\n} \n\n\n\/\/______________________________________________________________________________\nBool_t AliMpManuStore::WriteData(const TString& outDir)\n{\n\/\/\/ Write data files for all detection elements.\n\/\/\/ Return true if reading was successful.\n\/\/\/ Not yet in use, declared private.\n\n TString curDir = gSystem->pwd();\n\n \/\/ Create top directory\n \/\/\n if ( gSystem->OpenDirectory(outDir.Data()) ) {\n AliErrorStream() \n << \"Directory \" << outDir.Data() << \" already exists\" << endl;\n return kFALSE;\n }\n else {\n AliDebugStream(2) << \"Making directory \" << outDir.Data() << endl;\n gSystem->mkdir(outDir.Data());\n } \n\n \/\/ Loop over DE\n AliMpDEIterator it;\n for ( it.First(); ! it.IsDone(); it.Next() ) {\n \n AliMpDetElement* detElement = it.CurrentDE();\n Int_t detElemId = detElement->GetId();\n TString deName = detElement->GetDEName();\n AliMp::StationType stationType \n = AliMpDEManager::GetStationType(detElemId);\n AliMq::Station12Type station12Type \n = AliMpDEManager::GetStation12Type(detElemId);\n \n if ( stationType == AliMp::kStationTrigger ) continue; \n\n \/\/ Create directory if it does not yet exist\n \/\/\n TString dirPath = outDir + AliMpFiles::StationDataDir(stationType, station12Type);\n if ( ! gSystem->OpenDirectory(dirPath.Data()) ) {\n AliDebugStream(2) << \"Making directory \" << dirPath.Data() << endl;\n gSystem->mkdir(dirPath.Data());\n } \n\n \/\/ Compose output file path \n \/\/\n string dataPath = AliMpFiles::ManuToSerialPath(deName, stationType, station12Type).Data();\n string top = AliMpFiles::GetTop().Data();\n if ( dataPath.find(top) != string::npos ) dataPath.erase(0, top.size()+1);\n dataPath.erase(0,dataPath.find('\/')+1);\n TString dataPath1 = dataPath;\n TString filePath = outDir + \"\/\" + dataPath1; \n\n \/\/ Open file\n \/\/\n ofstream out(filePath.Data());\n if ( ! out.good() ) {\n AliErrorStream() \n << \"Cannot open output file \" << filePath.Data() << endl;\n return kFALSE; \n }\n \n \/\/ Loop over map\n TExMapIter it2(&fManuToSerialNbs);\n#if ROOT_SVN_REVISION >= 29598\n Long64_t key;\n Long64_t value;\n#else\n Long_t key;\n Long_t value;\n#endif\n while ( ( it2.Next(key, value) ) ) {\n Int_t pairFirst = AliMp::PairFirst(key);\n \n if ( pairFirst != detElemId ) continue;\n \n Int_t manuId = AliMp::PairSecond(key);\n\n AliDebugStream(3) \n << \"Go to write \" << key << \" \" \n << pairFirst << \" \" << manuId << \" \" << value << endl;\n\n static Int_t manuMask = AliMpConstants::ManuMask(AliMp::kNonBendingPlane);\n\n TString planeName = PlaneTypeName(AliMp::kBendingPlane);\n if ( manuId> manuMask ) {\n planeName = PlaneTypeName(AliMp::kNonBendingPlane);\n manuId -= manuMask;\n } \n out << manuId << \" \" << planeName.Data() << \" \" << value << endl;\n \n AliDebugStream(3) \n << manuId << \" \" << planeName.Data() << \" \" << value << endl;\n } \n out.close();\n } \n gSystem->cd(curDir); \n return kTRUE; \n} \n\n\/\/\n\/\/ public methods\n\/\/\n\n\n\/\/______________________________________________________________________________\nInt_t AliMpManuStore::NofManus() const\n{ \n\/\/\/ Return total number of manus in the store\n\n return fNofManus;\n} \n \n\n\/\/______________________________________________________________________________\nInt_t AliMpManuStore::NofManus(Int_t detElemId) const \n{ \n\/\/\/ Return number of manus in given detection element\n\n if ( ! AliMpDEManager::IsValidDetElemId(detElemId, kTRUE) ) return 0; \n\n return fNofManusInDE.GetValue(detElemId); \n}\n\n\/\/______________________________________________________________________________\nBool_t AliMpManuStore::AddManu(Int_t detElemId, Int_t manuId, Int_t serialNb) \n{\n\/\/\/ Add manu to the map\n\n Long_t index = AliMp::Pair(detElemId, manuId);\n \n AliDebugStream(2)\n << \"Adding (\" << detElemId << \",\" << manuId \n << \") as index=\" << index << \" and serialNb=\" << serialNb << endl;\n \n fManuToSerialNbs.Add(index, Long_t(serialNb));\n \n Long_t value = fSerialNbToManus.GetValue(Long_t(serialNb));\n if ( value ) {\n if ( fgWarnIfDoublon ) {\n AliWarningStream() \n << \"Serial number \" << serialNb \n << \" already present for (detElemId, manuId) = \" ;\n AliMp::PairPut(AliWarningStream(), (MpPair_t) value) << endl;\n }\n return kFALSE; \n }\n else {\n fSerialNbToManus.Add(Long_t(serialNb), index);\n return kTRUE;\n } \n} \n\n\n\/\/______________________________________________________________________________\nInt_t AliMpManuStore::GetManuSerial(Int_t detElemId, Int_t manuId) const\n{\n\/\/\/ Return manu serial number for given detElemId and manuId\n\n Long_t index = AliMp::Pair(detElemId, manuId);\n \/\/ cout << index << \" \" << fManuToSerialNbs.GetValue(index) << endl;\n \n return fManuToSerialNbs.GetValue(index);\n} \n\n\/\/______________________________________________________________________________\nMpPair_t AliMpManuStore::GetDetElemIdManu(Int_t manuSerial) const\n{\n\/\/\/ Return detElemId and manuId for given manu serial number \n\/\/\/ as encoded pair\n\n return fSerialNbToManus.GetValue(Long_t(manuSerial));\n} \n\n<|endoftext|>"} {"text":"\/******************************************************************************\n**\n** Copyright (C) 2009-2011 Kyle Lutz \n** All rights reserved.\n**\n** This file is a part of the chemkit project. For more information\n** see .\n**\n** Redistribution and use in source and binary forms, with or without\n** modification, are permitted provided that the following conditions\n** are met:\n**\n** * Redistributions of source code must retain the above copyright\n** notice, this list of conditions and the following disclaimer.\n** * Redistributions in binary form must reproduce the above copyright\n** notice, this list of conditions and the following disclaimer in the\n** documentation and\/or other materials provided with the distribution.\n** * Neither the name of the chemkit project nor the names of its\n** contributors may be used to endorse or promote products derived\n** from this software without specific prior written permission.\n**\n** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n** \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n**\n******************************************************************************\/\n\n#include \"uridineminimizationbenchmark.h\"\n\n#include \n#include \n#include \n\nconst std::string dataPath = \"..\/..\/data\/\";\n\nvoid UridineMinimizationBenchmark::benchmark()\n{\n boost::shared_ptr molecule = chemkit::MoleculeFile::quickRead(dataPath + \"uridine.mol2\");\n QVERIFY(molecule != 0);\n\n chemkit::ForceField *forceField = chemkit::ForceField::create(\"uff\");\n QVERIFY(forceField != 0);\n\n forceField->setMolecule(molecule.get());\n bool ok = forceField->setup();\n QVERIFY(ok);\n\n QBENCHMARK {\n for(;;){\n \/\/ converge when rmsg = 0.1\n bool converged = forceField->minimizationStep(0.1);\n\n if(converged){\n break;\n }\n }\n }\n\n delete forceField;\n}\n\nQTEST_APPLESS_MAIN(UridineMinimizationBenchmark)\nUse MoleculeGeometryOptimizer in UridineMinimizationBenchmark\/******************************************************************************\n**\n** Copyright (C) 2009-2011 Kyle Lutz \n** All rights reserved.\n**\n** This file is a part of the chemkit project. For more information\n** see .\n**\n** Redistribution and use in source and binary forms, with or without\n** modification, are permitted provided that the following conditions\n** are met:\n**\n** * Redistributions of source code must retain the above copyright\n** notice, this list of conditions and the following disclaimer.\n** * Redistributions in binary form must reproduce the above copyright\n** notice, this list of conditions and the following disclaimer in the\n** documentation and\/or other materials provided with the distribution.\n** * Neither the name of the chemkit project nor the names of its\n** contributors may be used to endorse or promote products derived\n** from this software without specific prior written permission.\n**\n** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n** \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n**\n******************************************************************************\/\n\n#include \"uridineminimizationbenchmark.h\"\n\n#include \n#include \n#include \n\nconst std::string dataPath = \"..\/..\/data\/\";\n\nvoid UridineMinimizationBenchmark::benchmark()\n{\n boost::shared_ptr molecule = chemkit::MoleculeFile::quickRead(dataPath + \"uridine.mol2\");\n QVERIFY(molecule != 0);\n\n chemkit::MoleculeGeometryOptimizer optimizer;\n optimizer.setForceField(\"uff\");\n optimizer.setMolecule(molecule.get());\n\n bool ok = optimizer.setup();\n QVERIFY(ok);\n\n QBENCHMARK {\n for(;;){\n \/\/ converge when rmsg = 0.1\n bool converged = optimizer.step();\n\n if(converged){\n break;\n }\n }\n }\n}\n\nQTEST_APPLESS_MAIN(UridineMinimizationBenchmark)\n<|endoftext|>"} {"text":"\/***************************************************************************\n * Copyright (C) 2008 by Daniel Schwen *\n * daniel@schwen.de *\n * *\n * This program is free software; you can redistribute it and\/or modify *\n * it under the terms of the GNU General Public License as published by *\n * the Free Software Foundation; either version 2 of the License, or *\n * (at your option) any later version. *\n * *\n * This program is distributed in the hope that it will be useful, *\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *\n * GNU General Public License for more details. *\n * *\n * You should have received a copy of the GNU General Public License *\n * along with this program; if not, write to the *\n * Free Software Foundation, Inc., *\n * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *\n ***************************************************************************\/\n\n\n#ifdef HAVE_CONFIG_H\n#include \n#endif\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"simconf.h\"\n#include \"element.h\"\n#include \"material.h\"\n#include \"sample_wire.h\"\n#include \"sample_burried_wire.h\"\n#include \"ion.h\"\n#include \"trim.h\"\n#include \"invert.h\"\n#include \n\n#include \"functions.h\"\n\nusing namespace std;\n\nint main(int argc, char *argv[])\n{\n char fname[200];\n if( argc != 6 ) \n {\n cerr << \"syntax: \" << argv[0] << \" basename angle[deg] diameter(nm) burried[0,1] numbermultiplier\" << endl;\n return 1;\n }\n\n double theta = atof(argv[2]) * M_PI\/180.0; \/\/ 0 = parallel to wire\n double diameter = 10.0*atof(argv[3]);\n double length = 11000.0; \/\/ 1.1 mu\n bool burried = ( atoi(argv[4]) != 0 );\n double mult = atof(argv[5]);\n\n \/\/ ion series\n const int nstep = 5;\n double ion_dose[nstep] = { 3.0e13, 2.2e13, 1.5e13, 1.2e13, 2.5e13 }; \/\/ in ions\/cm^2\n int ion_count[nstep];\n ionBase* ion_prototype[nstep];\n ion_prototype[0] = new ionBase( 5, 11.0 , 320.0e3 ); \/\/ Z,m,E\n ion_prototype[1] = new ionBase( 5, 11.0 , 220.0e3 ); \/\/ Z,m,E\n ion_prototype[2] = new ionBase( 5, 11.0 , 160.0e3 ); \/\/ Z,m,E\n ion_prototype[3] = new ionBase( 5, 11.0 , 120.0e3 ); \/\/ Z,m,E\n ion_prototype[4] = new ionBase( 15, 31.0 , 250.0e3 ); \/\/ Z,m,E\n\n \/\/ seed randomnumber generator from system entropy pool\n FILE *urand = fopen( \"\/dev\/random\", \"r\" );\n int seed;\n fread( &seed, sizeof(int), 1, urand );\n fclose( urand );\n r250_init( seed<0 ? -seed : seed ); \/\/ random generator goes haywire with neg. seed\n\n \/\/ initialize global parameter structure and read data tables from file\n simconf = new simconfType;\n\n \/\/ initialize sample structure\n sampleWire *sample;\n if( burried )\n sample = new sampleBurriedWire( diameter, diameter, length );\n else\n {\n sample = new sampleWire( diameter, diameter, length );\n sample->bc[2] = sampleWire::CUT;\n }\n\n \/\/ calculate actual ion numbers\n for( int s = 0; s < nstep; ++s )\n {\n double A; \/\/ irradiated area in Ang^2\n if( burried )\n A =( 2.0*length + sample->w[0] ) * ( 2.0*length + sample->w[1] );\n else\n A = cos(theta) * M_PI * 0.25 * sample->w[0] * sample->w[1] + \/\/ slanted top face\n sin(theta) * length * sample->w[0]; \/\/ + projected side\n\n \/\/ 1cm^2 = 1e16 Ang**2, 1Ang^2 = 1e-16cm^2\n ion_count[s] = ion_dose[s] * A * 1.0e-16 * mult;\n cerr << \"Ion \" << s << ' ' << ion_count[s] << endl;\n }\n\n \/\/ initialize trim engine for the sample\n\/* const int z1 = 31;\n const int z2 = 33;\n trimVacMap *trim = new trimVacMap( sample, z1, z2 ); \/\/ GaAs*\/\n \/\/trimBase *trim = new trimBase( sample );\n trimBase *trim = new trimPrimaries( sample );\n\n materialBase *material;\n elementBase *element;\n\n \/\/ Si\n material = new materialBase( 2.329 ); \/\/ rho\n element = new elementBase;\n element->z = 14; \/\/ Si\n element->m = 28.0;\n element->t = 1.0;\n material->element.push_back( element );\n material->prepare(); \/\/ all materials added\n sample->material.push_back( material ); \/\/ add material to sample\n\n \/\/ SiO2 (material[1] for the cover layer in SampleBurriedWire)\n material = new materialBase( 2.634 ); \/\/ rho\n element = new elementBase;\n element->z = 14; \/\/ Si\n element->m = 28.0;\n element->t = 1.0;\n material->element.push_back( element );\n element = new elementBase;\n element->z = 8; \/\/ O\n element->m = 16.0;\n element->t = 2.0;\n material->element.push_back( element );\n material->prepare(); \/\/ all materials added\n sample->material.push_back( material ); \/\/ add material to sample\n\n \/\/ create a FIFO for recoils\n queue recoils;\n\n double norm;\n double jmp = 2.7; \/\/ diffusion jump distance\n int jumps;\n double dif[3];\n\n \/\/snprintf( fname, 199, \"%s.Erec\", argv[1] );\n \/\/FILE *erec = fopen( fname, \"wt\" );\n\n \/\/snprintf( fname, 199, \"%s.dist\", argv[1] );\n \/\/FILE *rdist = fopen( fname, \"wt\" );\n\n ionBase *pka;\n\n \/\/ map concentration along length\n int *lbins[2];\n int lx = 100; \/\/ 100 bins\n int dl = length\/double(lx);\n lbins[1] = new int[lx]; \/\/ P z=15\n for( int i = 0; i < 2; ++i )\n {\n lbins[i] = new int[lx]; \/\/ 0=B (z=5), 1=P (z=15)\n for( int l = 0; l < lx; ++l )\n lbins[i][l] = 0;\n }\n\n \/\/ xyz data\n int xyz_lines = 0;\n stringstream xyz_data;\n\n for( int s = 0; s < nstep; ++s )\n {\n for( int n = 0; n < ion_count[s]; ++n )\n {\n if( n % 10000 == 0 ) \n cerr << \"pka #\" << n+1 << endl;\n\n \/\/ generate new PKA from prototype ion\n pka = new ionBase( ion_prototype[s] );\n pka->gen = 0; \/\/ generation (0 = PKA)\n pka->tag = -1;\n pka->md = 0;\n\n pka->dir[0] = 0.0;\n pka->dir[1] = sin( theta );\n pka->dir[2] = cos( theta );\n\n v_norm( pka->dir );\n\n if( burried )\n {\n \/\/ cannot anticipate the straggling in the burrial layer, thus have to shoot onto a big surface\n \/\/ TODO: take theta into account!\n pka->pos[0] = dr250() * ( 2.0*length + sample->w[0] ) - ( length + 0.5 * sample->w[0] ) ;\n pka->pos[1] = dr250() * ( 2.0*length + sample->w[1] ) - ( length + 0.5 * sample->w[1] ) ;\n pka->pos[2] = -250.0; \/\/ overcoat thickness\n }\n else\n {\n if( theta == 0.0 )\n {\n \/\/ 0 degrees => start on top of wire!\n pka->pos[2] = 0.0;\n do\n {\n pka->pos[0] = dr250() * sample->w[0];\n pka->pos[1] = dr250() * sample->w[1];\n } while( sample->lookupMaterial(pka->pos ) == 0 );\n }\n else\n {\n \/\/ start on side _or_ top!\n double vpos[3], t;\n do\n {\n do\n {\n vpos[0] = dr250() * sample->w[0];\n vpos[1] = 0.0;\n vpos[2] = ( dr250() * ( length + diameter\/tan(theta) ) ) - diameter\/tan(theta);\n\n t = ( 1.0 - sqrt( 1.0 - sqr( 2*vpos[0]\/diameter - 1.0 ) ) ) * diameter\/(2.0*pka->dir[1]);\n\n \/\/ if we start beyond wire length (that would be inside the substrate) then retry\n } while( t*pka->dir[2] + vpos[2] >= length );\n\n \/\/ if first intersection with cylinder is at z<0 then check if we hit the top face instead\n if( t*pka->dir[2] + vpos[2] < 0.0 )\n t = -vpos[2]\/pka->dir[2];\n\n \/\/ start PKA at calculated intersection point\n for( int i = 0; i < 3; i++ )\n pka->pos[i] = t*pka->dir[i] + vpos[i];\n\n } while( sample->lookupMaterial(pka->pos ) == 0 );\n }\n }\n \/\/cout << \"START \" << pka->pos[0] << ' ' << pka->pos[1] << ' ' << pka->pos[2] << ' ' << endl;\n \/\/continue;\n\n pka->set_ef();\n recoils.push( pka );\n\n while( !recoils.empty() )\n {\n pka = recoils.front();\n recoils.pop();\n sample->averages( pka );\n\n \/\/ do ion analysis\/processing BEFORE the cascade here\n\n if( pka->z1 == ion_prototype[s]->z1 )\n {\n \/\/printf( \"p1 %f\\t%f\\t%f\\n\", pka->pos[0], pka->pos[1], pka->pos[2] );\n }\n\n \/\/ follow this ion's trajectory and store recoils\n trim->trim( pka, recoils );\n\n \/\/ do ion analysis\/processing AFTER the cascade here\n\n \/\/ ion is in the wire\n if( sample->lookupMaterial( pka->pos ) == sample->material[0] )\n {\n xyz_data << simconf->scoef[pka->z1-1].sym << ' ' \n << pka->pos[0]\/100.0 << ' ' << pka->pos[1]\/100.0 << ' ' << pka->pos[2]\/100.0 << endl;\n xyz_lines++;\n\n int l = pka->pos[2] \/ dl;\n if( l >=0 && l < lx ) lbins[ pka->z1 == 5 ? 0 : 1 ][l]++;\n }\n\n \/\/ done with this recoil\n delete pka;\n }\n }\n }\n\n \/\/ write xyz file\n stringstream xyz_name;\n xyz_name << argv[1] << \".xyz\";\n ofstream xyz( xyz_name.str().c_str() );\n xyz << xyz_lines << endl << endl << xyz_data.str();\n xyz.close();\n\n \/\/ write lbins file (atoms per nm wire length)\n stringstream ldat_name;\n ldat_name << argv[1] << \".ldat\";\n ofstream ldat( ldat_name.str().c_str() );\n for( int l = 0; l < lx; ++l )\n ldat << l*dl << ' ' << lbins[0][l]\/(mult*0.1*dl) << ' ' << lbins[1][l]\/(mult*0.1*dl) << endl;\n ldat.close();\n\n delete[] lbins[0];\n delete[] lbins[1];\n\n return EXIT_SUCCESS;\n}\noutput concentration per nm^3\/***************************************************************************\n * Copyright (C) 2008 by Daniel Schwen *\n * daniel@schwen.de *\n * *\n * This program is free software; you can redistribute it and\/or modify *\n * it under the terms of the GNU General Public License as published by *\n * the Free Software Foundation; either version 2 of the License, or *\n * (at your option) any later version. *\n * *\n * This program is distributed in the hope that it will be useful, *\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *\n * GNU General Public License for more details. *\n * *\n * You should have received a copy of the GNU General Public License *\n * along with this program; if not, write to the *\n * Free Software Foundation, Inc., *\n * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *\n ***************************************************************************\/\n\n\n#ifdef HAVE_CONFIG_H\n#include \n#endif\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"simconf.h\"\n#include \"element.h\"\n#include \"material.h\"\n#include \"sample_wire.h\"\n#include \"sample_burried_wire.h\"\n#include \"ion.h\"\n#include \"trim.h\"\n#include \"invert.h\"\n#include \n\n#include \"functions.h\"\n\nusing namespace std;\n\nint main(int argc, char *argv[])\n{\n char fname[200];\n if( argc != 6 ) \n {\n cerr << \"syntax: \" << argv[0] << \" basename angle[deg] diameter(nm) burried[0,1] numbermultiplier\" << endl;\n return 1;\n }\n\n double theta = atof(argv[2]) * M_PI\/180.0; \/\/ 0 = parallel to wire\n double diameter = 10.0*atof(argv[3]);\n double length = 11000.0; \/\/ 1.1 mu\n bool burried = ( atoi(argv[4]) != 0 );\n double mult = atof(argv[5]);\n\n \/\/ ion series\n const int nstep = 5;\n double ion_dose[nstep] = { 3.0e13, 2.2e13, 1.5e13, 1.2e13, 2.5e13 }; \/\/ in ions\/cm^2\n int ion_count[nstep];\n ionBase* ion_prototype[nstep];\n ion_prototype[0] = new ionBase( 5, 11.0 , 320.0e3 ); \/\/ Z,m,E\n ion_prototype[1] = new ionBase( 5, 11.0 , 220.0e3 ); \/\/ Z,m,E\n ion_prototype[2] = new ionBase( 5, 11.0 , 160.0e3 ); \/\/ Z,m,E\n ion_prototype[3] = new ionBase( 5, 11.0 , 120.0e3 ); \/\/ Z,m,E\n ion_prototype[4] = new ionBase( 15, 31.0 , 250.0e3 ); \/\/ Z,m,E\n\n \/\/ seed randomnumber generator from system entropy pool\n FILE *urand = fopen( \"\/dev\/random\", \"r\" );\n int seed;\n fread( &seed, sizeof(int), 1, urand );\n fclose( urand );\n r250_init( seed<0 ? -seed : seed ); \/\/ random generator goes haywire with neg. seed\n\n \/\/ initialize global parameter structure and read data tables from file\n simconf = new simconfType;\n\n \/\/ initialize sample structure\n sampleWire *sample;\n if( burried )\n sample = new sampleBurriedWire( diameter, diameter, length );\n else\n {\n sample = new sampleWire( diameter, diameter, length );\n sample->bc[2] = sampleWire::CUT;\n }\n\n \/\/ calculate actual ion numbers\n for( int s = 0; s < nstep; ++s )\n {\n double A; \/\/ irradiated area in Ang^2\n if( burried )\n A =( 2.0*length + sample->w[0] ) * ( 2.0*length + sample->w[1] );\n else\n A = cos(theta) * M_PI * 0.25 * sample->w[0] * sample->w[1] + \/\/ slanted top face\n sin(theta) * length * sample->w[0]; \/\/ + projected side\n\n \/\/ 1cm^2 = 1e16 Ang**2, 1Ang^2 = 1e-16cm^2\n ion_count[s] = ion_dose[s] * A * 1.0e-16 * mult;\n cerr << \"Ion \" << s << ' ' << ion_count[s] << endl;\n }\n\n \/\/ initialize trim engine for the sample\n\/* const int z1 = 31;\n const int z2 = 33;\n trimVacMap *trim = new trimVacMap( sample, z1, z2 ); \/\/ GaAs*\/\n \/\/trimBase *trim = new trimBase( sample );\n trimBase *trim = new trimPrimaries( sample );\n\n materialBase *material;\n elementBase *element;\n\n \/\/ Si\n material = new materialBase( 2.329 ); \/\/ rho\n element = new elementBase;\n element->z = 14; \/\/ Si\n element->m = 28.0;\n element->t = 1.0;\n material->element.push_back( element );\n material->prepare(); \/\/ all materials added\n sample->material.push_back( material ); \/\/ add material to sample\n\n \/\/ SiO2 (material[1] for the cover layer in SampleBurriedWire)\n material = new materialBase( 2.634 ); \/\/ rho\n element = new elementBase;\n element->z = 14; \/\/ Si\n element->m = 28.0;\n element->t = 1.0;\n material->element.push_back( element );\n element = new elementBase;\n element->z = 8; \/\/ O\n element->m = 16.0;\n element->t = 2.0;\n material->element.push_back( element );\n material->prepare(); \/\/ all materials added\n sample->material.push_back( material ); \/\/ add material to sample\n\n \/\/ create a FIFO for recoils\n queue recoils;\n\n double norm;\n double jmp = 2.7; \/\/ diffusion jump distance\n int jumps;\n double dif[3];\n\n \/\/snprintf( fname, 199, \"%s.Erec\", argv[1] );\n \/\/FILE *erec = fopen( fname, \"wt\" );\n\n \/\/snprintf( fname, 199, \"%s.dist\", argv[1] );\n \/\/FILE *rdist = fopen( fname, \"wt\" );\n\n ionBase *pka;\n\n \/\/ map concentration along length\n int *lbins[2];\n int lx = 100; \/\/ 100 bins\n int dl = length\/double(lx);\n lbins[1] = new int[lx]; \/\/ P z=15\n for( int i = 0; i < 2; ++i )\n {\n lbins[i] = new int[lx]; \/\/ 0=B (z=5), 1=P (z=15)\n for( int l = 0; l < lx; ++l )\n lbins[i][l] = 0;\n }\n\n \/\/ xyz data\n int xyz_lines = 0;\n stringstream xyz_data;\n\n for( int s = 0; s < nstep; ++s )\n {\n for( int n = 0; n < ion_count[s]; ++n )\n {\n if( n % 10000 == 0 ) \n cerr << \"pka #\" << n+1 << endl;\n\n \/\/ generate new PKA from prototype ion\n pka = new ionBase( ion_prototype[s] );\n pka->gen = 0; \/\/ generation (0 = PKA)\n pka->tag = -1;\n pka->md = 0;\n\n pka->dir[0] = 0.0;\n pka->dir[1] = sin( theta );\n pka->dir[2] = cos( theta );\n\n v_norm( pka->dir );\n\n if( burried )\n {\n \/\/ cannot anticipate the straggling in the burrial layer, thus have to shoot onto a big surface\n \/\/ TODO: take theta into account!\n pka->pos[0] = dr250() * ( 2.0*length + sample->w[0] ) - ( length + 0.5 * sample->w[0] ) ;\n pka->pos[1] = dr250() * ( 2.0*length + sample->w[1] ) - ( length + 0.5 * sample->w[1] ) ;\n pka->pos[2] = -250.0; \/\/ overcoat thickness\n }\n else\n {\n if( theta == 0.0 )\n {\n \/\/ 0 degrees => start on top of wire!\n pka->pos[2] = 0.0;\n do\n {\n pka->pos[0] = dr250() * sample->w[0];\n pka->pos[1] = dr250() * sample->w[1];\n } while( sample->lookupMaterial(pka->pos ) == 0 );\n }\n else\n {\n \/\/ start on side _or_ top!\n double vpos[3], t;\n do\n {\n do\n {\n vpos[0] = dr250() * sample->w[0];\n vpos[1] = 0.0;\n vpos[2] = ( dr250() * ( length + diameter\/tan(theta) ) ) - diameter\/tan(theta);\n\n t = ( 1.0 - sqrt( 1.0 - sqr( 2*vpos[0]\/diameter - 1.0 ) ) ) * diameter\/(2.0*pka->dir[1]);\n\n \/\/ if we start beyond wire length (that would be inside the substrate) then retry\n } while( t*pka->dir[2] + vpos[2] >= length );\n\n \/\/ if first intersection with cylinder is at z<0 then check if we hit the top face instead\n if( t*pka->dir[2] + vpos[2] < 0.0 )\n t = -vpos[2]\/pka->dir[2];\n\n \/\/ start PKA at calculated intersection point\n for( int i = 0; i < 3; i++ )\n pka->pos[i] = t*pka->dir[i] + vpos[i];\n\n } while( sample->lookupMaterial(pka->pos ) == 0 );\n }\n }\n \/\/cout << \"START \" << pka->pos[0] << ' ' << pka->pos[1] << ' ' << pka->pos[2] << ' ' << endl;\n \/\/continue;\n\n pka->set_ef();\n recoils.push( pka );\n\n while( !recoils.empty() )\n {\n pka = recoils.front();\n recoils.pop();\n sample->averages( pka );\n\n \/\/ do ion analysis\/processing BEFORE the cascade here\n\n if( pka->z1 == ion_prototype[s]->z1 )\n {\n \/\/printf( \"p1 %f\\t%f\\t%f\\n\", pka->pos[0], pka->pos[1], pka->pos[2] );\n }\n\n \/\/ follow this ion's trajectory and store recoils\n trim->trim( pka, recoils );\n\n \/\/ do ion analysis\/processing AFTER the cascade here\n\n \/\/ ion is in the wire\n if( sample->lookupMaterial( pka->pos ) == sample->material[0] )\n {\n xyz_data << simconf->scoef[pka->z1-1].sym << ' ' \n << pka->pos[0]\/100.0 << ' ' << pka->pos[1]\/100.0 << ' ' << pka->pos[2]\/100.0 << endl;\n xyz_lines++;\n\n int l = pka->pos[2] \/ dl;\n if( l >=0 && l < lx ) lbins[ pka->z1 == 5 ? 0 : 1 ][l]++;\n }\n\n \/\/ done with this recoil\n delete pka;\n }\n }\n }\n\n \/\/ write xyz file\n stringstream xyz_name;\n xyz_name << argv[1] << \".xyz\";\n ofstream xyz( xyz_name.str().c_str() );\n xyz << xyz_lines << endl << endl << xyz_data.str();\n xyz.close();\n\n \/\/ write lbins file (atoms per nm^3)\n stringstream ldat_name;\n ldat_name << argv[1] << \".ldat\";\n ofstream ldat( ldat_name.str().c_str() );\n double dv = 1e-3 * dl * M_PI * 0.25 *sample->w[0] * sample->w[1]; \/\/ volume per bin in nm^3\n for( int l = 0; l < lx; ++l )\n ldat << l*dl << ' ' << lbins[0][l]\/(mult*dv) << ' ' << lbins[1][l]\/(mult*dv) << endl;\n ldat.close();\n\n delete[] lbins[0];\n delete[] lbins[1];\n\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"\/***************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2008-2009 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Qt Software Information (qt-info@nokia.com)\n**\n**\n** Non-Open Source Usage\n**\n** Licensees may use this file in accordance with the Qt Beta Version\n** License Agreement, Agreement version 2.2 provided with the Software or,\n** alternatively, in accordance with the terms contained in a written\n** agreement between you and Nokia.\n**\n** GNU General Public License Usage\n**\n** Alternatively, this file may be used under the terms of the GNU General\n** Public License versions 2.0 or 3.0 as published by the Free Software\n** Foundation and appearing in the file LICENSE.GPL included in the packaging\n** of this file. Please review the following information to ensure GNU\n** General Public Licensing requirements will be met:\n**\n** http:\/\/www.fsf.org\/licensing\/licenses\/info\/GPLv2.html and\n** http:\/\/www.gnu.org\/copyleft\/gpl.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt GPL Exception\n** version 1.3, included in the file GPL_EXCEPTION.txt in this package.\n**\n***************************************************************************\/\n\n#include \"LookupContext.h\"\n#include \"ResolveExpression.h\"\n#include \"Overview.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\nusing namespace CPlusPlus;\n\nbool LookupContext::isNameCompatibleWithIdentifier(Name *name, Identifier *id)\n{\n if (! name) {\n return false;\n } else if (NameId *nameId = name->asNameId()) {\n Identifier *identifier = nameId->identifier();\n return identifier->isEqualTo(id);\n } else if (DestructorNameId *nameId = name->asDestructorNameId()) {\n Identifier *identifier = nameId->identifier();\n return identifier->isEqualTo(id);\n } else if (TemplateNameId *templNameId = name->asTemplateNameId()) {\n Identifier *identifier = templNameId->identifier();\n return identifier->isEqualTo(id);\n }\n\n return false;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ LookupContext\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nLookupContext::LookupContext(Control *control)\n : _control(control),\n _symbol(0)\n{ }\n\nLookupContext::LookupContext(Symbol *symbol,\n Document::Ptr expressionDocument,\n Document::Ptr thisDocument,\n const Snapshot &documents)\n : _symbol(symbol),\n _expressionDocument(expressionDocument),\n _thisDocument(thisDocument),\n _documents(documents)\n{\n _control = _expressionDocument->control();\n _visibleScopes = buildVisibleScopes();\n}\n\nLookupContext::LookupContext(Symbol *symbol,\n const LookupContext &context)\n : _control(context._control),\n _symbol(symbol),\n _expressionDocument(context._expressionDocument),\n _documents(context._documents)\n{\n const QString fn = QString::fromUtf8(symbol->fileName(), symbol->fileNameLength());\n _thisDocument = _documents.value(fn);\n _visibleScopes = buildVisibleScopes();\n}\n\nLookupContext::LookupContext(Symbol *symbol,\n Document::Ptr thisDocument,\n const LookupContext &context)\n : _control(context._control),\n _symbol(symbol),\n _expressionDocument(context._expressionDocument),\n _thisDocument(thisDocument),\n _documents(context._documents)\n{\n _visibleScopes = buildVisibleScopes();\n}\n\nbool LookupContext::isValid() const\n{ return _control != 0; }\n\nLookupContext::operator bool() const\n{ return _control != 0; }\n\nControl *LookupContext::control() const\n{ return _control; }\n\nSymbol *LookupContext::symbol() const\n{ return _symbol; }\n\nDocument::Ptr LookupContext::expressionDocument() const\n{ return _expressionDocument; }\n\nDocument::Ptr LookupContext::thisDocument() const\n{ return _thisDocument; }\n\nDocument::Ptr LookupContext::document(const QString &fileName) const\n{ return _documents.value(fileName); }\n\nIdentifier *LookupContext::identifier(Name *name) const\n{\n if (NameId *nameId = name->asNameId())\n return nameId->identifier();\n else if (TemplateNameId *templId = name->asTemplateNameId())\n return templId->identifier();\n else if (DestructorNameId *dtorId = name->asDestructorNameId())\n return dtorId->identifier();\n else if (QualifiedNameId *q = name->asQualifiedNameId())\n return identifier(q->unqualifiedNameId());\n return 0;\n}\n\nbool LookupContext::maybeValidSymbol(Symbol *symbol,\n ResolveMode mode,\n const QList &candidates)\n{\n if (((mode & ResolveNamespace) && symbol->isNamespace()) ||\n ((mode & ResolveClass) && symbol->isClass()) ||\n (mode & ResolveSymbol)) {\n return ! candidates.contains(symbol);\n }\n\n return false;\n}\n\nQList LookupContext::resolve(Name *name, const QList &visibleScopes,\n ResolveMode mode) const\n{\n if (QualifiedNameId *q = name->asQualifiedNameId()) {\n QList candidates;\n QList scopes = visibleScopes;\n for (unsigned i = 0; i < q->nameCount(); ++i) {\n Name *name = q->nameAt(i);\n\n if (i + 1 == q->nameCount())\n candidates = resolve(name, scopes, mode);\n else\n candidates = resolveClassOrNamespace(name, scopes);\n\n if (candidates.isEmpty() || i + 1 == q->nameCount())\n break;\n\n scopes.clear();\n foreach (Symbol *candidate, candidates) {\n if (ScopedSymbol *scoped = candidate->asScopedSymbol()) {\n expand(scoped->members(), visibleScopes, &scopes);\n }\n }\n }\n\n Identifier *id = identifier(name);\n foreach (Scope *scope, visibleScopes) {\n Symbol *symbol = scope->lookat(id);\n for (; symbol; symbol = symbol->next()) {\n if (! symbol->name())\n continue;\n else if (! maybeValidSymbol(symbol, mode, candidates))\n continue;\n QualifiedNameId *qq = symbol->name()->asQualifiedNameId();\n if (! qq)\n continue;\n if (q->nameCount() > qq->nameCount())\n continue;\n\n for (int i = q->nameCount() - 1; i != -1; --i) {\n Name *a = q->nameAt(i);\n Name *b = qq->nameAt(i);\n\n if (! a->isEqualTo(b))\n break;\n else if (i == 0)\n candidates.append(symbol);\n }\n }\n }\n\n return candidates;\n }\n\n QList candidates;\n if (Identifier *id = identifier(name)) {\n for (int scopeIndex = 0; scopeIndex < visibleScopes.size(); ++scopeIndex) {\n Scope *scope = visibleScopes.at(scopeIndex);\n for (Symbol *symbol = scope->lookat(id); symbol; symbol = symbol->next()) {\n if (! symbol->name()) {\n continue;\n } else if (! maybeValidSymbol(symbol, mode, candidates)) {\n continue;\n } else if (QualifiedNameId *q = symbol->name()->asQualifiedNameId()) {\n if (! q->unqualifiedNameId()->isEqualTo(name))\n continue;\n\n if (q->nameCount() > 1) {\n Name *classOrNamespaceName =\n control()->qualifiedNameId(q->names(),\n q->nameCount() - 1);\n\n const QList resolvedClassOrNamespace =\n resolveClassOrNamespace(classOrNamespaceName, visibleScopes);\n\n bool good = false;\n foreach (Symbol *classOrNamespace, resolvedClassOrNamespace) {\n ScopedSymbol *scoped = classOrNamespace->asScopedSymbol();\n if (visibleScopes.contains(scoped->members())) {\n good = true;\n break;\n }\n }\n\n if (! good)\n continue;\n }\n } else if (! isNameCompatibleWithIdentifier(symbol->name(), id)) {\n continue;\n } else if (symbol->name()->isDestructorNameId() != name->isDestructorNameId()) {\n continue;\n }\n\n candidates.append(symbol);\n }\n }\n } else if (OperatorNameId *opId = name->asOperatorNameId()) {\n for (int scopeIndex = 0; scopeIndex < visibleScopes.size(); ++scopeIndex) {\n Scope *scope = visibleScopes.at(scopeIndex);\n for (Symbol *symbol = scope->lookat(opId->kind()); symbol; symbol = symbol->next()) {\n if (! opId->isEqualTo(symbol->name()))\n continue;\n else if (! candidates.contains(symbol))\n candidates.append(symbol);\n }\n }\n }\n\n return candidates;\n}\n\nQList LookupContext::buildVisibleScopes()\n{\n QList scopes;\n\n if (_symbol) {\n for (Scope *scope = _symbol->scope(); scope; scope = scope->enclosingScope()) {\n scopes.append(scope);\n }\n }\n\n QSet processed;\n processed.insert(_thisDocument->fileName());\n\n QList todo = _thisDocument->includedFiles();\n while (! todo.isEmpty()) {\n QString fn = todo.last();\n todo.removeLast();\n\n if (processed.contains(fn))\n continue;\n\n processed.insert(fn);\n if (Document::Ptr doc = document(fn)) {\n scopes.append(doc->globalNamespace()->members());\n todo += doc->includedFiles();\n }\n }\n\n while (true) {\n QList expandedScopes;\n expand(scopes, &expandedScopes);\n\n if (expandedScopes.size() == scopes.size())\n return expandedScopes;\n\n scopes = expandedScopes;\n }\n\n return scopes;\n}\n\nQList LookupContext::visibleScopes(const QPair &result) const\n{\n Symbol *symbol = result.second;\n QList scopes;\n for (Scope *scope = symbol->scope(); scope; scope = scope->enclosingScope())\n scopes.append(scope);\n scopes += visibleScopes();\n scopes = expand(scopes);\n return scopes;\n}\n\nQList LookupContext::expand(const QList &scopes) const\n{\n QList expanded;\n expand(scopes, &expanded);\n return expanded;\n}\n\nvoid LookupContext::expand(const QList &scopes, QList *expandedScopes) const\n{\n for (int i = 0; i < scopes.size(); ++i) {\n expand(scopes.at(i), scopes, expandedScopes);\n }\n}\n\nvoid LookupContext::expandNamespace(Scope *scope,\n const QList &visibleScopes,\n QList *expandedScopes) const\n{\n Namespace *ns = scope->owner()->asNamespace();\n if (! ns)\n return;\n\n if (Name *nsName = ns->name()) {\n const QList namespaceList = resolveNamespace(nsName, visibleScopes);\n foreach (Symbol *otherNs, namespaceList) {\n if (otherNs == ns)\n continue;\n expand(otherNs->asNamespace()->members(), visibleScopes, expandedScopes);\n }\n }\n\n for (unsigned i = 0; i < scope->symbolCount(); ++i) { \/\/ ### make me fast\n Symbol *symbol = scope->symbolAt(i);\n if (Namespace *ns = symbol->asNamespace()) {\n if (! ns->name()) {\n expand(ns->members(), visibleScopes, expandedScopes);\n }\n } else if (UsingNamespaceDirective *u = symbol->asUsingNamespaceDirective()) {\n const QList candidates = resolveNamespace(u->name(), visibleScopes);\n for (int j = 0; j < candidates.size(); ++j) {\n expand(candidates.at(j)->asNamespace()->members(),\n visibleScopes, expandedScopes);\n }\n } else if (Enum *e = symbol->asEnum()) {\n expand(e->members(), visibleScopes, expandedScopes);\n }\n }\n}\n\nvoid LookupContext::expandClass(Scope *scope,\n const QList &visibleScopes,\n QList *expandedScopes) const\n{\n Class *klass = scope->owner()->asClass();\n if (! klass)\n return;\n\n for (unsigned i = 0; i < scope->symbolCount(); ++i) {\n Symbol *symbol = scope->symbolAt(i);\n if (Class *nestedClass = symbol->asClass()) {\n if (! nestedClass->name()) {\n expand(nestedClass->members(), visibleScopes, expandedScopes);\n }\n } else if (Enum *e = symbol->asEnum()) {\n expand(e->members(), visibleScopes, expandedScopes);\n }\n }\n\n if (klass->baseClassCount()) {\n QList classVisibleScopes = visibleScopes;\n for (Scope *scope = klass->scope(); scope; scope = scope->enclosingScope()) {\n if (scope->isNamespaceScope()) {\n Namespace *enclosingNamespace = scope->owner()->asNamespace();\n if (enclosingNamespace->name()) {\n const QList nsList = resolveNamespace(enclosingNamespace->name(),\n visibleScopes);\n foreach (Symbol *ns, nsList) {\n expand(ns->asNamespace()->members(), classVisibleScopes,\n &classVisibleScopes);\n }\n }\n }\n }\n\n for (unsigned i = 0; i < klass->baseClassCount(); ++i) {\n BaseClass *baseClass = klass->baseClassAt(i);\n Name *baseClassName = baseClass->name();\n const QList baseClassCandidates = resolveClass(baseClassName,\n classVisibleScopes);\n if (baseClassCandidates.isEmpty()) {\n Overview overview;\n qDebug() << \"unresolved base class:\" << overview.prettyName(baseClassName);\n }\n\n for (int j = 0; j < baseClassCandidates.size(); ++j) {\n if (Class *baseClassSymbol = baseClassCandidates.at(j)->asClass())\n expand(baseClassSymbol->members(), visibleScopes, expandedScopes);\n }\n }\n }\n}\n\nvoid LookupContext::expandBlock(Scope *scope,\n const QList &visibleScopes,\n QList *expandedScopes) const\n{\n for (unsigned i = 0; i < scope->symbolCount(); ++i) {\n Symbol *symbol = scope->symbolAt(i);\n if (UsingNamespaceDirective *u = symbol->asUsingNamespaceDirective()) {\n const QList candidates = resolveNamespace(u->name(),\n visibleScopes);\n for (int j = 0; j < candidates.size(); ++j) {\n expand(candidates.at(j)->asNamespace()->members(),\n visibleScopes, expandedScopes);\n }\n }\n\n }\n}\n\nvoid LookupContext::expandFunction(Scope *scope,\n const QList &visibleScopes,\n QList *expandedScopes) const\n{\n Function *function = scope->owner()->asFunction();\n if (! expandedScopes->contains(function->arguments()))\n expandedScopes->append(function->arguments());\n if (QualifiedNameId *q = function->name()->asQualifiedNameId()) {\n Name *nestedNameSpec = 0;\n if (q->nameCount() == 1 && q->isGlobal())\n nestedNameSpec = q->nameAt(0);\n else\n nestedNameSpec = control()->qualifiedNameId(q->names(), q->nameCount() - 1,\n q->isGlobal());\n const QList candidates = resolveClassOrNamespace(nestedNameSpec, visibleScopes);\n for (int j = 0; j < candidates.size(); ++j) {\n expand(candidates.at(j)->asScopedSymbol()->members(),\n visibleScopes, expandedScopes);\n }\n }\n}\n\nvoid LookupContext::expand(Scope *scope,\n const QList &visibleScopes,\n QList *expandedScopes) const\n{\n if (expandedScopes->contains(scope))\n return;\n\n expandedScopes->append(scope);\n\n if (scope->isNamespaceScope()) {\n expandNamespace(scope, visibleScopes, expandedScopes);\n } else if (scope->isClassScope()) {\n expandClass(scope, visibleScopes, expandedScopes);\n } else if (scope->isBlockScope()) {\n expandBlock(scope, visibleScopes, expandedScopes);\n } else if (scope->isFunctionScope()) {\n expandFunction(scope, visibleScopes, expandedScopes);\n } else if (scope->isPrototypeScope()) {\n \/\/qDebug() << \"prototype scope\" << overview.prettyName(scope->owner()->name());\n }\n}\nFixed crash in lookup context due to null-name\/***************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2008-2009 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Qt Software Information (qt-info@nokia.com)\n**\n**\n** Non-Open Source Usage\n**\n** Licensees may use this file in accordance with the Qt Beta Version\n** License Agreement, Agreement version 2.2 provided with the Software or,\n** alternatively, in accordance with the terms contained in a written\n** agreement between you and Nokia.\n**\n** GNU General Public License Usage\n**\n** Alternatively, this file may be used under the terms of the GNU General\n** Public License versions 2.0 or 3.0 as published by the Free Software\n** Foundation and appearing in the file LICENSE.GPL included in the packaging\n** of this file. Please review the following information to ensure GNU\n** General Public Licensing requirements will be met:\n**\n** http:\/\/www.fsf.org\/licensing\/licenses\/info\/GPLv2.html and\n** http:\/\/www.gnu.org\/copyleft\/gpl.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt GPL Exception\n** version 1.3, included in the file GPL_EXCEPTION.txt in this package.\n**\n***************************************************************************\/\n\n#include \"LookupContext.h\"\n#include \"ResolveExpression.h\"\n#include \"Overview.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\nusing namespace CPlusPlus;\n\nbool LookupContext::isNameCompatibleWithIdentifier(Name *name, Identifier *id)\n{\n if (! name) {\n return false;\n } else if (NameId *nameId = name->asNameId()) {\n Identifier *identifier = nameId->identifier();\n return identifier->isEqualTo(id);\n } else if (DestructorNameId *nameId = name->asDestructorNameId()) {\n Identifier *identifier = nameId->identifier();\n return identifier->isEqualTo(id);\n } else if (TemplateNameId *templNameId = name->asTemplateNameId()) {\n Identifier *identifier = templNameId->identifier();\n return identifier->isEqualTo(id);\n }\n\n return false;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ LookupContext\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nLookupContext::LookupContext(Control *control)\n : _control(control),\n _symbol(0)\n{ }\n\nLookupContext::LookupContext(Symbol *symbol,\n Document::Ptr expressionDocument,\n Document::Ptr thisDocument,\n const Snapshot &documents)\n : _symbol(symbol),\n _expressionDocument(expressionDocument),\n _thisDocument(thisDocument),\n _documents(documents)\n{\n _control = _expressionDocument->control();\n _visibleScopes = buildVisibleScopes();\n}\n\nLookupContext::LookupContext(Symbol *symbol,\n const LookupContext &context)\n : _control(context._control),\n _symbol(symbol),\n _expressionDocument(context._expressionDocument),\n _documents(context._documents)\n{\n const QString fn = QString::fromUtf8(symbol->fileName(), symbol->fileNameLength());\n _thisDocument = _documents.value(fn);\n _visibleScopes = buildVisibleScopes();\n}\n\nLookupContext::LookupContext(Symbol *symbol,\n Document::Ptr thisDocument,\n const LookupContext &context)\n : _control(context._control),\n _symbol(symbol),\n _expressionDocument(context._expressionDocument),\n _thisDocument(thisDocument),\n _documents(context._documents)\n{\n _visibleScopes = buildVisibleScopes();\n}\n\nbool LookupContext::isValid() const\n{ return _control != 0; }\n\nLookupContext::operator bool() const\n{ return _control != 0; }\n\nControl *LookupContext::control() const\n{ return _control; }\n\nSymbol *LookupContext::symbol() const\n{ return _symbol; }\n\nDocument::Ptr LookupContext::expressionDocument() const\n{ return _expressionDocument; }\n\nDocument::Ptr LookupContext::thisDocument() const\n{ return _thisDocument; }\n\nDocument::Ptr LookupContext::document(const QString &fileName) const\n{ return _documents.value(fileName); }\n\nIdentifier *LookupContext::identifier(Name *name) const\n{\n if (NameId *nameId = name->asNameId())\n return nameId->identifier();\n else if (TemplateNameId *templId = name->asTemplateNameId())\n return templId->identifier();\n else if (DestructorNameId *dtorId = name->asDestructorNameId())\n return dtorId->identifier();\n else if (QualifiedNameId *q = name->asQualifiedNameId())\n return identifier(q->unqualifiedNameId());\n return 0;\n}\n\nbool LookupContext::maybeValidSymbol(Symbol *symbol,\n ResolveMode mode,\n const QList &candidates)\n{\n if (((mode & ResolveNamespace) && symbol->isNamespace()) ||\n ((mode & ResolveClass) && symbol->isClass()) ||\n (mode & ResolveSymbol)) {\n return ! candidates.contains(symbol);\n }\n\n return false;\n}\n\nQList LookupContext::resolve(Name *name, const QList &visibleScopes,\n ResolveMode mode) const\n{\n QList candidates;\n\n if (!name)\n return candidates;\n\n if (QualifiedNameId *q = name->asQualifiedNameId()) {\n QList scopes = visibleScopes;\n for (unsigned i = 0; i < q->nameCount(); ++i) {\n Name *name = q->nameAt(i);\n\n if (i + 1 == q->nameCount())\n candidates = resolve(name, scopes, mode);\n else\n candidates = resolveClassOrNamespace(name, scopes);\n\n if (candidates.isEmpty() || i + 1 == q->nameCount())\n break;\n\n scopes.clear();\n foreach (Symbol *candidate, candidates) {\n if (ScopedSymbol *scoped = candidate->asScopedSymbol()) {\n expand(scoped->members(), visibleScopes, &scopes);\n }\n }\n }\n\n Identifier *id = identifier(name);\n foreach (Scope *scope, visibleScopes) {\n Symbol *symbol = scope->lookat(id);\n for (; symbol; symbol = symbol->next()) {\n if (! symbol->name())\n continue;\n else if (! maybeValidSymbol(symbol, mode, candidates))\n continue;\n QualifiedNameId *qq = symbol->name()->asQualifiedNameId();\n if (! qq)\n continue;\n if (q->nameCount() > qq->nameCount())\n continue;\n\n for (int i = q->nameCount() - 1; i != -1; --i) {\n Name *a = q->nameAt(i);\n Name *b = qq->nameAt(i);\n\n if (! a->isEqualTo(b))\n break;\n else if (i == 0)\n candidates.append(symbol);\n }\n }\n }\n\n return candidates;\n }\n\n if (Identifier *id = identifier(name)) {\n for (int scopeIndex = 0; scopeIndex < visibleScopes.size(); ++scopeIndex) {\n Scope *scope = visibleScopes.at(scopeIndex);\n for (Symbol *symbol = scope->lookat(id); symbol; symbol = symbol->next()) {\n if (! symbol->name()) {\n continue;\n } else if (! maybeValidSymbol(symbol, mode, candidates)) {\n continue;\n } else if (QualifiedNameId *q = symbol->name()->asQualifiedNameId()) {\n if (! q->unqualifiedNameId()->isEqualTo(name))\n continue;\n\n if (q->nameCount() > 1) {\n Name *classOrNamespaceName =\n control()->qualifiedNameId(q->names(),\n q->nameCount() - 1);\n\n const QList resolvedClassOrNamespace =\n resolveClassOrNamespace(classOrNamespaceName, visibleScopes);\n\n bool good = false;\n foreach (Symbol *classOrNamespace, resolvedClassOrNamespace) {\n ScopedSymbol *scoped = classOrNamespace->asScopedSymbol();\n if (visibleScopes.contains(scoped->members())) {\n good = true;\n break;\n }\n }\n\n if (! good)\n continue;\n }\n } else if (! isNameCompatibleWithIdentifier(symbol->name(), id)) {\n continue;\n } else if (symbol->name()->isDestructorNameId() != name->isDestructorNameId()) {\n continue;\n }\n\n candidates.append(symbol);\n }\n }\n } else if (OperatorNameId *opId = name->asOperatorNameId()) {\n for (int scopeIndex = 0; scopeIndex < visibleScopes.size(); ++scopeIndex) {\n Scope *scope = visibleScopes.at(scopeIndex);\n for (Symbol *symbol = scope->lookat(opId->kind()); symbol; symbol = symbol->next()) {\n if (! opId->isEqualTo(symbol->name()))\n continue;\n else if (! candidates.contains(symbol))\n candidates.append(symbol);\n }\n }\n }\n\n return candidates;\n}\n\nQList LookupContext::buildVisibleScopes()\n{\n QList scopes;\n\n if (_symbol) {\n for (Scope *scope = _symbol->scope(); scope; scope = scope->enclosingScope()) {\n scopes.append(scope);\n }\n }\n\n QSet processed;\n processed.insert(_thisDocument->fileName());\n\n QList todo = _thisDocument->includedFiles();\n while (! todo.isEmpty()) {\n QString fn = todo.last();\n todo.removeLast();\n\n if (processed.contains(fn))\n continue;\n\n processed.insert(fn);\n if (Document::Ptr doc = document(fn)) {\n scopes.append(doc->globalNamespace()->members());\n todo += doc->includedFiles();\n }\n }\n\n while (true) {\n QList expandedScopes;\n expand(scopes, &expandedScopes);\n\n if (expandedScopes.size() == scopes.size())\n return expandedScopes;\n\n scopes = expandedScopes;\n }\n\n return scopes;\n}\n\nQList LookupContext::visibleScopes(const QPair &result) const\n{\n Symbol *symbol = result.second;\n QList scopes;\n for (Scope *scope = symbol->scope(); scope; scope = scope->enclosingScope())\n scopes.append(scope);\n scopes += visibleScopes();\n scopes = expand(scopes);\n return scopes;\n}\n\nQList LookupContext::expand(const QList &scopes) const\n{\n QList expanded;\n expand(scopes, &expanded);\n return expanded;\n}\n\nvoid LookupContext::expand(const QList &scopes, QList *expandedScopes) const\n{\n for (int i = 0; i < scopes.size(); ++i) {\n expand(scopes.at(i), scopes, expandedScopes);\n }\n}\n\nvoid LookupContext::expandNamespace(Scope *scope,\n const QList &visibleScopes,\n QList *expandedScopes) const\n{\n Namespace *ns = scope->owner()->asNamespace();\n if (! ns)\n return;\n\n if (Name *nsName = ns->name()) {\n const QList namespaceList = resolveNamespace(nsName, visibleScopes);\n foreach (Symbol *otherNs, namespaceList) {\n if (otherNs == ns)\n continue;\n expand(otherNs->asNamespace()->members(), visibleScopes, expandedScopes);\n }\n }\n\n for (unsigned i = 0; i < scope->symbolCount(); ++i) { \/\/ ### make me fast\n Symbol *symbol = scope->symbolAt(i);\n if (Namespace *ns = symbol->asNamespace()) {\n if (! ns->name()) {\n expand(ns->members(), visibleScopes, expandedScopes);\n }\n } else if (UsingNamespaceDirective *u = symbol->asUsingNamespaceDirective()) {\n const QList candidates = resolveNamespace(u->name(), visibleScopes);\n for (int j = 0; j < candidates.size(); ++j) {\n expand(candidates.at(j)->asNamespace()->members(),\n visibleScopes, expandedScopes);\n }\n } else if (Enum *e = symbol->asEnum()) {\n expand(e->members(), visibleScopes, expandedScopes);\n }\n }\n}\n\nvoid LookupContext::expandClass(Scope *scope,\n const QList &visibleScopes,\n QList *expandedScopes) const\n{\n Class *klass = scope->owner()->asClass();\n if (! klass)\n return;\n\n for (unsigned i = 0; i < scope->symbolCount(); ++i) {\n Symbol *symbol = scope->symbolAt(i);\n if (Class *nestedClass = symbol->asClass()) {\n if (! nestedClass->name()) {\n expand(nestedClass->members(), visibleScopes, expandedScopes);\n }\n } else if (Enum *e = symbol->asEnum()) {\n expand(e->members(), visibleScopes, expandedScopes);\n }\n }\n\n if (klass->baseClassCount()) {\n QList classVisibleScopes = visibleScopes;\n for (Scope *scope = klass->scope(); scope; scope = scope->enclosingScope()) {\n if (scope->isNamespaceScope()) {\n Namespace *enclosingNamespace = scope->owner()->asNamespace();\n if (enclosingNamespace->name()) {\n const QList nsList = resolveNamespace(enclosingNamespace->name(),\n visibleScopes);\n foreach (Symbol *ns, nsList) {\n expand(ns->asNamespace()->members(), classVisibleScopes,\n &classVisibleScopes);\n }\n }\n }\n }\n\n for (unsigned i = 0; i < klass->baseClassCount(); ++i) {\n BaseClass *baseClass = klass->baseClassAt(i);\n Name *baseClassName = baseClass->name();\n const QList baseClassCandidates = resolveClass(baseClassName,\n classVisibleScopes);\n if (baseClassCandidates.isEmpty()) {\n Overview overview;\n qDebug() << \"unresolved base class:\" << overview.prettyName(baseClassName);\n }\n\n for (int j = 0; j < baseClassCandidates.size(); ++j) {\n if (Class *baseClassSymbol = baseClassCandidates.at(j)->asClass())\n expand(baseClassSymbol->members(), visibleScopes, expandedScopes);\n }\n }\n }\n}\n\nvoid LookupContext::expandBlock(Scope *scope,\n const QList &visibleScopes,\n QList *expandedScopes) const\n{\n for (unsigned i = 0; i < scope->symbolCount(); ++i) {\n Symbol *symbol = scope->symbolAt(i);\n if (UsingNamespaceDirective *u = symbol->asUsingNamespaceDirective()) {\n const QList candidates = resolveNamespace(u->name(),\n visibleScopes);\n for (int j = 0; j < candidates.size(); ++j) {\n expand(candidates.at(j)->asNamespace()->members(),\n visibleScopes, expandedScopes);\n }\n }\n\n }\n}\n\nvoid LookupContext::expandFunction(Scope *scope,\n const QList &visibleScopes,\n QList *expandedScopes) const\n{\n Function *function = scope->owner()->asFunction();\n if (! expandedScopes->contains(function->arguments()))\n expandedScopes->append(function->arguments());\n if (QualifiedNameId *q = function->name()->asQualifiedNameId()) {\n Name *nestedNameSpec = 0;\n if (q->nameCount() == 1 && q->isGlobal())\n nestedNameSpec = q->nameAt(0);\n else\n nestedNameSpec = control()->qualifiedNameId(q->names(), q->nameCount() - 1,\n q->isGlobal());\n const QList candidates = resolveClassOrNamespace(nestedNameSpec, visibleScopes);\n for (int j = 0; j < candidates.size(); ++j) {\n expand(candidates.at(j)->asScopedSymbol()->members(),\n visibleScopes, expandedScopes);\n }\n }\n}\n\nvoid LookupContext::expand(Scope *scope,\n const QList &visibleScopes,\n QList *expandedScopes) const\n{\n if (expandedScopes->contains(scope))\n return;\n\n expandedScopes->append(scope);\n\n if (scope->isNamespaceScope()) {\n expandNamespace(scope, visibleScopes, expandedScopes);\n } else if (scope->isClassScope()) {\n expandClass(scope, visibleScopes, expandedScopes);\n } else if (scope->isBlockScope()) {\n expandBlock(scope, visibleScopes, expandedScopes);\n } else if (scope->isFunctionScope()) {\n expandFunction(scope, visibleScopes, expandedScopes);\n } else if (scope->isPrototypeScope()) {\n \/\/qDebug() << \"prototype scope\" << overview.prettyName(scope->owner()->name());\n }\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n\nclass Application : public okui::applications::Native {\npublic:\n virtual std::string name() const override { return \"StateMachine Example\"; }\n virtual std::string organization() const override { return \"BitTorrent Inc.\"; }\n};\n\nstruct State {\n double x, y, opacity;\n constexpr auto members() { return std::tie(x, y, opacity); }\n};\n\nclass View : public okui::View, public okui::StateMachine {\npublic:\n View() : okui::StateMachine(\"Above\") {\n addUpdateHook(\"StateMachine\", [&]{ drive(); });\n setTransition(\"Above\", \"Normal\", 200ms, okui::interpolation::Quadratic::EaseOut);\n setTransition(\"Normal\", \"Left\", 200ms, okui::interpolation::Quadratic::EaseIn);\n }\n\nprivate:\n virtual void update(stdts::string_view id, State& state, bool& isAnimated) override {\n state.opacity = id == \"Normal\" ? 1.0 : 0.0;\n state.x = id == \"Left\" ? -100.0 : 300.0;\n state.y = id == \"Above\" ? -100.0 : 300.0;\n }\n\n virtual void apply(const State& state) override {\n setOpacity(state.opacity);\n setBounds(state.x, state.y, 100.0, 100.0);\n }\n};\n\nint main() {\n Application application;\n\n okui::Window window{&application};\n window.open();\n\n View view;\n view.setBackgroundColor(okui::Color::kBlue);\n window.contentView()->addSubview(&view);\n\n view.asyncAfter(2s, [&] { view.setState(\"Normal\"); });\n view.asyncAfter(4s, [&] { view.setState(\"Left\"); });\n\n application.run();\n return 0;\n}\nadd final specifier to quiet analysis#include \n#include \n#include \n\nclass Application : public okui::applications::Native {\npublic:\n virtual std::string name() const override { return \"StateMachine Example\"; }\n virtual std::string organization() const override { return \"BitTorrent Inc.\"; }\n};\n\nstruct State {\n double x, y, opacity;\n constexpr auto members() { return std::tie(x, y, opacity); }\n};\n\nclass View final : public okui::View, public okui::StateMachine {\npublic:\n View() : okui::StateMachine(\"Above\") {\n addUpdateHook(\"StateMachine\", [&]{ drive(); });\n setTransition(\"Above\", \"Normal\", 200ms, okui::interpolation::Quadratic::EaseOut);\n setTransition(\"Normal\", \"Left\", 200ms, okui::interpolation::Quadratic::EaseIn);\n }\n\nprivate:\n virtual void update(stdts::string_view id, State& state, bool& isAnimated) override {\n state.opacity = id == \"Normal\" ? 1.0 : 0.0;\n state.x = id == \"Left\" ? -100.0 : 300.0;\n state.y = id == \"Above\" ? -100.0 : 300.0;\n }\n\n virtual void apply(const State& state) override {\n setOpacity(state.opacity);\n setBounds(state.x, state.y, 100.0, 100.0);\n }\n};\n\nint main() {\n Application application;\n\n okui::Window window{&application};\n window.open();\n\n View view;\n view.setBackgroundColor(okui::Color::kBlue);\n window.contentView()->addSubview(&view);\n\n view.asyncAfter(2s, [&] { view.setState(\"Normal\"); });\n view.asyncAfter(4s, [&] { view.setState(\"Left\"); });\n\n application.run();\n return 0;\n}\n<|endoftext|>"} {"text":"\/*\n Generic Console Output Support\n Copyright (C) 1998-2001 by Jorrit Tyberghein\n Copyright (c) 2004-2005 by Frank Richter\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Library General Public\n License as published by the Free Software Foundation; either\n version 2 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Library General Public License for more details.\n\n You should have received a copy of the GNU Library General Public\n License along with this library; if not, write to the Free\n Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n*\/\n\n#include \n#include \n#include \"cssysdef.h\"\n#include \"csutil\/ansiparse.h\"\n#include \"csutil\/csstring.h\"\n#include \"csutil\/csuctransform.h\"\n#include \"csutil\/sysfunc.h\"\n\n\/\/ Replacement for printf(); exact same prototype\/functionality as printf()\nint csPrintf (char const* str, ...)\n{\n va_list args;\n va_start (args, str);\n int const rc = csPrintfV (str, args);\n va_end (args);\n return rc;\n}\n\nstatic int cs_fputsn (FILE* file, const char* str, size_t len)\n{\n size_t wstrSize = len + 1;\n CS_ALLOC_STACK_ARRAY(wchar_t, wstr, wstrSize);\n\n csUnicodeTransform::UTF8toWC (wstr, wstrSize, (utf8_char*)str, len);\n\n int n = 0;\n const wchar_t* wcsPtr = wstr;\n#if defined(CS_HAVE_FPUTWS) && defined(CS_HAVE_FWIDE) \\\n && defined(CS_HAVE_WCSRTOMBS)\n if (fwide (file, 0) > 0)\n {\n return fputws (wstr, file);\n }\n else\n {\n mbstate_t mbs;\n memset (&mbs, 0, sizeof (mbs));\n char mbstr[64];\n size_t mbslen;\n while (wcsPtr != 0)\n {\n memset (mbstr, 0, sizeof (mbstr));\n mbslen = wcsrtombs (mbstr, &wcsPtr, sizeof (mbstr) - 1, &mbs);\n if (mbslen == (size_t)-1)\n {\n\tif (errno == EILSEQ)\n\t{\n\t \/\/ Catch char that couldn't be encoded, print ? instead\n\t if (fputs (mbstr, file) == EOF) return EOF;\n\t if (fputc ('?', file) == EOF) return EOF;\n\t if (CS_UC_IS_HIGH_SURROGATE (*wcsPtr))\n\t {\n\t wcsPtr++;\n\t if (CS_UC_IS_LOW_SURROGATE (*wcsPtr))\n\t wcsPtr++;\n\t }\n\t else\n\t wcsPtr++;\n\t continue;\n\t}\n\tbreak;\n }\n if (fputs (mbstr, file) == EOF) return EOF;\n }\n if (wcsPtr == 0) return (int)len;\n }\n#endif\n \/\/ Use a cheap Wide-to-ASCII conversion.\n const wchar_t* ch = wcsPtr;\n \n while (len-- > 0)\n {\n if (*ch < 0x80)\n {\n if (fputc ((char)*ch, file) == EOF) return EOF;\n n++;\n }\n else \n {\n if (fputc ('?', file) == EOF) return EOF;\n n++;\n }\n \n ch++; \n }\n \n return n;\n}\n\nstatic int csFPutStr (FILE* file, const char* str)\n{\n bool isTTY = isatty (fileno (file));\n \n int ret = 0;\n size_t ansiCommandLen;\n csAnsiParser::CommandClass cmdClass;\n size_t textLen;\n \/\/ Check for ANSI codes\n while (csAnsiParser::ParseAnsi (str, ansiCommandLen, cmdClass, textLen))\n {\n int rc;\n if (isTTY && (cmdClass == csAnsiParser::classFormat))\n {\n \/\/ Only let formatting codes through\n rc = cs_fputsn (file, str, ansiCommandLen);\n if (rc == EOF)\n\treturn EOF;\n ret += rc;\n }\n\n if (textLen > 0)\n {\n rc = cs_fputsn (file, str + ansiCommandLen, textLen);\n if (rc == EOF)\n\treturn EOF;\n ret += rc;\n }\n\n str += ansiCommandLen + textLen;\n }\n return ret;\n}\n\n\/\/ Replacement for vprintf()\nint csPrintfV(char const* str, va_list args)\n{\n csString temp;\n temp.FormatV (str, args);\n \n return csFPutStr (stdout, temp);\n}\n\nint csFPrintf (FILE* file, const char* str, ...)\n{\n va_list args;\n va_start (args, str);\n int const rc = csFPrintfV (file, str, args);\n va_end (args);\n return rc;\n}\n\nint csFPrintfV (FILE* file, const char* str, va_list args)\n{\n csString temp;\n temp.FormatV (str, args);\n \n return csFPutStr (file, temp);\n}\n\nint csPrintfErrV (const char* str, va_list arg)\n{\n int rc = csFPrintfV (stderr, str, arg);\n fflush (stderr);\n return rc;\n}\n\nint csPrintfErr (const char* str, ...)\n{\n va_list args;\n va_start (args, str);\n int const rc = csFPrintfV (stderr, str, args);\n va_end (args);\n return rc;\n}\n\nres made some tweaks to the lighter2 TUI to better work on Linux. res fixed the lighter2 tui and Win32 ANSI support for the fact that cursor positions are 1-based, not 0-based.\/*\n Generic Console Output Support\n Copyright (C) 1998-2001 by Jorrit Tyberghein\n Copyright (c) 2004-2005 by Frank Richter\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Library General Public\n License as published by the Free Software Foundation; either\n version 2 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Library General Public License for more details.\n\n You should have received a copy of the GNU Library General Public\n License along with this library; if not, write to the Free\n Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n*\/\n\n#include \n#include \n#include \"cssysdef.h\"\n#include \"csutil\/ansiparse.h\"\n#include \"csutil\/csstring.h\"\n#include \"csutil\/csuctransform.h\"\n#include \"csutil\/sysfunc.h\"\n\n\/\/ Replacement for printf(); exact same prototype\/functionality as printf()\nint csPrintf (char const* str, ...)\n{\n va_list args;\n va_start (args, str);\n int const rc = csPrintfV (str, args);\n va_end (args);\n return rc;\n}\n\nstatic int cs_fputsn (FILE* file, const char* str, size_t len)\n{\n size_t wstrSize = len + 1;\n CS_ALLOC_STACK_ARRAY(wchar_t, wstr, wstrSize);\n\n csUnicodeTransform::UTF8toWC (wstr, wstrSize, (utf8_char*)str, len);\n\n int n = 0;\n const wchar_t* wcsPtr = wstr;\n#if defined(CS_HAVE_FPUTWS) && defined(CS_HAVE_FWIDE) \\\n && defined(CS_HAVE_WCSRTOMBS)\n if (fwide (file, 0) > 0)\n {\n return fputws (wstr, file);\n }\n else\n {\n mbstate_t mbs;\n memset (&mbs, 0, sizeof (mbs));\n char mbstr[64];\n size_t mbslen;\n while (wcsPtr != 0)\n {\n memset (mbstr, 0, sizeof (mbstr));\n mbslen = wcsrtombs (mbstr, &wcsPtr, sizeof (mbstr) - 1, &mbs);\n if (mbslen == (size_t)-1)\n {\n\tif (errno == EILSEQ)\n\t{\n\t \/\/ Catch char that couldn't be encoded, print ? instead\n\t if (fputs (mbstr, file) == EOF) return EOF;\n\t if (fputc ('?', file) == EOF) return EOF;\n\t if (CS_UC_IS_HIGH_SURROGATE (*wcsPtr))\n\t {\n\t wcsPtr++;\n\t if (CS_UC_IS_LOW_SURROGATE (*wcsPtr))\n\t wcsPtr++;\n\t }\n\t else\n\t wcsPtr++;\n\t continue;\n\t}\n\tbreak;\n }\n if (fputs (mbstr, file) == EOF) return EOF;\n }\n if (wcsPtr == 0) return (int)len;\n }\n#endif\n \/\/ Use a cheap Wide-to-ASCII conversion.\n const wchar_t* ch = wcsPtr;\n \n while (len-- > 0)\n {\n if (*ch < 0x80)\n {\n if (fputc ((char)*ch, file) == EOF) return EOF;\n n++;\n }\n else \n {\n if (fputc ('?', file) == EOF) return EOF;\n n++;\n }\n \n ch++; \n }\n \n return n;\n}\n\nstatic int csFPutStr (FILE* file, const char* str)\n{\n bool isTTY = isatty (fileno (file));\n \n int ret = 0;\n size_t ansiCommandLen;\n csAnsiParser::CommandClass cmdClass;\n size_t textLen;\n \/\/ Check for ANSI codes\n while (csAnsiParser::ParseAnsi (str, ansiCommandLen, cmdClass, textLen))\n {\n int rc;\n if (isTTY && (cmdClass != csAnsiParser::classNone)\n && (cmdClass != csAnsiParser::classUnknown))\n {\n \/\/ Only let known codes through\n rc = cs_fputsn (file, str, ansiCommandLen);\n if (rc == EOF)\n\treturn EOF;\n ret += rc;\n }\n\n if (textLen > 0)\n {\n rc = cs_fputsn (file, str + ansiCommandLen, textLen);\n if (rc == EOF)\n\treturn EOF;\n ret += rc;\n }\n\n str += ansiCommandLen + textLen;\n }\n return ret;\n}\n\n\/\/ Replacement for vprintf()\nint csPrintfV(char const* str, va_list args)\n{\n csString temp;\n temp.FormatV (str, args);\n \n return csFPutStr (stdout, temp);\n}\n\nint csFPrintf (FILE* file, const char* str, ...)\n{\n va_list args;\n va_start (args, str);\n int const rc = csFPrintfV (file, str, args);\n va_end (args);\n return rc;\n}\n\nint csFPrintfV (FILE* file, const char* str, va_list args)\n{\n csString temp;\n temp.FormatV (str, args);\n \n return csFPutStr (file, temp);\n}\n\nint csPrintfErrV (const char* str, va_list arg)\n{\n int rc = csFPrintfV (stderr, str, arg);\n fflush (stderr);\n return rc;\n}\n\nint csPrintfErr (const char* str, ...)\n{\n va_list args;\n va_start (args, str);\n int const rc = csFPrintfV (stderr, str, args);\n va_end (args);\n return rc;\n}\n\n<|endoftext|>"} {"text":"\/\/\n\/\/ Copyright (c) 2017 Kimball Thurston\n\/\/ All rights reserved.\n\/\/ Copyrights licensed under the MIT License.\n\/\/ See the accompanying LICENSE.txt file for terms\n\/\/\n\n#if defined(HAVE_PYTHON2) || defined(HAVE_PYTHON3)\n# define HAVE_PYTHON 1\n#endif\n\n#ifdef HAVE_PYTHON\n#pragma GCC diagnostic ignored \"-Wreserved-id-macro\"\n#pragma GCC diagnostic ignored \"-Wold-style-cast\"\n#include \n#endif\n#if PY_MAJOR_VERSION <= 1\n#error python 2 or higher is required\n#else\n# if PY_MAJOR_VERSION < 3\n# define IS_PYTHON2 1\n# elif PY_MAJOR_VERSION < 4\n# define IS_PYTHON3 1\n# endif\n#endif\n\n\n#include \"context.h\"\n#include \n#include \n#include \n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nnamespace python_bridge\n{\n\n#ifdef HAVE_PYTHON\nstatic std::atomic_flag _active_context = ATOMIC_FLAG_INIT;\nclass context::priv_Impl\n{\npublic:\n\tpriv_Impl( const std::string &argv0 )\n\t{\n\t\tif ( _active_context.test_and_set( std::memory_order_acquire ) )\n\t\t\tthrow std::runtime_error( \"Current version of python does not allow multiple active contexts at once\" );\n\n#ifdef IS_PYTHON2\n\t\t_progname = strdup( argv0.c_str() );\n#else\n\t\t_progname = Py_DecodeLocale( argv0.c_str(), nullptr );\n\t\tif ( ! _progname )\n\t\t\tthrow std::runtime_error( \"Unable to decode argv[0]\" );\n#endif\n\t\tPy_SetProgramName( _progname );\n\t\tPy_Initialize();\n\t}\n\n\t~priv_Impl( void )\n\t{\n#ifdef IS_PYTHON2\n\t\tPy_Finalize();\n\t\tif ( _progname )\n\t\t\t::free( _progname );\n#else\n\t\tif ( Py_FinalizeEx() < 0 )\n\t\t\tstd::cerr << \"ERROR shutting down python interpreter\" << std::endl;\n\t\tif ( _progname )\n\t\t\tPyMem_RawFree( _progname );\n#endif\n\t\t_active_context.clear( std::memory_order_release );\n\t}\n\n\tbool load_module( const char *fn, const std::string &tag )\n\t{\n\t\tauto i = _glob_modules.find( tag );\n\t\tif ( i != _glob_modules.end() )\n\t\t\tPy_DECREF( i->second );\n\n#ifdef IS_PYTHON2\n\t\tPyObject *pName = PyString_FromString( fn );\n#else\n\t\tPyObject *pName = PyUnicode_DecodeFSDefault( fn );\n#endif\n\t\t\/\/ TODO: add error checks\n\t\tPyObject *pModule = PyImport_Import( pName );\n\t\tPy_DECREF( pName );\n\t\tif ( pModule )\n\t\t{\n\t\t\t_glob_modules[tag] = pModule;\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\nprivate:\n#ifdef IS_PYTHON2\n\tchar *_progname = nullptr;\n#else\n\twchar_t *_progname = nullptr;\n#endif\n\tstd::map _glob_modules;\n};\n#endif\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ncontext::context( const std::string &argv0 )\n#ifdef HAVE_PYTHON\n\t\t: _impl( new priv_Impl( argv0 ) )\n#endif\n{\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ncontext::~context( void )\n{\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool context::run( const std::string &fn )\n{\n#ifdef HAVE_PYTHON\n\treturn _impl->load_module( fn.c_str(), fn );\n#else\n\treturn false;\n#endif\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool context::run( const base::uri &u )\n{\n#ifdef HAVE_PYTHON\n\tthrow std::logic_error( \"Not Yet Implemented\" );\n#else\n\treturn false;\n#endif\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid context::push_eval_lookup( lookup &l )\n{\n#ifdef HAVE_PYTHON\n#endif\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid context::pop_eval_lookup( void )\n{\n#ifdef HAVE_PYTHON\n#endif\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool context::evaluate( bool &result, const char *s )\n{\n#ifdef HAVE_PYTHON\n#else\n\treturn false;\n#endif\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool context::evaluate( int &result, const char *s )\n{\n#ifdef HAVE_PYTHON\n#else\n\treturn false;\n#endif\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool context::evaluate( float &result, const char *s )\n{\n#ifdef HAVE_PYTHON\n#else\n\treturn false;\n#endif\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool context::evaluate( double &result, const char *s )\n{\n#ifdef HAVE_PYTHON\n#else\n\treturn false;\n#endif\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool context::evaluate( int64_t &result, const char *s )\n{\n#ifdef HAVE_PYTHON\n#else\n\treturn false;\n#endif\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool context::evaluate( std::string &result, const char *s )\n{\n#ifdef HAVE_PYTHON\n#else\n\treturn false;\n#endif\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool context::evaluate( std::wstring &result, const char *s )\n{\n#ifdef HAVE_PYTHON\n#else\n\treturn false;\n#endif\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n} \/\/ namespace python_bridge\n\nfix includes for prototype\/\/\n\/\/ Copyright (c) 2017 Kimball Thurston\n\/\/ All rights reserved.\n\/\/ Copyrights licensed under the MIT License.\n\/\/ See the accompanying LICENSE.txt file for terms\n\/\/\n\n#if defined(HAVE_PYTHON2) || defined(HAVE_PYTHON3)\n# define HAVE_PYTHON 1\n#endif\n\n#ifdef HAVE_PYTHON\n# if defined(__clang__)\n# pragma GCC diagnostic ignored \"-Wreserved-id-macro\"\n# pragma GCC diagnostic ignored \"-Wold-style-cast\"\n# endif\n# include \n# if PY_MAJOR_VERSION <= 1\n# error python 2 or higher is required\n# else\n# if PY_MAJOR_VERSION < 3\n# define IS_PYTHON2 1\n# elif PY_MAJOR_VERSION < 4\n# define IS_PYTHON3 1\n# endif\n# endif\n#endif\n\n#include \"context.h\"\n#include \n#include \n#include \n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nnamespace python_bridge\n{\n\n#ifdef HAVE_PYTHON\nstatic std::atomic_flag _active_context = ATOMIC_FLAG_INIT;\nclass context::priv_Impl\n{\npublic:\n\tpriv_Impl( const std::string &argv0 )\n\t{\n\t\tif ( _active_context.test_and_set( std::memory_order_acquire ) )\n\t\t\tthrow std::runtime_error( \"Current version of python does not allow multiple active contexts at once\" );\n\n#ifdef IS_PYTHON2\n\t\t_progname = strdup( argv0.c_str() );\n#else\n\t\t_progname = Py_DecodeLocale( argv0.c_str(), nullptr );\n\t\tif ( ! _progname )\n\t\t\tthrow std::runtime_error( \"Unable to decode argv[0]\" );\n#endif\n\t\tPy_SetProgramName( _progname );\n\t\tPy_Initialize();\n\t}\n\n\t~priv_Impl( void )\n\t{\n#ifdef IS_PYTHON2\n\t\tPy_Finalize();\n\t\tif ( _progname )\n\t\t\t::free( _progname );\n#else\n\t\tif ( Py_FinalizeEx() < 0 )\n\t\t\tstd::cerr << \"ERROR shutting down python interpreter\" << std::endl;\n\t\tif ( _progname )\n\t\t\tPyMem_RawFree( _progname );\n#endif\n\t\t_active_context.clear( std::memory_order_release );\n\t}\n\n\tbool load_module( const char *fn, const std::string &tag )\n\t{\n\t\tauto i = _glob_modules.find( tag );\n\t\tif ( i != _glob_modules.end() )\n\t\t\tPy_DECREF( i->second );\n\n#ifdef IS_PYTHON2\n\t\tPyObject *pName = PyString_FromString( fn );\n#else\n\t\tPyObject *pName = PyUnicode_DecodeFSDefault( fn );\n#endif\n\t\t\/\/ TODO: add error checks\n\t\tPyObject *pModule = PyImport_Import( pName );\n\t\tPy_DECREF( pName );\n\t\tif ( pModule )\n\t\t{\n\t\t\t_glob_modules[tag] = pModule;\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\nprivate:\n#ifdef IS_PYTHON2\n\tchar *_progname = nullptr;\n#else\n\twchar_t *_progname = nullptr;\n#endif\n\tstd::map _glob_modules;\n};\n#endif\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ncontext::context( const std::string &argv0 )\n#ifdef HAVE_PYTHON\n\t\t: _impl( new priv_Impl( argv0 ) )\n#endif\n{\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ncontext::~context( void )\n{\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool context::run( const std::string &fn )\n{\n#ifdef HAVE_PYTHON\n\treturn _impl->load_module( fn.c_str(), fn );\n#else\n\treturn false;\n#endif\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool context::run( const base::uri &u )\n{\n#ifdef HAVE_PYTHON\n\tthrow std::logic_error( \"Not Yet Implemented\" );\n#else\n\treturn false;\n#endif\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid context::push_eval_lookup( lookup &l )\n{\n#ifdef HAVE_PYTHON\n#endif\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid context::pop_eval_lookup( void )\n{\n#ifdef HAVE_PYTHON\n#endif\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool context::evaluate( bool &result, const char *s )\n{\n#ifdef HAVE_PYTHON\n\treturn true;\n#else\n\treturn false;\n#endif\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool context::evaluate( int &result, const char *s )\n{\n#ifdef HAVE_PYTHON\n\treturn true;\n#else\n\treturn false;\n#endif\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool context::evaluate( float &result, const char *s )\n{\n#ifdef HAVE_PYTHON\n\treturn true;\n#else\n\treturn false;\n#endif\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool context::evaluate( double &result, const char *s )\n{\n#ifdef HAVE_PYTHON\n\treturn true;\n#else\n\treturn false;\n#endif\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool context::evaluate( int64_t &result, const char *s )\n{\n#ifdef HAVE_PYTHON\n\treturn true;\n#else\n\treturn false;\n#endif\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool context::evaluate( std::string &result, const char *s )\n{\n#ifdef HAVE_PYTHON\n\treturn true;\n#else\n\treturn false;\n#endif\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool context::evaluate( std::wstring &result, const char *s )\n{\n#ifdef HAVE_PYTHON\n\treturn true;\n#else\n\treturn false;\n#endif\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n} \/\/ namespace python_bridge\n\n<|endoftext|>"} {"text":"#include \"ui\/socket_item.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"elements\/package.h\"\n#include \"ui\/colors.h\"\n#include \"ui\/link_item.h\"\n#include \"ui\/package_view.h\"\n\nSocketItem::SocketItem(Type a_type, QGraphicsItem *const a_parent)\n : QGraphicsItem{ a_parent }\n , m_type{ a_type }\n{\n m_font.setFamily(\"Consolas\");\n m_font.setPointSize(12);\n\n setFlags(QGraphicsItem::ItemIsMovable | QGraphicsItem::ItemIsFocusable |\n QGraphicsItem::ItemSendsScenePositionChanges);\n setAcceptHoverEvents(true);\n setAcceptedMouseButtons(Qt::LeftButton);\n\n setZValue(1);\n\n if (a_type == Type::eOutput)\n setCursor(Qt::OpenHandCursor);\n else\n setAcceptDrops(true);\n}\n\nQRectF SocketItem::boundingRect() const\n{\n return QRectF{ -(static_cast(SIZE) \/ 2.), 0, static_cast(SIZE), static_cast(SIZE) };\n}\n\nvoid SocketItem::paint(QPainter *a_painter, const QStyleOptionGraphicsItem *a_option, QWidget *a_widget)\n{\n Q_UNUSED(a_option);\n Q_UNUSED(a_widget);\n\n QRectF const rect{ boundingRect() };\n\n QPen pen{ get_color(Color::eSocketBorder) };\n pen.setWidth(2);\n\n QBrush brush{};\n if (m_isHover)\n brush.setColor(get_color(Color::eSocketHover));\n else if (m_isDrop)\n brush.setColor(get_color(Color::eSocketDrop));\n else if (m_isSignalOn)\n brush.setColor(m_colorSignalOn);\n else if (!m_isSignalOn)\n brush.setColor(m_colorSignalOff);\n \/\/ else if (m_type == Type::eInput)\n \/\/ brush.setColor(config.getColor(Config::Color::eSocketInput));\n \/\/ else if (m_type == Type::eOutput)\n \/\/ brush.setColor(config.getColor(Config::Color::eSocketOutput));\n brush.setStyle(Qt::SolidPattern);\n\n a_painter->setPen(pen);\n a_painter->setBrush(brush);\n a_painter->drawEllipse(rect);\n\n if (m_used) {\n a_painter->save();\n a_painter->setPen(Qt::NoPen);\n a_painter->setBrush(pen.color());\n a_painter->drawEllipse(rect.adjusted(4, 4, -4, -4));\n a_painter->restore();\n }\n\n if (!m_nameHidden) {\n pen.setColor(get_color(Color::eFontName));\n a_painter->setPen(pen);\n QFont font{ a_painter->font() };\n font.setPointSize(12);\n a_painter->setFont(font);\n\n QFontMetrics const metrics{ font };\n\n if (m_type == Type::eInput)\n a_painter->drawText(static_cast(rect.width()) - 2, 13, m_name);\n else\n a_painter->drawText(-metrics.width(m_name) - 14, 13, m_name);\n }\n}\n\nvoid SocketItem::hoverEnterEvent(QGraphicsSceneHoverEvent *a_event)\n{\n Q_UNUSED(a_event);\n\n m_isHover = true;\n\n for (auto const link : m_links) link->setHover(m_isHover);\n}\n\nvoid SocketItem::hoverLeaveEvent(QGraphicsSceneHoverEvent *a_event)\n{\n Q_UNUSED(a_event);\n\n m_isHover = false;\n\n for (auto const link : m_links) link->setHover(m_isHover);\n}\n\nvoid SocketItem::dragEnterEvent(QGraphicsSceneDragDropEvent *a_event)\n{\n Q_UNUSED(a_event);\n\n if (m_used) {\n a_event->ignore();\n return;\n }\n\n PackageView *const view{ reinterpret_cast(scene()->views()[0]) };\n\n LinkItem *const linkItem{ view->dragLink() };\n if (!linkItem || m_valueType != linkItem->valueType()) {\n a_event->ignore();\n return;\n }\n\n linkItem->setTo(this);\n m_isDrop = true;\n}\n\nvoid SocketItem::dragLeaveEvent(QGraphicsSceneDragDropEvent *a_event)\n{\n Q_UNUSED(a_event);\n\n m_isDrop = false;\n\n PackageView *const view{ reinterpret_cast(scene()->views()[0]) };\n\n LinkItem *const linkItem{ view->dragLink() };\n if (!linkItem) return;\n linkItem->setTo(nullptr);\n}\n\nvoid SocketItem::dragMoveEvent(QGraphicsSceneDragDropEvent *a_event)\n{\n Q_UNUSED(a_event);\n}\n\nvoid SocketItem::dropEvent(QGraphicsSceneDragDropEvent *a_event)\n{\n Q_UNUSED(a_event);\n\n PackageView *const packageView{ reinterpret_cast(scene()->views()[0]) };\n\n LinkItem *const linkItem{ packageView->dragLink() };\n if (!linkItem) return;\n\n m_links.push_back(linkItem);\n linkItem->setTo(this);\n m_used = true;\n m_isDrop = false;\n\n packageView->acceptDragLink();\n\n auto const package = packageView->package();\n auto const from = linkItem->from();\n\n package->connect(from->elementId(), from->socketId(), m_elementId, m_socketId);\n\n}\n\nvoid SocketItem::mousePressEvent(QGraphicsSceneMouseEvent *a_event)\n{\n Q_UNUSED(a_event);\n\n if (m_type == Type::eInput) return;\n\n setCursor(Qt::ClosedHandCursor);\n}\n\nvoid SocketItem::mouseMoveEvent(QGraphicsSceneMouseEvent *a_event)\n{\n Q_UNUSED(a_event);\n\n if (m_type == Type::eInput) return;\n\n if (QLineF(a_event->screenPos(), a_event->buttonDownScreenPos(Qt::LeftButton)).length() <\n QApplication::startDragDistance())\n return;\n\n \/\/ QRectF const rect{ boundingRect() };\n\n QDrag *const drag = new QDrag(a_event->widget());\n\n QMimeData *const mime = new QMimeData;\n \/\/ mime->setData(\"data\/x-element\", QByteArray());\n drag->setMimeData(mime);\n\n LinkItem *linkItem{ new LinkItem };\n linkItem->setColors(m_colorSignalOff, m_colorSignalOn);\n linkItem->setFrom(this);\n\n scene()->addItem(linkItem);\n\n PackageView *const view{ reinterpret_cast(scene()->views()[0]) };\n view->setDragLink(linkItem);\n\n Qt::DropAction const action{ drag->exec() };\n if (action == Qt::IgnoreAction)\n view->cancelDragLink();\n else {\n m_links.push_back(linkItem);\n m_used = true;\n }\n\n setCursor(Qt::OpenHandCursor);\n}\n\nvoid SocketItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *a_event)\n{\n Q_UNUSED(a_event);\n\n if (m_type == Type::eInput) return;\n\n setCursor(Qt::OpenHandCursor);\n}\n\nQVariant SocketItem::itemChange(QGraphicsItem::GraphicsItemChange a_change, const QVariant &a_value)\n{\n if (a_change == QGraphicsItem::ItemScenePositionHasChanged) {\n for (LinkItem *const link : m_links) link->trackNodes();\n }\n return QGraphicsItem::itemChange(a_change, a_value);\n}\n\nint SocketItem::nameWidth() const\n{\n QFontMetrics const metrics{ m_font };\n return metrics.width(m_name);\n}\n\nvoid SocketItem::setColors(QColor const a_signalOff, QColor const a_signalOn)\n{\n m_colorSignalOff = a_signalOff;\n m_colorSignalOn = a_signalOn;\n}\n\nvoid SocketItem::setSignal(const bool a_signal)\n{\n m_isSignalOn = a_signal;\n\n if (m_type == Type::eOutput) {\n for (LinkItem *const link : m_links) link->setSignal(a_signal);\n }\n}\n\nvoid SocketItem::connect(SocketItem *const a_other)\n{\n auto const linkItem = new LinkItem;\n linkItem->setColors(m_colorSignalOff, m_colorSignalOn);\n linkItem->setFrom(this);\n linkItem->setTo(a_other);\n\n m_links.push_back(linkItem);\n m_used = true;\n\n a_other->m_links.push_back(linkItem);\n a_other->m_used = true;\n a_other->m_isDrop = false;\n\n scene()->addItem(linkItem);\n}\nCall setSignal in SocketItem::dropEvent#include \"ui\/socket_item.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"elements\/package.h\"\n#include \"ui\/colors.h\"\n#include \"ui\/link_item.h\"\n#include \"ui\/package_view.h\"\n\nSocketItem::SocketItem(Type a_type, QGraphicsItem *const a_parent)\n : QGraphicsItem{ a_parent }\n , m_type{ a_type }\n{\n m_font.setFamily(\"Consolas\");\n m_font.setPointSize(12);\n\n setFlags(QGraphicsItem::ItemIsMovable | QGraphicsItem::ItemIsFocusable |\n QGraphicsItem::ItemSendsScenePositionChanges);\n setAcceptHoverEvents(true);\n setAcceptedMouseButtons(Qt::LeftButton);\n\n setZValue(1);\n\n if (a_type == Type::eOutput)\n setCursor(Qt::OpenHandCursor);\n else\n setAcceptDrops(true);\n}\n\nQRectF SocketItem::boundingRect() const\n{\n return QRectF{ -(static_cast(SIZE) \/ 2.), 0, static_cast(SIZE), static_cast(SIZE) };\n}\n\nvoid SocketItem::paint(QPainter *a_painter, const QStyleOptionGraphicsItem *a_option, QWidget *a_widget)\n{\n Q_UNUSED(a_option);\n Q_UNUSED(a_widget);\n\n QRectF const rect{ boundingRect() };\n\n QPen pen{ get_color(Color::eSocketBorder) };\n pen.setWidth(2);\n\n QBrush brush{};\n if (m_isHover)\n brush.setColor(get_color(Color::eSocketHover));\n else if (m_isDrop)\n brush.setColor(get_color(Color::eSocketDrop));\n else if (m_isSignalOn)\n brush.setColor(m_colorSignalOn);\n else if (!m_isSignalOn)\n brush.setColor(m_colorSignalOff);\n \/\/ else if (m_type == Type::eInput)\n \/\/ brush.setColor(config.getColor(Config::Color::eSocketInput));\n \/\/ else if (m_type == Type::eOutput)\n \/\/ brush.setColor(config.getColor(Config::Color::eSocketOutput));\n brush.setStyle(Qt::SolidPattern);\n\n a_painter->setPen(pen);\n a_painter->setBrush(brush);\n a_painter->drawEllipse(rect);\n\n if (m_used) {\n a_painter->save();\n a_painter->setPen(Qt::NoPen);\n a_painter->setBrush(pen.color());\n a_painter->drawEllipse(rect.adjusted(4, 4, -4, -4));\n a_painter->restore();\n }\n\n if (!m_nameHidden) {\n pen.setColor(get_color(Color::eFontName));\n a_painter->setPen(pen);\n QFont font{ a_painter->font() };\n font.setPointSize(12);\n a_painter->setFont(font);\n\n QFontMetrics const metrics{ font };\n\n if (m_type == Type::eInput)\n a_painter->drawText(static_cast(rect.width()) - 2, 13, m_name);\n else\n a_painter->drawText(-metrics.width(m_name) - 14, 13, m_name);\n }\n}\n\nvoid SocketItem::hoverEnterEvent(QGraphicsSceneHoverEvent *a_event)\n{\n Q_UNUSED(a_event);\n\n m_isHover = true;\n\n for (auto const link : m_links) link->setHover(m_isHover);\n}\n\nvoid SocketItem::hoverLeaveEvent(QGraphicsSceneHoverEvent *a_event)\n{\n Q_UNUSED(a_event);\n\n m_isHover = false;\n\n for (auto const link : m_links) link->setHover(m_isHover);\n}\n\nvoid SocketItem::dragEnterEvent(QGraphicsSceneDragDropEvent *a_event)\n{\n Q_UNUSED(a_event);\n\n if (m_used) {\n a_event->ignore();\n return;\n }\n\n PackageView *const view{ reinterpret_cast(scene()->views()[0]) };\n\n LinkItem *const linkItem{ view->dragLink() };\n if (!linkItem || m_valueType != linkItem->valueType()) {\n a_event->ignore();\n return;\n }\n\n linkItem->setTo(this);\n m_isDrop = true;\n}\n\nvoid SocketItem::dragLeaveEvent(QGraphicsSceneDragDropEvent *a_event)\n{\n Q_UNUSED(a_event);\n\n m_isDrop = false;\n\n PackageView *const view{ reinterpret_cast(scene()->views()[0]) };\n\n LinkItem *const linkItem{ view->dragLink() };\n if (!linkItem) return;\n linkItem->setTo(nullptr);\n}\n\nvoid SocketItem::dragMoveEvent(QGraphicsSceneDragDropEvent *a_event)\n{\n Q_UNUSED(a_event);\n}\n\nvoid SocketItem::dropEvent(QGraphicsSceneDragDropEvent *a_event)\n{\n Q_UNUSED(a_event);\n\n PackageView *const packageView{ reinterpret_cast(scene()->views()[0]) };\n\n LinkItem *const linkItem{ packageView->dragLink() };\n if (!linkItem) return;\n\n m_links.push_back(linkItem);\n linkItem->setTo(this);\n m_used = true;\n m_isDrop = false;\n\n packageView->acceptDragLink();\n\n auto const package = packageView->package();\n auto const from = linkItem->from();\n\n package->connect(from->elementId(), from->socketId(), m_elementId, m_socketId);\n\n setSignal(linkItem->isSignalOn());\n}\n\nvoid SocketItem::mousePressEvent(QGraphicsSceneMouseEvent *a_event)\n{\n Q_UNUSED(a_event);\n\n if (m_type == Type::eInput) return;\n\n setCursor(Qt::ClosedHandCursor);\n}\n\nvoid SocketItem::mouseMoveEvent(QGraphicsSceneMouseEvent *a_event)\n{\n Q_UNUSED(a_event);\n\n if (m_type == Type::eInput) return;\n\n if (QLineF(a_event->screenPos(), a_event->buttonDownScreenPos(Qt::LeftButton)).length() <\n QApplication::startDragDistance())\n return;\n\n \/\/ QRectF const rect{ boundingRect() };\n\n QDrag *const drag = new QDrag(a_event->widget());\n\n QMimeData *const mime = new QMimeData;\n \/\/ mime->setData(\"data\/x-element\", QByteArray());\n drag->setMimeData(mime);\n\n LinkItem *linkItem{ new LinkItem };\n linkItem->setColors(m_colorSignalOff, m_colorSignalOn);\n linkItem->setFrom(this);\n\n scene()->addItem(linkItem);\n\n PackageView *const view{ reinterpret_cast(scene()->views()[0]) };\n view->setDragLink(linkItem);\n\n Qt::DropAction const action{ drag->exec() };\n if (action == Qt::IgnoreAction)\n view->cancelDragLink();\n else {\n m_links.push_back(linkItem);\n m_used = true;\n }\n\n setCursor(Qt::OpenHandCursor);\n}\n\nvoid SocketItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *a_event)\n{\n Q_UNUSED(a_event);\n\n if (m_type == Type::eInput) return;\n\n setCursor(Qt::OpenHandCursor);\n}\n\nQVariant SocketItem::itemChange(QGraphicsItem::GraphicsItemChange a_change, const QVariant &a_value)\n{\n if (a_change == QGraphicsItem::ItemScenePositionHasChanged) {\n for (LinkItem *const link : m_links) link->trackNodes();\n }\n return QGraphicsItem::itemChange(a_change, a_value);\n}\n\nint SocketItem::nameWidth() const\n{\n QFontMetrics const metrics{ m_font };\n return metrics.width(m_name);\n}\n\nvoid SocketItem::setColors(QColor const a_signalOff, QColor const a_signalOn)\n{\n m_colorSignalOff = a_signalOff;\n m_colorSignalOn = a_signalOn;\n}\n\nvoid SocketItem::setSignal(const bool a_signal)\n{\n m_isSignalOn = a_signal;\n\n if (m_type == Type::eOutput) {\n for (LinkItem *const link : m_links) link->setSignal(a_signal);\n }\n}\n\nvoid SocketItem::connect(SocketItem *const a_other)\n{\n auto const linkItem = new LinkItem;\n linkItem->setColors(m_colorSignalOff, m_colorSignalOn);\n linkItem->setFrom(this);\n linkItem->setTo(a_other);\n\n m_links.push_back(linkItem);\n m_used = true;\n\n a_other->m_links.push_back(linkItem);\n a_other->m_used = true;\n a_other->m_isDrop = false;\n\n scene()->addItem(linkItem);\n}\n<|endoftext|>"} {"text":"#ifdef NG_PYTHON\n\n#include \n#include \n\n#include \n#include \"meshing.hpp\"\n\n\nusing namespace netgen;\nnamespace bp = boost::python;\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Lambda to function pointer conversion\ntemplate \nstruct function_traits\n : public function_traits {};\n\ntemplate \nstruct function_traits {\n typedef ReturnType (*pointer)(Args...);\n typedef ReturnType return_type;\n};\n\ntemplate \ntypename function_traits::pointer\nFunctionPointer (const Function& lambda) {\n return static_cast::pointer>(lambda);\n}\n\n\ntemplate \ninline string ToString (const T& t)\n{\n stringstream ss;\n ss << t;\n return ss.str();\n}\n\n\n\ntemplate \nvoid ExportArray ()\n{\n string name = string(\"Array_\") + typeid(T).name();\n bp::class_,boost::noncopyable>(name.c_str())\n .def (\"__len__\", &Array::Size)\n .def (\"__getitem__\", \n FunctionPointer ([](Array & self, TIND i) -> T&\n {\n if (i < BASE || i >= BASE+self.Size())\n bp::exec(\"raise IndexError()\\n\");\n return self[i];\n }),\n bp::return_value_policy())\n\n .def (\"__iter__\", \n bp::range (FunctionPointer([](Array & self) { return &self[BASE]; }),\n FunctionPointer([](Array & self) { return &self[BASE+self.Size()]; })))\n\n ;\n}\n\n\n\nvoid ExportNetgenMeshing() \n{\n \n std::string nested_name = \"meshing\";\n if( bp::scope() )\n nested_name = bp::extract(bp::scope().attr(\"__name__\") + \".meshing\");\n \n bp::object module(bp::handle<>(bp::borrowed(PyImport_AddModule(nested_name.c_str()))));\n \n cout << \"exporting meshing \" << nested_name << endl;\n bp::object parent = bp::scope() ? bp::scope() : bp::import(\"__main__\");\n parent.attr(\"meshing\") = module ;\n \n bp::scope local_scope(module);\n\n bp::class_(\"PointId\", bp::init())\n .def(\"__repr__\", &ToString)\n .def(\"__str__\", &ToString)\n .add_property(\"nr\", &PointIndex::operator int)\n ;\n \n bp::class_> (\"Point\")\n .def(bp::init())\n ;\n \n bp::class_>>(\"MeshPoint\")\n .def(bp::init>())\n .add_property(\"p\", FunctionPointer([](const MeshPoint & self)\n {\n bp::list l;\n l.append ( (self)[0] );\n l.append ( (self)[1] );\n l.append ( (self)[2] );\n return l;\n }))\n ;\n\n bp::class_(\"Element3D\")\n .add_property(\"index\", &Element::GetIndex, &Element::SetIndex)\n .add_property(\"vertices\", \n FunctionPointer ([](const Element & self) -> bp::list\n {\n bp::list li;\n for (int i = 0; i < self.GetNV(); i++)\n li.append (self[i]);\n return li;\n }))\n ;\n \n ExportArray();\n ExportArray();\n ExportArray();\n ;\n \n \n bp::class_,boost::noncopyable>(\"Mesh\")\n .def(\"__str__\", &ToString)\n .def(\"Load\", static_cast(&Mesh::Load))\n .def(\"Save\", static_cast(&Mesh::Save))\n\n .def(\"Elements3D\", \n static_cast&(Mesh::*)()> (& &Mesh::VolumeElements),\n bp::return_value_policy())\n\n .def(\"Elements2D\", \n static_cast&(Mesh::*)()> (& &Mesh::SurfaceElements),\n bp::return_value_policy())\n\n .def(\"Points\", \n static_cast (& &Mesh::Points),\n bp::return_value_policy())\n\n\n .def(\"__getitem__\", FunctionPointer ([](const Mesh & self, PointIndex pi)\n {\n return self[pi];\n }))\n\n .def (\"Add\", FunctionPointer ([](Mesh & self, MeshPoint p)\n {\n return self.AddPoint (Point3d(p));\n }))\n ;\n \n\n typedef MeshingParameters MP;\n bp::class_ (\"MeshingParameters\")\n .def(\"__str__\", &ToString)\n .add_property(\"maxh\", \n FunctionPointer ([](const MP & mp ) { return mp.maxh; }),\n FunctionPointer ([](MP & mp, double maxh) { return mp.maxh = maxh; }))\n \n ;\n}\n\n\n\nBOOST_PYTHON_MODULE(libmesh) {\n ExportNetgenMeshing();\n}\n\n\n\n#endif\n\n\n\n\nremoved & &#ifdef NG_PYTHON\n\n#include \n#include \n\n#include \n#include \"meshing.hpp\"\n\n\nusing namespace netgen;\nnamespace bp = boost::python;\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Lambda to function pointer conversion\ntemplate \nstruct function_traits\n : public function_traits {};\n\ntemplate \nstruct function_traits {\n typedef ReturnType (*pointer)(Args...);\n typedef ReturnType return_type;\n};\n\ntemplate \ntypename function_traits::pointer\nFunctionPointer (const Function& lambda) {\n return static_cast::pointer>(lambda);\n}\n\n\ntemplate \ninline string ToString (const T& t)\n{\n stringstream ss;\n ss << t;\n return ss.str();\n}\n\n\n\ntemplate \nvoid ExportArray ()\n{\n string name = string(\"Array_\") + typeid(T).name();\n bp::class_,boost::noncopyable>(name.c_str())\n .def (\"__len__\", &Array::Size)\n .def (\"__getitem__\", \n FunctionPointer ([](Array & self, TIND i) -> T&\n {\n if (i < BASE || i >= BASE+self.Size())\n bp::exec(\"raise IndexError()\\n\");\n return self[i];\n }),\n bp::return_value_policy())\n\n .def (\"__iter__\", \n bp::range (FunctionPointer([](Array & self) { return &self[BASE]; }),\n FunctionPointer([](Array & self) { return &self[BASE+self.Size()]; })))\n\n ;\n}\n\n\n\nvoid ExportNetgenMeshing() \n{\n \n std::string nested_name = \"meshing\";\n if( bp::scope() )\n nested_name = bp::extract(bp::scope().attr(\"__name__\") + \".meshing\");\n \n bp::object module(bp::handle<>(bp::borrowed(PyImport_AddModule(nested_name.c_str()))));\n \n cout << \"exporting meshing \" << nested_name << endl;\n bp::object parent = bp::scope() ? bp::scope() : bp::import(\"__main__\");\n parent.attr(\"meshing\") = module ;\n \n bp::scope local_scope(module);\n\n bp::class_(\"PointId\", bp::init())\n .def(\"__repr__\", &ToString)\n .def(\"__str__\", &ToString)\n .add_property(\"nr\", &PointIndex::operator int)\n ;\n \n bp::class_> (\"Point\")\n .def(bp::init())\n ;\n \n bp::class_>>(\"MeshPoint\")\n .def(bp::init>())\n .add_property(\"p\", FunctionPointer([](const MeshPoint & self)\n {\n bp::list l;\n l.append ( (self)[0] );\n l.append ( (self)[1] );\n l.append ( (self)[2] );\n return l;\n }))\n ;\n\n bp::class_(\"Element3D\")\n .add_property(\"index\", &Element::GetIndex, &Element::SetIndex)\n .add_property(\"vertices\", \n FunctionPointer ([](const Element & self) -> bp::list\n {\n bp::list li;\n for (int i = 0; i < self.GetNV(); i++)\n li.append (self[i]);\n return li;\n }))\n ;\n \n ExportArray();\n ExportArray();\n ExportArray();\n ;\n \n \n bp::class_,boost::noncopyable>(\"Mesh\")\n .def(\"__str__\", &ToString)\n .def(\"Load\", static_cast(&Mesh::Load))\n .def(\"Save\", static_cast(&Mesh::Save))\n\n .def(\"Elements3D\", \n static_cast&(Mesh::*)()> (&Mesh::VolumeElements),\n bp::return_value_policy())\n\n .def(\"Elements2D\", \n static_cast&(Mesh::*)()> (&Mesh::SurfaceElements),\n bp::return_value_policy())\n\n .def(\"Points\", \n static_cast (&Mesh::Points),\n bp::return_value_policy())\n\n\n .def(\"__getitem__\", FunctionPointer ([](const Mesh & self, PointIndex pi)\n {\n return self[pi];\n }))\n\n .def (\"Add\", FunctionPointer ([](Mesh & self, MeshPoint p)\n {\n return self.AddPoint (Point3d(p));\n }))\n ;\n \n\n typedef MeshingParameters MP;\n bp::class_ (\"MeshingParameters\")\n .def(\"__str__\", &ToString)\n .add_property(\"maxh\", \n FunctionPointer ([](const MP & mp ) { return mp.maxh; }),\n FunctionPointer ([](MP & mp, double maxh) { return mp.maxh = maxh; }))\n \n ;\n}\n\n\n\nBOOST_PYTHON_MODULE(libmesh) {\n ExportNetgenMeshing();\n}\n\n\n\n#endif\n\n\n\n\n<|endoftext|>"} {"text":"\/*\r\n* Copyright (c) 2011-2013 MLBA-Team. All rights reserved.\r\n*\r\n* @MLBA_OPEN_LICENSE_HEADER_START@\r\n*\r\n* Licensed under the Apache License, Version 2.0 (the \"License\");\r\n* you may not use this file except in compliance with the License.\r\n* You may obtain a copy of the License at\r\n*\r\n* http:\/\/www.apache.org\/licenses\/LICENSE-2.0\r\n*\r\n* Unless required by applicable law or agreed to in writing, software\r\n* distributed under the License is distributed on an \"AS IS\" BASIS,\r\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n* See the License for the specific language governing permissions and\r\n* limitations under the License.\r\n*\r\n* @MLBA_OPEN_LICENSE_HEADER_END@\r\n*\/\r\n\r\n\r\n#include \r\n#include \r\n#include \"xdispatch_internal.h\"\r\n\r\n__XDISPATCH_USE_NAMESPACE iteration_wrap::iteration_wrap (\r\n iteration_operation *o,\r\n size_t ct\r\n)\r\n : op( o ),\r\n ref( ct )\r\n{\r\n XDISPATCH_ASSERT( o );\r\n}\r\n\r\n\r\niteration_wrap::~iteration_wrap ()\r\n{\r\n if( op && op->auto_delete() )\r\n delete op;\r\n}\r\n\r\n\r\niteration_operation * iteration_wrap::operation()\r\n{\r\n return op;\r\n}\r\n\r\n\r\nbool iteration_wrap::deref()\r\n{\r\n return dispatch_atomic_dec( &ref ) == 0;\r\n}\r\n\r\n\r\nvoid set_debugger_threadname()\r\n{\r\n#ifdef DEBUG\r\n\r\n#endif\r\n}\r\n\r\n\r\nextern \"C\"\r\nvoid _xdispatch_run_operation(\r\n void *dt\r\n)\r\n{\r\n XDISPATCH_ASSERT( dt );\r\n operation *w = static_cast< operation * > ( dt );\r\n XDISPATCH_ASSERT( w );\r\n\r\n try\r\n {\r\n ( *w )();\r\n }\r\n catch( const std::exception &e )\r\n {\r\n std::cerr << \"##################################################################\" << std::endl;\r\n std::cerr << \" Queue '\" << xdispatch::current_queue().label() << \"'\" << std::endl;\r\n std::cerr << \"xdispatch: Throwing exceptions within an xdispatch::operation is\" << std::endl;\r\n std::cerr << \" not recommended, please make sure to catch them before:\\n\" << std::endl;\r\n std::cerr << e.what() << std::endl;\r\n std::cerr << \"##################################################################\" << std::endl;\r\n throw;\r\n }\r\n catch( ... )\r\n {\r\n std::cerr << \"##################################################################\" << std::endl;\r\n std::cerr << \" Queue '\" << xdispatch::current_queue().label() << \"'\" << std::endl;\r\n std::cerr << \"xdispatch: Throwing exceptions within an xdispatch::operation is\" << std::endl;\r\n std::cerr << \" not recommended, please make sure to catch them before!\" << std::endl;\r\n std::cerr << \"##################################################################\" << std::endl;\r\n std::terminate();\r\n }\r\n if( w->auto_delete() )\r\n delete w;\r\n} \/\/ _xdispatch_run_operation\r\n\r\n\r\nextern \"C\"\r\nvoid _xdispatch_run_iter_wrap(\r\n void *dt,\r\n size_t index\r\n)\r\n{\r\n XDISPATCH_ASSERT( dt );\r\n iteration_wrap *wrap = static_cast< iteration_wrap * > ( dt );\r\n XDISPATCH_ASSERT( wrap );\r\n\r\n try\r\n {\r\n ( *( wrap->operation() ) )( index );\r\n }\r\n catch( const std::exception &e )\r\n {\r\n std::cerr << \"##################################################################\" << std::endl;\r\n std::cerr << \" Queue '\" << xdispatch::current_queue().label() << \"'\" << std::endl;\r\n std::cerr << \"xdispatch: Throwing exceptions within an xdispatch::operation is\" << std::endl;\r\n std::cerr << \" not recommended, please make sure to catch them before:\\n\" << std::endl;\r\n std::cerr << e.what() << std::endl;\r\n std::cerr << \"##################################################################\" << std::endl;\r\n throw;\r\n }\r\n catch( ... )\r\n {\r\n std::cerr << \"##################################################################\" << std::endl;\r\n std::cerr << \" Queue '\" << xdispatch::current_queue().label() << \"'\" << std::endl;\r\n std::cerr << \"xdispatch: Throwing exceptions within an xdispatch::operation is\" << std::endl;\r\n std::cerr << \" not recommended, please make sure to catch them before!\" << std::endl;\r\n std::cerr << \"##################################################################\" << std::endl;\r\n std::terminate();\r\n }\r\n} \/\/ _xdispatch_run_iter_wrap\r\n\r\n\r\nSet threadname according to queue\/*\r\n* Copyright (c) 2011-2013 MLBA-Team. All rights reserved.\r\n*\r\n* @MLBA_OPEN_LICENSE_HEADER_START@\r\n*\r\n* Licensed under the Apache License, Version 2.0 (the \"License\");\r\n* you may not use this file except in compliance with the License.\r\n* You may obtain a copy of the License at\r\n*\r\n* http:\/\/www.apache.org\/licenses\/LICENSE-2.0\r\n*\r\n* Unless required by applicable law or agreed to in writing, software\r\n* distributed under the License is distributed on an \"AS IS\" BASIS,\r\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n* See the License for the specific language governing permissions and\r\n* limitations under the License.\r\n*\r\n* @MLBA_OPEN_LICENSE_HEADER_END@\r\n*\/\r\n\r\n\r\n#include \r\n#include \r\n#include \"xdispatch_internal.h\"\r\n\r\n__XDISPATCH_USE_NAMESPACE iteration_wrap::iteration_wrap (\r\n iteration_operation *o,\r\n size_t ct\r\n)\r\n : op( o ),\r\n ref( ct )\r\n{\r\n XDISPATCH_ASSERT( o );\r\n}\r\n\r\n\r\niteration_wrap::~iteration_wrap ()\r\n{\r\n if( op && op->auto_delete() )\r\n delete op;\r\n}\r\n\r\n\r\niteration_operation * iteration_wrap::operation()\r\n{\r\n return op;\r\n}\r\n\r\n\r\nbool iteration_wrap::deref()\r\n{\r\n return dispatch_atomic_dec( &ref ) == 0;\r\n}\r\n\r\n\r\ninline void set_debugger_threadname( const std::string& name = std::string() )\r\n{\r\n#if (defined DEBUG) && (defined __APPLE__ || defined __linux__)\r\n# if (defined __linux__)\r\n prctl(PR_SET_NAME, (unsigned long)( name.c_str() ), 0, 0, 0);\r\n# elif (defined __APPLE__)\r\n pthread_setname_np( name.c_str() );\r\n# endif\r\n#endif\r\n}\r\n\r\nextern \"C\"\r\nvoid _xdispatch_run_operation(\r\n void *dt\r\n)\r\n{\r\n XDISPATCH_ASSERT( dt );\r\n operation *w = static_cast< operation * > ( dt );\r\n XDISPATCH_ASSERT( w );\r\n\r\n try\r\n {\r\n set_debugger_threadname( xdispatch::current_queue().label() );\r\n ( *w )();\r\n set_debugger_threadname();\r\n }\r\n catch( const std::exception &e )\r\n {\r\n std::cerr << \"##################################################################\" << std::endl;\r\n std::cerr << \" Queue '\" << xdispatch::current_queue().label() << \"'\" << std::endl;\r\n std::cerr << \"xdispatch: Throwing exceptions within an xdispatch::operation is\" << std::endl;\r\n std::cerr << \" not recommended, please make sure to catch them before:\\n\" << std::endl;\r\n std::cerr << e.what() << std::endl;\r\n std::cerr << \"##################################################################\" << std::endl;\r\n throw;\r\n }\r\n catch( ... )\r\n {\r\n std::cerr << \"##################################################################\" << std::endl;\r\n std::cerr << \" Queue '\" << xdispatch::current_queue().label() << \"'\" << std::endl;\r\n std::cerr << \"xdispatch: Throwing exceptions within an xdispatch::operation is\" << std::endl;\r\n std::cerr << \" not recommended, please make sure to catch them before!\" << std::endl;\r\n std::cerr << \"##################################################################\" << std::endl;\r\n std::terminate();\r\n }\r\n if( w->auto_delete() )\r\n delete w;\r\n} \/\/ _xdispatch_run_operation\r\n\r\n\r\nextern \"C\"\r\nvoid _xdispatch_run_iter_wrap(\r\n void *dt,\r\n size_t index\r\n)\r\n{\r\n XDISPATCH_ASSERT( dt );\r\n iteration_wrap *wrap = static_cast< iteration_wrap * > ( dt );\r\n XDISPATCH_ASSERT( wrap );\r\n\r\n try\r\n {\r\n set_debugger_threadname( xdispatch::current_queue().label() );\r\n ( *( wrap->operation() ) )( index );\r\n set_debugger_threadname();\r\n }\r\n catch( const std::exception &e )\r\n {\r\n std::cerr << \"##################################################################\" << std::endl;\r\n std::cerr << \" Queue '\" << xdispatch::current_queue().label() << \"'\" << std::endl;\r\n std::cerr << \"xdispatch: Throwing exceptions within an xdispatch::operation is\" << std::endl;\r\n std::cerr << \" not recommended, please make sure to catch them before:\\n\" << std::endl;\r\n std::cerr << e.what() << std::endl;\r\n std::cerr << \"##################################################################\" << std::endl;\r\n throw;\r\n }\r\n catch( ... )\r\n {\r\n std::cerr << \"##################################################################\" << std::endl;\r\n std::cerr << \" Queue '\" << xdispatch::current_queue().label() << \"'\" << std::endl;\r\n std::cerr << \"xdispatch: Throwing exceptions within an xdispatch::operation is\" << std::endl;\r\n std::cerr << \" not recommended, please make sure to catch them before!\" << std::endl;\r\n std::cerr << \"##################################################################\" << std::endl;\r\n std::terminate();\r\n }\r\n} \/\/ _xdispatch_run_iter_wrap\r\n\r\n\r\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2003 Daniel Wallin and Arvid Norberg\n\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a\n\/\/ copy of this software and associated documentation files (the \"Software\"),\n\/\/ to deal in the Software without restriction, including without limitation\n\/\/ the rights to use, copy, modify, merge, publish, distribute, sublicense,\n\/\/ and\/or sell copies of the Software, and to permit persons to whom the\n\/\/ Software is furnished to do so, subject to the following conditions:\n\n\/\/ The above copyright notice and this permission notice shall be included\n\/\/ in all copies or substantial portions of the Software.\n\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF\n\/\/ ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED\n\/\/ TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n\/\/ PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT\n\/\/ SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR\n\/\/ ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n\/\/ ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE\n\/\/ OR OTHER DEALINGS IN THE SOFTWARE.\n\n\n#if !BOOST_PP_IS_ITERATING\n\n#ifndef LUABIND_CALL_MEMBER_HPP_INCLUDED\n#define LUABIND_CALL_MEMBER_HPP_INCLUDED\n\n#include \n#include \n#include \n#include \n#include \n#include \/\/ TODO: REMOVE DEPENDENCY\n\n#include \n#include \n#include \n#include \n#include \n\nnamespace luabind\n{\n namespace detail\n {\n\n namespace mpl = boost::mpl;\n\n \/\/ if the proxy_member_caller returns non-void\n template\n class proxy_member_caller\n {\n\/\/ friend class luabind::object;\n public:\n\n proxy_member_caller(lua_State* L_, const Tuple args)\n : L(L_)\n , m_args(args)\n , m_called(false)\n {\n }\n\n proxy_member_caller(const proxy_member_caller& rhs)\n : L(rhs.L)\n , m_args(rhs.m_args)\n , m_called(rhs.m_called)\n {\n rhs.m_called = true;\n }\n\n ~proxy_member_caller()\n {\n if (m_called) return;\n\n m_called = true;\n\n \/\/ don't count the function and self-reference\n \/\/ since those will be popped by pcall\n int top = lua_gettop(L) - 2;\n\n \/\/ pcall will pop the function and self reference\n \/\/ and all the parameters\n\n push_args_from_tuple<1>::apply(L, m_args);\n if (pcall(L, boost::tuples::length::value + 1, 0))\n {\n assert(lua_gettop(L) == top + 1);\n#ifndef LUABIND_NO_EXCEPTIONS\n throw luabind::error(L);\n#else\n error_callback_fun e = get_error_callback();\n if (e) e(L);\n\n assert(0 && \"the lua function threw an error and exceptions are disabled.\"\n \"If you want to handle this error use luabind::set_error_callback()\");\n std::terminate();\n#endif\n }\n \/\/ pops the return values from the function\n stack_pop pop(L, lua_gettop(L) - top);\n }\n\n operator Ret()\n {\n typename mpl::apply_wrap2::type converter;\n\n m_called = true;\n\n \/\/ don't count the function and self-reference\n \/\/ since those will be popped by pcall\n int top = lua_gettop(L) - 2;\n\n \/\/ pcall will pop the function and self reference\n \/\/ and all the parameters\n push_args_from_tuple<1>::apply(L, m_args);\n if (pcall(L, boost::tuples::length::value + 1, 1))\n {\n assert(lua_gettop(L) == top + 1);\n#ifndef LUABIND_NO_EXCEPTIONS\n throw luabind::error(L);\n#else\n error_callback_fun e = get_error_callback();\n if (e) e(L);\n\n assert(0 && \"the lua function threw an error and exceptions are disabled.\"\n \"If you want to handle this error use luabind::set_error_callback()\");\n std::terminate();\n#endif\n }\n\n \/\/ pops the return values from the function\n stack_pop pop(L, lua_gettop(L) - top);\n\n if (converter.match(L, LUABIND_DECORATE_TYPE(Ret), -1) < 0)\n {\n assert(lua_gettop(L) == top + 1);\n#ifndef LUABIND_NO_EXCEPTIONS\n throw cast_failed(L, typeid(Ret));\n#else\n cast_failed_callback_fun e = get_cast_failed_callback();\n if (e) e(L, typeid(Ret));\n\n assert(0 && \"the lua function's return value could not be converted.\"\n \"If you want to handle this error use luabind::set_error_callback()\");\n std::terminate();\n#endif\n }\n\n return converter.apply(L, LUABIND_DECORATE_TYPE(Ret), -1);\n }\n\n template\n Ret operator[](const Policies& p)\n {\n typedef typename find_conversion_policy<0, Policies>::type converter_policy;\n typename mpl::apply_wrap2::type converter;\n\n m_called = true;\n\n \/\/ don't count the function and self-reference\n \/\/ since those will be popped by pcall\n int top = lua_gettop(L) - 2;\n\n \/\/ pcall will pop the function and self reference\n \/\/ and all the parameters\n\n detail::push_args_from_tuple<1>::apply(L, m_args, p);\n if (pcall(L, boost::tuples::length::value + 1, 1))\n {\n assert(lua_gettop(L) == top + 1);\n#ifndef LUABIND_NO_EXCEPTIONS\n throw error(L);\n#else\n error_callback_fun e = get_error_callback();\n if (e) e(L);\n\n assert(0 && \"the lua function threw an error and exceptions are disabled.\"\n \"If you want to handle this error use luabind::set_error_callback()\");\n std::terminate();\n#endif\n }\n\n \/\/ pops the return values from the function\n stack_pop pop(L, lua_gettop(L) - top);\n\n if (converter.match(L, LUABIND_DECORATE_TYPE(Ret), -1) < 0)\n {\n assert(lua_gettop(L) == top + 1);\n#ifndef LUABIND_NO_EXCEPTIONS\n throw cast_failed(L, typeid(Ret));\n#else\n cast_failed_callback_fun e = get_cast_failed_callback();\n if (e) e(L, typeid(Ret));\n\n assert(0 && \"the lua function's return value could not be converted.\"\n \"If you want to handle this error use luabind::set_error_callback()\");\n std::terminate();\n#endif\n }\n return converter.apply(L, LUABIND_DECORATE_TYPE(Ret), -1);\n }\n\n private:\n\n lua_State* L;\n Tuple m_args;\n mutable bool m_called;\n\n };\n\n \/\/ if the proxy_member_caller returns void\n template\n class proxy_member_void_caller\n {\n friend class luabind::object;\n public:\n\n proxy_member_void_caller(lua_State* L_, const Tuple args)\n : L(L_)\n , m_args(args)\n , m_called(false)\n {\n }\n\n proxy_member_void_caller(const proxy_member_void_caller& rhs)\n : L(rhs.L)\n , m_args(rhs.m_args)\n , m_called(rhs.m_called)\n {\n rhs.m_called = true;\n }\n\n ~proxy_member_void_caller()\n {\n if (m_called) return;\n\n m_called = true;\n\n \/\/ don't count the function and self-reference\n \/\/ since those will be popped by pcall\n int top = lua_gettop(L) - 2;\n\n \/\/ pcall will pop the function and self reference\n \/\/ and all the parameters\n\n push_args_from_tuple<1>::apply(L, m_args);\n if (pcall(L, boost::tuples::length::value + 1, 0))\n {\n assert(lua_gettop(L) == top + 1);\n#ifndef LUABIND_NO_EXCEPTIONS\n throw luabind::error(L);\n#else\n error_callback_fun e = get_error_callback();\n if (e) e(L);\n\n assert(0 && \"the lua function threw an error and exceptions are disabled.\"\n \"If you want to handle this error use luabind::set_error_callback()\");\n std::terminate();\n#endif\n }\n \/\/ pops the return values from the function\n stack_pop pop(L, lua_gettop(L) - top);\n }\n\n template\n void operator[](const Policies& p)\n {\n m_called = true;\n\n \/\/ don't count the function and self-reference\n \/\/ since those will be popped by pcall\n int top = lua_gettop(L) - 2;\n\n \/\/ pcall will pop the function and self reference\n \/\/ and all the parameters\n\n detail::push_args_from_tuple<1>::apply(L, m_args, p);\n if (pcall(L, boost::tuples::length::value + 1, 0))\n {\n assert(lua_gettop(L) == top + 1);\n#ifndef LUABIND_NO_EXCEPTIONS\n throw error(L);\n#else\n error_callback_fun e = get_error_callback();\n if (e) e(L);\n\n assert(0 && \"the lua function threw an error and exceptions are disabled.\"\n \"If you want to handle this error use luabind::set_error_callback()\");\n std::terminate();\n#endif\n }\n \/\/ pops the return values from the function\n stack_pop pop(L, lua_gettop(L) - top);\n }\n\n private:\n lua_State* L;\n Tuple m_args;\n mutable bool m_called;\n\n };\n\n } \/\/ detail\n\n #define BOOST_PP_ITERATION_PARAMS_1 (4, (0, LUABIND_MAX_ARITY, , 1))\n #include BOOST_PP_ITERATE()\n\n}\n\n#endif \/\/ LUABIND_CALL_MEMBER_HPP_INCLUDED\n\n#else\n#if BOOST_PP_ITERATION_FLAGS() == 1\n\n#define LUABIND_TUPLE_PARAMS(z, n, data) const A##n *\n#define LUABIND_OPERATOR_PARAMS(z, n, data) const A##n & a##n\n\n template\n typename boost::mpl::if_\n , luabind::detail::proxy_member_void_caller >\n , luabind::detail::proxy_member_caller > >::type\n call_member(object const& obj, const char* name BOOST_PP_COMMA_IF(BOOST_PP_ITERATION()) BOOST_PP_ENUM(BOOST_PP_ITERATION(), LUABIND_OPERATOR_PARAMS, _))\n {\n typedef boost::tuples::tuple tuple_t;\n#if BOOST_PP_ITERATION() == 0\n tuple_t args;\n#else\n tuple_t args(BOOST_PP_ENUM_PARAMS(BOOST_PP_ITERATION(), &a));\n#endif\n\n typedef typename boost::mpl::if_\n , luabind::detail::proxy_member_void_caller >\n , luabind::detail::proxy_member_caller > >::type proxy_type;\n\n \/\/ this will be cleaned up by the proxy object\n \/\/ once the call has been made\n\n \/\/ get the function\n obj.push(obj.interpreter());\n lua_pushstring(obj.interpreter(), name);\n lua_gettable(obj.interpreter(), -2);\n \/\/ duplicate the self-object\n lua_pushvalue(obj.interpreter(), -2);\n \/\/ remove the bottom self-object\n lua_remove(obj.interpreter(), -3);\n\n \/\/ now the function and self objects\n \/\/ are on the stack. These will both\n \/\/ be popped by pcall\n return proxy_type(obj.interpreter(), args);\n }\n\n#undef LUABIND_OPERATOR_PARAMS\n#undef LUABIND_TUPLE_PARAMS\n\n#endif\n#endif\nFix missing LUABIND_MAY_THROW in member caller.\/\/ Copyright (c) 2003 Daniel Wallin and Arvid Norberg\n\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a\n\/\/ copy of this software and associated documentation files (the \"Software\"),\n\/\/ to deal in the Software without restriction, including without limitation\n\/\/ the rights to use, copy, modify, merge, publish, distribute, sublicense,\n\/\/ and\/or sell copies of the Software, and to permit persons to whom the\n\/\/ Software is furnished to do so, subject to the following conditions:\n\n\/\/ The above copyright notice and this permission notice shall be included\n\/\/ in all copies or substantial portions of the Software.\n\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF\n\/\/ ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED\n\/\/ TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n\/\/ PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT\n\/\/ SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR\n\/\/ ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n\/\/ ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE\n\/\/ OR OTHER DEALINGS IN THE SOFTWARE.\n\n\n#if !BOOST_PP_IS_ITERATING\n\n#ifndef LUABIND_CALL_MEMBER_HPP_INCLUDED\n#define LUABIND_CALL_MEMBER_HPP_INCLUDED\n\n#include \n#include \n#include \n#include \n#include \n#include \/\/ TODO: REMOVE DEPENDENCY\n\n#include \n#include \n#include \n#include \n#include \n\nnamespace luabind\n{\n namespace detail\n {\n\n namespace mpl = boost::mpl;\n\n \/\/ if the proxy_member_caller returns non-void\n template\n class proxy_member_caller\n {\n\/\/ friend class luabind::object;\n public:\n\n proxy_member_caller(lua_State* L_, const Tuple args)\n : L(L_)\n , m_args(args)\n , m_called(false)\n {\n }\n\n proxy_member_caller(const proxy_member_caller& rhs)\n : L(rhs.L)\n , m_args(rhs.m_args)\n , m_called(rhs.m_called)\n {\n rhs.m_called = true;\n }\n\n ~proxy_member_caller() LUABIND_MAY_THROW\n {\n if (m_called) return;\n\n m_called = true;\n\n \/\/ don't count the function and self-reference\n \/\/ since those will be popped by pcall\n int top = lua_gettop(L) - 2;\n\n \/\/ pcall will pop the function and self reference\n \/\/ and all the parameters\n\n push_args_from_tuple<1>::apply(L, m_args);\n if (pcall(L, boost::tuples::length::value + 1, 0))\n {\n assert(lua_gettop(L) == top + 1);\n#ifndef LUABIND_NO_EXCEPTIONS\n throw luabind::error(L);\n#else\n error_callback_fun e = get_error_callback();\n if (e) e(L);\n\n assert(0 && \"the lua function threw an error and exceptions are disabled.\"\n \"If you want to handle this error use luabind::set_error_callback()\");\n std::terminate();\n#endif\n }\n \/\/ pops the return values from the function\n stack_pop pop(L, lua_gettop(L) - top);\n }\n\n operator Ret()\n {\n typename mpl::apply_wrap2::type converter;\n\n m_called = true;\n\n \/\/ don't count the function and self-reference\n \/\/ since those will be popped by pcall\n int top = lua_gettop(L) - 2;\n\n \/\/ pcall will pop the function and self reference\n \/\/ and all the parameters\n push_args_from_tuple<1>::apply(L, m_args);\n if (pcall(L, boost::tuples::length::value + 1, 1))\n {\n assert(lua_gettop(L) == top + 1);\n#ifndef LUABIND_NO_EXCEPTIONS\n throw luabind::error(L);\n#else\n error_callback_fun e = get_error_callback();\n if (e) e(L);\n\n assert(0 && \"the lua function threw an error and exceptions are disabled.\"\n \"If you want to handle this error use luabind::set_error_callback()\");\n std::terminate();\n#endif\n }\n\n \/\/ pops the return values from the function\n stack_pop pop(L, lua_gettop(L) - top);\n\n if (converter.match(L, LUABIND_DECORATE_TYPE(Ret), -1) < 0)\n {\n assert(lua_gettop(L) == top + 1);\n#ifndef LUABIND_NO_EXCEPTIONS\n throw cast_failed(L, typeid(Ret));\n#else\n cast_failed_callback_fun e = get_cast_failed_callback();\n if (e) e(L, typeid(Ret));\n\n assert(0 && \"the lua function's return value could not be converted.\"\n \"If you want to handle this error use luabind::set_error_callback()\");\n std::terminate();\n#endif\n }\n\n return converter.apply(L, LUABIND_DECORATE_TYPE(Ret), -1);\n }\n\n template\n Ret operator[](const Policies& p)\n {\n typedef typename find_conversion_policy<0, Policies>::type converter_policy;\n typename mpl::apply_wrap2::type converter;\n\n m_called = true;\n\n \/\/ don't count the function and self-reference\n \/\/ since those will be popped by pcall\n int top = lua_gettop(L) - 2;\n\n \/\/ pcall will pop the function and self reference\n \/\/ and all the parameters\n\n detail::push_args_from_tuple<1>::apply(L, m_args, p);\n if (pcall(L, boost::tuples::length::value + 1, 1))\n {\n assert(lua_gettop(L) == top + 1);\n#ifndef LUABIND_NO_EXCEPTIONS\n throw error(L);\n#else\n error_callback_fun e = get_error_callback();\n if (e) e(L);\n\n assert(0 && \"the lua function threw an error and exceptions are disabled.\"\n \"If you want to handle this error use luabind::set_error_callback()\");\n std::terminate();\n#endif\n }\n\n \/\/ pops the return values from the function\n stack_pop pop(L, lua_gettop(L) - top);\n\n if (converter.match(L, LUABIND_DECORATE_TYPE(Ret), -1) < 0)\n {\n assert(lua_gettop(L) == top + 1);\n#ifndef LUABIND_NO_EXCEPTIONS\n throw cast_failed(L, typeid(Ret));\n#else\n cast_failed_callback_fun e = get_cast_failed_callback();\n if (e) e(L, typeid(Ret));\n\n assert(0 && \"the lua function's return value could not be converted.\"\n \"If you want to handle this error use luabind::set_error_callback()\");\n std::terminate();\n#endif\n }\n return converter.apply(L, LUABIND_DECORATE_TYPE(Ret), -1);\n }\n\n private:\n\n lua_State* L;\n Tuple m_args;\n mutable bool m_called;\n\n };\n\n \/\/ if the proxy_member_caller returns void\n template\n class proxy_member_void_caller\n {\n friend class luabind::object;\n public:\n\n proxy_member_void_caller(lua_State* L_, const Tuple args)\n : L(L_)\n , m_args(args)\n , m_called(false)\n {\n }\n\n proxy_member_void_caller(const proxy_member_void_caller& rhs)\n : L(rhs.L)\n , m_args(rhs.m_args)\n , m_called(rhs.m_called)\n {\n rhs.m_called = true;\n }\n\n ~proxy_member_void_caller()\n {\n if (m_called) return;\n\n m_called = true;\n\n \/\/ don't count the function and self-reference\n \/\/ since those will be popped by pcall\n int top = lua_gettop(L) - 2;\n\n \/\/ pcall will pop the function and self reference\n \/\/ and all the parameters\n\n push_args_from_tuple<1>::apply(L, m_args);\n if (pcall(L, boost::tuples::length::value + 1, 0))\n {\n assert(lua_gettop(L) == top + 1);\n#ifndef LUABIND_NO_EXCEPTIONS\n throw luabind::error(L);\n#else\n error_callback_fun e = get_error_callback();\n if (e) e(L);\n\n assert(0 && \"the lua function threw an error and exceptions are disabled.\"\n \"If you want to handle this error use luabind::set_error_callback()\");\n std::terminate();\n#endif\n }\n \/\/ pops the return values from the function\n stack_pop pop(L, lua_gettop(L) - top);\n }\n\n template\n void operator[](const Policies& p)\n {\n m_called = true;\n\n \/\/ don't count the function and self-reference\n \/\/ since those will be popped by pcall\n int top = lua_gettop(L) - 2;\n\n \/\/ pcall will pop the function and self reference\n \/\/ and all the parameters\n\n detail::push_args_from_tuple<1>::apply(L, m_args, p);\n if (pcall(L, boost::tuples::length::value + 1, 0))\n {\n assert(lua_gettop(L) == top + 1);\n#ifndef LUABIND_NO_EXCEPTIONS\n throw error(L);\n#else\n error_callback_fun e = get_error_callback();\n if (e) e(L);\n\n assert(0 && \"the lua function threw an error and exceptions are disabled.\"\n \"If you want to handle this error use luabind::set_error_callback()\");\n std::terminate();\n#endif\n }\n \/\/ pops the return values from the function\n stack_pop pop(L, lua_gettop(L) - top);\n }\n\n private:\n lua_State* L;\n Tuple m_args;\n mutable bool m_called;\n\n };\n\n } \/\/ detail\n\n #define BOOST_PP_ITERATION_PARAMS_1 (4, (0, LUABIND_MAX_ARITY, , 1))\n #include BOOST_PP_ITERATE()\n\n}\n\n#endif \/\/ LUABIND_CALL_MEMBER_HPP_INCLUDED\n\n#else\n#if BOOST_PP_ITERATION_FLAGS() == 1\n\n#define LUABIND_TUPLE_PARAMS(z, n, data) const A##n *\n#define LUABIND_OPERATOR_PARAMS(z, n, data) const A##n & a##n\n\n template\n typename boost::mpl::if_\n , luabind::detail::proxy_member_void_caller >\n , luabind::detail::proxy_member_caller > >::type\n call_member(object const& obj, const char* name BOOST_PP_COMMA_IF(BOOST_PP_ITERATION()) BOOST_PP_ENUM(BOOST_PP_ITERATION(), LUABIND_OPERATOR_PARAMS, _))\n {\n typedef boost::tuples::tuple tuple_t;\n#if BOOST_PP_ITERATION() == 0\n tuple_t args;\n#else\n tuple_t args(BOOST_PP_ENUM_PARAMS(BOOST_PP_ITERATION(), &a));\n#endif\n\n typedef typename boost::mpl::if_\n , luabind::detail::proxy_member_void_caller >\n , luabind::detail::proxy_member_caller > >::type proxy_type;\n\n \/\/ this will be cleaned up by the proxy object\n \/\/ once the call has been made\n\n \/\/ get the function\n obj.push(obj.interpreter());\n lua_pushstring(obj.interpreter(), name);\n lua_gettable(obj.interpreter(), -2);\n \/\/ duplicate the self-object\n lua_pushvalue(obj.interpreter(), -2);\n \/\/ remove the bottom self-object\n lua_remove(obj.interpreter(), -3);\n\n \/\/ now the function and self objects\n \/\/ are on the stack. These will both\n \/\/ be popped by pcall\n return proxy_type(obj.interpreter(), args);\n }\n\n#undef LUABIND_OPERATOR_PARAMS\n#undef LUABIND_TUPLE_PARAMS\n\n#endif\n#endif\n<|endoftext|>"} {"text":"#include \"WatchdogProcessView.h\"\n#include \"ui_WatchdogProcessView.h\"\n\nWatchdogProcessView::WatchdogProcessView(QWidget *parent) :\n QWidget(parent),\n m_ui(new Ui::WatchdogProcessView)\n{\n m_ui->setupUi(this);\n}\n\nWatchdogProcessView::~WatchdogProcessView()\n{\n delete m_ui;\n}\n\nvoid WatchdogProcessView::changeEvent(QEvent *e)\n{\n QWidget::changeEvent(e);\n switch (e->type()) {\n case QEvent::LanguageChange:\n m_ui->retranslateUi(this);\n break;\n default:\n break;\n }\n}\nFixed minor compile error#include \"WatchdogProcessView.h\"\n#include \"ui_WatchdogProcessView.h\"\n\nWatchdogProcessView::WatchdogProcessView(int processid, QWidget *parent) :\n QWidget(parent),\n m_ui(new Ui::WatchdogProcessView)\n{\n m_ui->setupUi(this);\n}\n\nWatchdogProcessView::~WatchdogProcessView()\n{\n delete m_ui;\n}\n\nvoid WatchdogProcessView::changeEvent(QEvent *e)\n{\n QWidget::changeEvent(e);\n switch (e->type()) {\n case QEvent::LanguageChange:\n m_ui->retranslateUi(this);\n break;\n default:\n break;\n }\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/extensions\/browser_extension_window_controller.h\"\n\n#include \"chrome\/browser\/extensions\/api\/tabs\/tabs_constants.h\"\n#include \"chrome\/browser\/extensions\/extension_tab_util.h\"\n#include \"chrome\/browser\/extensions\/window_controller_list.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/browser\/sessions\/session_id.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/browser\/ui\/browser_tabstrip.h\"\n#include \"chrome\/browser\/ui\/browser_window.h\"\n#include \"chrome\/common\/extensions\/extension.h\"\n\nBrowserExtensionWindowController::BrowserExtensionWindowController(\n Browser* browser)\n : extensions::WindowController(browser->window(), browser->profile()),\n browser_(browser) {\n extensions::WindowControllerList::GetInstance()->AddExtensionWindow(this);\n}\n\nBrowserExtensionWindowController::~BrowserExtensionWindowController() {\n extensions::WindowControllerList::GetInstance()->RemoveExtensionWindow(this);\n}\n\nint BrowserExtensionWindowController::GetWindowId() const {\n return static_cast(browser_->session_id().id());\n}\n\nnamespace keys = extensions::tabs_constants;\n\nstd::string BrowserExtensionWindowController::GetWindowTypeText() const {\n if (browser_->is_type_popup())\n return keys::kWindowTypeValuePopup;\n if (browser_->is_type_panel())\n return keys::kWindowTypeValuePanel;\n if (browser_->is_app())\n return keys::kWindowTypeValueApp;\n return keys::kWindowTypeValueNormal;\n}\n\nbase::DictionaryValue*\nBrowserExtensionWindowController::CreateWindowValue() const {\n DictionaryValue* result = extensions::WindowController::CreateWindowValue();\n return result;\n}\n\nbase::DictionaryValue*\nBrowserExtensionWindowController::CreateWindowValueWithTabs(\n const extensions::Extension* extension) const {\n DictionaryValue* result = CreateWindowValue();\n\n result->Set(keys::kTabsKey, ExtensionTabUtil::CreateTabList(browser_,\n extension));\n\n return result;\n}\n\nbool BrowserExtensionWindowController::CanClose(Reason* reason) const {\n \/\/ Don't let an extension remove the window if the user is dragging tabs\n \/\/ in that window.\n if (!chrome::IsTabStripEditable(browser_)) {\n *reason = extensions::WindowController::REASON_NOT_EDITABLE;\n return false;\n }\n return true;\n}\n\nvoid BrowserExtensionWindowController::SetFullscreenMode(\n bool is_fullscreen,\n const GURL& extension_url) const {\n if (browser_->window()->IsFullscreen() != is_fullscreen)\n browser_->ToggleFullscreenModeWithExtension(extension_url);\n}\n\nBrowser* BrowserExtensionWindowController::GetBrowser() const {\n return browser_;\n}\n\nbool BrowserExtensionWindowController::IsVisibleToExtension(\n const extensions::Extension* extension) const {\n \/\/ Platform apps can only see their own windows.\n \/\/ TODO(mihaip): what about non-Aura panels?\n return !extension->is_platform_app();\n}\nRemove obsolete TODO about browser-based panels.\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/extensions\/browser_extension_window_controller.h\"\n\n#include \"chrome\/browser\/extensions\/api\/tabs\/tabs_constants.h\"\n#include \"chrome\/browser\/extensions\/extension_tab_util.h\"\n#include \"chrome\/browser\/extensions\/window_controller_list.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/browser\/sessions\/session_id.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/browser\/ui\/browser_tabstrip.h\"\n#include \"chrome\/browser\/ui\/browser_window.h\"\n#include \"chrome\/common\/extensions\/extension.h\"\n\nBrowserExtensionWindowController::BrowserExtensionWindowController(\n Browser* browser)\n : extensions::WindowController(browser->window(), browser->profile()),\n browser_(browser) {\n extensions::WindowControllerList::GetInstance()->AddExtensionWindow(this);\n}\n\nBrowserExtensionWindowController::~BrowserExtensionWindowController() {\n extensions::WindowControllerList::GetInstance()->RemoveExtensionWindow(this);\n}\n\nint BrowserExtensionWindowController::GetWindowId() const {\n return static_cast(browser_->session_id().id());\n}\n\nnamespace keys = extensions::tabs_constants;\n\nstd::string BrowserExtensionWindowController::GetWindowTypeText() const {\n if (browser_->is_type_popup())\n return keys::kWindowTypeValuePopup;\n if (browser_->is_type_panel())\n return keys::kWindowTypeValuePanel;\n if (browser_->is_app())\n return keys::kWindowTypeValueApp;\n return keys::kWindowTypeValueNormal;\n}\n\nbase::DictionaryValue*\nBrowserExtensionWindowController::CreateWindowValue() const {\n DictionaryValue* result = extensions::WindowController::CreateWindowValue();\n return result;\n}\n\nbase::DictionaryValue*\nBrowserExtensionWindowController::CreateWindowValueWithTabs(\n const extensions::Extension* extension) const {\n DictionaryValue* result = CreateWindowValue();\n\n result->Set(keys::kTabsKey, ExtensionTabUtil::CreateTabList(browser_,\n extension));\n\n return result;\n}\n\nbool BrowserExtensionWindowController::CanClose(Reason* reason) const {\n \/\/ Don't let an extension remove the window if the user is dragging tabs\n \/\/ in that window.\n if (!chrome::IsTabStripEditable(browser_)) {\n *reason = extensions::WindowController::REASON_NOT_EDITABLE;\n return false;\n }\n return true;\n}\n\nvoid BrowserExtensionWindowController::SetFullscreenMode(\n bool is_fullscreen,\n const GURL& extension_url) const {\n if (browser_->window()->IsFullscreen() != is_fullscreen)\n browser_->ToggleFullscreenModeWithExtension(extension_url);\n}\n\nBrowser* BrowserExtensionWindowController::GetBrowser() const {\n return browser_;\n}\n\nbool BrowserExtensionWindowController::IsVisibleToExtension(\n const extensions::Extension* extension) const {\n \/\/ Platform apps can only see their own windows.\n return !extension->is_platform_app();\n}\n<|endoftext|>"} {"text":"#ifdef NL_DATA_CONTAINER_H_\n\n#include \"NL_DataContainer.h\"\n\nnamespace NLE\n{\n\tnamespace Core\n\t{\n\t\ttemplate\n\t\tDataContainer::DataContainer() :\n\t\t\t_sysId(-1),\n\t\t\t_dataPool(),\n\t\t\t_data(_dataPool),\n\t\t\t_updateQueue(),\n\t\t\t_distributor(nullptr)\n\t\t{\n\t\t}\n\n\t\ttemplate\n\t\tDataContainer::~DataContainer()\n\t\t{\n\t\t}\n\n\t\ttemplate\n\t\tbool DataContainer::initialize(uint_fast8_t sysId, uint_fast8_t initSize)\n\t\t{\n\t\t\t_sysId = sysId;\n\t\t\t_data.reserve(initSize);\n\t\t\treturn true;\n\t\t}\n\n\t\ttemplate\n\t\tvoid DataContainer::release()\n\t\t{\n\t\t\t_data.clear();\n\t\t\t_dataPool.recycle();\n\t\t}\n\n\t\ttemplate\n\t\tvoid DataContainer::bindDistributor(DataDistributor* distributor)\n\t\t{\n\t\t\t_distributor = distributor;\n\t\t}\n\n\t\ttemplate\n\t\tinline void add(T data)\n\t\t{\n\t\t\t_data.push_back(data);\n\t\t}\n\n\t\ttemplate\n\t\tvoid DataContainer::remove(uint_fast8_t index)\n\t\t{\n\t\t\tuint_fast8_t size = _data.size();\n\t\t\tif (index < size)\n\t\t\t{\n\t\t\t\tuint_fast8_t lastOccupied = size - 1;\n\t\t\t\tif (index != lastOccupied)\n\t\t\t\t{\n\t\t\t\t\t_data[index] = _data[lastOccupied];\n\t\t\t\t}\n\t\t\t\t_data.pop_back();\n\t\t\t}\n\t\t}\n\n\t\ttemplate\n\t\tvoid DataContainer::modify(uint_fast8_t index, T data)\n\t\t{\n\t\t\t_data[index] = data;\n\t\t\tif (_distributor)\n\t\t\t{\n\t\t\t\t_distributor->queue({ _sysId, index, data });\n\t\t\t}\n\t\t}\n\n\t\ttemplate\n\t\tinline void DataContainer::clear()\n\t\t{\n\t\t\t_data.clear();\n\t\t}\n\n\t\ttemplate\n\t\tinline uint_fast8_t DataContainer::size()\n\t\t{\n\t\t\treturn _data.size();\n\t\t}\n\n\t\ttemplate\n\t\tinline T& DataContainer::get(uint_fast8_t index)\n\t\t{\n\t\t\treturn _data[index];\n\t\t}\n\n\t\ttemplate\n\t\tinline void DataContainer::queuePacket(DataPacket packet)\n\t\t{\n\t\t\t_updateQueue.push(packet);\n\t\t}\n\n\t\ttemplate\n\t\tvoid DataContainer::applyUpdates()\n\t\t{\n\t\t\tDataPacket packet;\n\t\t\twhile (_updateQueue.try_pop(packet))\n\t\t\t{\n\t\t\t\tmodify(packet.getItemNumber(), packet.getData());\n\t\t\t}\n\t\t}\n\t}\n}\n\n#endifbug fix: applying container update distributes data#ifdef NL_DATA_CONTAINER_H_\n\n#include \"NL_DataContainer.h\"\n\nnamespace NLE\n{\n\tnamespace Core\n\t{\n\t\ttemplate\n\t\tDataContainer::DataContainer() :\n\t\t\t_sysId(-1),\n\t\t\t_dataPool(),\n\t\t\t_data(_dataPool),\n\t\t\t_updateQueue(),\n\t\t\t_distributor(nullptr)\n\t\t{\n\t\t}\n\n\t\ttemplate\n\t\tDataContainer::~DataContainer()\n\t\t{\n\t\t}\n\n\t\ttemplate\n\t\tbool DataContainer::initialize(uint_fast8_t sysId, uint_fast8_t initSize)\n\t\t{\n\t\t\t_sysId = sysId;\n\t\t\t_data.reserve(initSize);\n\t\t\treturn true;\n\t\t}\n\n\t\ttemplate\n\t\tvoid DataContainer::release()\n\t\t{\n\t\t\t_data.clear();\n\t\t\t_dataPool.recycle();\n\t\t}\n\n\t\ttemplate\n\t\tvoid DataContainer::bindDistributor(DataDistributor* distributor)\n\t\t{\n\t\t\t_distributor = distributor;\n\t\t}\n\n\t\ttemplate\n\t\tinline void add(T data)\n\t\t{\n\t\t\t_data.push_back(data);\n\t\t}\n\n\t\ttemplate\n\t\tvoid DataContainer::remove(uint_fast8_t index)\n\t\t{\n\t\t\tuint_fast8_t size = _data.size();\n\t\t\tif (index < size)\n\t\t\t{\n\t\t\t\tuint_fast8_t lastOccupied = size - 1;\n\t\t\t\tif (index != lastOccupied)\n\t\t\t\t{\n\t\t\t\t\t_data[index] = _data[lastOccupied];\n\t\t\t\t}\n\t\t\t\t_data.pop_back();\n\t\t\t}\n\t\t}\n\n\t\ttemplate\n\t\tvoid DataContainer::modify(uint_fast8_t index, T data)\n\t\t{\n\t\t\t_data[index] = data;\n\t\t\tif (_distributor)\n\t\t\t{\n\t\t\t\t_distributor->queue({ _sysId, index, data });\n\t\t\t}\n\t\t}\n\n\t\ttemplate\n\t\tinline void DataContainer::clear()\n\t\t{\n\t\t\t_data.clear();\n\t\t}\n\n\t\ttemplate\n\t\tinline uint_fast8_t DataContainer::size()\n\t\t{\n\t\t\treturn _data.size();\n\t\t}\n\n\t\ttemplate\n\t\tinline T& DataContainer::get(uint_fast8_t index)\n\t\t{\n\t\t\treturn _data[index];\n\t\t}\n\n\t\ttemplate\n\t\tinline void DataContainer::queuePacket(DataPacket packet)\n\t\t{\n\t\t\t_updateQueue.push(packet);\n\t\t}\n\n\t\ttemplate\n\t\tvoid DataContainer::applyUpdates()\n\t\t{\n\t\t\tDataPacket packet;\n\t\t\twhile (_updateQueue.try_pop(packet))\n\t\t\t{\n\t\t\t\t_data[packet.getItemNumber()] = packet.getData();\n\t\t\t}\n\t\t}\n\t}\n}\n\n#endif<|endoftext|>"} {"text":"#include \"unit_tests\/suite\/lumix_unit_tests.h\"\n\n#include \"engine\/log.h\"\n#ifdef _WIN32\n\t#include \"engine\/win\/simple_win.h\"\n#endif\n#include \n\n\nnamespace Lumix\n{\n\tnamespace UnitTest\n\t{\n\t\tvoid outputToVS(const char* system, const char* message)\n\t\t{\n\t\t\tchar tmp[2048];\n\t\t\tcopyString(tmp, system);\n\t\t\tcatString(tmp, \": \");\n\t\t\tcatString(tmp, message);\n\t\t\tcatString(tmp, \"\\r\");\n\t\t\t\n\t\t\t#ifdef _WIN32\n\t\t\t\tOutputDebugString(tmp);\n\t\t\t#endif\n\t\t}\n\n\t\tvoid outputToConsole(const char* system, const char* message)\n\t\t{\n\t\t\tprintf(\"%s: %s\\n\", system, message);\n\t\t}\n\n\t\tvoid App::init()\n\t\t{\n\t\t\tg_log_info.getCallback().bind();\n\t\t\tg_log_warning.getCallback().bind();\n\t\t\tg_log_error.getCallback().bind();\n\n\t\t\tg_log_info.getCallback().bind();\n\t\t\tg_log_warning.getCallback().bind();\n\t\t\tg_log_error.getCallback().bind();\n\t\t}\n\n\t\tvoid App::run(int argc, const char *argv[])\n\t\t{\n\t\t\tManager::instance().dumpTests();\n\t\t\tManager::instance().runTests(\"unit_tests\/engine\/universe\/hierarchy3\");\n\t\t\tManager::instance().dumpResults();\n\t\t}\n\n\t\tvoid App::exit()\n\t\t{\n\t\t\tManager::release();\n\t\t}\n\t} \/\/~UnitTest\n} \/\/~UnitTestfixed unit tests#include \"unit_tests\/suite\/lumix_unit_tests.h\"\n\n#include \"engine\/log.h\"\n#ifdef _WIN32\n\t#include \"engine\/win\/simple_win.h\"\n#endif\n#include \n\n\nnamespace Lumix\n{\n\tnamespace UnitTest\n\t{\n\t\tvoid outputToVS(const char* system, const char* message)\n\t\t{\n\t\t\tchar tmp[2048];\n\t\t\tcopyString(tmp, system);\n\t\t\tcatString(tmp, \": \");\n\t\t\tcatString(tmp, message);\n\t\t\tcatString(tmp, \"\\r\");\n\t\t\t\n\t\t\t#ifdef _WIN32\n\t\t\t\tOutputDebugString(tmp);\n\t\t\t#endif\n\t\t}\n\n\t\tvoid outputToConsole(const char* system, const char* message)\n\t\t{\n\t\t\tprintf(\"%s: %s\\n\", system, message);\n\t\t}\n\n\t\tvoid App::init()\n\t\t{\n\t\t\tg_log_info.getCallback().bind();\n\t\t\tg_log_warning.getCallback().bind();\n\t\t\tg_log_error.getCallback().bind();\n\n\t\t\tg_log_info.getCallback().bind();\n\t\t\tg_log_warning.getCallback().bind();\n\t\t\tg_log_error.getCallback().bind();\n\t\t}\n\n\t\tvoid App::run(int argc, const char *argv[])\n\t\t{\n\t\t\tManager::instance().dumpTests();\n\t\t\tManager::instance().runTests(\"*\");\n\t\t\tManager::instance().dumpResults();\n\t\t}\n\n\t\tvoid App::exit()\n\t\t{\n\t\t\tManager::release();\n\t\t}\n\t} \/\/~UnitTest\n} \/\/~UnitTest<|endoftext|>"} {"text":"#include \"NL_ImguiEditorUiManager.h\"\n#include \"NL_ThreadLocal.h\"\n#include \"NL_EngineServices.h\"\n#include \"NL_SharedData.h\"\n#include \"NL_SystemServices.h\"\n#include \"NL_InputEvents.h\"\n#include \"NL_ImguiInputMap.h\"\n\n#include \n#include \n#include \n#include \n\nnamespace NLE\n{\n\tnamespace UI\n\t{\n\t\tImguiEditorUiManager::ImguiEditorUiManager(\n\t\t\tEngineServices& eServices,\n\t\t\tCONSOLE::IConsoleQueue& consoleQueue,\n\t\t\tIWindowManager& windowManager,\n\t\t\tGAME::IGameManager& gameManager,\n\t\t\tINPUT::IInputProcessor& inputProcessor,\n\t\t\tGRAPHICS::IRenderingEngine& renderingEngine,\n\t\t\tSCRIPT::IScriptingEngine& scriptingEngine)\n\t\t\t:\n\t\t\t_eServices(eServices),\n\t\t\t_consoleQueue(consoleQueue),\n\t\t\t_windowManager(windowManager),\n\t\t\t_gameManager(gameManager),\n\t\t\t_inputProcessor(inputProcessor),\n\t\t\t_renderingEngine(renderingEngine),\n\t\t\t_scriptingEngine(scriptingEngine),\n\n\t\t\t_showEditor(true),\n\t\t\t_showEditorSettings(false),\n\n\t\t\t_windowBgColor(0.0f, 0.0f, 1.0f, 0.5f),\n\t\t\t_textColor(0.0f, 1.0f, 0.0f, 1.0f),\n\t\t\t_borderColor(0.0f, 1.0f, 0.0f, 1.0f),\n\t\t\t_itemColor(0.0f, 0.0f, 1.0f, 0.5f),\n\t\t\t_itemHoverColor(0.0f, 0.0f, 1.0f, 0.8f),\n\t\t\t_itemActiveColor(0.0f, 0.0f, 1.0f, 0.8f),\n\t\t\t_selectionColor(1.0f, 1.0f, 1.0f, 0.8f)\n\t\t{\n\t\t}\n\n\t\tImguiEditorUiManager::~ImguiEditorUiManager()\n\t\t{\n\t\t}\n\n\t\tbool ImguiEditorUiManager::initialize()\n\t\t{\n\t\t\treturn true;\n\t\t}\n\n\t\tint ImguiEditorUiManager::getScancodeForKeyEvent(INPUT::Event event)\n\t\t{\n\t\t\tassert(event.eventType == INPUT::EVENT_KEY);\n\t\t\tImGuiIO& io = ImGui::GetIO();\n\n\t\t\tauto key = INPUT::NLEtoImguiKey(event.eventData.keyEvent.key);\n\t\t\tif (key == -1)\n\t\t\t\treturn event.eventData.keyEvent.scancode;\n\n\t\t\tif (io.KeyMap[key] == -1)\n\t\t\t\tio.KeyMap[key] = event.eventData.keyEvent.scancode;\n\n\t\t\treturn io.KeyMap[key];\n\t\t}\n\n\t\tImDrawData* ImguiEditorUiManager::getDrawData()\n\t\t{\n\t\t\treturn ImGui::GetDrawData();\n\t\t}\n\n\t\tvoid ImguiEditorUiManager::queueKeyAndCharEvent(INPUT::Event event)\n\t\t{\n\t\t\t_keyAndCharEvents.push(event);\n\t\t}\n\n\t\tvoid ImguiEditorUiManager::update(SystemServices* sServices, double deltaT, Size2D screenSize)\n\t\t{\n\t\t\tNLE::TLS::PerformanceTimer::reference timer = NLE::TLS::performanceTimer.local();\n\t\t\ttimer.deltaT();\n\n\t\t\tDATA::SharedData& data = _eServices.data->getData();\n\t\t\tImGuiIO& io = ImGui::GetIO();\n\t\t\tio.DisplaySize = ImVec2((float)screenSize.width, (float)screenSize.height);\n\t\t\tio.DeltaTime = (float)(deltaT * 0.000000001);\n\n\t\t\t\/\/Need crossplatform implementation\n\t\t\t\/\/ Hide OS mouse cursor if ImGui is drawing it\n\t\t\t\/\/SetCursor(io.MouseDrawCursor ? NULL : LoadCursor(NULL, IDC_ARROW));\n\n\t\t\tcaptureInput(sServices, deltaT, screenSize);\n\t\t\tImGui::NewFrame();\n\t\t\tdrawUI(sServices, screenSize);\n\t\t\tImGui::Render();\n\n\t\t\tdata.sysExecutionTimes.set(UI_MANAGER, timer.deltaT());\n\t\t}\n\n\t\tvoid ImguiEditorUiManager::captureInput(SystemServices* sServices, double deltaT, Size2D screenSize)\n\t\t{\n\t\t\tDATA::SharedData& data = _eServices.data->getData();\n\t\t\tImGuiIO& io = ImGui::GetIO();\n\n\t\t\tio.MouseDown[0] = data.mouseButtonPressed.get()[INPUT::MOUSE_BUTTON_LEFT];\n\t\t\tio.MouseDown[1] = data.mouseButtonPressed.get()[INPUT::MOUSE_BUTTON_RIGHT];\n\t\t\tio.MouseDown[2] = data.mouseButtonPressed.get()[INPUT::MOUSE_BUTTON_MIDDLE];\n\t\t\tio.MouseWheel += (float)data.scrollOffset.get()[1];\n\t\t\tio.MousePos.x = (float)data.mouseCursorPosition.get()[0];\n\t\t\tio.MousePos.y = (float)data.mouseCursorPosition.get()[1];\n\n\t\t\tINPUT::Event event;\n\t\t\twhile (_keyAndCharEvents.pop(event))\n\t\t\t{\n\t\t\t\tif (event.eventType == INPUT::EVENT_KEY)\n\t\t\t\t{\n\t\t\t\t\tint scancode = getScancodeForKeyEvent(event);\n\t\t\t\t\tio.KeysDown[scancode] = event.eventData.keyEvent.action == INPUT::ACTION_PRESS ? 1 : 0;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tio.AddInputCharacter((unsigned short)event.eventData.charEvent.code);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tio.KeyCtrl = data.keyModsPressed.get()[INPUT::KEY_MOD_CONTROL];\n\t\t\tio.KeyShift = data.keyModsPressed.get()[INPUT::KEY_MOD_SHIFT];\n\t\t\tio.KeyAlt = data.keyModsPressed.get()[INPUT::KEY_MOD_ALT];\n\t\t\tio.KeySuper = data.keyModsPressed.get()[INPUT::KEY_MOD_SUPER];\n\t\t}\n\n\t\tvoid ImguiEditorUiManager::drawUI(SystemServices* sServices, Size2D screenSize)\n\t\t{\n\t\t\tImGuiWindowFlags window_flags = 0;\n\t\t\twindow_flags |= ImGuiWindowFlags_NoTitleBar;\n\t\t\twindow_flags |= ImGuiWindowFlags_NoResize;\n\t\t\twindow_flags |= ImGuiWindowFlags_NoMove;\n\t\t\twindow_flags |= ImGuiWindowFlags_NoScrollbar;\n\t\t\twindow_flags |= ImGuiWindowFlags_NoCollapse;\n\t\t\twindow_flags |= ImGuiWindowFlags_MenuBar;\n\t\t\twindow_flags |= ImGuiWindowFlags_NoSavedSettings;\n\t\t\twindow_flags |= ImGuiWindowFlags_NoBringToFrontOnFocus;\n\n\t\t\tImGui::SetNextWindowPos(ImVec2(0,0));\n\t\t\tImGui::SetNextWindowSize(ImVec2((float)screenSize.width, (float)screenSize.height), ImGuiSetCond_FirstUseEver);\n\t\t\tImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f);\n\t\t\tapplyColorScheme(true);\n\t\t\tImGui::Begin(\"Engine UI Overlay Window\", &_showEditor, window_flags);\n\n\t\t\tif (ImGui::BeginMenuBar())\n\t\t\t{\n\t\t\t\tif (ImGui::BeginMenu(\"File\"))\n\t\t\t\t{\n\t\t\t\t\tImGui::EndMenu();\n\t\t\t\t}\n\t\t\t\tif (ImGui::BeginMenu(\"View\"))\n\t\t\t\t{\n\t\t\t\t\tImGui::MenuItem(\"Editor\", NULL, &_showEditorSettings);\n\t\t\t\t\tImGui::EndMenu();\n\t\t\t\t}\n\t\t\t\tImGui::EndMenuBar();\n\t\t\t}\n\n\t\t\tImGui::End();\n\t\t\trestoreColorScheme();\n\t\t\tImGui::PopStyleVar();\n\t\t\t\n\t\t\tif(_showEditorSettings)\n\t\t\t\tshowEditorSettings(sServices, screenSize);\n\t\t\t\n\t\t}\n\n\t\tvoid ImguiEditorUiManager::showEditorSettings(SystemServices* sServices, Size2D screenSize)\n\t\t{\n\t\t\tImGuiWindowFlags window_flags = 0;\n\t\t\twindow_flags |= ImGuiWindowFlags_NoSavedSettings;\n\t\t\twindow_flags |= ImGuiWindowFlags_AlwaysAutoResize;\n\n\t\t\tImGui::SetNextWindowPos(ImVec2((float)screenSize.width \/ 2, (float)screenSize.height \/ 2), ImGuiSetCond_FirstUseEver);\n\t\t\tImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f);\n\t\t\tapplyColorScheme(false);\n\t\t\tImGui::Begin(\"Editor Settings\", &_showEditorSettings, window_flags);\n\n\t\t\tif (ImGui::CollapsingHeader(\"Color Scheme\"))\n\t\t\t{\n\t\t\t\tImGui::ColorEdit4(\"Window Background\", (float*)&_windowBgColor);\n\t\t\t\tImGui::ColorEdit4(\"Text Color\", (float*)&_textColor);\n\t\t\t\tImGui::ColorEdit4(\"Border Color\", (float*)&_borderColor);\n\t\t\t\tImGui::ColorEdit4(\"Item Color\", (float*)&_itemColor);\n\t\t\t\tImGui::ColorEdit4(\"Item Hover Color\", (float*)&_itemHoverColor);\n\t\t\t\tImGui::ColorEdit4(\"Item Active Color\", (float*)&_itemActiveColor);\n\t\t\t\tImGui::ColorEdit4(\"Selection Color\", (float*)&_selectionColor);\n\t\t\t}\n\n\t\t\tImGui::End();\n\t\t\trestoreColorScheme();\n\t\t\tImGui::PopStyleVar();\n\t\t}\n\n\t\tvoid ImguiEditorUiManager::applyColorScheme(bool root)\n\t\t{\n\t\t\tif(root)\n\t\t\t\tImGui::PushStyleColor(ImGuiCol_WindowBg, ImColor(0.0f, 0.0f, 0.0f, 0.0f));\n\t\t\telse\n\t\t\t\tImGui::PushStyleColor(ImGuiCol_WindowBg, _windowBgColor);\n\n\t\t\tImGui::PushStyleColor(ImGuiCol_MenuBarBg, _windowBgColor);\n\t\t\tImGui::PushStyleColor(ImGuiCol_Text, _textColor);\n\t\t\tImGui::PushStyleColor(ImGuiCol_Border, _borderColor);\n\t\t\tImGui::PushStyleColor(ImGuiCol_Button, _itemColor);\n\t\t\tImGui::PushStyleColor(ImGuiCol_ButtonHovered, _itemHoverColor);\n\t\t\tImGui::PushStyleColor(ImGuiCol_ButtonActive, _itemActiveColor);\n\t\t\tImGui::PushStyleColor(ImGuiCol_Header, _itemColor);\n\t\t\tImGui::PushStyleColor(ImGuiCol_HeaderHovered, _itemHoverColor);\n\t\t\tImGui::PushStyleColor(ImGuiCol_HeaderActive, _itemActiveColor);\n\t\t\tImGui::PushStyleColor(ImGuiCol_FrameBg, _itemColor);\n\t\t\tImGui::PushStyleColor(ImGuiCol_FrameBgHovered, _itemHoverColor);\n\t\t\tImGui::PushStyleColor(ImGuiCol_FrameBgActive, _itemActiveColor);\n\t\t\tImGui::PushStyleColor(ImGuiCol_TitleBg, _itemColor);\n\t\t\tImGui::PushStyleColor(ImGuiCol_TitleBgCollapsed, _itemColor);\n\t\t\tImGui::PushStyleColor(ImGuiCol_TitleBgActive, _itemActiveColor);\n\t\t\tImGui::PushStyleColor(ImGuiCol_CloseButton, _itemColor);\n\t\t\tImGui::PushStyleColor(ImGuiCol_CloseButtonHovered, _itemHoverColor);\n\t\t\tImGui::PushStyleColor(ImGuiCol_CloseButtonActive, _itemActiveColor);\n\t\t\tImGui::PushStyleColor(ImGuiCol_TextSelectedBg, _selectionColor);\n\t\t}\n\n\t\tvoid ImguiEditorUiManager::restoreColorScheme()\n\t\t{\n\t\t\tImGui::PopStyleColor();\n\t\t\tImGui::PopStyleColor();\n\t\t\tImGui::PopStyleColor();\n\t\t\tImGui::PopStyleColor();\n\t\t\tImGui::PopStyleColor();\n\t\t\tImGui::PopStyleColor();\n\t\t\tImGui::PopStyleColor();\n\t\t\tImGui::PopStyleColor();\n\t\t\tImGui::PopStyleColor();\n\t\t\tImGui::PopStyleColor();\n\t\t\tImGui::PopStyleColor();\n\t\t\tImGui::PopStyleColor();\n\t\t\tImGui::PopStyleColor();\n\t\t\tImGui::PopStyleColor();\n\t\t\tImGui::PopStyleColor();\n\t\t\tImGui::PopStyleColor();\n\t\t\tImGui::PopStyleColor();\n\t\t\tImGui::PopStyleColor();\n\t\t\tImGui::PopStyleColor();\n\t\t\tImGui::PopStyleColor();\n\t\t}\n\n\t\tvoid ImguiEditorUiManager::show(bool show)\n\t\t{\n\t\t\t_showEditor = show;\n\t\t}\n\t}\n}added borders and fps counter#include \"NL_ImguiEditorUiManager.h\"\n#include \"NL_ThreadLocal.h\"\n#include \"NL_EngineServices.h\"\n#include \"NL_SharedData.h\"\n#include \"NL_SystemServices.h\"\n#include \"NL_InputEvents.h\"\n#include \"NL_ImguiInputMap.h\"\n\n#include \n#include \n#include \n#include \n\nnamespace NLE\n{\n\tnamespace UI\n\t{\n\t\tImguiEditorUiManager::ImguiEditorUiManager(\n\t\t\tEngineServices& eServices,\n\t\t\tCONSOLE::IConsoleQueue& consoleQueue,\n\t\t\tIWindowManager& windowManager,\n\t\t\tGAME::IGameManager& gameManager,\n\t\t\tINPUT::IInputProcessor& inputProcessor,\n\t\t\tGRAPHICS::IRenderingEngine& renderingEngine,\n\t\t\tSCRIPT::IScriptingEngine& scriptingEngine)\n\t\t\t:\n\t\t\t_eServices(eServices),\n\t\t\t_consoleQueue(consoleQueue),\n\t\t\t_windowManager(windowManager),\n\t\t\t_gameManager(gameManager),\n\t\t\t_inputProcessor(inputProcessor),\n\t\t\t_renderingEngine(renderingEngine),\n\t\t\t_scriptingEngine(scriptingEngine),\n\n\t\t\t_showEditor(true),\n\t\t\t_showEditorSettings(false),\n\n\t\t\t_windowBgColor(0.0f, 0.0f, 1.0f, 0.5f),\n\t\t\t_textColor(0.0f, 1.0f, 0.0f, 1.0f),\n\t\t\t_borderColor(0.0f, 1.0f, 0.0f, 1.0f),\n\t\t\t_itemColor(0.0f, 0.0f, 1.0f, 0.5f),\n\t\t\t_itemHoverColor(0.0f, 0.0f, 1.0f, 0.8f),\n\t\t\t_itemActiveColor(0.0f, 0.0f, 1.0f, 0.8f),\n\t\t\t_selectionColor(1.0f, 1.0f, 1.0f, 0.8f)\n\t\t{\n\t\t}\n\n\t\tImguiEditorUiManager::~ImguiEditorUiManager()\n\t\t{\n\t\t}\n\n\t\tbool ImguiEditorUiManager::initialize()\n\t\t{\n\t\t\treturn true;\n\t\t}\n\n\t\tint ImguiEditorUiManager::getScancodeForKeyEvent(INPUT::Event event)\n\t\t{\n\t\t\tassert(event.eventType == INPUT::EVENT_KEY);\n\t\t\tImGuiIO& io = ImGui::GetIO();\n\n\t\t\tauto key = INPUT::NLEtoImguiKey(event.eventData.keyEvent.key);\n\t\t\tif (key == -1)\n\t\t\t\treturn event.eventData.keyEvent.scancode;\n\n\t\t\tif (io.KeyMap[key] == -1)\n\t\t\t\tio.KeyMap[key] = event.eventData.keyEvent.scancode;\n\n\t\t\treturn io.KeyMap[key];\n\t\t}\n\n\t\tImDrawData* ImguiEditorUiManager::getDrawData()\n\t\t{\n\t\t\treturn ImGui::GetDrawData();\n\t\t}\n\n\t\tvoid ImguiEditorUiManager::queueKeyAndCharEvent(INPUT::Event event)\n\t\t{\n\t\t\t_keyAndCharEvents.push(event);\n\t\t}\n\n\t\tvoid ImguiEditorUiManager::update(SystemServices* sServices, double deltaT, Size2D screenSize)\n\t\t{\n\t\t\tNLE::TLS::PerformanceTimer::reference timer = NLE::TLS::performanceTimer.local();\n\t\t\ttimer.deltaT();\n\n\t\t\tDATA::SharedData& data = _eServices.data->getData();\n\t\t\tImGuiIO& io = ImGui::GetIO();\n\t\t\tio.DisplaySize = ImVec2((float)screenSize.width, (float)screenSize.height);\n\t\t\tio.DeltaTime = (float)(deltaT * 0.000000001);\n\n\t\t\t\/\/Need crossplatform implementation\n\t\t\t\/\/ Hide OS mouse cursor if ImGui is drawing it\n\t\t\t\/\/SetCursor(io.MouseDrawCursor ? NULL : LoadCursor(NULL, IDC_ARROW));\n\n\t\t\tcaptureInput(sServices, deltaT, screenSize);\n\t\t\tImGui::NewFrame();\n\t\t\tdrawUI(sServices, screenSize);\n\t\t\tImGui::Render();\n\n\t\t\tdata.sysExecutionTimes.set(UI_MANAGER, timer.deltaT());\n\t\t}\n\n\t\tvoid ImguiEditorUiManager::captureInput(SystemServices* sServices, double deltaT, Size2D screenSize)\n\t\t{\n\t\t\tDATA::SharedData& data = _eServices.data->getData();\n\t\t\tImGuiIO& io = ImGui::GetIO();\n\n\t\t\tio.MouseDown[0] = data.mouseButtonPressed.get()[INPUT::MOUSE_BUTTON_LEFT];\n\t\t\tio.MouseDown[1] = data.mouseButtonPressed.get()[INPUT::MOUSE_BUTTON_RIGHT];\n\t\t\tio.MouseDown[2] = data.mouseButtonPressed.get()[INPUT::MOUSE_BUTTON_MIDDLE];\n\t\t\tio.MouseWheel += (float)data.scrollOffset.get()[1];\n\t\t\tio.MousePos.x = (float)data.mouseCursorPosition.get()[0];\n\t\t\tio.MousePos.y = (float)data.mouseCursorPosition.get()[1];\n\n\t\t\tINPUT::Event event;\n\t\t\twhile (_keyAndCharEvents.pop(event))\n\t\t\t{\n\t\t\t\tif (event.eventType == INPUT::EVENT_KEY)\n\t\t\t\t{\n\t\t\t\t\tint scancode = getScancodeForKeyEvent(event);\n\t\t\t\t\tio.KeysDown[scancode] = event.eventData.keyEvent.action == INPUT::ACTION_PRESS ? 1 : 0;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tio.AddInputCharacter((unsigned short)event.eventData.charEvent.code);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tio.KeyCtrl = data.keyModsPressed.get()[INPUT::KEY_MOD_CONTROL];\n\t\t\tio.KeyShift = data.keyModsPressed.get()[INPUT::KEY_MOD_SHIFT];\n\t\t\tio.KeyAlt = data.keyModsPressed.get()[INPUT::KEY_MOD_ALT];\n\t\t\tio.KeySuper = data.keyModsPressed.get()[INPUT::KEY_MOD_SUPER];\n\t\t}\n\n\t\tvoid ImguiEditorUiManager::drawUI(SystemServices* sServices, Size2D screenSize)\n\t\t{\n\t\t\tImGuiWindowFlags window_flags = 0;\n\t\t\twindow_flags |= ImGuiWindowFlags_NoTitleBar;\n\t\t\twindow_flags |= ImGuiWindowFlags_NoResize;\n\t\t\twindow_flags |= ImGuiWindowFlags_NoMove;\n\t\t\twindow_flags |= ImGuiWindowFlags_NoScrollbar;\n\t\t\twindow_flags |= ImGuiWindowFlags_NoCollapse;\n\t\t\twindow_flags |= ImGuiWindowFlags_MenuBar;\n\t\t\twindow_flags |= ImGuiWindowFlags_NoSavedSettings;\n\t\t\twindow_flags |= ImGuiWindowFlags_NoBringToFrontOnFocus;\n\n\t\t\tImGui::SetNextWindowPos(ImVec2(0,0));\n\t\t\tImGui::SetNextWindowSize(ImVec2((float)screenSize.width, (float)screenSize.height), ImGuiSetCond_FirstUseEver);\n\t\t\tImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f);\n\t\t\tapplyColorScheme(true);\n\t\t\tImGui::Begin(\"Engine UI Overlay Window\", &_showEditor, window_flags);\n\n\t\t\tif (ImGui::BeginMenuBar())\n\t\t\t{\n\t\t\t\tif (ImGui::BeginMenu(\"File\"))\n\t\t\t\t{\n\t\t\t\t\tImGui::EndMenu();\n\t\t\t\t}\n\t\t\t\tif (ImGui::BeginMenu(\"View\"))\n\t\t\t\t{\n\t\t\t\t\tImGui::MenuItem(\"Editor\", NULL, &_showEditorSettings);\n\t\t\t\t\tImGui::EndMenu();\n\t\t\t\t}\n\t\t\t\tImGui::SameLine(ImGui::GetWindowWidth() - 100);\n\t\t\t\tImGui::Text(\"%.1f FPS\", ImGui::GetIO().Framerate);\n\t\t\t\tImGui::EndMenuBar();\n\t\t\t}\n\n\t\t\tImGui::End();\n\t\t\trestoreColorScheme();\n\t\t\tImGui::PopStyleVar();\n\t\t\t\n\t\t\tif(_showEditorSettings)\n\t\t\t\tshowEditorSettings(sServices, screenSize);\n\t\t\t\n\t\t}\n\n\t\tvoid ImguiEditorUiManager::showEditorSettings(SystemServices* sServices, Size2D screenSize)\n\t\t{\n\t\t\tImGuiWindowFlags window_flags = 0;\n\t\t\twindow_flags |= ImGuiWindowFlags_NoSavedSettings;\n\t\t\twindow_flags |= ImGuiWindowFlags_AlwaysAutoResize;\n\t\t\twindow_flags |= ImGuiWindowFlags_ShowBorders;\n\n\t\t\tImGui::SetNextWindowPos(ImVec2((float)screenSize.width \/ 2, (float)screenSize.height \/ 2), ImGuiSetCond_FirstUseEver);\n\t\t\tImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f);\n\t\t\tapplyColorScheme(false);\n\t\t\tImGui::Begin(\"Editor Settings\", &_showEditorSettings, window_flags);\n\n\t\t\tif (ImGui::CollapsingHeader(\"Color Scheme\"))\n\t\t\t{\n\t\t\t\tImGui::ColorEdit4(\"Window Background\", (float*)&_windowBgColor);\n\t\t\t\tImGui::ColorEdit4(\"Text Color\", (float*)&_textColor);\n\t\t\t\tImGui::ColorEdit4(\"Border Color\", (float*)&_borderColor);\n\t\t\t\tImGui::ColorEdit4(\"Item Color\", (float*)&_itemColor);\n\t\t\t\tImGui::ColorEdit4(\"Item Hover Color\", (float*)&_itemHoverColor);\n\t\t\t\tImGui::ColorEdit4(\"Item Active Color\", (float*)&_itemActiveColor);\n\t\t\t\tImGui::ColorEdit4(\"Selection Color\", (float*)&_selectionColor);\n\t\t\t}\n\n\t\t\tImGui::End();\n\t\t\trestoreColorScheme();\n\t\t\tImGui::PopStyleVar();\n\t\t}\n\n\t\tvoid ImguiEditorUiManager::applyColorScheme(bool root)\n\t\t{\n\t\t\tif(root)\n\t\t\t\tImGui::PushStyleColor(ImGuiCol_WindowBg, ImColor(0.0f, 0.0f, 0.0f, 0.0f));\n\t\t\telse\n\t\t\t\tImGui::PushStyleColor(ImGuiCol_WindowBg, _windowBgColor);\n\n\t\t\tImGui::PushStyleColor(ImGuiCol_MenuBarBg, _windowBgColor);\n\t\t\tImGui::PushStyleColor(ImGuiCol_Text, _textColor);\n\t\t\tImGui::PushStyleColor(ImGuiCol_Border, _borderColor);\n\t\t\tImGui::PushStyleColor(ImGuiCol_Button, _itemColor);\n\t\t\tImGui::PushStyleColor(ImGuiCol_ButtonHovered, _itemHoverColor);\n\t\t\tImGui::PushStyleColor(ImGuiCol_ButtonActive, _itemActiveColor);\n\t\t\tImGui::PushStyleColor(ImGuiCol_Header, _itemColor);\n\t\t\tImGui::PushStyleColor(ImGuiCol_HeaderHovered, _itemHoverColor);\n\t\t\tImGui::PushStyleColor(ImGuiCol_HeaderActive, _itemActiveColor);\n\t\t\tImGui::PushStyleColor(ImGuiCol_FrameBg, _itemColor);\n\t\t\tImGui::PushStyleColor(ImGuiCol_FrameBgHovered, _itemHoverColor);\n\t\t\tImGui::PushStyleColor(ImGuiCol_FrameBgActive, _itemActiveColor);\n\t\t\tImGui::PushStyleColor(ImGuiCol_TitleBg, _itemColor);\n\t\t\tImGui::PushStyleColor(ImGuiCol_TitleBgCollapsed, _itemColor);\n\t\t\tImGui::PushStyleColor(ImGuiCol_TitleBgActive, _itemActiveColor);\n\t\t\tImGui::PushStyleColor(ImGuiCol_CloseButton, _itemColor);\n\t\t\tImGui::PushStyleColor(ImGuiCol_CloseButtonHovered, _itemHoverColor);\n\t\t\tImGui::PushStyleColor(ImGuiCol_CloseButtonActive, _itemActiveColor);\n\t\t\tImGui::PushStyleColor(ImGuiCol_TextSelectedBg, _selectionColor);\n\t\t}\n\n\t\tvoid ImguiEditorUiManager::restoreColorScheme()\n\t\t{\n\t\t\tImGui::PopStyleColor();\n\t\t\tImGui::PopStyleColor();\n\t\t\tImGui::PopStyleColor();\n\t\t\tImGui::PopStyleColor();\n\t\t\tImGui::PopStyleColor();\n\t\t\tImGui::PopStyleColor();\n\t\t\tImGui::PopStyleColor();\n\t\t\tImGui::PopStyleColor();\n\t\t\tImGui::PopStyleColor();\n\t\t\tImGui::PopStyleColor();\n\t\t\tImGui::PopStyleColor();\n\t\t\tImGui::PopStyleColor();\n\t\t\tImGui::PopStyleColor();\n\t\t\tImGui::PopStyleColor();\n\t\t\tImGui::PopStyleColor();\n\t\t\tImGui::PopStyleColor();\n\t\t\tImGui::PopStyleColor();\n\t\t\tImGui::PopStyleColor();\n\t\t\tImGui::PopStyleColor();\n\t\t\tImGui::PopStyleColor();\n\t\t}\n\n\t\tvoid ImguiEditorUiManager::show(bool show)\n\t\t{\n\t\t\t_showEditor = show;\n\t\t}\n\t}\n}<|endoftext|>"} {"text":"\/**\n * The MIT License (MIT)\n *\n * Copyright (c) 2013-2018 Igor Zinken - http:\/\/www.igorski.nl\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy of\n * this software and associated documentation files (the \"Software\"), to deal in\n * the Software without restriction, including without limitation the rights to\n * use, copy, modify, merge, publish, distribute, sublicense, and\/or sell copies of\n * the Software, and to permit persons to whom the Software is furnished to do so,\n * subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\n * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\n * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\/\n#include \"sequencercontroller.h\"\n#include \"sequencer.h\"\n#include \"audioengine.h\"\n#include \n#include \n#include \n#include \n#include \n\nnamespace MWEngine {\n\n\/* constructor \/ destructor *\/\n\nSequencerController::SequencerController()\n{\n \/\/ by default, function as a sixteen step sequencer\n\n stepsPerBar = 16;\n AudioEngine::max_step_position = stepsPerBar - 1;\n};\n\nSequencerController::~SequencerController()\n{\n setPlaying( false );\n};\n\n\/* public methods *\/\n\nvoid SequencerController::prepare( float aQueuedTempo, int aTimeSigBeatAmount, int aTimeSigBeatUnit )\n{\n \/\/ calculate buffers and ranges\n if ( aQueuedTempo > 0 )\n {\n setTempo( aQueuedTempo, aTimeSigBeatAmount, aTimeSigBeatUnit );\n AudioEngine::handleTempoUpdate( aQueuedTempo, false ); \/\/ just to initialize all buffer sizes\n setLoopRange( 0, ( AudioEngine::amount_of_bars * AudioEngine::samples_per_bar ) - 1, stepsPerBar );\n }\n};\n\nfloat SequencerController::getTempo()\n{\n return AudioEngine::tempo;\n}\n\nvoid SequencerController::setTempo( float aTempo, int aTimeSigBeatAmount, int aTimeSigBeatUnit )\n{\n AudioEngine::queuedTempo = aTempo;\n\n AudioEngine::queuedTime_sig_beat_amount = aTimeSigBeatAmount;\n AudioEngine::queuedTime_sig_beat_unit = aTimeSigBeatUnit;\n}\n\nvoid SequencerController::setTempoNow( float aTempo, int aTimeSigBeatAmount, int aTimeSigBeatUnit )\n{\n setTempo( aTempo, aTimeSigBeatAmount, aTimeSigBeatUnit );\n updateStepsPerBar( stepsPerBar );\n AudioEngine::handleTempoUpdate( AudioEngine::queuedTempo, true );\n}\n\nvoid SequencerController::setVolume( float aVolume )\n{\n AudioEngine::volume = VolumeUtil::toLog( aVolume );\n}\n\nvoid SequencerController::setPlaying( bool aIsPlaying )\n{\n Sequencer::playing = aIsPlaying;\n}\n\nvoid SequencerController::setLoopRange( int aStartPosition, int aEndPosition )\n{\n setLoopRange( aStartPosition, aEndPosition, stepsPerBar );\n}\n\n\/**\n * make the sequencer loop between two given points\n *\n * @param aStartPosition {int} buffer offset of the loops startpoint (starts at 0 !)\n * @param aEndPosition {int} buffer offset of the loops endpoint\n * @param aStepsPerBar {int} the amount of individual segments the sequencer subdivides a single bar into\n * this is used for periodic notifications when the sequencer switches step\n *\/\nvoid SequencerController::setLoopRange( int aStartPosition, int aEndPosition, int aStepsPerBar )\n{\n AudioEngine::min_buffer_position = aStartPosition;\n AudioEngine::max_buffer_position = aEndPosition;\n\n \/\/ keep current buffer read pointer within the new loop range\n if ( AudioEngine::bufferPosition < AudioEngine::min_buffer_position ||\n AudioEngine::bufferPosition > AudioEngine::max_buffer_position )\n {\n AudioEngine::bufferPosition = AudioEngine::min_buffer_position;\n }\n\n AudioEngine::min_step_position = ( int ) round(( aStartPosition \/ AudioEngine::samples_per_bar ) * aStepsPerBar );\n AudioEngine::max_step_position = ( int ) round(((( float ) aEndPosition \/ ( float ) AudioEngine::samples_per_bar ) * aStepsPerBar ) - 1 );\n\n \/\/ keep current sequencer step within the new loop range\n if ( AudioEngine::stepPosition < AudioEngine::min_step_position ||\n AudioEngine::stepPosition > AudioEngine::max_step_position )\n {\n AudioEngine::stepPosition = AudioEngine::min_step_position;\n }\n updateStepsPerBar( aStepsPerBar );\n}\n\nint SequencerController::getStepPosition()\n{\n return AudioEngine::stepPosition;\n}\n\nint SequencerController::getBufferPosition()\n{\n return AudioEngine::bufferPosition;\n}\n\nvoid SequencerController::setBufferPosition( int aPosition )\n{\n \/\/ keep position within the sequences range (see \"setLoopRange\")\n\n if ( aPosition < AudioEngine::min_buffer_position ||\n aPosition > AudioEngine::max_buffer_position )\n {\n aPosition = AudioEngine::min_buffer_position;\n }\n\n AudioEngine::bufferPosition = aPosition;\n AudioEngine::stepPosition = ( aPosition \/ AudioEngine::samples_per_bar ) * stepsPerBar;\n\n Notifier::broadcast( Notifications::SEQUENCER_POSITION_UPDATED );\n}\n\nint SequencerController::getSamplesPerBeat()\n{\n return AudioEngine::samples_per_beat;\n}\n\nint SequencerController::getSamplesPerStep()\n{\n return ( int ) AudioEngine::samples_per_step;\n}\n\nint SequencerController::getSamplesPerBar()\n{\n return AudioEngine::samples_per_bar;\n}\n\nint SequencerController::getTimeSigBeatAmount()\n{\n return AudioEngine::time_sig_beat_amount;\n}\n\nint SequencerController::getTimeSigBeatUnit()\n{\n return AudioEngine::time_sig_beat_unit;\n}\n\nvoid SequencerController::updateStepsPerBar( int aStepsPerBar )\n{\n stepsPerBar = aStepsPerBar;\n AudioEngine::max_step_position = ( stepsPerBar * AudioEngine::amount_of_bars ) - 1;\n AudioEngine::beat_subdivision = stepsPerBar \/ AudioEngine::time_sig_beat_amount;\n\n \/\/ keep current sequencer step within the new loop range\n\n if ( AudioEngine::stepPosition > AudioEngine::max_step_position )\n AudioEngine::stepPosition = AudioEngine::min_step_position;\n}\n\nvoid SequencerController::updateMeasures( int aValue, int aStepsPerBar )\n{\n AudioEngine::amount_of_bars = aValue;\n AudioEngine::max_buffer_position = ( AudioEngine::samples_per_bar * AudioEngine::amount_of_bars ) - 1;\n\n updateStepsPerBar( aStepsPerBar );\n}\n\nvoid SequencerController::rewind()\n{\n setBufferPosition( AudioEngine::min_buffer_position );\n}\n\nvoid SequencerController::setNotificationMarker( int aPosition )\n{\n AudioEngine::marked_buffer_position = aPosition;\n}\n\n\/**\n * used for intelligent pre-caching, get the BaseCacheableAudioEvents\n * belonging to a specific measure for on-demand caching\n *\n * @param aMeasure {int} the measure containing the events we'd like to precache\n *\/\nvoid SequencerController::cacheAudioEventsForMeasure( int aMeasure )\n{\n int startBufferPos = AudioEngine::samples_per_bar * aMeasure;\n int endBufferPos = ( startBufferPos + AudioEngine::samples_per_bar ) - 1;\n\n std::vector* list = Sequencer::collectCacheableSequencerEvents( startBufferPos, endBufferPos );\n getBulkCacher()->addToQueue( list );\n\n delete list; \/\/ free memory\n\n if ( getBulkCacher()->hasQueue())\n getBulkCacher()->cacheQueue();\n}\n\nBulkCacher* SequencerController::getBulkCacher()\n{\n return Sequencer::bulkCacher;\n}\n\n\/**\n * when bouncing, the writing of buffers into the hardware is omitted\n * for an increase in bouncing speed (otherwise its real time)\n *\/\nvoid SequencerController::setBounceState( bool aIsBouncing, int aMaxBuffers, char* aOutputFile )\n{\n AudioEngine::bouncing = aIsBouncing;\n\n if ( AudioEngine::bouncing )\n {\n AudioEngine::bufferPosition = 0;\n AudioEngine::stepPosition = 0;\n }\n setRecordingState( aIsBouncing, aMaxBuffers, aOutputFile );\n}\n\n\/**\n * Record the output of the sequencer onto storage\n *\n * aRecording {bool} toggles the recording state\n * aMaxBuffers {int} the total recorded buffer size to store in memory\n * before writing the recorded snippet as .WAV file into\n * the given output file's directory.\n * aOutputDirectory {char*} name of the output WAV file to generate when recording completes\n * (when recording state is disabled), this will concatenate all snippets.\n *\/\nvoid SequencerController::setRecordingState( bool aRecording, int aMaxBuffers, char* aOutputFile )\n{\n \/\/ in case Sequencer was recording input from the Android device, halt recording of input\n if ( AudioEngine::recordInputToDisk )\n setRecordingFromDeviceState( false, 0, ( char* ) \"\\0\" );\n\n bool wasRecording = AudioEngine::recordOutputToDisk;\n AudioEngine::recordOutputToDisk = aRecording;\n\n if ( AudioEngine::recordOutputToDisk )\n {\n DiskWriter::prepare(\n std::string( aOutputFile ), roundTo( aMaxBuffers, AudioEngineProps::BUFFER_SIZE ),\n AudioEngineProps::OUTPUT_CHANNELS\n );\n }\n else if ( wasRecording )\n {\n \/\/ recording halted, write currently recording snippet into file\n \/\/ and concatenate all recorded snippets into the requested output file name\n \/\/ we can do this synchronously as this method is called from outside the\n \/\/ rendering thread and thus won't lead to buffer under runs\n\n DiskWriter::writeBufferToFile( DiskWriter::currentBufferIndex, false );\n\n if ( DiskWriter::finish())\n Notifier::broadcast( Notifications::RECORDING_COMPLETED );\n }\n}\n\n\/**\n * record audio from the Androids input channel, this stores only the incoming audio\n * not the remaining audio processed \/ generated by the engine\n *\n * aRecording {bool} toggles the recording state\n * aMaxBuffers {int} the total recorded buffer size to store in memory\n * before writing the recorded contents as .WAV file into\n * the given output directory.\n * aOutputDirectory {char*} name of the folder to write each snippet into\n *\/\nvoid SequencerController::setRecordingFromDeviceState( bool aRecording, int aMaxBuffers, char* aOutputFile )\n{\n \/\/ in case Sequencer was recording its output, halt recording of output\n if ( AudioEngine::recordOutputToDisk )\n setRecordingState( false, 0, ( char* ) \"\\0\" );\n\n bool wasRecording = AudioEngine::recordInputToDisk;\n AudioEngine::recordInputToDisk = aRecording;\n\n if ( AudioEngine::recordInputToDisk )\n {\n DiskWriter::prepare(\n std::string( aOutputFile ), roundTo( aMaxBuffers, AudioEngineProps::BUFFER_SIZE ),\n AudioEngineProps::INPUT_CHANNELS\n );\n }\n else if ( wasRecording )\n {\n \/\/ recording halted, write currently recording snippet into file\n \/\/ and concatenate all recorded snippets into the requested output file name\n \/\/ we can do this synchronously as this method is called from outside the\n \/\/ rendering thread and thus won't lead to buffer under runs\n\n DiskWriter::writeBufferToFile( DiskWriter::currentBufferIndex, false );\n\n if ( DiskWriter::finish())\n Notifier::broadcast( Notifications::RECORDING_COMPLETED );\n }\n}\n\n\/**\n * Save the contents of the snippet at given buffer index\n * onto storage. This should be invoked from a thread separate to the\n * audio rendering thread to prevent buffer under runs from happening\n *\/\nvoid SequencerController::saveRecordedSnippet( int snippetBufferIndex )\n{\n DiskWriter::writeBufferToFile( snippetBufferIndex, true );\n}\n\n} \/\/ E.O namespace MWEngine\nRemoved global play operation from SequencerController destructor\/**\n * The MIT License (MIT)\n *\n * Copyright (c) 2013-2019 Igor Zinken - http:\/\/www.igorski.nl\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy of\n * this software and associated documentation files (the \"Software\"), to deal in\n * the Software without restriction, including without limitation the rights to\n * use, copy, modify, merge, publish, distribute, sublicense, and\/or sell copies of\n * the Software, and to permit persons to whom the Software is furnished to do so,\n * subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\n * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\n * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\/\n#include \"sequencercontroller.h\"\n#include \"sequencer.h\"\n#include \"audioengine.h\"\n#include \n#include \n#include \n#include \n#include \n\nnamespace MWEngine {\n\n\/* constructor \/ destructor *\/\n\nSequencerController::SequencerController()\n{\n \/\/ by default, function as a sixteen step sequencer\n\n stepsPerBar = 16;\n AudioEngine::max_step_position = stepsPerBar - 1;\n};\n\nSequencerController::~SequencerController()\n{\n \/\/ nothing allocated here...\n};\n\n\/* public methods *\/\n\nvoid SequencerController::prepare( float aQueuedTempo, int aTimeSigBeatAmount, int aTimeSigBeatUnit )\n{\n \/\/ calculate buffers and ranges\n if ( aQueuedTempo > 0 )\n {\n setTempo( aQueuedTempo, aTimeSigBeatAmount, aTimeSigBeatUnit );\n AudioEngine::handleTempoUpdate( aQueuedTempo, false ); \/\/ just to initialize all buffer sizes\n setLoopRange( 0, ( AudioEngine::amount_of_bars * AudioEngine::samples_per_bar ) - 1, stepsPerBar );\n }\n};\n\nfloat SequencerController::getTempo()\n{\n return AudioEngine::tempo;\n}\n\nvoid SequencerController::setTempo( float aTempo, int aTimeSigBeatAmount, int aTimeSigBeatUnit )\n{\n AudioEngine::queuedTempo = aTempo;\n\n AudioEngine::queuedTime_sig_beat_amount = aTimeSigBeatAmount;\n AudioEngine::queuedTime_sig_beat_unit = aTimeSigBeatUnit;\n}\n\nvoid SequencerController::setTempoNow( float aTempo, int aTimeSigBeatAmount, int aTimeSigBeatUnit )\n{\n setTempo( aTempo, aTimeSigBeatAmount, aTimeSigBeatUnit );\n updateStepsPerBar( stepsPerBar );\n AudioEngine::handleTempoUpdate( AudioEngine::queuedTempo, true );\n}\n\nvoid SequencerController::setVolume( float aVolume )\n{\n AudioEngine::volume = VolumeUtil::toLog( aVolume );\n}\n\nvoid SequencerController::setPlaying( bool aIsPlaying )\n{\n Sequencer::playing = aIsPlaying;\n}\n\nvoid SequencerController::setLoopRange( int aStartPosition, int aEndPosition )\n{\n setLoopRange( aStartPosition, aEndPosition, stepsPerBar );\n}\n\n\/**\n * make the sequencer loop between two given points\n *\n * @param aStartPosition {int} buffer offset of the loops startpoint (starts at 0 !)\n * @param aEndPosition {int} buffer offset of the loops endpoint\n * @param aStepsPerBar {int} the amount of individual segments the sequencer subdivides a single bar into\n * this is used for periodic notifications when the sequencer switches step\n *\/\nvoid SequencerController::setLoopRange( int aStartPosition, int aEndPosition, int aStepsPerBar )\n{\n AudioEngine::min_buffer_position = aStartPosition;\n AudioEngine::max_buffer_position = aEndPosition;\n\n \/\/ keep current buffer read pointer within the new loop range\n if ( AudioEngine::bufferPosition < AudioEngine::min_buffer_position ||\n AudioEngine::bufferPosition > AudioEngine::max_buffer_position )\n {\n AudioEngine::bufferPosition = AudioEngine::min_buffer_position;\n }\n\n AudioEngine::min_step_position = ( int ) round(( aStartPosition \/ AudioEngine::samples_per_bar ) * aStepsPerBar );\n AudioEngine::max_step_position = ( int ) round(((( float ) aEndPosition \/ ( float ) AudioEngine::samples_per_bar ) * aStepsPerBar ) - 1 );\n\n \/\/ keep current sequencer step within the new loop range\n if ( AudioEngine::stepPosition < AudioEngine::min_step_position ||\n AudioEngine::stepPosition > AudioEngine::max_step_position )\n {\n AudioEngine::stepPosition = AudioEngine::min_step_position;\n }\n updateStepsPerBar( aStepsPerBar );\n}\n\nint SequencerController::getStepPosition()\n{\n return AudioEngine::stepPosition;\n}\n\nint SequencerController::getBufferPosition()\n{\n return AudioEngine::bufferPosition;\n}\n\nvoid SequencerController::setBufferPosition( int aPosition )\n{\n \/\/ keep position within the sequences range (see \"setLoopRange\")\n\n if ( aPosition < AudioEngine::min_buffer_position ||\n aPosition > AudioEngine::max_buffer_position )\n {\n aPosition = AudioEngine::min_buffer_position;\n }\n\n AudioEngine::bufferPosition = aPosition;\n AudioEngine::stepPosition = ( aPosition \/ AudioEngine::samples_per_bar ) * stepsPerBar;\n\n Notifier::broadcast( Notifications::SEQUENCER_POSITION_UPDATED );\n}\n\nint SequencerController::getSamplesPerBeat()\n{\n return AudioEngine::samples_per_beat;\n}\n\nint SequencerController::getSamplesPerStep()\n{\n return ( int ) AudioEngine::samples_per_step;\n}\n\nint SequencerController::getSamplesPerBar()\n{\n return AudioEngine::samples_per_bar;\n}\n\nint SequencerController::getTimeSigBeatAmount()\n{\n return AudioEngine::time_sig_beat_amount;\n}\n\nint SequencerController::getTimeSigBeatUnit()\n{\n return AudioEngine::time_sig_beat_unit;\n}\n\nvoid SequencerController::updateStepsPerBar( int aStepsPerBar )\n{\n stepsPerBar = aStepsPerBar;\n AudioEngine::max_step_position = ( stepsPerBar * AudioEngine::amount_of_bars ) - 1;\n AudioEngine::beat_subdivision = stepsPerBar \/ AudioEngine::time_sig_beat_amount;\n\n \/\/ keep current sequencer step within the new loop range\n\n if ( AudioEngine::stepPosition > AudioEngine::max_step_position )\n AudioEngine::stepPosition = AudioEngine::min_step_position;\n}\n\nvoid SequencerController::updateMeasures( int aValue, int aStepsPerBar )\n{\n AudioEngine::amount_of_bars = aValue;\n AudioEngine::max_buffer_position = ( AudioEngine::samples_per_bar * AudioEngine::amount_of_bars ) - 1;\n\n updateStepsPerBar( aStepsPerBar );\n}\n\nvoid SequencerController::rewind()\n{\n setBufferPosition( AudioEngine::min_buffer_position );\n}\n\nvoid SequencerController::setNotificationMarker( int aPosition )\n{\n AudioEngine::marked_buffer_position = aPosition;\n}\n\n\/**\n * used for intelligent pre-caching, get the BaseCacheableAudioEvents\n * belonging to a specific measure for on-demand caching\n *\n * @param aMeasure {int} the measure containing the events we'd like to precache\n *\/\nvoid SequencerController::cacheAudioEventsForMeasure( int aMeasure )\n{\n int startBufferPos = AudioEngine::samples_per_bar * aMeasure;\n int endBufferPos = ( startBufferPos + AudioEngine::samples_per_bar ) - 1;\n\n std::vector* list = Sequencer::collectCacheableSequencerEvents( startBufferPos, endBufferPos );\n getBulkCacher()->addToQueue( list );\n\n delete list; \/\/ free memory\n\n if ( getBulkCacher()->hasQueue())\n getBulkCacher()->cacheQueue();\n}\n\nBulkCacher* SequencerController::getBulkCacher()\n{\n return Sequencer::bulkCacher;\n}\n\n\/**\n * when bouncing, the writing of buffers into the hardware is omitted\n * for an increase in bouncing speed (otherwise its real time)\n *\/\nvoid SequencerController::setBounceState( bool aIsBouncing, int aMaxBuffers, char* aOutputFile )\n{\n AudioEngine::bouncing = aIsBouncing;\n\n if ( AudioEngine::bouncing )\n {\n AudioEngine::bufferPosition = 0;\n AudioEngine::stepPosition = 0;\n }\n setRecordingState( aIsBouncing, aMaxBuffers, aOutputFile );\n}\n\n\/**\n * Record the output of the sequencer onto storage\n *\n * aRecording {bool} toggles the recording state\n * aMaxBuffers {int} the total recorded buffer size to store in memory\n * before writing the recorded snippet as .WAV file into\n * the given output file's directory.\n * aOutputDirectory {char*} name of the output WAV file to generate when recording completes\n * (when recording state is disabled), this will concatenate all snippets.\n *\/\nvoid SequencerController::setRecordingState( bool aRecording, int aMaxBuffers, char* aOutputFile )\n{\n \/\/ in case Sequencer was recording input from the Android device, halt recording of input\n if ( AudioEngine::recordInputToDisk )\n setRecordingFromDeviceState( false, 0, ( char* ) \"\\0\" );\n\n bool wasRecording = AudioEngine::recordOutputToDisk;\n AudioEngine::recordOutputToDisk = aRecording;\n\n if ( AudioEngine::recordOutputToDisk )\n {\n DiskWriter::prepare(\n std::string( aOutputFile ), roundTo( aMaxBuffers, AudioEngineProps::BUFFER_SIZE ),\n AudioEngineProps::OUTPUT_CHANNELS\n );\n }\n else if ( wasRecording )\n {\n \/\/ recording halted, write currently recording snippet into file\n \/\/ and concatenate all recorded snippets into the requested output file name\n \/\/ we can do this synchronously as this method is called from outside the\n \/\/ rendering thread and thus won't lead to buffer under runs\n\n DiskWriter::writeBufferToFile( DiskWriter::currentBufferIndex, false );\n\n if ( DiskWriter::finish())\n Notifier::broadcast( Notifications::RECORDING_COMPLETED );\n }\n}\n\n\/**\n * record audio from the Androids input channel, this stores only the incoming audio\n * not the remaining audio processed \/ generated by the engine\n *\n * aRecording {bool} toggles the recording state\n * aMaxBuffers {int} the total recorded buffer size to store in memory\n * before writing the recorded contents as .WAV file into\n * the given output directory.\n * aOutputDirectory {char*} name of the folder to write each snippet into\n *\/\nvoid SequencerController::setRecordingFromDeviceState( bool aRecording, int aMaxBuffers, char* aOutputFile )\n{\n \/\/ in case Sequencer was recording its output, halt recording of output\n if ( AudioEngine::recordOutputToDisk )\n setRecordingState( false, 0, ( char* ) \"\\0\" );\n\n bool wasRecording = AudioEngine::recordInputToDisk;\n AudioEngine::recordInputToDisk = aRecording;\n\n if ( AudioEngine::recordInputToDisk )\n {\n DiskWriter::prepare(\n std::string( aOutputFile ), roundTo( aMaxBuffers, AudioEngineProps::BUFFER_SIZE ),\n AudioEngineProps::INPUT_CHANNELS\n );\n }\n else if ( wasRecording )\n {\n \/\/ recording halted, write currently recording snippet into file\n \/\/ and concatenate all recorded snippets into the requested output file name\n \/\/ we can do this synchronously as this method is called from outside the\n \/\/ rendering thread and thus won't lead to buffer under runs\n\n DiskWriter::writeBufferToFile( DiskWriter::currentBufferIndex, false );\n\n if ( DiskWriter::finish())\n Notifier::broadcast( Notifications::RECORDING_COMPLETED );\n }\n}\n\n\/**\n * Save the contents of the snippet at given buffer index\n * onto storage. This should be invoked from a thread separate to the\n * audio rendering thread to prevent buffer under runs from happening\n *\/\nvoid SequencerController::saveRecordedSnippet( int snippetBufferIndex )\n{\n DiskWriter::writeBufferToFile( snippetBufferIndex, true );\n}\n\n} \/\/ E.O namespace MWEngine\n<|endoftext|>"} {"text":"\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Name: vimacros.cpp\n\/\/ Purpose: Implementation of class wxExViMacros\n\/\/ Author: Anton van Wezenbeek\n\/\/ Copyright: (c) 2012 Anton van Wezenbeek\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \n#include \n#ifndef WX_PRECOMP\n#include \n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#if wxUSE_GUI\n\nbool wxExViMacros::m_IsExpand = false;\nbool wxExViMacros::m_IsModified = false;\nbool wxExViMacros::m_IsPlayback = false;\n\nstd::map > wxExViMacros::m_Macros;\nstd::map wxExViMacros::m_Variables;\n\nwxExViMacros::wxExViMacros()\n : m_IsRecording(false)\n{\n}\n\nvoid wxExViMacros::AskForInput()\n{\n for (std::map::iterator it = \n m_Variables.begin();\n it != m_Variables.end();\n ++it)\n {\n it->second.AskForInput();\n }\n}\n\nconst wxString wxExViMacros::Decode(const wxString& text)\n{\n long c;\n \n if (text.ToLong(&c))\n {\n return char(c);\n }\n \n return text;\n}\n \nconst wxString wxExViMacros::Encode(const wxString& text, bool& encoded)\n{\n if (text.length() == 1)\n {\n int c = text[0];\n \n \/\/ Encode control characters, and whitespace.\n if (iscntrl(c) || isspace(c))\n {\n encoded = true;\n return wxString::Format(\"%d\", c);\n }\n }\n\n return text; \n}\n\nbool wxExViMacros::Expand(wxExEx* ex, const wxString& variable)\n{\n std::map::iterator it = m_Variables.find(variable);\n \n bool ok;\n \n if (it == m_Variables.end())\n {\n std::pair::iterator, bool> ret = \n m_Variables.insert(std::make_pair(variable, wxExVariable(variable)));\n \n wxLogStatus(_(\"Added variable\") + \": \" + variable);\n \n ok = ret.first->second.Expand(ex);\n \n if (ret.first->second.IsModified())\n {\n m_IsModified = true;\n }\n }\n else\n {\n ok = it->second.Expand(ex);\n \n if (it->second.IsModified())\n {\n m_IsModified = true;\n }\n }\n \n if (!ok)\n {\n wxLogStatus(_(\"Could not expand variable\") + \": \" + variable);\n }\n \n return ok;\n} \n\nbool wxExViMacros::Expand(wxExEx* ex, const wxString& variable, wxString& value)\n{\n std::map::iterator it = m_Variables.find(variable);\n \n bool ok;\n \n if (it == m_Variables.end())\n {\n std::pair::iterator, bool> ret = \n m_Variables.insert(std::make_pair(variable, wxExVariable(variable)));\n \n wxLogStatus(_(\"Added variable\") + \": \" + variable);\n \n ok = ret.first->second.Expand(ex, value);\n \n \/\/ If we are expanding, one input is enough. \n if (m_IsExpand)\n {\n ret.first->second.SkipInput();\n }\n \n if (ret.first->second.IsModified())\n {\n m_IsModified = true;\n }\n }\n else\n {\n ok = it->second.Expand(ex, value);\n\n \/\/ If we are expanding, one input is enough. \n if (m_IsExpand)\n {\n it->second.SkipInput();\n }\n \n if (it->second.IsModified())\n {\n m_IsModified = true;\n }\n }\n \n if (!ok)\n {\n wxLogStatus(_(\"Could not expand variable\") + \": \" + variable);\n }\n \n return ok;\n}\n\nbool wxExViMacros::ExpandTemplate(\n wxExEx* ex, const wxExVariable& v, wxString& expanded)\n{\n if (!m_IsExpand)\n {\n m_IsExpand = true;\n AskForInput();\n }\n\n \/\/ Read the file (file name is in m_Value), expand\n \/\/ all macro variables in it, and set expanded.\n const wxFileName filename(\n#ifdef wxExUSE_PORTABLE\n wxPathOnly(wxStandardPaths::Get().GetExecutablePath())\n#else\n wxStandardPaths::Get().GetUserDataDir()\n#endif\n + wxFileName::GetPathSeparator() + v.GetValue());\n\n wxFileInputStream input(filename.GetFullPath());\n \n if (!input.IsOk())\n {\n wxLogError(\"Could not open template file: \" + filename.GetFullPath());\n return false;\n }\n \n wxTextInputStream text(input);\n \n while (input.IsOk() && !input.Eof()) \n {\n const wxChar c = text.GetChar();\n \n if (c != '@')\n {\n expanded += c;\n }\n else\n {\n wxString variable;\n bool completed = false;\n \n while (input.IsOk() && !input.Eof() && !completed) \n {\n const wxChar c = text.GetChar();\n \n if (c != '@')\n {\n variable += c;\n }\n else\n {\n completed = true;\n }\n }\n \n if (!completed)\n {\n return false;\n }\n \n \/\/ Prevent recursion.\n if (variable == v.GetName())\n {\n return false;\n }\n \n wxString value;\n \n if (!Expand(ex, variable, value))\n {\n return false;\n }\n \n expanded += value;\n }\n }\n \n m_IsExpand = false;\n\n \/\/ Set back to normal value. \n AskForInput();\n \n return true;\n}\n\nconst wxArrayString wxExViMacros::Get() const\n{\n wxArrayString as;\n \n for (\n std::map >::const_iterator it = \n m_Macros.begin();\n it != m_Macros.end();\n ++it)\n {\n as.Add(it->first);\n }\n \n return as;\n}\n\nconst std::vector< wxString > wxExViMacros::Get(const wxString& macro) const\n{\n std::map >::const_iterator it = \n m_Macros.find(macro);\n \n if (it != m_Macros.end())\n {\n return it->second;\n }\n else\n {\n std::vector empty;\n return empty;\n }\n}\n\nconst wxFileName wxExViMacros::GetFileName()\n{\n return wxFileName(\n#ifdef wxExUSE_PORTABLE\n wxPathOnly(wxStandardPaths::Get().GetExecutablePath())\n#else\n wxStandardPaths::Get().GetUserDataDir()\n#endif\n + wxFileName::GetPathSeparator() + \"macros.xml\");\n}\n\nbool wxExViMacros::IsRecorded(const wxString& macro) const\n{\n if (macro.empty())\n {\n return !m_Macros.empty();\n }\n else\n {\n return !Get(macro).empty();\n }\n}\n\nbool wxExViMacros::Load(wxXmlDocument& doc)\n{\n \/\/ This test is to prevent showing an error if the macro file does not exist,\n \/\/ as this is not required.\n if (!GetFileName().FileExists())\n {\n return false;\n } \n \n if (!doc.Load(GetFileName().GetFullPath()))\n {\n return false;\n }\n \n return true;\n}\n\nbool wxExViMacros::LoadDocument()\n{\n wxXmlDocument doc;\n \n if (!Load(doc))\n {\n return false;\n }\n \n \/\/ If modified is true, then you did not save previous\n \/\/ recordings.\n \/\/ We assume that this is your choice, so we reset the member.\n m_IsModified = false;\n \n m_Macros.clear();\n m_Variables.clear();\n \n wxXmlNode* root = doc.GetRoot();\n wxXmlNode* child = root->GetChildren();\n \n while (child)\n {\n if (child->GetName() == \"macro\")\n {\n std::vector v;\n \n wxXmlNode* command = child->GetChildren();\n \n while (command)\n {\n if (command->GetAttribute(\"encoded\", \"false\") == \"true\")\n {\n v.push_back(Decode(command->GetNodeContent()));\n }\n else\n {\n v.push_back(command->GetNodeContent());\n }\n \n command = command->GetNext();\n }\n \n std::map>::const_iterator it = \n m_Macros.find(child->GetAttribute(\"name\"));\n \n if (it != m_Macros.end())\n {\n wxLogError(\"Duplicate macro: %s on line: %d\", \n child->GetAttribute(\"name\"),\n child->GetLineNumber());\n }\n else\n {\n m_Macros.insert(std::make_pair(child->GetAttribute(\"name\"), v));\n }\n }\n else if (child->GetName() == \"variable\")\n {\n wxExVariable variable(child);\n \n std::map::const_iterator it = m_Variables.find(variable.GetName());\n \n if (it != m_Variables.end())\n {\n wxLogError(\"Duplicate variable: %s on line: %d\", \n variable.GetName(),\n child->GetLineNumber());\n }\n else\n {\n m_Variables.insert(std::make_pair(variable.GetName(), variable));\n }\n }\n \n child = child->GetNext();\n }\n \n return true;\n}\n\nbool wxExViMacros::Playback(wxExEx* ex, const wxString& macro, int repeat)\n{\n if (!IsRecorded(macro) || macro.empty())\n {\n wxLogStatus(_(\"Unknown macro\") + \": \" + macro);\n return false;\n }\n \n if (m_IsPlayback && macro == m_Macro)\n {\n wxLogStatus(_(\"Already playing back\"));\n return false;\n }\n\n if (repeat <= 0)\n {\n return false;\n }\n \n ex->GetSTC()->BeginUndoAction();\n \n bool stop = false;\n \n m_IsPlayback = true;\n \n m_Macro = macro;\n \n wxBusyCursor;\n \n AskForInput();\n \n for (int i = 0; i < repeat; i++)\n {\n for (\n std::vector::const_iterator it = m_Macros[macro].begin();\n it != m_Macros[macro].end() && !stop;\n ++it)\n { \n stop = !ex->Command(*it);\n \n if (stop)\n {\n wxLogStatus(_(\"Macro aborted at '\") + *it + \"'\");\n }\n }\n }\n\n ex->GetSTC()->EndUndoAction();\n\n if (!stop)\n {\n wxLogStatus(_(\"Macro played back\"));\n }\n \n m_IsPlayback = false;\n \n return !stop;\n}\n\nvoid wxExViMacros::Record(const wxString& text, bool new_command)\n{\n if (!m_IsRecording)\n {\n return;\n }\n \n m_IsModified = true;\n \n if (new_command) \n {\n m_Macros[m_Macro].push_back(text);\n }\n else\n {\n if (m_Macros[m_Macro].empty())\n {\n m_Macros[m_Macro].push_back(wxEmptyString);\n }\n \n m_Macros[m_Macro].back() += text;\n }\n}\n\nbool wxExViMacros::SaveDocument(bool only_if_modified)\n{\n if (!m_IsModified && only_if_modified)\n {\n return false;\n }\n \n wxXmlDocument doc;\n \n if (!Load(doc))\n {\n return false;\n }\n \n wxXmlNode* root = doc.GetRoot();\n wxXmlNode* child;\n \n while (child = root->GetChildren())\n {\n root->RemoveChild(child);\n delete child;\n }\n \n for (\n std::map >::reverse_iterator it = \n m_Macros.rbegin();\n it != m_Macros.rend();\n ++it)\n {\n wxXmlNode* element = new wxXmlNode(root, wxXML_ELEMENT_NODE, \"macro\");\n element->AddAttribute(\"name\", it->first);\n \n for (\n std::vector::reverse_iterator it2 = it->second.rbegin();\n it2 != it->second.rend();\n ++it2)\n { \n bool encoded = false; \n const wxString contents(Encode(*it2, encoded));\n \n wxXmlNode* cmd = new wxXmlNode(element, wxXML_ELEMENT_NODE, \"command\");\n new wxXmlNode(cmd, wxXML_TEXT_NODE, \"\", contents);\n \n if (encoded)\n {\n cmd->AddAttribute(\"encoded\", \"true\");\n }\n }\n }\n \n for (\n std::map< wxString, wxExVariable >::reverse_iterator it2 = \n m_Variables.rbegin();\n it2 != m_Variables.rend();\n ++it2)\n {\n wxXmlNode* element = new wxXmlNode(root, wxXML_ELEMENT_NODE, \"variable\");\n it2->second.Save(element);\n }\n \n const bool ok = doc.Save(GetFileName().GetFullPath());\n \n if (ok)\n {\n m_IsModified = false;\n }\n\n return ok;\n}\n\nvoid wxExViMacros::StartRecording(const wxString& macro)\n{\n if (m_IsRecording || macro.empty())\n {\n return;\n }\n \n m_IsRecording = true;\n \n if (macro.size() == 1)\n {\n \/\/ We only use lower case macro's, to be able to\n \/\/ append to them using qA.\n m_Macro = macro.Lower();\n \n \/\/ Clear macro if it is lower case\n \/\/ (otherwise append to the macro).\n if (wxIslower(macro[0]))\n {\n m_Macros[m_Macro].clear();\n }\n }\n else\n {\n m_Macro = macro;\n m_Macros[m_Macro].clear();\n }\n \n wxLogStatus(_(\"Macro recording\"));\n}\n\nvoid wxExViMacros::StopRecording()\n{\n if (!m_IsRecording)\n {\n return;\n }\n \n m_IsRecording = false;\n \n if (!Get(m_Macro).empty())\n {\n wxLogStatus(wxString::Format(_(\"Macro '%s' is recorded\"), m_Macro.c_str()));\n }\n else\n {\n wxLogStatus(_(\"Ready\"));\n }\n}\n\n#endif \/\/ wxUSE_GUI\nfixed compile error\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Name: vimacros.cpp\n\/\/ Purpose: Implementation of class wxExViMacros\n\/\/ Author: Anton van Wezenbeek\n\/\/ Copyright: (c) 2012 Anton van Wezenbeek\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \n#include \n#ifndef WX_PRECOMP\n#include \n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#if wxUSE_GUI\n\nbool wxExViMacros::m_IsExpand = false;\nbool wxExViMacros::m_IsModified = false;\nbool wxExViMacros::m_IsPlayback = false;\n\nstd::map > wxExViMacros::m_Macros;\nstd::map wxExViMacros::m_Variables;\n\nwxExViMacros::wxExViMacros()\n : m_IsRecording(false)\n{\n}\n\nvoid wxExViMacros::AskForInput()\n{\n for (std::map::iterator it = \n m_Variables.begin();\n it != m_Variables.end();\n ++it)\n {\n it->second.AskForInput();\n }\n}\n\nconst wxString wxExViMacros::Decode(const wxString& text)\n{\n long c;\n \n if (text.ToLong(&c))\n {\n return char(c);\n }\n \n return text;\n}\n \nconst wxString wxExViMacros::Encode(const wxString& text, bool& encoded)\n{\n if (text.length() == 1)\n {\n int c = text[0];\n \n \/\/ Encode control characters, and whitespace.\n if (iscntrl(c) || isspace(c))\n {\n encoded = true;\n return wxString::Format(\"%d\", c);\n }\n }\n\n return text; \n}\n\nbool wxExViMacros::Expand(wxExEx* ex, const wxString& variable)\n{\n std::map::iterator it = m_Variables.find(variable);\n \n bool ok;\n \n if (it == m_Variables.end())\n {\n std::pair::iterator, bool> ret = \n m_Variables.insert(std::make_pair(variable, wxExVariable(variable)));\n \n wxLogStatus(_(\"Added variable\") + \": \" + variable);\n \n ok = ret.first->second.Expand(ex);\n \n if (ret.first->second.IsModified())\n {\n m_IsModified = true;\n }\n }\n else\n {\n ok = it->second.Expand(ex);\n \n if (it->second.IsModified())\n {\n m_IsModified = true;\n }\n }\n \n if (!ok)\n {\n wxLogStatus(_(\"Could not expand variable\") + \": \" + variable);\n }\n \n return ok;\n} \n\nbool wxExViMacros::Expand(wxExEx* ex, const wxString& variable, wxString& value)\n{\n std::map::iterator it = m_Variables.find(variable);\n \n bool ok;\n \n if (it == m_Variables.end())\n {\n std::pair::iterator, bool> ret = \n m_Variables.insert(std::make_pair(variable, wxExVariable(variable)));\n \n wxLogStatus(_(\"Added variable\") + \": \" + variable);\n \n ok = ret.first->second.Expand(ex, value);\n \n \/\/ If we are expanding, one input is enough. \n if (m_IsExpand)\n {\n ret.first->second.SkipInput();\n }\n \n if (ret.first->second.IsModified())\n {\n m_IsModified = true;\n }\n }\n else\n {\n ok = it->second.Expand(ex, value);\n\n \/\/ If we are expanding, one input is enough. \n if (m_IsExpand)\n {\n it->second.SkipInput();\n }\n \n if (it->second.IsModified())\n {\n m_IsModified = true;\n }\n }\n \n if (!ok)\n {\n wxLogStatus(_(\"Could not expand variable\") + \": \" + variable);\n }\n \n return ok;\n}\n\nbool wxExViMacros::ExpandTemplate(\n wxExEx* ex, const wxExVariable& v, wxString& expanded)\n{\n if (!m_IsExpand)\n {\n m_IsExpand = true;\n AskForInput();\n }\n\n \/\/ Read the file (file name is in m_Value), expand\n \/\/ all macro variables in it, and set expanded.\n const wxFileName filename(\n#ifdef wxExUSE_PORTABLE\n wxPathOnly(wxStandardPaths::Get().GetExecutablePath())\n#else\n wxStandardPaths::Get().GetUserDataDir()\n#endif\n + wxFileName::GetPathSeparator() + v.GetValue());\n\n wxFileInputStream input(filename.GetFullPath());\n \n if (!input.IsOk())\n {\n wxLogError(\"Could not open template file: \" + filename.GetFullPath());\n return false;\n }\n \n wxTextInputStream text(input);\n \n while (input.IsOk() && !input.Eof()) \n {\n const wxChar c = text.GetChar();\n \n if (c != '@')\n {\n expanded += c;\n }\n else\n {\n wxString variable;\n bool completed = false;\n \n while (input.IsOk() && !input.Eof() && !completed) \n {\n const wxChar c = text.GetChar();\n \n if (c != '@')\n {\n variable += c;\n }\n else\n {\n completed = true;\n }\n }\n \n if (!completed)\n {\n return false;\n }\n \n \/\/ Prevent recursion.\n if (variable == v.GetName())\n {\n return false;\n }\n \n wxString value;\n \n if (!Expand(ex, variable, value))\n {\n return false;\n }\n \n expanded += value;\n }\n }\n \n m_IsExpand = false;\n\n \/\/ Set back to normal value. \n AskForInput();\n \n return true;\n}\n\nconst wxArrayString wxExViMacros::Get() const\n{\n wxArrayString as;\n \n for (\n std::map >::const_iterator it = \n m_Macros.begin();\n it != m_Macros.end();\n ++it)\n {\n as.Add(it->first);\n }\n \n return as;\n}\n\nconst std::vector< wxString > wxExViMacros::Get(const wxString& macro) const\n{\n std::map >::const_iterator it = \n m_Macros.find(macro);\n \n if (it != m_Macros.end())\n {\n return it->second;\n }\n else\n {\n std::vector empty;\n return empty;\n }\n}\n\nconst wxFileName wxExViMacros::GetFileName()\n{\n return wxFileName(\n#ifdef wxExUSE_PORTABLE\n wxPathOnly(wxStandardPaths::Get().GetExecutablePath())\n#else\n wxStandardPaths::Get().GetUserDataDir()\n#endif\n + wxFileName::GetPathSeparator() + \"macros.xml\");\n}\n\nbool wxExViMacros::IsRecorded(const wxString& macro) const\n{\n if (macro.empty())\n {\n return !m_Macros.empty();\n }\n else\n {\n return !Get(macro).empty();\n }\n}\n\nbool wxExViMacros::Load(wxXmlDocument& doc)\n{\n \/\/ This test is to prevent showing an error if the macro file does not exist,\n \/\/ as this is not required.\n if (!GetFileName().FileExists())\n {\n return false;\n } \n \n if (!doc.Load(GetFileName().GetFullPath()))\n {\n return false;\n }\n \n return true;\n}\n\nbool wxExViMacros::LoadDocument()\n{\n wxXmlDocument doc;\n \n if (!Load(doc))\n {\n return false;\n }\n \n \/\/ If modified is true, then you did not save previous\n \/\/ recordings.\n \/\/ We assume that this is your choice, so we reset the member.\n m_IsModified = false;\n \n m_Macros.clear();\n m_Variables.clear();\n \n wxXmlNode* root = doc.GetRoot();\n wxXmlNode* child = root->GetChildren();\n \n while (child)\n {\n if (child->GetName() == \"macro\")\n {\n std::vector v;\n \n wxXmlNode* command = child->GetChildren();\n \n while (command)\n {\n if (command->GetAttribute(\"encoded\", \"false\") == \"true\")\n {\n v.push_back(Decode(command->GetNodeContent()));\n }\n else\n {\n v.push_back(command->GetNodeContent());\n }\n \n command = command->GetNext();\n }\n \n std::map>::const_iterator it = \n m_Macros.find(child->GetAttribute(\"name\"));\n \n if (it != m_Macros.end())\n {\n wxLogError(\"Duplicate macro: %s on line: %d\", \n child->GetAttribute(\"name\"),\n child->GetLineNumber());\n }\n else\n {\n m_Macros.insert(std::make_pair(child->GetAttribute(\"name\"), v));\n }\n }\n else if (child->GetName() == \"variable\")\n {\n wxExVariable variable(child);\n \n std::map::const_iterator it = m_Variables.find(variable.GetName());\n \n if (it != m_Variables.end())\n {\n wxLogError(\"Duplicate variable: %s on line: %d\", \n variable.GetName(),\n child->GetLineNumber());\n }\n else\n {\n m_Variables.insert(std::make_pair(variable.GetName(), variable));\n }\n }\n \n child = child->GetNext();\n }\n \n return true;\n}\n\nbool wxExViMacros::Playback(wxExEx* ex, const wxString& macro, int repeat)\n{\n if (!IsRecorded(macro) || macro.empty())\n {\n wxLogStatus(_(\"Unknown macro\") + \": \" + macro);\n return false;\n }\n \n if (m_IsPlayback && macro == m_Macro)\n {\n wxLogStatus(_(\"Already playing back\"));\n return false;\n }\n\n if (repeat <= 0)\n {\n return false;\n }\n \n ex->GetSTC()->BeginUndoAction();\n \n bool stop = false;\n \n m_IsPlayback = true;\n \n m_Macro = macro;\n \n wxBusyCursor wait;\n \n AskForInput();\n \n for (int i = 0; i < repeat; i++)\n {\n for (\n std::vector::const_iterator it = m_Macros[macro].begin();\n it != m_Macros[macro].end() && !stop;\n ++it)\n { \n stop = !ex->Command(*it);\n \n if (stop)\n {\n wxLogStatus(_(\"Macro aborted at '\") + *it + \"'\");\n }\n }\n }\n\n ex->GetSTC()->EndUndoAction();\n\n if (!stop)\n {\n wxLogStatus(_(\"Macro played back\"));\n }\n \n m_IsPlayback = false;\n \n return !stop;\n}\n\nvoid wxExViMacros::Record(const wxString& text, bool new_command)\n{\n if (!m_IsRecording)\n {\n return;\n }\n \n m_IsModified = true;\n \n if (new_command) \n {\n m_Macros[m_Macro].push_back(text);\n }\n else\n {\n if (m_Macros[m_Macro].empty())\n {\n m_Macros[m_Macro].push_back(wxEmptyString);\n }\n \n m_Macros[m_Macro].back() += text;\n }\n}\n\nbool wxExViMacros::SaveDocument(bool only_if_modified)\n{\n if (!m_IsModified && only_if_modified)\n {\n return false;\n }\n \n wxXmlDocument doc;\n \n if (!Load(doc))\n {\n return false;\n }\n \n wxXmlNode* root = doc.GetRoot();\n wxXmlNode* child;\n \n while (child = root->GetChildren())\n {\n root->RemoveChild(child);\n delete child;\n }\n \n for (\n std::map >::reverse_iterator it = \n m_Macros.rbegin();\n it != m_Macros.rend();\n ++it)\n {\n wxXmlNode* element = new wxXmlNode(root, wxXML_ELEMENT_NODE, \"macro\");\n element->AddAttribute(\"name\", it->first);\n \n for (\n std::vector::reverse_iterator it2 = it->second.rbegin();\n it2 != it->second.rend();\n ++it2)\n { \n bool encoded = false; \n const wxString contents(Encode(*it2, encoded));\n \n wxXmlNode* cmd = new wxXmlNode(element, wxXML_ELEMENT_NODE, \"command\");\n new wxXmlNode(cmd, wxXML_TEXT_NODE, \"\", contents);\n \n if (encoded)\n {\n cmd->AddAttribute(\"encoded\", \"true\");\n }\n }\n }\n \n for (\n std::map< wxString, wxExVariable >::reverse_iterator it2 = \n m_Variables.rbegin();\n it2 != m_Variables.rend();\n ++it2)\n {\n wxXmlNode* element = new wxXmlNode(root, wxXML_ELEMENT_NODE, \"variable\");\n it2->second.Save(element);\n }\n \n const bool ok = doc.Save(GetFileName().GetFullPath());\n \n if (ok)\n {\n m_IsModified = false;\n }\n\n return ok;\n}\n\nvoid wxExViMacros::StartRecording(const wxString& macro)\n{\n if (m_IsRecording || macro.empty())\n {\n return;\n }\n \n m_IsRecording = true;\n \n if (macro.size() == 1)\n {\n \/\/ We only use lower case macro's, to be able to\n \/\/ append to them using qA.\n m_Macro = macro.Lower();\n \n \/\/ Clear macro if it is lower case\n \/\/ (otherwise append to the macro).\n if (wxIslower(macro[0]))\n {\n m_Macros[m_Macro].clear();\n }\n }\n else\n {\n m_Macro = macro;\n m_Macros[m_Macro].clear();\n }\n \n wxLogStatus(_(\"Macro recording\"));\n}\n\nvoid wxExViMacros::StopRecording()\n{\n if (!m_IsRecording)\n {\n return;\n }\n \n m_IsRecording = false;\n \n if (!Get(m_Macro).empty())\n {\n wxLogStatus(wxString::Format(_(\"Macro '%s' is recorded\"), m_Macro.c_str()));\n }\n else\n {\n wxLogStatus(_(\"Ready\"));\n }\n}\n\n#endif \/\/ wxUSE_GUI\n<|endoftext|>"} {"text":"\/** Copyright (C) 2016, 2017 European Spallation Source ERIC *\/\n\n#include \n#include \n#include \n#include \n#include \n\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wpedantic\"\n\nint fail = -1; \/\/ Dont fail\n\n\/\/ Create pointers to the retuned objects\ntypedef RdKafka::Conf *(*pcreate)(RdKafka::Conf::ConfType);\ntypedef RdKafka::Producer *(*pcreateprod)(RdKafka::Conf *, std::string &);\ntypedef RdKafka::Topic *(*pcreatetopic)(RdKafka::Handle *, std::string const &,\n RdKafka::Conf *, std::string &);\n\n\/**Attmpt to load primary and alternatively secondary symbols using dlsym()\n * Created to cover different compilations of librdkafka (old and new abis)\n * Used for forcing external functions to fail for unit testing purposes\n * exit if none of the symbols can be loaded.\n**\/\nvoid * loadsyms(const char * primary, const char * secondary) {\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wpedantic\"\n\n void * vpsym = dlsym(RTLD_NEXT, primary);\n\n if (vpsym == NULL) {\n printf(\"Could not load primary symbol: %s\\n\", primary);\n printf(\"Trying secondary...\\n\");\n\n dlerror();\n vpsym = dlsym(RTLD_NEXT, secondary);\n if (vpsym == NULL) {\n printf(\"Could not load secondary symbol: %s\\n\", secondary);\n printf(\"Error stubbing kafka functions\\n\");\n exit(1);\n }\n }\n#pragma GCC diagnostic pop\n return vpsym;\n}\n\n\n\/** Intercept RdKafka::Conf::create() *\/\nRdKafka::Conf *RdKafka::Conf::create(ConfType type) {\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wpedantic\"\n pcreate real_create = (pcreate)loadsyms(\n \"_ZN7RdKafka4Conf6createENS0_8ConfTypeE\",\n \"_ZN7RdKafka4Conf6createENS0_8ConfTypeE\"); \/\/ nm -C\n#pragma GCC diagnostic pop\n\n if (fail != -1 && type == fail) {\n printf(\"Forcing RdKafka::Conf::create() to fail\\n\");\n return nullptr;\n } else {\n return real_create(type);\n }\n}\n\n\n\/** Intercept RdKafka::Producer::create() *\/\nRdKafka::Producer *RdKafka::Producer::create(RdKafka::Conf *type,\n std::string &str) {\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wpedantic\"\n pcreateprod real_create = (pcreateprod)loadsyms(\n \"_ZN7RdKafka8Producer6createEPNS_4ConfERSs\",\n \"_ZN7RdKafka8Producer6createEPNS_4ConfERNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE\"); \/\/ nm -C librdkafka.a\n#pragma GCC diagnostic pop\n\n if (fail == 777) {\n printf(\"Forcing RdKafka::Producer::create() to fail\\n\");\n return nullptr;\n } else {\n return real_create(type, str);\n }\n}\n\n\n\/** Intercept RdKafka::Topic::create() *\/\nRdKafka::Topic *RdKafka::Topic::create(RdKafka::Handle *handle,\n std::string const &topic,\n RdKafka::Conf *conf, std::string &str) {\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wpedantic\"\n pcreatetopic real_create = (pcreatetopic)loadsyms(\n \"_ZN7RdKafka5Topic6createEPNS_6HandleERKSsPNS_4ConfERSs\",\n \"_ZN7RdKafka5Topic6createEPNS_6HandleERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPNS_4ConfERS8_\");\n#pragma GCC diagnostic pop\n\n if (fail == 888) {\n printf(\"Forcing RdKafka::Topic::create() to fail\\n\");\n return nullptr;\n } else {\n return real_create(handle, topic, conf, str);\n }\n}\n\n\/\/\n\/\/ Google test code below\n\/\/\n\nclass ProducerTest : public TestBase {\n virtual void SetUp() { fail = -1; }\n virtual void TearDown() {}\n};\n\nTEST_F(ProducerTest, ConstructorOK) {\n Producer prod{\"nobroker\", \"notopic\"};\n int ret = prod.produce(0, 0);\n ASSERT_EQ(ret, RdKafka::ERR_NO_ERROR);\n ASSERT_EQ(prod.dr_errors, 0);\n ASSERT_EQ(prod.dr_noerrors, 0);\n ASSERT_EQ(prod.ev_errors, 0);\n ASSERT_EQ(prod.stats.ev_others, 0);\n}\n\nTEST_F(ProducerTest, CreateConfGlobalFail) {\n fail = RdKafka::Conf::CONF_GLOBAL;\n Producer prod{\"nobroker\", \"notopic\"};\n int ret = prod.produce(0, 0);\n ASSERT_EQ(ret, RdKafka::ERR_UNKNOWN);\n}\n\nTEST_F(ProducerTest, CreateConfTopicFail) {\n fail = RdKafka::Conf::CONF_TOPIC;\n Producer prod{\"nobroker\", \"notopic\"};\n int ret = prod.produce(0, 0);\n ASSERT_EQ(ret, RdKafka::ERR_UNKNOWN);\n}\n\nTEST_F(ProducerTest, CreateProducerFail) {\n fail = 777;\n Producer prod{\"nobroker\", \"notopic\"};\n int ret = prod.produce(0, 0);\n ASSERT_EQ(ret, RdKafka::ERR_UNKNOWN);\n}\n\nTEST_F(ProducerTest, CreateTopicFail) {\n fail = 888;\n Producer prod{\"nobroker\", \"notopic\"};\n int ret = prod.produce(0, 0);\n ASSERT_EQ(ret, RdKafka::ERR_UNKNOWN);\n\n}\n\nTEST_F(ProducerTest, ProducerFail) {\n Producer prod{\"nobroker\", \"notopic\"};\n int ret = prod.produce((char *)10000, 100000000);\n ASSERT_EQ(ret, RdKafka::ERR_MSG_SIZE_TOO_LARGE);\n}\n\nint main(int argc, char **argv) {\n testing::InitGoogleTest(&argc, argv);\n return RUN_ALL_TESTS();\n}\n\n#pragma GCC diagnostic pop\nfixing unit test\/** Copyright (C) 2016, 2017 European Spallation Source ERIC *\/\n\n#include \n#include \n#include \n#include \n#include \n\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wpedantic\"\n\nint fail = -1; \/\/ Dont fail\n\n\/\/ Create pointers to the retuned objects\ntypedef RdKafka::Conf *(*pcreate)(RdKafka::Conf::ConfType);\ntypedef RdKafka::Producer *(*pcreateprod)(RdKafka::Conf *, std::string &);\ntypedef RdKafka::Topic *(*pcreatetopic)(RdKafka::Handle *, std::string const &,\n RdKafka::Conf *, std::string &);\n\n\/**Attmpt to load primary and alternatively secondary symbols using dlsym()\n * Created to cover different compilations of librdkafka (old and new abis)\n * Used for forcing external functions to fail for unit testing purposes\n * exit if none of the symbols can be loaded.\n**\/\nvoid * loadsyms(const char * primary, const char * secondary) {\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wpedantic\"\n\n void * vpsym = dlsym(RTLD_NEXT, primary);\n\n if (vpsym == NULL) {\n printf(\"Could not load primary symbol: %s\\n\", primary);\n printf(\"Trying secondary...\\n\");\n\n dlerror();\n vpsym = dlsym(RTLD_NEXT, secondary);\n if (vpsym == NULL) {\n printf(\"Could not load secondary symbol: %s\\n\", secondary);\n printf(\"Error stubbing kafka functions\\n\");\n exit(1);\n }\n }\n#pragma GCC diagnostic pop\n return vpsym;\n}\n\n\n\/** Intercept RdKafka::Conf::create() *\/\nRdKafka::Conf *RdKafka::Conf::create(ConfType type) {\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wpedantic\"\n pcreate real_create = (pcreate)loadsyms(\n \"_ZN7RdKafka4Conf6createENS0_8ConfTypeE\",\n \"_ZN7RdKafka4Conf6createENS0_8ConfTypeE\"); \/\/ nm -C\n#pragma GCC diagnostic pop\n\n if (fail != -1 && type == fail) {\n printf(\"Forcing RdKafka::Conf::create() to fail\\n\");\n return nullptr;\n } else {\n return real_create(type);\n }\n}\n\n\n\/** Intercept RdKafka::Producer::create() *\/\nRdKafka::Producer *RdKafka::Producer::create(RdKafka::Conf *type,\n std::string &str) {\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wpedantic\"\n pcreateprod real_create = (pcreateprod)loadsyms(\n \"_ZN7RdKafka8Producer6createEPNS_4ConfERSs\",\n \"_ZN7RdKafka8Producer6createEPNS_4ConfERNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE\"); \/\/ nm -C librdkafka.a\n#pragma GCC diagnostic pop\n\n if (fail == 777) {\n printf(\"Forcing RdKafka::Producer::create() to fail\\n\");\n return nullptr;\n } else {\n return real_create(type, str);\n }\n}\n\n\n\/** Intercept RdKafka::Topic::create() *\/\nRdKafka::Topic *RdKafka::Topic::create(RdKafka::Handle *handle,\n std::string const &topic,\n RdKafka::Conf *conf, std::string &str) {\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wpedantic\"\n pcreatetopic real_create = (pcreatetopic)loadsyms(\n \"_ZN7RdKafka5Topic6createEPNS_6HandleERKSsPNS_4ConfERSs\",\n \"_ZN7RdKafka5Topic6createEPNS_6HandleERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPNS_4ConfERS8_\");\n#pragma GCC diagnostic pop\n\n if (fail == 888) {\n printf(\"Forcing RdKafka::Topic::create() to fail\\n\");\n return nullptr;\n } else {\n return real_create(handle, topic, conf, str);\n }\n}\n\n\/\/\n\/\/ Google test code below\n\/\/\n\nclass ProducerTest : public TestBase {\n virtual void SetUp() { fail = -1; }\n virtual void TearDown() {}\n};\n\nTEST_F(ProducerTest, ConstructorOK) {\n Producer prod{\"nobroker\", \"notopic\"};\n int ret = prod.produce(0, 0);\n ASSERT_EQ(ret, RdKafka::ERR_NO_ERROR);\n ASSERT_EQ(prod.stats.dr_errors, 0);\n ASSERT_EQ(prod.stats.dr_noerrors, 0);\n ASSERT_EQ(prod.stats.ev_errors, 0);\n ASSERT_EQ(prod.stats.ev_others, 0);\n ASSERT_EQ(prod.stats.produce_fails, 0);\n}\n\nTEST_F(ProducerTest, CreateConfGlobalFail) {\n fail = RdKafka::Conf::CONF_GLOBAL;\n Producer prod{\"nobroker\", \"notopic\"};\n int ret = prod.produce(0, 0);\n ASSERT_EQ(ret, RdKafka::ERR_UNKNOWN);\n}\n\nTEST_F(ProducerTest, CreateConfTopicFail) {\n fail = RdKafka::Conf::CONF_TOPIC;\n Producer prod{\"nobroker\", \"notopic\"};\n int ret = prod.produce(0, 0);\n ASSERT_EQ(ret, RdKafka::ERR_UNKNOWN);\n}\n\nTEST_F(ProducerTest, CreateProducerFail) {\n fail = 777;\n Producer prod{\"nobroker\", \"notopic\"};\n int ret = prod.produce(0, 0);\n ASSERT_EQ(ret, RdKafka::ERR_UNKNOWN);\n}\n\nTEST_F(ProducerTest, CreateTopicFail) {\n fail = 888;\n Producer prod{\"nobroker\", \"notopic\"};\n int ret = prod.produce(0, 0);\n ASSERT_EQ(ret, RdKafka::ERR_UNKNOWN);\n\n}\n\nTEST_F(ProducerTest, ProducerFail) {\n Producer prod{\"nobroker\", \"notopic\"};\n int ret = prod.produce((char *)10000, 100000000);\n ASSERT_EQ(ret, RdKafka::ERR_MSG_SIZE_TOO_LARGE);\n}\n\nint main(int argc, char **argv) {\n testing::InitGoogleTest(&argc, argv);\n return RUN_ALL_TESTS();\n}\n\n#pragma GCC diagnostic pop\n<|endoftext|>"} {"text":"\/*----------------------------------------------------------------------------*\/\n\/* Copyright (c) FIRST 2015-2017. All Rights Reserved. *\/\n\/* Open Source Software - may be modified and shared by FRC teams. The code *\/\n\/* must be accompanied by the FIRST BSD license file in the root directory of *\/\n\/* the project. *\/\n\/*----------------------------------------------------------------------------*\/\n\n#include \"InstanceImpl.h\"\n\nusing namespace nt;\n\nstd::atomic InstanceImpl::s_default{-1};\nstd::atomic InstanceImpl::s_fast_instances[10];\nwpi::UidVector, 10> InstanceImpl::s_instances;\nstd::mutex InstanceImpl::s_mutex;\n\nusing namespace std::placeholders;\n\nInstanceImpl::InstanceImpl(int inst)\n : logger_impl(inst),\n logger(std::bind(&LoggerImpl::Log, &logger_impl, _1, _2, _3, _4)),\n connection_notifier(inst),\n entry_notifier(inst, logger),\n rpc_server(inst, logger),\n storage(entry_notifier, rpc_server, logger),\n dispatcher(storage, connection_notifier, logger),\n ds_client(dispatcher, logger) {}\n\nInstanceImpl::~InstanceImpl() { logger.SetLogger(nullptr); }\n\nInstanceImpl* InstanceImpl::GetDefault() { return Get(GetDefaultIndex()); }\n\nInstanceImpl* InstanceImpl::Get(int inst) {\n if (inst < 0) return nullptr;\n\n \/\/ fast path, just an atomic read\n if (static_cast(inst) <\n (sizeof(s_fast_instances) \/ sizeof(s_fast_instances[0]))) {\n InstanceImpl* ptr = s_fast_instances[inst];\n if (ptr) return ptr;\n }\n\n \/\/ slow path\n std::lock_guard lock(s_mutex);\n\n \/\/ static fast-path block\n if (static_cast(inst) <\n (sizeof(s_fast_instances) \/ sizeof(s_fast_instances[0]))) {\n \/\/ double-check\n return s_fast_instances[inst];\n }\n\n \/\/ vector\n if (static_cast(inst) < s_instances.size()) {\n return s_instances[inst].get();\n }\n\n \/\/ doesn't exist\n return nullptr;\n}\n\nint InstanceImpl::GetDefaultIndex() {\n int inst = s_default;\n if (inst >= 0) return inst;\n\n \/\/ slow path\n std::lock_guard lock(s_mutex);\n\n \/\/ double-check\n inst = s_default;\n if (inst >= 0) return inst;\n\n \/\/ alloc and save\n inst = AllocImpl();\n s_default = inst;\n return inst;\n}\n\nint InstanceImpl::Alloc() {\n std::lock_guard lock(s_mutex);\n return AllocImpl();\n}\n\nint InstanceImpl::AllocImpl() {\n unsigned int inst = s_instances.emplace_back();\n InstanceImpl* ptr = new InstanceImpl(inst);\n s_instances[inst].reset(ptr);\n\n if (inst < (sizeof(s_fast_instances) \/ sizeof(s_fast_instances[0]))) {\n s_fast_instances[inst] = ptr;\n }\n\n return static_cast(inst);\n}\n\nvoid InstanceImpl::Destroy(int inst) {\n std::lock_guard lock(s_mutex);\n if (inst < 0 || static_cast(inst) >= s_instances.size()) return;\n\n if (static_cast(inst) <\n (sizeof(s_fast_instances) \/ sizeof(s_fast_instances[0]))) {\n s_fast_instances[inst] = nullptr;\n }\n\n s_instances.erase(inst);\n}\nInitialize logger min level from logger_impl.\/*----------------------------------------------------------------------------*\/\n\/* Copyright (c) FIRST 2015-2017. All Rights Reserved. *\/\n\/* Open Source Software - may be modified and shared by FRC teams. The code *\/\n\/* must be accompanied by the FIRST BSD license file in the root directory of *\/\n\/* the project. *\/\n\/*----------------------------------------------------------------------------*\/\n\n#include \"InstanceImpl.h\"\n\nusing namespace nt;\n\nstd::atomic InstanceImpl::s_default{-1};\nstd::atomic InstanceImpl::s_fast_instances[10];\nwpi::UidVector, 10> InstanceImpl::s_instances;\nstd::mutex InstanceImpl::s_mutex;\n\nusing namespace std::placeholders;\n\nInstanceImpl::InstanceImpl(int inst)\n : logger_impl(inst),\n logger(std::bind(&LoggerImpl::Log, &logger_impl, _1, _2, _3, _4)),\n connection_notifier(inst),\n entry_notifier(inst, logger),\n rpc_server(inst, logger),\n storage(entry_notifier, rpc_server, logger),\n dispatcher(storage, connection_notifier, logger),\n ds_client(dispatcher, logger) {\n logger.set_min_level(logger_impl.GetMinLevel());\n}\n\nInstanceImpl::~InstanceImpl() { logger.SetLogger(nullptr); }\n\nInstanceImpl* InstanceImpl::GetDefault() { return Get(GetDefaultIndex()); }\n\nInstanceImpl* InstanceImpl::Get(int inst) {\n if (inst < 0) return nullptr;\n\n \/\/ fast path, just an atomic read\n if (static_cast(inst) <\n (sizeof(s_fast_instances) \/ sizeof(s_fast_instances[0]))) {\n InstanceImpl* ptr = s_fast_instances[inst];\n if (ptr) return ptr;\n }\n\n \/\/ slow path\n std::lock_guard lock(s_mutex);\n\n \/\/ static fast-path block\n if (static_cast(inst) <\n (sizeof(s_fast_instances) \/ sizeof(s_fast_instances[0]))) {\n \/\/ double-check\n return s_fast_instances[inst];\n }\n\n \/\/ vector\n if (static_cast(inst) < s_instances.size()) {\n return s_instances[inst].get();\n }\n\n \/\/ doesn't exist\n return nullptr;\n}\n\nint InstanceImpl::GetDefaultIndex() {\n int inst = s_default;\n if (inst >= 0) return inst;\n\n \/\/ slow path\n std::lock_guard lock(s_mutex);\n\n \/\/ double-check\n inst = s_default;\n if (inst >= 0) return inst;\n\n \/\/ alloc and save\n inst = AllocImpl();\n s_default = inst;\n return inst;\n}\n\nint InstanceImpl::Alloc() {\n std::lock_guard lock(s_mutex);\n return AllocImpl();\n}\n\nint InstanceImpl::AllocImpl() {\n unsigned int inst = s_instances.emplace_back();\n InstanceImpl* ptr = new InstanceImpl(inst);\n s_instances[inst].reset(ptr);\n\n if (inst < (sizeof(s_fast_instances) \/ sizeof(s_fast_instances[0]))) {\n s_fast_instances[inst] = ptr;\n }\n\n return static_cast(inst);\n}\n\nvoid InstanceImpl::Destroy(int inst) {\n std::lock_guard lock(s_mutex);\n if (inst < 0 || static_cast(inst) >= s_instances.size()) return;\n\n if (static_cast(inst) <\n (sizeof(s_fast_instances) \/ sizeof(s_fast_instances[0]))) {\n s_fast_instances[inst] = nullptr;\n }\n\n s_instances.erase(inst);\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2019 DeepMind Technologies Ltd. All rights reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"open_spiel\/games\/othello.h\"\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"open_spiel\/spiel_utils.h\"\n#include \"open_spiel\/utils\/tensor_view.h\"\n\nnamespace open_spiel {\nnamespace othello {\nnamespace {\n\n\/\/ Facts about the game.\nconst GameType kGameType{\n \/*short_name=*\/\"othello\",\n \/*long_name=*\/\"Othello\",\n GameType::Dynamics::kSequential,\n GameType::ChanceMode::kDeterministic,\n GameType::Information::kPerfectInformation,\n GameType::Utility::kZeroSum,\n GameType::RewardModel::kTerminal,\n \/*max_num_players=*\/2,\n \/*min_num_players=*\/2,\n \/*provides_information_state_string=*\/true,\n \/*provides_information_state_tensor=*\/false,\n \/*provides_observation_string=*\/true,\n \/*provides_observation_tensor=*\/true,\n \/*parameter_specification=*\/{} \/\/ no parameters\n};\n\nstd::shared_ptr Factory(const GameParameters& params) {\n return std::shared_ptr(new OthelloGame(params));\n}\n\nREGISTER_SPIEL_GAME(kGameType, Factory);\n\n} \/\/ namespace\n\nstd::tuple GetNext(int row, int col, Direction dir) {\n switch (dir) {\n case Direction::kUp:\n return std::make_tuple(row - 1, col);\n case Direction::kDown:\n return std::make_tuple(row + 1, col);\n case Direction::kLeft:\n return std::make_tuple(row, col - 1);\n case Direction::kRight:\n return std::make_tuple(row, col + 1);\n case Direction::kUpRight:\n return std::make_tuple(row - 1, col + 1);\n case Direction::kUpLeft:\n return std::make_tuple(row - 1, col - 1);\n case Direction::kDownRight:\n return std::make_tuple(row + 1, col + 1);\n case Direction::kDownLeft:\n return std::make_tuple(row + 1, col - 1);\n default:\n SpielFatalError(absl::StrCat(\"Found unmatched case in GetNext.\"));\n }\n}\n\ninline bool OthelloState::OnBoard(int row, int col) const {\n return (0 <= row) && (row < kNumRows) && (0 <= col) && (col < kNumCols);\n}\n\nint OthelloState::CountSteps(Player player, int row, int col, Direction dir) const {\n std::tuple rowcol = GetNext(row, col, dir);\n row = std::get<0>(rowcol);\n col = std::get<1>(rowcol);\n\n int count = 0;\n CellState cell = PlayerToState(player);\n while (OnBoard(row, col)) {\n if (BoardAt(row, col) == cell) {\n return count;\n } else if (BoardAt(row, col) == CellState::kEmpty) {\n return 0;\n }\n \n count++;\n rowcol = GetNext(row, col, dir);\n row = std::get<0>(rowcol);\n col = std::get<1>(rowcol);\n }\n\n return 0;\n}\n\nbool OthelloState::CanCapture(Player player, int move) const {\n if (board_[move] != CellState::kEmpty) return false;\n\n std::tuple row_col = XYFromCode(move);\n int row = std::get<0>(row_col);\n int col = std::get<1>(row_col);\n\n \/\/ bool none_adjacent = true;\n \/\/ for (int i = -1; i < 2; i++) {\n \/\/ for (int j = -1; j < 2; j++) {\n \/\/ if (OnBoard(row + i, col + j) && (BoardAt(row + i, col + j) != CellState::kEmpty)) none_adjacent = false;\n \/\/ }\n \/\/ }\n\n \/\/ if (none_adjacent) return false;\n\n bool valid = false;\n for (int direction = Direction::kUp; direction < Direction::kLast; direction++) {\n if (CountSteps(player, row, col, static_cast(direction)) != 0) {\n return true;\n }\n }\n\n return false;\n}\n\nvoid OthelloState::Capture(Player player, int row, int col, Direction dir, int steps) {\n std::tuple rowcol = GetNext(row, col, dir);\n row = std::get<0>(rowcol);\n col = std::get<1>(rowcol);\n CellState cell = PlayerToState(player);\n\n for (int step = 0; step < steps; step++) {\n if (BoardAt(row, col) == CellState::kEmpty || BoardAt(row, col) == cell) {\n SpielFatalError(absl::StrCat(\"Cannot capture cell (\", row, \", \", col, \")\"));\n }\n\n board_[row * kNumCols + col] = cell;\n \n rowcol = GetNext(row, col, dir);\n row = std::get<0>(rowcol);\n col = std::get<1>(rowcol);\n }\n}\n\nint OthelloState::DiskCount(Player player) const {\n int count = 0;\n CellState cell = PlayerToState(player);\n for (int i = 0; i < kNumCells; i++) {\n if (board_[i] == cell) count++;\n }\n\n return count;\n}\n\nbool OthelloState::NoValidActions() const {\n return (LegalRegularActions(Player(0)).empty() & LegalRegularActions(Player(1)).empty());\n}\n\nstd::tuple OthelloState::XYFromCode(int move) const {\n if (move >= kNumCells || move < 0) {\n SpielFatalError(absl::StrCat(\"Move too large: \", move));\n }\n\n return std::make_tuple(move \/ kNumCols, move % kNumRows);\n}\n\nCellState PlayerToState(Player player) {\n switch (player) {\n case 0:\n return CellState::kBlack;\n case 1:\n return CellState::kWhite;\n default:\n SpielFatalError(absl::StrCat(\"Invalid player id \", player));\n return CellState::kEmpty;\n }\n}\n\nstd::string StateToString(CellState state) {\n switch (state) {\n case CellState::kEmpty:\n return \".\";\n case CellState::kWhite:\n return \"o\";\n case CellState::kBlack:\n return \"x\";\n default:\n SpielFatalError(\"Unknown state.\");\n }\n}\n\nbool OthelloState::ValidAction(Player player, int move) const {\n return (board_[move] == CellState::kEmpty && CanCapture(player, move));\n}\n\nvoid OthelloState::DoApplyAction(Action move) {\n if (move == passMove) { \/\/ pass\n current_player_ = 1 - current_player_;\n num_moves_ += 1;\n return;\n }\n\n if (!ValidAction(current_player_, move)) {\n SpielFatalError(absl::StrCat(\"Invalid move \", move));\n }\n\n std::tuple rowcol = XYFromCode(move);\n CellState cell = PlayerToState(current_player_);\n\n int row = std::get<0>(rowcol);\n int col = std::get<1>(rowcol);\n board_[row * kNumCols + col] = cell;\n \n for (int direction = Direction::kUp; direction < Direction::kLast; direction++) {\n int steps = 0;\n if ((steps = CountSteps(current_player_, row, col, static_cast(direction))) > 0) {\n Capture(current_player_, row, col, static_cast(direction), steps);\n }\n }\n\n if (NoValidActions()) {\n int count_zero = DiskCount(Player(0));\n int count_one = DiskCount(Player(1));\n\n if (count_zero > count_one) {\n outcome_ = Player(0);\n } else if (count_zero < count_one) {\n outcome_ = Player(1);\n }\n }\n\n current_player_ = 1 - current_player_;\n num_moves_ += 1;\n}\n\nstd::vector OthelloState::LegalRegularActions(Player p) const { \/\/ list \n std::vector moves;\n for (int cell = 0; cell < kNumCells; ++cell) {\n if (ValidAction(p, cell)) {\n moves.push_back(cell);\n }\n }\n\n return moves;\n}\n\nstd::vector OthelloState::LegalActions() const {\n if (IsTerminal()) return {};\n \n \/\/ can move in an empty cell that captures\n std::vector moves = LegalRegularActions(current_player_);\n if (moves.empty()) {\n moves.push_back(passMove); \/\/ pass\n }\n\n return moves;\n}\n\nstd::string OthelloState::ActionToString(Player player,\n Action action_id) const {\n\n if (action_id == passMove) {\n return absl::StrCat(StateToString(PlayerToState(player)), \"(pass)\");\n } else {\n return absl::StrCat(StateToString(PlayerToState(player)), \"(\",\n action_id \/ kNumCols, \",\", action_id % kNumCols, \")\");\n }\n}\n\nbool OthelloState::IsFull() const { \n for (int i = 0; i < kNumCells; i++) {\n if (board_[i] == CellState::kEmpty) return false;\n }\n\n return true;\n}\n\nOthelloState::OthelloState(std::shared_ptr game) : State(game) {\n std::fill(begin(board_), end(board_), CellState::kEmpty);\n board_[27] = CellState::kWhite;\n board_[28] = CellState::kBlack;\n board_[35] = CellState::kBlack;\n board_[36] = CellState::kWhite;\n}\n\nstd::string OthelloState::ToString() const {\n std::string str;\n for (int r = 0; r < kNumRows; ++r) {\n for (int c = 0; c < kNumCols; ++c) {\n absl::StrAppend(&str, StateToString(BoardAt(r, c)));\n }\n if (r < (kNumRows - 1)) {\n absl::StrAppend(&str, \"\\n\");\n }\n }\n return str;\n}\n\nbool OthelloState::IsTerminal() const {\n return outcome_ != kInvalidPlayer || NoValidActions();\n}\n\nstd::vector OthelloState::Returns() const {\n if (outcome_ == Player{0}) {\n return {1.0, -1.0};\n } else if (outcome_ == Player{1}) {\n return {-1.0, 1.0};\n } else {\n return {0.0, 0.0};\n }\n}\n\nstd::string OthelloState::InformationStateString(Player player) const {\n return HistoryString();\n}\n\nstd::string OthelloState::ObservationString(Player player) const {\n SPIEL_CHECK_GE(player, 0);\n SPIEL_CHECK_LT(player, num_players_);\n return ToString();\n}\n\nvoid OthelloState::ObservationTensor(Player player,\n std::vector* values) const {\n SPIEL_CHECK_GE(player, 0);\n SPIEL_CHECK_LT(player, num_players_);\n\n \/\/ Treat `values` as a 2-d tensor.\n TensorView<2> view(values, {kCellStates, kNumCells}, true);\n for (int cell = 0; cell < kNumCells; ++cell) {\n view[{static_cast(board_[cell]), cell}] = 1.0;\n }\n}\n\nvoid OthelloState::UndoAction(Player player, Action move) {\n SpielFatalError(\"Undo not implemented for this game.\");\n}\n\nstd::unique_ptr OthelloState::Clone() const {\n return std::unique_ptr(new OthelloState(*this));\n}\n\nOthelloGame::OthelloGame(const GameParameters& params)\n : Game(kGameType, params) {}\n\n} \/\/ namespace othello\n} \/\/ namespace open_spiel\nremoved commented code\/\/ Copyright 2019 DeepMind Technologies Ltd. All rights reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"open_spiel\/games\/othello.h\"\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"open_spiel\/spiel_utils.h\"\n#include \"open_spiel\/utils\/tensor_view.h\"\n\nnamespace open_spiel {\nnamespace othello {\nnamespace {\n\n\/\/ Facts about the game.\nconst GameType kGameType{\n \/*short_name=*\/\"othello\",\n \/*long_name=*\/\"Othello\",\n GameType::Dynamics::kSequential,\n GameType::ChanceMode::kDeterministic,\n GameType::Information::kPerfectInformation,\n GameType::Utility::kZeroSum,\n GameType::RewardModel::kTerminal,\n \/*max_num_players=*\/2,\n \/*min_num_players=*\/2,\n \/*provides_information_state_string=*\/true,\n \/*provides_information_state_tensor=*\/false,\n \/*provides_observation_string=*\/true,\n \/*provides_observation_tensor=*\/true,\n \/*parameter_specification=*\/{} \/\/ no parameters\n};\n\nstd::shared_ptr Factory(const GameParameters& params) {\n return std::shared_ptr(new OthelloGame(params));\n}\n\nREGISTER_SPIEL_GAME(kGameType, Factory);\n\n} \/\/ namespace\n\nstd::tuple GetNext(int row, int col, Direction dir) {\n switch (dir) {\n case Direction::kUp:\n return std::make_tuple(row - 1, col);\n case Direction::kDown:\n return std::make_tuple(row + 1, col);\n case Direction::kLeft:\n return std::make_tuple(row, col - 1);\n case Direction::kRight:\n return std::make_tuple(row, col + 1);\n case Direction::kUpRight:\n return std::make_tuple(row - 1, col + 1);\n case Direction::kUpLeft:\n return std::make_tuple(row - 1, col - 1);\n case Direction::kDownRight:\n return std::make_tuple(row + 1, col + 1);\n case Direction::kDownLeft:\n return std::make_tuple(row + 1, col - 1);\n default:\n SpielFatalError(absl::StrCat(\"Found unmatched case in GetNext.\"));\n }\n}\n\ninline bool OthelloState::OnBoard(int row, int col) const {\n return (0 <= row) && (row < kNumRows) && (0 <= col) && (col < kNumCols);\n}\n\nint OthelloState::CountSteps(Player player, int row, int col, Direction dir) const {\n std::tuple rowcol = GetNext(row, col, dir);\n row = std::get<0>(rowcol);\n col = std::get<1>(rowcol);\n\n int count = 0;\n CellState cell = PlayerToState(player);\n while (OnBoard(row, col)) {\n if (BoardAt(row, col) == cell) {\n return count;\n } else if (BoardAt(row, col) == CellState::kEmpty) {\n return 0;\n }\n \n count++;\n rowcol = GetNext(row, col, dir);\n row = std::get<0>(rowcol);\n col = std::get<1>(rowcol);\n }\n\n return 0;\n}\n\nbool OthelloState::CanCapture(Player player, int move) const {\n if (board_[move] != CellState::kEmpty) return false;\n\n std::tuple row_col = XYFromCode(move);\n int row = std::get<0>(row_col);\n int col = std::get<1>(row_col);\n\n bool valid = false;\n for (int direction = Direction::kUp; direction < Direction::kLast; direction++) {\n if (CountSteps(player, row, col, static_cast(direction)) != 0) {\n return true;\n }\n }\n\n return false;\n}\n\nvoid OthelloState::Capture(Player player, int row, int col, Direction dir, int steps) {\n std::tuple rowcol = GetNext(row, col, dir);\n row = std::get<0>(rowcol);\n col = std::get<1>(rowcol);\n CellState cell = PlayerToState(player);\n\n for (int step = 0; step < steps; step++) {\n if (BoardAt(row, col) == CellState::kEmpty || BoardAt(row, col) == cell) {\n SpielFatalError(absl::StrCat(\"Cannot capture cell (\", row, \", \", col, \")\"));\n }\n\n board_[row * kNumCols + col] = cell;\n \n rowcol = GetNext(row, col, dir);\n row = std::get<0>(rowcol);\n col = std::get<1>(rowcol);\n }\n}\n\nint OthelloState::DiskCount(Player player) const {\n int count = 0;\n CellState cell = PlayerToState(player);\n for (int i = 0; i < kNumCells; i++) {\n if (board_[i] == cell) count++;\n }\n\n return count;\n}\n\nbool OthelloState::NoValidActions() const {\n return (LegalRegularActions(Player(0)).empty() & LegalRegularActions(Player(1)).empty());\n}\n\nstd::tuple OthelloState::XYFromCode(int move) const {\n if (move >= kNumCells || move < 0) {\n SpielFatalError(absl::StrCat(\"Move too large: \", move));\n }\n\n return std::make_tuple(move \/ kNumCols, move % kNumRows);\n}\n\nCellState PlayerToState(Player player) {\n switch (player) {\n case 0:\n return CellState::kBlack;\n case 1:\n return CellState::kWhite;\n default:\n SpielFatalError(absl::StrCat(\"Invalid player id \", player));\n return CellState::kEmpty;\n }\n}\n\nstd::string StateToString(CellState state) {\n switch (state) {\n case CellState::kEmpty:\n return \".\";\n case CellState::kWhite:\n return \"o\";\n case CellState::kBlack:\n return \"x\";\n default:\n SpielFatalError(\"Unknown state.\");\n }\n}\n\nbool OthelloState::ValidAction(Player player, int move) const {\n return (board_[move] == CellState::kEmpty && CanCapture(player, move));\n}\n\nvoid OthelloState::DoApplyAction(Action move) {\n if (move == passMove) { \/\/ pass\n current_player_ = 1 - current_player_;\n num_moves_ += 1;\n return;\n }\n\n if (!ValidAction(current_player_, move)) {\n SpielFatalError(absl::StrCat(\"Invalid move \", move));\n }\n\n std::tuple rowcol = XYFromCode(move);\n CellState cell = PlayerToState(current_player_);\n\n int row = std::get<0>(rowcol);\n int col = std::get<1>(rowcol);\n board_[row * kNumCols + col] = cell;\n \n for (int direction = Direction::kUp; direction < Direction::kLast; direction++) {\n int steps = 0;\n if ((steps = CountSteps(current_player_, row, col, static_cast(direction))) > 0) {\n Capture(current_player_, row, col, static_cast(direction), steps);\n }\n }\n\n if (NoValidActions()) {\n int count_zero = DiskCount(Player(0));\n int count_one = DiskCount(Player(1));\n\n if (count_zero > count_one) {\n outcome_ = Player(0);\n } else if (count_zero < count_one) {\n outcome_ = Player(1);\n }\n }\n\n current_player_ = 1 - current_player_;\n num_moves_ += 1;\n}\n\nstd::vector OthelloState::LegalRegularActions(Player p) const { \/\/ list \n std::vector moves;\n for (int cell = 0; cell < kNumCells; ++cell) {\n if (ValidAction(p, cell)) {\n moves.push_back(cell);\n }\n }\n\n return moves;\n}\n\nstd::vector OthelloState::LegalActions() const {\n if (IsTerminal()) return {};\n \n \/\/ can move in an empty cell that captures\n std::vector moves = LegalRegularActions(current_player_);\n if (moves.empty()) {\n moves.push_back(passMove); \/\/ pass\n }\n\n return moves;\n}\n\nstd::string OthelloState::ActionToString(Player player,\n Action action_id) const {\n\n if (action_id == passMove) {\n return absl::StrCat(StateToString(PlayerToState(player)), \"(pass)\");\n } else {\n return absl::StrCat(StateToString(PlayerToState(player)), \"(\",\n action_id \/ kNumCols, \",\", action_id % kNumCols, \")\");\n }\n}\n\nbool OthelloState::IsFull() const { \n for (int i = 0; i < kNumCells; i++) {\n if (board_[i] == CellState::kEmpty) return false;\n }\n\n return true;\n}\n\nOthelloState::OthelloState(std::shared_ptr game) : State(game) {\n std::fill(begin(board_), end(board_), CellState::kEmpty);\n board_[27] = CellState::kWhite;\n board_[28] = CellState::kBlack;\n board_[35] = CellState::kBlack;\n board_[36] = CellState::kWhite;\n}\n\nstd::string OthelloState::ToString() const {\n std::string str;\n for (int r = 0; r < kNumRows; ++r) {\n for (int c = 0; c < kNumCols; ++c) {\n absl::StrAppend(&str, StateToString(BoardAt(r, c)));\n }\n if (r < (kNumRows - 1)) {\n absl::StrAppend(&str, \"\\n\");\n }\n }\n return str;\n}\n\nbool OthelloState::IsTerminal() const {\n return outcome_ != kInvalidPlayer || NoValidActions();\n}\n\nstd::vector OthelloState::Returns() const {\n if (outcome_ == Player{0}) {\n return {1.0, -1.0};\n } else if (outcome_ == Player{1}) {\n return {-1.0, 1.0};\n } else {\n return {0.0, 0.0};\n }\n}\n\nstd::string OthelloState::InformationStateString(Player player) const {\n return HistoryString();\n}\n\nstd::string OthelloState::ObservationString(Player player) const {\n SPIEL_CHECK_GE(player, 0);\n SPIEL_CHECK_LT(player, num_players_);\n return ToString();\n}\n\nvoid OthelloState::ObservationTensor(Player player,\n std::vector* values) const {\n SPIEL_CHECK_GE(player, 0);\n SPIEL_CHECK_LT(player, num_players_);\n\n \/\/ Treat `values` as a 2-d tensor.\n TensorView<2> view(values, {kCellStates, kNumCells}, true);\n for (int cell = 0; cell < kNumCells; ++cell) {\n view[{static_cast(board_[cell]), cell}] = 1.0;\n }\n}\n\nvoid OthelloState::UndoAction(Player player, Action move) {\n SpielFatalError(\"Undo not implemented for this game.\");\n}\n\nstd::unique_ptr OthelloState::Clone() const {\n return std::unique_ptr(new OthelloState(*this));\n}\n\nOthelloGame::OthelloGame(const GameParameters& params)\n : Game(kGameType, params) {}\n\n} \/\/ namespace othello\n} \/\/ namespace open_spiel\n<|endoftext|>"} {"text":"\/*\n * Copyright 2015 Open Connectome Project (http:\/\/openconnecto.me)\n * Written by Da Zheng (zhengda1936@gmail.com)\n *\n * This file is part of FlashMatrix.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"mapply_matrix_store.h\"\n#include \"local_matrix_store.h\"\n\nnamespace fm\n{\n\nnamespace detail\n{\n\nnamespace\n{\n\nclass lmapply_col_matrix_store: public lvirtual_col_matrix_store\n{\n\tstd::vector ins;\n\tconst portion_mapply_op &op;\n\traw_data_array data;\n\n\tvoid materialize() const {\n\t\tlocal_buf_col_matrix_store res(get_global_start_row(),\n\t\t\t\tget_global_start_col(), get_num_rows(), get_num_cols(),\n\t\t\t\tget_type(), -1);\n\t\top.run(ins, res);\n\t\tlmapply_col_matrix_store *mutable_this\n\t\t\t= const_cast(this);\n\t\tmutable_this->data = res.get_data();\n\t}\npublic:\n\tlmapply_col_matrix_store(\n\t\t\tconst std::vector &ins,\n\t\t\tconst portion_mapply_op &_op,\n\t\t\toff_t global_start_row, off_t global_start_col,\n\t\t\tsize_t nrow, size_t ncol, const scalar_type &type,\n\t\t\tint node_id): lvirtual_col_matrix_store(global_start_row,\n\t\t\t\tglobal_start_col, nrow, ncol, type, node_id), op(_op) {\n\t\tthis->ins = ins;\n\t}\n\n\tvirtual const char *get_raw_arr() const {\n\t\tif (data.is_empty())\n\t\t\tmaterialize();\n\t\treturn data.get_raw();\n\t}\n\n\tvirtual matrix_store::const_ptr transpose() const {\n\t\t\/\/ TODO\n\t\tassert(0);\n\t\treturn matrix_store::const_ptr();\n\t}\n\n\tvirtual const char *get_col(size_t col) const {\n\t\tif (data.is_empty())\n\t\t\tmaterialize();\n\t\treturn data.get_raw() + get_num_rows() * col * get_type().get_size();\n\t}\n};\n\nclass lmapply_row_matrix_store: public lvirtual_row_matrix_store\n{\n\tstd::vector ins;\n\tconst portion_mapply_op &op;\n\traw_data_array data;\n\n\tvoid materialize() const {\n\t\tlocal_buf_row_matrix_store res(get_global_start_row(),\n\t\t\t\tget_global_start_col(), get_num_rows(), get_num_cols(),\n\t\t\t\tget_type(), -1);\n\t\top.run(ins, res);\n\t\tlmapply_row_matrix_store *mutable_this\n\t\t\t= const_cast(this);\n\t\tmutable_this->data = res.get_data();\n\t}\npublic:\n\tlmapply_row_matrix_store(\n\t\t\tconst std::vector &ins,\n\t\t\tconst portion_mapply_op &_op,\n\t\t\toff_t global_start_row, off_t global_start_col,\n\t\t\tsize_t nrow, size_t ncol, const scalar_type &type,\n\t\t\tint node_id): lvirtual_row_matrix_store(global_start_row,\n\t\t\t\tglobal_start_col, nrow, ncol, type, node_id), op(_op) {\n\t\tthis->ins = ins;\n\t}\n\n\tvirtual const char *get_raw_arr() const {\n\t\tif (data.is_empty())\n\t\t\tmaterialize();\n\t\treturn data.get_raw();\n\t}\n\n\tvirtual matrix_store::const_ptr transpose() const {\n\t\t\/\/ TODO\n\t\tassert(0);\n\t\treturn matrix_store::const_ptr();\n\t}\n\n\tvirtual const char *get_row(size_t row) const {\n\t\tif (data.is_empty())\n\t\t\tmaterialize();\n\t\treturn data.get_raw() + get_num_cols() * row * get_type().get_size();\n\t}\n\n\tvirtual const char *get_rows(size_t row_start, size_t row_end) const {\n\t\t\/\/ TODO\n\t\tassert(0);\n\t\treturn NULL;\n\t}\n};\n\n}\n\nmapply_matrix_store::mapply_matrix_store(\n\t\tconst std::vector &in_mats,\n\t\tportion_mapply_op::const_ptr op, matrix_layout_t layout,\n\t\tsize_t nrow, size_t ncol): virtual_matrix_store(nrow, ncol,\n\t\t\top->get_output_type())\n{\n\tthis->layout = layout;\n\tthis->in_mats = in_mats;\n\tthis->op = op;\n}\n\nmatrix_store::ptr mapply_matrix_store::materialize() const\n{\n\treturn _mapply_portion(in_mats, op, layout);\n}\n\nmatrix_store::const_ptr mapply_matrix_store::get_cols(\n\t\tconst std::vector &idxs) const\n{\n\t\/\/ TODO\n\tassert(0);\n\treturn matrix_store::const_ptr();\n}\n\nmatrix_store::const_ptr mapply_matrix_store::get_rows(\n\t\tconst std::vector &idxs) const\n{\n\t\/\/ TODO\n\tassert(0);\n\treturn matrix_store::const_ptr();\n}\n\nlocal_matrix_store::const_ptr mapply_matrix_store::get_portion(\n\t\t\tsize_t start_row, size_t start_col, size_t num_rows,\n\t\t\tsize_t num_cols) const\n{\n\tstd::vector parts(in_mats.size());\n\tif (is_wide()) {\n\t\tassert(start_row == 0);\n\t\tassert(num_rows == get_num_rows());\n\t\tfor (size_t i = 0; i < in_mats.size(); i++)\n\t\t\tparts[i] = static_cast(\n\t\t\t\t\tin_mats[i]->get_data()).get_portion(start_row, start_col,\n\t\t\t\t\tin_mats[i]->get_num_rows(), num_cols);\n\t}\n\telse {\n\t\tassert(start_col == 0);\n\t\tassert(num_cols == get_num_cols());\n\t\tfor (size_t i = 0; i < in_mats.size(); i++)\n\t\t\tparts[i] = static_cast(\n\t\t\t\t\tin_mats[i]->get_data()).get_portion(start_row, start_col,\n\t\t\t\t\tnum_rows, in_mats[i]->get_num_cols());\n\t}\n\n\tif (store_layout() == matrix_layout_t::L_ROW)\n\t\treturn local_matrix_store::const_ptr(new lmapply_row_matrix_store(\n\t\t\t\t\tparts, *op, start_row, start_col, num_rows, num_cols,\n\t\t\t\t\tget_type(), parts.front()->get_node_id()));\n\telse\n\t\treturn local_matrix_store::const_ptr(new lmapply_col_matrix_store(\n\t\t\t\t\tparts, *op, start_row, start_col, num_rows, num_cols,\n\t\t\t\t\tget_type(), parts.front()->get_node_id()));\n}\n\nlocal_matrix_store::const_ptr mapply_matrix_store::get_portion(\n\t\t\tsize_t id) const\n{\n\tsize_t start_row;\n\tsize_t start_col;\n\tsize_t num_rows;\n\tsize_t num_cols;\n\tstd::pair chunk_size = get_portion_size();\n\tif (is_wide()) {\n\t\tstart_row = 0;\n\t\tstart_col = chunk_size.second * id;\n\t\tnum_rows = get_num_rows();\n\t\tnum_cols = std::min(chunk_size.second, get_num_cols() - start_col);\n\t}\n\telse {\n\t\tstart_row = chunk_size.first * id;\n\t\tstart_col = 0;\n\t\tnum_rows = std::min(chunk_size.first, get_num_rows() - start_row);\n\t\tnum_cols = get_num_cols();\n\t}\n\treturn get_portion(start_row, start_col, num_rows, num_cols);\n}\n\nmatrix_store::const_ptr mapply_matrix_store::transpose() const\n{\n\t\/\/ TODO\n\tassert(0);\n\treturn matrix_store::const_ptr();\n}\n\n}\n\n}\n[Matrix]: optimize mapply_matrix_store for CPU cache.\/*\n * Copyright 2015 Open Connectome Project (http:\/\/openconnecto.me)\n * Written by Da Zheng (zhengda1936@gmail.com)\n *\n * This file is part of FlashMatrix.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"mapply_matrix_store.h\"\n#include \"local_matrix_store.h\"\n\nnamespace fm\n{\n\nnamespace detail\n{\n\nnamespace\n{\n\nsize_t SUB_CHUNK_SIZE = 4 * 1024;\n\nclass mapply_store\n{\n\tstd::vector ins;\n\tconst portion_mapply_op &op;\n\traw_data_array buf;\n\tbool materialized;\n\tlocal_matrix_store *lstore;\npublic:\n\tmapply_store(const std::vector &ins,\n\t\t\tconst portion_mapply_op &_op, local_matrix_store *lstore): op(_op) {\n\t\tthis->lstore = lstore;\n\t\tthis->ins = ins;\n\t\tmaterialized = false;\n\t}\n\n\tconst char *get_raw_arr() const {\n\t\treturn buf.get_raw();\n\t}\n\n\tbool is_materialized() const {\n\t\treturn materialized;\n\t}\n\tvoid materialize() const;\n\tvoid materialize_whole();\n\n\tvoid resize(off_t local_start_row, off_t local_start_col,\n\t\t\tsize_t local_num_rows, size_t local_num_cols);\n\tvoid reset_size();\n};\n\nvoid mapply_store::reset_size()\n{\n\t\/\/ When the matrix store is resized, we should drop the materialized data.\n\tmaterialized = false;\n\tbuf = raw_data_array();\n\tfor (size_t i = 0; i < ins.size(); i++)\n\t\tconst_cast(ins[i].get())->reset_size();\n}\n\nvoid mapply_store::resize(off_t local_start_row, off_t local_start_col,\n\t\tsize_t local_num_rows, size_t local_num_cols)\n{\n\t\/\/ When the matrix store is resized, we should drop the materialized data.\n\tmaterialized = false;\n\t\/\/ To avoid unnecessary memory allocation, if the new exposed part isn't\n\t\/\/ larger than the buffer size, we can keep the buffer.\n\tif (local_num_rows * local_num_cols * lstore->get_entry_size()\n\t\t\t> buf.get_num_bytes())\n\t\tbuf = raw_data_array();\n\n\tif (lstore->is_wide()) {\n\t\tassert(local_start_row == 0 && local_num_rows == lstore->get_num_rows());\n\t\tfor (size_t i = 0; i < ins.size(); i++)\n\t\t\tconst_cast(ins[i].get())->resize(0,\n\t\t\t\t\tlocal_start_col, ins[i]->get_num_rows(), local_num_cols);\n\t}\n\telse {\n\t\tassert(local_start_col == 0 && local_num_cols == lstore->get_num_cols());\n\t\tfor (size_t i = 0; i < ins.size(); i++)\n\t\t\tconst_cast(ins[i].get())->resize(\n\t\t\t\t\tlocal_start_row, 0, local_num_rows, ins[i]->get_num_cols());\n\t}\n}\n\nvoid mapply_store::materialize_whole()\n{\n\tlocal_matrix_store::ptr res;\n\tif (lstore->store_layout() == matrix_layout_t::L_COL) {\n\t\tlocal_buf_col_matrix_store *tmp = new local_buf_col_matrix_store(\n\t\t\t\tlstore->get_global_start_row(),\n\t\t\t\tlstore->get_global_start_col(), lstore->get_num_rows(),\n\t\t\t\tlstore->get_num_cols(), lstore->get_type(), -1);\n\t\tres = local_matrix_store::ptr(tmp);\n\t\tthis->buf = tmp->get_data();\n\t}\n\telse {\n\t\tlocal_buf_row_matrix_store *tmp = new local_buf_row_matrix_store(\n\t\t\t\tlstore->get_global_start_row(),\n\t\t\t\tlstore->get_global_start_col(), lstore->get_num_rows(),\n\t\t\t\tlstore->get_num_cols(), lstore->get_type(), -1);\n\t\tres = local_matrix_store::ptr(tmp);\n\t\tthis->buf = tmp->get_data();\n\t}\n\n\tstd::vector mutable_ins(ins.size());\n\tfor (size_t i = 0; i < ins.size(); i++)\n\t\tmutable_ins[i] = const_cast(ins[i].get());\n\n\tif (lstore->is_wide()) {\n\t\tfor (size_t local_start_col = 0; local_start_col < lstore->get_num_cols();\n\t\t\t\tlocal_start_col += SUB_CHUNK_SIZE) {\n\t\t\tsize_t local_num_cols = std::min(SUB_CHUNK_SIZE,\n\t\t\t\t\tlstore->get_num_cols() - local_start_col);\n\t\t\tfor (size_t i = 0; i < mutable_ins.size(); i++) {\n\t\t\t\tmutable_ins[i]->resize(0, local_start_col,\n\t\t\t\t\t\tmutable_ins[i]->get_num_rows(), local_num_cols);\n\t\t\t}\n\t\t\tres->resize(0, local_start_col, res->get_num_rows(), local_num_cols);\n\t\t\top.run(ins, *res);\n\t\t}\n\t}\n\telse {\n\t\t\/\/ If this is a tall matrix.\n\t\tfor (size_t local_start_row = 0; local_start_row < lstore->get_num_rows();\n\t\t\t\tlocal_start_row += SUB_CHUNK_SIZE) {\n\t\t\tsize_t local_num_rows = std::min(SUB_CHUNK_SIZE,\n\t\t\t\t\tlstore->get_num_rows() - local_start_row);\n\t\t\tfor (size_t i = 0; i < mutable_ins.size(); i++) {\n\t\t\t\tmutable_ins[i]->resize(local_start_row, 0, local_num_rows,\n\t\t\t\t\t\tmutable_ins[i]->get_num_cols());\n\t\t\t}\n\t\t\tres->resize(local_start_row, 0, local_num_rows, res->get_num_cols());\n\t\t\top.run(ins, *res);\n\t\t}\n\t}\n\tfor (size_t i = 0; i < mutable_ins.size(); i++)\n\t\tmutable_ins[i]->reset_size();\n}\n\nvoid mapply_store::materialize() const\n{\n\tmapply_store *mutable_this = const_cast(this);\n\tif (lstore->is_whole())\n\t\tmutable_this->materialize_whole();\n\telse if (lstore->store_layout() == matrix_layout_t::L_COL\n\t\t\t&& this->buf.is_empty()) {\n\t\tlocal_buf_col_matrix_store res(lstore->get_global_start_row(),\n\t\t\t\tlstore->get_global_start_col(), lstore->get_num_rows(),\n\t\t\t\tlstore->get_num_cols(), lstore->get_type(), -1);\n\t\top.run(ins, res);\n\t\tmutable_this->buf = res.get_data();\n\t}\n\telse if (lstore->store_layout() == matrix_layout_t::L_COL) {\n\t\tlocal_ref_contig_col_matrix_store res(mutable_this->buf.get_raw(),\n\t\t\t\tlstore->get_global_start_row(), lstore->get_global_start_col(),\n\t\t\t\tlstore->get_num_rows(), lstore->get_num_cols(),\n\t\t\t\tlstore->get_type(), -1);\n\t\top.run(ins, res);\n\t}\n\telse if (this->buf.is_empty()) {\n\t\tlocal_buf_row_matrix_store res(lstore->get_global_start_row(),\n\t\t\t\tlstore->get_global_start_col(), lstore->get_num_rows(),\n\t\t\t\tlstore->get_num_cols(), lstore->get_type(), -1);\n\t\top.run(ins, res);\n\t\tmutable_this->buf = res.get_data();\n\t}\n\telse {\n\t\tlocal_ref_contig_row_matrix_store res(mutable_this->buf.get_raw(),\n\t\t\t\tlstore->get_global_start_row(), lstore->get_global_start_col(),\n\t\t\t\tlstore->get_num_rows(), lstore->get_num_cols(),\n\t\t\t\tlstore->get_type(), -1);\n\t\top.run(ins, res);\n\t}\n\tmutable_this->materialized = true;\n}\n\nclass lmapply_col_matrix_store: public lvirtual_col_matrix_store\n{\n\tmapply_store store;\npublic:\n\tlmapply_col_matrix_store(\n\t\t\tconst std::vector &ins,\n\t\t\tconst portion_mapply_op &op,\n\t\t\toff_t global_start_row, off_t global_start_col,\n\t\t\tsize_t nrow, size_t ncol, const scalar_type &type,\n\t\t\tint node_id): lvirtual_col_matrix_store(global_start_row,\n\t\t\t\tglobal_start_col, nrow, ncol, type, node_id),\n\t\t\tstore(ins, op, this) {\n\t}\n\n\tvirtual bool resize(off_t local_start_row, off_t local_start_col,\n\t\t\tsize_t local_num_rows, size_t local_num_cols) {\n\t\tstore.resize(local_start_row, local_start_col, local_num_rows,\n\t\t\t\tlocal_num_cols);\n\t\treturn local_matrix_store::resize(local_start_row, local_start_col,\n\t\t\t\tlocal_num_rows, local_num_cols);\n\t}\n\tvirtual void reset_size() {\n\t\tstore.reset_size();\n\t\tlocal_matrix_store::reset_size();\n\t}\n\n\tvirtual const char *get_raw_arr() const {\n\t\tif (!store.is_materialized())\n\t\t\tstore.materialize();\n\t\treturn store.get_raw_arr();\n\t}\n\n\tvirtual matrix_store::const_ptr transpose() const {\n\t\t\/\/ TODO\n\t\tassert(0);\n\t\treturn matrix_store::const_ptr();\n\t}\n\n\tvirtual const char *get_col(size_t col) const {\n\t\tif (!store.is_materialized())\n\t\t\tstore.materialize();\n\t\treturn store.get_raw_arr() + get_num_rows() * col * get_type().get_size();\n\t}\n};\n\nclass lmapply_row_matrix_store: public lvirtual_row_matrix_store\n{\n\tmapply_store store;\npublic:\n\tlmapply_row_matrix_store(\n\t\t\tconst std::vector &ins,\n\t\t\tconst portion_mapply_op &op,\n\t\t\toff_t global_start_row, off_t global_start_col,\n\t\t\tsize_t nrow, size_t ncol, const scalar_type &type,\n\t\t\tint node_id): lvirtual_row_matrix_store(global_start_row,\n\t\t\t\tglobal_start_col, nrow, ncol, type, node_id),\n\t\t\tstore(ins, op, this) {\n\t}\n\n\tvirtual bool resize(off_t local_start_row, off_t local_start_col,\n\t\t\tsize_t local_num_rows, size_t local_num_cols) {\n\t\tstore.resize(local_start_row, local_start_col, local_num_rows,\n\t\t\t\tlocal_num_cols);\n\t\treturn local_matrix_store::resize(local_start_row, local_start_col,\n\t\t\t\tlocal_num_rows, local_num_cols);\n\t}\n\tvirtual void reset_size() {\n\t\tstore.reset_size();\n\t\tlocal_matrix_store::reset_size();\n\t}\n\n\tvirtual const char *get_raw_arr() const {\n\t\tif (!store.is_materialized())\n\t\t\tstore.materialize();\n\t\treturn store.get_raw_arr();\n\t}\n\n\tvirtual matrix_store::const_ptr transpose() const {\n\t\t\/\/ TODO\n\t\tassert(0);\n\t\treturn matrix_store::const_ptr();\n\t}\n\n\tvirtual const char *get_row(size_t row) const {\n\t\tif (!store.is_materialized())\n\t\t\tstore.materialize();\n\t\treturn store.get_raw_arr() + get_num_cols() * row * get_type().get_size();\n\t}\n\n\tvirtual const char *get_rows(size_t row_start, size_t row_end) const {\n\t\t\/\/ TODO\n\t\tassert(0);\n\t\treturn NULL;\n\t}\n};\n\n}\n\nmapply_matrix_store::mapply_matrix_store(\n\t\tconst std::vector &in_mats,\n\t\tportion_mapply_op::const_ptr op, matrix_layout_t layout,\n\t\tsize_t nrow, size_t ncol): virtual_matrix_store(nrow, ncol,\n\t\t\top->get_output_type())\n{\n\tthis->layout = layout;\n\tthis->in_mats = in_mats;\n\tthis->op = op;\n}\n\nmatrix_store::ptr mapply_matrix_store::materialize() const\n{\n\treturn _mapply_portion(in_mats, op, layout);\n}\n\nmatrix_store::const_ptr mapply_matrix_store::get_cols(\n\t\tconst std::vector &idxs) const\n{\n\t\/\/ TODO\n\tassert(0);\n\treturn matrix_store::const_ptr();\n}\n\nmatrix_store::const_ptr mapply_matrix_store::get_rows(\n\t\tconst std::vector &idxs) const\n{\n\t\/\/ TODO\n\tassert(0);\n\treturn matrix_store::const_ptr();\n}\n\nlocal_matrix_store::const_ptr mapply_matrix_store::get_portion(\n\t\t\tsize_t start_row, size_t start_col, size_t num_rows,\n\t\t\tsize_t num_cols) const\n{\n\tstd::vector parts(in_mats.size());\n\tif (is_wide()) {\n\t\tassert(start_row == 0);\n\t\tassert(num_rows == get_num_rows());\n\t\tfor (size_t i = 0; i < in_mats.size(); i++)\n\t\t\tparts[i] = static_cast(\n\t\t\t\t\tin_mats[i]->get_data()).get_portion(start_row, start_col,\n\t\t\t\t\tin_mats[i]->get_num_rows(), num_cols);\n\t}\n\telse {\n\t\tassert(start_col == 0);\n\t\tassert(num_cols == get_num_cols());\n\t\tfor (size_t i = 0; i < in_mats.size(); i++)\n\t\t\tparts[i] = static_cast(\n\t\t\t\t\tin_mats[i]->get_data()).get_portion(start_row, start_col,\n\t\t\t\t\tnum_rows, in_mats[i]->get_num_cols());\n\t}\n\n\tif (store_layout() == matrix_layout_t::L_ROW)\n\t\treturn local_matrix_store::const_ptr(new lmapply_row_matrix_store(\n\t\t\t\t\tparts, *op, start_row, start_col, num_rows, num_cols,\n\t\t\t\t\tget_type(), parts.front()->get_node_id()));\n\telse\n\t\treturn local_matrix_store::const_ptr(new lmapply_col_matrix_store(\n\t\t\t\t\tparts, *op, start_row, start_col, num_rows, num_cols,\n\t\t\t\t\tget_type(), parts.front()->get_node_id()));\n}\n\nlocal_matrix_store::const_ptr mapply_matrix_store::get_portion(\n\t\t\tsize_t id) const\n{\n\tsize_t start_row;\n\tsize_t start_col;\n\tsize_t num_rows;\n\tsize_t num_cols;\n\tstd::pair chunk_size = get_portion_size();\n\tif (is_wide()) {\n\t\tstart_row = 0;\n\t\tstart_col = chunk_size.second * id;\n\t\tnum_rows = get_num_rows();\n\t\tnum_cols = std::min(chunk_size.second, get_num_cols() - start_col);\n\t}\n\telse {\n\t\tstart_row = chunk_size.first * id;\n\t\tstart_col = 0;\n\t\tnum_rows = std::min(chunk_size.first, get_num_rows() - start_row);\n\t\tnum_cols = get_num_cols();\n\t}\n\treturn get_portion(start_row, start_col, num_rows, num_cols);\n}\n\nmatrix_store::const_ptr mapply_matrix_store::transpose() const\n{\n\t\/\/ TODO\n\tassert(0);\n\treturn matrix_store::const_ptr();\n}\n\n}\n\n}\n<|endoftext|>"} {"text":"#pragma once\n#include \n#include \n#include \"error.hpp\"\n#include \n#include \n\n\/\/ clangでshared_ptrが定義されない問題への一時的な対処\n#include \n#include \n#undef BOOST_NO_CXX11_SMART_PTR\n#include \n#include \n\nnamespace spn {\n\tDEF_HASMETHOD(clone)\n\t\/\/ cloneメソッドを持っていればそれを呼ぶ\n\ttemplate \n\tauto CopyAsSP(T& t, std::true_type) {\n\t\treturn t.clone();\n\t}\n\t\/\/ cloneメソッドを持っていない時はコピーコンストラクタで対処\n\ttemplate \n\tauto CopyAsSP(T& t, std::false_type) {\n\t\tusing Tc = typename std::remove_const::type;\n\t\treturn std::shared_ptr(new Tc(t));\n\t}\n\t\/\/! iterateDepthFirstの戻り値\n\tenum class Iterate {\n\t\tReturnFromChild,\t\/\/!< 内部用\n\t\tStepIn,\t\t\t\t\/\/!< 子を巡回\n\t\tNext,\t\t\t\t\/\/!< 子を巡回せず兄弟ノードへ進む\n\t\tQuit\t\t\t\t\/\/!< 直ちに巡回を終える\n\t};\n\t\/\/! 汎用ツリー構造\n\t\/*! Tは必ずTreeNodeを継承する前提 *\/\n\ttemplate \n\tclass TreeNode : public std::enable_shared_from_this {\n\t\tprivate:\n\t\t\tfriend class boost::serialization::access;\n\t\t\ttemplate \n\t\t\tvoid serialize(Ar& ar, const unsigned int) {\n\t\t\t\tar\t& BOOST_SERIALIZATION_NVP(_spChild)\n\t\t\t\t\t& BOOST_SERIALIZATION_NVP(_wpParent)\n\t\t\t\t\t& BOOST_SERIALIZATION_NVP(_spSibling);\n\t\t\t}\n\n\t\t\/\/ 巡回参照を避けるために親ノードはweak_ptrで格納\n\t\tpublic:\n\t\t\tusing this_t = TreeNode;\n\t\t\tusing pointer = this_t*;\n\t\t\tusing SP = std::shared_ptr;\n\t\t\tusing SPC = std::shared_ptr;\n\t\t\tusing WP = std::weak_ptr;\n\t\t\tusing SPVector = std::vector;\n\t\t\tusing SPCVector = std::vector;\n\n\t\t\tSP\t\t\t_spChild,\n\t\t\t\t\t\t_spSibling;\n\t\t\tWP\t\t\t_wpParent;\n\n\t\t\t\/\/ --- ノードつなぎ変え時に呼ばれる関数. 継承先クラスが適時オーバーライドする ---\n\t\t\tvoid onParentChange(const SP& \/*from*\/, const SP& \/*to*\/) {}\n\t\t\tvoid onChildRemove(const SP& \/*node*\/) {}\n\t\t\tvoid onChildAdded(const SP& \/*node*\/) {}\n\n\t\t\tstatic void _PrintIndent(std::ostream& os, int n) {\n\t\t\t\twhile(--n >= 0)\n\t\t\t\t\tos << '\\t';\n\t\t\t}\n\t\t\ttemplate \n\t\t\tvoid _iterateAll(CB&& cb) const {\n\t\t\t\tauto* self = const_cast(this);\n\t\t\t\tself->template iterateDepthFirst([&cb](auto& nd, int){\n\t\t\t\t\tcb(nd);\n\t\t\t\t\treturn Iterate::StepIn;\n\t\t\t\t});\n\t\t\t}\n\n\t\t\ttemplate \n\t\t\tstd::vector _plain() const {\n\t\t\t\tstd::vector spv;\n\t\t\t\t_iterateAll([&spv](auto& nd){\n\t\t\t\t\tspv.emplace_back(nd.shared_from_this());\n\t\t\t\t});\n\t\t\t\treturn spv;\n\t\t\t}\n\t\t\ttemplate \n\t\t\tstd::vector _plainPtr() const {\n\t\t\t\tstd::vector pv;\n\t\t\t\t_iterateAll([&pv](auto& nd){\n\t\t\t\t\tpv.emplace_back(&nd);\n\t\t\t\t});\n\t\t\t\treturn pv;\n\t\t\t}\n\n\t\tpublic:\n\t\t\tTreeNode() = default;\n\t\t\texplicit TreeNode(TreeNode&& t) = default;\n\t\t\t\/\/! copy-ctorに置いてはリンク情報をコピーしない\n\t\t\texplicit TreeNode(const TreeNode&) {}\n\t\t\t\/\/ コピー禁止\n\t\t\tTreeNode& operator = (const TreeNode&) = delete;\n\t\t\t\/\/ ムーブは可\n\t\t\tTreeNode& operator = (TreeNode&& t) = default;\n\n\t\t\tvoid setParent(const SP& s) {\n\t\t\t\tsetParent(WP(s));\n\t\t\t}\n\t\t\tvoid setParent(const WP& w) {\n\t\t\t\tSP sp = w.lock(),\n\t\t\t\t spP = getParent();\n\t\t\t\tAssertP(Trap, sp.get() != this, \"self-reference detected\")\n\t\t\t\tif(sp.get() != spP.get()) {\n\t\t\t\t\tonParentChange(spP, sp);\n\t\t\t\t\t_wpParent = w;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tSP getParent() const {\n\t\t\t\treturn SP(_wpParent.lock());\n\t\t\t}\n\t\t\tconst SP& getChild() const {\n\t\t\t\treturn _spChild;\n\t\t\t}\n\t\t\tconst SP& getSibling() const {\n\t\t\t\treturn _spSibling;\n\t\t\t}\n\t\t\tSP getPrevSibling(const bool bLoop=false) const {\n\t\t\t\tconst SP p = getParent();\n\t\t\t\tif(p) {\n\t\t\t\t\tauto cur = p->getChild();\n\t\t\t\t\tif(!cur->getSibling()) {\n\t\t\t\t\t\t\/\/ 項目が1つしかない\n\t\t\t\t\t\treturn nullptr;\n\t\t\t\t\t}\n\t\t\t\t\t\/\/ カーソルがリストの最初\n\t\t\t\t\tif(cur.get() == this) {\n\t\t\t\t\t\tif(bLoop) {\n\t\t\t\t\t\t\t\/\/ カーソルを末尾にループ\n\t\t\t\t\t\t\twhile(const auto& tmp = cur->getSibling())\n\t\t\t\t\t\t\t\tcur = tmp;\n\t\t\t\t\t\t\treturn cur;\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn nullptr;\n\t\t\t\t\t}\n\t\t\t\t\t\/\/ 直前の項目を探す\n\t\t\t\t\twhile(const auto& cur2 = cur->getSibling()) {\n\t\t\t\t\t\tif(cur2.get() == this)\n\t\t\t\t\t\t\treturn cur;\n\t\t\t\t\t\tcur = cur2;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn nullptr;\n\t\t\t}\n\t\t\tvoid removeChild(const SP& target) {\n\t\t\t\tAssertP(Trap, _spChild)\n\t\t\t\tif(_spChild == target) {\n\t\t\t\t\tonChildRemove(target);\n\t\t\t\t\t\/\/ 最初の子ノードが削除対象\n\t\t\t\t\ttarget->setParent(WP());\n\t\t\t\t\t_spChild = target->getSibling();\n\t\t\t\t\ttarget->_spSibling = nullptr;\n\t\t\t\t} else {\n\t\t\t\t\t\/\/ 兄弟ノードのどれかが削除対象\n\t\t\t\t\t_spChild->removeSibling(nullptr, target);\n\t\t\t\t}\n\t\t\t}\n\t\t\tvoid removeSibling(pointer prev, const SP& target) {\n\t\t\t\tif(target.get() == this) {\n\t\t\t\t\tif(auto sp = getParent())\n\t\t\t\t\t\tsp->onChildRemove(this->shared_from_this());\n\t\t\t\t\t\/\/ このノードが削除対象\n\t\t\t\t\tAssertP(Trap, prev)\n\t\t\t\t\tprev->_spSibling = _spSibling;\n\t\t\t\t\tsetParent(WP());\n\t\t\t\t\t_spSibling = nullptr;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tAssertP(Trap, _spSibling)\n\t\t\t\t_spSibling->removeSibling(this, target);\n\t\t\t}\n\t\t\tvoid addChild(const SP& s) {\n\t\t\t\tAssertP(Trap, s.get() != this, \"self-reference detected\")\n\t\t\t\tif(_spChild)\n\t\t\t\t\t_spChild->addSibling(s);\n\t\t\t\telse {\n\t\t\t\t\t_spChild = s;\n\t\t\t\t\ts->setParent(this->shared_from_this());\n\t\t\t\t\tonChildAdded(s);\n\t\t\t\t}\n\t\t\t}\n\t\t\tvoid addSibling(const SP& s) {\n\t\t\t\tAssertP(Trap, s.get() != this, \"self-reference detected\")\n\t\t\t\tif(_spSibling)\n\t\t\t\t\t_spSibling->addSibling(s);\n\t\t\t\telse {\n\t\t\t\t\t_spSibling = s;\n\t\t\t\t\ts->setParent(_wpParent);\n\t\t\t\t\tif(auto sp = getParent())\n\t\t\t\t\t\tsp->onChildAdded(s);\n\t\t\t\t}\n\t\t\t}\n\t\t\t\/\/! 深さ優先で巡回\n\t\t\t\/*! \\tparam Sib\t\t兄弟ノードを巡回対象に加えるか\n\t\t\t\t\\tparam BConst\ttrueならconst巡回 *\/\n\t\t\ttemplate \n\t\t\tIterate iterateDepthFirst(Callback&& cb, int depth=0) {\n\t\t\t\tusing thistc = std::conditional_t;\n\t\t\t\tIterate t = cb(static_cast(*this), depth);\n\t\t\t\tif(t == Iterate::Quit)\n\t\t\t\t\treturn Iterate::Quit;\n\t\t\t\tif(t == Iterate::StepIn) {\n\t\t\t\t\tif(_spChild) {\n\t\t\t\t\t\tif(_spChild->template iterateDepthFirst(std::forward(cb), depth+1) == Iterate::Quit)\n\t\t\t\t\t\t\treturn Iterate::Quit;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif(Sib && _spSibling)\n\t\t\t\t\treturn _spSibling->template iterateDepthFirst(std::forward(cb), depth);\n\t\t\t\treturn Iterate::ReturnFromChild;\n\t\t\t}\n\t\t\ttemplate \n\t\t\tIterate iterateDepthFirst(Callback&& cb, int depth=0) const {\n\t\t\t\treturn const_cast(this)->template iterateDepthFirst(std::forward(cb), depth);\n\t\t\t}\n\t\t\ttemplate \n\t\t\tSP find(Callback&& cb) const {\n\t\t\t\tSP ret;\n\t\t\t\titerateDepthFirst([&cb, &ret](auto& nd, int){\n\t\t\t\t\tif(cb(nd)) {\n\t\t\t\t\t\tret = nd.shared_from_this();\n\t\t\t\t\t\treturn Iterate::Quit;\n\t\t\t\t\t}\n\t\t\t\t\treturn Iterate::StepIn;\n\t\t\t\t});\n\t\t\t\treturn ret;\n\t\t\t}\n\t\t\t\/\/! このノード以下を全て複製\n\t\t\tSP cloneTree(const WP& parent=WP()) const {\n\t\t\t\tSP sp = CopyAsSP(static_cast(*this),\n\t\t\t\t\t\t\t\tHasMethod_clone(nullptr));\n\t\t\t\tif(_spChild)\n\t\t\t\t\tsp->_spChild = _spChild->cloneTree(sp);\n\t\t\t\tif(_spSibling)\n\t\t\t\t\tsp->_spSibling = _spSibling->cloneTree(parent);\n\t\t\t\tsp->_wpParent = parent;\n\t\t\t\treturn sp;\n\t\t\t}\n\t\t\t\/\/! 主にデバッグ用\n\t\t\tvoid print(std::ostream& os, int indent) const {\n\t\t\t\t_PrintIndent(os, indent);\n\t\t\t\t\/\/ 明示的なダウンキャスト\n\t\t\t\tos << *static_cast(this);\n\t\t\t}\n\t\t\t\/\/! ツリー構造を配列化\n\t\t\tSPVector plain() {\n\t\t\t\treturn _plain();\n\t\t\t}\n\t\t\t\/\/! ツリー構造を配列化 (const)\n\t\t\tSPCVector plain() const {\n\t\t\t\treturn _plain();\n\t\t\t}\n\t\t\t\/\/! ツリー構造を配列化 (pointer)\n\t\t\tstd::vector plainPtr() {\n\t\t\t\treturn _plainPtr();\n\t\t\t}\n\t\t\t\/\/! ツリー構造を配列化 (const pointer)\n\t\t\tstd::vector plainPtr() const {\n\t\t\t\treturn _plainPtr();\n\t\t\t}\n\t\t\t\/\/! 最大ツリー深度を取得\n\t\t\tint getDepth() const {\n\t\t\t\tint depth = 0;\n\t\t\t\tif(_spChild)\n\t\t\t\t\tdepth = _spChild->getDepth() + 1;\n\t\t\t\tif(_spSibling)\n\t\t\t\t\tdepth = std::max(depth, _spSibling->getDepth());\n\t\t\t\treturn depth;\n\t\t\t}\n\t};\n\ttemplate \n\tbool _CompareTree(const TreeNode& t0, const TreeNode& t1, CMP&& cmp) {\n\t\tauto fnParentIndex = [](const auto& ar, const auto& p){\n\t\t\tif(!p)\n\t\t\t\treturn ar.end() - ar.begin();\n\t\t\tauto itr = std::find_if(ar.begin(), ar.end(), [&p](auto& r){ return r == p.get(); });\n\t\t\treturn itr - ar.begin();\n\t\t};\n\t\t\/\/ 配列化して親ノード番号をチェック\n\t\tauto ar0 = t0.plainPtr();\n\t\tauto ar1 = t1.plainPtr();\n\t\tif(ar0.size() != ar1.size())\n\t\t\treturn false;\n\t\tauto sz = ar0.size();\n\t\tfor(size_t i=0 ; igetParent()),\n\t\t\t\tidx1 = fnParentIndex(ar1, ar1[i]->getParent());\n\t\t\tif(idx0!=idx1 || !cmp(ar0[i], ar1[i]))\n\t\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n\t\/\/ ツリー構造のみを比較する\n\ttemplate \n\tbool CompareTreeStructure(const TreeNode& t0, const TreeNode& t1) {\n\t\treturn _CompareTree(t0, t1, [](auto&,auto&){ return true; });\n\t}\n\t\/\/! データも含めて比較\n\ttemplate \n\tbool CompareTree(const TreeNode& t0, const TreeNode& t1) {\n\t\tauto cmp = [](auto& sp0, auto& sp1){\n\t\t\treturn *sp0 == *sp1;\n\t\t};\n\t\treturn _CompareTree(t0, t1, cmp);\n\t}\n\ttemplate \n\tinline std::ostream& operator << (std::ostream& os, const TreeNode& t) {\n\t\tauto& self = const_cast&>(t);\n\t\tself.iterateDepthFirst([&os](auto& s, int indent){\n\t\t\ts.print(os, indent);\n\t\t\tos << std::endl;\n\t\t\treturn TreeNode::Iterate::StepIn;\n\t\t});\n\t\treturn os;\n\t}\n}\n\nTreeNode: 子ノードのソート関数#pragma once\n#include \n#include \n#include \"error.hpp\"\n#include \n#include \n\n\/\/ clangでshared_ptrが定義されない問題への一時的な対処\n#include \n#include \n#undef BOOST_NO_CXX11_SMART_PTR\n#include \n#include \n\nnamespace spn {\n\tDEF_HASMETHOD(clone)\n\t\/\/ cloneメソッドを持っていればそれを呼ぶ\n\ttemplate \n\tauto CopyAsSP(T& t, std::true_type) {\n\t\treturn t.clone();\n\t}\n\t\/\/ cloneメソッドを持っていない時はコピーコンストラクタで対処\n\ttemplate \n\tauto CopyAsSP(T& t, std::false_type) {\n\t\tusing Tc = typename std::remove_const::type;\n\t\treturn std::shared_ptr(new Tc(t));\n\t}\n\t\/\/! iterateDepthFirstの戻り値\n\tenum class Iterate {\n\t\tReturnFromChild,\t\/\/!< 内部用\n\t\tStepIn,\t\t\t\t\/\/!< 子を巡回\n\t\tNext,\t\t\t\t\/\/!< 子を巡回せず兄弟ノードへ進む\n\t\tQuit\t\t\t\t\/\/!< 直ちに巡回を終える\n\t};\n\t\/\/! 汎用ツリー構造\n\t\/*! Tは必ずTreeNodeを継承する前提 *\/\n\ttemplate \n\tclass TreeNode : public std::enable_shared_from_this {\n\t\tprivate:\n\t\t\tfriend class boost::serialization::access;\n\t\t\ttemplate \n\t\t\tvoid serialize(Ar& ar, const unsigned int) {\n\t\t\t\tar\t& BOOST_SERIALIZATION_NVP(_spChild)\n\t\t\t\t\t& BOOST_SERIALIZATION_NVP(_wpParent)\n\t\t\t\t\t& BOOST_SERIALIZATION_NVP(_spSibling);\n\t\t\t}\n\n\t\t\/\/ 巡回参照を避けるために親ノードはweak_ptrで格納\n\t\tpublic:\n\t\t\tusing Iterate = ::spn::Iterate;\n\t\t\tusing this_t = TreeNode;\n\t\t\tusing pointer = this_t*;\n\t\t\tusing element_type = T;\n\t\t\tusing SP = std::shared_ptr;\n\t\t\tusing SPC = std::shared_ptr;\n\t\t\tusing WP = std::weak_ptr;\n\t\t\tusing SPVector = std::vector;\n\t\t\tusing SPCVector = std::vector;\n\n\t\t\tSP\t\t\t_spChild,\n\t\t\t\t\t\t_spSibling;\n\t\t\tWP\t\t\t_wpParent;\n\n\t\t\t\/\/ --- ノードつなぎ変え時に呼ばれる関数. 継承先クラスが適時オーバーライドする ---\n\t\t\tvoid onParentChange(const SP& \/*from*\/, const SP& \/*to*\/) {}\n\t\t\tvoid onChildRemove(const SP& \/*node*\/) {}\n\t\t\tvoid onChildAdded(const SP& \/*node*\/) {}\n\n\t\t\tstatic void _PrintIndent(std::ostream& os, int n) {\n\t\t\t\twhile(--n >= 0)\n\t\t\t\t\tos << '\\t';\n\t\t\t}\n\t\t\ttemplate \n\t\t\tvoid _iterateAll(CB&& cb) const {\n\t\t\t\tauto* self = const_cast(this);\n\t\t\t\tself->template iterateDepthFirst([&cb](auto& nd, int){\n\t\t\t\t\tcb(nd);\n\t\t\t\t\treturn Iterate::StepIn;\n\t\t\t\t});\n\t\t\t}\n\n\t\t\ttemplate \n\t\t\tstd::vector _plain() const {\n\t\t\t\tstd::vector spv;\n\t\t\t\t_iterateAll([&spv](auto& nd){\n\t\t\t\t\tspv.emplace_back(nd.shared_from_this());\n\t\t\t\t});\n\t\t\t\treturn spv;\n\t\t\t}\n\t\t\ttemplate \n\t\t\tstd::vector _plainPtr() const {\n\t\t\t\tstd::vector pv;\n\t\t\t\t_iterateAll([&pv](auto& nd){\n\t\t\t\t\tpv.emplace_back(&nd);\n\t\t\t\t});\n\t\t\t\treturn pv;\n\t\t\t}\n\t\t\ttemplate \n\t\t\tvoid _iterateChild(CB&& cb) const {\n\t\t\t\tif(SP sp = getChild()) {\n\t\t\t\t\tdo {\n\t\t\t\t\t\tcb(sp);\n\t\t\t\t\t\tsp = sp->getSibling();\n\t\t\t\t\t} while(sp);\n\t\t\t\t}\n\t\t\t}\n\n\t\tpublic:\n\t\t\tTreeNode() = default;\n\t\t\texplicit TreeNode(TreeNode&& t) = default;\n\t\t\t\/\/! copy-ctorに置いてはリンク情報をコピーしない\n\t\t\texplicit TreeNode(const TreeNode&) {}\n\t\t\t\/\/ コピー禁止\n\t\t\tTreeNode& operator = (const TreeNode&) = delete;\n\t\t\t\/\/ ムーブは可\n\t\t\tTreeNode& operator = (TreeNode&& t) = default;\n\n\t\t\t\/\/! 任意の基準で子ノードをソート\n\t\t\ttemplate \n\t\t\tvoid sortChild(CMP&& cmp, const bool recursive) {\n\t\t\t\tif(auto c = getChild()) {\n\t\t\t\t\tSPVector spv;\n\t\t\t\t\t_iterateChild([&spv](auto& nd){\n\t\t\t\t\t\tspv.emplace_back(nd);\n\t\t\t\t\t});\n\t\t\t\t\tstd::sort(spv.begin(), spv.end(), cmp);\n\t\t\t\t\tSP\tcur = spv.front(),\n\t\t\t\t\t\tpcur;\n\t\t\t\t\t_spChild = cur;\n\t\t\t\t\tauto itr = spv.begin();\n\t\t\t\t\tdo {\n\t\t\t\t\t\tcur = *itr;\n\t\t\t\t\t\tif(pcur)\n\t\t\t\t\t\t\tpcur->_spSibling = cur;\n\t\t\t\t\t\tpcur = cur;\n\t\t\t\t\t} while(++itr != spv.end());\n\t\t\t\t\tcur->_spSibling.reset();\n\n\t\t\t\t\tif(recursive) {\n\t\t\t\t\t\tfor(auto& s : spv)\n\t\t\t\t\t\t\ts->sortChild(cmp, recursive);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tvoid setParent(const SP& s) {\n\t\t\t\tsetParent(WP(s));\n\t\t\t}\n\t\t\tvoid setParent(const WP& w) {\n\t\t\t\tSP sp = w.lock(),\n\t\t\t\t spP = getParent();\n\t\t\t\tAssertP(Trap, sp.get() != this, \"self-reference detected\")\n\t\t\t\tif(sp.get() != spP.get()) {\n\t\t\t\t\tonParentChange(spP, sp);\n\t\t\t\t\t_wpParent = w;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tSP getParent() const {\n\t\t\t\treturn SP(_wpParent.lock());\n\t\t\t}\n\t\t\tconst SP& getChild() const {\n\t\t\t\treturn _spChild;\n\t\t\t}\n\t\t\tconst SP& getSibling() const {\n\t\t\t\treturn _spSibling;\n\t\t\t}\n\t\t\tSP getPrevSibling(const bool bLoop=false) const {\n\t\t\t\tconst SP p = getParent();\n\t\t\t\tif(p) {\n\t\t\t\t\tauto cur = p->getChild();\n\t\t\t\t\tif(!cur->getSibling()) {\n\t\t\t\t\t\t\/\/ 項目が1つしかない\n\t\t\t\t\t\treturn nullptr;\n\t\t\t\t\t}\n\t\t\t\t\t\/\/ カーソルがリストの最初\n\t\t\t\t\tif(cur.get() == this) {\n\t\t\t\t\t\tif(bLoop) {\n\t\t\t\t\t\t\t\/\/ カーソルを末尾にループ\n\t\t\t\t\t\t\twhile(const auto& tmp = cur->getSibling())\n\t\t\t\t\t\t\t\tcur = tmp;\n\t\t\t\t\t\t\treturn cur;\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn nullptr;\n\t\t\t\t\t}\n\t\t\t\t\t\/\/ 直前の項目を探す\n\t\t\t\t\twhile(const auto& cur2 = cur->getSibling()) {\n\t\t\t\t\t\tif(cur2.get() == this)\n\t\t\t\t\t\t\treturn cur;\n\t\t\t\t\t\tcur = cur2;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn nullptr;\n\t\t\t}\n\t\t\tvoid removeChild(const SP& target) {\n\t\t\t\tAssertP(Trap, _spChild)\n\t\t\t\tif(_spChild == target) {\n\t\t\t\t\tonChildRemove(target);\n\t\t\t\t\t\/\/ 最初の子ノードが削除対象\n\t\t\t\t\ttarget->setParent(WP());\n\t\t\t\t\t_spChild = target->getSibling();\n\t\t\t\t\ttarget->_spSibling = nullptr;\n\t\t\t\t} else {\n\t\t\t\t\t\/\/ 兄弟ノードのどれかが削除対象\n\t\t\t\t\t_spChild->removeSibling(nullptr, target);\n\t\t\t\t}\n\t\t\t}\n\t\t\tvoid removeSibling(pointer prev, const SP& target) {\n\t\t\t\tif(target.get() == this) {\n\t\t\t\t\tif(auto sp = getParent())\n\t\t\t\t\t\tsp->onChildRemove(this->shared_from_this());\n\t\t\t\t\t\/\/ このノードが削除対象\n\t\t\t\t\tAssertP(Trap, prev)\n\t\t\t\t\tprev->_spSibling = _spSibling;\n\t\t\t\t\tsetParent(WP());\n\t\t\t\t\t_spSibling = nullptr;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tAssertP(Trap, _spSibling)\n\t\t\t\t_spSibling->removeSibling(this, target);\n\t\t\t}\n\t\t\tvoid addChild(const SP& s) {\n\t\t\t\tAssertP(Trap, s.get() != this, \"self-reference detected\")\n\t\t\t\tif(_spChild)\n\t\t\t\t\t_spChild->addSibling(s);\n\t\t\t\telse {\n\t\t\t\t\t_spChild = s;\n\t\t\t\t\ts->setParent(this->shared_from_this());\n\t\t\t\t\tonChildAdded(s);\n\t\t\t\t}\n\t\t\t}\n\t\t\tvoid addSibling(const SP& s) {\n\t\t\t\tAssertP(Trap, s.get() != this, \"self-reference detected\")\n\t\t\t\tif(_spSibling)\n\t\t\t\t\t_spSibling->addSibling(s);\n\t\t\t\telse {\n\t\t\t\t\t_spSibling = s;\n\t\t\t\t\ts->setParent(_wpParent);\n\t\t\t\t\tif(auto sp = getParent())\n\t\t\t\t\t\tsp->onChildAdded(s);\n\t\t\t\t}\n\t\t\t}\n\t\t\t\/\/! 深さ優先で巡回\n\t\t\t\/*! \\tparam Sib\t\t兄弟ノードを巡回対象に加えるか\n\t\t\t\t\\tparam BConst\ttrueならconst巡回 *\/\n\t\t\ttemplate \n\t\t\tIterate iterateDepthFirst(Callback&& cb, int depth=0) {\n\t\t\t\tusing thistc = std::conditional_t;\n\t\t\t\tIterate t = cb(static_cast(*this), depth);\n\t\t\t\tif(t == Iterate::Quit)\n\t\t\t\t\treturn Iterate::Quit;\n\t\t\t\tif(t == Iterate::StepIn) {\n\t\t\t\t\tif(_spChild) {\n\t\t\t\t\t\tif(_spChild->template iterateDepthFirst(std::forward(cb), depth+1) == Iterate::Quit)\n\t\t\t\t\t\t\treturn Iterate::Quit;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif(Sib && _spSibling)\n\t\t\t\t\treturn _spSibling->template iterateDepthFirst(std::forward(cb), depth);\n\t\t\t\treturn Iterate::ReturnFromChild;\n\t\t\t}\n\t\t\ttemplate \n\t\t\tIterate iterateDepthFirst(Callback&& cb, int depth=0) const {\n\t\t\t\treturn const_cast(this)->template iterateDepthFirst(std::forward(cb), depth);\n\t\t\t}\n\t\t\ttemplate \n\t\t\tSP find(Callback&& cb) const {\n\t\t\t\tSP ret;\n\t\t\t\titerateDepthFirst([&cb, &ret](auto& nd, int){\n\t\t\t\t\tif(cb(nd)) {\n\t\t\t\t\t\tret = nd.shared_from_this();\n\t\t\t\t\t\treturn Iterate::Quit;\n\t\t\t\t\t}\n\t\t\t\t\treturn Iterate::StepIn;\n\t\t\t\t});\n\t\t\t\treturn ret;\n\t\t\t}\n\t\t\t\/\/! このノード以下を全て複製\n\t\t\tSP cloneTree(const WP& parent=WP()) const {\n\t\t\t\tSP sp = CopyAsSP(static_cast(*this),\n\t\t\t\t\t\t\t\tHasMethod_clone(nullptr));\n\t\t\t\tif(_spChild)\n\t\t\t\t\tsp->_spChild = _spChild->cloneTree(sp);\n\t\t\t\tif(_spSibling)\n\t\t\t\t\tsp->_spSibling = _spSibling->cloneTree(parent);\n\t\t\t\tsp->_wpParent = parent;\n\t\t\t\treturn sp;\n\t\t\t}\n\t\t\t\/\/! 主にデバッグ用\n\t\t\tvoid print(std::ostream& os, int indent) const {\n\t\t\t\t_PrintIndent(os, indent);\n\t\t\t\t\/\/ 明示的なダウンキャスト\n\t\t\t\tos << *static_cast(this);\n\t\t\t}\n\t\t\t\/\/! ツリー構造を配列化\n\t\t\tSPVector plain() {\n\t\t\t\treturn _plain();\n\t\t\t}\n\t\t\t\/\/! ツリー構造を配列化 (const)\n\t\t\tSPCVector plain() const {\n\t\t\t\treturn _plain();\n\t\t\t}\n\t\t\t\/\/! ツリー構造を配列化 (pointer)\n\t\t\tstd::vector plainPtr() {\n\t\t\t\treturn _plainPtr();\n\t\t\t}\n\t\t\t\/\/! ツリー構造を配列化 (const pointer)\n\t\t\tstd::vector plainPtr() const {\n\t\t\t\treturn _plainPtr();\n\t\t\t}\n\t\t\t\/\/! 最大ツリー深度を取得\n\t\t\tint getDepth() const {\n\t\t\t\tint depth = 0;\n\t\t\t\tif(_spChild)\n\t\t\t\t\tdepth = _spChild->getDepth() + 1;\n\t\t\t\tif(_spSibling)\n\t\t\t\t\tdepth = std::max(depth, _spSibling->getDepth());\n\t\t\t\treturn depth;\n\t\t\t}\n\t};\n\ttemplate \n\tbool _CompareTree(const TreeNode& t0, const TreeNode& t1, CMP&& cmp) {\n\t\tauto fnParentIndex = [](const auto& ar, const auto& p){\n\t\t\tif(!p)\n\t\t\t\treturn ar.end() - ar.begin();\n\t\t\tauto itr = std::find_if(ar.begin(), ar.end(), [&p](auto& r){ return r == p.get(); });\n\t\t\treturn itr - ar.begin();\n\t\t};\n\t\t\/\/ 配列化して親ノード番号をチェック\n\t\tauto ar0 = t0.plainPtr();\n\t\tauto ar1 = t1.plainPtr();\n\t\tif(ar0.size() != ar1.size())\n\t\t\treturn false;\n\t\tauto sz = ar0.size();\n\t\tfor(size_t i=0 ; igetParent()),\n\t\t\t\tidx1 = fnParentIndex(ar1, ar1[i]->getParent());\n\t\t\tif(idx0!=idx1 || !cmp(ar0[i], ar1[i]))\n\t\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n\t\/\/ ツリー構造のみを比較する\n\ttemplate \n\tbool CompareTreeStructure(const TreeNode& t0, const TreeNode& t1) {\n\t\treturn _CompareTree(t0, t1, [](auto&,auto&){ return true; });\n\t}\n\t\/\/! データも含めて比較\n\ttemplate \n\tbool CompareTree(const TreeNode& t0, const TreeNode& t1) {\n\t\tauto cmp = [](auto& sp0, auto& sp1){\n\t\t\treturn *sp0 == *sp1;\n\t\t};\n\t\treturn _CompareTree(t0, t1, cmp);\n\t}\n\ttemplate \n\tinline std::ostream& operator << (std::ostream& os, const TreeNode& t) {\n\t\tauto& self = const_cast&>(t);\n\t\tself.iterateDepthFirst([&os](auto& s, int indent){\n\t\t\ts.print(os, indent);\n\t\t\tos << std::endl;\n\t\t\treturn TreeNode::Iterate::StepIn;\n\t\t});\n\t\treturn os;\n\t}\n}\n\n<|endoftext|>"} {"text":"#include \"..\/stdafx.h\"\n#include \"list_view.h\"\n\nnamespace uih {\n\nvoid ListView::destroy_header()\n{\n if (m_wnd_header) {\n DestroyWindow(m_wnd_header);\n m_wnd_header = nullptr;\n m_header_font.reset();\n }\n}\n\nvoid ListView::create_header()\n{\n \/\/ if (m_show_header)\n {\n if (!m_wnd_header) {\n m_header_font.reset(m_lf_header_valid ? CreateFontIndirect(&m_lf_header) : uih::create_icon_font());\n m_wnd_header = CreateWindowEx(0, WC_HEADER, _T(\"NGLVH\"),\n WS_CHILD | (0) | \/*(m_autosize ? 0x0800 : NULL) |*\/ HDS_HOTTRACK\n | (m_allow_header_rearrange ? HDS_DRAGDROP : NULL) | HDS_HORZ | HDS_FULLDRAG\n | (m_sorting_enabled ? HDS_BUTTONS : 0) | WS_CLIPSIBLINGS | WS_CLIPCHILDREN,\n 0, 0, 0, 0, get_wnd(), HMENU(IDC_HEADER), mmh::get_current_instance(), nullptr);\n SetWindowTheme(m_wnd_header, m_use_dark_mode ? L\"DarkMode_ItemsView\" : L\"ItemsView\", nullptr);\n SendMessage(m_wnd_header, WM_SETFONT, (WPARAM)m_header_font.get(), MAKELPARAM(FALSE, 0));\n if (m_initialised) {\n build_header();\n ShowWindow(m_wnd_header, SW_SHOWNORMAL);\n }\n }\n }\n}\n\nvoid ListView::set_show_header(bool b_val)\n{\n if (b_val != m_show_header) {\n m_show_header = b_val;\n if (m_initialised) {\n if (m_show_header)\n create_header();\n else\n destroy_header();\n on_size();\n }\n }\n}\n\nvoid ListView::reposition_header()\n{\n RECT rc;\n GetClientRect(get_wnd(), &rc);\n int cx = RECT_CX(rc);\n RECT rc_header;\n get_header_rect(&rc_header);\n SetWindowPos(m_wnd_header, nullptr, -m_horizontal_scroll_position, 0, cx + m_horizontal_scroll_position,\n RECT_CY(rc_header), SWP_NOZORDER);\n}\n\nvoid ListView::build_header()\n{\n if (m_wnd_header) {\n pfc::vartoggle_t toggle(m_ignore_column_size_change_notification, true);\n\n t_size header_count = Header_GetItemCount(m_wnd_header);\n for (; header_count; header_count--)\n Header_DeleteItem(m_wnd_header, header_count - 1);\n\n HDITEM hdi;\n memset(&hdi, 0, sizeof(HDITEM));\n\n hdi.mask = HDI_TEXT | HDI_FORMAT | HDI_WIDTH;\n hdi.fmt = HDF_LEFT | HDF_STRING;\n\n pfc::string8 name;\n pfc::stringcvt::string_wide_from_utf8 wstr;\n\n {\n int n;\n int t = m_columns.size();\n int i = 0;\n const auto indentation = get_total_indentation();\n if (indentation \/*m_group_count*\/) {\n hdi.fmt = HDF_STRING | HDF_LEFT;\n hdi.cchTextMax = 0;\n hdi.pszText = const_cast(L\"\");\n\n hdi.cxy = indentation;\n\n Header_InsertItem(m_wnd_header, i++, &hdi);\n\n m_have_indent_column = true;\n } else\n m_have_indent_column = false;\n for (n = 0; n < t; n++) {\n hdi.fmt = HDF_STRING | HDF_LEFT;\n if (m_columns[n].m_alignment == uih::ALIGN_CENTRE)\n hdi.fmt |= HDF_CENTER;\n else if (m_columns[n].m_alignment == uih::ALIGN_RIGHT)\n hdi.fmt |= HDF_RIGHT;\n hdi.cchTextMax = m_columns[n].m_title.length();\n wstr.convert(m_columns[n].m_title);\n hdi.pszText = const_cast(wstr.get_ptr());\n\n hdi.cxy = m_columns[n].m_display_size;\n\n if (m_sort_column_index == n && m_show_sort_indicators) {\n hdi.fmt |= (m_sort_direction ? HDF_SORTDOWN : HDF_SORTUP);\n }\n\n Header_InsertItem(m_wnd_header, i++, &hdi);\n }\n }\n }\n}\n\nbool ListView::on_wm_notify_header(LPNMHDR lpnm, LRESULT& ret)\n{\n switch (lpnm->code) {\n case NM_CUSTOMDRAW: {\n LPNMCUSTOMDRAW lpcd = (LPNMCUSTOMDRAW)lpnm;\n switch (lpcd->dwDrawStage) {\n case CDDS_PREPAINT:\n ret = CDRF_NOTIFYITEMDRAW;\n return true;\n\n case CDDS_ITEMPREPAINT: {\n auto cr{RGB(255, 0, 0)};\n if (!SUCCEEDED(GetThemeColor(m_header_theme.get(), HP_HEADERITEM, 0, TMT_TEXTCOLOR, &cr)))\n return false;\n\n SetTextColor(lpcd->hdc, cr);\n ret = CDRF_NEWFONT;\n return true;\n }\n default:\n return false;\n }\n }\n case HDN_BEGINTRACKA:\n case HDN_BEGINTRACKW: {\n auto lpnmh = (LPNMHEADER)lpnm;\n if (m_autosize && (!get_show_group_info_area() || lpnmh->iItem)) {\n ret = TRUE;\n return true;\n }\n } break;\n case HDN_DIVIDERDBLCLICK: {\n auto lpnmh = (LPNMHEADER)lpnm;\n if (!m_autosize) {\n if (lpnmh->iItem != -1 && (!m_have_indent_column || lpnmh->iItem)) {\n t_size realIndex = lpnmh->iItem;\n if (m_have_indent_column)\n realIndex--;\n if (realIndex < m_columns.size()) {\n HDC dc;\n dc = GetDC(get_wnd());\n int size;\n\n HFONT fnt_old = SelectFont(dc, m_items_font.get());\n\n int w = 0;\n int n;\n int t = get_item_count();\n\n for (n = 0; n < t; n++) {\n const char* str = get_item_text(n, realIndex);\n size = uih::get_text_width_colour(dc, str, strlen(str));\n if (size > w)\n w = size;\n }\n w += uih::scale_dpi_value(3) * 2 + scale_dpi_value(1);\n\n SelectFont(dc, fnt_old);\n ReleaseDC(get_wnd(), dc);\n\n m_columns[realIndex].m_size = w;\n m_columns[realIndex].m_display_size = w;\n update_header();\n invalidate_all();\n notify_on_column_size_change(realIndex, m_columns[realIndex].m_size);\n update_scroll_info();\n }\n }\n }\n } break;\n case HDN_ITEMCHANGING: {\n if (!m_ignore_column_size_change_notification) {\n auto lpnmh = (LPNMHEADER)lpnm;\n if (lpnmh->pitem->mask & HDI_WIDTH) {\n if (m_have_indent_column && lpnmh->iItem == 0) {\n int min_indent = get_item_indentation();\n if (get_show_group_info_area())\n min_indent += get_default_indentation_step();\n if (lpnmh->pitem->cxy < min_indent) {\n ret = TRUE;\n return true;\n }\n }\n }\n }\n } break;\n case HDN_ITEMCHANGED: {\n if (!m_ignore_column_size_change_notification) {\n auto lpnmh = (LPNMHEADER)lpnm;\n if (lpnmh->pitem->mask & HDI_WIDTH) {\n if (lpnmh->iItem != -1) {\n if (m_have_indent_column && lpnmh->iItem == 0) {\n int new_size = lpnmh->pitem->cxy - get_item_indentation() - get_default_indentation_step();\n if (new_size >= 0 && new_size != get_group_info_area_width()) {\n \/*set_group_info_area_size(new_size);\n if (m_autosize)\n {\n update_column_sizes();\n update_header();\n }*\/\n notify_on_group_info_area_size_change(new_size);\n \/*invalidate_all();\n update_scroll_info();*\/\n }\n } else if (!m_autosize) {\n t_size realIndex = lpnmh->iItem;\n if (m_have_indent_column)\n realIndex--;\n if (realIndex < m_columns.size() && m_columns[realIndex].m_display_size != lpnmh->pitem->cxy) {\n m_columns[realIndex].m_size = lpnmh->pitem->cxy;\n m_columns[realIndex].m_display_size = lpnmh->pitem->cxy;\n invalidate_all();\n notify_on_column_size_change(realIndex, m_columns[realIndex].m_size);\n on_size();\n }\n }\n }\n }\n }\n } break;\n case HDN_ITEMCLICK: {\n auto lpnmh = (LPNMHEADER)lpnm;\n if (lpnmh->iItem != -1 && (!m_have_indent_column || lpnmh->iItem)) {\n t_size realIndex = lpnmh->iItem;\n if (m_have_indent_column)\n realIndex--;\n if (realIndex < m_columns.size()) {\n bool des = (realIndex == m_sort_column_index ? !m_sort_direction : false);\n sort_by_column(realIndex, des);\n }\n }\n } break;\n \/*case HDN_BEGINDRAG:\n {\n LPNMHEADER lpnmh = (LPNMHEADER)lpnm;\n if (lpnmh->iItem == 0 && m_have_indent_column)\n {\n ret = TRUE;\n return true;\n }\n }\n break;*\/\n case HDN_ENDDRAG: {\n auto lpnmh = (LPNMHEADER)lpnm;\n if (lpnmh->iButton == 0) {\n if (lpnmh->pitem && (lpnmh->pitem->mask & HDI_ORDER)) {\n int from = lpnmh->iItem;\n int to = lpnmh->pitem->iOrder;\n if (m_have_indent_column) {\n from--;\n to--;\n }\n if (to >= 0 && from >= 0 && from != to) {\n notify_on_header_rearrange(from, to);\n }\n }\n }\n }\n ret = TRUE;\n return true;\n }\n return false;\n}\n\nvoid ListView::get_header_rect(LPRECT rc) const\n{\n if (m_wnd_header)\n *rc = uih::get_relative_rect(m_wnd_header, get_wnd());\n else {\n GetClientRect(get_wnd(), rc);\n rc->bottom = rc->top;\n }\n}\n\nunsigned ListView::get_header_height() const\n{\n unsigned ret = 0;\n if (m_wnd_header) {\n RECT rc;\n get_header_rect(&rc);\n ret = RECT_CY(rc);\n }\n return ret;\n}\nunsigned ListView::calculate_header_height()\n{\n unsigned rv = 0;\n if (m_wnd_header) {\n auto font = (HFONT)SendMessage(m_wnd_header, WM_GETFONT, 0, 0);\n rv = uih::get_font_height(font) + m_vertical_item_padding + scale_dpi_value(2);\n }\n return rv;\n}\n\nvoid ListView::update_header()\n{\n if (m_wnd_header) {\n pfc::vartoggle_t toggle(m_ignore_column_size_change_notification, true);\n \/\/ SendMessage(m_wnd_header, WM_SETREDRAW, FALSE, NULL);\n t_size i;\n t_size count = m_columns.size();\n t_size j = 0;\n if (m_have_indent_column) {\n uih::header_set_item_width(m_wnd_header, j, get_total_indentation());\n j++;\n }\n for (i = 0; i < count; i++) {\n uih::header_set_item_width(m_wnd_header, i + j, m_columns[i].m_display_size);\n }\n \/\/ SendMessage(m_wnd_header, WM_SETREDRAW, TRUE, NULL);\n \/\/ RedrawWindow(m_wnd_header, NULL, NULL, RDW_INVALIDATE|(b_update?RDW_UPDATENOW:0));\n }\n}\n} \/\/ namespace uih\nDon't set list view header window theme in non-dark mode#include \"..\/stdafx.h\"\n#include \"list_view.h\"\n\nnamespace uih {\n\nvoid ListView::destroy_header()\n{\n if (m_wnd_header) {\n DestroyWindow(m_wnd_header);\n m_wnd_header = nullptr;\n m_header_font.reset();\n }\n}\n\nvoid ListView::create_header()\n{\n \/\/ if (m_show_header)\n {\n if (!m_wnd_header) {\n m_header_font.reset(m_lf_header_valid ? CreateFontIndirect(&m_lf_header) : uih::create_icon_font());\n m_wnd_header = CreateWindowEx(0, WC_HEADER, _T(\"NGLVH\"),\n WS_CHILD | (0) | \/*(m_autosize ? 0x0800 : NULL) |*\/ HDS_HOTTRACK\n | (m_allow_header_rearrange ? HDS_DRAGDROP : NULL) | HDS_HORZ | HDS_FULLDRAG\n | (m_sorting_enabled ? HDS_BUTTONS : 0) | WS_CLIPSIBLINGS | WS_CLIPCHILDREN,\n 0, 0, 0, 0, get_wnd(), HMENU(IDC_HEADER), mmh::get_current_instance(), nullptr);\n SetWindowTheme(m_wnd_header, m_use_dark_mode ? L\"DarkMode_ItemsView\" : nullptr, nullptr);\n SendMessage(m_wnd_header, WM_SETFONT, (WPARAM)m_header_font.get(), MAKELPARAM(FALSE, 0));\n if (m_initialised) {\n build_header();\n ShowWindow(m_wnd_header, SW_SHOWNORMAL);\n }\n }\n }\n}\n\nvoid ListView::set_show_header(bool b_val)\n{\n if (b_val != m_show_header) {\n m_show_header = b_val;\n if (m_initialised) {\n if (m_show_header)\n create_header();\n else\n destroy_header();\n on_size();\n }\n }\n}\n\nvoid ListView::reposition_header()\n{\n RECT rc;\n GetClientRect(get_wnd(), &rc);\n int cx = RECT_CX(rc);\n RECT rc_header;\n get_header_rect(&rc_header);\n SetWindowPos(m_wnd_header, nullptr, -m_horizontal_scroll_position, 0, cx + m_horizontal_scroll_position,\n RECT_CY(rc_header), SWP_NOZORDER);\n}\n\nvoid ListView::build_header()\n{\n if (m_wnd_header) {\n pfc::vartoggle_t toggle(m_ignore_column_size_change_notification, true);\n\n t_size header_count = Header_GetItemCount(m_wnd_header);\n for (; header_count; header_count--)\n Header_DeleteItem(m_wnd_header, header_count - 1);\n\n HDITEM hdi;\n memset(&hdi, 0, sizeof(HDITEM));\n\n hdi.mask = HDI_TEXT | HDI_FORMAT | HDI_WIDTH;\n hdi.fmt = HDF_LEFT | HDF_STRING;\n\n pfc::string8 name;\n pfc::stringcvt::string_wide_from_utf8 wstr;\n\n {\n int n;\n int t = m_columns.size();\n int i = 0;\n const auto indentation = get_total_indentation();\n if (indentation \/*m_group_count*\/) {\n hdi.fmt = HDF_STRING | HDF_LEFT;\n hdi.cchTextMax = 0;\n hdi.pszText = const_cast(L\"\");\n\n hdi.cxy = indentation;\n\n Header_InsertItem(m_wnd_header, i++, &hdi);\n\n m_have_indent_column = true;\n } else\n m_have_indent_column = false;\n for (n = 0; n < t; n++) {\n hdi.fmt = HDF_STRING | HDF_LEFT;\n if (m_columns[n].m_alignment == uih::ALIGN_CENTRE)\n hdi.fmt |= HDF_CENTER;\n else if (m_columns[n].m_alignment == uih::ALIGN_RIGHT)\n hdi.fmt |= HDF_RIGHT;\n hdi.cchTextMax = m_columns[n].m_title.length();\n wstr.convert(m_columns[n].m_title);\n hdi.pszText = const_cast(wstr.get_ptr());\n\n hdi.cxy = m_columns[n].m_display_size;\n\n if (m_sort_column_index == n && m_show_sort_indicators) {\n hdi.fmt |= (m_sort_direction ? HDF_SORTDOWN : HDF_SORTUP);\n }\n\n Header_InsertItem(m_wnd_header, i++, &hdi);\n }\n }\n }\n}\n\nbool ListView::on_wm_notify_header(LPNMHDR lpnm, LRESULT& ret)\n{\n switch (lpnm->code) {\n case NM_CUSTOMDRAW: {\n LPNMCUSTOMDRAW lpcd = (LPNMCUSTOMDRAW)lpnm;\n switch (lpcd->dwDrawStage) {\n case CDDS_PREPAINT:\n ret = CDRF_NOTIFYITEMDRAW;\n return true;\n\n case CDDS_ITEMPREPAINT: {\n auto cr{RGB(255, 0, 0)};\n if (!SUCCEEDED(GetThemeColor(m_header_theme.get(), HP_HEADERITEM, 0, TMT_TEXTCOLOR, &cr)))\n return false;\n\n SetTextColor(lpcd->hdc, cr);\n ret = CDRF_NEWFONT;\n return true;\n }\n default:\n return false;\n }\n }\n case HDN_BEGINTRACKA:\n case HDN_BEGINTRACKW: {\n auto lpnmh = (LPNMHEADER)lpnm;\n if (m_autosize && (!get_show_group_info_area() || lpnmh->iItem)) {\n ret = TRUE;\n return true;\n }\n } break;\n case HDN_DIVIDERDBLCLICK: {\n auto lpnmh = (LPNMHEADER)lpnm;\n if (!m_autosize) {\n if (lpnmh->iItem != -1 && (!m_have_indent_column || lpnmh->iItem)) {\n t_size realIndex = lpnmh->iItem;\n if (m_have_indent_column)\n realIndex--;\n if (realIndex < m_columns.size()) {\n HDC dc;\n dc = GetDC(get_wnd());\n int size;\n\n HFONT fnt_old = SelectFont(dc, m_items_font.get());\n\n int w = 0;\n int n;\n int t = get_item_count();\n\n for (n = 0; n < t; n++) {\n const char* str = get_item_text(n, realIndex);\n size = uih::get_text_width_colour(dc, str, strlen(str));\n if (size > w)\n w = size;\n }\n w += uih::scale_dpi_value(3) * 2 + scale_dpi_value(1);\n\n SelectFont(dc, fnt_old);\n ReleaseDC(get_wnd(), dc);\n\n m_columns[realIndex].m_size = w;\n m_columns[realIndex].m_display_size = w;\n update_header();\n invalidate_all();\n notify_on_column_size_change(realIndex, m_columns[realIndex].m_size);\n update_scroll_info();\n }\n }\n }\n } break;\n case HDN_ITEMCHANGING: {\n if (!m_ignore_column_size_change_notification) {\n auto lpnmh = (LPNMHEADER)lpnm;\n if (lpnmh->pitem->mask & HDI_WIDTH) {\n if (m_have_indent_column && lpnmh->iItem == 0) {\n int min_indent = get_item_indentation();\n if (get_show_group_info_area())\n min_indent += get_default_indentation_step();\n if (lpnmh->pitem->cxy < min_indent) {\n ret = TRUE;\n return true;\n }\n }\n }\n }\n } break;\n case HDN_ITEMCHANGED: {\n if (!m_ignore_column_size_change_notification) {\n auto lpnmh = (LPNMHEADER)lpnm;\n if (lpnmh->pitem->mask & HDI_WIDTH) {\n if (lpnmh->iItem != -1) {\n if (m_have_indent_column && lpnmh->iItem == 0) {\n int new_size = lpnmh->pitem->cxy - get_item_indentation() - get_default_indentation_step();\n if (new_size >= 0 && new_size != get_group_info_area_width()) {\n \/*set_group_info_area_size(new_size);\n if (m_autosize)\n {\n update_column_sizes();\n update_header();\n }*\/\n notify_on_group_info_area_size_change(new_size);\n \/*invalidate_all();\n update_scroll_info();*\/\n }\n } else if (!m_autosize) {\n t_size realIndex = lpnmh->iItem;\n if (m_have_indent_column)\n realIndex--;\n if (realIndex < m_columns.size() && m_columns[realIndex].m_display_size != lpnmh->pitem->cxy) {\n m_columns[realIndex].m_size = lpnmh->pitem->cxy;\n m_columns[realIndex].m_display_size = lpnmh->pitem->cxy;\n invalidate_all();\n notify_on_column_size_change(realIndex, m_columns[realIndex].m_size);\n on_size();\n }\n }\n }\n }\n }\n } break;\n case HDN_ITEMCLICK: {\n auto lpnmh = (LPNMHEADER)lpnm;\n if (lpnmh->iItem != -1 && (!m_have_indent_column || lpnmh->iItem)) {\n t_size realIndex = lpnmh->iItem;\n if (m_have_indent_column)\n realIndex--;\n if (realIndex < m_columns.size()) {\n bool des = (realIndex == m_sort_column_index ? !m_sort_direction : false);\n sort_by_column(realIndex, des);\n }\n }\n } break;\n \/*case HDN_BEGINDRAG:\n {\n LPNMHEADER lpnmh = (LPNMHEADER)lpnm;\n if (lpnmh->iItem == 0 && m_have_indent_column)\n {\n ret = TRUE;\n return true;\n }\n }\n break;*\/\n case HDN_ENDDRAG: {\n auto lpnmh = (LPNMHEADER)lpnm;\n if (lpnmh->iButton == 0) {\n if (lpnmh->pitem && (lpnmh->pitem->mask & HDI_ORDER)) {\n int from = lpnmh->iItem;\n int to = lpnmh->pitem->iOrder;\n if (m_have_indent_column) {\n from--;\n to--;\n }\n if (to >= 0 && from >= 0 && from != to) {\n notify_on_header_rearrange(from, to);\n }\n }\n }\n }\n ret = TRUE;\n return true;\n }\n return false;\n}\n\nvoid ListView::get_header_rect(LPRECT rc) const\n{\n if (m_wnd_header)\n *rc = uih::get_relative_rect(m_wnd_header, get_wnd());\n else {\n GetClientRect(get_wnd(), rc);\n rc->bottom = rc->top;\n }\n}\n\nunsigned ListView::get_header_height() const\n{\n unsigned ret = 0;\n if (m_wnd_header) {\n RECT rc;\n get_header_rect(&rc);\n ret = RECT_CY(rc);\n }\n return ret;\n}\nunsigned ListView::calculate_header_height()\n{\n unsigned rv = 0;\n if (m_wnd_header) {\n auto font = (HFONT)SendMessage(m_wnd_header, WM_GETFONT, 0, 0);\n rv = uih::get_font_height(font) + m_vertical_item_padding + scale_dpi_value(2);\n }\n return rv;\n}\n\nvoid ListView::update_header()\n{\n if (m_wnd_header) {\n pfc::vartoggle_t toggle(m_ignore_column_size_change_notification, true);\n \/\/ SendMessage(m_wnd_header, WM_SETREDRAW, FALSE, NULL);\n t_size i;\n t_size count = m_columns.size();\n t_size j = 0;\n if (m_have_indent_column) {\n uih::header_set_item_width(m_wnd_header, j, get_total_indentation());\n j++;\n }\n for (i = 0; i < count; i++) {\n uih::header_set_item_width(m_wnd_header, i + j, m_columns[i].m_display_size);\n }\n \/\/ SendMessage(m_wnd_header, WM_SETREDRAW, TRUE, NULL);\n \/\/ RedrawWindow(m_wnd_header, NULL, NULL, RDW_INVALIDATE|(b_update?RDW_UPDATENOW:0));\n }\n}\n} \/\/ namespace uih\n<|endoftext|>"} {"text":"#ifndef TEST_HELPER_H_\n#define TEST_HELPER_H_\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n\nnamespace itertest {\n\n \/\/ non-copyable. non-movable. non-default-constructible\n class SolidInt {\n private:\n const int i;\n\n public:\n constexpr SolidInt(int n) : i{n} {}\n\n constexpr int getint() const {\n return this->i;\n }\n\n SolidInt() = delete;\n SolidInt(const SolidInt&) = delete;\n SolidInt& operator=(const SolidInt&) = delete;\n SolidInt& operator=(SolidInt&&) = delete;\n SolidInt(SolidInt&&) = delete;\n };\n\n namespace {\n struct DoubleDereferenceError : std::exception {\n const char* what() const noexcept override {\n return \"Iterator dereferenced twice without increment\";\n }\n };\n\n \/\/ this class's iterator will throw if it's dereference twice without\n \/\/ an increment in between\n class InputIterable {\n public:\n class Iterator {\n private:\n int i;\n bool was_incremented = true;\n\n public:\n Iterator(int n) : i{n} {}\n\n Iterator& operator++() {\n ++this->i;\n this->was_incremented = true;\n return *this;\n }\n\n int operator*() {\n if (!this->was_incremented) {\n throw DoubleDereferenceError{};\n }\n this->was_incremented = false;\n return this->i;\n }\n\n bool operator!=(const Iterator& other) const {\n return this->i != other.i;\n }\n };\n\n Iterator begin() {\n return {0};\n }\n\n Iterator end() {\n return {5};\n }\n };\n }\n\n \/\/ BasicIterable provides a minimal forward iterator\n \/\/ operator++(), operator!=(const BasicIterable&), operator*()\n \/\/ move constructible only\n \/\/ not copy constructible, move assignable, or copy assignable\n template \n class BasicIterable {\n private:\n T* data;\n std::size_t size;\n bool was_moved_from_ = false;\n mutable bool was_copied_from_ = false;\n\n public:\n BasicIterable(std::initializer_list il)\n : data{new T[il.size()]}, size{il.size()} {\n \/\/ would like to use enumerate, can't because it's for unit\n \/\/ testing enumerate\n std::size_t i = 0;\n for (auto&& e : il) {\n data[i] = e;\n ++i;\n }\n }\n\n BasicIterable& operator=(BasicIterable&&) = delete;\n BasicIterable& operator=(const BasicIterable&) = delete;\n\n#ifndef DEFINE_BASIC_ITERABLE_COPY_CTOR\n BasicIterable(const BasicIterable&) = delete;\n#else\n BasicIterable(const BasicIterable& other)\n : data{new T[other.size]}, size{other.size} {\n other.was_copied_from_ = true;\n auto o_it = begin(other);\n for (auto it = begin(*this); o_it != end(other); ++it, ++o_it) {\n *it = *o_it;\n }\n }\n#endif\n\n BasicIterable(BasicIterable&& other) : data{other.data}, size{other.size} {\n other.data = nullptr;\n other.was_moved_from_ = true;\n }\n\n bool was_moved_from() const {\n return this->was_moved_from_;\n }\n\n bool was_copied_from() const {\n return this->was_copied_from_;\n }\n\n ~BasicIterable() {\n delete[] this->data;\n }\n\n template \n class Iterator {\n private:\n U* p;\n\n public:\n#ifdef DEFINE_DEFAULT_ITERATOR_CTOR\n Iterator() = default;\n#endif\n Iterator(U* b) : p{b} {}\n bool operator!=(const Iterator& other) const {\n return this->p != other.p;\n }\n\n Iterator& operator++() {\n ++this->p;\n return *this;\n }\n\n U& operator*() {\n return *this->p;\n }\n };\n\n friend BasicIterable::Iterator begin(BasicIterable& b) {\n return {b.data};\n }\n\n friend BasicIterable::Iterator end(BasicIterable& b) {\n return {b.data + b.size};\n }\n\n#ifdef DEFINE_BASIC_ITERABLE_CONST_BEGIN_AND_END\n friend BasicIterable::Iterator begin(const BasicIterable& b) {\n return {b.data};\n }\n\n friend BasicIterable::Iterator end(const BasicIterable& b) {\n return {b.data + b.size};\n }\n#endif\n\n#ifdef DECLARE_REVERSE_ITERATOR\n Iterator rbegin();\n Iterator rend();\n#endif \/\/ ifdef DECLARE_REVERSE_ITERATOR\n };\n\n template \n struct IsIterator : std::false_type {};\n\n template \n struct IsIterator())), \/\/ copyctor\n decltype(std::declval() = std::declval()), \/\/ copy =\n decltype(*std::declval()), \/\/ operator*\n decltype(std::declval().operator->()), \/\/ operator->\n decltype(++std::declval()), \/\/ prefix ++\n decltype(std::declval()++), \/\/ postfix ++\n decltype(\n std::declval() != std::declval()), \/\/ !=\n decltype(std::declval() == std::declval()) \/\/ ==\n >> : std::true_type {};\n\n template \n struct IsForwardIterator\n : std::integral_constant::value && std::is_default_constructible::value> {};\n\n template \n struct IsMoveConstructibleOnly\n : std::integral_constant::value\n && !std::is_copy_assignable::value\n && !std::is_move_assignable::value\n && std::is_move_constructible::value> {};\n\n struct Point {\n int x;\n int y;\n int get_x() const {\n return x;\n }\n int get_y() const {\n return y;\n }\n\n std::string prefix(const std::string& str) {\n std::ostringstream ss;\n ss << str << \"(\" << x << \", \" << y << \")\";\n return ss.str();\n }\n };\n}\ntemplate \nclass DiffEndRange {\n private:\n T start_;\n T stop_;\n std::vector all_results_;\n\n public:\n constexpr DiffEndRange(T start, T stop) : start_{start}, stop_{stop} {\n while (start < stop_) {\n all_results_.push_back(start);\n Inc{}(start);\n }\n }\n\n class Iterator;\n class EndIterator;\n\n class Iterator {\n using SubIter = typename std::vector::iterator;\n\n private:\n SubIter it_;\n SubIter end_;\n\n public:\n#ifdef CHAR_RANGE_DEFAULT_CONSTRUCTIBLE\n Iterator() = default;\n#endif\n Iterator(SubIter it, SubIter end_it) : it_{it}, end_{end_it} {}\n\n T& operator*() const {\n return *it_;\n }\n T* operator->() const {\n return &*it_;\n }\n\n Iterator& operator++() {\n ++it_;\n return *this;\n }\n\n bool operator!=(const Iterator& other) const {\n return it_ != other.it_;\n }\n\n bool operator!=(const EndIterator&) const {\n return it_ != end_;\n }\n\n friend bool operator!=(const EndIterator& lhs, const Iterator& rhs) {\n return rhs != lhs;\n }\n };\n\n class ReverseIterator {\n using SubIter = typename std::vector::reverse_iterator;\n\n private:\n SubIter it_;\n SubIter end_;\n\n public:\n#ifdef CHAR_RANGE_DEFAULT_CONSTRUCTIBLE\n ReverseIterator() = default;\n#endif\n ReverseIterator(SubIter it, SubIter end_it) : it_{it}, end_{end_it} {}\n\n T& operator*() const {\n return *it_;\n }\n T* operator->() const {\n return &*it_;\n }\n\n Iterator& operator++() {\n ++it_;\n return *this;\n }\n\n bool operator!=(const Iterator& other) const {\n return it_ != other.it_;\n }\n\n bool operator!=(const EndIterator&) const {\n return it_ != end_;\n }\n\n friend bool operator!=(const EndIterator& lhs, const Iterator& rhs) {\n return rhs != lhs;\n }\n };\n\n class EndIterator {};\n class ReverseEndIterator {};\n\n Iterator begin() {\n return {std::begin(all_results_), std::end(all_results_)};\n }\n\n EndIterator end() {\n return {};\n }\n\n ReverseIterator rbegin() {\n return {std::rbegin(all_results_), std::rend(all_results_)};\n }\n\n ReverseEndIterator rend() {\n return {};\n }\n};\n\nstruct CharInc {\n void operator()(char& c) {\n ++c;\n }\n};\n\n\/\/ A range from 'a' to stop, begin() and end() are different\nclass CharRange : public DiffEndRange {\n public:\n constexpr CharRange(char stop) : DiffEndRange('a', stop) {}\n};\n\nstruct IncIntCharPair {\n void operator()(std::pair& p) {\n ++p.first;\n ++p.second;\n }\n};\n\nclass IntCharPairRange\n : public DiffEndRange, IncIntCharPair> {\n public:\n IntCharPairRange(std::pair stop)\n : DiffEndRange, IncIntCharPair>({0, 'a'}, stop) {}\n};\n\n#endif\nAdds == and != operators to Point#ifndef TEST_HELPER_H_\n#define TEST_HELPER_H_\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n\nnamespace itertest {\n\n \/\/ non-copyable. non-movable. non-default-constructible\n class SolidInt {\n private:\n const int i;\n\n public:\n constexpr SolidInt(int n) : i{n} {}\n\n constexpr int getint() const {\n return this->i;\n }\n\n SolidInt() = delete;\n SolidInt(const SolidInt&) = delete;\n SolidInt& operator=(const SolidInt&) = delete;\n SolidInt& operator=(SolidInt&&) = delete;\n SolidInt(SolidInt&&) = delete;\n };\n\n namespace {\n struct DoubleDereferenceError : std::exception {\n const char* what() const noexcept override {\n return \"Iterator dereferenced twice without increment\";\n }\n };\n\n \/\/ this class's iterator will throw if it's dereference twice without\n \/\/ an increment in between\n class InputIterable {\n public:\n class Iterator {\n private:\n int i;\n bool was_incremented = true;\n\n public:\n Iterator(int n) : i{n} {}\n\n Iterator& operator++() {\n ++this->i;\n this->was_incremented = true;\n return *this;\n }\n\n int operator*() {\n if (!this->was_incremented) {\n throw DoubleDereferenceError{};\n }\n this->was_incremented = false;\n return this->i;\n }\n\n bool operator!=(const Iterator& other) const {\n return this->i != other.i;\n }\n };\n\n Iterator begin() {\n return {0};\n }\n\n Iterator end() {\n return {5};\n }\n };\n }\n\n \/\/ BasicIterable provides a minimal forward iterator\n \/\/ operator++(), operator!=(const BasicIterable&), operator*()\n \/\/ move constructible only\n \/\/ not copy constructible, move assignable, or copy assignable\n template \n class BasicIterable {\n private:\n T* data;\n std::size_t size;\n bool was_moved_from_ = false;\n mutable bool was_copied_from_ = false;\n\n public:\n BasicIterable(std::initializer_list il)\n : data{new T[il.size()]}, size{il.size()} {\n \/\/ would like to use enumerate, can't because it's for unit\n \/\/ testing enumerate\n std::size_t i = 0;\n for (auto&& e : il) {\n data[i] = e;\n ++i;\n }\n }\n\n BasicIterable& operator=(BasicIterable&&) = delete;\n BasicIterable& operator=(const BasicIterable&) = delete;\n\n#ifndef DEFINE_BASIC_ITERABLE_COPY_CTOR\n BasicIterable(const BasicIterable&) = delete;\n#else\n BasicIterable(const BasicIterable& other)\n : data{new T[other.size]}, size{other.size} {\n other.was_copied_from_ = true;\n auto o_it = begin(other);\n for (auto it = begin(*this); o_it != end(other); ++it, ++o_it) {\n *it = *o_it;\n }\n }\n#endif\n\n BasicIterable(BasicIterable&& other) : data{other.data}, size{other.size} {\n other.data = nullptr;\n other.was_moved_from_ = true;\n }\n\n bool was_moved_from() const {\n return this->was_moved_from_;\n }\n\n bool was_copied_from() const {\n return this->was_copied_from_;\n }\n\n ~BasicIterable() {\n delete[] this->data;\n }\n\n template \n class Iterator {\n private:\n U* p;\n\n public:\n#ifdef DEFINE_DEFAULT_ITERATOR_CTOR\n Iterator() = default;\n#endif\n Iterator(U* b) : p{b} {}\n bool operator!=(const Iterator& other) const {\n return this->p != other.p;\n }\n\n Iterator& operator++() {\n ++this->p;\n return *this;\n }\n\n U& operator*() {\n return *this->p;\n }\n };\n\n friend BasicIterable::Iterator begin(BasicIterable& b) {\n return {b.data};\n }\n\n friend BasicIterable::Iterator end(BasicIterable& b) {\n return {b.data + b.size};\n }\n\n#ifdef DEFINE_BASIC_ITERABLE_CONST_BEGIN_AND_END\n friend BasicIterable::Iterator begin(const BasicIterable& b) {\n return {b.data};\n }\n\n friend BasicIterable::Iterator end(const BasicIterable& b) {\n return {b.data + b.size};\n }\n#endif\n\n#ifdef DECLARE_REVERSE_ITERATOR\n Iterator rbegin();\n Iterator rend();\n#endif \/\/ ifdef DECLARE_REVERSE_ITERATOR\n };\n\n template \n struct IsIterator : std::false_type {};\n\n template \n struct IsIterator())), \/\/ copyctor\n decltype(std::declval() = std::declval()), \/\/ copy =\n decltype(*std::declval()), \/\/ operator*\n decltype(std::declval().operator->()), \/\/ operator->\n decltype(++std::declval()), \/\/ prefix ++\n decltype(std::declval()++), \/\/ postfix ++\n decltype(\n std::declval() != std::declval()), \/\/ !=\n decltype(std::declval() == std::declval()) \/\/ ==\n >> : std::true_type {};\n\n template \n struct IsForwardIterator\n : std::integral_constant::value && std::is_default_constructible::value> {};\n\n template \n struct IsMoveConstructibleOnly\n : std::integral_constant::value\n && !std::is_copy_assignable::value\n && !std::is_move_assignable::value\n && std::is_move_constructible::value> {};\n\n struct Point {\n int x;\n int y;\n int get_x() const {\n return x;\n }\n int get_y() const {\n return y;\n }\n\n std::string prefix(const std::string& str) {\n std::ostringstream ss;\n ss << str << \"(\" << x << \", \" << y << \")\";\n return ss.str();\n }\n\n bool operator==(Point other) const {\n return x == other.x && y == other.y;\n }\n\n bool operator!=(Point other) const {\n return !(*this == other);\n }\n };\n}\ntemplate \nclass DiffEndRange {\n private:\n T start_;\n T stop_;\n std::vector all_results_;\n\n public:\n constexpr DiffEndRange(T start, T stop) : start_{start}, stop_{stop} {\n while (start < stop_) {\n all_results_.push_back(start);\n Inc{}(start);\n }\n }\n\n class Iterator;\n class EndIterator;\n\n class Iterator {\n using SubIter = typename std::vector::iterator;\n\n private:\n SubIter it_;\n SubIter end_;\n\n public:\n#ifdef CHAR_RANGE_DEFAULT_CONSTRUCTIBLE\n Iterator() = default;\n#endif\n Iterator(SubIter it, SubIter end_it) : it_{it}, end_{end_it} {}\n\n T& operator*() const {\n return *it_;\n }\n T* operator->() const {\n return &*it_;\n }\n\n Iterator& operator++() {\n ++it_;\n return *this;\n }\n\n bool operator!=(const Iterator& other) const {\n return it_ != other.it_;\n }\n\n bool operator!=(const EndIterator&) const {\n return it_ != end_;\n }\n\n friend bool operator!=(const EndIterator& lhs, const Iterator& rhs) {\n return rhs != lhs;\n }\n };\n\n class ReverseIterator {\n using SubIter = typename std::vector::reverse_iterator;\n\n private:\n SubIter it_;\n SubIter end_;\n\n public:\n#ifdef CHAR_RANGE_DEFAULT_CONSTRUCTIBLE\n ReverseIterator() = default;\n#endif\n ReverseIterator(SubIter it, SubIter end_it) : it_{it}, end_{end_it} {}\n\n T& operator*() const {\n return *it_;\n }\n T* operator->() const {\n return &*it_;\n }\n\n Iterator& operator++() {\n ++it_;\n return *this;\n }\n\n bool operator!=(const Iterator& other) const {\n return it_ != other.it_;\n }\n\n bool operator!=(const EndIterator&) const {\n return it_ != end_;\n }\n\n friend bool operator!=(const EndIterator& lhs, const Iterator& rhs) {\n return rhs != lhs;\n }\n };\n\n class EndIterator {};\n class ReverseEndIterator {};\n\n Iterator begin() {\n return {std::begin(all_results_), std::end(all_results_)};\n }\n\n EndIterator end() {\n return {};\n }\n\n ReverseIterator rbegin() {\n return {std::rbegin(all_results_), std::rend(all_results_)};\n }\n\n ReverseEndIterator rend() {\n return {};\n }\n};\n\nstruct CharInc {\n void operator()(char& c) {\n ++c;\n }\n};\n\n\/\/ A range from 'a' to stop, begin() and end() are different\nclass CharRange : public DiffEndRange {\n public:\n constexpr CharRange(char stop) : DiffEndRange('a', stop) {}\n};\n\nstruct IncIntCharPair {\n void operator()(std::pair& p) {\n ++p.first;\n ++p.second;\n }\n};\n\nclass IntCharPairRange\n : public DiffEndRange, IncIntCharPair> {\n public:\n IntCharPairRange(std::pair stop)\n : DiffEndRange, IncIntCharPair>({0, 'a'}, stop) {}\n};\n\n#endif\n<|endoftext|>"} {"text":"\/**\n * @copyright Copyright 2016 The J-PET Framework Authors. All rights reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may find a copy of the License in the LICENCE file.\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n * @file HitFinderTools.h\n *\/\n\n#include \"HitFinderTools.h\"\n\nusing namespace std;\n\nvector HitFinderTools::createHits(const SignalsContainer& allSignalsInTimeWindow, const double timeDifferenceWindow){\n\n\n \/\/ This method takes signal from side A on a scintilator and compares it with signals on side B - if they are within time window then it creates hit\n\n vector hits;\n\n for (auto scintillator : allSignalsInTimeWindow) {\n\n auto sideA = scintillator.second.first;\n auto sideB = scintillator.second.second;\n\n if(sideA.size() > 0 and sideB.size() > 0){\n\n for(auto signalA : sideA){\n for(auto signalB : sideB){\n\n if(abs(signalA.getTime() - signalB.getTime()) < timeDifferenceWindow \/*ps*\/){\n\n JPetHit hit;\n hit.setSignalA(signalA);\n hit.setSignalB(signalB);\n hit.setTime( (signalA.getTime() + signalB.getTime())\/2.0 );\n hit.setScintillator(signalA.getRecoSignal().getRawSignal().getPM().getScin());\n hit.setBarrelSlot(signalA.getRecoSignal().getRawSignal().getPM().getScin().getBarrelSlot());\n\n hits.push_back(hit);\n }\n }\n }\n\n }\n }\n return hits;\n}\nSort signals\/**\n * @copyright Copyright 2016 The J-PET Framework Authors. All rights reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may find a copy of the License in the LICENCE file.\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n * @file HitFinderTools.h\n *\/\n\n#include \"HitFinderTools.h\"\n\nusing namespace std;\n\nvector HitFinderTools::createHits(const SignalsContainer& allSignalsInTimeWindow, const double timeDifferenceWindow){\n\n\n \/\/ This method takes signal from side A on a scintilator and compares it with signals on side B - if they are within time window then it creates hit\n\n vector hits;\n\n for (auto scintillator : allSignalsInTimeWindow) {\n\n auto sideA = scintillator.second.first;\n auto sideB = scintillator.second.second;\n\n if(sideA.size() > 0 and sideB.size() > 0){\n\n std::sort(sideA.begin(), sideA.end(), [] (const JPetPhysSignal & h1, const JPetPhysSignal & h2) {return h1.getTime() < h2.getTime();});\n std::sort(sideB.begin(), sideB.end(), [] (const JPetPhysSignal & h1, const JPetPhysSignal & h2) {return h1.getTime() < h2.getTime();});\n for(auto signalA : sideA){\n for(auto signalB : sideB){\n\n if(abs(signalA.getTime() - signalB.getTime()) < timeDifferenceWindow && (signalA.getTime() - signalB.getTime()) < timeDifferenceWindow\/*ps*\/){\n\n JPetHit hit;\n hit.setSignalA(signalA);\n hit.setSignalB(signalB);\n hit.setTime( (signalA.getTime() + signalB.getTime())\/2.0 );\n hit.setScintillator(signalA.getRecoSignal().getRawSignal().getPM().getScin());\n hit.setBarrelSlot(signalA.getRecoSignal().getRawSignal().getPM().getScin().getBarrelSlot());\n\n hits.push_back(hit);\n }\n }\n }\n\n }\n }\n return hits;\n}\n<|endoftext|>"} {"text":"\/*\n * The Apache Software License, Version 1.1\n *\n * Copyright (c) 1999-2000 The Apache Software Foundation. All rights\n * reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n * if any, must include the following acknowledgment:\n * \"This product includes software developed by the\n * Apache Software Foundation (http:\/\/www.apache.org\/).\"\n * Alternately, this acknowledgment may appear in the software itself,\n * if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xerces\" and \"Apache Software Foundation\" must\n * not be used to endorse or promote products derived from this\n * software without prior written permission. For written\n * permission, please contact apache\\@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n * nor may \"Apache\" appear in their name, without prior written\n * permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation, and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com . For more information\n * on the Apache Software Foundation, please see\n * .\n *\/\n\n\/**\n * $Log$\n * Revision 1.2 2000\/02\/06 07:47:24 rahulj\n * Year 2K copyright swat.\n *\n * Revision 1.1.1.1 1999\/11\/09 01:09:29 twl\n * Initial checkin\n *\n * Revision 1.11 1999\/11\/08 20:43:42 rahul\n * Swat for adding in Product name and CVS comment log variable.\n *\n *\/\n\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Includes\n\/\/ ---------------------------------------------------------------------------\n#include \n#include \n#include \"SAXPrint.hpp\"\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ SAXPrintHandlers: Constructors and Destructor\n\/\/ ---------------------------------------------------------------------------\nSAXPrintHandlers::SAXPrintHandlers(const bool doEscapes) :\n\n fDoEscapes(doEscapes)\n{\n}\n\nSAXPrintHandlers::~SAXPrintHandlers()\n{\n}\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ SAXPrintHandlers: Overrides of the SAX ErrorHandler interface\n\/\/ ---------------------------------------------------------------------------\nvoid SAXPrintHandlers::error(const SAXParseException& e)\n{\n cerr << \"\\nError at (file \" << StrX(e.getSystemId())\n\t\t << \", line \" << e.getLineNumber()\n\t\t << \", char \" << e.getColumnNumber()\n << \"): \" << StrX(e.getMessage()) << endl;\n}\n\nvoid SAXPrintHandlers::fatalError(const SAXParseException& e)\n{\n cerr << \"\\nFatal Error at (file \" << StrX(e.getSystemId())\n\t\t << \", line \" << e.getLineNumber()\n\t\t << \", char \" << e.getColumnNumber()\n << \"): \" << StrX(e.getMessage()) << endl;\n}\n\nvoid SAXPrintHandlers::warning(const SAXParseException& e)\n{\n cerr << \"\\nWarning at (file \" << StrX(e.getSystemId())\n\t\t << \", line \" << e.getLineNumber()\n\t\t << \", char \" << e.getColumnNumber()\n << \"): \" << StrX(e.getMessage()) << endl;\n}\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ SAXPrintHandlers: Overrides of the SAX DTDHandler interface\n\/\/ ---------------------------------------------------------------------------\nvoid SAXPrintHandlers::unparsedEntityDecl(const XMLCh* const name\n , const XMLCh* const publicId\n , const XMLCh* const systemId\n , const XMLCh* const notationName)\n{\n \/\/ Not used at this time\n}\n\n\nvoid SAXPrintHandlers::notationDecl( const XMLCh* const name\n , const XMLCh* const publicId\n , const XMLCh* const systemId)\n{\n \/\/ Not used at this time\n}\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ SAXPrintHandlers: Overrides of the SAX DocumentHandler interface\n\/\/ ---------------------------------------------------------------------------\nvoid SAXPrintHandlers::characters(const XMLCh* const chars\n , const unsigned int length)\n{\n \/\/ Transcode to UTF-8 for portable display\n StrX tmpXCode(chars, length);\n\tconst char* tmpText = tmpXCode.localForm();\n\n \/\/\n \/\/ If we were asked to escape special chars, then do that. Else just\n \/\/ display it as normal text.\n \/\/\n if (fDoEscapes)\n {\n for (unsigned int index = 0; index < length; index++)\n {\n switch (tmpText[index])\n {\n case chAmpersand :\n cout << \"&\";\n break;\n\n case chOpenAngle :\n cout << \"<\";\n break;\n\n case chCloseAngle:\n cout << \">\";\n break;\n\n case chDoubleQuote :\n cout << \""\";\n break;\n\n default:\n cout << tmpText[index];\n break;\n }\n }\n }\n else\n {\n cout << tmpText;\n }\n}\n\n\nvoid SAXPrintHandlers::endDocument()\n{\n}\n\nvoid SAXPrintHandlers::endElement(const XMLCh* const name)\n{\n cout << \"<\/\" << StrX(name) << \">\";\n}\n\nvoid SAXPrintHandlers::ignorableWhitespace( const XMLCh* const chars\n ,const unsigned int length)\n{\n cout << StrX(chars, length);\n}\n\nvoid SAXPrintHandlers::processingInstruction(const XMLCh* const target\n , const XMLCh* const data)\n{\n cout << \"\\n\";\n}\n\nvoid SAXPrintHandlers::startDocument()\n{\n}\n\nvoid SAXPrintHandlers::startElement(const XMLCh* const name\n , AttributeList& attributes)\n{\n cout << \"<\" << StrX(name);\n unsigned int len = attributes.getLength();\n\n for (unsigned int index = 0; index < len; index++)\n {\n cout << \" \" << StrX(attributes.getName(index)) << \"=\\\"\";\n\t\tcout << StrX(attributes.getValue(index)) << \"\\\"\";\n }\n cout << \">\";\n}\n\n\nRemoved second parameter from call to StrX constructor\/*\n * The Apache Software License, Version 1.1\n *\n * Copyright (c) 1999-2000 The Apache Software Foundation. All rights\n * reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n * if any, must include the following acknowledgment:\n * \"This product includes software developed by the\n * Apache Software Foundation (http:\/\/www.apache.org\/).\"\n * Alternately, this acknowledgment may appear in the software itself,\n * if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xerces\" and \"Apache Software Foundation\" must\n * not be used to endorse or promote products derived from this\n * software without prior written permission. For written\n * permission, please contact apache\\@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n * nor may \"Apache\" appear in their name, without prior written\n * permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation, and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com . For more information\n * on the Apache Software Foundation, please see\n * .\n *\/\n\n\/**\n * $Log$\n * Revision 1.3 2000\/02\/11 03:05:35 abagchi\n * Removed second parameter from call to StrX constructor\n *\n * Revision 1.2 2000\/02\/06 07:47:24 rahulj\n * Year 2K copyright swat.\n *\n * Revision 1.1.1.1 1999\/11\/09 01:09:29 twl\n * Initial checkin\n *\n * Revision 1.11 1999\/11\/08 20:43:42 rahul\n * Swat for adding in Product name and CVS comment log variable.\n *\n *\/\n\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Includes\n\/\/ ---------------------------------------------------------------------------\n#include \n#include \n#include \"SAXPrint.hpp\"\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ SAXPrintHandlers: Constructors and Destructor\n\/\/ ---------------------------------------------------------------------------\nSAXPrintHandlers::SAXPrintHandlers(const bool doEscapes) :\n\n fDoEscapes(doEscapes)\n{\n}\n\nSAXPrintHandlers::~SAXPrintHandlers()\n{\n}\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ SAXPrintHandlers: Overrides of the SAX ErrorHandler interface\n\/\/ ---------------------------------------------------------------------------\nvoid SAXPrintHandlers::error(const SAXParseException& e)\n{\n cerr << \"\\nError at (file \" << StrX(e.getSystemId())\n\t\t << \", line \" << e.getLineNumber()\n\t\t << \", char \" << e.getColumnNumber()\n << \"): \" << StrX(e.getMessage()) << endl;\n}\n\nvoid SAXPrintHandlers::fatalError(const SAXParseException& e)\n{\n cerr << \"\\nFatal Error at (file \" << StrX(e.getSystemId())\n\t\t << \", line \" << e.getLineNumber()\n\t\t << \", char \" << e.getColumnNumber()\n << \"): \" << StrX(e.getMessage()) << endl;\n}\n\nvoid SAXPrintHandlers::warning(const SAXParseException& e)\n{\n cerr << \"\\nWarning at (file \" << StrX(e.getSystemId())\n\t\t << \", line \" << e.getLineNumber()\n\t\t << \", char \" << e.getColumnNumber()\n << \"): \" << StrX(e.getMessage()) << endl;\n}\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ SAXPrintHandlers: Overrides of the SAX DTDHandler interface\n\/\/ ---------------------------------------------------------------------------\nvoid SAXPrintHandlers::unparsedEntityDecl(const XMLCh* const name\n , const XMLCh* const publicId\n , const XMLCh* const systemId\n , const XMLCh* const notationName)\n{\n \/\/ Not used at this time\n}\n\n\nvoid SAXPrintHandlers::notationDecl( const XMLCh* const name\n , const XMLCh* const publicId\n , const XMLCh* const systemId)\n{\n \/\/ Not used at this time\n}\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ SAXPrintHandlers: Overrides of the SAX DocumentHandler interface\n\/\/ ---------------------------------------------------------------------------\nvoid SAXPrintHandlers::characters(const XMLCh* const chars\n , const unsigned int length)\n{\n \/\/ Transcode to UTF-8 for portable display\n StrX tmpXCode(chars);\n const char* tmpText = tmpXCode.localForm();\n\n \/\/\n \/\/ If we were asked to escape special chars, then do that. Else just\n \/\/ display it as normal text.\n \/\/\n if (fDoEscapes)\n {\n for (unsigned int index = 0; index < length; index++)\n {\n switch (tmpText[index])\n {\n case chAmpersand :\n cout << \"&\";\n break;\n\n case chOpenAngle :\n cout << \"<\";\n break;\n\n case chCloseAngle:\n cout << \">\";\n break;\n\n case chDoubleQuote :\n cout << \""\";\n break;\n\n default:\n cout << tmpText[index];\n break;\n }\n }\n }\n else\n {\n cout << tmpText;\n }\n}\n\n\nvoid SAXPrintHandlers::endDocument()\n{\n}\n\nvoid SAXPrintHandlers::endElement(const XMLCh* const name)\n{\n cout << \"<\/\" << StrX(name) << \">\";\n}\n\nvoid SAXPrintHandlers::ignorableWhitespace( const XMLCh* const chars\n ,const unsigned int length)\n{\n cout << StrX(chars);\n}\n\nvoid SAXPrintHandlers::processingInstruction(const XMLCh* const target\n , const XMLCh* const data)\n{\n cout << \"\\n\";\n}\n\nvoid SAXPrintHandlers::startDocument()\n{\n}\n\nvoid SAXPrintHandlers::startElement(const XMLCh* const name\n , AttributeList& attributes)\n{\n cout << \"<\" << StrX(name);\n unsigned int len = attributes.getLength();\n\n for (unsigned int index = 0; index < len; index++)\n {\n cout << \" \" << StrX(attributes.getName(index)) << \"=\\\"\";\n\t\tcout << StrX(attributes.getValue(index)) << \"\\\"\";\n }\n cout << \">\";\n}\n\n\n<|endoftext|>"} {"text":"\/\/\n\/\/ Exponent.cpp\n\/\/ Calculator\n\/\/\n\/\/ Created by Gavin Scheele on 3\/27\/14.\n\/\/ Copyright (c) 2014 Gavin Scheele. All rights reserved.\n\/\/\n\n#include \"Exponential.h\"\n\n\nExponential::Exponential(Expression* base, Rational* exponent){\n this->type = \"exponential\";\n this->base = base;\n this->exponent = exponent;\n this->exde = new Integer(exponent->getDenominator());\n if (exde->getValue() != 1) {\n \t\/\/if the denominator of the exponent is not 1, make the base a root of the denominator, then setting the denominator equal to 1\n \tInteger* baseAsInteger = (Integer *) base;\n base = new nthRoot(exde->getValue(), baseAsInteger->getValue(), 1);\n Integer* one = new Integer(1);\n exponent->setDenominator(one);\n }\n this->exnu = new Integer(exponent->getNumerator());\n if (canExponentiate()) {\n \texponentiate();\n }\n}\nExponential::~Exponential(){\n\n}\n\nbool Exponential::canExponentiate() {\n if(base->type == \"euler\"){\n return false;\n\n }else if(base->type == \"exponential\"){\n\tExponential* ex = (Exponential *) base;\n\tthis->exponent->multiply(ex->getExponent());\n\tInteger* numSum = new Integer (1);\n\tex->getExponent()->setNumerator(numSum);\n return false;\n \/\/ false is returned because the base itself would have already been exponentiated if it were possible\n\n }else if(base->type == \"integer\"){\n return true;\n\n\n }else if(base->type == \"logarithm\"){\n return false;\n\n }else if(base->type == \"nthRoot\"){\n\tnthRoot* nr = (nthRoot *) base;\n\tRational* r = new Rational(this->exponent->getNumerator(), nr->getRoot()*this->exponent->getDenominator());\n\t\/\/makes a new exponent, multiplying the denominator by the root, allowing the root to be simplified to one\n\tthis->exponent = r;\n\tnr->setRoot(1);\n\treturn false;\n\n }else if(base->type == \"pi\"){\n return false;\n\n }else if(base->type == \"rational\"){\n Rational* r = (Rational *) base;\n if (r->geteNumerator()->type == \"integer\" && r->geteDenominator()->type == \"integer\") {\n Exponential* nu = new Exponential(r->geteNumerator(), this->exponent);\n r->setNumerator(nu);\n Exponential* de = new Exponential(r->geteDenominator(), this->exponent);\n r->setDenominator(de);\n }\n\n }else{\n cout << \"type not recognized\" << endl;\n }\n return false;\n}\n\nvoid Exponential::exponentiate(){\n\tInteger* one = new Integer(1);\n Rational* oneRat = new Rational(1, 1);\n\tif (this->base->type == \"rational\") {\n\t\tRational* ratBase = (Rational *) this->base;\n\t\tExponential* numAsExponential = new Exponential ((ratBase->geteNumerator()), (this->exponent)); \/\/no matching constructor for exponential\n\t\tExponential* denAsExponential = new Exponential ((ratBase->geteDenominator()), (this->exponent)); \/\/same error\n\t\tRational* newRatBase = new Rational(numAsExponential, denAsExponential);\n\t\tthis->base = newRatBase;\n\t\tthis->exponent = oneRat;\n\t}\n\telse {\n\n if (this->exponent->getNumerator()==0) {\n \n this->exponent=oneRat;\n this->base=one;\n\n }\n bool toFlip = false;\n if (exnu->getValue()<0) {\n\t exnu->setValue(exnu->getValue()*-1);\n toFlip = true;\n \/\/handles negative exponents\n }\n Expression* constantBase = 0;\n if (base->type == \"integer\") { \/\/fixed the problem for integers but nothing else\n Integer *a = (Integer *)base;\n constantBase = new Integer(a->getValue());\n }\n\n\n while (exponent->getNumerator()>1)\n \t{\n base->multiply(constantBase);\n exponent->setNumerator(exponent->geteNumerator()->subtract(one));\n }\n if (toFlip) {\n Integer* one = new Integer(1);\n Rational* mouse = new Rational(one, base);\n \tbase = mouse;\n }\n \n\t}\n\n}\n\nExpression* Exponential::add(Expression* a){\n if(a->type == \"euler\"){\n\n }else if(a->type == \"exponential\"){\n\tExponential* ex = (Exponential *) a;\n\tif (ex->getBase()==this->base) {\n\t\tif (ex->getExponent()==this->exponent) {\n\t\t\tInteger* two = new Integer(2);\n\t\t\tthis->multiply(two);\n\t\t}\n\t}\n\n }else if(a->type == \"integer\"){\n\n }else if(a->type == \"logarithm\"){\n\n }else if(a->type == \"nthRoot\"){\n\n }else if(a->type == \"pi\"){\n\n }else if(a->type == \"rational\"){\n\n }else{\n cout << \"type not recognized\" << endl;\n }\n return this;\n}\nExpression* Exponential::subtract(Expression* a){\n if(a->type == \"euler\"){\n\n }else if(a->type == \"exponential\"){\n\tExponential* ex = (Exponential *) a;\n\tif (ex->getBase()==this->base) {\n\t\tif (ex->getExponent()==this->exponent) {\n\t\t\tInteger* zero = new Integer(0);\n\t\t\tthis->multiply(zero);\n\t\t}\n\t}\n }else if(a->type == \"integer\"){\n\n }else if(a->type == \"logarithm\"){\n\n }else if(a->type == \"nthRoot\"){\n\n }else if(a->type == \"pi\"){\n\n }else if(a->type == \"rational\"){\n\n }else{\n cout << \"type not recognized\" << endl;\n }\n return this;\n}\nExpression* Exponential::multiply(Expression* a){\n\tif(a->type == \"euler\"){\n \t\tif (this->base->type == \"euler\") {\n \t\t\tRational* oneRat = new Rational(1, 1);\n\t\t\tthis->exponent->add(oneRat);\n \t\t\n \t}\n\n }else if(a->type == \"exponential\"){\n\t\tExponential* ex = (Exponential *) a;\n\tif (this->base == ex->getBase()) {\n\t\tthis->exponent->add(ex->getExponent());\n\t}\n\n }else if(a->type == \"integer\"){\n\n }else if(a->type == \"logarithm\"){\n\n }else if(a->type == \"nthRoot\"){\n\n }else if(a->type == \"pi\"){\n \tif (this->base->type == \"pi\") {\n \t\t\tRational* oneRat = new Rational(1, 1);\n\t\t\tthis->exponent->add(oneRat);\n \t}\n\n }else if(a->type == \"rational\"){\n\tRational* r = (Rational *) a;\n\tExpression* numToSet = r->geteNumerator();\n\tnumToSet->multiply(this);\n\tr->setNumerator(numToSet);\n\treturn r;\n\n }else{\n cout << \"type not recognized\" << endl;\n }\n return this;\n}\nExpression* Exponential::divide(Expression* a){\n\tif(a->type == \"euler\"){\n\t\tif (this->base->type == \"euler\") {\n \t\t\t\tRational* oneRat = new Rational(1, 1);\n\t\t\t\tthis->exponent->subtract(oneRat);\n \t\t}\n\n }else if(a->type == \"exponential\"){\n\tExponential* ex = (Exponential *) a;\n\tif (this->base == ex->getBase()) {\n\t\tthis->exponent->subtract(ex->getExponent());\n\t}\n\n }else if(a->type == \"integer\"){\n\n }else if(a->type == \"logarithm\"){\n\n }else if(a->type == \"nthRoot\"){\n\n }else if(a->type == \"pi\"){\n \tif (this->base->type == \"pi\") {\n \t\t\t\tRational* oneRat = new Rational(1, 1);\n\t\t\t\tthis->exponent->subtract(oneRat);\n \t\t}\n\n }else if(a->type == \"rational\"){\n\tRational* r = (Rational *) a;\n\tExpression* denToSet = r->geteDenominator();\n\tdenToSet->multiply(this);\n\tr->setDenominator(denToSet);\n\treturn r;\n\n }else{\n cout << \"type not recognized\" << endl;\n }\n return this;\n}\n\nRational* Exponential::getExponent() {\n return exponent;\n}\n\nExpression* Exponential::getBase() {\n return base;\n}\n\nInteger* Exponential::getExnu() {\n\treturn exnu;\n}\n\nInteger* Exponential::getExde() {\n\treturn exde;\n}\n\nvoid Exponential::setExnu(Integer* n) {\n\texnu = n;\n}\n\nvoid Exponential::setExde(Integer* n) {\n\texde = n;\n}\n\nvoid Exponential::setExponent(Rational* e) {\n exponent = e;\n}\n\nvoid Exponential::setBase(Expression* e) {\n base = e;\n}\n\nstring Exponential::toString() {\n stringstream str;\n if(exponent->getNumerator() == 1 && exponent->getDenominator() == 1){\n str << *base;\n }\n else if(exponent->getDenominator() == 1){\n str << *base << \"^\" << *exponent->geteNumerator();\n }else{\n str << *base << \"^\" << *exponent;\n }\n return str.str();\n}\n\n\nostream& Exponential::print(std::ostream& output) const{\n Exponential *a = (Exponential *)this;\n output << a->toString();\n return output;\n}\n\n\n\nbool Exponential::canAdd(Expression* b){ \/\/use \"this\" as comparison. Solver will call someExpression.canAdd(&someOtherExpression)\n \n if (this->type == b->type && this->type != \"logarithm\") {\n if (this->type == \"nthRoot\") {\n }\n return true;\n }else if((this->type == \"integer\" && b->type == \"rational\") || (this->type == \"rational\" && b->type == \"integer\")){\n return true;\n }else if(this->type == \"multiple\" && b->type == \"multiple\"){\n MultipleExpressions *t = (MultipleExpressions *)this;\n MultipleExpressions *m = (MultipleExpressions *)b;\n if ((t->meType == \"as\" && m->meType == \"as\") || (t->meType == \"md\" && m->meType == \"md\")) {\n return true;\n }\n }else if(this->type == \"multiple\" || b->type == \"multiple\") return true;\n return false;\n}\nbool Exponential::canSubtract(Expression* b){\n if (this->type == b->type) {\n return true;\n }else if((this->type == \"integer\" && b->type == \"rational\") || (this->type == \"rational\" && b->type == \"integer\")){\n return true;\n }else if(this->type == \"multiple\" && b->type == \"multiple\"){\n MultipleExpressions *t = (MultipleExpressions *)this;\n MultipleExpressions *m = (MultipleExpressions *)b;\n if ((t->meType == \"as\" && m->meType == \"as\") || (t->meType == \"md\" && m->meType == \"md\")) {\n return true;\n }\n }else if(this->type == \"multiple\" || b->type == \"multiple\") return true;\n return false;\n}\nbool Exponential::canMultiply(Expression* b){\n if (this->type == b->type) {\n return true;\n }\n else if(this->type == \"integer\" && b->type == \"rational\") return true;\n else if(this->type == \"rational\" && b->type == \"integer\") return true;\n else if(this->type == \"multiple\" && b->type == \"multiple\"){\n MultipleExpressions *t = (MultipleExpressions *)this;\n MultipleExpressions *m = (MultipleExpressions *)b;\n if ((t->meType == \"as\" && m->meType == \"as\") || (t->meType == \"md\" && m->meType == \"md\")) {\n return true;\n }\n }else if(this->type == \"multiple\" || b->type == \"multiple\") return true;\n return false;\n \n}\nbool Exponential::canDivide(Expression* b){\n if (this->type == b->type) {\n return true;\n }\n else if(this->type == \"integer\"){\n if( b->type == \"rational\") return true;\n }\n else if(this->type == \"rational\" && b->type == \"integer\") return true;\n else if(this->type == \"multiple\" && b->type == \"multiple\"){\n MultipleExpressions *t = (MultipleExpressions *)this;\n MultipleExpressions *m = (MultipleExpressions *)b;\n if ((t->meType == \"as\" && m->meType == \"as\") || (t->meType == \"md\" && m->meType == \"md\")) {\n return true;\n }\n }else if(this->type == \"multiple\" || b->type == \"multiple\") return true;\n return false;\n}\nFixed canMultiply and canDivide\/\/\n\/\/ Exponent.cpp\n\/\/ Calculator\n\/\/\n\/\/ Created by Gavin Scheele on 3\/27\/14.\n\/\/ Copyright (c) 2014 Gavin Scheele. All rights reserved.\n\/\/\n\n#include \"Exponential.h\"\n\n\nExponential::Exponential(Expression* base, Rational* exponent){\n this->type = \"exponential\";\n this->base = base;\n this->exponent = exponent;\n this->exde = new Integer(exponent->getDenominator());\n if (exde->getValue() != 1) {\n \t\/\/if the denominator of the exponent is not 1, make the base a root of the denominator, then setting the denominator equal to 1\n \tInteger* baseAsInteger = (Integer *) base;\n base = new nthRoot(exde->getValue(), baseAsInteger->getValue(), 1);\n Integer* one = new Integer(1);\n exponent->setDenominator(one);\n }\n this->exnu = new Integer(exponent->getNumerator());\n if (canExponentiate()) {\n \texponentiate();\n }\n}\nExponential::~Exponential(){\n\n}\n\nbool Exponential::canExponentiate() {\n if(base->type == \"euler\"){\n return false;\n\n }else if(base->type == \"exponential\"){\n\tExponential* ex = (Exponential *) base;\n\tthis->exponent->multiply(ex->getExponent());\n\tInteger* numSum = new Integer (1);\n\tex->getExponent()->setNumerator(numSum);\n return false;\n \/\/ false is returned because the base itself would have already been exponentiated if it were possible\n\n }else if(base->type == \"integer\"){\n return true;\n\n\n }else if(base->type == \"logarithm\"){\n return false;\n\n }else if(base->type == \"nthRoot\"){\n\tnthRoot* nr = (nthRoot *) base;\n\tRational* r = new Rational(this->exponent->getNumerator(), nr->getRoot()*this->exponent->getDenominator());\n\t\/\/makes a new exponent, multiplying the denominator by the root, allowing the root to be simplified to one\n\tthis->exponent = r;\n\tnr->setRoot(1);\n\treturn false;\n\n }else if(base->type == \"pi\"){\n return false;\n\n }else if(base->type == \"rational\"){\n Rational* r = (Rational *) base;\n if (r->geteNumerator()->type == \"integer\" && r->geteDenominator()->type == \"integer\") {\n Exponential* nu = new Exponential(r->geteNumerator(), this->exponent);\n r->setNumerator(nu);\n Exponential* de = new Exponential(r->geteDenominator(), this->exponent);\n r->setDenominator(de);\n }\n\n }else{\n cout << \"type not recognized\" << endl;\n }\n return false;\n}\n\nvoid Exponential::exponentiate(){\n\tInteger* one = new Integer(1);\n Rational* oneRat = new Rational(1, 1);\n\tif (this->base->type == \"rational\") {\n\t\tRational* ratBase = (Rational *) this->base;\n\t\tExponential* numAsExponential = new Exponential ((ratBase->geteNumerator()), (this->exponent)); \/\/no matching constructor for exponential\n\t\tExponential* denAsExponential = new Exponential ((ratBase->geteDenominator()), (this->exponent)); \/\/same error\n\t\tRational* newRatBase = new Rational(numAsExponential, denAsExponential);\n\t\tthis->base = newRatBase;\n\t\tthis->exponent = oneRat;\n\t}\n\telse {\n\n if (this->exponent->getNumerator()==0) {\n \n this->exponent=oneRat;\n this->base=one;\n\n }\n bool toFlip = false;\n if (exnu->getValue()<0) {\n\t exnu->setValue(exnu->getValue()*-1);\n toFlip = true;\n \/\/handles negative exponents\n }\n Expression* constantBase = 0;\n if (base->type == \"integer\") { \/\/fixed the problem for integers but nothing else\n Integer *a = (Integer *)base;\n constantBase = new Integer(a->getValue());\n }\n\n\n while (exponent->getNumerator()>1)\n \t{\n base->multiply(constantBase);\n exponent->setNumerator(exponent->geteNumerator()->subtract(one));\n }\n if (toFlip) {\n Integer* one = new Integer(1);\n Rational* mouse = new Rational(one, base);\n \tbase = mouse;\n }\n \n\t}\n\n}\n\nExpression* Exponential::add(Expression* a){\n if(a->type == \"euler\"){\n\n }else if(a->type == \"exponential\"){\n\tExponential* ex = (Exponential *) a;\n\tif (ex->getBase()==this->base) {\n\t\tif (ex->getExponent()==this->exponent) {\n\t\t\tInteger* two = new Integer(2);\n\t\t\tthis->multiply(two);\n\t\t}\n\t}\n\n }else if(a->type == \"integer\"){\n\n }else if(a->type == \"logarithm\"){\n\n }else if(a->type == \"nthRoot\"){\n\n }else if(a->type == \"pi\"){\n\n }else if(a->type == \"rational\"){\n\n }else{\n cout << \"type not recognized\" << endl;\n }\n return this;\n}\nExpression* Exponential::subtract(Expression* a){\n if(a->type == \"euler\"){\n\n }else if(a->type == \"exponential\"){\n\tExponential* ex = (Exponential *) a;\n\tif (ex->getBase()==this->base) {\n\t\tif (ex->getExponent()==this->exponent) {\n\t\t\tInteger* zero = new Integer(0);\n\t\t\tthis->multiply(zero);\n\t\t}\n\t}\n }else if(a->type == \"integer\"){\n\n }else if(a->type == \"logarithm\"){\n\n }else if(a->type == \"nthRoot\"){\n\n }else if(a->type == \"pi\"){\n\n }else if(a->type == \"rational\"){\n\n }else{\n cout << \"type not recognized\" << endl;\n }\n return this;\n}\nExpression* Exponential::multiply(Expression* a){\n\tif(a->type == \"euler\"){\n \t\tif (this->base->type == \"euler\") {\n \t\t\tRational* oneRat = new Rational(1, 1);\n\t\t\tthis->exponent->add(oneRat);\n \t\t\n \t}\n\n }else if(a->type == \"exponential\"){\n\t\tExponential* ex = (Exponential *) a;\n\tif (this->base == ex->getBase()) {\n\t\tthis->exponent->add(ex->getExponent());\n\t}\n\n }else if(a->type == \"integer\"){\n\n }else if(a->type == \"logarithm\"){\n\n }else if(a->type == \"nthRoot\"){\n\n }else if(a->type == \"pi\"){\n \tif (this->base->type == \"pi\") {\n \t\t\tRational* oneRat = new Rational(1, 1);\n\t\t\tthis->exponent->add(oneRat);\n \t}\n\n }else if(a->type == \"rational\"){\n\tRational* r = (Rational *) a;\n\tExpression* numToSet = r->geteNumerator();\n\tnumToSet->multiply(this);\n\tr->setNumerator(numToSet);\n\treturn r;\n\n }else{\n cout << \"type not recognized\" << endl;\n }\n return this;\n}\nExpression* Exponential::divide(Expression* a){\n\tif(a->type == \"euler\"){\n\t\tif (this->base->type == \"euler\") {\n \t\t\t\tRational* oneRat = new Rational(1, 1);\n\t\t\t\tthis->exponent->subtract(oneRat);\n \t\t}\n\n }else if(a->type == \"exponential\"){\n\tExponential* ex = (Exponential *) a;\n\tif (this->base == ex->getBase()) {\n\t\tthis->exponent->subtract(ex->getExponent());\n\t}\n\n }else if(a->type == \"integer\"){\n\n }else if(a->type == \"logarithm\"){\n\n }else if(a->type == \"nthRoot\"){\n\n }else if(a->type == \"pi\"){\n \tif (this->base->type == \"pi\") {\n \t\t\t\tRational* oneRat = new Rational(1, 1);\n\t\t\t\tthis->exponent->subtract(oneRat);\n \t\t}\n\n }else if(a->type == \"rational\"){\n\tRational* r = (Rational *) a;\n\tExpression* denToSet = r->geteDenominator();\n\tdenToSet->multiply(this);\n\tr->setDenominator(denToSet);\n\treturn r;\n\n }else{\n cout << \"type not recognized\" << endl;\n }\n return this;\n}\n\nRational* Exponential::getExponent() {\n return exponent;\n}\n\nExpression* Exponential::getBase() {\n return base;\n}\n\nInteger* Exponential::getExnu() {\n\treturn exnu;\n}\n\nInteger* Exponential::getExde() {\n\treturn exde;\n}\n\nvoid Exponential::setExnu(Integer* n) {\n\texnu = n;\n}\n\nvoid Exponential::setExde(Integer* n) {\n\texde = n;\n}\n\nvoid Exponential::setExponent(Rational* e) {\n exponent = e;\n}\n\nvoid Exponential::setBase(Expression* e) {\n base = e;\n}\n\nstring Exponential::toString() {\n stringstream str;\n if(exponent->getNumerator() == 1 && exponent->getDenominator() == 1){\n str << *base;\n }\n else if(exponent->getDenominator() == 1){\n str << *base << \"^\" << *exponent->geteNumerator();\n }else{\n str << *base << \"^\" << *exponent;\n }\n return str.str();\n}\n\n\nostream& Exponential::print(std::ostream& output) const{\n Exponential *a = (Exponential *)this;\n output << a->toString();\n return output;\n}\n\n\n\nbool Exponential::canAdd(Expression* b){ \/\/use \"this\" as comparison. Solver will call someExpression.canAdd(&someOtherExpression)\n \n if (this->type == b->type && this->type != \"logarithm\") {\n if (this->type == \"nthRoot\") {\n }\n return true;\n }else if((this->type == \"integer\" && b->type == \"rational\") || (this->type == \"rational\" && b->type == \"integer\")){\n return true;\n }else if(this->type == \"multiple\" && b->type == \"multiple\"){\n MultipleExpressions *t = (MultipleExpressions *)this;\n MultipleExpressions *m = (MultipleExpressions *)b;\n if ((t->meType == \"as\" && m->meType == \"as\") || (t->meType == \"md\" && m->meType == \"md\")) {\n return true;\n }\n }else if(this->type == \"multiple\" || b->type == \"multiple\") return true;\n return false;\n}\nbool Exponential::canSubtract(Expression* b){\n if (this->type == b->type) {\n return true;\n }else if((this->type == \"integer\" && b->type == \"rational\") || (this->type == \"rational\" && b->type == \"integer\")){\n return true;\n }else if(this->type == \"multiple\" && b->type == \"multiple\"){\n MultipleExpressions *t = (MultipleExpressions *)this;\n MultipleExpressions *m = (MultipleExpressions *)b;\n if ((t->meType == \"as\" && m->meType == \"as\") || (t->meType == \"md\" && m->meType == \"md\")) {\n return true;\n }\n }else if(this->type == \"multiple\" || b->type == \"multiple\") return true;\n return false;\n}\nbool Exponential::canMultiply(Expression* b){\n if (this->type == b->type) {\n return true;\n }\n else if (this->base->type == b->type) {\n \treturn true;\n }\n else if(this->type == \"integer\" && b->type == \"rational\") return true;\n else if(this->type == \"rational\" && b->type == \"integer\") return true;\n else if(this->type == \"multiple\" && b->type == \"multiple\"){\n MultipleExpressions *t = (MultipleExpressions *)this;\n MultipleExpressions *m = (MultipleExpressions *)b;\n if ((t->meType == \"as\" && m->meType == \"as\") || (t->meType == \"md\" && m->meType == \"md\")) {\n return true;\n }\n }else if(this->type == \"multiple\" || b->type == \"multiple\") return true;\n return false;\n \n}\nbool Exponential::canDivide(Expression* b){\n if (this->type == b->type) {\n return true;\n }\n else if (this->base->type == b->type) {\n \treturn true;\n }\n else if(this->type == \"integer\"){\n if( b->type == \"rational\") return true;\n }\n else if(this->type == \"rational\" && b->type == \"integer\") return true;\n else if(this->type == \"multiple\" && b->type == \"multiple\"){\n MultipleExpressions *t = (MultipleExpressions *)this;\n MultipleExpressions *m = (MultipleExpressions *)b;\n if ((t->meType == \"as\" && m->meType == \"as\") || (t->meType == \"md\" && m->meType == \"md\")) {\n return true;\n }\n }else if(this->type == \"multiple\" || b->type == \"multiple\") return true;\n return false;\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: fprogressbar.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: rt $ $Date: 2003-05-21 08:02:21 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n\/\/ ============================================================================\n\n#ifndef SC_FPROGRESSBAR_HXX\n#define SC_FPROGRESSBAR_HXX\n\n#include \"globstr.hrc\"\n\n#ifndef SC_FTOOLS_HXX\n#include \"ftools.hxx\"\n#endif\n\nclass SfxObjectShell;\nclass ScProgress;\n\n\n\/\/ ============================================================================\n\nconst sal_Int32 SCF_INV_SEGMENT = -1;\n\n\n\/\/ ============================================================================\n\n\/** Progress bar for complex progress representation.\n @descr The progress bar contains one or more segments, each with customable\n size. Each segment is represented by a unique identifier. While showing the\n progress bar, several segments can be started simultaneously. The progress\n bar displays the sum of all started segments on screen.\n\n It is possible to create a full featured ScfProgressBar object from\n any segment. This sub progress bar works only on that parent segment, with\n the effect, that if the sub progress bar reaches 100%, the parent segment is\n filled completely.\n\n After adding segments, the progress bar has to be activated. In this step the\n total size of all segments is calculated. Therefore it is not possible to add\n more segments from here.\n\n If a sub progress bar is created from a segment, and the main progress bar\n has been started (but not the sub progress bar), it is still possible to add\n segments to the sub progress bar. It is not allowed to get the sub progress bar\n of a started segment. And it is not allowed to modify the segment containing\n a sub progress bar directly.\n\n Following a few code examples, how to use the progress bar.\n\n Example 1: Simple progress bar (see also ScfSimpleProgressBar below).\n\n ScfProgressBar aProgress( ... );\n sal_Int32 nSeg = aProgress.AddSegment( 50 ); \/\/ segment with 50 steps (1 step = 2%)\n\n aProgress.ActivateSegment( nSeg ); \/\/ start segment nSeg\n aProgress.Progress(); \/\/ 0->1; display: 2%\n aProgress.Progress( 9 ); \/\/ 1->9; display: 18%\n\n Example 2: Progress bar with 2 segments.\n\n ScfProgressBar aProgress( ... );\n sal_Int32 nSeg1 = aProgress.AddSegment( 70 ); \/\/ segment with 70 steps\n sal_Int32 nSeg2 = aProgress.AddSegment( 30 ); \/\/ segment with 30 steps\n \/\/ both segments: 100 steps (1 step = 1%)\n\n aProgress.ActivateSegment( nSeg1 ); \/\/ start first segment\n aProgress.Progress(); \/\/ 0->1, display: 1%\n aProgress.Progress( 3 ); \/\/ 1->3, display: 3%\n aProgress.ActivateSegment( nSeg2 ); \/\/ start second segment\n aProgress.Progress( 5 ); \/\/ 0->5, display: 8% (5+3 steps)\n aProgress.ActivateSegment( nSeg1 ); \/\/ continue with first segment\n aProgress.Progress(); \/\/ 3->4, display: 9% (5+4 steps)\n\n Example 3: Progress bar with 2 segments, one contains a sub progress bar.\n\n ScfProgressBar aProgress( ... );\n sal_Int32 nSeg1 = aProgress.AddSegment( 75 ); \/\/ segment with 75 steps\n sal_Int32 nSeg2 = aProgress.AddSegment( 25 ); \/\/ segment with 25 steps\n \/\/ both segments: 100 steps (1 step = 1%)\n\n aProgress.ActivateSegment( nSeg1 ); \/\/ start first segment\n aProgress.Progress(); \/\/ 0->1, display: 1%\n\n ScfProgressBar& rSubProgress = aProgress.GetSegmentProgressBar( nSeg2 );\n \/\/ sub progress bar from second segment\n sal_Int32 nSubSeg = rSubProgress.AddSegment( 5 ); \/\/ 5 steps, mapped to second segment\n \/\/ => 1 step = 5 steps in parent = 5%\n\n rSubProgress.ActivateSegment( nSubSeg ); \/\/ start the segment (auto activate parent segment)\n rSubProgress.Progress(); \/\/ 0->1 (0->5 in parent); display: 6% (1+5)\n\n \/\/ not allowed (second segment active): aProgress.Progress();\n \/\/ not allowed (first segment not empty): aProgress.GetSegmentProgressBar( nSeg1 );\n *\/\nclass ScfProgressBar : ScfNoCopy\n{\nprivate:\n \/** Contains all data of a segment of the progress bar. *\/\n struct ScfProgressSegment\n {\n typedef ::std::auto_ptr< ScfProgressBar > ScfProgressBarPtr;\n\n ScfProgressBarPtr mpProgress; \/\/\/ Pointer to sub progress bar for this segment.\n sal_uInt32 mnSize; \/\/\/ Size of this segment.\n sal_uInt32 mnPos; \/\/\/ Current position of this segment.\n\n explicit ScfProgressSegment( sal_uInt32 nSize );\n ~ScfProgressSegment();\n };\n\n typedef ::std::auto_ptr< ScProgress > ScProgressPtr;\n typedef ScfDelList< ScfProgressSegment > ScfSegmentList;\n\n ScfSegmentList maSegments; \/\/\/ List of progress segments.\n String maText; \/\/\/ UI string for system progress.\n\n ScProgressPtr mpSysProgress; \/\/\/ System progress bar.\n SfxObjectShell* mpDocShell; \/\/\/ The document shell for the progress bar.\n ScfProgressBar* mpParentProgress; \/\/\/ Parent progress bar, if this is a segment progress bar.\n ScfProgressSegment* mpParentSegment; \/\/\/ Parent segment, if this is a segment progress bar.\n ScfProgressSegment* mpCurrSegment; \/\/\/ Current segment for progress.\n\n sal_uInt32 mnTotalSize; \/\/\/ Total size of all segments.\n sal_uInt32 mnTotalPos; \/\/\/ Sum of positions of all segments.\n sal_uInt32 mnUnitSize; \/\/\/ Size between two calls of system progress.\n sal_uInt32 mnNextUnitPos; \/\/\/ Limit for next system progress call.\n bool mbInProgress; \/\/\/ true = progress bar started.\n\npublic:\n explicit ScfProgressBar( SfxObjectShell* pDocShell, const String& rText );\n explicit ScfProgressBar( SfxObjectShell* pDocShell, sal_uInt16 nResId );\n virtual ~ScfProgressBar();\n\n \/** Adds a new segment to the progress bar.\n @return the identifier of the segment. *\/\n sal_Int32 AddSegment( sal_uInt32 nSize );\n \/** Returns a complete progress bar for the specified segment.\n @descr The progress bar can be used to create sub segments inside of the\n segment. Do not delete it (done by root progress bar)!\n @return A reference to an ScfProgressBar connected to the segment. *\/\n ScfProgressBar& GetSegmentProgressBar( sal_Int32 nSegment );\n\n \/** Returns true, if any progress segment has been started. *\/\n inline bool IsStarted() const { return mbInProgress; }\n\n \/** Starts the progress bar or activates another segment. *\/\n void ActivateSegment( sal_Int32 nSegment );\n \/** Starts the progress bar (with first segment). *\/\n inline void Activate() { ActivateSegment( 0 ); }\n \/** Set current segment to the specified position. *\/\n void Progress( sal_uInt32 nPos );\n \/** Increase current segment by 1. *\/\n void Progress();\n\nprivate:\n \/** Used to create sub progress bars. *\/\n explicit ScfProgressBar(\n ScfProgressBar& rParProgress,\n ScfProgressSegment* pParSegment );\n\n \/** Initializes all members on construction. *\/\n void Init( SfxObjectShell* pDocShell );\n\n \/** Returns the segment specified by list index. *\/\n ScfProgressSegment* GetSegment( sal_Int32 nSegment ) const;\n \/** Activates progress bar and sets current segment. *\/\n void SetCurrSegment( ScfProgressSegment* pSegment );\n \/** Increases mnTotalPos and calls the system progress bar. *\/\n void IncreaseProgressBar( sal_uInt32 nDelta );\n};\n\n\n\/\/ ============================================================================\n\n\/** A simplified progress bar with only one segment. *\/\nclass ScfSimpleProgressBar\n{\nprivate:\n ScfProgressBar maProgress; \/\/\/ The used progress bar.\n\npublic:\n explicit ScfSimpleProgressBar( sal_uInt32 nSize, SfxObjectShell* pDocShell, const String& rText );\n explicit ScfSimpleProgressBar( sal_uInt32 nSize, SfxObjectShell* pDocShell, sal_uInt16 nResId );\n\n \/** Set progress bar to the specified position. *\/\n inline void Progress( sal_uInt32 nPos ) { maProgress.Progress( nPos ); }\n \/** Increase progress bar by 1. *\/\n inline void Progress() { maProgress.Progress(); }\n\nprivate:\n \/** Initializes and starts the progress bar. *\/\n void Init( sal_uInt32 nSize );\n};\n\n\n\/\/ ============================================================================\n\n\/** A simplified progress bar based on the stream position of an existing stream. *\/\nclass ScfStreamProgressBar\n{\nprivate:\n typedef ::std::auto_ptr< ScfSimpleProgressBar > ScfSimpleProgressBarPtr;\n\n ScfSimpleProgressBarPtr mpProgress; \/\/\/ The used progress bar.\n SvStream& mrStrm; \/\/\/ The used stream.\n\npublic:\n explicit ScfStreamProgressBar( SvStream& rStrm, SfxObjectShell* pDocShell, const String& rText );\n explicit ScfStreamProgressBar( SvStream& rStrm, SfxObjectShell* pDocShell, sal_uInt16 nResId = STR_LOAD_DOC );\n\n \/** Sets the progress bar to the current stream position. *\/\n void Progress();\n\nprivate:\n \/** Initializes and starts the progress bar. *\/\n void Init( SfxObjectShell* pDocShell, const String& rText );\n};\n\n\n\/\/ ============================================================================\n\n#endif\n\nINTEGRATION: CWS dr20 (1.3.320); FILE MERGED 2004\/08\/11 10:43:50 dr 1.3.320.3: #i12577# #i16277# #i24129# #i31482# #i24672# #i27407# #i30411# rework of cell table export - default row\/column formats and shared formulas 2004\/06\/17 14:58:10 dr 1.3.320.2: #i27407# handle limit of SfxProgress (ULONG_MAX\/100) 2004\/06\/15 16:40:26 dr 1.3.320.1: #i30205# Excel filter code cleanup - rowlimit changes: SCCOL\/SCROW\/SCTAB usage - type correctness: USHORT vs. sal_uInt16, ULONG\/size_t vs. sal_uInt32 - removed compiler warnings\/*************************************************************************\n *\n * $RCSfile: fprogressbar.hxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: hr $ $Date: 2004-09-08 15:43:00 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef SC_FPROGRESSBAR_HXX\n#define SC_FPROGRESSBAR_HXX\n\n#include \"globstr.hrc\"\n\n#ifndef SC_FTOOLS_HXX\n#include \"ftools.hxx\"\n#endif\n\nclass SfxObjectShell;\nclass ScProgress;\n\n\/\/ ============================================================================\n\nconst sal_Int32 SCF_INV_SEGMENT = -1;\n\n\/\/ ============================================================================\n\n\/** Progress bar for complex progress representation.\n\n The progress bar contains one or more segments, each with customable\n size. Each segment is represented by a unique identifier. While showing the\n progress bar, several segments can be started simultaneously. The progress\n bar displays the sum of all started segments on screen.\n\n It is possible to create a full featured ScfProgressBar object from\n any segment. This sub progress bar works only on that parent segment, with\n the effect, that if the sub progress bar reaches 100%, the parent segment is\n filled completely.\n\n After adding segments, the progress bar has to be activated. In this step the\n total size of all segments is calculated. Therefore it is not possible to add\n more segments from here.\n\n If a sub progress bar is created from a segment, and the main progress bar\n has been started (but not the sub progress bar), it is still possible to add\n segments to the sub progress bar. It is not allowed to get the sub progress bar\n of a started segment. And it is not allowed to modify the segment containing\n a sub progress bar directly.\n\n Following a few code examples, how to use the progress bar.\n\n Example 1: Simple progress bar (see also ScfSimpleProgressBar below).\n\n ScfProgressBar aProgress( ... );\n sal_Int32 nSeg = aProgress.AddSegment( 50 ); \/\/ segment with 50 steps (1 step = 2%)\n\n aProgress.ActivateSegment( nSeg ); \/\/ start segment nSeg\n aProgress.Progress(); \/\/ 0->1; display: 2%\n aProgress.Progress( 9 ); \/\/ 1->9; display: 18%\n\n Example 2: Progress bar with 2 segments.\n\n ScfProgressBar aProgress( ... );\n sal_Int32 nSeg1 = aProgress.AddSegment( 70 ); \/\/ segment with 70 steps\n sal_Int32 nSeg2 = aProgress.AddSegment( 30 ); \/\/ segment with 30 steps\n \/\/ both segments: 100 steps (1 step = 1%)\n\n aProgress.ActivateSegment( nSeg1 ); \/\/ start first segment\n aProgress.Progress(); \/\/ 0->1, display: 1%\n aProgress.Progress( 3 ); \/\/ 1->3, display: 3%\n aProgress.ActivateSegment( nSeg2 ); \/\/ start second segment\n aProgress.Progress( 5 ); \/\/ 0->5, display: 8% (5+3 steps)\n aProgress.ActivateSegment( nSeg1 ); \/\/ continue with first segment\n aProgress.Progress(); \/\/ 3->4, display: 9% (5+4 steps)\n\n Example 3: Progress bar with 2 segments, one contains a sub progress bar.\n\n ScfProgressBar aProgress( ... );\n sal_Int32 nSeg1 = aProgress.AddSegment( 75 ); \/\/ segment with 75 steps\n sal_Int32 nSeg2 = aProgress.AddSegment( 25 ); \/\/ segment with 25 steps\n \/\/ both segments: 100 steps (1 step = 1%)\n\n aProgress.ActivateSegment( nSeg1 ); \/\/ start first segment\n aProgress.Progress(); \/\/ 0->1, display: 1%\n\n ScfProgressBar& rSubProgress = aProgress.GetSegmentProgressBar( nSeg2 );\n \/\/ sub progress bar from second segment\n sal_Int32 nSubSeg = rSubProgress.AddSegment( 5 ); \/\/ 5 steps, mapped to second segment\n \/\/ => 1 step = 5 steps in parent = 5%\n\n rSubProgress.ActivateSegment( nSubSeg ); \/\/ start the segment (auto activate parent segment)\n rSubProgress.Progress(); \/\/ 0->1 (0->5 in parent); display: 6% (1+5)\n\n \/\/ not allowed (second segment active): aProgress.Progress();\n \/\/ not allowed (first segment not empty): aProgress.GetSegmentProgressBar( nSeg1 );\n *\/\nclass ScfProgressBar : ScfNoCopy\n{\npublic:\n explicit ScfProgressBar( SfxObjectShell* pDocShell, const String& rText );\n explicit ScfProgressBar( SfxObjectShell* pDocShell, USHORT nResId );\n virtual ~ScfProgressBar();\n\n \/** Adds a new segment to the progress bar.\n @return the identifier of the segment. *\/\n sal_Int32 AddSegment( sal_uInt32 nSize );\n \/** Returns a complete progress bar for the specified segment.\n @descr The progress bar can be used to create sub segments inside of the\n segment. Do not delete it (done by root progress bar)!\n @return A reference to an ScfProgressBar connected to the segment. *\/\n ScfProgressBar& GetSegmentProgressBar( sal_Int32 nSegment );\n\n \/** Returns true, if any progress segment has been started. *\/\n inline bool IsStarted() const { return mbInProgress; }\n \/** Returns true, if the current progress segment is already full. *\/\n bool IsFull() const;\n\n \/** Starts the progress bar or activates another segment. *\/\n void ActivateSegment( sal_Int32 nSegment );\n \/** Starts the progress bar (with first segment). *\/\n inline void Activate() { ActivateSegment( 0 ); }\n \/** Set current segment to the specified position. *\/\n void Progress( sal_uInt32 nPos );\n \/** Increase current segment by 1. *\/\n void Progress();\n\nprivate:\n struct ScfProgressSegment;\n\n \/** Used to create sub progress bars. *\/\n explicit ScfProgressBar(\n ScfProgressBar& rParProgress,\n ScfProgressSegment* pParSegment );\n\n \/** Initializes all members on construction. *\/\n void Init( SfxObjectShell* pDocShell );\n\n \/** Returns the segment specified by list index. *\/\n ScfProgressSegment* GetSegment( sal_Int32 nSegment ) const;\n \/** Activates progress bar and sets current segment. *\/\n void SetCurrSegment( ScfProgressSegment* pSegment );\n \/** Increases mnTotalPos and calls the system progress bar. *\/\n void IncreaseProgressBar( sal_uInt32 nDelta );\n\nprivate:\n \/** Contains all data of a segment of the progress bar. *\/\n struct ScfProgressSegment\n {\n typedef ::std::auto_ptr< ScfProgressBar > ScfProgressBarPtr;\n\n ScfProgressBarPtr mxProgress; \/\/\/ Pointer to sub progress bar for this segment.\n sal_uInt32 mnSize; \/\/\/ Size of this segment.\n sal_uInt32 mnPos; \/\/\/ Current position of this segment.\n\n explicit ScfProgressSegment( sal_uInt32 nSize );\n ~ScfProgressSegment();\n };\n\n typedef ::std::auto_ptr< ScProgress > ScProgressPtr;\n typedef ScfDelList< ScfProgressSegment > ScfSegmentList;\n\n ScfSegmentList maSegments; \/\/\/ List of progress segments.\n String maText; \/\/\/ UI string for system progress.\n\n ScProgressPtr mxSysProgress; \/\/\/ System progress bar.\n SfxObjectShell* mpDocShell; \/\/\/ The document shell for the progress bar.\n ScfProgressBar* mpParentProgress; \/\/\/ Parent progress bar, if this is a segment progress bar.\n ScfProgressSegment* mpParentSegment; \/\/\/ Parent segment, if this is a segment progress bar.\n ScfProgressSegment* mpCurrSegment; \/\/\/ Current segment for progress.\n\n sal_uInt32 mnTotalSize; \/\/\/ Total size of all segments.\n sal_uInt32 mnTotalPos; \/\/\/ Sum of positions of all segments.\n sal_uInt32 mnUnitSize; \/\/\/ Size between two calls of system progress.\n sal_uInt32 mnNextUnitPos; \/\/\/ Limit for next system progress call.\n sal_uInt32 mnSysProgressScale; \/\/\/ Additionally scaling factor for system progress.\n bool mbInProgress; \/\/\/ true = progress bar started.\n};\n\n\/\/ ============================================================================\n\n\/** A simplified progress bar with only one segment. *\/\nclass ScfSimpleProgressBar\n{\npublic:\n explicit ScfSimpleProgressBar( sal_uInt32 nSize, SfxObjectShell* pDocShell, const String& rText );\n explicit ScfSimpleProgressBar( sal_uInt32 nSize, SfxObjectShell* pDocShell, USHORT nResId );\n\n \/** Set progress bar to the specified position. *\/\n inline void Progress( sal_uInt32 nPos ) { maProgress.Progress( nPos ); }\n \/** Increase progress bar by 1. *\/\n inline void Progress() { maProgress.Progress(); }\n\nprivate:\n \/** Initializes and starts the progress bar. *\/\n void Init( sal_uInt32 nSize );\n\nprivate:\n ScfProgressBar maProgress; \/\/\/ The used progress bar.\n};\n\n\/\/ ============================================================================\n\n\/** A simplified progress bar based on the stream position of an existing stream. *\/\nclass ScfStreamProgressBar\n{\npublic:\n explicit ScfStreamProgressBar( SvStream& rStrm, SfxObjectShell* pDocShell, const String& rText );\n explicit ScfStreamProgressBar( SvStream& rStrm, SfxObjectShell* pDocShell, USHORT nResId = STR_LOAD_DOC );\n\n \/** Sets the progress bar to the current stream position. *\/\n void Progress();\n\nprivate:\n \/** Initializes and starts the progress bar. *\/\n void Init( SfxObjectShell* pDocShell, const String& rText );\n\nprivate:\n typedef ::std::auto_ptr< ScfSimpleProgressBar > ScfSimpleProgressBarPtr;\n\n ScfSimpleProgressBarPtr mxProgress; \/\/\/ The used progress bar.\n SvStream& mrStrm; \/\/\/ The used stream.\n};\n\n\/\/ ============================================================================\n\n#endif\n\n<|endoftext|>"} {"text":"#ifndef _LIBYAML_HPP_\n#define _LIBYAML_HPP_\n\n#include \n#include \n\n#include \n\n\/\/-----------------------------------------------------------------------------\n\/\/-----------------------------------------------------------------------------\n\/\/-----------------------------------------------------------------------------\n\nnamespace c4 {\nnamespace yml {\n\n\nnamespace detail {\nclass Event;\n} \/\/ detail\n\nclass detail::Event\n{\npublic:\n yaml_event_t m_event;\npublic:\n Event() {}\n ~Event()\n {\n yaml_event_delete(&m_event);\n }\n};\n\n\/\/-----------------------------------------------------------------------------\n\/\/-----------------------------------------------------------------------------\n\/\/-----------------------------------------------------------------------------\n\nclass LibyamlParser\n{\npublic:\n\n yaml_parser_t m_parser;\n\n const char * m_input;\n size_t m_length;\n\n NodeData * m_load_root;\n\nprivate:\n\n cspan get_scalar_val(detail::Event const &ev) const\n {\n \/\/ the memory in data.scalar is allocated anew, so don't do this\n \/\/auto const& scalar = e.m_event.data.scalar;\n \/\/cspan val((const char*)scalar.value, scalar.length);\n \/\/return val;\n \/\/ ... but the event tells us where in the string the value is\n auto const& e = ev.m_event;\n size_t len = e.end_mark.index - e.start_mark.index;\n cspan val(m_input + e.start_mark.index, len);\n return val;\n }\n\npublic:\n\n LibyamlParser()\n {\n memset(this, 0, sizeof(*this));\n yaml_parser_initialize(&m_parser);\n }\n\n ~LibyamlParser()\n {\n yaml_parser_delete(&m_parser);\n memset(&m_parser, 0, sizeof(decltype(m_parser)));\n }\n\n template< size_t N >\n void parse(\/*Tree *s, *\/const char (&input)[N])\n {\n parse(\/*s, *\/&input[0], N-1);\n }\n\n void parse(\/*Tree *s, *\/const cspan sp)\n {\n parse(\/*s, *\/sp.str, sp.len);\n }\n void parse(\/*Tree *s, *\/const char* input, size_t length)\n {\n m_input = input;\n m_length = length;\n yaml_parser_set_input_string(&m_parser, (const unsigned char*)input, length);\n _do_parse(\/*s*\/);\n }\n\n void _do_parse(\/*Tree *s*\/)\n {\n bool done = false;\n \/\/bool doc_had_scalars = false;\n \/\/cspan prev_scalar;\n while( ! done)\n {\n detail::Event ev;\n if( ! yaml_parser_parse(&m_parser, &ev.m_event))\n {\n _handle_error();\n break;\n }\n\n#define _c4_handle_case(_ev) \\\ncase YAML_ ## _ev ## _EVENT: \\\n printf(#_ev \" val=%.*s\\n\", \\\n \/*(int)prev_scalar.len, prev_scalar.str,*\/ \\\n (int)val.len, val.str);\n\n cspan val = get_scalar_val(ev);\n switch(ev.m_event.type)\n {\n\n _c4_handle_case(MAPPING_START)\n \/*if(( ! s->stack_top_is_type(DOC) || doc_had_scalars)\n &&\n ( ! m_load_root))\n {\n C4_ASSERT( ! prev_scalar.empty());\n s->begin_map(prev_scalar, s->top_last());\n prev_scalar.clear();\n }\n *\/\n break;\n _c4_handle_case(MAPPING_END)\n \/*if( ! s->stack_top_is_type(DOC) && ! m_load_root)\n {\n s->end_map();\n }*\/\n break;\n\n _c4_handle_case(SEQUENCE_START)\n \/\/s->begin_seq(prev_scalar, s->top_last());\n break;\n _c4_handle_case(SEQUENCE_END)\n \/\/s->end_seq();\n break;\n\n _c4_handle_case(SCALAR)\n \/*if(s->stack_top_is_type(SEQ))\n {\n s->add_val({}, val, s->top_last());\n prev_scalar.clear();\n }\n else\n {\n if( ! prev_scalar.empty())\n {\n s->add_val(prev_scalar, val, s->top_last());\n prev_scalar.clear();\n }\n else\n {\n prev_scalar = val;\n }\n }\n doc_had_scalars = true;\n *\/\n break;\n\n _c4_handle_case(DOCUMENT_START)\n \/*if( ! m_load_root)\n {\n s->begin_doc(s->top_last());\n doc_had_scalars = false;\n }*\/\n break;\n _c4_handle_case(DOCUMENT_END)\n \/*if( ! m_load_root)\n {\n s->end_doc();\n }*\/\n break;\n\n _c4_handle_case(STREAM_START)\n \/\/s->begin_stream();\n break;\n _c4_handle_case(STREAM_END)\n \/\/s->end_stream();\n done = true;\n break;\n\n _c4_handle_case(ALIAS)\n \/\/C4_ASSERT(false && \"YAML_ALIAS_EVENT not implemented\");\n break;\n#undef _c4_handle_case\n default:\n break;\n };\n }\n }\n\n void _handle_error()\n {\n Location problem_loc, context_loc;\n if(m_parser.problem)\n {\n auto const& m = m_parser.problem_mark;\n problem_loc = Location(m_parser.problem, m.index, m.line+1, m.column+1);\n }\n if(m_parser.context)\n {\n auto const& m = m_parser.context_mark;\n context_loc = Location(m_parser.context, m.index, m.line+1, m.column+1);\n }\n\n switch(m_parser.error)\n {\n\n case YAML_MEMORY_ERROR:\n error(\"Memory error: Not enough memory for parsing\");\n break;\n\n case YAML_READER_ERROR:\n if (m_parser.problem_value != -1)\n {\n char buf[32];\n int ret = snprintf(buf, sizeof(buf), \"Reader error: #%X\", m_parser.problem_value);\n error(buf, ret, &problem_loc);\n }\n else\n {\n error(\"Reader error\", &problem_loc);\n }\n break;\n\n case YAML_SCANNER_ERROR:\n error(\"Scanner error\", &context_loc, &problem_loc);\n break;\n\n case YAML_PARSER_ERROR:\n error(\"Parser error\", &context_loc, &problem_loc);\n break;\n\n default:\n \/* Couldn't happen. *\/\n error(\"Internal error\");\n break;\n };\n }\n\n static void error(const char* msg, size_t length, Location *loc1 = nullptr, Location *loc2 = nullptr)\n {\n fprintf(stderr, \"%.*s\\n\", (int)length, msg);\n if(loc1 && *loc1)\n {\n fprintf(stderr, \" : %s at %zd:%zd (offset %zd)\\n\", loc1->name, loc1->line, loc1->col, loc1->offset);\n }\n if(loc2 && *loc2)\n {\n fprintf(stderr, \" : %s at %zd:%zd (offset %zd)\\n\", loc2->name, loc1->line, loc2->col, loc2->offset);\n }\n throw std::runtime_error({msg, length});\n }\n template< size_t N >\n static void error(char const (&msg)[N], Location *loc1 = nullptr, Location *loc2 = nullptr)\n {\n error(&msg[0], N-1, loc1, loc2);\n }\n\n};\n\n} \/\/ namespace yml\n} \/\/ namespace c4\n\n#endif \/\/ _LIBYAML_HPP_\nreduce test verbosity#ifndef _LIBYAML_HPP_\n#define _LIBYAML_HPP_\n\n#include \n#include \n\n#include \n\n\/\/-----------------------------------------------------------------------------\n\/\/-----------------------------------------------------------------------------\n\/\/-----------------------------------------------------------------------------\n\nnamespace c4 {\nnamespace yml {\n\n\nnamespace detail {\nclass Event;\n} \/\/ detail\n\nclass detail::Event\n{\npublic:\n yaml_event_t m_event;\npublic:\n Event() {}\n ~Event()\n {\n yaml_event_delete(&m_event);\n }\n};\n\n\/\/-----------------------------------------------------------------------------\n\/\/-----------------------------------------------------------------------------\n\/\/-----------------------------------------------------------------------------\n\nclass LibyamlParser\n{\npublic:\n\n yaml_parser_t m_parser;\n\n const char * m_input;\n size_t m_length;\n\n NodeData * m_load_root;\n\nprivate:\n\n cspan get_scalar_val(detail::Event const &ev) const\n {\n \/\/ the memory in data.scalar is allocated anew, so don't do this\n \/\/auto const& scalar = e.m_event.data.scalar;\n \/\/cspan val((const char*)scalar.value, scalar.length);\n \/\/return val;\n \/\/ ... but the event tells us where in the string the value is\n auto const& e = ev.m_event;\n size_t len = e.end_mark.index - e.start_mark.index;\n cspan val(m_input + e.start_mark.index, len);\n return val;\n }\n\npublic:\n\n LibyamlParser()\n {\n memset(this, 0, sizeof(*this));\n yaml_parser_initialize(&m_parser);\n }\n\n ~LibyamlParser()\n {\n yaml_parser_delete(&m_parser);\n memset(&m_parser, 0, sizeof(decltype(m_parser)));\n }\n\n template< size_t N >\n void parse(\/*Tree *s, *\/const char (&input)[N])\n {\n parse(\/*s, *\/&input[0], N-1);\n }\n\n void parse(\/*Tree *s, *\/const cspan sp)\n {\n parse(\/*s, *\/sp.str, sp.len);\n }\n void parse(\/*Tree *s, *\/const char* input, size_t length)\n {\n m_input = input;\n m_length = length;\n yaml_parser_set_input_string(&m_parser, (const unsigned char*)input, length);\n _do_parse(\/*s*\/);\n }\n\n void _do_parse(\/*Tree *s*\/)\n {\n bool done = false;\n \/\/bool doc_had_scalars = false;\n \/\/cspan prev_scalar;\n while( ! done)\n {\n detail::Event ev;\n if( ! yaml_parser_parse(&m_parser, &ev.m_event))\n {\n _handle_error();\n break;\n }\n\n#ifdef RYML_DBG\n#define _c4_handle_case(_ev) \\\ncase YAML_ ## _ev ## _EVENT: \\\n printf(#_ev \" val=%.*s\\n\", \\\n \/*(int)prev_scalar.len, prev_scalar.str,*\/ \\\n (int)val.len, val.str);\n#else\n#define _c4_handle_case(_ev) \\\ncase YAML_ ## _ev ## _EVENT: \\\n (void)val;\n#endif\n\n cspan val = get_scalar_val(ev);\n switch(ev.m_event.type)\n {\n\n _c4_handle_case(MAPPING_START)\n \/*if(( ! s->stack_top_is_type(DOC) || doc_had_scalars)\n &&\n ( ! m_load_root))\n {\n C4_ASSERT( ! prev_scalar.empty());\n s->begin_map(prev_scalar, s->top_last());\n prev_scalar.clear();\n }\n *\/\n break;\n _c4_handle_case(MAPPING_END)\n \/*if( ! s->stack_top_is_type(DOC) && ! m_load_root)\n {\n s->end_map();\n }*\/\n break;\n\n _c4_handle_case(SEQUENCE_START)\n \/\/s->begin_seq(prev_scalar, s->top_last());\n break;\n _c4_handle_case(SEQUENCE_END)\n \/\/s->end_seq();\n break;\n\n _c4_handle_case(SCALAR)\n \/*if(s->stack_top_is_type(SEQ))\n {\n s->add_val({}, val, s->top_last());\n prev_scalar.clear();\n }\n else\n {\n if( ! prev_scalar.empty())\n {\n s->add_val(prev_scalar, val, s->top_last());\n prev_scalar.clear();\n }\n else\n {\n prev_scalar = val;\n }\n }\n doc_had_scalars = true;\n *\/\n break;\n\n _c4_handle_case(DOCUMENT_START)\n \/*if( ! m_load_root)\n {\n s->begin_doc(s->top_last());\n doc_had_scalars = false;\n }*\/\n break;\n _c4_handle_case(DOCUMENT_END)\n \/*if( ! m_load_root)\n {\n s->end_doc();\n }*\/\n break;\n\n _c4_handle_case(STREAM_START)\n \/\/s->begin_stream();\n break;\n _c4_handle_case(STREAM_END)\n \/\/s->end_stream();\n done = true;\n break;\n\n _c4_handle_case(ALIAS)\n \/\/C4_ASSERT(false && \"YAML_ALIAS_EVENT not implemented\");\n break;\n#undef _c4_handle_case\n default:\n break;\n };\n }\n }\n\n void _handle_error()\n {\n Location problem_loc, context_loc;\n if(m_parser.problem)\n {\n auto const& m = m_parser.problem_mark;\n problem_loc = Location(m_parser.problem, m.index, m.line+1, m.column+1);\n }\n if(m_parser.context)\n {\n auto const& m = m_parser.context_mark;\n context_loc = Location(m_parser.context, m.index, m.line+1, m.column+1);\n }\n\n switch(m_parser.error)\n {\n\n case YAML_MEMORY_ERROR:\n error(\"Memory error: Not enough memory for parsing\");\n break;\n\n case YAML_READER_ERROR:\n if (m_parser.problem_value != -1)\n {\n char buf[32];\n int ret = snprintf(buf, sizeof(buf), \"Reader error: #%X\", m_parser.problem_value);\n error(buf, ret, &problem_loc);\n }\n else\n {\n error(\"Reader error\", &problem_loc);\n }\n break;\n\n case YAML_SCANNER_ERROR:\n error(\"Scanner error\", &context_loc, &problem_loc);\n break;\n\n case YAML_PARSER_ERROR:\n error(\"Parser error\", &context_loc, &problem_loc);\n break;\n\n default:\n \/* Couldn't happen. *\/\n error(\"Internal error\");\n break;\n };\n }\n\n static void error(const char* msg, size_t length, Location *loc1 = nullptr, Location *loc2 = nullptr)\n {\n fprintf(stderr, \"%.*s\\n\", (int)length, msg);\n if(loc1 && *loc1)\n {\n fprintf(stderr, \" : %s at %zd:%zd (offset %zd)\\n\", loc1->name, loc1->line, loc1->col, loc1->offset);\n }\n if(loc2 && *loc2)\n {\n fprintf(stderr, \" : %s at %zd:%zd (offset %zd)\\n\", loc2->name, loc1->line, loc2->col, loc2->offset);\n }\n throw std::runtime_error({msg, length});\n }\n template< size_t N >\n static void error(char const (&msg)[N], Location *loc1 = nullptr, Location *loc2 = nullptr)\n {\n error(&msg[0], N-1, loc1, loc2);\n }\n\n};\n\n} \/\/ namespace yml\n} \/\/ namespace c4\n\n#endif \/\/ _LIBYAML_HPP_\n<|endoftext|>"} {"text":"\/*\n * mf_test.cpp\n *\n * Created on: Aug 7, 2011\n * Author: gmueller\n *\/\n\n#include \"gadget\/MagneticField.hpp\"\n#include \"gadget\/SmoothParticle.hpp\"\n\n#include \n#include \n#include \n\nclass AbstractTest {\nprotected:\n\tstd::vector particles;\n\tstd::auto_ptr dmf;\n\tstd::auto_ptr smf;\n\tstd::vector > positions;\npublic:\n\n\tvirtual void setup() = 0;\n\n\tvoid run() {\n\t\tfor (size_t i = 0; i < positions.size(); i++)\n\t\t\ttestPosition(positions[i].first, positions[i].second);\n\t}\n\n\tvoid testPosition(const Vector3f &position, float expected_error =\n\t\t\tstd::numeric_limits::epsilon()) {\n\t\tVector3f df = dmf->getField(position);\n\t\tVector3f sf = smf->getField(position);\n\t\tfloat error = (df - sf).length();\n\t\tstd::cout << \"Direct: \" << df << \", Sampled: \" << sf << \", Error: \"\n\t\t\t\t<< error << std::endl;\n\t\tif (error > expected_error)\n\t\t\tthrow std::runtime_error(\"unexpected deviation!\");\n\t}\n\n\tvoid addPosition(const Vector3f &position, float expected_error =\n\t\t\tstd::numeric_limits::epsilon()) {\n\t\tpositions.push_back(std::make_pair(position, expected_error));\n\t}\n};\n\nclass SimpleTest: public AbstractTest {\npublic:\n\n\tvoid setup() {\n\t\tparticles.resize(1);\n\t\tparticles[0].bfield = Vector3f(0, 1, 0);\n\t\tparticles[0].position = Vector3f(120000, 120000, 120000);\n\t\tparticles[0].smoothingLength = 10000;\n\t\tparticles[0].mass = 1;\n\n\t\tSmoothParticleHelper::updateRho(particles);\n\n\t\tVector3f origin(100000, 100000, 100000);\n\t\tfloat size(40000);\n\n\t\tdmf.reset(new DirectMagneticField(origin, size));\n\t\tdmf->init(100);\n\t\tdmf->load(particles);\n\n\t\tsmf.reset(new SampledMagneticField(origin, size));\n\t\tsmf->init(500);\n\t\tsmf->load(particles);\n\n\t\taddPosition(Vector3f(120000, 120000, 120000));\n\t\taddPosition(Vector3f(120500, 120500, 120500));\n\t\taddPosition(Vector3f(120550, 120550, 120550), 0.01);\n\t}\n\n};\n\nint main() {\n\tSimpleTest stest;\n\tstest.setup();\n\tstest.run();\n}\nimprove mf_test, use coma radial profile\/*\n * mf_test.cpp\n *\n * Created on: Aug 7, 2011\n * Author: gmueller\n *\/\n\n#include \"gadget\/MagneticField.hpp\"\n#include \"gadget\/SmoothParticle.hpp\"\n\n#include \n#include \n#include \n\nclass AbstractTest {\npublic:\n\tstruct TestPoint {\n\t\tTestPoint() :\n\t\t\t\tposition(Vector3f(0, 0, 0)), value(Vector3f(0, 0, 0)), error(\n\t\t\t\t\t\tstd::numeric_limits::epsilon()) {\n\n\t\t}\n\t\tTestPoint(Vector3f position, Vector3f value, float error =\n\t\t\t\tstd::numeric_limits::epsilon()) :\n\t\t\t\tposition(position), value(value), error(error) {\n\n\t\t}\n\t\tVector3f position;\n\t\tVector3f value;\n\t\tfloat error;\n\t};\nprotected:\n\tstd::vector particles;\n\tstd::auto_ptr dmf;\n\tstd::auto_ptr smf;\n\tstd::vector testPoints;\npublic:\n\n\tvirtual void setup() = 0;\n\n\tvoid runTestPoints() {\n\t\tstd::cout << \">> test points: \" << testPoints.size() << std::endl;\n\t\tfor (size_t i = 0; i < testPoints.size(); i++)\n\t\t\ttest(testPoints[i]);\n\t\tstd::cout << \">> done\" << std::endl;\n\t}\n\n\tvoid runSweep(const Vector3f &from, const Vector3f &to, float stepSize,\n\t\t\tfloat allowedError) {\n\t\tstd::cout << \">> Sweep from \" << from << \" to \" << to << \", Step: \"\n\t\t\t\t<< stepSize << std::endl;\n\t\tfloat length = (from - to).length();\n\t\tsize_t steps = length \/ stepSize;\n\t\tVector3f step = (to - from) * stepSize \/ length;\n\t\tVector3f position = from;\n\t\tfloat minError = std::numeric_limits::max();\n\t\tfloat maxError = std::numeric_limits::min();\n\t\tfor (size_t i = 0; i < steps; i++) {\n\t\t\tposition += step;\n\t\t\tVector3f df = dmf->getField(position);\n\t\t\tVector3f sf = smf->getField(position);\n\t\t\tstd::cout << \" -> \" << df.length() << std::endl;\n\t\t\tfloat error = (df - sf).length();\n\t\t\tminError = std::min(error, minError);\n\t\t\tmaxError = std::max(error, maxError);\n\t\t\tif (error > allowedError)\n\t\t\t\tthrow std::runtime_error(\"unexpected deviation!\");\n\t\t}\n\t\tstd::cout << \" min error: \" << minError << std::endl;\n\t\tstd::cout << \" max error: \" << maxError << std::endl;\n\t\tstd::cout << \" average total: \"\n\t\t\t\t<< dmf->getStatistics().getAverageTotal() << std::endl;\n\t\tstd::cout << \" average actual: \"\n\t\t\t\t<< dmf->getStatistics().getAverageActual() << std::endl;\n\t\tstd::cout << \">> done\" << std::endl;\n\t}\n\n\tvoid test(const TestPoint &testPoint) {\n\t\tstd::cout << \" TestPoint: \" << testPoint.position << \" -> \"\n\t\t\t\t<< testPoint.value << \", +- \" << testPoint.error << std::endl;\n\n\t\tVector3f df = dmf->getField(testPoint.position);\n\t\tfloat dfError = (df - testPoint.value).length();\n\t\tstd::cout << \" - Direct: \" << df << \", Error: \" << dfError\n\t\t\t\t<< std::endl;\n\n\t\tVector3f sf = smf->getField(testPoint.position);\n\t\tfloat sfError = (sf - testPoint.value).length();\n\t\tstd::cout << \" - Samples: \" << sf << \", Error: \" << sfError\n\t\t\t\t<< std::endl;\n\n\t\tif (dfError > testPoint.error || sfError > testPoint.error)\n\t\t\tthrow std::runtime_error(\"unexpected deviation!\");\n\t}\n\n\tvoid getAverageFieldOnSphere(const Vector3f ¢er, float radius,\n\t\t\tfloat &avgDirect, float &avgSampled) {\n\t\tavgDirect = 0;\n\t\tavgSampled = 0;\n\t\tsize_t count = 0;\n\t\tfloat phi = 0;\n\t\twhile (phi < 360) {\n\t\t\tfloat theta = -90;\n\t\t\twhile (theta <= 90) {\n\t\t\t\ttheta += 10;\n\t\t\t\tVector3f position = center;\n\t\t\t\ttry {\n\t\t\t\t\tposition.x += radius * sin(phi) * cos(theta);\n\t\t\t\t\tposition.y += radius * cos(phi) * cos(theta);\n\t\t\t\t\tposition.z += radius * sin(theta);\n\t\t\t\t\tavgDirect += dmf->getField(position).length();\n\t\t\t\t\tavgSampled += smf->getField(position).length();\n\t\t\t\t\tcount++;\n\t\t\t\t} catch (...) {\n\n\t\t\t\t}\n\t\t\t}\n\t\t\tphi += 10;\n\t\t}\n\n\t\tavgDirect \/= count;\n\t\tavgSampled \/= count;\n\t}\n\n\tvoid runHaloTest(const Vector3f ¢er, float radius) {\n\t\tstd::cout << \">> Halo Test around \" << center << \", R_v: \" << radius\n\t\t\t\t<< std::endl;\n\t\tstd::cout << \" - direct sampled\" << std::endl;\n\t\tfor (size_t i = 0; i < 51; i++) {\n\t\t\tfloat r = (radius \/ 50) * i;\n\t\t\tfloat avgDirect, avgSampled;\n\t\t\tgetAverageFieldOnSphere(center, r, avgDirect, avgSampled);\n\t\t\tstd::cout << r\/radius << \" \" << avgDirect << \" \" << avgSampled\n\t\t\t\t\t<< std::endl;\n\t\t}\n\t}\n};\n\nclass SimpleTest: public AbstractTest {\npublic:\n\n\tvoid setup() {\n\t\tparticles.resize(1);\n\t\tparticles[0].bfield = Vector3f(0, 1, 0);\n\t\tparticles[0].position = Vector3f(120000, 120000, 120000);\n\t\tparticles[0].smoothingLength = 10000;\n\t\tparticles[0].mass = 1;\n\n\t\tSmoothParticleHelper::updateRho(particles);\n\n\t\tVector3f origin(100000, 100000, 100000);\n\t\tfloat size(40000);\n\n\t\tdmf.reset(new DirectMagneticField(origin, size));\n\t\tdmf->init(100);\n\t\tdmf->load(particles);\n\n\t\tsmf.reset(new SampledMagneticField(origin, size));\n\t\tsmf->init(500);\n\t\tsmf->load(particles);\n\n\t\ttestPoints.push_back(\n\t\t\t\tTestPoint(Vector3f(120000, 120000, 120000), Vector3f(0, 1, 0)));\n\t\ttestPoints.push_back(\n\t\t\t\tTestPoint(Vector3f(120500, 120500, 120500),\n\t\t\t\t\t\tVector3f(0, 0.958897, 0)));\n\t\ttestPoints.push_back(\n\t\t\t\tTestPoint(Vector3f(120550, 120550, 120550),\n\t\t\t\t\t\tVector3f(0, 0.950737, 0), 0.01));\n\t}\n\n};\n\n\/\/ Coma\n\/\/ 11 411121 214459 7.570E+14 6.634E+14 1885.23 119.8023 190.8159 129.1431 -361.72 566.41 -315.91 949.39\nVector3f ComaPosition(119717, 221164, 133061);\n\nclass HaloTest: public AbstractTest {\npublic:\n\n\tvoid setup() {\n\t\tSmoothParticleHelper::read(\"test\/mhd_z-5-11-6.raw\", particles);\n\n\t\tVector3f origin(99000, 219000, 119000);\n\t\tfloat size(22000);\n\n\t\tdmf.reset(new DirectMagneticField(origin, size));\n\t\tdmf->init(50);\n\t\tdmf->load(particles);\n\n\t\tsmf.reset(new SampledMagneticField(origin, size));\n\t\tsmf->init(100);\n\t\tsmf->load(particles);\n\n\t\ttestPoints.push_back(\n\t\t\t\tTestPoint(ComaPosition,\n\t\t\t\t\t\tVector3f(-1.60984e-09, -3.48952e-10, 1.00858e-09), 1));\n\t}\n\n};\n\nint main() {\n\tSimpleTest stest;\n\tstest.setup();\n\tstest.runTestPoints();\n\tstest.runSweep(Vector3f(120000, 120000, 120000),\n\t\t\tVector3f(120000, 110000, 120000), 10, 0.01);\n\n\tHaloTest htest;\n\thtest.setup();\n\thtest.runTestPoints();\n\thtest.runSweep(ComaPosition, ComaPosition + Vector3f(-1000, 1000, 500), 10,\n\t\t\t0.01);\n\thtest.runHaloTest(ComaPosition, 2700);\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2015 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"mandoline\/tab\/web_view_impl.h\"\n\n#include \"components\/view_manager\/public\/cpp\/view.h\"\n#include \"components\/view_manager\/public\/cpp\/view_manager.h\"\n#include \"mandoline\/tab\/frame.h\"\n#include \"mandoline\/tab\/frame_connection.h\"\n#include \"mandoline\/tab\/frame_tree.h\"\n#include \"mojo\/application\/public\/cpp\/application_impl.h\"\n#include \"mojo\/converters\/geometry\/geometry_type_converters.h\"\n\n\/\/ TODO(beng): remove once these classes are in the web_view namespace.\nusing mandoline::FrameTreeClient;\nusing mandoline::FrameConnection;\n\nnamespace web_view {\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ WebViewImpl, public:\n\nWebViewImpl::WebViewImpl(mojo::ApplicationImpl* app,\n mojom::WebViewClientPtr client,\n mojo::InterfaceRequest request)\n : app_(app),\n client_(client.Pass()),\n binding_(this, request.Pass()),\n content_(nullptr),\n view_manager_client_factory_(app->shell(), this) {\n}\n\nWebViewImpl::~WebViewImpl() {}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ WebViewImpl, WebView implementation:\n\nvoid WebViewImpl::LoadRequest(mojo::URLRequestPtr request) {\n if (!content_) {\n \/\/ We haven't been embedded yet, store the request for when we are.\n pending_request_ = request.Pass();\n return;\n }\n scoped_ptr frame_connection(new FrameConnection);\n mojo::ViewManagerClientPtr view_manager_client;\n frame_connection->Init(app_, request.Pass(), &view_manager_client);\n FrameTreeClient* frame_tree_client = frame_connection->frame_tree_client();\n frame_tree_.reset(new FrameTree(content_, this, frame_tree_client,\n frame_connection.Pass()));\n content_->Embed(view_manager_client.Pass());\n}\n\nvoid WebViewImpl::GetViewManagerClient(\n mojo::InterfaceRequest view_manager_client) {\n view_manager_client_factory_.Create(nullptr, view_manager_client.Pass());\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ WebViewImpl, mojo::ViewManagerDelegate implementation:\n\nvoid WebViewImpl::OnEmbed(mojo::View* root) {\n root->view_manager()->SetEmbedRoot();\n root->AddObserver(this);\n content_ = root->view_manager()->CreateView();\n root->AddChild(content_);\n content_->SetVisible(true);\n content_->AddObserver(this);\n\n if (!pending_request_.is_null())\n LoadRequest(pending_request_.Pass());\n}\n\nvoid WebViewImpl::OnEmbedForDescendant(mojo::View* view,\n mojo::URLRequestPtr request,\n mojo::ViewManagerClientPtr* client) {\n \/\/ TODO(sky): move this to Frame\/FrameTree.\n Frame* frame = Frame::FindFirstFrameAncestor(view);\n if (!frame || !frame->HasAncestor(frame_tree_->root())) {\n \/\/ TODO(sky): add requestor url so that we can return false if it's not\n \/\/ an app we expect.\n scoped_ptr connection =\n app_->ConnectToApplication(request.Pass());\n connection->ConnectToService(client);\n return;\n }\n\n scoped_ptr frame_connection(new FrameConnection);\n frame_connection->Init(app_, request.Pass(), client);\n FrameTreeClient* frame_tree_client = frame_connection->frame_tree_client();\n frame_tree_->CreateOrReplaceFrame(frame, view, frame_tree_client,\n frame_connection.Pass());\n}\n\nvoid WebViewImpl::OnViewManagerDestroyed(mojo::ViewManager* view_manager) {\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ WebViewImpl, mojo::ViewObserver implementation:\n\nvoid WebViewImpl::OnViewBoundsChanged(mojo::View* view,\n const mojo::Rect& old_bounds,\n const mojo::Rect& new_bounds) {\n if (view != content_) {\n mojo::Rect rect;\n rect.width = new_bounds.width;\n rect.height = new_bounds.height;\n content_->SetBounds(rect);\n }\n}\n\nvoid WebViewImpl::OnViewDestroyed(mojo::View* view) {\n \/\/ |FrameTree| cannot outlive the content view.\n if (view == content_)\n frame_tree_.reset();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ WebViewImpl, mandoline::FrameTreeDelegate implementation:\n\nbool WebViewImpl::CanPostMessageEventToFrame(const Frame* source,\n const Frame* target,\n HTMLMessageEvent* event) {\n return true;\n}\n\nvoid WebViewImpl::LoadingStateChanged(bool loading) {\n client_->LoadingStateChanged(loading);\n}\n\nvoid WebViewImpl::ProgressChanged(double progress) {\n client_->ProgressChanged(progress);\n}\n\nvoid WebViewImpl::RequestNavigate(Frame* source,\n mandoline::NavigationTargetType target_type,\n Frame* target_frame,\n mojo::URLRequestPtr request) {\n \/\/ TODO: this needs security checks.\n if (target_type == mandoline::NAVIGATION_TARGET_TYPE_EXISTING_FRAME) {\n if (target_frame && target_frame != frame_tree_->root() &&\n target_frame->view()) {\n NavigateExistingFrame(target_frame, request.Pass());\n return;\n }\n DVLOG(1) << \"RequestNavigate() targeted existing frame that doesn't exist.\";\n return;\n }\n client_->TopLevelNavigate(request.Pass());\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ WebViewImpl, private:\n\nvoid WebViewImpl::NavigateExistingFrame(Frame* frame,\n mojo::URLRequestPtr request) {\n scoped_ptr frame_connection(new FrameConnection);\n mojo::ViewManagerClientPtr view_manager_client;\n frame_connection->Init(app_, request.Pass(), &view_manager_client);\n frame->view()->Embed(view_manager_client.Pass());\n FrameTreeClient* frame_tree_client = frame_connection->frame_tree_client();\n frame_tree_->CreateOrReplaceFrame(frame, frame->view(), frame_tree_client,\n frame_connection.Pass());\n}\n\n} \/\/ namespace web_view\nHonors requests to navigate in existing frame for the root\/\/ Copyright 2015 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"mandoline\/tab\/web_view_impl.h\"\n\n#include \"components\/view_manager\/public\/cpp\/view.h\"\n#include \"components\/view_manager\/public\/cpp\/view_manager.h\"\n#include \"mandoline\/tab\/frame.h\"\n#include \"mandoline\/tab\/frame_connection.h\"\n#include \"mandoline\/tab\/frame_tree.h\"\n#include \"mojo\/application\/public\/cpp\/application_impl.h\"\n#include \"mojo\/converters\/geometry\/geometry_type_converters.h\"\n\n\/\/ TODO(beng): remove once these classes are in the web_view namespace.\nusing mandoline::FrameTreeClient;\nusing mandoline::FrameConnection;\n\nnamespace web_view {\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ WebViewImpl, public:\n\nWebViewImpl::WebViewImpl(mojo::ApplicationImpl* app,\n mojom::WebViewClientPtr client,\n mojo::InterfaceRequest request)\n : app_(app),\n client_(client.Pass()),\n binding_(this, request.Pass()),\n content_(nullptr),\n view_manager_client_factory_(app->shell(), this) {\n}\n\nWebViewImpl::~WebViewImpl() {}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ WebViewImpl, WebView implementation:\n\nvoid WebViewImpl::LoadRequest(mojo::URLRequestPtr request) {\n if (!content_) {\n \/\/ We haven't been embedded yet, store the request for when we are.\n pending_request_ = request.Pass();\n return;\n }\n scoped_ptr frame_connection(new FrameConnection);\n mojo::ViewManagerClientPtr view_manager_client;\n frame_connection->Init(app_, request.Pass(), &view_manager_client);\n FrameTreeClient* frame_tree_client = frame_connection->frame_tree_client();\n frame_tree_.reset(new FrameTree(content_, this, frame_tree_client,\n frame_connection.Pass()));\n content_->Embed(view_manager_client.Pass());\n}\n\nvoid WebViewImpl::GetViewManagerClient(\n mojo::InterfaceRequest view_manager_client) {\n view_manager_client_factory_.Create(nullptr, view_manager_client.Pass());\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ WebViewImpl, mojo::ViewManagerDelegate implementation:\n\nvoid WebViewImpl::OnEmbed(mojo::View* root) {\n root->view_manager()->SetEmbedRoot();\n root->AddObserver(this);\n content_ = root->view_manager()->CreateView();\n root->AddChild(content_);\n content_->SetVisible(true);\n content_->AddObserver(this);\n\n if (!pending_request_.is_null())\n LoadRequest(pending_request_.Pass());\n}\n\nvoid WebViewImpl::OnEmbedForDescendant(mojo::View* view,\n mojo::URLRequestPtr request,\n mojo::ViewManagerClientPtr* client) {\n \/\/ TODO(sky): move this to Frame\/FrameTree.\n Frame* frame = Frame::FindFirstFrameAncestor(view);\n if (!frame || !frame->HasAncestor(frame_tree_->root())) {\n \/\/ TODO(sky): add requestor url so that we can return false if it's not\n \/\/ an app we expect.\n scoped_ptr connection =\n app_->ConnectToApplication(request.Pass());\n connection->ConnectToService(client);\n return;\n }\n\n scoped_ptr frame_connection(new FrameConnection);\n frame_connection->Init(app_, request.Pass(), client);\n FrameTreeClient* frame_tree_client = frame_connection->frame_tree_client();\n frame_tree_->CreateOrReplaceFrame(frame, view, frame_tree_client,\n frame_connection.Pass());\n}\n\nvoid WebViewImpl::OnViewManagerDestroyed(mojo::ViewManager* view_manager) {\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ WebViewImpl, mojo::ViewObserver implementation:\n\nvoid WebViewImpl::OnViewBoundsChanged(mojo::View* view,\n const mojo::Rect& old_bounds,\n const mojo::Rect& new_bounds) {\n if (view != content_) {\n mojo::Rect rect;\n rect.width = new_bounds.width;\n rect.height = new_bounds.height;\n content_->SetBounds(rect);\n }\n}\n\nvoid WebViewImpl::OnViewDestroyed(mojo::View* view) {\n \/\/ |FrameTree| cannot outlive the content view.\n if (view == content_)\n frame_tree_.reset();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ WebViewImpl, mandoline::FrameTreeDelegate implementation:\n\nbool WebViewImpl::CanPostMessageEventToFrame(const Frame* source,\n const Frame* target,\n HTMLMessageEvent* event) {\n return true;\n}\n\nvoid WebViewImpl::LoadingStateChanged(bool loading) {\n client_->LoadingStateChanged(loading);\n}\n\nvoid WebViewImpl::ProgressChanged(double progress) {\n client_->ProgressChanged(progress);\n}\n\nvoid WebViewImpl::RequestNavigate(Frame* source,\n mandoline::NavigationTargetType target_type,\n Frame* target_frame,\n mojo::URLRequestPtr request) {\n \/\/ TODO: this needs security checks.\n if (target_type == mandoline::NAVIGATION_TARGET_TYPE_EXISTING_FRAME &&\n target_frame != frame_tree_->root()) {\n if (target_frame && target_frame->view()) {\n NavigateExistingFrame(target_frame, request.Pass());\n return;\n }\n DVLOG(1) << \"RequestNavigate() targeted existing frame that doesn't exist.\";\n return;\n }\n client_->TopLevelNavigate(request.Pass());\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ WebViewImpl, private:\n\nvoid WebViewImpl::NavigateExistingFrame(Frame* frame,\n mojo::URLRequestPtr request) {\n scoped_ptr frame_connection(new FrameConnection);\n mojo::ViewManagerClientPtr view_manager_client;\n frame_connection->Init(app_, request.Pass(), &view_manager_client);\n frame->view()->Embed(view_manager_client.Pass());\n FrameTreeClient* frame_tree_client = frame_connection->frame_tree_client();\n frame_tree_->CreateOrReplaceFrame(frame, frame->view(), frame_tree_client,\n frame_connection.Pass());\n}\n\n} \/\/ namespace web_view\n<|endoftext|>"} {"text":"\/*\n * Copyright (C) 2014 Cloudius Systems, Ltd.\n *\/\n\n#include \n#include \n#include \"core\/posix.hh\"\n#include \"core\/vla.hh\"\n#include \"core\/reactor.hh\"\n#include \"core\/future-util.hh\"\n#include \"core\/stream.hh\"\n#include \"core\/circular_buffer.hh\"\n#include \"core\/align.hh\"\n#include \n#include \n#include \n#include \n#include \n#include \"ip.hh\"\n\n#include \n\n#include \n#include \n\n#include \"core\/xen\/xenstore.hh\"\n#include \"core\/xen\/evtchn.hh\"\n\n#include \"xenfront.hh\"\n#include \n\nusing namespace net;\n\nusing phys = uint64_t;\n\nclass xenfront_net_device : public net::device {\nprivate:\n bool _userspace;\n stream _rx_stream;\n net::hw_features _hw_features;\n\n std::string _device_str;\n xenstore* _xenstore = xenstore::instance();\n unsigned _otherend;\n std::string _backend;\n gntalloc *_gntalloc;\n evtchn *_evtchn;\n port *_tx_evtchn;\n port *_rx_evtchn;\n\n front_ring _tx_ring;\n front_ring _rx_ring;\n\n grant_head *_tx_refs;\n grant_head *_rx_refs;\n\n std::list> _features;\n static std::unordered_set _supported_features;\n\n ethernet_address _hw_address;\n\n port *bind_tx_evtchn();\n port *bind_rx_evtchn();\n\n future<> alloc_rx_references();\n future<> handle_tx_completions();\n future<> queue_rx_packet();\n\n void alloc_one_rx_reference(unsigned id);\n std::string path(std::string s) { return _device_str + \"\/\" + s; }\n\npublic:\n explicit xenfront_net_device(boost::program_options::variables_map opts, bool userspace);\n ~xenfront_net_device();\n virtual subscription receive(std::function (packet)> next) override;\n virtual future<> send(packet p) override;\n\n ethernet_address hw_address();\n net::hw_features hw_features();\n};\n\nstd::unordered_set\nxenfront_net_device::_supported_features = {\n \"feature-split-event-channels\",\n \"feature-rx-copy\",\n};\n\nsubscription\nxenfront_net_device::receive(std::function (packet)> next) {\n auto sub = _rx_stream.listen(std::move(next));\n keep_doing([this] {\n return _rx_evtchn->pending().then([this] {\n return queue_rx_packet();\n });\n });\n\n return std::move(sub);\n}\n\nfuture<>\nxenfront_net_device::send(packet _p) {\n\n uint32_t frag = 0;\n \/\/ There doesn't seem to be a way to tell xen, when using the userspace\n \/\/ drivers, to map a particular page. Therefore, the only alternative\n \/\/ here is to copy. All pages shared must come from the gntalloc mmap.\n \/\/\n \/\/ A better solution could be to change the packet allocation path to\n \/\/ use a pre-determined page for data.\n \/\/\n \/\/ In-kernel should be fine\n\n \/\/ FIXME: negotiate and use scatter\/gather\n _p.linearize();\n\n return _tx_ring.entries.get_index().then([this, p = std::move(_p), frag] (unsigned idx) mutable {\n\n auto req_prod = _tx_ring._sring->req_prod;\n\n auto f = p.frag(frag);\n\n auto ref = _tx_refs->new_ref(f.base, f.size);\n\n assert(!_tx_ring.entries[idx]);\n\n _tx_ring.entries[idx] = ref;\n\n auto req = &_tx_ring._sring->_ring[idx].req;\n req->gref = ref.xen_id;\n req->offset = 0;\n req->flags = {};\n if (p.offload_info().protocol != ip_protocol_num::unused) {\n req->flags.csum_blank = true;\n req->flags.data_validated = true;\n } else {\n req->flags.data_validated = true;\n }\n req->id = idx;\n req->size = f.size;\n\n _tx_ring.req_prod_pvt = idx;\n _tx_ring._sring->req_prod = req_prod + 1;\n\n _tx_ring._sring->req_event++;\n if ((frag + 1) == p.nr_frags()) {\n _tx_evtchn->notify();\n return make_ready_future<>();\n } else {\n return make_ready_future<>();\n }\n });\n\n \/\/ FIXME: Don't forget to clear all grant refs when frontend closes. Or is it automatic?\n}\n\n#define rmb() asm volatile(\"lfence\":::\"memory\");\n#define wmb() asm volatile(\"\":::\"memory\");\n\ntemplate \nfuture front_ring::entries::get_index() {\n return _available.wait().then([this] {\n auto ret = _ids.front();\n _ids.pop();\n return make_ready_future(ret);\n });\n}\n\ntemplate \nvoid front_ring::entries::free_index(unsigned id) {\n _ids.push(id);\n _available.signal();\n}\n\nfuture<> xenfront_net_device::queue_rx_packet() {\n\n auto rsp_cons = _rx_ring.rsp_cons;\n rmb();\n auto rsp_prod = _rx_ring._sring->rsp_prod;\n\n while (rsp_cons < rsp_prod) {\n auto rsp = _rx_ring[rsp_cons].rsp;\n auto& entry = _rx_ring.entries[rsp.id];\n\n rsp_cons++;\n _rx_ring.rsp_cons = rsp_cons;\n\n if (rsp.status < 0) {\n printf(\"Packet error: Handle it\\n\");\n continue;\n }\n auto rsp_size = rsp.status;\n\n packet p(static_cast(entry.page) + rsp.offset, rsp_size);\n _rx_stream.produce(std::move(p));\n\n _rx_ring._sring->rsp_event = rsp_cons + 1;\n\n rsp_prod = _rx_ring._sring->rsp_prod;\n\n _rx_refs->free_ref(entry);\n _rx_ring.entries.free_index(rsp.id);\n }\n\n \/\/ FIXME: Queue_rx maybe should not be a future then\n return make_ready_future<>();\n}\n\nvoid xenfront_net_device::alloc_one_rx_reference(unsigned index) {\n\n _rx_ring.entries[index] = _rx_refs->new_ref();\n\n \/\/ This is how the backend knows where to put data.\n auto req = &_rx_ring._sring->_ring[index].req;\n req->id = index;\n req->gref = _rx_ring.entries[index].xen_id;\n}\n\nfuture<> xenfront_net_device::alloc_rx_references() {\n return _rx_ring.entries.get_index().then([this] (unsigned i) {\n auto req_prod = _rx_ring.req_prod_pvt;\n alloc_one_rx_reference(i);\n ++req_prod;\n _rx_ring.req_prod_pvt = req_prod;\n wmb();\n _rx_ring._sring->req_prod = req_prod;\n \/* ready *\/\n _rx_evtchn->notify();\n });\n}\n\nfuture<> xenfront_net_device::handle_tx_completions() {\n auto prod = _tx_ring._sring->rsp_prod;\n rmb();\n\n for (unsigned i = _tx_ring.rsp_cons; i != prod; i++) {\n auto rsp = _tx_ring[i].rsp;\n\n if (rsp.status == 1) {\n continue;\n }\n\n if (rsp.status != 0) {\n printf(\"Packet error: Handle it\\n\");\n continue;\n }\n\n auto& entry = _tx_ring.entries[rsp.id];\n _tx_refs->free_ref(entry);\n _tx_ring.entries.free_index(rsp.id);\n }\n _tx_ring.rsp_cons = prod;\n _tx_ring._sring->rsp_event = prod + 1;\n return make_ready_future<>();\n}\n\nethernet_address xenfront_net_device::hw_address() {\n return _hw_address;\n}\n\nnet::hw_features xenfront_net_device::hw_features() {\n return _hw_features;\n}\n\nport *xenfront_net_device::bind_tx_evtchn() {\n return _evtchn->bind();\n}\n\nport *xenfront_net_device::bind_rx_evtchn() {\n\n auto split = _xenstore->read(_backend + \"\/feature-split-event-channels\");\n if (split != \"\") {\n return _evtchn->bind();\n }\n return _evtchn->bind(*_tx_evtchn);\n}\n\nxenfront_net_device::xenfront_net_device(boost::program_options::variables_map opts, bool userspace)\n : _userspace(userspace)\n , _rx_stream()\n , _device_str(\"device\/vif\/\" + std::to_string(opts[\"vif\"].as()))\n , _otherend(_xenstore->read(path(\"backend-id\")))\n , _backend(_xenstore->read(path(\"backend\")))\n , _gntalloc(gntalloc::instance(_userspace, _otherend))\n , _evtchn(evtchn::instance(_userspace, _otherend))\n , _tx_evtchn(bind_tx_evtchn())\n , _rx_evtchn(bind_rx_evtchn())\n , _tx_ring(_gntalloc->alloc_ref())\n , _rx_ring(_gntalloc->alloc_ref())\n , _tx_refs(_gntalloc->alloc_ref(front_ring::nr_ents))\n , _rx_refs(_gntalloc->alloc_ref(front_ring::nr_ents))\n , _hw_address(net::parse_ethernet_address(_xenstore->read(path(\"mac\")))) {\n\n _rx_stream.started();\n\n auto all_features = _xenstore->ls(_backend);\n std::unordered_map features_nack;\n\n for (auto&& feat : all_features) {\n if (feat.compare(0, 8, \"feature-\") == 0 && !_supported_features.count(feat)) {\n features_nack[feat] = 0;\n }\n }\n\n _hw_features.rx_csum_offload = true;\n _hw_features.tx_csum_offload = true;\n\n for (auto&s : all_features) {\n auto value = _xenstore->read(_backend + \"\/\" + s);\n _features.push_back(std::make_pair(s, value));\n }\n\n {\n auto t = xenstore::xenstore_transaction();\n\n for (auto&& f: features_nack) {\n _xenstore->write(path(f.first), f.second, t);\n }\n\n _xenstore->write(path(\"event-channel-tx\"), *_tx_evtchn, t);\n _xenstore->write(path(\"event-channel-rx\"), *_rx_evtchn, t);\n _xenstore->write(path(\"tx-ring-ref\"), _tx_ring.ref, t);\n _xenstore->write(path(\"rx-ring-ref\"), _rx_ring.ref, t);\n _xenstore->write(path(\"state\"), 4, t);\n }\n\n keep_doing([this] {\n return alloc_rx_references();\n });\n keep_doing([this] () {\n return _tx_evtchn->pending().then([this] {\n handle_tx_completions();\n });\n });\n}\n\nxenfront_net_device::~xenfront_net_device() {\n\n {\n auto t = xenstore::xenstore_transaction();\n\n for (auto& f: _features) {\n _xenstore->remove(path(f.first), t);\n }\n _xenstore->remove(path(\"event-channel-tx\"), t);\n _xenstore->remove(path(\"event-channel-rx\"), t);\n _xenstore->remove(path(\"tx-ring-ref\"), t);\n _xenstore->remove(path(\"rx-ring-ref\"), t);\n _xenstore->write(path(\"state\"), 6, t);\n }\n\n _xenstore->write(path(\"state\"), 1);\n}\n\nboost::program_options::options_description\nget_xenfront_net_options_description() {\n\n boost::program_options::options_description opts(\n \"xenfront net options\");\n opts.add_options()\n (\"vif\",\n boost::program_options::value()->default_value(0),\n \"vif number to hijack\")\n ;\n return opts;\n}\n\n\nstd::unique_ptr create_xenfront_net_device(boost::program_options::variables_map opts, bool userspace) {\n auto ptr = std::make_unique(opts, userspace);\n \/\/ This assumes only one device per cpu. Will need to be fixed when\n \/\/ this assumption will no longer hold.\n dev = ptr.get();\n return std::move(ptr);\n}\nxen: fix explicitly-disabled split event channel feature\/*\n * Copyright (C) 2014 Cloudius Systems, Ltd.\n *\/\n\n#include \n#include \n#include \"core\/posix.hh\"\n#include \"core\/vla.hh\"\n#include \"core\/reactor.hh\"\n#include \"core\/future-util.hh\"\n#include \"core\/stream.hh\"\n#include \"core\/circular_buffer.hh\"\n#include \"core\/align.hh\"\n#include \n#include \n#include \n#include \n#include \n#include \"ip.hh\"\n\n#include \n\n#include \n#include \n\n#include \"core\/xen\/xenstore.hh\"\n#include \"core\/xen\/evtchn.hh\"\n\n#include \"xenfront.hh\"\n#include \n\nusing namespace net;\n\nusing phys = uint64_t;\n\nclass xenfront_net_device : public net::device {\nprivate:\n bool _userspace;\n stream _rx_stream;\n net::hw_features _hw_features;\n\n std::string _device_str;\n xenstore* _xenstore = xenstore::instance();\n unsigned _otherend;\n std::string _backend;\n gntalloc *_gntalloc;\n evtchn *_evtchn;\n port *_tx_evtchn;\n port *_rx_evtchn;\n\n front_ring _tx_ring;\n front_ring _rx_ring;\n\n grant_head *_tx_refs;\n grant_head *_rx_refs;\n\n std::list> _features;\n static std::unordered_set _supported_features;\n\n ethernet_address _hw_address;\n\n port *bind_tx_evtchn();\n port *bind_rx_evtchn();\n\n future<> alloc_rx_references();\n future<> handle_tx_completions();\n future<> queue_rx_packet();\n\n void alloc_one_rx_reference(unsigned id);\n std::string path(std::string s) { return _device_str + \"\/\" + s; }\n\npublic:\n explicit xenfront_net_device(boost::program_options::variables_map opts, bool userspace);\n ~xenfront_net_device();\n virtual subscription receive(std::function (packet)> next) override;\n virtual future<> send(packet p) override;\n\n ethernet_address hw_address();\n net::hw_features hw_features();\n};\n\nstd::unordered_set\nxenfront_net_device::_supported_features = {\n \"feature-split-event-channels\",\n \"feature-rx-copy\",\n};\n\nsubscription\nxenfront_net_device::receive(std::function (packet)> next) {\n auto sub = _rx_stream.listen(std::move(next));\n keep_doing([this] {\n return _rx_evtchn->pending().then([this] {\n return queue_rx_packet();\n });\n });\n\n return std::move(sub);\n}\n\nfuture<>\nxenfront_net_device::send(packet _p) {\n\n uint32_t frag = 0;\n \/\/ There doesn't seem to be a way to tell xen, when using the userspace\n \/\/ drivers, to map a particular page. Therefore, the only alternative\n \/\/ here is to copy. All pages shared must come from the gntalloc mmap.\n \/\/\n \/\/ A better solution could be to change the packet allocation path to\n \/\/ use a pre-determined page for data.\n \/\/\n \/\/ In-kernel should be fine\n\n \/\/ FIXME: negotiate and use scatter\/gather\n _p.linearize();\n\n return _tx_ring.entries.get_index().then([this, p = std::move(_p), frag] (unsigned idx) mutable {\n\n auto req_prod = _tx_ring._sring->req_prod;\n\n auto f = p.frag(frag);\n\n auto ref = _tx_refs->new_ref(f.base, f.size);\n\n assert(!_tx_ring.entries[idx]);\n\n _tx_ring.entries[idx] = ref;\n\n auto req = &_tx_ring._sring->_ring[idx].req;\n req->gref = ref.xen_id;\n req->offset = 0;\n req->flags = {};\n if (p.offload_info().protocol != ip_protocol_num::unused) {\n req->flags.csum_blank = true;\n req->flags.data_validated = true;\n } else {\n req->flags.data_validated = true;\n }\n req->id = idx;\n req->size = f.size;\n\n _tx_ring.req_prod_pvt = idx;\n _tx_ring._sring->req_prod = req_prod + 1;\n\n _tx_ring._sring->req_event++;\n if ((frag + 1) == p.nr_frags()) {\n _tx_evtchn->notify();\n return make_ready_future<>();\n } else {\n return make_ready_future<>();\n }\n });\n\n \/\/ FIXME: Don't forget to clear all grant refs when frontend closes. Or is it automatic?\n}\n\n#define rmb() asm volatile(\"lfence\":::\"memory\");\n#define wmb() asm volatile(\"\":::\"memory\");\n\ntemplate \nfuture front_ring::entries::get_index() {\n return _available.wait().then([this] {\n auto ret = _ids.front();\n _ids.pop();\n return make_ready_future(ret);\n });\n}\n\ntemplate \nvoid front_ring::entries::free_index(unsigned id) {\n _ids.push(id);\n _available.signal();\n}\n\nfuture<> xenfront_net_device::queue_rx_packet() {\n\n auto rsp_cons = _rx_ring.rsp_cons;\n rmb();\n auto rsp_prod = _rx_ring._sring->rsp_prod;\n\n while (rsp_cons < rsp_prod) {\n auto rsp = _rx_ring[rsp_cons].rsp;\n auto& entry = _rx_ring.entries[rsp.id];\n\n rsp_cons++;\n _rx_ring.rsp_cons = rsp_cons;\n\n if (rsp.status < 0) {\n printf(\"Packet error: Handle it\\n\");\n continue;\n }\n auto rsp_size = rsp.status;\n\n packet p(static_cast(entry.page) + rsp.offset, rsp_size);\n _rx_stream.produce(std::move(p));\n\n _rx_ring._sring->rsp_event = rsp_cons + 1;\n\n rsp_prod = _rx_ring._sring->rsp_prod;\n\n _rx_refs->free_ref(entry);\n _rx_ring.entries.free_index(rsp.id);\n }\n\n \/\/ FIXME: Queue_rx maybe should not be a future then\n return make_ready_future<>();\n}\n\nvoid xenfront_net_device::alloc_one_rx_reference(unsigned index) {\n\n _rx_ring.entries[index] = _rx_refs->new_ref();\n\n \/\/ This is how the backend knows where to put data.\n auto req = &_rx_ring._sring->_ring[index].req;\n req->id = index;\n req->gref = _rx_ring.entries[index].xen_id;\n}\n\nfuture<> xenfront_net_device::alloc_rx_references() {\n return _rx_ring.entries.get_index().then([this] (unsigned i) {\n auto req_prod = _rx_ring.req_prod_pvt;\n alloc_one_rx_reference(i);\n ++req_prod;\n _rx_ring.req_prod_pvt = req_prod;\n wmb();\n _rx_ring._sring->req_prod = req_prod;\n \/* ready *\/\n _rx_evtchn->notify();\n });\n}\n\nfuture<> xenfront_net_device::handle_tx_completions() {\n auto prod = _tx_ring._sring->rsp_prod;\n rmb();\n\n for (unsigned i = _tx_ring.rsp_cons; i != prod; i++) {\n auto rsp = _tx_ring[i].rsp;\n\n if (rsp.status == 1) {\n continue;\n }\n\n if (rsp.status != 0) {\n printf(\"Packet error: Handle it\\n\");\n continue;\n }\n\n auto& entry = _tx_ring.entries[rsp.id];\n _tx_refs->free_ref(entry);\n _tx_ring.entries.free_index(rsp.id);\n }\n _tx_ring.rsp_cons = prod;\n _tx_ring._sring->rsp_event = prod + 1;\n return make_ready_future<>();\n}\n\nethernet_address xenfront_net_device::hw_address() {\n return _hw_address;\n}\n\nnet::hw_features xenfront_net_device::hw_features() {\n return _hw_features;\n}\n\nport *xenfront_net_device::bind_tx_evtchn() {\n return _evtchn->bind();\n}\n\nport *xenfront_net_device::bind_rx_evtchn() {\n\n auto split = _xenstore->read_or_default(_backend + \"\/feature-split-event-channels\");\n if (split) {\n return _evtchn->bind();\n }\n return _evtchn->bind(*_tx_evtchn);\n}\n\nxenfront_net_device::xenfront_net_device(boost::program_options::variables_map opts, bool userspace)\n : _userspace(userspace)\n , _rx_stream()\n , _device_str(\"device\/vif\/\" + std::to_string(opts[\"vif\"].as()))\n , _otherend(_xenstore->read(path(\"backend-id\")))\n , _backend(_xenstore->read(path(\"backend\")))\n , _gntalloc(gntalloc::instance(_userspace, _otherend))\n , _evtchn(evtchn::instance(_userspace, _otherend))\n , _tx_evtchn(bind_tx_evtchn())\n , _rx_evtchn(bind_rx_evtchn())\n , _tx_ring(_gntalloc->alloc_ref())\n , _rx_ring(_gntalloc->alloc_ref())\n , _tx_refs(_gntalloc->alloc_ref(front_ring::nr_ents))\n , _rx_refs(_gntalloc->alloc_ref(front_ring::nr_ents))\n , _hw_address(net::parse_ethernet_address(_xenstore->read(path(\"mac\")))) {\n\n _rx_stream.started();\n\n auto all_features = _xenstore->ls(_backend);\n std::unordered_map features_nack;\n\n for (auto&& feat : all_features) {\n if (feat.compare(0, 8, \"feature-\") == 0 && !_supported_features.count(feat)) {\n features_nack[feat] = 0;\n }\n }\n\n _hw_features.rx_csum_offload = true;\n _hw_features.tx_csum_offload = true;\n\n for (auto&s : all_features) {\n auto value = _xenstore->read(_backend + \"\/\" + s);\n _features.push_back(std::make_pair(s, value));\n }\n\n {\n auto t = xenstore::xenstore_transaction();\n\n for (auto&& f: features_nack) {\n _xenstore->write(path(f.first), f.second, t);\n }\n\n _xenstore->write(path(\"event-channel-tx\"), *_tx_evtchn, t);\n _xenstore->write(path(\"event-channel-rx\"), *_rx_evtchn, t);\n _xenstore->write(path(\"tx-ring-ref\"), _tx_ring.ref, t);\n _xenstore->write(path(\"rx-ring-ref\"), _rx_ring.ref, t);\n _xenstore->write(path(\"state\"), 4, t);\n }\n\n keep_doing([this] {\n return alloc_rx_references();\n });\n keep_doing([this] () {\n return _tx_evtchn->pending().then([this] {\n handle_tx_completions();\n });\n });\n}\n\nxenfront_net_device::~xenfront_net_device() {\n\n {\n auto t = xenstore::xenstore_transaction();\n\n for (auto& f: _features) {\n _xenstore->remove(path(f.first), t);\n }\n _xenstore->remove(path(\"event-channel-tx\"), t);\n _xenstore->remove(path(\"event-channel-rx\"), t);\n _xenstore->remove(path(\"tx-ring-ref\"), t);\n _xenstore->remove(path(\"rx-ring-ref\"), t);\n _xenstore->write(path(\"state\"), 6, t);\n }\n\n _xenstore->write(path(\"state\"), 1);\n}\n\nboost::program_options::options_description\nget_xenfront_net_options_description() {\n\n boost::program_options::options_description opts(\n \"xenfront net options\");\n opts.add_options()\n (\"vif\",\n boost::program_options::value()->default_value(0),\n \"vif number to hijack\")\n ;\n return opts;\n}\n\n\nstd::unique_ptr create_xenfront_net_device(boost::program_options::variables_map opts, bool userspace) {\n auto ptr = std::make_unique(opts, userspace);\n \/\/ This assumes only one device per cpu. Will need to be fixed when\n \/\/ this assumption will no longer hold.\n dev = ptr.get();\n return std::move(ptr);\n}\n<|endoftext|>"} {"text":"\/*-------------netlist_gen.cpp------------------------------------------------\/\/\n*\n* netlist generator\n*\n* Purpose: The BIAS project intends to re-implement the TrueNorth architechture\n* in analog electronics. For this purpose, we will need to create a \n* simple script that will create a netlist to be read into a SPICE \n* simulator (or similar software that is compatable with the netlist \n* format. \n*\n* Notes: This could be written a little cleaner in another language, but...\n* We need to determine the appropriate analog inputs for this file\n*\n* To compile, use the following command:\n* g++ netlist_gen.cpp -std=c++11 -o genet\n*\n* PEMDAS: We will place everything on a grid. The components we need are:\n* 1. inverting amp\n* 2. summing amp\n* 3. differential amp\n* 4. sample and hold\n*\n* The grid will then be enumerated appropriately by filling the grid\n* points with integers and counting.\n* \n* Finally, this will be written out to a file. \n*\n*-----------------------------------------------------------------------------*\/\n\n#include \n#include \n#include \n#include \n\nusing namespace std;\n\n\/*----------------------------------------------------------------------------\/\/\n* STRUCTURES AND FUNCTIONS\n*-----------------------------------------------------------------------------*\/\n\nstruct resistor{\n\n double value;\n int forw, back;\n};\n\nstruct capacitor{\n\n double value;\n int forw, back;\n\n};\n\n\/\/ opamps are weird in spice. They have 4 extremities:\n\/\/ out, ground, in+, in-\nstruct opamp{\n int inp, inn, out; \n};\n\n\/\/ struct to pass output and index between functions\nstruct netlist{\n string str;\n int index;\n};\n\n\/\/ These functions will all take the current netlist and count and append the\n\/\/ appropriate variables to it. These will be used in the larger f(x)'s below\nnetlist inv_amp(netlist net);\nnetlist sum_amp(netlist net, vector connections);\nnetlist diff_amp(netlist net, int inp, int inn);\nnetlist samhold(netlist net);\n\n\/\/ These functions will take care of connections and such within the core\nnetlist neuron(netlist net);\nnetlist junction(netlist net);\nnetlist connectome(netlist net);\n\n\/\/ Quick function to write the netlist to a file\nvoid write_netlist(netlist net, ofstream &output);\n\n\/*----------------------------------------------------------------------------\/\/\n* MAIN\n*-----------------------------------------------------------------------------*\/\n\nint main(void){\n\n return 0;\n}\n\n\/*----------------------------------------------------------------------------\/\/\n* SUBROUTINES\n*-----------------------------------------------------------------------------*\/\n\n\/\/ These functions will all take the current netlist and count and append the\n\/\/ appropriate variables to it. These will be used in the larger f(x)'s below\n\nnetlist inv_amp(netlist net){\n resistor res, res_2;\n opamp oa;\n\n \/\/ Setting initial values\n res.value = res_2.value = 1000;\n\n \/\/ Setting resistors in place\n res.back = net.index;\n res.forw = net.index + 1;\n res_2.back = net.index + 1;\n res_2.forw = net.index + 2;\n\n \/\/ Setting opamp up\n oa.inp = 0;\n oa.inn = net.index + 1;\n oa.out = net.index + 2;\n\n \/\/ appending to netlist\n\n \/\/ opamp\n net.str.append(\" e\" + to_string(net.index) + \" \" + to_string(oa.out) + \" 0 \"\n + to_string(oa.inp) + \" \" + to_string(oa.inn) + \" 999k\");\n\n \/\/ R1\n net.str.append(\" r\" + to_string(res.back) + \" \" + to_string(res.forw) + \" \"\n + to_string(res.value) + \"k\");\n\n \/\/ R2\n net.str.append(\" r\" + to_string(res_2.back) + \" \" + to_string(res_2.forw) +\n \" \" + to_string(res.value) + \"k\");\n \n return net;\n}\n\n\/\/ Write out summing amp, including preceding resistors here.\n\/\/ This function is simple because we are assuming we are reading in the R vals\nnetlist sum_amp(netlist net, vector connections){\n\n opamp oa;\n resistor res;\n\n \/\/ For this function, it is assumed that all the incoming resistors are\n \/\/ of the same value\n\n for (auto &r : connections){\n r.forw = net.index;\n net.str.append(\" r\" + to_string(r.back) + \" \" + to_string(r.forw) +\n \" \" + to_string(res.value) + \"k\");\n }\n\n \/\/Setting up op amp\n oa.inp = 0;\n oa.inn = net.index;\n oa.out = net.index + 1;\n\n \/\/ setting up resistor\n res.back = net.index;\n res.forw = net.index + 1;\n res.value = connections[0].value;\n\n \/\/ appending to netlist\n\n \/\/ opamp\n net.str.append(\" e\" + to_string(net.index) + \" \" + to_string(oa.out) + \" 0 \"\n + to_string(oa.inp) + \" \" + to_string(oa.inn) + \" 999k\");\n\n \/\/ Resistor\n net.str.append(\" r\" + to_string(res.back) + \" \" + to_string(res.forw) + \" \"\n + to_string(res.value) + \"k\");\n\n\n return net;\n}\n\nnetlist diff_amp(netlist net, int inp, int inn){\n return net;\n}\n\nnetlist samhold(netlist net){\n return net;\n}\n\n\n\/\/ These functions will take care of connections and such within the core\nnetlist neuron(netlist net){\n return net;\n}\n\nnetlist junction(netlist net){\n return net;\n}\n\nnetlist connectome(netlist net){\n return net;\n}\n\n\n\/\/ Quick function to write the netlist to a file\nvoid write_netlist(netlist net, ofstream &output){\n}\n\nadded the sample and hold and differential amplifier\/*-------------netlist_gen.cpp------------------------------------------------\/\/\n*\n* netlist generator\n*\n* Purpose: The BIAS project intends to re-implement the TrueNorth architechture\n* in analog electronics. For this purpose, we will need to create a \n* simple script that will create a netlist to be read into a SPICE \n* simulator (or similar software that is compatable with the netlist \n* format. \n*\n* Notes: This could be written a little cleaner in another language, but...\n* We need to determine the appropriate analog inputs for this file\n*\n* To compile, use the following command:\n* g++ netlist_gen.cpp -std=c++11 -o genet\n*\n* PEMDAS: We will place everything on a grid. The components we need are:\n* 1. inverting amp\n* 2. summing amp\n* 3. differential amp\n* 4. sample and hold\n*\n* The grid will then be enumerated appropriately by filling the grid\n* points with integers and counting.\n* \n* Finally, this will be written out to a file. \n*\n*-----------------------------------------------------------------------------*\/\n\n#include \n#include \n#include \n#include \n\nusing namespace std;\n\n\/*----------------------------------------------------------------------------\/\/\n* STRUCTURES AND FUNCTIONS\n*-----------------------------------------------------------------------------*\/\n\nstruct resistor{\n\n double value;\n int forw, back;\n};\n\nstruct capacitor{\n\n double value;\n int forw, back;\n\n};\n\n\/\/ opamps are weird in spice. They have 4 extremities:\n\/\/ out, ground, in+, in-\nstruct opamp{\n int inp, inn, out; \n};\n\n\/\/ struct to pass output and index between functions\nstruct netlist{\n string str;\n int index;\n};\n\n\/\/ These functions will all take the current netlist and count and append the\n\/\/ appropriate variables to it. These will be used in the larger f(x)'s below\nnetlist inv_amp(netlist net);\nnetlist sum_amp(netlist net, vector connections);\nnetlist diff_amp(netlist net, resistor inrp, resistor inrn);\nnetlist samhold(netlist net);\n\n\/\/ These functions will take care of connections and such within the core\nnetlist neuron(netlist net);\nnetlist junction(netlist net);\nnetlist connectome(netlist net);\n\n\/\/ Quick function to write the netlist to a file\nvoid write_netlist(netlist net, ofstream &output);\n\n\/*----------------------------------------------------------------------------\/\/\n* MAIN\n*-----------------------------------------------------------------------------*\/\n\nint main(void){\n\n return 0;\n}\n\n\/*----------------------------------------------------------------------------\/\/\n* SUBROUTINES\n*-----------------------------------------------------------------------------*\/\n\n\/\/ These functions will all take the current netlist and count and append the\n\/\/ appropriate variables to it. These will be used in the larger f(x)'s below\n\nnetlist inv_amp(netlist net){\n resistor res, res_2;\n opamp oa;\n\n \/\/ Setting initial values\n res.value = res_2.value = 1000;\n\n \/\/ Setting resistors in place\n res.back = net.index;\n res.forw = net.index + 1;\n res_2.back = net.index + 1;\n res_2.forw = net.index + 2;\n\n \/\/ Setting opamp up\n oa.inp = 0;\n oa.inn = net.index + 1;\n oa.out = net.index + 2;\n\n \/\/ appending to netlist\n\n \/\/ opamp\n net.str.append(\" e\" + to_string(net.index) + \" \" + to_string(oa.out) + \" 0 \"\n + to_string(oa.inp) + \" \" + to_string(oa.inn) + \" 999k\");\n\n \/\/ R1\n net.str.append(\" r\" + to_string(res.back) + \" \" + to_string(res.forw) + \" \"\n + to_string(res.value) + \"k\");\n\n \/\/ R2\n net.str.append(\" r\" + to_string(res_2.back) + \" \" + to_string(res_2.forw) +\n \" \" + to_string(res.value) + \"k\");\n\n net.index++;\n \n return net;\n}\n\n\/\/ Write out summing amp, including preceding resistors here.\n\/\/ This function is simple because we are assuming we are reading in the R vals\nnetlist sum_amp(netlist net, vector connections){\n\n opamp oa;\n resistor res;\n\n \/\/ For this function, it is assumed that all the incoming resistors are\n \/\/ of the same value\n\n for (auto &r : connections){\n r.forw = net.index;\n net.str.append(\" r\" + to_string(r.back) + \" \" + to_string(r.forw) +\n \" \" + to_string(res.value) + \"k\");\n }\n\n \/\/Setting up op amp\n oa.inp = 0;\n oa.inn = net.index;\n oa.out = net.index + 1;\n\n \/\/ setting up resistor\n res.back = net.index;\n res.forw = net.index + 1;\n res.value = connections[0].value;\n\n \/\/ appending to netlist\n\n \/\/ opamp\n net.str.append(\" e\" + to_string(net.index) + \" \" + to_string(oa.out) + \" 0 \"\n + to_string(oa.inp) + \" \" + to_string(oa.inn) + \" 999k\");\n\n \/\/ Resistor\n net.str.append(\" r\" + to_string(res.back) + \" \" + to_string(res.forw) + \" \"\n + to_string(res.value) + \"k\");\n\n\n net.index++;\n\n return net;\n}\n\n\/\/ Because we only want the differences between the voltages, we do not need\n\/\/ to worry about different resistor values.\n\/\/ Like the summing amplifier, its easier to read in resistors than ints and\n\/\/ write them here.\nnetlist diff_amp(netlist net, resistor inrp, resistor inrn){\n\n opamp oa;\n \/\/ Note: No resistor def necessary since all resistor values are the same\n\n \/\/ First, let's write out the resistors we have coming in\n inrp.forw = net.index + 1;\n inrn.forw = net.index;\n net.str.append(\" r\" + to_string(inrp.back) + \" \" + to_string(inrp.forw) +\" \"\n + to_string(inrp.value) + \"k\");\n net.str.append(\" r\" + to_string(inrn.back) + \" \" + to_string(inrn.forw) +\" \"\n + to_string(inrn.value) + \"k\");\n\n \/\/ Now we need to create the rest of the differential amplifier circuit\n\n \/\/ r2 clone to ground\n net.str.append(\" r\" + to_string(inrp.forw) + \" \" + to_string(0) +\" \"\n + to_string(inrp.value) + \"k\");\n\n \/\/ r1 clone to out\n net.str.append(\" r\" + to_string(inrn.forw) + \" \" + to_string(net.index + 2)\n + \" \" + to_string(inrn.value) + \"k\");\n\n \/\/ opamp definitions and writing\n\n oa.inp = inrp.forw;\n oa.inn = inrn.forw;\n \/\/ Note +2 instead of +1 due to two inputs\n oa.out = net.index + 2;\n\n net.str.append(\" e\" + to_string(net.index) + \" \" + to_string(oa.out) + \" 0 \"\n + to_string(oa.inp) + \" \" + to_string(oa.inn) + \" 999k\");\n\n net.index += 2;\n\n return net;\n}\n\n\/\/ This iteration of a sample and hold circuit will not have FET switches.\n\/\/ To implement FET switches, just put on the output of oa1 for charging, and\n\/\/ another parallel to the capacitor for discarging\nnetlist samhold(netlist net){\n\n opamp oa1, oa2;\n capacitor cap;\n\n \/\/ opamp1\n oa1.inp = 0;\n oa1.inn = net.index;\n oa1.out = net.index + 1;\n\n \/\/ opamp2\n oa2.inp = 0;\n oa2.inn = net.index + 1;\n oa2.out = net.index + 2;\n\n \/\/ capacitor\n cap.back = net.index + 1;\n cap.forw = 0;\n\n \/\/appending to netlist\n \/\/ opamp\n net.str.append(\" e\"+to_string(net.index)+\" \"+to_string(oa1.out)+\" 0 \"\n + to_string(oa1.inp) + \" \" + to_string(oa1.inn) + \" 999k\");\n\n net.str.append(\" e\"+to_string(net.index+1)+\" \"+to_string(oa2.out)+\" 0 \"\n + to_string(oa2.inp) + \" \" + to_string(oa2.inn) + \" 999k\");\n\n \/\/ Resistor\n net.str.append(\" c\" + to_string(cap.back) + \" \" + to_string(cap.forw) + \" \"\n + to_string(cap.value) + \"k\");\n\n\n\n net.index += 2;\n\n return net;\n}\n\n\n\/\/ These functions will take care of connections and such within the core\nnetlist neuron(netlist net){\n return net;\n}\n\nnetlist junction(netlist net){\n return net;\n}\n\nnetlist connectome(netlist net){\n return net;\n}\n\n\n\/\/ Quick function to write the netlist to a file\nvoid write_netlist(netlist net, ofstream &output){\n}\n\n<|endoftext|>"} {"text":"\/**************************************************************************************\/\r\n\/* *\/\r\n\/* Visualization Library *\/\r\n\/* http:\/\/www.visualizationlibrary.org *\/\r\n\/* *\/\r\n\/* Copyright (c) 2005-2010, Michele Bosi *\/\r\n\/* All rights reserved. *\/\r\n\/* *\/\r\n\/* Redistribution and use in source and binary forms, with or without modification, *\/\r\n\/* are permitted provided that the following conditions are met: *\/\r\n\/* *\/\r\n\/* - Redistributions of source code must retain the above copyright notice, this *\/\r\n\/* list of conditions and the following disclaimer. *\/\r\n\/* *\/\r\n\/* - Redistributions in binary form must reproduce the above copyright notice, this *\/\r\n\/* list of conditions and the following disclaimer in the documentation and\/or *\/\r\n\/* other materials provided with the distribution. *\/\r\n\/* *\/\r\n\/* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND *\/\r\n\/* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED *\/\r\n\/* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE *\/\r\n\/* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR *\/\r\n\/* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES *\/\r\n\/* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; *\/\r\n\/* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON *\/\r\n\/* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT *\/\r\n\/* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS *\/\r\n\/* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *\/\r\n\/* *\/\r\n\/**************************************************************************************\/\r\n\r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\nusing namespace vl;\r\n\r\n\/\/-----------------------------------------------------------------------------\r\n\/\/ Portal\r\n\/\/-----------------------------------------------------------------------------\r\nbool Portal::computeNormal()\r\n{\r\n mNormal = 0;\r\n if (geometry().size() < 3)\r\n {\r\n vl::Log::error(\"Portal::computeNormal() error, no portal geometry defined.\\n\");\r\n return false;\r\n }\r\n if (!mTargetSector)\r\n {\r\n vl::Log::error(\"Portal::computeNormal() error, no sector bound to this portal.\\n\");\r\n return false;\r\n }\r\n\r\n fvec3 v0 = geometry()[0];\r\n fvec3 v1 = geometry()[1] - v0;\r\n fvec3 v2 = geometry()[2] - v0;\r\n mNormal = cross(v1,v2);\r\n\r\n return true;\r\n}\r\n\/\/-----------------------------------------------------------------------------\r\n\/\/ Sector\r\n\/\/-----------------------------------------------------------------------------\r\nAABB Sector::computeBoundingBox()\r\n{\r\n AABB aabb;\r\n for(int i=0; isize(); ++i)\r\n {\r\n actors()->at(i)->computeBounds();\r\n aabb += actors()->at(i)->boundingBox();\r\n }\r\n return aabb;\r\n}\r\n\/\/-----------------------------------------------------------------------------\r\nvoid Sector::executeCallbacks(const Camera*cam,SceneManagerPortals* psm, Portal*p)\r\n{\r\n for(unsigned i=0; ioperator()(cam,psm,this,p);\r\n}\r\n\/\/-----------------------------------------------------------------------------\r\n\/\/ SceneManagerPortals\r\n\/\/-----------------------------------------------------------------------------\r\nvoid SceneManagerPortals::initialize()\r\n{\r\n computePortalNormals();\r\n for(unsigned i=0; ivolumes().empty())\r\n vl::Log::error( vl::Say(\"Sector #%n does not have any volume!\\n\") << i );\r\n for(unsigned j=0; jportals().size(); ++j)\r\n if (!mSectors[i]->portals()[j]->targetSector())\r\n vl::Log::error( vl::Say(\"In Sector #%n Portal #%n does not have any target sector!\\n\") << i << j);\r\n }\r\n}\r\n\/\/-----------------------------------------------------------------------------\r\nvoid SceneManagerPortals::renderPortal(Portal* portal)\r\n{\r\n if (mPortalActorMap.find(portal) == mPortalActorMap.end())\r\n {\r\n const fvec4 portal_color = fvec4(1,0,0,0.25f);\r\n vl::ref portal_fx = new vl::Effect;\r\n \/*portal_fx->shader()->enable(vl::EN_DEPTH_TEST);\r\n portal_fx->shader()->gocDepthFunc()->set(vl::FU_LEQUAL);*\/\r\n portal_fx->shader()->enable(vl::EN_BLEND);\r\n portal_fx->shader()->gocLineWidth()->set(2.0f);\r\n portal_fx->shader()->gocColor()->setValue(portal_color);\r\n\r\n vl::ref portal_geom = new vl::Geometry;\r\n vl::ref vert_array = new vl::ArrayFloat3;\r\n portal_geom->setVertexArray(vert_array.get());\r\n vert_array->resize(portal->geometry().size());\r\n for(unsigned int i=0; igeometry().size(); ++i)\r\n vert_array->at(i) = portal->geometry()[i];\r\n portal_geom->drawCalls()->push_back( new vl::DrawArrays(vl::PT_LINE_LOOP, 0, (int)vert_array->size()) );\r\n#if defined(VL_OPENGL)\r\n portal_geom->drawCalls()->push_back( new vl::DrawArrays(vl::PT_POLYGON, 0, (int)vert_array->size()) );\r\n#endif\r\n mPortalActorMap[portal] = new vl::Actor(portal_geom.get(), portal_fx.get(), NULL);\r\n }\r\n}\r\n\/\/-----------------------------------------------------------------------------\r\nvoid SceneManagerPortals::extractActors(ActorCollection& list)\r\n{\r\n for(unsigned i=0; iactors()->size(); ++j)\r\n list.push_back( mSectors[i]->actors()->at(j) );\r\n}\r\n\/\/-----------------------------------------------------------------------------\r\nvoid SceneManagerPortals::extractVisibleActors(ActorCollection& list, const Camera* camera)\r\n{\r\n if (cullingEnabled())\r\n {\r\n Sector* start = computeStartingSector(camera);\r\n if (!start)\r\n extractActors(list);\r\n else\r\n {\r\n ++mVisitTick;\r\n mTempActors.clear();\r\n mFrustumStack.clear();\r\n\r\n mFrustumStack.push_back(camera->frustum());\r\n start->executeCallbacks(camera,this,NULL);\r\n visitSector(NULL, start, camera->modelingMatrix().getT(), camera);\r\n\r\n \/\/ insert portal actors\r\n if (showPortals())\r\n {\r\n for(std::map >::const_iterator it = mPortalActorMap.begin(); it != mPortalActorMap.end(); ++it)\r\n mTempActors.push_back(it->second);\r\n }\r\n\r\n \/\/ mic fixme: isn't quicker to use sets instead of sort()+unique()?\r\n \/\/ avoid reporting duplicates\r\n std::sort(mTempActors.begin(), mTempActors.end());\r\n std::vector< ref >::iterator new_end = std::unique(mTempActors.begin(), mTempActors.end());\r\n for(std::vector< ref >::iterator it = mTempActors.begin(); it != new_end; ++it)\r\n list.push_back(it->get());\r\n }\r\n }\r\n else\r\n extractActors(list);\r\n}\r\n\/\/-----------------------------------------------------------------------------\r\nvoid SceneManagerPortals::visitSector(Sector* prev, Sector* sector, const vec3& eye, const Camera* camera)\r\n{\r\n \/\/ this sector is visible so we add the visible objects\r\n for(int j=0; jactors()->size(); ++j)\r\n {\r\n if (isEnabled(sector->actors()->at(j)))\r\n {\r\n sector->actors()->at(j)->computeBounds();\r\n bool visible = true;\r\n for(unsigned i=0; visible && iactors()->at(j)->boundingBox() );\r\n if( visible )\r\n mTempActors.push_back( sector->actors()->at(j) );\r\n }\r\n }\r\n \/\/ check the visible portals\r\n for(unsigned j=0; jportals().size(); ++j)\r\n {\r\n if(showPortals())\r\n renderPortal(sector->portals()[j].get());\r\n\r\n \/\/ open\/closed portals.\r\n if(!sector->portals()[j]->isOpen())\r\n continue;\r\n\r\n if (sector->portals()[j]->mVisitTick == mVisitTick)\r\n continue;\r\n else\r\n sector->portals()[j]->mVisitTick = mVisitTick;\r\n\r\n Sector* target_sec = sector->portals()[j]->targetSector();\r\n VL_CHECK(target_sec != sector)\r\n if ( target_sec != prev )\r\n {\r\n bool visible = true;\r\n for(unsigned i=0; visible && iportals()[j]->geometry() );\r\n\r\n if (visible)\r\n {\r\n \/\/ make visiting_portal_frustum\r\n Frustum portal_frustum;\r\n portal_frustum.planes().resize(sector->portals()[j]->geometry().size());\r\n bool flip = dot((fvec3)eye - sector->portals()[j]->geometry()[0], sector->portals()[j]->normal()) < 0;\r\n for(unsigned i=0; iportals()[j]->geometry().size(); ++i)\r\n {\r\n int i2 = (i+1) % sector->portals()[j]->geometry().size();\r\n vec3 v1 = (vec3)sector->portals()[j]->geometry()[i] - eye;\r\n vec3 v2 = (vec3)sector->portals()[j]->geometry()[i2] - eye;\r\n vec3 n = cross(v1,v2);\r\n n.normalize();\r\n if (flip)\r\n n = -n;\r\n portal_frustum.setPlane(i, Plane(dot(n,eye),n));\r\n }\r\n\r\n mFrustumStack.push_back(portal_frustum);\r\n sector->executeCallbacks(camera,this,sector->portals()[j].get());\r\n visitSector(sector, sector->portals()[j]->targetSector(), eye, camera);\r\n mFrustumStack.pop_back();\r\n }\r\n }\r\n }\r\n}\r\n\/\/-----------------------------------------------------------------------------\r\nvoid SceneManagerPortals::computePortalNormals()\r\n{\r\n for(unsigned i=0; iportals().size(); ++j)\r\n mSectors[i]->portals()[j]->computeNormal();\r\n}\r\n\/\/-----------------------------------------------------------------------------\r\nSector* SceneManagerPortals::computeStartingSector(const Camera* camera)\r\n{\r\n vec3 eye = camera->modelingMatrix().getT();\r\n for(unsigned i=0; ivolumes().size(); ++j)\r\n {\r\n if (sectors()[i]->volumes()[j].isInside(eye))\r\n return sectors()[i].get();\r\n }\r\n }\r\n return externalSector();\r\n}\r\n\/\/-----------------------------------------------------------------------------\r\nSceneManagerPortals.cpp fixed rendering of portals.\/**************************************************************************************\/\r\n\/* *\/\r\n\/* Visualization Library *\/\r\n\/* http:\/\/www.visualizationlibrary.org *\/\r\n\/* *\/\r\n\/* Copyright (c) 2005-2010, Michele Bosi *\/\r\n\/* All rights reserved. *\/\r\n\/* *\/\r\n\/* Redistribution and use in source and binary forms, with or without modification, *\/\r\n\/* are permitted provided that the following conditions are met: *\/\r\n\/* *\/\r\n\/* - Redistributions of source code must retain the above copyright notice, this *\/\r\n\/* list of conditions and the following disclaimer. *\/\r\n\/* *\/\r\n\/* - Redistributions in binary form must reproduce the above copyright notice, this *\/\r\n\/* list of conditions and the following disclaimer in the documentation and\/or *\/\r\n\/* other materials provided with the distribution. *\/\r\n\/* *\/\r\n\/* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND *\/\r\n\/* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED *\/\r\n\/* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE *\/\r\n\/* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR *\/\r\n\/* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES *\/\r\n\/* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; *\/\r\n\/* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON *\/\r\n\/* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT *\/\r\n\/* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS *\/\r\n\/* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *\/\r\n\/* *\/\r\n\/**************************************************************************************\/\r\n\r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\nusing namespace vl;\r\n\r\n\/\/-----------------------------------------------------------------------------\r\n\/\/ Portal\r\n\/\/-----------------------------------------------------------------------------\r\nbool Portal::computeNormal()\r\n{\r\n mNormal = 0;\r\n if (geometry().size() < 3)\r\n {\r\n vl::Log::error(\"Portal::computeNormal() error, no portal geometry defined.\\n\");\r\n return false;\r\n }\r\n if (!mTargetSector)\r\n {\r\n vl::Log::error(\"Portal::computeNormal() error, no sector bound to this portal.\\n\");\r\n return false;\r\n }\r\n\r\n fvec3 v0 = geometry()[0];\r\n fvec3 v1 = geometry()[1] - v0;\r\n fvec3 v2 = geometry()[2] - v0;\r\n mNormal = cross(v1,v2);\r\n\r\n return true;\r\n}\r\n\/\/-----------------------------------------------------------------------------\r\n\/\/ Sector\r\n\/\/-----------------------------------------------------------------------------\r\nAABB Sector::computeBoundingBox()\r\n{\r\n AABB aabb;\r\n for(int i=0; isize(); ++i)\r\n {\r\n actors()->at(i)->computeBounds();\r\n aabb += actors()->at(i)->boundingBox();\r\n }\r\n return aabb;\r\n}\r\n\/\/-----------------------------------------------------------------------------\r\nvoid Sector::executeCallbacks(const Camera*cam,SceneManagerPortals* psm, Portal*p)\r\n{\r\n for(unsigned i=0; ioperator()(cam,psm,this,p);\r\n}\r\n\/\/-----------------------------------------------------------------------------\r\n\/\/ SceneManagerPortals\r\n\/\/-----------------------------------------------------------------------------\r\nvoid SceneManagerPortals::initialize()\r\n{\r\n computePortalNormals();\r\n for(unsigned i=0; ivolumes().empty())\r\n vl::Log::error( vl::Say(\"Sector #%n does not have any volume!\\n\") << i );\r\n for(unsigned j=0; jportals().size(); ++j)\r\n if (!mSectors[i]->portals()[j]->targetSector())\r\n vl::Log::error( vl::Say(\"In Sector #%n Portal #%n does not have any target sector!\\n\") << i << j);\r\n }\r\n}\r\n\/\/-----------------------------------------------------------------------------\r\nvoid SceneManagerPortals::renderPortal(Portal* portal)\r\n{\r\n std::map >::iterator it = mPortalActorMap.find(portal);\r\n if (it == mPortalActorMap.end())\r\n {\r\n const fvec4 portal_color = fvec4(1,0,0,0.25f);\r\n vl::ref portal_fx = new vl::Effect;\r\n \/*portal_fx->shader()->enable(vl::EN_DEPTH_TEST);\r\n portal_fx->shader()->gocDepthFunc()->set(vl::FU_LEQUAL);*\/\r\n portal_fx->shader()->enable(vl::EN_BLEND);\r\n portal_fx->shader()->gocLineWidth()->set(2.0f);\r\n portal_fx->shader()->gocColor()->setValue(portal_color);\r\n\r\n vl::ref portal_geom = new vl::Geometry;\r\n vl::ref vert_array = new vl::ArrayFloat3;\r\n portal_geom->setVertexArray(vert_array.get());\r\n vert_array->resize(portal->geometry().size());\r\n for(unsigned int i=0; igeometry().size(); ++i)\r\n vert_array->at(i) = portal->geometry()[i];\r\n portal_geom->drawCalls()->push_back( new vl::DrawArrays(vl::PT_LINE_LOOP, 0, (int)vert_array->size()) );\r\n#if defined(VL_OPENGL)\r\n portal_geom->drawCalls()->push_back( new vl::DrawArrays(vl::PT_POLYGON, 0, (int)vert_array->size()) );\r\n#endif\r\n ref actor = new vl::Actor(portal_geom.get(), portal_fx.get(), NULL);\r\n mPortalActorMap[portal] = actor;\r\n mTempActors.push_back(actor);\r\n }\r\n else\r\n mTempActors.push_back(it->second);\r\n}\r\n\/\/-----------------------------------------------------------------------------\r\nvoid SceneManagerPortals::extractActors(ActorCollection& list)\r\n{\r\n for(unsigned i=0; iactors()->size(); ++j)\r\n list.push_back( mSectors[i]->actors()->at(j) );\r\n}\r\n\/\/-----------------------------------------------------------------------------\r\nvoid SceneManagerPortals::extractVisibleActors(ActorCollection& list, const Camera* camera)\r\n{\r\n if (cullingEnabled())\r\n {\r\n Sector* start = computeStartingSector(camera);\r\n if (!start)\r\n extractActors(list);\r\n else\r\n {\r\n ++mVisitTick;\r\n mTempActors.clear();\r\n mFrustumStack.clear();\r\n\r\n mFrustumStack.push_back(camera->frustum());\r\n start->executeCallbacks(camera,this,NULL);\r\n visitSector(NULL, start, camera->modelingMatrix().getT(), camera);\r\n\r\n \/\/ remove duplicates\r\n std::sort(mTempActors.begin(), mTempActors.end());\r\n std::vector< ref >::iterator new_end = std::unique(mTempActors.begin(), mTempActors.end());\r\n for(std::vector< ref >::iterator it = mTempActors.begin(); it != new_end; ++it)\r\n list.push_back(it->get());\r\n }\r\n }\r\n else\r\n extractActors(list);\r\n}\r\n\/\/-----------------------------------------------------------------------------\r\nvoid SceneManagerPortals::visitSector(Sector* prev, Sector* sector, const vec3& eye, const Camera* camera)\r\n{\r\n \/\/ this sector is visible so we add the visible objects\r\n for(int j=0; jactors()->size(); ++j)\r\n {\r\n if (isEnabled(sector->actors()->at(j)))\r\n {\r\n sector->actors()->at(j)->computeBounds();\r\n bool visible = true;\r\n for(unsigned i=0; visible && iactors()->at(j)->boundingBox() );\r\n if( visible )\r\n mTempActors.push_back( sector->actors()->at(j) );\r\n }\r\n }\r\n \/\/ check the visible portals\r\n for(unsigned j=0; jportals().size(); ++j)\r\n {\r\n if(showPortals())\r\n renderPortal(sector->portals()[j].get());\r\n\r\n \/\/ open\/closed portals.\r\n if(!sector->portals()[j]->isOpen())\r\n continue;\r\n\r\n if (sector->portals()[j]->mVisitTick == mVisitTick)\r\n continue;\r\n else\r\n sector->portals()[j]->mVisitTick = mVisitTick;\r\n\r\n Sector* target_sec = sector->portals()[j]->targetSector();\r\n VL_CHECK(target_sec != sector)\r\n if ( target_sec != prev )\r\n {\r\n bool visible = true;\r\n for(unsigned i=0; visible && iportals()[j]->geometry() );\r\n\r\n if (visible)\r\n {\r\n \/\/ make visiting_portal_frustum\r\n Frustum portal_frustum;\r\n portal_frustum.planes().resize(sector->portals()[j]->geometry().size());\r\n bool flip = dot((fvec3)eye - sector->portals()[j]->geometry()[0], sector->portals()[j]->normal()) < 0;\r\n for(unsigned i=0; iportals()[j]->geometry().size(); ++i)\r\n {\r\n int i2 = (i+1) % sector->portals()[j]->geometry().size();\r\n vec3 v1 = (vec3)sector->portals()[j]->geometry()[i] - eye;\r\n vec3 v2 = (vec3)sector->portals()[j]->geometry()[i2] - eye;\r\n vec3 n = cross(v1,v2);\r\n n.normalize();\r\n if (flip)\r\n n = -n;\r\n portal_frustum.setPlane(i, Plane(dot(n,eye),n));\r\n }\r\n\r\n mFrustumStack.push_back(portal_frustum);\r\n sector->executeCallbacks(camera,this,sector->portals()[j].get());\r\n visitSector(sector, sector->portals()[j]->targetSector(), eye, camera);\r\n mFrustumStack.pop_back();\r\n }\r\n }\r\n }\r\n}\r\n\/\/-----------------------------------------------------------------------------\r\nvoid SceneManagerPortals::computePortalNormals()\r\n{\r\n for(unsigned i=0; iportals().size(); ++j)\r\n mSectors[i]->portals()[j]->computeNormal();\r\n}\r\n\/\/-----------------------------------------------------------------------------\r\nSector* SceneManagerPortals::computeStartingSector(const Camera* camera)\r\n{\r\n vec3 eye = camera->modelingMatrix().getT();\r\n for(unsigned i=0; ivolumes().size(); ++j)\r\n {\r\n if (sectors()[i]->volumes()[j].isInside(eye))\r\n return sectors()[i].get();\r\n }\r\n }\r\n return externalSector();\r\n}\r\n\/\/-----------------------------------------------------------------------------\r\n<|endoftext|>"} {"text":"fix: GAMxVEN register class<|endoftext|>"} {"text":"#ifndef MIMOSA_FORMAT_FORMAT_STREAM_HH\n# define MIMOSA_FORMAT_FORMAT_STREAM_HH\n\n# include \"format.hh\"\n# include \"..\/stream\/stream.hh\"\n\nnamespace mimosa\n{\n namespace format\n {\n template \n inline\n bool format(stream::Stream::Ptr stream,\n runtime::Time timeout,\n const char * fmt,\n Args ... args)\n {\n std::string str(format::str(fmt, args...));\n int64_t bytes = stream->loopWrite(str.data(), str.size(), timeout);\n return static_cast (bytes) == str.size();\n }\n\n template \n inline\n bool format(stream::Stream::Ptr stream,\n const char * fmt,\n Args ... args)\n {\n return format(stream, static_cast(0), fmt, args...);\n }\n }\n}\n\n#endif \/* !MIMOSA_FORMAT_FORMAT_STREAM_HH *\/\nFixed a case where the formated string is empty#ifndef MIMOSA_FORMAT_FORMAT_STREAM_HH\n# define MIMOSA_FORMAT_FORMAT_STREAM_HH\n\n# include \"format.hh\"\n# include \"..\/stream\/stream.hh\"\n\nnamespace mimosa\n{\n namespace format\n {\n template \n inline\n bool format(stream::Stream::Ptr stream,\n runtime::Time timeout,\n const char * fmt,\n Args ... args)\n {\n std::string str(format::str(fmt, args...));\n if (str.empty())\n return true;\n int64_t bytes = stream->loopWrite(str.data(), str.size(), timeout);\n return static_cast (bytes) == str.size();\n }\n\n template \n inline\n bool format(stream::Stream::Ptr stream,\n const char * fmt,\n Args ... args)\n {\n return format(stream, static_cast(0), fmt, args...);\n }\n }\n}\n\n#endif \/* !MIMOSA_FORMAT_FORMAT_STREAM_HH *\/\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: svarray.cxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: obo $ $Date: 2006-10-12 15:23:09 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_svtools.hxx\"\n\n#define _SVARRAY_CXX\n\n#define _SVSTDARR_BOOLS\n#define _SVSTDARR_BYTES\n#define _SVSTDARR_ULONGS\n#define _SVSTDARR_ULONGSSORT\n#define _SVSTDARR_USHORTS\n#define _SVSTDARR_LONGS\n#define _SVSTDARR_LONGSSORT\n#define _SVSTDARR_SHORTS\n#define _SVSTDARR_STRINGS\n#define _SVSTDARR_STRINGSDTOR\n#define _SVSTDARR_STRINGSSORT\n#define _SVSTDARR_STRINGSSORTDTOR\n#define _SVSTDARR_STRINGSISORT\n#define _SVSTDARR_STRINGSISORTDTOR\n#define _SVSTDARR_USHORTSSORT\n\n#define _SVSTDARR_BYTESTRINGS\n#define _SVSTDARR_BYTESTRINGSDTOR\n#define _SVSTDARR_BYTESTRINGSSORT\n#define _SVSTDARR_BYTESTRINGSSORTDTOR\n#define _SVSTDARR_BYTESTRINGSISORT\n#define _SVSTDARR_BYTESTRINGSISORTDTOR\n\n#define _SVSTDARR_XUB_STRLEN\n#define _SVSTDARR_XUB_STRLENSORT\n\n#include \n\n#ifndef _STRING_HXX \/\/autogen\n#include \n#endif\n\n#ifndef _TOOLS_DEBUG_HXX \/\/autogen\n#include \n#endif\n\n#ifdef MAC\n#pragma segment NEVER_PURGE\n#endif\n\nSV_IMPL_VARARR(SvPtrarr,VoidPtr)\nSV_IMPL_VARARR_PLAIN(SvPtrarrPlain,VoidPtr)\n\nUSHORT SvPtrarr::GetPos( const VoidPtr& aElement ) const\n{ USHORT n;\n for( n=0; n < nA && *(GetData()+n) != aElement; ) n++;\n return ( n >= nA ? USHRT_MAX : n );\n}\n\nUSHORT SvPtrarrPlain::GetPos( const VoidPtr aElement ) const\n{ USHORT n;\n for( n=0; n < nA && *(GetData()+n) != aElement; ) n++;\n return ( n >= nA ? USHRT_MAX : n );\n}\n\n\nSV_IMPL_VARARR( SvBools, BOOL )\nSV_IMPL_VARARR( SvBytes, BYTE )\nSV_IMPL_VARARR( SvULongs, ULONG )\nSV_IMPL_VARARR( SvUShorts, USHORT )\nSV_IMPL_VARARR( SvLongs, long)\nSV_IMPL_VARARR( SvShorts, short )\n\nSV_IMPL_VARARR_SORT( SvULongsSort, ULONG )\nSV_IMPL_VARARR_SORT( SvLongsSort, long )\nSV_IMPL_VARARR_SORT( SvXub_StrLensSort, xub_StrLen )\n\nSV_IMPL_VARARR( SvXub_StrLens, xub_StrLen )\n\nSV_IMPL_PTRARR( SvStrings, StringPtr )\nSV_IMPL_PTRARR( SvStringsDtor, StringPtr )\nSV_IMPL_OP_PTRARR_SORT( SvStringsSort, StringPtr )\nSV_IMPL_OP_PTRARR_SORT( SvStringsSortDtor, StringPtr )\n\nSV_IMPL_PTRARR( SvByteStrings, ByteStringPtr )\nSV_IMPL_PTRARR( SvByteStringsDtor, ByteStringPtr )\nSV_IMPL_OP_PTRARR_SORT( SvByteStringsSort, ByteStringPtr )\nSV_IMPL_OP_PTRARR_SORT( SvByteStringsSortDtor, ByteStringPtr )\n\n\n\n\/\/ ---------------- strings -------------------------------------\n\n\/\/ Array mit anderer Seek-Methode!\n_SV_IMPL_SORTAR_ALG( SvStringsISort, StringPtr )\nvoid SvStringsISort::DeleteAndDestroy( USHORT nP, USHORT nL )\n{\n if( nL )\n {\n DBG_ASSERT( nP < nA && nP + nL <= nA, \"ERR_VAR_DEL\" );\n for( USHORT n=nP; n < nP + nL; n++ )\n delete *((StringPtr*)pData+n);\n SvPtrarr::Remove( nP, nL );\n }\n}\nBOOL SvStringsISort::Seek_Entry( const StringPtr aE, USHORT* pP ) const\n{\n register USHORT nO = SvStringsISort_SAR::Count(),\n nM,\n nU = 0;\n if( nO > 0 )\n {\n nO--;\n while( nU <= nO )\n {\n nM = nU + ( nO - nU ) \/ 2;\n StringCompare eCmp = (*((StringPtr*)pData + nM))->\n CompareIgnoreCaseToAscii( *(aE) );\n if( COMPARE_EQUAL == eCmp )\n {\n if( pP ) *pP = nM;\n return TRUE;\n }\n else if( COMPARE_LESS == eCmp )\n nU = nM + 1;\n else if( nM == 0 )\n {\n if( pP ) *pP = nU;\n return FALSE;\n }\n else\n nO = nM - 1;\n }\n }\n if( pP ) *pP = nU;\n return FALSE;\n}\n\n\/\/ ---------------- strings -------------------------------------\n\n\/\/ Array mit anderer Seek-Methode!\n_SV_IMPL_SORTAR_ALG( SvStringsISortDtor, StringPtr )\nvoid SvStringsISortDtor::DeleteAndDestroy( USHORT nP, USHORT nL )\n{\n if( nL )\n {\n DBG_ASSERT( nP < nA && nP + nL <= nA, \"ERR_VAR_DEL\" );\n for( USHORT n=nP; n < nP + nL; n++ )\n delete *((StringPtr*)pData+n);\n SvPtrarr::Remove( nP, nL );\n }\n}\nBOOL SvStringsISortDtor::Seek_Entry( const StringPtr aE, USHORT* pP ) const\n{\n register USHORT nO = SvStringsISortDtor_SAR::Count(),\n nM,\n nU = 0;\n if( nO > 0 )\n {\n nO--;\n while( nU <= nO )\n {\n nM = nU + ( nO - nU ) \/ 2;\n StringCompare eCmp = (*((StringPtr*)pData + nM))->\n CompareIgnoreCaseToAscii( *(aE) );\n if( COMPARE_EQUAL == eCmp )\n {\n if( pP ) *pP = nM;\n return TRUE;\n }\n else if( COMPARE_LESS == eCmp )\n nU = nM + 1;\n else if( nM == 0 )\n {\n if( pP ) *pP = nU;\n return FALSE;\n }\n else\n nO = nM - 1;\n }\n }\n if( pP ) *pP = nU;\n return FALSE;\n}\n\n\/\/ ---------------- Ushorts -------------------------------------\n\n\/* SortArray fuer UShorts *\/\nBOOL SvUShortsSort::Seek_Entry( const USHORT aE, USHORT* pP ) const\n{\n register USHORT nO = SvUShorts::Count(),\n nM,\n nU = 0;\n if( nO > 0 )\n {\n nO--;\n while( nU <= nO )\n {\n nM = nU + ( nO - nU ) \/ 2;\n if( *(pData + nM) == aE )\n {\n if( pP ) *pP = nM;\n return TRUE;\n }\n else if( *(pData + nM) < aE )\n nU = nM + 1;\n else if( nM == 0 )\n {\n if( pP ) *pP = nU;\n return FALSE;\n }\n else\n nO = nM - 1;\n }\n }\n if( pP ) *pP = nU;\n return FALSE;\n}\n\nvoid SvUShortsSort::Insert( const SvUShortsSort * pI, USHORT nS, USHORT nE )\n{\n if( USHRT_MAX == nE )\n nE = pI->Count();\n USHORT nP;\n const USHORT * pIArr = pI->GetData();\n for( ; nS < nE; ++nS )\n {\n if( ! Seek_Entry( *(pIArr+nS), &nP) )\n SvUShorts::Insert( *(pIArr+nS), nP );\n if( ++nP >= Count() )\n {\n SvUShorts::Insert( pI, nP, nS+1, nE );\n nS = nE;\n }\n }\n}\n\nBOOL SvUShortsSort::Insert( const USHORT aE )\n{\n USHORT nP;\n BOOL bExist = Seek_Entry( aE, &nP );\n if( !bExist )\n SvUShorts::Insert( aE, nP );\n return !bExist;\n}\n\nBOOL SvUShortsSort::Insert( const USHORT aE, USHORT& rP )\n{\n BOOL bExist = Seek_Entry( aE, &rP );\n if( !bExist )\n SvUShorts::Insert( aE, rP );\n return !bExist;\n}\n\nvoid SvUShortsSort::Insert( const USHORT* pE, USHORT nL)\n{\n USHORT nP;\n for( USHORT n = 0; n < nL; ++n )\n if( ! Seek_Entry( *(pE+n), &nP ))\n SvUShorts::Insert( *(pE+n), nP );\n}\n\n\/\/ remove ab Pos\nvoid SvUShortsSort::RemoveAt( const USHORT nP, USHORT nL )\n{\n if( nL )\n SvUShorts::Remove( nP, nL);\n}\n\n\/\/ remove ab dem Eintrag\nvoid SvUShortsSort::Remove( const USHORT aE, USHORT nL )\n{\n USHORT nP;\n if( nL && Seek_Entry( aE, &nP ) )\n SvUShorts::Remove( nP, nL);\n}\n\n\/\/ ---------------- bytestrings -------------------------------------\n\n\/\/ Array mit anderer Seek-Methode!\n_SV_IMPL_SORTAR_ALG( SvByteStringsISort, ByteStringPtr )\nvoid SvByteStringsISort::DeleteAndDestroy( USHORT nP, USHORT nL )\n{\n if( nL )\n {\n DBG_ASSERT( nP < nA && nP + nL <= nA, \"ERR_VAR_DEL\" );\n for( USHORT n=nP; n < nP + nL; n++ )\n delete *((ByteStringPtr*)pData+n);\n SvPtrarr::Remove( nP, nL );\n }\n}\nBOOL SvByteStringsISort::Seek_Entry( const ByteStringPtr aE, USHORT* pP ) const\n{\n register USHORT nO = SvByteStringsISort_SAR::Count(),\n nM,\n nU = 0;\n if( nO > 0 )\n {\n nO--;\n while( nU <= nO )\n {\n nM = nU + ( nO - nU ) \/ 2;\n StringCompare eCmp = (*((ByteStringPtr*)pData + nM))->\n CompareIgnoreCaseToAscii( *(aE) );\n if( COMPARE_EQUAL == eCmp )\n {\n if( pP ) *pP = nM;\n return TRUE;\n }\n else if( COMPARE_LESS == eCmp )\n nU = nM + 1;\n else if( nM == 0 )\n {\n if( pP ) *pP = nU;\n return FALSE;\n }\n else\n nO = nM - 1;\n }\n }\n if( pP ) *pP = nU;\n return FALSE;\n}\n\n\n\/\/ Array mit anderer Seek-Methode!\n_SV_IMPL_SORTAR_ALG( SvByteStringsISortDtor, ByteStringPtr )\nvoid SvByteStringsISortDtor::DeleteAndDestroy( USHORT nP, USHORT nL )\n{\n if( nL )\n {\n DBG_ASSERT( nP < nA && nP + nL <= nA, \"ERR_VAR_DEL\" );\n for( USHORT n=nP; n < nP + nL; n++ )\n delete *((ByteStringPtr*)pData+n);\n SvPtrarr::Remove( nP, nL );\n }\n}\nBOOL SvByteStringsISortDtor::Seek_Entry( const ByteStringPtr aE, USHORT* pP ) const\n{\n register USHORT nO = SvByteStringsISortDtor_SAR::Count(),\n nM,\n nU = 0;\n if( nO > 0 )\n {\n nO--;\n while( nU <= nO )\n {\n nM = nU + ( nO - nU ) \/ 2;\n StringCompare eCmp = (*((ByteStringPtr*)pData + nM))->\n CompareIgnoreCaseToAscii( *(aE) );\n if( COMPARE_EQUAL == eCmp )\n {\n if( pP ) *pP = nM;\n return TRUE;\n }\n else if( COMPARE_LESS == eCmp )\n nU = nM + 1;\n else if( nM == 0 )\n {\n if( pP ) *pP = nU;\n return FALSE;\n }\n else\n nO = nM - 1;\n }\n }\n if( pP ) *pP = nU;\n return FALSE;\n}\n\nINTEGRATION: CWS vgbugs07 (1.5.182); FILE MERGED 2007\/06\/04 13:31:42 vg 1.5.182.1: #i76605# Remove -I ...\/inc\/module hack introduced by hedaburemove01\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: svarray.cxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: hr $ $Date: 2007-06-27 21:48:00 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_svtools.hxx\"\n\n#define _SVARRAY_CXX\n\n#define _SVSTDARR_BOOLS\n#define _SVSTDARR_BYTES\n#define _SVSTDARR_ULONGS\n#define _SVSTDARR_ULONGSSORT\n#define _SVSTDARR_USHORTS\n#define _SVSTDARR_LONGS\n#define _SVSTDARR_LONGSSORT\n#define _SVSTDARR_SHORTS\n#define _SVSTDARR_STRINGS\n#define _SVSTDARR_STRINGSDTOR\n#define _SVSTDARR_STRINGSSORT\n#define _SVSTDARR_STRINGSSORTDTOR\n#define _SVSTDARR_STRINGSISORT\n#define _SVSTDARR_STRINGSISORTDTOR\n#define _SVSTDARR_USHORTSSORT\n\n#define _SVSTDARR_BYTESTRINGS\n#define _SVSTDARR_BYTESTRINGSDTOR\n#define _SVSTDARR_BYTESTRINGSSORT\n#define _SVSTDARR_BYTESTRINGSSORTDTOR\n#define _SVSTDARR_BYTESTRINGSISORT\n#define _SVSTDARR_BYTESTRINGSISORTDTOR\n\n#define _SVSTDARR_XUB_STRLEN\n#define _SVSTDARR_XUB_STRLENSORT\n\n#include \n\n#ifndef _STRING_HXX \/\/autogen\n#include \n#endif\n\n#ifndef _TOOLS_DEBUG_HXX \/\/autogen\n#include \n#endif\n\n#ifdef MAC\n#pragma segment NEVER_PURGE\n#endif\n\nSV_IMPL_VARARR(SvPtrarr,VoidPtr)\nSV_IMPL_VARARR_PLAIN(SvPtrarrPlain,VoidPtr)\n\nUSHORT SvPtrarr::GetPos( const VoidPtr& aElement ) const\n{ USHORT n;\n for( n=0; n < nA && *(GetData()+n) != aElement; ) n++;\n return ( n >= nA ? USHRT_MAX : n );\n}\n\nUSHORT SvPtrarrPlain::GetPos( const VoidPtr aElement ) const\n{ USHORT n;\n for( n=0; n < nA && *(GetData()+n) != aElement; ) n++;\n return ( n >= nA ? USHRT_MAX : n );\n}\n\n\nSV_IMPL_VARARR( SvBools, BOOL )\nSV_IMPL_VARARR( SvBytes, BYTE )\nSV_IMPL_VARARR( SvULongs, ULONG )\nSV_IMPL_VARARR( SvUShorts, USHORT )\nSV_IMPL_VARARR( SvLongs, long)\nSV_IMPL_VARARR( SvShorts, short )\n\nSV_IMPL_VARARR_SORT( SvULongsSort, ULONG )\nSV_IMPL_VARARR_SORT( SvLongsSort, long )\nSV_IMPL_VARARR_SORT( SvXub_StrLensSort, xub_StrLen )\n\nSV_IMPL_VARARR( SvXub_StrLens, xub_StrLen )\n\nSV_IMPL_PTRARR( SvStrings, StringPtr )\nSV_IMPL_PTRARR( SvStringsDtor, StringPtr )\nSV_IMPL_OP_PTRARR_SORT( SvStringsSort, StringPtr )\nSV_IMPL_OP_PTRARR_SORT( SvStringsSortDtor, StringPtr )\n\nSV_IMPL_PTRARR( SvByteStrings, ByteStringPtr )\nSV_IMPL_PTRARR( SvByteStringsDtor, ByteStringPtr )\nSV_IMPL_OP_PTRARR_SORT( SvByteStringsSort, ByteStringPtr )\nSV_IMPL_OP_PTRARR_SORT( SvByteStringsSortDtor, ByteStringPtr )\n\n\n\n\/\/ ---------------- strings -------------------------------------\n\n\/\/ Array mit anderer Seek-Methode!\n_SV_IMPL_SORTAR_ALG( SvStringsISort, StringPtr )\nvoid SvStringsISort::DeleteAndDestroy( USHORT nP, USHORT nL )\n{\n if( nL )\n {\n DBG_ASSERT( nP < nA && nP + nL <= nA, \"ERR_VAR_DEL\" );\n for( USHORT n=nP; n < nP + nL; n++ )\n delete *((StringPtr*)pData+n);\n SvPtrarr::Remove( nP, nL );\n }\n}\nBOOL SvStringsISort::Seek_Entry( const StringPtr aE, USHORT* pP ) const\n{\n register USHORT nO = SvStringsISort_SAR::Count(),\n nM,\n nU = 0;\n if( nO > 0 )\n {\n nO--;\n while( nU <= nO )\n {\n nM = nU + ( nO - nU ) \/ 2;\n StringCompare eCmp = (*((StringPtr*)pData + nM))->\n CompareIgnoreCaseToAscii( *(aE) );\n if( COMPARE_EQUAL == eCmp )\n {\n if( pP ) *pP = nM;\n return TRUE;\n }\n else if( COMPARE_LESS == eCmp )\n nU = nM + 1;\n else if( nM == 0 )\n {\n if( pP ) *pP = nU;\n return FALSE;\n }\n else\n nO = nM - 1;\n }\n }\n if( pP ) *pP = nU;\n return FALSE;\n}\n\n\/\/ ---------------- strings -------------------------------------\n\n\/\/ Array mit anderer Seek-Methode!\n_SV_IMPL_SORTAR_ALG( SvStringsISortDtor, StringPtr )\nvoid SvStringsISortDtor::DeleteAndDestroy( USHORT nP, USHORT nL )\n{\n if( nL )\n {\n DBG_ASSERT( nP < nA && nP + nL <= nA, \"ERR_VAR_DEL\" );\n for( USHORT n=nP; n < nP + nL; n++ )\n delete *((StringPtr*)pData+n);\n SvPtrarr::Remove( nP, nL );\n }\n}\nBOOL SvStringsISortDtor::Seek_Entry( const StringPtr aE, USHORT* pP ) const\n{\n register USHORT nO = SvStringsISortDtor_SAR::Count(),\n nM,\n nU = 0;\n if( nO > 0 )\n {\n nO--;\n while( nU <= nO )\n {\n nM = nU + ( nO - nU ) \/ 2;\n StringCompare eCmp = (*((StringPtr*)pData + nM))->\n CompareIgnoreCaseToAscii( *(aE) );\n if( COMPARE_EQUAL == eCmp )\n {\n if( pP ) *pP = nM;\n return TRUE;\n }\n else if( COMPARE_LESS == eCmp )\n nU = nM + 1;\n else if( nM == 0 )\n {\n if( pP ) *pP = nU;\n return FALSE;\n }\n else\n nO = nM - 1;\n }\n }\n if( pP ) *pP = nU;\n return FALSE;\n}\n\n\/\/ ---------------- Ushorts -------------------------------------\n\n\/* SortArray fuer UShorts *\/\nBOOL SvUShortsSort::Seek_Entry( const USHORT aE, USHORT* pP ) const\n{\n register USHORT nO = SvUShorts::Count(),\n nM,\n nU = 0;\n if( nO > 0 )\n {\n nO--;\n while( nU <= nO )\n {\n nM = nU + ( nO - nU ) \/ 2;\n if( *(pData + nM) == aE )\n {\n if( pP ) *pP = nM;\n return TRUE;\n }\n else if( *(pData + nM) < aE )\n nU = nM + 1;\n else if( nM == 0 )\n {\n if( pP ) *pP = nU;\n return FALSE;\n }\n else\n nO = nM - 1;\n }\n }\n if( pP ) *pP = nU;\n return FALSE;\n}\n\nvoid SvUShortsSort::Insert( const SvUShortsSort * pI, USHORT nS, USHORT nE )\n{\n if( USHRT_MAX == nE )\n nE = pI->Count();\n USHORT nP;\n const USHORT * pIArr = pI->GetData();\n for( ; nS < nE; ++nS )\n {\n if( ! Seek_Entry( *(pIArr+nS), &nP) )\n SvUShorts::Insert( *(pIArr+nS), nP );\n if( ++nP >= Count() )\n {\n SvUShorts::Insert( pI, nP, nS+1, nE );\n nS = nE;\n }\n }\n}\n\nBOOL SvUShortsSort::Insert( const USHORT aE )\n{\n USHORT nP;\n BOOL bExist = Seek_Entry( aE, &nP );\n if( !bExist )\n SvUShorts::Insert( aE, nP );\n return !bExist;\n}\n\nBOOL SvUShortsSort::Insert( const USHORT aE, USHORT& rP )\n{\n BOOL bExist = Seek_Entry( aE, &rP );\n if( !bExist )\n SvUShorts::Insert( aE, rP );\n return !bExist;\n}\n\nvoid SvUShortsSort::Insert( const USHORT* pE, USHORT nL)\n{\n USHORT nP;\n for( USHORT n = 0; n < nL; ++n )\n if( ! Seek_Entry( *(pE+n), &nP ))\n SvUShorts::Insert( *(pE+n), nP );\n}\n\n\/\/ remove ab Pos\nvoid SvUShortsSort::RemoveAt( const USHORT nP, USHORT nL )\n{\n if( nL )\n SvUShorts::Remove( nP, nL);\n}\n\n\/\/ remove ab dem Eintrag\nvoid SvUShortsSort::Remove( const USHORT aE, USHORT nL )\n{\n USHORT nP;\n if( nL && Seek_Entry( aE, &nP ) )\n SvUShorts::Remove( nP, nL);\n}\n\n\/\/ ---------------- bytestrings -------------------------------------\n\n\/\/ Array mit anderer Seek-Methode!\n_SV_IMPL_SORTAR_ALG( SvByteStringsISort, ByteStringPtr )\nvoid SvByteStringsISort::DeleteAndDestroy( USHORT nP, USHORT nL )\n{\n if( nL )\n {\n DBG_ASSERT( nP < nA && nP + nL <= nA, \"ERR_VAR_DEL\" );\n for( USHORT n=nP; n < nP + nL; n++ )\n delete *((ByteStringPtr*)pData+n);\n SvPtrarr::Remove( nP, nL );\n }\n}\nBOOL SvByteStringsISort::Seek_Entry( const ByteStringPtr aE, USHORT* pP ) const\n{\n register USHORT nO = SvByteStringsISort_SAR::Count(),\n nM,\n nU = 0;\n if( nO > 0 )\n {\n nO--;\n while( nU <= nO )\n {\n nM = nU + ( nO - nU ) \/ 2;\n StringCompare eCmp = (*((ByteStringPtr*)pData + nM))->\n CompareIgnoreCaseToAscii( *(aE) );\n if( COMPARE_EQUAL == eCmp )\n {\n if( pP ) *pP = nM;\n return TRUE;\n }\n else if( COMPARE_LESS == eCmp )\n nU = nM + 1;\n else if( nM == 0 )\n {\n if( pP ) *pP = nU;\n return FALSE;\n }\n else\n nO = nM - 1;\n }\n }\n if( pP ) *pP = nU;\n return FALSE;\n}\n\n\n\/\/ Array mit anderer Seek-Methode!\n_SV_IMPL_SORTAR_ALG( SvByteStringsISortDtor, ByteStringPtr )\nvoid SvByteStringsISortDtor::DeleteAndDestroy( USHORT nP, USHORT nL )\n{\n if( nL )\n {\n DBG_ASSERT( nP < nA && nP + nL <= nA, \"ERR_VAR_DEL\" );\n for( USHORT n=nP; n < nP + nL; n++ )\n delete *((ByteStringPtr*)pData+n);\n SvPtrarr::Remove( nP, nL );\n }\n}\nBOOL SvByteStringsISortDtor::Seek_Entry( const ByteStringPtr aE, USHORT* pP ) const\n{\n register USHORT nO = SvByteStringsISortDtor_SAR::Count(),\n nM,\n nU = 0;\n if( nO > 0 )\n {\n nO--;\n while( nU <= nO )\n {\n nM = nU + ( nO - nU ) \/ 2;\n StringCompare eCmp = (*((ByteStringPtr*)pData + nM))->\n CompareIgnoreCaseToAscii( *(aE) );\n if( COMPARE_EQUAL == eCmp )\n {\n if( pP ) *pP = nM;\n return TRUE;\n }\n else if( COMPARE_LESS == eCmp )\n nU = nM + 1;\n else if( nM == 0 )\n {\n if( pP ) *pP = nU;\n return FALSE;\n }\n else\n nO = nM - 1;\n }\n }\n if( pP ) *pP = nU;\n return FALSE;\n}\n\n<|endoftext|>"} {"text":"\/* \n * Copyright 2015 Google Inc. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"PhotonWaveOut.h\"\n\nstatic WaveOut *current = NULL;\n\nstatic void playback_handler(void) {\n int v = current->advance();\n \/\/ manual PWM, we map value to pulse-width\n if (v >= 0x80) {\n v = 0xFF-v;\n if (v > 0) {\n pinSetFast(current->pin_n);\n delayMicroseconds(v);\n pinResetFast(current->pin_n);\n }\n } else {\n if (v > 0) {\n pinSetFast(current->pin_p);\n delayMicroseconds(v);\n pinResetFast(current->pin_p);\n }\n }\n}\n \nbool WaveOut::play(char *wave, unsigned int wave_len, bool loop) {\n if (playing)\n stop();\n\n this->wave = wave;\n this->wave_len = wave_len;\n this->loop = loop;\n this->wave_ix = 0;\n current = this;\n \/\/ for 8000 Hz this should be 125, but we cheat a bit to be able to map the samples straight\n audio_clock->begin(playback_handler, 127, uSec);\n this->playing = true;\n return true;\n}\n\nvoid WaveOut::stop(void) {\n if (!playing)\n return;\n\n audio_clock->end();\n pinResetFast(pin_p);\n pinResetFast(pin_n);\n this->playing = false;\n current = NULL;\n}\n\nint WaveOut::advance(void) {\n int v = wave[wave_ix];\n wave_ix++;\n if (wave_ix >= wave_len) {\n wave_ix = 0;\n \/\/ TODO: do loop = false\n }\n return v;\n}\n\nAdd loop support.\/* \n * Copyright 2015 Google Inc. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"PhotonWaveOut.h\"\n\nstatic WaveOut *current = NULL;\n\nstatic void playback_handler(void) {\n int v = current->advance();\n \/\/ manual PWM, we map value to pulse-width\n if (v >= 0x80) {\n v = 0xFF-v;\n if (v > 0) {\n pinSetFast(current->pin_n);\n delayMicroseconds(v);\n pinResetFast(current->pin_n);\n }\n } else {\n if (v > 0) {\n pinSetFast(current->pin_p);\n delayMicroseconds(v);\n pinResetFast(current->pin_p);\n }\n }\n}\n \nbool WaveOut::play(char *wave, unsigned int wave_len, bool loop) {\n if (playing)\n stop();\n\n this->wave = wave;\n this->wave_len = wave_len;\n this->loop = loop;\n this->wave_ix = 0;\n current = this;\n \/\/ for 8000 Hz this should be 125, but we cheat a bit to be able to map the samples straight\n audio_clock->begin(playback_handler, 127, uSec);\n this->playing = true;\n return true;\n}\n\nvoid WaveOut::stop(void) {\n if (!playing)\n return;\n\n audio_clock->end();\n pinResetFast(pin_p);\n pinResetFast(pin_n);\n this->playing = false;\n current = NULL;\n}\n\nint WaveOut::advance(void) {\n int v = wave[wave_ix];\n wave_ix++;\n if (wave_ix >= wave_len) {\n if (loop) {\n wave_ix = 0;\n } else {\n stop();\n }\n }\n return v;\n}\n\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: fmtwrapinfluenceonobjpos.hxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: rt $ $Date: 2008-03-12 12:11:56 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#ifndef _FMTWRAPINFLUENCEONOBJPOS_HXX\n#define _FMTWRAPINFLUENCEONOBJPOS_HXX\n\n#ifndef _HINTIDS_HXX\n#include \n#endif\n#ifndef _FORMAT_HXX\n#include \n#endif\n#ifndef _SFXPOOLITEM_HXX\n#include \n#endif\n#ifndef _COM_SUN_STAR_TEXT_WRAPINFLUENCEONPOSITION_HPP_\n#include \n#endif\n\nclass SwFmtWrapInfluenceOnObjPos: public SfxPoolItem\n{\nprivate:\n sal_Int16 mnWrapInfluenceOnPosition;\n\npublic:\n TYPEINFO();\n\n \/\/ --> OD 2004-10-18 #i35017# - constant name has changed\n SwFmtWrapInfluenceOnObjPos(\n sal_Int16 _nWrapInfluenceOnPosition =\n com::sun::star::text::WrapInfluenceOnPosition::ONCE_CONCURRENT );\n \/\/ <--\n SwFmtWrapInfluenceOnObjPos(\n const SwFmtWrapInfluenceOnObjPos& _rCpy );\n ~SwFmtWrapInfluenceOnObjPos();\n\n SwFmtWrapInfluenceOnObjPos& operator=(\n const SwFmtWrapInfluenceOnObjPos& _rSource );\n\n \/\/ pure virtual methods of class \n virtual int operator==( const SfxPoolItem& _rAttr ) const;\n virtual SfxPoolItem* Clone( SfxItemPool* pPool = 0 ) const;\n\n virtual BOOL QueryValue( com::sun::star::uno::Any& rVal, BYTE nMemberId = 0 ) const;\n virtual BOOL PutValue( const com::sun::star::uno::Any& rVal, BYTE nMemberId = 0 );\n\n \/\/ direct accessors to data\n void SetWrapInfluenceOnObjPos( sal_Int16 _nWrapInfluenceOnPosition );\n \/\/ --> OD 2004-10-18 #i35017# - add parameter <_bIterativeAsOnceConcurrent>\n \/\/ to control, if value has to be treated as \n sal_Int16 GetWrapInfluenceOnObjPos(\n const bool _bIterativeAsOnceConcurrent = false ) const;\n \/\/ <--\n};\n\ninline const SwFmtWrapInfluenceOnObjPos& SwAttrSet::GetWrapInfluenceOnObjPos(BOOL bInP) const\n { return (const SwFmtWrapInfluenceOnObjPos&)Get( RES_WRAP_INFLUENCE_ON_OBJPOS,bInP); }\n\n inline const SwFmtWrapInfluenceOnObjPos& SwFmt::GetWrapInfluenceOnObjPos(BOOL bInP) const\n { return aSet.GetWrapInfluenceOnObjPos(bInP); }\n\n#endif\nINTEGRATION: CWS changefileheader (1.6.34); FILE MERGED 2008\/04\/01 15:56:13 thb 1.6.34.3: #i85898# Stripping all external header guards 2008\/04\/01 12:53:31 thb 1.6.34.2: #i85898# Stripping all external header guards 2008\/03\/31 16:52:38 rt 1.6.34.1: #i87441# Change license header to LPGL v3.\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: fmtwrapinfluenceonobjpos.hxx,v $\n * $Revision: 1.7 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n#ifndef _FMTWRAPINFLUENCEONOBJPOS_HXX\n#define _FMTWRAPINFLUENCEONOBJPOS_HXX\n\n#include \n#include \n#include \n#include \n\nclass SwFmtWrapInfluenceOnObjPos: public SfxPoolItem\n{\nprivate:\n sal_Int16 mnWrapInfluenceOnPosition;\n\npublic:\n TYPEINFO();\n\n \/\/ --> OD 2004-10-18 #i35017# - constant name has changed\n SwFmtWrapInfluenceOnObjPos(\n sal_Int16 _nWrapInfluenceOnPosition =\n com::sun::star::text::WrapInfluenceOnPosition::ONCE_CONCURRENT );\n \/\/ <--\n SwFmtWrapInfluenceOnObjPos(\n const SwFmtWrapInfluenceOnObjPos& _rCpy );\n ~SwFmtWrapInfluenceOnObjPos();\n\n SwFmtWrapInfluenceOnObjPos& operator=(\n const SwFmtWrapInfluenceOnObjPos& _rSource );\n\n \/\/ pure virtual methods of class \n virtual int operator==( const SfxPoolItem& _rAttr ) const;\n virtual SfxPoolItem* Clone( SfxItemPool* pPool = 0 ) const;\n\n virtual BOOL QueryValue( com::sun::star::uno::Any& rVal, BYTE nMemberId = 0 ) const;\n virtual BOOL PutValue( const com::sun::star::uno::Any& rVal, BYTE nMemberId = 0 );\n\n \/\/ direct accessors to data\n void SetWrapInfluenceOnObjPos( sal_Int16 _nWrapInfluenceOnPosition );\n \/\/ --> OD 2004-10-18 #i35017# - add parameter <_bIterativeAsOnceConcurrent>\n \/\/ to control, if value has to be treated as \n sal_Int16 GetWrapInfluenceOnObjPos(\n const bool _bIterativeAsOnceConcurrent = false ) const;\n \/\/ <--\n};\n\ninline const SwFmtWrapInfluenceOnObjPos& SwAttrSet::GetWrapInfluenceOnObjPos(BOOL bInP) const\n { return (const SwFmtWrapInfluenceOnObjPos&)Get( RES_WRAP_INFLUENCE_ON_OBJPOS,bInP); }\n\n inline const SwFmtWrapInfluenceOnObjPos& SwFmt::GetWrapInfluenceOnObjPos(BOOL bInP) const\n { return aSet.GetWrapInfluenceOnObjPos(bInP); }\n\n#endif\n<|endoftext|>"} {"text":"\/**\n * \\file ConvolutionFilter.cpp\n *\/\n\n#include \"ConvolutionFilter.h\"\n\n#include \n\nnamespace ATK\n{\n template \n ConvolutionFilter::ConvolutionFilter()\n :Parent(1, 1), split_position(0), split_size(0)\n {\n }\n\n template\n void ConvolutionFilter::set_impulse(std::vector impulse)\n {\n this->impulse = std::move(impulse);\n setup();\n }\n \n template\n void ConvolutionFilter::set_split_size(int split_size)\n {\n this->split_size = split_size;\n setup();\n }\n \n template\n void ConvolutionFilter::setup()\n {\n if(impulse.size() == 0 || split_size == 0)\n {\n return;\n }\n\n auto nb_splits = (impulse.size() + split_size - 1) \/ split_size;\n partial_frequency_input.assign(nb_splits - 1, std::vector >(split_size * 2, 0));\n \/\/ Pad with zeros so the convolution is easier created.\n impulse.resize((partial_frequency_input.size() + 1) * split_size, 0);\n\n temp_out_buffer.assign(split_size * 2, 0);\n processor.set_size(split_size * 2);\n \n \/\/ The size is twice as big than the impulse, less\n partial_frequency_impulse.assign(split_size * 2 * (nb_splits - 1), 0);\n for(int i = 1; i < nb_splits; ++i)\n {\n processor.process_forward(impulse.data() + i * split_size, partial_frequency_impulse.data() + (i - 1) * split_size * 2, split_size);\n }\n\n input_delay = split_size - 1;\n \n Parent::setup();\n }\n\n template\n void ConvolutionFilter::compute_convolutions() const\n {\n for(int i = 0; i < split_size; ++i)\n {\n temp_out_buffer[i] = temp_out_buffer[i + split_size];\n temp_out_buffer[i + split_size] = 0;\n }\n \n std::vector > result(2 * split_size, 0);\n const std::complex* ATK_RESTRICT partial_frequency_impulse_ptr = partial_frequency_impulse.data();\n std::complex* ATK_RESTRICT result_ptr = result.data();\n\t\n \/\/ offset in the impulse frequencies\n int64_t offset = 0;\n for(const auto& buffer: partial_frequency_input)\n {\n const std::complex* ATK_RESTRICT buffer_ptr = buffer.data();\n \/\/ Add the frequency result of this partial FFT\n for(int64_t i = 0; i < 2*split_size; ++i)\n {\n result_ptr[i] += buffer_ptr[i] * partial_frequency_impulse_ptr[i + offset];\n }\n offset += 2 * split_size;\n }\n\n std::vector ifft_result(2*split_size, 0);\n processor.process_backward(result.data(), ifft_result.data(), 2*split_size);\n for(int i = 0; i < 2*split_size; ++i)\n {\n temp_out_buffer[i] += ifft_result[i] * split_size * 2;\n }\n }\n\n template\n void ConvolutionFilter::process_new_chunk(int64_t position) const\n {\n if(partial_frequency_input.empty())\n return;\n partial_frequency_input.pop_back();\n std::vector > chunk(2 * split_size);\n processor.process_forward(converted_inputs[0] + position - split_size, chunk.data(), split_size);\n \n partial_frequency_input.push_front(std::move(chunk));\n compute_convolutions();\n }\n\n template\n void ConvolutionFilter::process_impulse_beginning(int64_t processed_size, int64_t size_to_process) const\n {\n const DataType* ATK_RESTRICT input = converted_inputs[0];\n DataType* ATK_RESTRICT output = outputs[0];\n for(int64_t i = 0; i < size_to_process; ++i)\n {\n DataType tempout = temp_out_buffer[split_position + i];\n for(int j = 0; j < input_delay + 1; ++j)\n {\n tempout += impulse[j] * input[processed_size + i - j];\n }\n output[processed_size + i] = tempout;\n }\n }\n\n template\n void ConvolutionFilter::process_impl(int64_t size) const\n {\n assert(input_sampling_rate == output_sampling_rate);\n assert(nb_input_ports == nb_output_ports);\n \n int processed_size = 0;\n do\n {\n \/\/ We can only process split_size elements at a time, but if we already have some elements in the buffer,\n \/\/ we need to take them into account.\n int64_t size_to_process = std::min(split_size - split_position, size - processed_size);\n\n process_impulse_beginning(processed_size, size_to_process);\n\n split_position += size_to_process;\n processed_size += size_to_process;\n if(split_position == split_size)\n {\n process_new_chunk(processed_size);\n split_position = 0;\n }\n }while(processed_size != size);\n }\n\n template class ConvolutionFilter;\n}\nOptimized the impulse processing as well as the complex FMA\/**\n * \\file ConvolutionFilter.cpp\n *\/\n\n#include \"ConvolutionFilter.h\"\n\n#include \n\nnamespace ATK\n{\n template \n ConvolutionFilter::ConvolutionFilter()\n :Parent(1, 1), split_position(0), split_size(0)\n {\n }\n\n template\n void ConvolutionFilter::set_impulse(std::vector impulse)\n {\n this->impulse = std::move(impulse);\n setup();\n }\n \n template\n void ConvolutionFilter::set_split_size(int split_size)\n {\n this->split_size = split_size;\n setup();\n }\n \n template\n void ConvolutionFilter::setup()\n {\n if(impulse.size() == 0 || split_size == 0)\n {\n return;\n }\n\n auto nb_splits = (impulse.size() + split_size - 1) \/ split_size;\n partial_frequency_input.assign(nb_splits - 1, std::vector >(split_size * 2, 0));\n \/\/ Pad with zeros so the convolution is easier created.\n impulse.resize((partial_frequency_input.size() + 1) * split_size, 0);\n\n temp_out_buffer.assign(split_size * 2, 0);\n processor.set_size(split_size * 2);\n \n \/\/ The size is twice as big than the impulse, less\n partial_frequency_impulse.assign(split_size * 2 * (nb_splits - 1), 0);\n for(int i = 1; i < nb_splits; ++i)\n {\n processor.process_forward(impulse.data() + i * split_size, partial_frequency_impulse.data() + (i - 1) * split_size * 2, split_size);\n }\n\n input_delay = split_size - 1;\n \n Parent::setup();\n }\n\n template\n void ConvolutionFilter::compute_convolutions() const\n {\n for(int i = 0; i < split_size; ++i)\n {\n temp_out_buffer[i] = temp_out_buffer[i + split_size];\n temp_out_buffer[i + split_size] = 0;\n }\n \n std::vector > result(2 * split_size, 0);\n const std::complex* ATK_RESTRICT partial_frequency_impulse_ptr = partial_frequency_impulse.data();\n std::complex* ATK_RESTRICT result_ptr = result.data();\n\t\n \/\/ offset in the impulse frequencies\n int64_t offset = 0;\n for(const auto& buffer: partial_frequency_input)\n {\n const std::complex* ATK_RESTRICT buffer_ptr = buffer.data();\n \/\/ Add the frequency result of this partial FFT\n for(int64_t i = 0; i < 2*split_size; ++i)\n {\n DataType br = buffer_ptr[i].real();\n DataType bi = buffer_ptr[i].imag();\n DataType pr = partial_frequency_impulse_ptr[i + offset].real();\n DataType pi = partial_frequency_impulse_ptr[i + offset].imag();\n result_ptr[i] += std::complex(br*pr-bi*pi, br*pi+pr*bi);\n }\n offset += 2 * split_size;\n }\n\n std::vector ifft_result(2*split_size, 0);\n processor.process_backward(result.data(), ifft_result.data(), 2*split_size);\n for(int i = 0; i < 2*split_size; ++i)\n {\n temp_out_buffer[i] += ifft_result[i] * split_size * 2;\n }\n }\n\n template\n void ConvolutionFilter::process_new_chunk(int64_t position) const\n {\n if(partial_frequency_input.empty())\n return;\n partial_frequency_input.pop_back();\n std::vector > chunk(2 * split_size);\n processor.process_forward(converted_inputs[0] + position - split_size, chunk.data(), split_size);\n \n partial_frequency_input.push_front(std::move(chunk));\n compute_convolutions();\n }\n\n template\n void ConvolutionFilter::process_impulse_beginning(int64_t processed_size, int64_t size_to_process) const\n {\n const DataType* ATK_RESTRICT input = converted_inputs[0] + processed_size;\n const DataType* ATK_RESTRICT impulse_ptr = impulse.data();\n DataType* ATK_RESTRICT output = outputs[0] + processed_size;\n\n for(int64_t i = 0; i < size_to_process; ++i)\n {\n output[i] = temp_out_buffer[split_position + i];\n }\n\n for(int j = 0; j < input_delay + 1; ++j)\n {\n for(int64_t i = 0; i < size_to_process; ++i)\n {\n output[i] += impulse_ptr[j] * input[i - j];\n }\n }\n }\n\n template\n void ConvolutionFilter::process_impl(int64_t size) const\n {\n assert(input_sampling_rate == output_sampling_rate);\n assert(nb_input_ports == nb_output_ports);\n \n int processed_size = 0;\n do\n {\n \/\/ We can only process split_size elements at a time, but if we already have some elements in the buffer,\n \/\/ we need to take them into account.\n int64_t size_to_process = std::min(split_size - split_position, size - processed_size);\n\n process_impulse_beginning(processed_size, size_to_process);\n\n split_position += size_to_process;\n processed_size += size_to_process;\n if(split_position == split_size)\n {\n process_new_chunk(processed_size);\n split_position = 0;\n }\n }while(processed_size != size);\n }\n\n template class ConvolutionFilter;\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: txatbase.cxx,v $\n *\n * $Revision: 1.8 $\n *\n * last change: $Author: rt $ $Date: 2005-09-09 05:14:31 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\n#pragma hdrstop\n\n#ifndef _SFXITEMPOOL_HXX\n#include \n#endif\n#ifndef _TXATBASE_HXX\n#include \n#endif\n\nSwTxtAttr::SwTxtAttr( const SfxPoolItem& rAttr, xub_StrLen nStt )\n : pAttr( &rAttr ), nStart( nStt )\n{\n bDontExpand = bLockExpandFlag = bDontMergeAttr = bDontMoveAttr =\n bCharFmtAttr = bOverlapAllowedAttr = bPriorityAttr =\n bDontExpandStart = FALSE;\n}\n\nSwTxtAttr::~SwTxtAttr( )\n{\n}\n\nxub_StrLen* SwTxtAttr::GetEnd()\n{\n return 0;\n}\n\n \/\/ RemoveFromPool muss immer vorm DTOR Aufruf erfolgen!!\n \/\/ Meldet sein Attribut beim Pool ab\nvoid SwTxtAttr::RemoveFromPool( SfxItemPool& rPool )\n{\n rPool.Remove( GetAttr() );\n pAttr = 0;\n}\n\nint SwTxtAttr::operator==( const SwTxtAttr& rAttr ) const\n{\n return GetAttr() == rAttr.GetAttr();\n}\n\nSwTxtAttrEnd::SwTxtAttrEnd( const SfxPoolItem& rAttr, xub_StrLen nS,\n xub_StrLen nE )\n : SwTxtAttr( rAttr, nS ), nEnd( nE )\n{\n}\n\nxub_StrLen* SwTxtAttrEnd::GetEnd()\n{\n return &nEnd;\n}\nINTEGRATION: CWS pchfix02 (1.8.476); FILE MERGED 2006\/09\/01 17:52:13 kaib 1.8.476.1: #i68856# Added header markers and pch files\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: txatbase.cxx,v $\n *\n * $Revision: 1.9 $\n *\n * last change: $Author: obo $ $Date: 2006-09-16 21:47:32 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sw.hxx\"\n\n\n\n#ifndef _SFXITEMPOOL_HXX\n#include \n#endif\n#ifndef _TXATBASE_HXX\n#include \n#endif\n\nSwTxtAttr::SwTxtAttr( const SfxPoolItem& rAttr, xub_StrLen nStt )\n : pAttr( &rAttr ), nStart( nStt )\n{\n bDontExpand = bLockExpandFlag = bDontMergeAttr = bDontMoveAttr =\n bCharFmtAttr = bOverlapAllowedAttr = bPriorityAttr =\n bDontExpandStart = FALSE;\n}\n\nSwTxtAttr::~SwTxtAttr( )\n{\n}\n\nxub_StrLen* SwTxtAttr::GetEnd()\n{\n return 0;\n}\n\n \/\/ RemoveFromPool muss immer vorm DTOR Aufruf erfolgen!!\n \/\/ Meldet sein Attribut beim Pool ab\nvoid SwTxtAttr::RemoveFromPool( SfxItemPool& rPool )\n{\n rPool.Remove( GetAttr() );\n pAttr = 0;\n}\n\nint SwTxtAttr::operator==( const SwTxtAttr& rAttr ) const\n{\n return GetAttr() == rAttr.GetAttr();\n}\n\nSwTxtAttrEnd::SwTxtAttrEnd( const SfxPoolItem& rAttr, xub_StrLen nS,\n xub_StrLen nE )\n : SwTxtAttr( rAttr, nS ), nEnd( nE )\n{\n}\n\nxub_StrLen* SwTxtAttrEnd::GetEnd()\n{\n return &nEnd;\n}\n<|endoftext|>"} {"text":"\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * This file incorporates work covered by the following license notice:\n *\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed\n * with this work for additional information regarding copyright\n * ownership. The ASF licenses this file to you under the Apache\n * License, Version 2.0 (the \"License\"); you may not use this file\n * except in compliance with the License. You may obtain a copy of\n * the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0 .\n *\/\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace ::com::sun::star::i18n;\n\n\nSwScriptIterator::SwScriptIterator( const String& rStr, xub_StrLen nStt, bool bFrwrd )\n : rText( rStr ),\n nChgPos( rStr.Len() ),\n nCurScript( ScriptType::WEAK ),\n bForward( bFrwrd )\n{\n if( pBreakIt->GetBreakIter().is() )\n {\n if ( ! bFrwrd && nStt )\n --nStt;\n\n xub_StrLen nPos = nStt;\n nCurScript = pBreakIt->GetBreakIter()->getScriptType( rText, nPos );\n if( ScriptType::WEAK == nCurScript )\n {\n if( nPos )\n {\n nPos = (xub_StrLen)pBreakIt->GetBreakIter()->beginOfScript(\n rText, nPos, nCurScript );\n if( nPos && nPos < rText.Len() )\n {\n nStt = --nPos;\n nCurScript = pBreakIt->GetBreakIter()->getScriptType( rText,nPos);\n }\n }\n }\n\n nChgPos = bForward ?\n (xub_StrLen)pBreakIt->GetBreakIter()->endOfScript( rText, nStt, nCurScript ) :\n (xub_StrLen)pBreakIt->GetBreakIter()->beginOfScript( rText, nStt, nCurScript );\n }\n}\n\nbool SwScriptIterator::Next()\n{\n bool bRet = false;\n if( pBreakIt->GetBreakIter().is() )\n {\n if ( bForward && nChgPos < rText.Len() )\n {\n nCurScript = pBreakIt->GetBreakIter()->getScriptType( rText, nChgPos );\n nChgPos = (xub_StrLen)pBreakIt->GetBreakIter()->endOfScript(\n rText, nChgPos, nCurScript );\n bRet = true;\n }\n else if ( ! bForward && nChgPos )\n {\n --nChgPos;\n nCurScript = pBreakIt->GetBreakIter()->getScriptType( rText, nChgPos );\n nChgPos = (xub_StrLen)pBreakIt->GetBreakIter()->beginOfScript(\n rText, nChgPos, nCurScript );\n bRet = true;\n }\n }\n else\n nChgPos = rText.Len();\n return bRet;\n}\n\n\/\/ --------------------------------------------------------------------\n\nSwTxtAttrIterator::SwTxtAttrIterator( const SwTxtNode& rTNd, sal_uInt16 nWhchId,\n xub_StrLen nStt,\n bool bUseGetWhichOfScript )\n : aSIter( rTNd.GetTxt(), nStt ), rTxtNd( rTNd ),\n pParaItem( 0 ), nChgPos( nStt ), nAttrPos( 0 ), nWhichId( nWhchId ),\n bIsUseGetWhichOfScript( bUseGetWhichOfScript )\n{\n SearchNextChg();\n}\n\nbool SwTxtAttrIterator::Next()\n{\n bool bRet = false;\n if( nChgPos < aSIter.GetText().Len() )\n {\n bRet = true;\n if( !aStack.empty() )\n {\n do {\n const SwTxtAttr* pHt = aStack.front();\n sal_uInt16 nEndPos = *pHt->GetEnd();\n if( nChgPos >= nEndPos )\n aStack.pop_front();\n else\n break;\n } while( !aStack.empty() );\n }\n\n if( !aStack.empty() )\n {\n sal_uInt16 nSavePos = nAttrPos;\n SearchNextChg();\n if( !aStack.empty() )\n {\n const SwTxtAttr* pHt = aStack.front();\n sal_uInt16 nEndPos = *pHt->GetEnd();\n if( nChgPos >= nEndPos )\n {\n nChgPos = nEndPos;\n nAttrPos = nSavePos;\n\n if( RES_TXTATR_CHARFMT == pHt->Which() )\n {\n sal_uInt16 nWId = bIsUseGetWhichOfScript ?\n GetWhichOfScript( nWhichId,\n aSIter.GetCurrScript() ) : nWhichId;\n pCurItem = &pHt->GetCharFmt().GetCharFmt()->GetFmtAttr(nWId);\n }\n else\n pCurItem = &pHt->GetAttr();\n\n aStack.pop_front();\n }\n }\n }\n else\n SearchNextChg();\n }\n return bRet;\n}\n\nvoid SwTxtAttrIterator::AddToStack( const SwTxtAttr& rAttr )\n{\n sal_uInt16 nIns = 0, nEndPos = *rAttr.GetEnd();\n for( ; nIns < aStack.size(); ++nIns )\n if( *aStack[ nIns ]->GetEnd() > nEndPos )\n break;\n\n aStack.insert( aStack.begin() + nIns, &rAttr );\n}\n\nvoid SwTxtAttrIterator::SearchNextChg()\n{\n sal_uInt16 nWh = 0;\n if( nChgPos == aSIter.GetScriptChgPos() )\n {\n aSIter.Next();\n pParaItem = 0;\n nAttrPos = 0; \/\/ must be restart at the beginning, because\n \/\/ some attributes can start before or inside\n \/\/ the current scripttype!\n aStack.clear();\n }\n if( !pParaItem )\n {\n nWh = bIsUseGetWhichOfScript ?\n GetWhichOfScript( nWhichId,\n aSIter.GetCurrScript() ) : nWhichId;\n pParaItem = &rTxtNd.GetSwAttrSet().Get( nWh );\n }\n\n xub_StrLen nStt = nChgPos;\n nChgPos = aSIter.GetScriptChgPos();\n pCurItem = pParaItem;\n\n const SwpHints* pHts = rTxtNd.GetpSwpHints();\n if( pHts )\n {\n if( !nWh )\n {\n nWh = bIsUseGetWhichOfScript ?\n GetWhichOfScript( nWhichId,\n aSIter.GetCurrScript() ) : nWhichId;\n }\n\n const SfxPoolItem* pItem = 0;\n for( ; nAttrPos < pHts->Count(); ++nAttrPos )\n {\n const SwTxtAttr* pHt = (*pHts)[ nAttrPos ];\n const sal_uInt16* pEnd = pHt->GetEnd();\n const sal_uInt16 nHtStt = *pHt->GetStart();\n if( nHtStt < nStt && ( !pEnd || *pEnd <= nStt ))\n continue;\n\n if( nHtStt >= nChgPos )\n break;\n\n pItem = CharFmt::GetItem( *pHt, nWh );\n if ( pItem )\n {\n if( nHtStt > nStt )\n {\n if( nChgPos > nHtStt )\n nChgPos = nHtStt;\n break;\n }\n AddToStack( *pHt );\n pCurItem = pItem;\n if( *pEnd < nChgPos )\n nChgPos = *pEnd;\n }\n }\n }\n}\n\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\nremove unnecessary #include\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * This file incorporates work covered by the following license notice:\n *\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed\n * with this work for additional information regarding copyright\n * ownership. The ASF licenses this file to you under the Apache\n * License, Version 2.0 (the \"License\"); you may not use this file\n * except in compliance with the License. You may obtain a copy of\n * the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0 .\n *\/\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace ::com::sun::star::i18n;\n\n\nSwScriptIterator::SwScriptIterator( const String& rStr, xub_StrLen nStt, bool bFrwrd )\n : rText( rStr ),\n nChgPos( rStr.Len() ),\n nCurScript( ScriptType::WEAK ),\n bForward( bFrwrd )\n{\n if( pBreakIt->GetBreakIter().is() )\n {\n if ( ! bFrwrd && nStt )\n --nStt;\n\n xub_StrLen nPos = nStt;\n nCurScript = pBreakIt->GetBreakIter()->getScriptType( rText, nPos );\n if( ScriptType::WEAK == nCurScript )\n {\n if( nPos )\n {\n nPos = (xub_StrLen)pBreakIt->GetBreakIter()->beginOfScript(\n rText, nPos, nCurScript );\n if( nPos && nPos < rText.Len() )\n {\n nStt = --nPos;\n nCurScript = pBreakIt->GetBreakIter()->getScriptType( rText,nPos);\n }\n }\n }\n\n nChgPos = bForward ?\n (xub_StrLen)pBreakIt->GetBreakIter()->endOfScript( rText, nStt, nCurScript ) :\n (xub_StrLen)pBreakIt->GetBreakIter()->beginOfScript( rText, nStt, nCurScript );\n }\n}\n\nbool SwScriptIterator::Next()\n{\n bool bRet = false;\n if( pBreakIt->GetBreakIter().is() )\n {\n if ( bForward && nChgPos < rText.Len() )\n {\n nCurScript = pBreakIt->GetBreakIter()->getScriptType( rText, nChgPos );\n nChgPos = (xub_StrLen)pBreakIt->GetBreakIter()->endOfScript(\n rText, nChgPos, nCurScript );\n bRet = true;\n }\n else if ( ! bForward && nChgPos )\n {\n --nChgPos;\n nCurScript = pBreakIt->GetBreakIter()->getScriptType( rText, nChgPos );\n nChgPos = (xub_StrLen)pBreakIt->GetBreakIter()->beginOfScript(\n rText, nChgPos, nCurScript );\n bRet = true;\n }\n }\n else\n nChgPos = rText.Len();\n return bRet;\n}\n\n\/\/ --------------------------------------------------------------------\n\nSwTxtAttrIterator::SwTxtAttrIterator( const SwTxtNode& rTNd, sal_uInt16 nWhchId,\n xub_StrLen nStt,\n bool bUseGetWhichOfScript )\n : aSIter( rTNd.GetTxt(), nStt ), rTxtNd( rTNd ),\n pParaItem( 0 ), nChgPos( nStt ), nAttrPos( 0 ), nWhichId( nWhchId ),\n bIsUseGetWhichOfScript( bUseGetWhichOfScript )\n{\n SearchNextChg();\n}\n\nbool SwTxtAttrIterator::Next()\n{\n bool bRet = false;\n if( nChgPos < aSIter.GetText().Len() )\n {\n bRet = true;\n if( !aStack.empty() )\n {\n do {\n const SwTxtAttr* pHt = aStack.front();\n sal_uInt16 nEndPos = *pHt->GetEnd();\n if( nChgPos >= nEndPos )\n aStack.pop_front();\n else\n break;\n } while( !aStack.empty() );\n }\n\n if( !aStack.empty() )\n {\n sal_uInt16 nSavePos = nAttrPos;\n SearchNextChg();\n if( !aStack.empty() )\n {\n const SwTxtAttr* pHt = aStack.front();\n sal_uInt16 nEndPos = *pHt->GetEnd();\n if( nChgPos >= nEndPos )\n {\n nChgPos = nEndPos;\n nAttrPos = nSavePos;\n\n if( RES_TXTATR_CHARFMT == pHt->Which() )\n {\n sal_uInt16 nWId = bIsUseGetWhichOfScript ?\n GetWhichOfScript( nWhichId,\n aSIter.GetCurrScript() ) : nWhichId;\n pCurItem = &pHt->GetCharFmt().GetCharFmt()->GetFmtAttr(nWId);\n }\n else\n pCurItem = &pHt->GetAttr();\n\n aStack.pop_front();\n }\n }\n }\n else\n SearchNextChg();\n }\n return bRet;\n}\n\nvoid SwTxtAttrIterator::AddToStack( const SwTxtAttr& rAttr )\n{\n sal_uInt16 nIns = 0, nEndPos = *rAttr.GetEnd();\n for( ; nIns < aStack.size(); ++nIns )\n if( *aStack[ nIns ]->GetEnd() > nEndPos )\n break;\n\n aStack.insert( aStack.begin() + nIns, &rAttr );\n}\n\nvoid SwTxtAttrIterator::SearchNextChg()\n{\n sal_uInt16 nWh = 0;\n if( nChgPos == aSIter.GetScriptChgPos() )\n {\n aSIter.Next();\n pParaItem = 0;\n nAttrPos = 0; \/\/ must be restart at the beginning, because\n \/\/ some attributes can start before or inside\n \/\/ the current scripttype!\n aStack.clear();\n }\n if( !pParaItem )\n {\n nWh = bIsUseGetWhichOfScript ?\n GetWhichOfScript( nWhichId,\n aSIter.GetCurrScript() ) : nWhichId;\n pParaItem = &rTxtNd.GetSwAttrSet().Get( nWh );\n }\n\n xub_StrLen nStt = nChgPos;\n nChgPos = aSIter.GetScriptChgPos();\n pCurItem = pParaItem;\n\n const SwpHints* pHts = rTxtNd.GetpSwpHints();\n if( pHts )\n {\n if( !nWh )\n {\n nWh = bIsUseGetWhichOfScript ?\n GetWhichOfScript( nWhichId,\n aSIter.GetCurrScript() ) : nWhichId;\n }\n\n const SfxPoolItem* pItem = 0;\n for( ; nAttrPos < pHts->Count(); ++nAttrPos )\n {\n const SwTxtAttr* pHt = (*pHts)[ nAttrPos ];\n const sal_uInt16* pEnd = pHt->GetEnd();\n const sal_uInt16 nHtStt = *pHt->GetStart();\n if( nHtStt < nStt && ( !pEnd || *pEnd <= nStt ))\n continue;\n\n if( nHtStt >= nChgPos )\n break;\n\n pItem = CharFmt::GetItem( *pHt, nWh );\n if ( pItem )\n {\n if( nHtStt > nStt )\n {\n if( nChgPos > nHtStt )\n nChgPos = nHtStt;\n break;\n }\n AddToStack( *pHt );\n pCurItem = pItem;\n if( *pEnd < nChgPos )\n nChgPos = *pEnd;\n }\n }\n }\n}\n\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<|endoftext|>"} {"text":"\/* database.cpp\n *\n * Copyright (C) 2012 Matthias Klumpp\n *\n * Licensed under the GNU General Public License Version 3\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n *\/\n\n#include \"database.hpp\"\n\n#include \n#include \n#include \n\nusing namespace std;\n\nDatabase::Database () :\n m_rwXapianDB(0)\n{\n\n}\n\nDatabase::~Database ()\n{\n\tif (m_rwXapianDB) {\n\t\tdelete m_rwXapianDB;\n\t}\n}\n\nbool Database::init (const gchar *dbPath)\n{\n\tm_dbPath = dbPath;\n\n\ttry {\n\t\tm_rwXapianDB = new Xapian::WritableDatabase (m_dbPath,\n\t\t\t\t\t\t\t Xapian::DB_CREATE_OR_OPEN);\n\t} catch (const Xapian::Error &error) {\n\t\tcout << \"ERROR!\" << endl;\n\t\tg_warning (\"Exception: %s\", error.get_msg ().c_str ());\n\t\treturn false;\n\t}\n\n\treturn true;\n}\n\nbool Database::rebuild (GArray *apps)\n{\n\tstring old_path = m_dbPath + \"_old\";\n\tstring rebuild_path = m_dbPath + \"_rb\";\n\n\t\/\/ Create the rebuild directory\n\tif (!uai_utils_touch_dir (rebuild_path.c_str ()))\n\t\treturn false;\n\n\t\/\/ check if old unrequired version of db still exists on filesystem\n\tif (g_file_test (old_path.c_str (), G_FILE_TEST_EXISTS)) {\n\t\tg_warning (\"Existing xapian old db was not previously cleaned: '%s'.\", old_path.c_str ());\n\t\tuai_utils_delete_dir_recursive (old_path.c_str ());\n\t}\n\n\t\/\/ check if old unrequired version of db still exists on filesystem\n\tif (g_file_test (rebuild_path.c_str (), G_FILE_TEST_EXISTS)) {\n\t\tcout << \"Removing old rebuild-dir from previous database rebuild.\" << endl;\n\t\tuai_utils_delete_dir_recursive (rebuild_path.c_str ());\n\t}\n\n\tXapian::WritableDatabase db (rebuild_path, Xapian::DB_CREATE_OR_OVERWRITE);\n\n\tXapian::TermGenerator term_generator;\n\tterm_generator.set_database(db);\n\ttry {\n\t\t\/* this tests if we have spelling suggestions (there must be\n\t\t * a better way?!?) - this is needed as inmemory does not have\n\t\t * spelling corrections, but it allows setting the flag and will\n\t\t * raise a exception much later\n\t\t *\/\n\t\tdb.add_spelling(\"test\");\n\t\tdb.remove_spelling(\"test\");\n\n\t\t\/* this enables the flag for it (we only reach this line if\n\t\t * the db supports spelling suggestions)\n\t\t *\/\n\t\tterm_generator.set_flags(Xapian::TermGenerator::FLAG_SPELLING);\n\t} catch (const Xapian::UnimplementedError &error) {\n\t\t\/\/ Ignore\n\t}\n\n\tfor (guint i=0; i < apps->len; i++) {\n\t\tUaiAppInfo *app = g_array_index (apps, UaiAppInfo*, i);\n\n\t\tXapian::Document doc;\n\n\t\tcout << \"Adding application: \" << uai_app_info_to_string (app) << endl;\n\n\t\tdoc.set_data (uai_app_info_get_name (app));\n\n\t\tdoc.add_value (APPNAME_UNTRANSLATED, uai_app_info_get_name_original (app));\n\t\tdoc.add_value (PKGNAME, uai_app_info_get_pkgname (app));\n\t\tdoc.add_value (DESKTOP_FILE, uai_app_info_get_desktop_file (app));\n\t\tdoc.add_value (SUPPORT_SITE_URL, uai_app_info_get_url (app));\n\t\tdoc.add_value (ICON, uai_app_info_get_icon (app));\n\t\tdoc.add_value (CATEGORIES, uai_app_info_get_categories (app));\n\t\tdoc.add_value (SUMMARY, uai_app_info_get_summary (app));\n\t\tdoc.add_value (SC_DESCRIPTION, uai_app_info_get_description (app));\n\t\t\/\/ TODO: Register more values and add TERMs\n\n\t\tterm_generator.set_document (doc);\n\n\t\t\/\/ TODO: Register terms\n\n\t\tdb.add_document (doc);\n\n\t}\n\n\tdb.set_metadata(\"db-schema-version\", DB_SCHEMA_VERSION);\n\tdb.flush ();\n\n\treturn true;\n}\n\nbool Database::addApplication (UaiAppInfo *app)\n{\n\t\/\/ TODO\n\treturn false;\n}\nMove Xapian DB to correct path\/* database.cpp\n *\n * Copyright (C) 2012 Matthias Klumpp\n *\n * Licensed under the GNU General Public License Version 3\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n *\/\n\n#include \"database.hpp\"\n\n#include \n#include \n#include \n#include \n\nusing namespace std;\n\nDatabase::Database () :\n m_rwXapianDB(0)\n{\n\n}\n\nDatabase::~Database ()\n{\n\tif (m_rwXapianDB) {\n\t\tdelete m_rwXapianDB;\n\t}\n}\n\nbool Database::init (const gchar *dbPath)\n{\n\tm_dbPath = dbPath;\n\n\ttry {\n\t\tm_rwXapianDB = new Xapian::WritableDatabase (m_dbPath,\n\t\t\t\t\t\t\t Xapian::DB_CREATE_OR_OPEN);\n\t} catch (const Xapian::Error &error) {\n\t\tcout << \"ERROR!\" << endl;\n\t\tg_warning (\"Exception: %s\", error.get_msg ().c_str ());\n\t\treturn false;\n\t}\n\n\treturn true;\n}\n\nbool Database::rebuild (GArray *apps)\n{\n\tstring old_path = m_dbPath + \"_old\";\n\tstring rebuild_path = m_dbPath + \"_rb\";\n\n\t\/\/ Create the rebuild directory\n\tif (!uai_utils_touch_dir (rebuild_path.c_str ()))\n\t\treturn false;\n\n\t\/\/ check if old unrequired version of db still exists on filesystem\n\tif (g_file_test (old_path.c_str (), G_FILE_TEST_EXISTS)) {\n\t\tg_warning (\"Existing xapian old db was not previously cleaned: '%s'.\", old_path.c_str ());\n\t\tuai_utils_delete_dir_recursive (old_path.c_str ());\n\t}\n\n\t\/\/ check if old unrequired version of db still exists on filesystem\n\tif (g_file_test (rebuild_path.c_str (), G_FILE_TEST_EXISTS)) {\n\t\tcout << \"Removing old rebuild-dir from previous database rebuild.\" << endl;\n\t\tuai_utils_delete_dir_recursive (rebuild_path.c_str ());\n\t}\n\n\tXapian::WritableDatabase db (rebuild_path, Xapian::DB_CREATE_OR_OVERWRITE);\n\n\tXapian::TermGenerator term_generator;\n\tterm_generator.set_database(db);\n\ttry {\n\t\t\/* this tests if we have spelling suggestions (there must be\n\t\t * a better way?!?) - this is needed as inmemory does not have\n\t\t * spelling corrections, but it allows setting the flag and will\n\t\t * raise a exception much later\n\t\t *\/\n\t\tdb.add_spelling(\"test\");\n\t\tdb.remove_spelling(\"test\");\n\n\t\t\/* this enables the flag for it (we only reach this line if\n\t\t * the db supports spelling suggestions)\n\t\t *\/\n\t\tterm_generator.set_flags(Xapian::TermGenerator::FLAG_SPELLING);\n\t} catch (const Xapian::UnimplementedError &error) {\n\t\t\/\/ Ignore\n\t}\n\n\tfor (guint i=0; i < apps->len; i++) {\n\t\tUaiAppInfo *app = g_array_index (apps, UaiAppInfo*, i);\n\n\t\tXapian::Document doc;\n\n\t\tcout << \"Adding application: \" << uai_app_info_to_string (app) << endl;\n\n\t\tdoc.set_data (uai_app_info_get_name (app));\n\n\t\tdoc.add_value (APPNAME_UNTRANSLATED, uai_app_info_get_name_original (app));\n\t\tdoc.add_value (PKGNAME, uai_app_info_get_pkgname (app));\n\t\tdoc.add_value (DESKTOP_FILE, uai_app_info_get_desktop_file (app));\n\t\tdoc.add_value (SUPPORT_SITE_URL, uai_app_info_get_url (app));\n\t\tdoc.add_value (ICON, uai_app_info_get_icon (app));\n\t\tdoc.add_value (CATEGORIES, uai_app_info_get_categories (app));\n\t\tdoc.add_value (SUMMARY, uai_app_info_get_summary (app));\n\t\tdoc.add_value (SC_DESCRIPTION, uai_app_info_get_description (app));\n\t\t\/\/ TODO: Register more values and add TERMs\n\n\t\tterm_generator.set_document (doc);\n\n\t\t\/\/ TODO: Register terms\n\n\t\tdb.add_document (doc);\n\n\t}\n\n\tdb.set_metadata(\"db-schema-version\", DB_SCHEMA_VERSION);\n\tdb.flush ();\n\n\tif (g_rename (m_dbPath.c_str (), old_path.c_str ()) < 0) {\n\t\tg_critical (\"Error while moving old database out of the way.\");\n\t\treturn false;\n\t}\n\tif (g_rename (rebuild_path.c_str (), m_dbPath.c_str ()) < 0) {\n\t\tg_critical (\"Error while moving rebuilt database.\");\n\t\treturn false;\n\t}\n\tuai_utils_delete_dir_recursive (old_path.c_str ());\n\n\treturn true;\n}\n\nbool Database::addApplication (UaiAppInfo *app)\n{\n\t\/\/ TODO\n\treturn false;\n}\n<|endoftext|>"} {"text":"\/*=========================================================================\n *\n * Copyright RTK Consortium\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *=========================================================================*\/\n\n#include \"rtkfdk_ggo.h\"\n#include \"rtkGgoFunctions.h\"\n#include \"rtkConfiguration.h\"\n\n#include \"rtkThreeDCircularProjectionGeometryXMLFile.h\"\n#include \"rtkDisplacedDetectorImageFilter.h\"\n#include \"rtkParkerShortScanImageFilter.h\"\n#include \"rtkFDKConeBeamReconstructionFilter.h\"\n#ifdef RTK_USE_CUDA\n# include \"rtkCudaFDKConeBeamReconstructionFilter.h\"\n#endif\n#ifdef RTK_USE_OPENCL\n# include \"rtkOpenCLFDKConeBeamReconstructionFilter.h\"\n#endif\n#include \"rtkFDKWarpBackProjectionImageFilter.h\"\n#include \"rtkCyclicDeformationImageFilter.h\"\n\n#include \n#include \n\nint main(int argc, char * argv[])\n{\n GGO(rtkfdk, args_info);\n\n typedef float OutputPixelType;\n const unsigned int Dimension = 3;\n\n typedef itk::Image< OutputPixelType, Dimension > CPUOutputImageType;\n#ifdef RTK_USE_CUDA\n typedef itk::CudaImage< OutputPixelType, Dimension > OutputImageType;\n#else\n typedef CPUOutputImageType OutputImageType;\n#endif\n\n \/\/ Projections reader\n typedef rtk::ProjectionsReader< OutputImageType > ReaderType;\n ReaderType::Pointer reader = ReaderType::New();\n rtk::SetProjectionsReaderFromGgo(reader, args_info);\n\n itk::TimeProbe readerProbe;\n if(!args_info.lowmem_flag)\n {\n if(args_info.verbose_flag)\n std::cout << \"Reading... \" << std::flush;\n readerProbe.Start();\n TRY_AND_EXIT_ON_ITK_EXCEPTION( reader->Update() )\n readerProbe.Stop();\n if(args_info.verbose_flag)\n std::cout << \"It took \" << readerProbe.GetMean() << ' ' << readerProbe.GetUnit() << std::endl;\n }\n\n \/\/ Geometry\n if(args_info.verbose_flag)\n std::cout << \"Reading geometry information from \"\n << args_info.geometry_arg\n << \"...\"\n << std::endl;\n rtk::ThreeDCircularProjectionGeometryXMLFileReader::Pointer geometryReader;\n geometryReader = rtk::ThreeDCircularProjectionGeometryXMLFileReader::New();\n geometryReader->SetFilename(args_info.geometry_arg);\n TRY_AND_EXIT_ON_ITK_EXCEPTION( geometryReader->GenerateOutputInformation() )\n\n \/\/ Displaced detector weighting\n typedef rtk::DisplacedDetectorImageFilter< OutputImageType > DDFType;\n DDFType::Pointer ddf = DDFType::New();\n ddf->SetInput( reader->GetOutput() );\n ddf->SetGeometry( geometryReader->GetOutputObject() );\n\n \/\/ Short scan image filter\n typedef rtk::ParkerShortScanImageFilter< OutputImageType > PSSFType;\n PSSFType::Pointer pssf = PSSFType::New();\n pssf->SetInput( ddf->GetOutput() );\n pssf->SetGeometry( geometryReader->GetOutputObject() );\n pssf->InPlaceOff();\n\n \/\/ Create reconstructed image\n typedef rtk::ConstantImageSource< OutputImageType > ConstantImageSourceType;\n ConstantImageSourceType::Pointer constantImageSource = ConstantImageSourceType::New();\n rtk::SetConstantImageSourceFromGgo(constantImageSource, args_info);\n\n \/\/ Motion-compensated objects for the compensation of a cyclic deformation.\n \/\/ Although these will only be used if the command line options for motion\n \/\/ compensation are set, we still create the object before hand to avoid auto\n \/\/ destruction.\n typedef itk::Vector DVFPixelType;\n typedef itk::Image< DVFPixelType, 3 > DVFImageType;\n typedef rtk::CyclicDeformationImageFilter< DVFImageType > DeformationType;\n typedef itk::ImageFileReader DVFReaderType;\n DVFReaderType::Pointer dvfReader = DVFReaderType::New();\n DeformationType::Pointer def = DeformationType::New();\n def->SetInput(dvfReader->GetOutput());\n typedef rtk::FDKWarpBackProjectionImageFilter WarpBPType;\n WarpBPType::Pointer bp = WarpBPType::New();\n bp->SetDeformation(def);\n bp->SetGeometry( geometryReader->GetOutputObject() );\n\n \/\/ This macro sets options for fdk filter which I can not see how to do better\n \/\/ because TFFTPrecision is not the same, e.g. for CPU and CUDA (SR)\n#define SET_FELDKAMP_OPTIONS(f) \\\n f->SetInput( 0, constantImageSource->GetOutput() ); \\\n f->SetInput( 1, pssf->GetOutput() ); \\\n f->SetGeometry( geometryReader->GetOutputObject() ); \\\n f->GetRampFilter()->SetTruncationCorrection(args_info.pad_arg); \\\n f->GetRampFilter()->SetHannCutFrequency(args_info.hann_arg); \\\n f->GetRampFilter()->SetHannCutFrequencyY(args_info.hannY_arg); \\\n f->SetProjectionSubsetSize(args_info.subsetsize_arg)\n\n \/\/ FDK reconstruction filtering\n typedef rtk::FDKConeBeamReconstructionFilter< OutputImageType > FDKCPUType;\n FDKCPUType::Pointer feldkamp = FDKCPUType::New();\n#ifdef RTK_USE_OPENCL\n typedef rtk::OpenCLFDKConeBeamReconstructionFilter FDKOPENCLType;\n FDKOPENCLType::Pointer feldkampOCL = FDKOPENCLType::New();\n#endif\n#ifdef RTK_USE_CUDA\n typedef rtk::CudaFDKConeBeamReconstructionFilter FDKCUDAType;\n FDKCUDAType::Pointer feldkampCUDA = FDKCUDAType::New();\n#endif\n itk::Image< OutputPixelType, Dimension > *pfeldkamp = NULL;\n if(!strcmp(args_info.hardware_arg, \"cpu\") )\n {\n typedef rtk::FDKConeBeamReconstructionFilter< OutputImageType > FDKCPUType;\n feldkamp = FDKCPUType::New();\n SET_FELDKAMP_OPTIONS( feldkamp );\n\n \/\/ Motion compensated CBCT settings\n if(args_info.signal_given && args_info.dvf_given)\n {\n dvfReader->SetFileName(args_info.dvf_arg);\n def->SetSignalFilename(args_info.signal_arg);\n feldkamp->SetBackProjectionFilter( bp.GetPointer() );\n }\n pfeldkamp = feldkamp->GetOutput();\n }\n else if(!strcmp(args_info.hardware_arg, \"cuda\") )\n {\n#ifdef RTK_USE_CUDA\n SET_FELDKAMP_OPTIONS( feldkampCUDA );\n pfeldkamp = feldkampCUDA->GetOutput();\n#else\n std::cerr << \"The program has not been compiled with cuda option\" << std::endl;\n return EXIT_FAILURE;\n#endif\n }\n else if(!strcmp(args_info.hardware_arg, \"opencl\") )\n {\n#ifdef RTK_USE_OPENCL\n SET_FELDKAMP_OPTIONS( feldkampOCL );\n pfeldkamp = feldkampOCL->GetOutput();\n#else\n std::cerr << \"The program has not been compiled with opencl option\" << std::endl;\n return EXIT_FAILURE;\n#endif\n }\n\n\n \/\/ Streaming depending on streaming capability of writer\n typedef itk::StreamingImageFilter StreamerType;\n StreamerType::Pointer streamerBP = StreamerType::New();\n streamerBP->SetInput( pfeldkamp );\n streamerBP->SetNumberOfStreamDivisions( args_info.divisions_arg );\n\n \/\/ Write\n typedef itk::ImageFileWriter WriterType;\n WriterType::Pointer writer = WriterType::New();\n writer->SetFileName( args_info.output_arg );\n writer->SetInput( streamerBP->GetOutput() );\n\n if(args_info.verbose_flag)\n std::cout << \"Reconstructing and writing... \" << std::flush;\n itk::TimeProbe writerProbe;\n\n writerProbe.Start();\n TRY_AND_EXIT_ON_ITK_EXCEPTION( writer->Update() );\n writerProbe.Stop();\n\n if(args_info.verbose_flag)\n {\n std::cout << \"It took \" << writerProbe.GetMean() << ' ' << readerProbe.GetUnit() << std::endl;\n if(!strcmp(args_info.hardware_arg, \"cpu\") )\n feldkamp->PrintTiming(std::cout);\n#ifdef RTK_USE_CUDA\n else if(!strcmp(args_info.hardware_arg, \"cuda\") )\n feldkampCUDA->PrintTiming(std::cout);\n#endif\n#ifdef RTK_USE_OPENCL\n else if(!strcmp(args_info.hardware_arg, \"opencl\") )\n feldkampOCL->PrintTiming(std::cout);\n#endif\n std::cout << std::endl;\n }\n\n return EXIT_SUCCESS;\n}\nRemove unnecessary New() and typedef of FDK recon filters\/*=========================================================================\n *\n * Copyright RTK Consortium\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *=========================================================================*\/\n\n#include \"rtkfdk_ggo.h\"\n#include \"rtkGgoFunctions.h\"\n#include \"rtkConfiguration.h\"\n\n#include \"rtkThreeDCircularProjectionGeometryXMLFile.h\"\n#include \"rtkDisplacedDetectorImageFilter.h\"\n#include \"rtkParkerShortScanImageFilter.h\"\n#include \"rtkFDKConeBeamReconstructionFilter.h\"\n#ifdef RTK_USE_CUDA\n# include \"rtkCudaFDKConeBeamReconstructionFilter.h\"\n#endif\n#ifdef RTK_USE_OPENCL\n# include \"rtkOpenCLFDKConeBeamReconstructionFilter.h\"\n#endif\n#include \"rtkFDKWarpBackProjectionImageFilter.h\"\n#include \"rtkCyclicDeformationImageFilter.h\"\n\n#include \n#include \n\nint main(int argc, char * argv[])\n{\n GGO(rtkfdk, args_info);\n\n typedef float OutputPixelType;\n const unsigned int Dimension = 3;\n\n typedef itk::Image< OutputPixelType, Dimension > CPUOutputImageType;\n#ifdef RTK_USE_CUDA\n typedef itk::CudaImage< OutputPixelType, Dimension > OutputImageType;\n#else\n typedef CPUOutputImageType OutputImageType;\n#endif\n\n \/\/ Projections reader\n typedef rtk::ProjectionsReader< OutputImageType > ReaderType;\n ReaderType::Pointer reader = ReaderType::New();\n rtk::SetProjectionsReaderFromGgo(reader, args_info);\n\n itk::TimeProbe readerProbe;\n if(!args_info.lowmem_flag)\n {\n if(args_info.verbose_flag)\n std::cout << \"Reading... \" << std::flush;\n readerProbe.Start();\n TRY_AND_EXIT_ON_ITK_EXCEPTION( reader->Update() )\n readerProbe.Stop();\n if(args_info.verbose_flag)\n std::cout << \"It took \" << readerProbe.GetMean() << ' ' << readerProbe.GetUnit() << std::endl;\n }\n\n \/\/ Geometry\n if(args_info.verbose_flag)\n std::cout << \"Reading geometry information from \"\n << args_info.geometry_arg\n << \"...\"\n << std::endl;\n rtk::ThreeDCircularProjectionGeometryXMLFileReader::Pointer geometryReader;\n geometryReader = rtk::ThreeDCircularProjectionGeometryXMLFileReader::New();\n geometryReader->SetFilename(args_info.geometry_arg);\n TRY_AND_EXIT_ON_ITK_EXCEPTION( geometryReader->GenerateOutputInformation() )\n\n \/\/ Displaced detector weighting\n typedef rtk::DisplacedDetectorImageFilter< OutputImageType > DDFType;\n DDFType::Pointer ddf = DDFType::New();\n ddf->SetInput( reader->GetOutput() );\n ddf->SetGeometry( geometryReader->GetOutputObject() );\n\n \/\/ Short scan image filter\n typedef rtk::ParkerShortScanImageFilter< OutputImageType > PSSFType;\n PSSFType::Pointer pssf = PSSFType::New();\n pssf->SetInput( ddf->GetOutput() );\n pssf->SetGeometry( geometryReader->GetOutputObject() );\n pssf->InPlaceOff();\n\n \/\/ Create reconstructed image\n typedef rtk::ConstantImageSource< OutputImageType > ConstantImageSourceType;\n ConstantImageSourceType::Pointer constantImageSource = ConstantImageSourceType::New();\n rtk::SetConstantImageSourceFromGgo(constantImageSource, args_info);\n\n \/\/ Motion-compensated objects for the compensation of a cyclic deformation.\n \/\/ Although these will only be used if the command line options for motion\n \/\/ compensation are set, we still create the object before hand to avoid auto\n \/\/ destruction.\n typedef itk::Vector DVFPixelType;\n typedef itk::Image< DVFPixelType, 3 > DVFImageType;\n typedef rtk::CyclicDeformationImageFilter< DVFImageType > DeformationType;\n typedef itk::ImageFileReader DVFReaderType;\n DVFReaderType::Pointer dvfReader = DVFReaderType::New();\n DeformationType::Pointer def = DeformationType::New();\n def->SetInput(dvfReader->GetOutput());\n typedef rtk::FDKWarpBackProjectionImageFilter WarpBPType;\n WarpBPType::Pointer bp = WarpBPType::New();\n bp->SetDeformation(def);\n bp->SetGeometry( geometryReader->GetOutputObject() );\n\n \/\/ This macro sets options for fdk filter which I can not see how to do better\n \/\/ because TFFTPrecision is not the same, e.g. for CPU and CUDA (SR)\n#define SET_FELDKAMP_OPTIONS(f) \\\n f->SetInput( 0, constantImageSource->GetOutput() ); \\\n f->SetInput( 1, pssf->GetOutput() ); \\\n f->SetGeometry( geometryReader->GetOutputObject() ); \\\n f->GetRampFilter()->SetTruncationCorrection(args_info.pad_arg); \\\n f->GetRampFilter()->SetHannCutFrequency(args_info.hann_arg); \\\n f->GetRampFilter()->SetHannCutFrequencyY(args_info.hannY_arg); \\\n f->SetProjectionSubsetSize(args_info.subsetsize_arg)\n\n \/\/ FDK reconstruction filtering\n typedef rtk::FDKConeBeamReconstructionFilter< OutputImageType > FDKCPUType;\n FDKCPUType::Pointer feldkamp;\n#ifdef RTK_USE_OPENCL\n typedef rtk::OpenCLFDKConeBeamReconstructionFilter FDKOPENCLType;\n FDKOPENCLType::Pointer feldkampOCL;\n#endif\n#ifdef RTK_USE_CUDA\n typedef rtk::CudaFDKConeBeamReconstructionFilter FDKCUDAType;\n FDKCUDAType::Pointer feldkampCUDA;\n#endif\n itk::Image< OutputPixelType, Dimension > *pfeldkamp = NULL;\n if(!strcmp(args_info.hardware_arg, \"cpu\") )\n {\n feldkamp = FDKCPUType::New();\n SET_FELDKAMP_OPTIONS( feldkamp );\n\n \/\/ Motion compensated CBCT settings\n if(args_info.signal_given && args_info.dvf_given)\n {\n dvfReader->SetFileName(args_info.dvf_arg);\n def->SetSignalFilename(args_info.signal_arg);\n feldkamp->SetBackProjectionFilter( bp.GetPointer() );\n }\n pfeldkamp = feldkamp->GetOutput();\n }\n else if(!strcmp(args_info.hardware_arg, \"cuda\") )\n {\n#ifdef RTK_USE_CUDA\n feldkampCUDA = FDKCUDAType::New();\n SET_FELDKAMP_OPTIONS( feldkampCUDA );\n pfeldkamp = feldkampCUDA->GetOutput();\n#else\n std::cerr << \"The program has not been compiled with cuda option\" << std::endl;\n return EXIT_FAILURE;\n#endif\n }\n else if(!strcmp(args_info.hardware_arg, \"opencl\") )\n {\n#ifdef RTK_USE_OPENCL\n feldkampOCL = FDKOPENCLType::New();\n SET_FELDKAMP_OPTIONS( feldkampOCL );\n pfeldkamp = feldkampOCL->GetOutput();\n#else\n std::cerr << \"The program has not been compiled with opencl option\" << std::endl;\n return EXIT_FAILURE;\n#endif\n }\n\n\n \/\/ Streaming depending on streaming capability of writer\n typedef itk::StreamingImageFilter StreamerType;\n StreamerType::Pointer streamerBP = StreamerType::New();\n streamerBP->SetInput( pfeldkamp );\n streamerBP->SetNumberOfStreamDivisions( args_info.divisions_arg );\n\n \/\/ Write\n typedef itk::ImageFileWriter WriterType;\n WriterType::Pointer writer = WriterType::New();\n writer->SetFileName( args_info.output_arg );\n writer->SetInput( streamerBP->GetOutput() );\n\n if(args_info.verbose_flag)\n std::cout << \"Reconstructing and writing... \" << std::flush;\n itk::TimeProbe writerProbe;\n\n writerProbe.Start();\n TRY_AND_EXIT_ON_ITK_EXCEPTION( writer->Update() );\n writerProbe.Stop();\n\n if(args_info.verbose_flag)\n {\n std::cout << \"It took \" << writerProbe.GetMean() << ' ' << readerProbe.GetUnit() << std::endl;\n if(!strcmp(args_info.hardware_arg, \"cpu\") )\n feldkamp->PrintTiming(std::cout);\n#ifdef RTK_USE_CUDA\n else if(!strcmp(args_info.hardware_arg, \"cuda\") )\n feldkampCUDA->PrintTiming(std::cout);\n#endif\n#ifdef RTK_USE_OPENCL\n else if(!strcmp(args_info.hardware_arg, \"opencl\") )\n feldkampOCL->PrintTiming(std::cout);\n#endif\n std::cout << std::endl;\n }\n\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"#include \n\n#include \n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \"wanproxy_codec.h\"\n#include \"wanproxy_codec_pipe_pair.h\"\n\nWANProxyCodecPipePair::WANProxyCodecPipePair(WANProxyCodec *incoming, WANProxyCodec *outgoing)\n: incoming_pipe_(NULL),\n outgoing_pipe_(NULL),\n pipes_(),\n pipe_pairs_(),\n pipe_links_()\n{\n\tstd::deque > pipe_list;\n\n\tif (incoming != NULL) {\n\t\tif (incoming->compressor_) {\n\t\t\tstd::pair pipe_pair(new DeflatePipe(incoming->compressor_level_), new InflatePipe());\n\n\t\t\tpipes_.insert(pipe_pair.first);\n\t\t\tpipes_.insert(pipe_pair.second);\n\n\t\t\tpipe_list.push_back(pipe_pair);\n\t\t}\n\n\t\tif (incoming->codec_ != NULL) {\n\t\t\tPipePair *pair = new XCodecPipePair(\"\/wanproxy\/codec\/\" + incoming->name_, incoming->codec_, XCodecPipePairTypeServer);\n\t\t\tpipe_pairs_.insert(pair);\n\n\t\t\tstd::pair pipe_pair(pair->get_incoming(), pair->get_outgoing());\n\t\t\tpipe_list.push_back(pipe_pair);\n\t\t}\n\t}\n\n\tif (outgoing != NULL) {\n\t\tif (outgoing->codec_ != NULL) {\n\t\t\tPipePair *pair = new XCodecPipePair(\"\/wanproxy\/codec\/\" + outgoing->name_, outgoing->codec_, XCodecPipePairTypeClient);\n\t\t\tpipe_pairs_.insert(pair);\n\n\t\t\tstd::pair pipe_pair(pair->get_incoming(), pair->get_outgoing());\n\t\t\tpipe_list.push_back(pipe_pair);\n\t\t}\n\n\t\tif (outgoing->compressor_) {\n\t\t\tstd::pair pipe_pair(new InflatePipe(), new DeflatePipe(outgoing->compressor_level_));\n\n\t\t\tpipes_.insert(pipe_pair.first);\n\t\t\tpipes_.insert(pipe_pair.second);\n\n\t\t\tpipe_list.push_back(pipe_pair);\n\t\t}\n\t}\n\n\tif (pipe_list.empty()) {\n\t\tincoming_pipe_ = new PipeNull();\n\t\toutgoing_pipe_ = new PipeNull();\n\n\t\tpipes_.insert(incoming_pipe_);\n\t\tpipes_.insert(outgoing_pipe_);\n\n\t\treturn;\n\t}\n\n\t\/*\n\t * XXX\n\t * I think the incoming Pipes may be in the wrong order.\n\t *\/\n\n\tincoming_pipe_ = pipe_list.front().first;\n\toutgoing_pipe_ = pipe_list.front().second;\n\tpipe_list.pop_front();\n\n\twhile (!pipe_list.empty()) {\n\t\tincoming_pipe_ = new PipeLink(incoming_pipe_, pipe_list.front().first);\n\t\toutgoing_pipe_ = new PipeLink(outgoing_pipe_, pipe_list.front().second);\n\n\t\tpipe_links_.push_front(incoming_pipe_);\n\t\tpipe_links_.push_front(outgoing_pipe_);\n\n\t\tpipe_list.pop_front();\n\t}\n}\n\nWANProxyCodecPipePair::~WANProxyCodecPipePair()\n{\n\t\/*\n\t * We need to delete the PipeLinks first, since they may have\n\t * actions running internally.\n\t *\/\n\tstd::list::iterator plit;\n\twhile ((plit = pipe_links_.begin()) != pipe_links_.end()) {\n\t\tPipe *pipe_link = *plit;\n\t\tpipe_links_.erase(plit);\n\n\t\tdelete pipe_link;\n\t}\n\n\tstd::set::iterator pit;\n\twhile ((pit = pipes_.begin()) != pipes_.end()) {\n\t\tPipe *pipe = *pit;\n\t\tpipes_.erase(pit);\n\n\t\tdelete pipe;\n\t}\n\n\tstd::set::iterator ppit;\n\twhile ((ppit = pipe_pairs_.begin()) != pipe_pairs_.end()) {\n\t\tPipePair *pipe_pair = *ppit;\n\t\tpipe_pairs_.erase(ppit);\n\n\t\tdelete pipe_pair;\n\t}\n}\n\nPipe *\nWANProxyCodecPipePair::get_incoming(void)\n{\n\treturn (incoming_pipe_);\n}\n\nPipe *\nWANProxyCodecPipePair::get_outgoing(void)\n{\n\treturn (outgoing_pipe_);\n}\nAttempt to get XCodec+zlib Pipe order correct.#include \n\n#include \n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \"wanproxy_codec.h\"\n#include \"wanproxy_codec_pipe_pair.h\"\n\nWANProxyCodecPipePair::WANProxyCodecPipePair(WANProxyCodec *incoming, WANProxyCodec *outgoing)\n: incoming_pipe_(NULL),\n outgoing_pipe_(NULL),\n pipes_(),\n pipe_pairs_(),\n pipe_links_()\n{\n\tstd::deque incoming_pipe_list, outgoing_pipe_list;\n\n\tif (incoming != NULL) {\n\t\tif (incoming->compressor_) {\n\t\t\tPipe *deflate_pipe = new DeflatePipe(incoming->compressor_level_);\n\t\t\tPipe *inflate_pipe = new InflatePipe();\n\n\t\t\tincoming_pipe_list.push_back(inflate_pipe);\n\t\t\toutgoing_pipe_list.push_front(deflate_pipe);\n\n\t\t\tpipes_.insert(deflate_pipe);\n\t\t\tpipes_.insert(inflate_pipe);\n\t\t}\n\n\t\tif (incoming->codec_ != NULL) {\n\t\t\tPipePair *pair = new XCodecPipePair(\"\/wanproxy\/codec\/\" + incoming->name_, incoming->codec_, XCodecPipePairTypeServer);\n\t\t\tpipe_pairs_.insert(pair);\n\n\t\t\tincoming_pipe_list.push_back(pair->get_incoming());\n\t\t\toutgoing_pipe_list.push_front(pair->get_outgoing());\n\t\t}\n\t}\n\n\tif (outgoing != NULL) {\n\t\tif (outgoing->codec_ != NULL) {\n\t\t\tPipePair *pair = new XCodecPipePair(\"\/wanproxy\/codec\/\" + outgoing->name_, outgoing->codec_, XCodecPipePairTypeClient);\n\t\t\tpipe_pairs_.insert(pair);\n\n\t\t\tincoming_pipe_list.push_back(pair->get_incoming());\n\t\t\toutgoing_pipe_list.push_front(pair->get_outgoing());\n\t\t}\n\n\t\tif (outgoing->compressor_) {\n\t\t\tPipe *deflate_pipe = new DeflatePipe(outgoing->compressor_level_);\n\t\t\tPipe *inflate_pipe = new InflatePipe();\n\n\t\t\tincoming_pipe_list.push_back(deflate_pipe);\n\t\t\toutgoing_pipe_list.push_front(inflate_pipe);\n\n\t\t\tpipes_.insert(deflate_pipe);\n\t\t\tpipes_.insert(inflate_pipe);\n\t\t}\n\t}\n\n\tASSERT(incoming_pipe_list.empty() == outgoing_pipe_list.empty());\n\n\tif (incoming_pipe_list.empty() && outgoing_pipe_list.empty()) {\n\t\tincoming_pipe_ = new PipeNull();\n\t\toutgoing_pipe_ = new PipeNull();\n\n\t\tpipes_.insert(incoming_pipe_);\n\t\tpipes_.insert(outgoing_pipe_);\n\n\t\treturn;\n\t}\n\n\tASSERT(incoming_pipe_list.size() == outgoing_pipe_list.size());\n\n\tincoming_pipe_ = incoming_pipe_list.front();\n\tincoming_pipe_list.pop_front();\n\n\toutgoing_pipe_ = outgoing_pipe_list.front();\n\toutgoing_pipe_list.pop_front();\n\n\twhile (!incoming_pipe_list.empty() && !outgoing_pipe_list.empty()) {\n\t\tincoming_pipe_ = new PipeLink(incoming_pipe_, incoming_pipe_list.front());\n\t\toutgoing_pipe_ = new PipeLink(outgoing_pipe_, outgoing_pipe_list.front());\n\n\t\tpipe_links_.push_front(incoming_pipe_);\n\t\tpipe_links_.push_front(outgoing_pipe_);\n\n\t\tincoming_pipe_list.pop_front();\n\t\toutgoing_pipe_list.pop_front();\n\t}\n\tASSERT(incoming_pipe_list.empty() && outgoing_pipe_list.empty());\n}\n\nWANProxyCodecPipePair::~WANProxyCodecPipePair()\n{\n\t\/*\n\t * We need to delete the PipeLinks first, since they may have\n\t * actions running internally.\n\t *\/\n\tstd::list::iterator plit;\n\twhile ((plit = pipe_links_.begin()) != pipe_links_.end()) {\n\t\tPipe *pipe_link = *plit;\n\t\tpipe_links_.erase(plit);\n\n\t\tdelete pipe_link;\n\t}\n\n\tstd::set::iterator pit;\n\twhile ((pit = pipes_.begin()) != pipes_.end()) {\n\t\tPipe *pipe = *pit;\n\t\tpipes_.erase(pit);\n\n\t\tdelete pipe;\n\t}\n\n\tstd::set::iterator ppit;\n\twhile ((ppit = pipe_pairs_.begin()) != pipe_pairs_.end()) {\n\t\tPipePair *pipe_pair = *ppit;\n\t\tpipe_pairs_.erase(ppit);\n\n\t\tdelete pipe_pair;\n\t}\n}\n\nPipe *\nWANProxyCodecPipePair::get_incoming(void)\n{\n\treturn (incoming_pipe_);\n}\n\nPipe *\nWANProxyCodecPipePair::get_outgoing(void)\n{\n\treturn (outgoing_pipe_);\n}\n<|endoftext|>"} {"text":"\/******************************************************************************\n* SOFA, Simulation Open-Framework Architecture, version 1.0 beta 4 *\n* (c) 2006-2009 MGH, INRIA, USTL, UJF, CNRS *\n* *\n* This program is free software; you can redistribute it and\/or modify it *\n* under the terms of the GNU General Public License as published by the Free *\n* Software Foundation; either version 2 of the License, or (at your option) *\n* any later version. *\n* *\n* This program is distributed in the hope that it will be useful, but WITHOUT *\n* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *\n* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for *\n* more details. *\n* *\n* You should have received a copy of the GNU General Public License along *\n* with this program; if not, write to the Free Software Foundation, Inc., 51 *\n* Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *\n*******************************************************************************\n* SOFA :: Applications *\n* *\n* Authors: M. Adam, J. Allard, B. Andre, P-J. Bensoussan, S. Cotin, C. Duriez,*\n* H. Delingette, F. Falipou, F. Faure, S. Fonteneau, L. Heigeas, C. Mendoza, *\n* M. Nesme, P. Neumann, J-P. de la Plata Alcade, F. Poyer and F. Roy *\n* *\n* Contact information: contact@sofa-framework.org *\n******************************************************************************\/\n#include \"SofaGUI.h\"\n#include \n#include \n\nnamespace sofa\n{\n\nnamespace gui\n{\n\nSOFA_LINK_CLASS(BatchGUI)\n\n#ifdef SOFA_GUI_GLUT\nSOFA_LINK_CLASS(SimpleGUI)\n#endif\n\n#ifdef SOFA_GUI_QGLVIEWER\nSOFA_LINK_CLASS(QGLViewerGUI)\n#endif\n#ifdef SOFA_GUI_QTVIEWER\nSOFA_LINK_CLASS(QTGUI)\n#endif\n#ifdef SOFA_GUI_QTOGREVIEWER\nSOFA_LINK_CLASS(OgreGUI)\n#endif\n\n\n\/\/ ligne 1 et 3\n#ifdef __GNUC__ 4\n#ifdef __GNUC__MINOR__ 2\nint fish\n#endif\n#endif\n\n#ifndef SOFA_DEV\nint fish\n#endif\n\n#ifdef __APPLE__\nint fish\n#endif\n\n\/\/ ligne 2\n\/\/#ifdef __GNUC__ 4\n\/\/ #ifdef __GNUC__MINOR__ 3\n\/\/ int fish\n\/\/ #endif\n\/\/#endif\n\/\/\n\/\/#ifdef __GNUC__ 4\n\/\/ #ifdef __GNUC__MINOR__ 1\n\/\/ int fish\n\/\/ #endif\n\/\/#endif\n\/\/\n\/\/#ifdef SOFA_GPU_CUDA\n\/\/ int fish\n\/\/#endif\n\n\n\nint SofaGUI::Init()\n{\n sofa::component::init();\n sofa::simulation::tree::xml::initXml();\n if (guiCreators().empty())\n {\n std::cerr << \"ERROR(SofaGUI): No GUI registered.\"<init)\n return (*creator->init)(name, guiOptions);\n else\n return 0;\n}\n\nint SofaGUI::createGUI(sofa::simulation::Node* groot, const char* filename)\n{\n const char* name = GetGUIName();\n if (!currentGUI)\n {\n GUICreator* creator = GetGUICreator(name);\n if (!creator)\n {\n return 1;\n }\n currentGUI = (*creator->creator)(name, guiOptions, groot, filename);\n if (!currentGUI)\n {\n std::cerr << \"ERROR(SofaGUI): GUI \"<mainLoop();\n if (ret)\n {\n std::cerr << \"ERROR(SofaGUI): GUI \"<r4606\/sofa-dev : \/******************************************************************************\n* SOFA, Simulation Open-Framework Architecture, version 1.0 beta 4 *\n* (c) 2006-2009 MGH, INRIA, USTL, UJF, CNRS *\n* *\n* This program is free software; you can redistribute it and\/or modify it *\n* under the terms of the GNU General Public License as published by the Free *\n* Software Foundation; either version 2 of the License, or (at your option) *\n* any later version. *\n* *\n* This program is distributed in the hope that it will be useful, but WITHOUT *\n* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *\n* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for *\n* more details. *\n* *\n* You should have received a copy of the GNU General Public License along *\n* with this program; if not, write to the Free Software Foundation, Inc., 51 *\n* Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *\n*******************************************************************************\n* SOFA :: Applications *\n* *\n* Authors: M. Adam, J. Allard, B. Andre, P-J. Bensoussan, S. Cotin, C. Duriez,*\n* H. Delingette, F. Falipou, F. Faure, S. Fonteneau, L. Heigeas, C. Mendoza, *\n* M. Nesme, P. Neumann, J-P. de la Plata Alcade, F. Poyer and F. Roy *\n* *\n* Contact information: contact@sofa-framework.org *\n******************************************************************************\/\n#include \"SofaGUI.h\"\n#include \n#include \n\nnamespace sofa\n{\n\nnamespace gui\n{\n\nSOFA_LINK_CLASS(BatchGUI)\n\n#ifdef SOFA_GUI_GLUT\nSOFA_LINK_CLASS(SimpleGUI)\n#endif\n\n#ifdef SOFA_GUI_QGLVIEWER\nSOFA_LINK_CLASS(QGLViewerGUI)\n#endif\n#ifdef SOFA_GUI_QTVIEWER\nSOFA_LINK_CLASS(QTGUI)\n#endif\n#ifdef SOFA_GUI_QTOGREVIEWER\nSOFA_LINK_CLASS(OgreGUI)\n#endif\n\nint SofaGUI::Init()\n{\n sofa::component::init();\n sofa::simulation::tree::xml::initXml();\n if (guiCreators().empty())\n {\n std::cerr << \"ERROR(SofaGUI): No GUI registered.\"<init)\n return (*creator->init)(name, guiOptions);\n else\n return 0;\n}\n\nint SofaGUI::createGUI(sofa::simulation::Node* groot, const char* filename)\n{\n const char* name = GetGUIName();\n if (!currentGUI)\n {\n GUICreator* creator = GetGUICreator(name);\n if (!creator)\n {\n return 1;\n }\n currentGUI = (*creator->creator)(name, guiOptions, groot, filename);\n if (!currentGUI)\n {\n std::cerr << \"ERROR(SofaGUI): GUI \"<mainLoop();\n if (ret)\n {\n std::cerr << \"ERROR(SofaGUI): GUI \"<"} {"text":"-Werror,-Winconsistent-missing-override<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: dump8.cxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: obo $ $Date: 2005-11-16 13:54:06 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\n#ifndef _SV_SVAPP_HXX \/\/autogen\n#include \n#endif\n#ifndef _SV_WRKWIN_HXX \/\/autogen\n#include \n#endif\n#ifndef _SV_MSGBOX_HXX \/\/autogen\n#include \n#endif\n\n#include \n\n\/\/ globale Vars\n\nchar** pPara;\n\n\/\/ Deklarationen\n\nint PrepareConvert( String& rName, String& rOutName, String& rMess );\nint DoConvert( const String& rName, BYTE nVersion );\nvoid DeInit();\n\n\n\n\/\/ -----------------------------------------------------------------------\n\nclass MyApp : public Application\n{\npublic:\n void Main();\n};\n\n\/\/ -----------------------------------------------------------------------\n\nMyApp aMyApp;\n\n\/\/ -----------------------------------------------------------------------\n\nclass MyWin : public WorkWindow\n{\n String& rMessg;\npublic:\n MyWin( Window* pParent, WinBits aWinStyle, String& rMess ) :\n WorkWindow(pParent, aWinStyle), rMessg( rMess ) {}\n\n void Paint( const Rectangle& );\n void Resize();\n\n void MouseButtonDown( const MouseEvent& rMEvt );\n void KeyInput( const KeyEvent& rKEvt );\n};\n\n\/\/ -----------------------------------------------------------------------\n\nextern SvStorageStreamRef xStrm;\n\nvoid MyApp::Main()\n{\n SvFactory::Init();\n String aMess, aName, aOutName;\n BYTE nVersion = 8;\n\n int nArgs = GetCommandLineParamCount();\n if (nArgs)\n {\n aName = GetCommandLineParam( 0 );\n if (aName.Search('.') == STRING_NOTFOUND)\n aName.AppendAscii( \".doc\" );\n if (nArgs >= 2)\n {\n aOutName = GetCommandLineParam( 1 );\n if (nArgs > 2)\n {\n nVersion = GetCommandLineParam( 2 ).ToInt32();\n if( 6 > nVersion || 8 < nVersion )\n {\n aMess.AssignAscii( \"Aufruf: Dump1 InFile [OutFile] [6|7|8]\" );\n }\n }\n }\n else\n {\n aOutName = aName;\n aOutName.Erase(aOutName.Search('.'));\n aOutName.AppendAscii( \".dmp\" );\n }\n }\n\n BOOL bOk = !aMess.Len()\n && !PrepareConvert( aName, aOutName, aMess )\n && !DoConvert( aName, nVersion );\n\n if( !bOk )\n {\n MyWin aMainWin( NULL, WB_APP | WB_STDWORK, aMess );\n\n aMainWin.SetText( String::CreateFromAscii( \"WW8-Dumper\" ));\n aMainWin.Show();\n aMainWin.Invalidate();\n\n Execute();\n }\n DeInit();\n\/\/ SvFactory::DeInit();\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid MyWin::Paint( const Rectangle& )\n{\n String aText( String::CreateFromAscii( \"Dumper fuer WinWord-Dateien !\\n\"\n \"Die Wandlung ging schief. Ist es wirklich ein WW-File ?\" ));\n\n Size aWinSize = GetOutputSizePixel();\n Size aTextSize( GetTextWidth( aText ), GetTextHeight());\n Point aPos( aWinSize.Width() \/ 2 - aTextSize.Width() \/ 2,\n aWinSize.Height() \/ 2 - aTextSize.Height() \/ 2 );\n\n DrawText( aPos, aText );\n\n aPos.Y() += 20;\n DrawText( aPos, rMessg );\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid MyWin::Resize()\n{\n Invalidate();\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid MyWin::MouseButtonDown( const MouseEvent& )\n{\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid MyWin::KeyInput( const KeyEvent& rKEvt )\n{\n WorkWindow::KeyInput( rKEvt );\n}\n\n\n\nINTEGRATION: CWS pchfix02 (1.7.390); FILE MERGED 2006\/09\/01 17:52:44 kaib 1.7.390.1: #i68856# Added header markers and pch files\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: dump8.cxx,v $\n *\n * $Revision: 1.8 $\n *\n * last change: $Author: obo $ $Date: 2006-09-16 22:25:42 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sw.hxx\"\n\n\n#ifndef _SV_SVAPP_HXX \/\/autogen\n#include \n#endif\n#ifndef _SV_WRKWIN_HXX \/\/autogen\n#include \n#endif\n#ifndef _SV_MSGBOX_HXX \/\/autogen\n#include \n#endif\n\n#include \n\n\/\/ globale Vars\n\nchar** pPara;\n\n\/\/ Deklarationen\n\nint PrepareConvert( String& rName, String& rOutName, String& rMess );\nint DoConvert( const String& rName, BYTE nVersion );\nvoid DeInit();\n\n\n\n\/\/ -----------------------------------------------------------------------\n\nclass MyApp : public Application\n{\npublic:\n void Main();\n};\n\n\/\/ -----------------------------------------------------------------------\n\nMyApp aMyApp;\n\n\/\/ -----------------------------------------------------------------------\n\nclass MyWin : public WorkWindow\n{\n String& rMessg;\npublic:\n MyWin( Window* pParent, WinBits aWinStyle, String& rMess ) :\n WorkWindow(pParent, aWinStyle), rMessg( rMess ) {}\n\n void Paint( const Rectangle& );\n void Resize();\n\n void MouseButtonDown( const MouseEvent& rMEvt );\n void KeyInput( const KeyEvent& rKEvt );\n};\n\n\/\/ -----------------------------------------------------------------------\n\nextern SvStorageStreamRef xStrm;\n\nvoid MyApp::Main()\n{\n SvFactory::Init();\n String aMess, aName, aOutName;\n BYTE nVersion = 8;\n\n int nArgs = GetCommandLineParamCount();\n if (nArgs)\n {\n aName = GetCommandLineParam( 0 );\n if (aName.Search('.') == STRING_NOTFOUND)\n aName.AppendAscii( \".doc\" );\n if (nArgs >= 2)\n {\n aOutName = GetCommandLineParam( 1 );\n if (nArgs > 2)\n {\n nVersion = GetCommandLineParam( 2 ).ToInt32();\n if( 6 > nVersion || 8 < nVersion )\n {\n aMess.AssignAscii( \"Aufruf: Dump1 InFile [OutFile] [6|7|8]\" );\n }\n }\n }\n else\n {\n aOutName = aName;\n aOutName.Erase(aOutName.Search('.'));\n aOutName.AppendAscii( \".dmp\" );\n }\n }\n\n BOOL bOk = !aMess.Len()\n && !PrepareConvert( aName, aOutName, aMess )\n && !DoConvert( aName, nVersion );\n\n if( !bOk )\n {\n MyWin aMainWin( NULL, WB_APP | WB_STDWORK, aMess );\n\n aMainWin.SetText( String::CreateFromAscii( \"WW8-Dumper\" ));\n aMainWin.Show();\n aMainWin.Invalidate();\n\n Execute();\n }\n DeInit();\n\/\/ SvFactory::DeInit();\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid MyWin::Paint( const Rectangle& )\n{\n String aText( String::CreateFromAscii( \"Dumper fuer WinWord-Dateien !\\n\"\n \"Die Wandlung ging schief. Ist es wirklich ein WW-File ?\" ));\n\n Size aWinSize = GetOutputSizePixel();\n Size aTextSize( GetTextWidth( aText ), GetTextHeight());\n Point aPos( aWinSize.Width() \/ 2 - aTextSize.Width() \/ 2,\n aWinSize.Height() \/ 2 - aTextSize.Height() \/ 2 );\n\n DrawText( aPos, aText );\n\n aPos.Y() += 20;\n DrawText( aPos, rMessg );\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid MyWin::Resize()\n{\n Invalidate();\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid MyWin::MouseButtonDown( const MouseEvent& )\n{\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid MyWin::KeyInput( const KeyEvent& rKEvt )\n{\n WorkWindow::KeyInput( rKEvt );\n}\n\n\n\n<|endoftext|>"} {"text":"#pragma once\n\n#include \n#include \n#include \n#include \n\n#include \"utils\/Concepts.hpp\"\n\nnamespace utils {\n\ntemplate \nclass DisjointSets {\npublic:\n using ValueType = TValue;\n\n [[nodiscard]] int64_t size() const noexcept {\n return static_cast(this->m_parents.size());\n }\n\n bool add(const ValueType value) {\n if (this->m_parents.contains(value)) {\n return false;\n }\n this->m_parents.emplace(value, value);\n return true;\n }\n\n std::optional find(const ValueType value) {\n if (auto it = this->m_parents.find(value); it != this->m_parents.end()) {\n return this->findParent(it)->first;\n }\n return std::nullopt;\n }\n\n bool merge(const ValueType lhs, const ValueType rhs) {\n auto lhsIts = this->m_parents.find(lhs);\n if (lhsIts == this->m_parents.end()) {\n return false;\n }\n auto rhsIts = this->m_parents.find(rhs);\n if (rhsIts == this->m_parents.end()) {\n return false;\n }\n\n auto lhsParent = this->findParent(lhsIts);\n auto rhsParent = this->findParent(rhsIts);\n if (&lhsParent == &rhsParent) {\n return false;\n }\n\n if (lhsParent->first < rhsParent->first) {\n rhsParent->second = lhsParent->first;\n } else {\n lhsParent->second = rhsParent->first;\n }\n return true;\n }\n\nprivate:\n using NoteIterator = typename std::unordered_map::iterator;\n [[nodiscard]] NoteIterator findParent(NoteIterator it) {\n\n std::vector::iterator> visitedNodesIts;\n\n while (it->first != it->second) {\n visitedNodesIts.push_back(it);\n it = this->m_parents.find(it->second);\n }\n\n for (auto &visitedNodeIt: visitedNodesIts) {\n visitedNodeIt->second = it->second;\n }\n return it;\n }\n std::unordered_map m_parents;\n};\n} \/\/ namespace utilsFix usage of NodeIterator#pragma once\n\n#include \n#include \n#include \n#include \n\n#include \"utils\/Concepts.hpp\"\n\nnamespace utils {\n\ntemplate \nclass DisjointSets {\npublic:\n using ValueType = TValue;\n\n [[nodiscard]] int64_t size() const noexcept {\n return static_cast(this->m_parents.size());\n }\n\n bool add(const ValueType value) {\n if (this->m_parents.contains(value)) {\n return false;\n }\n this->m_parents.emplace(value, value);\n return true;\n }\n\n std::optional find(const ValueType value) {\n if (auto it = this->m_parents.find(value); it != this->m_parents.end()) {\n return this->findParent(it)->first;\n }\n return std::nullopt;\n }\n\n bool merge(const ValueType lhs, const ValueType rhs) {\n auto lhsIts = this->m_parents.find(lhs);\n if (lhsIts == this->m_parents.end()) {\n return false;\n }\n auto rhsIts = this->m_parents.find(rhs);\n if (rhsIts == this->m_parents.end()) {\n return false;\n }\n\n auto lhsParent = this->findParent(lhsIts);\n auto rhsParent = this->findParent(rhsIts);\n if (&lhsParent == &rhsParent) {\n return false;\n }\n\n if (lhsParent->first < rhsParent->first) {\n rhsParent->second = lhsParent->first;\n } else {\n lhsParent->second = rhsParent->first;\n }\n return true;\n }\n\nprivate:\n using NodeIterator = typename std::unordered_map::iterator;\n [[nodiscard]] NodeIterator findParent(NodeIterator it) {\n\n std::vector visitedNodesIts;\n\n while (it->first != it->second) {\n visitedNodesIts.push_back(it);\n it = this->m_parents.find(it->second);\n }\n\n for (auto &visitedNodeIt: visitedNodesIts) {\n visitedNodeIt->second = it->second;\n }\n return it;\n }\n std::unordered_map m_parents;\n};\n} \/\/ namespace utils<|endoftext|>"} {"text":"\/\/ Filename: \tmain.cpp\n\/\/ Author: \t\tChristopher Goes\n\/\/ Course: \t\tCS 404 Machine Learning and Data Mining\n\/\/ Semester: \tSpring 2016\n\/\/ Description:\tAssignment 3 main program logic\n\/\/ Github:\t\thttps:\/\/github.com\/GhostofGoes\/cgoes-cs404\n\n#include \n#include \n#include \n#include \n#include \n#include \"matrix.h\"\n\n#define DEBUG 0\n#define DEBUGINPUT 0\n#define DEBUG_RESULTS 0\n\nusing namespace std;\n\ndouble sigmoid( double input ); \/\/ Sigmoid function\n\nint main() {\n\t\n\t\/\/ Initialization\n\t\/\/ weird init values are paranoia for error catching\n\tint numInputs = 0;\n\tint numOutputs = 0;\n\tint rows = 0;\n\tint cols = 0;\n\tint testRows = 0;\n\tint testCols = 0;\n\tdouble temp = -99;\n\tdouble bias = -1.0; \/\/ -1 is what the book uses.\n\tdouble eta = 0.025; \/\/ 0.25 is what the book uses. open to tweaking.\n\tint attempts = 1; \/\/ if debugging, SET THIS TO A SMALL NUMBER!\n\t\/\/int num_hidden_layers = 1; \/\/ is this a thing\n\tint num_hidden_nodes = 0;\n\tdouble max = 1;\n\tdouble min = 1;\n\t\n\t\n\t\/\/\t\tTraining Data Input \t\/\/\n\tcin >> numInputs;\n\tcin >> num_hidden_nodes;\n\tcin >> rows;\n\tcin >> cols;\n\tnumOutputs = cols - numInputs;\n\t\n\tMatrix* tinput = new Matrix(rows, numInputs + 1); \/\/ +1 for bias\n\tMatrix* toutput = new Matrix(rows, numOutputs); \n\t\n\tif(DEBUGINPUT) {\n\t\tcout << \"Inputs: \" << numInputs << \"\\nHidden Nodes: \" << num_hidden_nodes << \"\\nRows: \" << rows << \"\\nCols: \" << cols << endl;\n\t}\n\t\n\t\/\/ Fill the matrix\n\tfor(int r = 0; r < rows; r++) {\n\t\tfor(int c = 0; c < numInputs; c++) {\n\t\t\tcin >> temp;\n\t\t\tif( temp > max ) max = temp;\n\t\t\telse if( temp < min ) min = temp;\n\t\t\ttinput->setValue( r, c, temp);\n\t\t}\n\t\t\n\t\tfor(int c = 0; c < numOutputs; c++ ) {\n\t\t\tcin >> temp;\n\t\t\tif( temp > max ) max = temp;\n\t\t\telse if( temp < min ) min = temp;\n\t\t\ttoutput->setValue( r, c, temp);\t\n\t\t}\n\t}\n\t\n\t\/\/ Append the bias\n\tfor( int r = 0; r < rows; r++ ) {\n\t\ttinput->setValue(r, numInputs, bias);\n\t}\n\tnumInputs++;\n\t\n\n\tif(DEBUGINPUT) {\n\t\tcout << \"\\nTraining Inputs...\" << endl;\n\t\ttinput->printAll();\n\t\tcout << \"\\nTraining Outputs...\" << endl;\n\t\ttoutput->printAll();\n\t}\t\n\t\n\t\n\t\/\/\t\tTest Data Input \t\/\/\n\tcin >> testRows;\n\tcin >> testCols;\n\tMatrix * testInput = new Matrix(testRows, testCols + 1);\n\n\t\/\/ Fill the matrix\n\tfor(int r = 0; r < testRows; r++) {\n\t\tfor(int c = 0; c < testCols; c++) {\n\t\t\tcin >> temp;\n\t\t\tif( temp > max ) max = temp;\n\t\t\telse if( temp < min ) min = temp;\n\t\t\ttestInput->setValue(r, c, temp);\n\t\t}\n\t}\t\n\n\t\/\/ Append the bias\n\tfor( int r = 0; r < testRows; r++ ) {\n\t\ttestInput->setValue(r, testCols, bias);\n\t}\n\ttestCols;\n\n\tif(DEBUGINPUT) {\n\t\tcout << \"\\nTest Inputs matrix\" << endl;\n\t\ttestInput->printAll();\n\t}\n\t\n\t\n\t\/\/ \t\t\t\t\t\t\/\/\n\t\/\/ \t\t* Training * \t\/\/\n\n\tMatrix * hw = new Matrix(num_hidden_nodes, numOutputs, 2);\n\tMatrix * ow = new Matrix(num_hidden_nodes + 1, numOutputs, 2); \/\/ +1 for the extra bias between hidden and output layers\n\tMatrix * tempmat;\n\tMatrix * deltah; \/\/ error in hidden layer\n\tMatrix * deltao; \/\/ error in output layer\n\tMatrix * a; \/\/ hidden layer output\n\tMatrix * y; \/\/ output layer output\n\tMatrix * hVec;\t\n\tMatrix * inVec;\n\tMatrix * t;\n\ttemp = -99;\n\t\n\tif(DEBUG) {\n\t\tcout << \"\\nInitialized Hidden Weight matrix...\" << endl;\n\t\thw->printAll();\n\t}\n\n\t\/\/ Normalize our input\n\ttinput->normalize(min, max);\n\t\n\t\/\/ re-re-implementation\n\tfor( int attempt = 0; attempt < attempts; attempt++ ) {\n\t\t\/\/ TODO randomize order rows are done each attempt?\n\t\tfor( int r = 0; r < rows; r++ ) {\n\t\t\tinVec = tinput->getRow(r);\n\t\t\tt = toutput->getRow(r);\n\t\t\n\t\t\tif(DEBUG) {\n\t\t\tcout << \"inVec\" << endl;\n\t\t\tinVec->printAll();\n\t\t\tcout << endl;\n\t\t\t}\n\t\t\t\/\/ hidden layer\n\t\t\ta = inVec->dot(hw);\n\t\t\ta->sigmoid();\n\t\t\t\n\t\t\tif(DEBUG) {\n\t\t\tcout << \"a\" << endl;\n\t\t\ta->printAll();\n\t\t\tcout << endl;\n\t\t\t}\n\t\t\thVec = new Matrix(a);\n\t\t\thVec->data[0].push_back(bias);\n\t\t\thVec->numCols++;\n\t\t\t\n\t\t\tif(DEBUG) {\n\t\t\tcout << \"hVec\" << endl;\n\t\t\thVec->printAll();\n\t\t\tcout << endl;\n\t\t\t}\n\t\t\t\/\/ output layer\n\t\t\ty = hVec->dot(hw);\n\t\t\ty->sigmoid();\n\t\t\t\n\t\t\tif(DEBUG) {\n\t\t\tcout << \"y\" << endl;\n\t\t\ty->printAll();\n\t\t\tcout << endl;\n\t\t\t}\n\t\t\t\/\/ output error\n\t\t\tt = t->sub(y);\n\t\t\tt = t->dot(y);\n\t\t\t\n\t\t\tif(DEBUG) {\n\t\t\tcout << \"y\" << endl;\n\t\t\tt->printAll();\n\t\t\tcout << endl;\n\t\t\t}\n\t\t\t\n\t\t\ty->scalarPreSub(1.0);\n\t\t\tdeltao = t->mult(y);\n\t\t\t\n\t\t\tif(DEBUG) {\n\t\t\tcout << \"deltao\" << endl;\n\t\t\tdeltao->printAll();\n\t\t\tcout << endl;\t\n\t\t\t}\n\t\t\t\n\t\t\t\/\/ hidden error\n\t\t\tdeltah = hVec;\n\t\t\thVec->scalarPreSub(1.0);\n\t\t\tdeltah->mult(hVec);\n\t\t\thVec->scalarPreSub(1.0);\n\t\t\ttempmat = deltao->dot(ow);\n\t\t\ttempmat = tempmat->transpose();\n\t\t\tdeltah = deltah->mult(tempmat);\n\t\t\t\n\t\t\tif(DEBUG) {\n\t\t\tcout << \"deltah\" << endl;\n\t\t\tdeltah->printAll();\n\t\t\tcout << endl;\n\t\t\t}\n\t\t\t\n\t\t\t\/\/ update matricies\n\t\t\thVec = hVec->transpose();\n\t\t\thVec = hVec->dot(deltao);\n\t\t\thVec = hVec->dot(eta);\n\t\t\tow = ow->add(tempmat);\n\t\t\t\n\t\t\tdeltah->data[0].pop_back();\n\t\t\tdeltah->numCols--;\n\t\t\t\n\t\t\ttempmat = inVec->transpose();\n\t\t\ttempmat = inVec->dot(deltah);\n\t\t\ttempmat = tempmat->dot(eta);\n\t\t\thw = hw->add(tempmat);\n\t\t\t\n\t\t\tdelete deltao;\n\t\t\tdelete deltah;\n\t\t\tdelete a;\n\t\t\tdelete y;\n\t\t\tdelete hVec;\n\t\t\tdelete inVec;\n\t\t\tdelete t;\n\t\t} \/\/ rows\n\t\t\t\t\n\t\t\t\t\t\t\n\t} \/\/ attempts\t\n\n \n\t\/\/\t\t\t\t\t\t\t\/\/\n\t\/\/\t\t \tTesting\t\t\t\/\/\n\n\tcout << \"BEGIN TESTING\" << endl;\n\ttestInput->normalize(min, max);\n\t\n\tfor( int r = 0; r < testRows; r++ ) { \/\/ Each row in testing set\n\t\tinVec = testInput->getRow(r);\n\t\t\n\t\tfor (int i = 0; i < testCols; i++) {\n\t\t\tcout << fixed << setprecision(2) << testInput->getValue(r, i) << \" \";\n\t\t}\n\n\t\t\/\/ hidden layer\n\t\ta = inVec->dot(hw);\n\t\ta->sigmoid();\n\t\thVec = new Matrix(a);\n\t\thVec->data[0].push_back(bias);\n\t\thVec->numCols++;\n\t\t\n\t\t\/\/ output layer\n\t\ty = hVec->dot(hw);\n\t\ty->sigmoid();\t\t\n\n\t\tfor( int i = 0; i < numOutputs; i++ ) {\n\t\t\tcout << fixed << setprecision(2) << y->getValue(0, i) << \" \";\n\t\t}\n\t\tcout << endl; \/\/ end the row's output\n\t} \/\/ row in set loop\t\n\t\n\t\n\t\n\t\/\/\t\tFinal Cleanup\t\t\/\/\n\tdelete hw;\n\tdelete ow;\n\tdelete tinput;\n\tdelete toutput;\n\tdelete testInput;\n\treturn(0);\n}\n\ndouble sigmoid( double input ) {\n\treturn (2 \/ (1 + exp(-25 * input)) - 1);\n}\nMinor edits before final HW3 submission\/\/ Filename: \tmain.cpp\n\/\/ Author: \t\tChristopher Goes\n\/\/ Course: \t\tCS 404 Machine Learning and Data Mining\n\/\/ Semester: \tSpring 2016\n\/\/ Description:\tAssignment 3 main program logic\n\/\/ Github:\t\thttps:\/\/github.com\/GhostofGoes\/cgoes-cs404\n\n#include \n#include \n#include \n#include \n#include \n#include \"matrix.h\"\n\n#define DEBUG 0\n#define DEBUGINPUT 0\n#define DEBUG_RESULTS 0\n\nusing namespace std;\n\ndouble sigmoid( double input ); \/\/ Sigmoid function\n\nint main() {\n\t\n\t\/\/ Initialization\n\t\/\/ weird init values are paranoia for error catching\n\tint numInputs = 0;\n\tint numOutputs = 0;\n\tint rows = 0;\n\tint cols = 0;\n\tint testRows = 0;\n\tint testCols = 0;\n\tdouble temp = -99;\n\tdouble bias = -1.0; \/\/ -1 is what the book uses.\n\tdouble eta = 0.025; \/\/ 0.25 is what the book uses. open to tweaking.\n\tint attempts = 1; \/\/ if debugging, SET THIS TO A SMALL NUMBER!\n\t\/\/int num_hidden_layers = 1; \/\/ is this a thing\n\tint num_hidden_nodes = 0;\n\tdouble max = 1;\n\tdouble min = 1;\n\t\n\t\n\t\/\/\t\tTraining Data Input \t\/\/\n\tcin >> numInputs;\n\tcin >> num_hidden_nodes;\n\tcin >> rows;\n\tcin >> cols;\n\tnumOutputs = cols - numInputs;\n\t\n\tMatrix* tinput = new Matrix(rows, numInputs + 1); \/\/ +1 for bias\n\tMatrix* toutput = new Matrix(rows, numOutputs); \n\t\n\tif(DEBUGINPUT) {\n\t\tcout << \"Inputs: \" << numInputs << \"\\nHidden Nodes: \" << num_hidden_nodes << \"\\nRows: \" << rows << \"\\nCols: \" << cols << endl;\n\t}\n\t\n\t\/\/ Fill the matrix\n\tfor(int r = 0; r < rows; r++) {\n\t\tfor(int c = 0; c < numInputs; c++) {\n\t\t\tcin >> temp;\n\t\t\tif( temp > max ) max = temp;\n\t\t\telse if( temp < min ) min = temp;\n\t\t\ttinput->setValue( r, c, temp);\n\t\t}\n\t\t\n\t\tfor(int c = 0; c < numOutputs; c++ ) {\n\t\t\tcin >> temp;\n\t\t\tif( temp > max ) max = temp;\n\t\t\telse if( temp < min ) min = temp;\n\t\t\ttoutput->setValue( r, c, temp);\t\n\t\t}\n\t}\n\t\n\t\/\/ Append the bias\n\tfor( int r = 0; r < rows; r++ ) {\n\t\ttinput->setValue(r, numInputs, bias);\n\t}\n\tnumInputs++;\n\t\n\n\tif(DEBUGINPUT) {\n\t\tcout << \"\\nTraining Inputs...\" << endl;\n\t\ttinput->printAll();\n\t\tcout << \"\\nTraining Outputs...\" << endl;\n\t\ttoutput->printAll();\n\t}\t\n\t\n\t\n\t\/\/\t\tTest Data Input \t\/\/\n\tcin >> testRows;\n\tcin >> testCols;\n\tMatrix * testInput = new Matrix(testRows, testCols + 1);\n\n\t\/\/ Fill the matrix\n\tfor(int r = 0; r < testRows; r++) {\n\t\tfor(int c = 0; c < testCols; c++) {\n\t\t\tcin >> temp;\n\t\t\tif( temp > max ) max = temp;\n\t\t\telse if( temp < min ) min = temp;\n\t\t\ttestInput->setValue(r, c, temp);\n\t\t}\n\t}\t\n\n\t\/\/ Append the bias\n\tfor( int r = 0; r < testRows; r++ ) {\n\t\ttestInput->setValue(r, testCols, bias);\n\t}\n\ttestCols;\n\n\tif(DEBUGINPUT) {\n\t\tcout << \"\\nTest Inputs matrix\" << endl;\n\t\ttestInput->printAll();\n\t}\n\t\n\t\n\t\/\/ \t\t\t\t\t\t\/\/\n\t\/\/ \t\t* Training * \t\/\/\n\n\tMatrix * hw = new Matrix(num_hidden_nodes, numOutputs, 2);\n\tMatrix * ow = new Matrix(num_hidden_nodes + 1, numOutputs, 2); \/\/ +1 for the extra bias between hidden and output layers\n\tMatrix * tempmat;\n\tMatrix * deltah; \/\/ error in hidden layer\n\tMatrix * deltao; \/\/ error in output layer\n\tMatrix * a; \/\/ hidden layer output\n\tMatrix * y; \/\/ output layer output\n\tMatrix * hVec;\t\n\tMatrix * inVec;\n\tMatrix * t;\n\ttemp = -99;\n\t\n\tif(DEBUG) {\n\t\tcout << \"\\nInitialized Hidden Weight matrix...\" << endl;\n\t\thw->printAll();\n\t}\n\n\t\/\/ Normalize our input\n\ttinput->normalize(min, max);\n\t\n\t\/\/ re-re-implementation\n\tfor( int attempt = 0; attempt < attempts; attempt++ ) {\n\t\t\/\/ TODO randomize order rows are done each attempt?\n\t\tfor( int r = 0; r < rows; r++ ) {\n\t\t\tinVec = tinput->getRow(r);\n\t\t\tt = toutput->getRow(r);\n\t\t\n\t\t\tif(DEBUG) {\n\t\t\tcout << \"inVec\" << endl;\n\t\t\tinVec->printAll();\n\t\t\tcout << endl;\n\t\t\t}\n\t\t\t\/\/ hidden layer\n\t\t\ta = inVec->dot(hw);\n\t\t\ta->sigmoid();\n\t\t\t\n\t\t\tif(DEBUG) {\n\t\t\tcout << \"a\" << endl;\n\t\t\ta->printAll();\n\t\t\tcout << endl;\n\t\t\t}\n\t\t\thVec = new Matrix(a);\n\t\t\thVec->data[0].push_back(bias);\n\t\t\thVec->numCols++;\n\t\t\t\n\t\t\tif(DEBUG) {\n\t\t\tcout << \"hVec\" << endl;\n\t\t\thVec->printAll();\n\t\t\tcout << endl;\n\t\t\t}\n\t\t\t\/\/ output layer\n\t\t\ty = hVec->dot(hw);\n\t\t\ty->sigmoid();\n\t\t\t\n\t\t\tif(DEBUG) {\n\t\t\tcout << \"y\" << endl;\n\t\t\ty->printAll();\n\t\t\tcout << endl;\n\t\t\t}\n\t\t\t\/\/ output error\n\t\t\tt = t->sub(y);\n\t\t\tt = t->dot(y);\n\t\t\t\n\t\t\tif(DEBUG) {\n\t\t\tcout << \"y\" << endl;\n\t\t\tt->printAll();\n\t\t\tcout << endl;\n\t\t\t}\n\t\t\t\n\t\t\ty->scalarPreSub(1.0);\n\t\t\tdeltao = t->mult(y);\n\t\t\t\n\t\t\tif(DEBUG) {\n\t\t\tcout << \"deltao\" << endl;\n\t\t\tdeltao->printAll();\n\t\t\tcout << endl;\t\n\t\t\t}\n\t\t\t\n\t\t\t\/\/ hidden error\n\t\t\tdeltah = hVec;\n\t\t\thVec->scalarPreSub(1.0);\n\t\t\tdeltah->mult(hVec);\n\t\t\thVec->scalarPreSub(1.0);\n\t\t\ttempmat = deltao->dot(ow);\n\t\t\ttempmat = tempmat->transpose();\n\t\t\tdeltah = deltah->mult(tempmat);\n\t\t\t\n\t\t\tif(DEBUG) {\n\t\t\tcout << \"deltah\" << endl;\n\t\t\tdeltah->printAll();\n\t\t\tcout << endl;\n\t\t\t}\n\t\t\t\n\t\t\t\/\/ update matricies\n\t\t\thVec = hVec->transpose();\n\t\t\thVec = hVec->dot(deltao);\n\t\t\thVec = hVec->dot(eta);\n\t\t\tow = ow->add(tempmat);\n\t\t\t\n\t\t\tdeltah->data[0].pop_back();\n\t\t\tdeltah->numCols--;\n\t\t\t\n\t\t\ttempmat = inVec->transpose();\n\t\t\ttempmat = inVec->dot(deltah);\n\t\t\ttempmat = tempmat->dot(eta);\n\t\t\thw = hw->add(tempmat);\n\t\t\t\n\t\t\tdelete deltao;\n\t\t\tdelete deltah;\n\t\t\tdelete a;\n\t\t\tdelete y;\n\t\t\tdelete hVec;\n\t\t\tdelete inVec;\n\t\t\tdelete t;\n\t\t} \/\/ rows\n\t\t\t\t\n\t\t\t\t\t\t\n\t} \/\/ attempts\t\n\n \n\t\/\/\t\t\t\t\t\t\t\/\/\n\t\/\/\t\t \tTesting\t\t\t\/\/\n\n\tMatrix * normTestInput;\n\t\n\tcout << \"BEGIN TESTING\" << endl;\n\tnormTestInput = new Matrix(testInput);\n\tnormTestInput->normalize(min, max);\n\t\n\tfor( int r = 0; r < testRows; r++ ) { \/\/ Each row in testing set\n\t\tinVec = normTestInput->getRow(r);\n\t\t\n\t\tfor (int i = 0; i < testCols; i++) {\n\t\t\tcout << fixed << setprecision(2) << testInput->getValue(r, i) << \" \";\n\t\t}\n\n\t\t\/\/ hidden layer\n\t\ta = inVec->dot(hw);\n\t\ta->sigmoid();\n\t\thVec = new Matrix(a);\n\t\thVec->data[0].push_back(bias);\n\t\thVec->numCols++;\n\t\t\n\t\t\/\/ output layer\n\t\ty = hVec->dot(hw);\n\t\ty->sigmoid();\t\t\n\n\t\tfor( int i = 0; i < numOutputs; i++ ) {\n\t\t\tcout << fixed << setprecision(2) << y->getValue(0, i) << \" \";\n\t\t}\n\t\tcout << endl; \/\/ end the row's output\n\t} \/\/ row in set loop\t\n\t\n\t\n\t\n\t\/\/\t\tFinal Cleanup\t\t\/\/\n\tdelete hw;\n\tdelete ow;\n\tdelete tinput;\n\tdelete toutput;\n\tdelete testInput;\n\treturn(0);\n}\n\ndouble sigmoid( double input ) {\n\treturn (2 \/ (1 + exp(-25 * input)) - 1);\n}\n<|endoftext|>"} {"text":"#include \n\n#include \n#include \n#include \n\n#include \n\n#include \n\n#include \n#include \n#include \n\n#include \n\n#include \n\nclass SSHTransportPipe : public PipeProducer {\n\tenum State {\n\t\tGetIdentificationString,\n\t\tGetPacket\n\t};\n\n\tState state_;\n\tBuffer input_buffer_;\n\tsize_t mac_length_;\n\n\tEventCallback *receive_callback_;\n\tAction *receive_action_;\npublic:\n\tSSHTransportPipe(void)\n\t: PipeProducer(\"\/ssh\/transport\/pipe\"),\n\t state_(GetIdentificationString),\n\t mac_length_(0),\n\t receive_callback_(NULL),\n\t receive_action_(NULL)\n\t{\n\t\tBuffer identification_string(\"SSH-2.0-WANProxy \" + (std::string)log_ + \"\\r\\n\");\n\t\tproduce(&identification_string);\n\t}\n\n\t~SSHTransportPipe()\n\t{\n\t\tASSERT(receive_callback_ == NULL);\n\t\tASSERT(receive_action_ == NULL);\n\t}\n\n\tAction *receive(EventCallback *cb)\n\t{\n\t\tASSERT(receive_callback_ == NULL);\n\t\tASSERT(receive_action_ == NULL);\n\n\t\t\/*\n\t\t * XXX\n\t\t * This pattern is implemented about three different\n\t\t * ways in the WANProxy codebase, and they are all kind\n\t\t * of awful. Need a better way to handle code that\n\t\t * needs executed either on the request of the caller\n\t\t * or when data comes in that satisfies a deferred\n\t\t * callback to a caller.\n\t\t *\/\n\t\treceive_callback_ = cb;\n\t\treceive_do();\n\n\t\tif (receive_callback_ != NULL)\n\t\t\treturn (cancellation(this, &SSHTransportPipe::receive_cancel));\n\n\t\tASSERT(receive_action_ != NULL);\n\t\tAction *a = receive_action_;\n\t\treceive_action_ = NULL;\n\t\treturn (a);\n\t}\n\nprivate:\n\tvoid consume(Buffer *in)\n\t{\n\t\t\/* XXX XXX XXX *\/\n\t\tif (in->empty()) {\n\t\t\tif (!input_buffer_.empty())\n\t\t\t\tDEBUG(log_) << \"Received EOS with data outstanding.\";\n\t\t\tBuffer eos;\n\t\t\tproduce(&eos);\n\t\t\treturn;\n\t\t}\n\n\t\tinput_buffer_.append(in);\n\t\tin->clear();\n\n\t\tif (state_ == GetIdentificationString) {\n\t\t\tHTTPProtocol::ParseStatus status;\n\n\t\t\twhile (!input_buffer_.empty()) {\n\t\t\t\tBuffer line;\n\t\t\t\tstatus = HTTPProtocol::ExtractLine(&line, &input_buffer_);\n\t\t\t\tswitch (status) {\n\t\t\t\tcase HTTPProtocol::ParseSuccess:\n\t\t\t\t\tbreak;\n\t\t\t\tcase HTTPProtocol::ParseFailure:\n\t\t\t\t\tERROR(log_) << \"Invalid line while waiting for identification string.\";\n\t\t\t\t\tproduce_error();\n\t\t\t\t\treturn;\n\t\t\t\tcase HTTPProtocol::ParseIncomplete:\n\t\t\t\t\t\/* Wait for more. *\/\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (!line.prefix(\"SSH-\"))\n\t\t\t\t\tcontinue; \/* Next line. *\/\n\n\t\t\t\tif (!line.prefix(\"SSH-2.0\")) {\n\t\t\t\t\tERROR(log_) << \"Unsupported version.\";\n\t\t\t\t\tproduce_error();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tstate_ = GetPacket;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tif (state_ == GetPacket && receive_callback_ != NULL)\n\t\t\treceive_do();\n\t}\n\n\tvoid receive_cancel(void)\n\t{\n\t\tif (receive_action_ != NULL) {\n\t\t\treceive_action_->cancel();\n\t\t\treceive_action_ = NULL;\n\t\t}\n\n\t\tif (receive_callback_ != NULL) {\n\t\t\tdelete receive_callback_;\n\t\t\treceive_callback_ = NULL;\n\t\t}\n\t}\n\n\tvoid receive_do(void)\n\t{\n\t\tASSERT(receive_action_ == NULL);\n\t\tASSERT(receive_callback_ != NULL);\n\n\t\tif (state_ != GetPacket)\n\t\t\treturn;\n\n\t\twhile (!input_buffer_.empty()) {\n\t\t\tBuffer packet;\n\t\t\tBuffer mac;\n\t\t\tuint32_t packet_len;\n\t\t\tuint8_t padding_len;\n\n\t\t\tif (input_buffer_.length() <= sizeof packet_len) {\n\t\t\t\tDEBUG(log_) << \"Waiting for packet length.\";\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tinput_buffer_.extract(&packet_len);\n\t\t\tpacket_len = BigEndian::decode(packet_len);\n\n\t\t\tif (packet_len == 0) {\n\t\t\t\tERROR(log_) << \"Need to handle 0-length packet.\";\n\t\t\t\tproduce_error();\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (input_buffer_.length() < sizeof packet_len + packet_len + mac_length_) {\n\t\t\t\tDEBUG(log_) << \"Need \" << sizeof packet_len + packet_len + mac_length_ << \"bytes; have \" << input_buffer_.length() << \".\";\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tinput_buffer_.moveout(&packet, sizeof packet_len, packet_len);\n\t\t\tif (mac_length_ != 0)\n\t\t\t\tinput_buffer_.moveout(&mac, 0, mac_length_);\n\n\t\t\tpadding_len = packet.peek();\n\t\t\tpacket.skip(sizeof padding_len);\n\t\t\tif (padding_len != 0) {\n\t\t\t\tif (packet.length() < padding_len) {\n\t\t\t\t\tERROR(log_) << \"Padding too large for packet.\";\n\t\t\t\t\tproduce_error();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tpacket.trim(padding_len);\n\t\t\t}\n\n\t\t\tif (packet.empty()) {\n\t\t\t\tERROR(log_) << \"Need to handle empty packet.\";\n\t\t\t\tproduce_error();\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t\/*\n\t\t\t * XXX\n\t\t\t * Handle Transport messages internally?\n\t\t\t *\/\n\n\t\t\treceive_callback_->param(Event(Event::Done, packet));\n\t\t\treceive_action_ = receive_callback_->schedule();\n\t\t\treceive_callback_ = NULL;\n\n\t\t\treturn;\n\t\t}\n\t}\n};\n\nclass SSHConnection {\n\tLogHandle log_;\n\tSocket *peer_;\n\tSSHTransportPipe *pipe_;\n\tAction *receive_action_;\n\tSplice *splice_;\n\tAction *splice_action_;\n\tAction *close_action_;\npublic:\n\tSSHConnection(Socket *peer)\n\t: log_(\"\/ssh\/connection\"),\n\t peer_(peer),\n\t pipe_(NULL),\n\t splice_(NULL),\n\t splice_action_(NULL),\n\t close_action_(NULL)\n\t{\n\t\tpipe_ = new SSHTransportPipe();\n\t\tEventCallback *rcb = callback(this, &SSHConnection::receive_complete);\n\t\treceive_action_ = pipe_->receive(rcb);\n\n\t\tsplice_ = new Splice(log_ + \"\/splice\", peer_, pipe_, peer_);\n\t\tEventCallback *cb = callback(this, &SSHConnection::splice_complete);\n\t\tsplice_action_ = splice_->start(cb);\n\t}\n\n\t~SSHConnection()\n\t{\n\t\tASSERT(close_action_ == NULL);\n\t\tASSERT(splice_action_ == NULL);\n\t\tASSERT(splice_ == NULL);\n\t\tASSERT(receive_action_ == NULL);\n\t\tASSERT(pipe_ == NULL);\n\t\tASSERT(peer_ == NULL);\n\t}\n\nprivate:\n\tvoid receive_complete(Event e)\n\t{\n\t\treceive_action_->cancel();\n\t\treceive_action_ = NULL;\n\n\t\tswitch (e.type_) {\n\t\tcase Event::Done:\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tERROR(log_) << \"Unexpected event while waiting for a packet: \" << e;\n\t\t\treturn;\n\t\t}\n\n\t\tASSERT(!e.buffer_.empty());\n\n\t\tswitch (e.buffer_.peek()) {\n\t\tcase SSH::Protocol::KeyExchangeInitializationMessage:\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tDEBUG(log_) << \"Received packet:\" << std::endl << e.buffer_.hexdump();\n\t\t\tbreak;\n\t\t}\n\n\t\tEventCallback *rcb = callback(this, &SSHConnection::receive_complete);\n\t\treceive_action_ = pipe_->receive(rcb);\n\t}\n\n\tvoid close_complete(void)\n\t{\n\t\tclose_action_->cancel();\n\t\tclose_action_ = NULL;\n\n\t\tASSERT(peer_ != NULL);\n\t\tdelete peer_;\n\t\tpeer_ = NULL;\n\n\t\tdelete this;\n\t}\n\n\tvoid splice_complete(Event e)\n\t{\n\t\tsplice_action_->cancel();\n\t\tsplice_action_ = NULL;\n\n\t\tswitch (e.type_) {\n\t\tcase Event::EOS:\n\t\t\tDEBUG(log_) << \"Peer exiting normally.\";\n\t\t\tbreak;\n\t\tcase Event::Error:\n\t\t\tERROR(log_) << \"Peer exiting with error: \" << e;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tERROR(log_) << \"Peer exiting with unknown event: \" << e;\n\t\t\tbreak;\n\t\t}\n\n\t ASSERT(splice_ != NULL);\n\t\tdelete splice_;\n\t\tsplice_ = NULL;\n\n\t\tif (receive_action_ != NULL) {\n\t\t\tINFO(log_) << \"Peer exiting while waiting for a packet.\";\n\n\t\t\treceive_action_->cancel();\n\t\t\treceive_action_ = NULL;\n\t\t}\n\n\t\tASSERT(pipe_ != NULL);\n\t\tdelete pipe_;\n\t\tpipe_ = NULL;\n\n\t\tASSERT(close_action_ == NULL);\n\t\tSimpleCallback *cb = callback(this, &SSHConnection::close_complete);\n\t\tclose_action_ = peer_->close(cb);\n\t}\n};\n\nclass SSHServer : public SimpleServer {\npublic:\n\tSSHServer(SocketAddressFamily family, const std::string& interface)\n\t: SimpleServer(\"\/ssh\/server\", family, interface)\n\t{ }\n\n\t~SSHServer()\n\t{ }\n\n\tvoid client_connected(Socket *client)\n\t{\n\t\tnew SSHConnection(client);\n\t}\n};\n\n\nint\nmain(void)\n{\n\tnew SSHServer(SocketAddressFamilyIP, \"[::]:2299\");\n\tevent_main();\n}\nAdd a basic transmit function, use it to mirror packets.#include \n\n#include \n#include \n#include \n\n#include \n\n#include \n\n#include \n#include \n#include \n\n#include \n\n#include \n\nnamespace {\n\tstatic uint8_t zero_padding[255];\n}\n\nclass SSHTransportPipe : public PipeProducer {\n\tenum State {\n\t\tGetIdentificationString,\n\t\tGetPacket\n\t};\n\n\tState state_;\n\tBuffer input_buffer_;\n\n\t\/* XXX These parameters are different for receive and send. *\/\n\tsize_t block_size_;\n\tsize_t mac_length_;\n\n\tEventCallback *receive_callback_;\n\tAction *receive_action_;\npublic:\n\tSSHTransportPipe(void)\n\t: PipeProducer(\"\/ssh\/transport\/pipe\"),\n\t state_(GetIdentificationString),\n\t block_size_(8),\n\t mac_length_(0),\n\t receive_callback_(NULL),\n\t receive_action_(NULL)\n\t{\n\t\tBuffer identification_string(\"SSH-2.0-WANProxy \" + (std::string)log_ + \"\\r\\n\");\n\t\tproduce(&identification_string);\n\t}\n\n\t~SSHTransportPipe()\n\t{\n\t\tASSERT(receive_callback_ == NULL);\n\t\tASSERT(receive_action_ == NULL);\n\t}\n\n\tAction *receive(EventCallback *cb)\n\t{\n\t\tASSERT(receive_callback_ == NULL);\n\t\tASSERT(receive_action_ == NULL);\n\n\t\t\/*\n\t\t * XXX\n\t\t * This pattern is implemented about three different\n\t\t * ways in the WANProxy codebase, and they are all kind\n\t\t * of awful. Need a better way to handle code that\n\t\t * needs executed either on the request of the caller\n\t\t * or when data comes in that satisfies a deferred\n\t\t * callback to a caller.\n\t\t *\/\n\t\treceive_callback_ = cb;\n\t\treceive_do();\n\n\t\tif (receive_callback_ != NULL)\n\t\t\treturn (cancellation(this, &SSHTransportPipe::receive_cancel));\n\n\t\tASSERT(receive_action_ != NULL);\n\t\tAction *a = receive_action_;\n\t\treceive_action_ = NULL;\n\t\treturn (a);\n\t}\n\n\t\/*\n\t * Because this is primarily for WAN optimization we always use minimal\n\t * padding and zero padding. Quick and dirty. Perhaps revisit later,\n\t * although it makes send() asynchronous unless we add a blocking\n\t * RNG interface.\n\t *\/\n\tvoid send(Buffer *payload)\n\t{\n\t\tBuffer packet;\n\t\tuint8_t padding_len;\n\t\tuint32_t packet_len;\n\n\t\tpacket_len = sizeof padding_len + payload->length();\n\t\tpadding_len = 4 + (block_size_ - ((sizeof packet_len + packet_len + 4) % block_size_));\n\t\tpacket_len += padding_len;\n\n\t\tpacket_len = BigEndian::encode(packet_len);\n\t\tpacket.append(&packet_len);\n\t\tpacket.append(padding_len);\n\t\tpacket.append(payload);\n\t\tpacket.append(zero_padding, padding_len);\n\n\t\tif (mac_length_ != 0)\n\t\t\tNOTREACHED();\n\n\t\tpayload->clear();\n\n\t\tproduce(&packet);\n\t}\n\nprivate:\n\tvoid consume(Buffer *in)\n\t{\n\t\t\/* XXX XXX XXX *\/\n\t\tif (in->empty()) {\n\t\t\tif (!input_buffer_.empty())\n\t\t\t\tDEBUG(log_) << \"Received EOS with data outstanding.\";\n\t\t\tBuffer eos;\n\t\t\tproduce(&eos);\n\t\t\treturn;\n\t\t}\n\n\t\tinput_buffer_.append(in);\n\t\tin->clear();\n\n\t\tif (state_ == GetIdentificationString) {\n\t\t\tHTTPProtocol::ParseStatus status;\n\n\t\t\twhile (!input_buffer_.empty()) {\n\t\t\t\tBuffer line;\n\t\t\t\tstatus = HTTPProtocol::ExtractLine(&line, &input_buffer_);\n\t\t\t\tswitch (status) {\n\t\t\t\tcase HTTPProtocol::ParseSuccess:\n\t\t\t\t\tbreak;\n\t\t\t\tcase HTTPProtocol::ParseFailure:\n\t\t\t\t\tERROR(log_) << \"Invalid line while waiting for identification string.\";\n\t\t\t\t\tproduce_error();\n\t\t\t\t\treturn;\n\t\t\t\tcase HTTPProtocol::ParseIncomplete:\n\t\t\t\t\t\/* Wait for more. *\/\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (!line.prefix(\"SSH-\"))\n\t\t\t\t\tcontinue; \/* Next line. *\/\n\n\t\t\t\tif (!line.prefix(\"SSH-2.0\")) {\n\t\t\t\t\tERROR(log_) << \"Unsupported version.\";\n\t\t\t\t\tproduce_error();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tstate_ = GetPacket;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tif (state_ == GetPacket && receive_callback_ != NULL)\n\t\t\treceive_do();\n\t}\n\n\tvoid receive_cancel(void)\n\t{\n\t\tif (receive_action_ != NULL) {\n\t\t\treceive_action_->cancel();\n\t\t\treceive_action_ = NULL;\n\t\t}\n\n\t\tif (receive_callback_ != NULL) {\n\t\t\tdelete receive_callback_;\n\t\t\treceive_callback_ = NULL;\n\t\t}\n\t}\n\n\tvoid receive_do(void)\n\t{\n\t\tASSERT(receive_action_ == NULL);\n\t\tASSERT(receive_callback_ != NULL);\n\n\t\tif (state_ != GetPacket)\n\t\t\treturn;\n\n\t\twhile (!input_buffer_.empty()) {\n\t\t\tBuffer packet;\n\t\t\tBuffer mac;\n\t\t\tuint32_t packet_len;\n\t\t\tuint8_t padding_len;\n\n\t\t\tif (input_buffer_.length() <= sizeof packet_len) {\n\t\t\t\tDEBUG(log_) << \"Waiting for packet length.\";\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tinput_buffer_.extract(&packet_len);\n\t\t\tpacket_len = BigEndian::decode(packet_len);\n\n\t\t\tif (packet_len == 0) {\n\t\t\t\tERROR(log_) << \"Need to handle 0-length packet.\";\n\t\t\t\tproduce_error();\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (input_buffer_.length() < sizeof packet_len + packet_len + mac_length_) {\n\t\t\t\tDEBUG(log_) << \"Need \" << sizeof packet_len + packet_len + mac_length_ << \"bytes; have \" << input_buffer_.length() << \".\";\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tinput_buffer_.moveout(&packet, sizeof packet_len, packet_len);\n\t\t\tif (mac_length_ != 0)\n\t\t\t\tinput_buffer_.moveout(&mac, 0, mac_length_);\n\n\t\t\tpadding_len = packet.peek();\n\t\t\tpacket.skip(sizeof padding_len);\n\t\t\tif (padding_len != 0) {\n\t\t\t\tif (packet.length() < padding_len) {\n\t\t\t\t\tERROR(log_) << \"Padding too large for packet.\";\n\t\t\t\t\tproduce_error();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tpacket.trim(padding_len);\n\t\t\t}\n\n\t\t\tif (packet.empty()) {\n\t\t\t\tERROR(log_) << \"Need to handle empty packet.\";\n\t\t\t\tproduce_error();\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t\/*\n\t\t\t * XXX\n\t\t\t * Handle Transport messages internally?\n\t\t\t *\/\n\n\t\t\treceive_callback_->param(Event(Event::Done, packet));\n\t\t\treceive_action_ = receive_callback_->schedule();\n\t\t\treceive_callback_ = NULL;\n\n\t\t\treturn;\n\t\t}\n\t}\n};\n\nclass SSHConnection {\n\tLogHandle log_;\n\tSocket *peer_;\n\tSSHTransportPipe *pipe_;\n\tAction *receive_action_;\n\tSplice *splice_;\n\tAction *splice_action_;\n\tAction *close_action_;\npublic:\n\tSSHConnection(Socket *peer)\n\t: log_(\"\/ssh\/connection\"),\n\t peer_(peer),\n\t pipe_(NULL),\n\t splice_(NULL),\n\t splice_action_(NULL),\n\t close_action_(NULL)\n\t{\n\t\tpipe_ = new SSHTransportPipe();\n\t\tEventCallback *rcb = callback(this, &SSHConnection::receive_complete);\n\t\treceive_action_ = pipe_->receive(rcb);\n\n\t\tsplice_ = new Splice(log_ + \"\/splice\", peer_, pipe_, peer_);\n\t\tEventCallback *cb = callback(this, &SSHConnection::splice_complete);\n\t\tsplice_action_ = splice_->start(cb);\n\t}\n\n\t~SSHConnection()\n\t{\n\t\tASSERT(close_action_ == NULL);\n\t\tASSERT(splice_action_ == NULL);\n\t\tASSERT(splice_ == NULL);\n\t\tASSERT(receive_action_ == NULL);\n\t\tASSERT(pipe_ == NULL);\n\t\tASSERT(peer_ == NULL);\n\t}\n\nprivate:\n\tvoid receive_complete(Event e)\n\t{\n\t\treceive_action_->cancel();\n\t\treceive_action_ = NULL;\n\n\t\tswitch (e.type_) {\n\t\tcase Event::Done:\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tERROR(log_) << \"Unexpected event while waiting for a packet: \" << e;\n\t\t\treturn;\n\t\t}\n\n\t\tASSERT(!e.buffer_.empty());\n\n\t\t\/*\n\t\t * SSH Echo!\n\t\t *\/\n\t\tpipe_->send(&e.buffer_);\n#if 0\n\t\tswitch (e.buffer_.peek()) {\n\t\tcase SSH::Protocol::KeyExchangeInitializationMessage:\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tDEBUG(log_) << \"Received packet:\" << std::endl << e.buffer_.hexdump();\n\t\t\tbreak;\n\t\t}\n#endif\n\n\t\tEventCallback *rcb = callback(this, &SSHConnection::receive_complete);\n\t\treceive_action_ = pipe_->receive(rcb);\n\t}\n\n\tvoid close_complete(void)\n\t{\n\t\tclose_action_->cancel();\n\t\tclose_action_ = NULL;\n\n\t\tASSERT(peer_ != NULL);\n\t\tdelete peer_;\n\t\tpeer_ = NULL;\n\n\t\tdelete this;\n\t}\n\n\tvoid splice_complete(Event e)\n\t{\n\t\tsplice_action_->cancel();\n\t\tsplice_action_ = NULL;\n\n\t\tswitch (e.type_) {\n\t\tcase Event::EOS:\n\t\t\tDEBUG(log_) << \"Peer exiting normally.\";\n\t\t\tbreak;\n\t\tcase Event::Error:\n\t\t\tERROR(log_) << \"Peer exiting with error: \" << e;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tERROR(log_) << \"Peer exiting with unknown event: \" << e;\n\t\t\tbreak;\n\t\t}\n\n\t ASSERT(splice_ != NULL);\n\t\tdelete splice_;\n\t\tsplice_ = NULL;\n\n\t\tif (receive_action_ != NULL) {\n\t\t\tINFO(log_) << \"Peer exiting while waiting for a packet.\";\n\n\t\t\treceive_action_->cancel();\n\t\t\treceive_action_ = NULL;\n\t\t}\n\n\t\tASSERT(pipe_ != NULL);\n\t\tdelete pipe_;\n\t\tpipe_ = NULL;\n\n\t\tASSERT(close_action_ == NULL);\n\t\tSimpleCallback *cb = callback(this, &SSHConnection::close_complete);\n\t\tclose_action_ = peer_->close(cb);\n\t}\n};\n\nclass SSHServer : public SimpleServer {\npublic:\n\tSSHServer(SocketAddressFamily family, const std::string& interface)\n\t: SimpleServer(\"\/ssh\/server\", family, interface)\n\t{ }\n\n\t~SSHServer()\n\t{ }\n\n\tvoid client_connected(Socket *client)\n\t{\n\t\tnew SSHConnection(client);\n\t}\n};\n\n\nint\nmain(void)\n{\n\tnew SSHServer(SocketAddressFamilyIP, \"[::]:2299\");\n\tevent_main();\n}\n<|endoftext|>"} {"text":"\/\/ terark-db-schema-compile.cpp : Defines the entry point for the console application.\n\/\/\n\n#include \"stdafx.h\"\n\n#define TERARK_DB_SCHEMA_COMPILER\n#include \n\n#if defined(_WIN32) || defined(_WIN64)\n#include \n#endif\n\nusing namespace std;\nusing namespace terark;\nusing namespace terark::db;\n\nint maxColnameLen(const Schema& schema) {\n\tconst size_t colnum = schema.columnNum();\n\tint maxNameLen = 0;\n\tfor (size_t i = 0; i < colnum; ++i) {\n\t\tconst fstring colname = schema.getColumnName(i);\n\t\tmaxNameLen = std::max(maxNameLen, colname.ilen());\n\t}\n\treturn maxNameLen;\n}\n\nvoid compileOneSchema(const Schema& schema, const char* className,\n\t\t\t\t\t const char* rowClassName) {\n\tconst size_t colnum = schema.columnNum();\n\tprintf(\" struct %s {\\n\", className);\n\tfor (size_t i = 0; i < colnum; ++i) {\n\t\tconst ColumnMeta& colmeta = schema.getColumnMeta(i);\n\t\tconst fstring colname = schema.getColumnName(i);\n\t\tswitch (colmeta.type) {\n\t\tcase ColumnType::Any:\n\t\t\tassert(0); \/\/ not supported now\n\t\t\tbreak;\n\t\tcase ColumnType::Nested:\n\t\t\tassert(0); \/\/ not supported now\n\t\t\tbreak;\n\t\tcase ColumnType::Uint08:\n\t\t\tprintf(\" unsigned char %s;\\n\", colname.p);\n\t\t\tbreak;\n\t\tcase ColumnType::Sint08:\n\t\t\tprintf(\" signed char %s;\\n\", colname.p);\n\t\t\tbreak;\n\t\tcase ColumnType::Uint16:\n\t\t\tprintf(\" std::uint16_t %s;\\n\", colname.p);\n\t\t\tbreak;\n\t\tcase ColumnType::Sint16:\n\t\t\tprintf(\" std::int16_t %s;\\n\", colname.p);\n\t\t\tbreak;\n\t\tcase ColumnType::Uint32:\n\t\t\tprintf(\" std::uint32_t %s;\\n\", colname.p);\n\t\t\tbreak;\n\t\tcase ColumnType::Sint32:\n\t\t\tprintf(\" std::int32_t %s;\\n\", colname.p);\n\t\t\tbreak;\n\t\tcase ColumnType::Uint64:\n\t\t\tprintf(\" std::uint64_t %s;\\n\", colname.p);\n\t\t\tbreak;\n\t\tcase ColumnType::Sint64:\n\t\t\tprintf(\" std::int64_t %s;\\n\", colname.p);\n\t\t\tbreak;\n\t\tcase ColumnType::Uint128:\n\t\t\tprintf(\" unsigned __int128 %s;\\n\", colname.p);\n\t\t\tbreak;\n\t\tcase ColumnType::Sint128:\n\t\t\tprintf(\" signed __int128 %s;\\n\", colname.p);\n\t\t\tbreak;\n\t\tcase ColumnType::Float32:\n\t\t\tprintf(\" float %s;\\n\", colname.p);\n\t\t\tbreak;\n\t\tcase ColumnType::Float64:\n\t\t\tprintf(\" double %s;\\n\", colname.p);\n\t\t\tbreak;\n\t\tcase ColumnType::Float128:\n\t\t\tprintf(\" __float128 %s;\\n\", colname.p);\n\t\t\tbreak;\n\t\tcase ColumnType::Decimal128:\n\t\t\tprintf(\" __decimal128 %s;\\n\", colname.p);\n\t\t\tbreak;\n\t\tcase ColumnType::Uuid:\n\t\t\tprintf(\" terark::db::Schema::Fixed<16> %s;\\n\", colname.p);\n\t\t\tbreak;\n\t\tcase ColumnType::Fixed:\n\t\t\tif (colmeta.realtype.empty()) {\n\t\t\t\tprintf(\" terark::db::Schema::Fixed<%d> %s;\\n\", int(colmeta.fixedLen), colname.p);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tconst char* realtype = colmeta.realtype.c_str();\n\t\t\t\tconst int fixlen = int(colmeta.fixedLen);\n\t\t\t\tprintf(R\"EOS(\n %s %s;\n \/\/ dumpable type does not require sizeof(T)==fixlen, it only requires that\n \/\/ dump_size(T)==fixlen, but check for dump_size(T)==fixlen is cumbersome\n \/\/ and requires big changes for terark.dataio\n \/\/ so we static assert sizeof(T)==fixlen here:\n BOOST_STATIC_ASSERT(sizeof(%s) == %d);\n BOOST_STATIC_ASSERT((terark::DataIO_is_dump, %s >::value));\n\n)EOS\", realtype, colname.p, realtype, fixlen, realtype);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase ColumnType::VarSint:\n\t\t\tprintf(\" terark::var_int64_t %s;\\n\", colname.p);\n\t\t\tbreak;\n\t\tcase ColumnType::VarUint:\n\t\t\tprintf(\" terark::var_uint64_t %s;\\n\", colname.p);\n\t\t\tbreak;\n\t\tcase ColumnType::StrZero:\n\t\t\tprintf(\" std::string %s;\\n\", colname.p);\n\t\t\tbreak;\n\t\tcase ColumnType::TwoStrZero:\n\t\t\tprintf(\" terark::db::Schema::TwoStrZero %s;\\n\", colname.p);\n\t\t\tbreak;\n\t\tcase ColumnType::Binary:\n\t\t\tif (colmeta.realtype.empty()) {\n\t\t\t\tprintf(\" std::string %s;\\n\", colname.p);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tconst char* realtype = colmeta.realtype.c_str();\n\t\t\t\tprintf(\" %s %s;\\n\", realtype, colname.p);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase ColumnType::CarBin:\n\t\t\tif (colmeta.realtype.empty()) {\n\t\t\t\tprintf(\" terark::db::Schema::CarBin %s;\\n\", colname.p);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tconst char* realtype = colmeta.realtype.c_str();\n\t\t\t\tprintf(\" %s %s;\\n\", realtype, colname.p);\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t}\n\tprintf(\"\\n\");\n\tprintf(\" DATA_IO_LOAD_SAVE(%s,\\n\", className);\n\tfor (size_t i = 0; i < colnum; ++i) {\n\t\tconst ColumnMeta& colmeta = schema.getColumnMeta(i);\n\t\tconst fstring colname = schema.getColumnName(i);\n\t\tswitch (colmeta.type) {\n\t\tcase ColumnType::Any:\n\t\t\tassert(0); \/\/ not supported now\n\t\t\tbreak;\n\t\tcase ColumnType::Nested:\n\t\t\tassert(0); \/\/ not supported now\n\t\t\tbreak;\n\t\tcase ColumnType::Uint08:\n\t\tcase ColumnType::Sint08:\n\t\tcase ColumnType::Uint16:\n\t\tcase ColumnType::Sint16:\n\t\tcase ColumnType::Uint32:\n\t\tcase ColumnType::Sint32:\n\t\tcase ColumnType::Uint64:\n\t\tcase ColumnType::Sint64:\n\t\tcase ColumnType::Uint128:\n\t\tcase ColumnType::Sint128:\n\t\tcase ColumnType::Float32:\n\t\tcase ColumnType::Float64:\n\t\tcase ColumnType::Float128:\n\t\tcase ColumnType::Decimal128:\n\t\tcase ColumnType::Uuid:\n\t\tcase ColumnType::Fixed:\n\t\tcase ColumnType::VarSint:\n\t\tcase ColumnType::VarUint:\n\t\t\tprintf(\" &%s\\n\", colname.p);\n\t\t\tbreak;\n\t\tcase ColumnType::StrZero:\n\t\t\tif (i < colnum-1) {\n\t\t\t\tprintf(\" &terark::db::Schema::StrZero(%s)\\n\", colname.p);\n\t\t\t} else {\n\t\t\t\tprintf(\" &terark::RestAll(%s)\\n\", colname.p);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase ColumnType::TwoStrZero:\n\t\tcase ColumnType::Binary:\n\t\tCase_Binary:\n\t\t\tif (i < colnum-1) {\n\t\t\t\tprintf(\" &%s\\n\", colname.p);\n\t\t\t} else {\n\t\t\t\tprintf(\" &terark::RestAll(%s)\\n\", colname.p);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase ColumnType::CarBin:\n\t\t\tif (colmeta.realtype.empty()) {\n\t\t\t\tgoto Case_Binary;\n\t\t\t}\n\t\t\tif (i < colnum-1) {\n\t\t\t\t\/\/ read carbin size and check carbin size with real size\n\t\t\t\tprintf(\" &terark::db::Schema::CarBinPack(%s)\\n\", colname.p);\n\t\t\t} else {\n\t\t\t\tprintf(\" &%s\\n\", colname.p);\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t}\n\tprintf(\" )\\n\");\n\tprintf(\nR\"EOS(\n %s& decode(terark::fstring ___row) {\n terark::NativeDataInput ___dio(___row.range());\n ___dio >> *this;\n return *this;\n }\n terark::fstring\n encode(terark::NativeDataOutput& ___dio) const {\n ___dio.rewind();\n ___dio << *this;\n return ___dio.written();\n }\n)EOS\", className\n\t);\n\tint maxNameLen = maxColnameLen(schema);\n\tprintf(\" %s& select(const %s& ___row) {\\n\", className, rowClassName);\n\tfor (size_t i = 0; i < colnum; ++i) {\n\t\tconst char* colname = schema.getColumnName(i).c_str();\n\t\tprintf(\" %-*s = ___row.%s;\\n\", maxNameLen, colname, colname);\n\t}\n\tprintf(\" return *this;\\n\"); \/\/ select\n\tprintf(\" }\\n\"); \/\/ select\n\tprintf(\" void assign_to(%s& ___row) const {\\n\", rowClassName);\n\tfor (size_t i = 0; i < colnum; ++i) {\n\t\tconst char* colname = schema.getColumnName(i).c_str();\n\t\tprintf(\" ___row.%-*s = %s;\\n\", maxNameLen, colname, colname);\n\t}\n\tprintf(\" }\\n\"); \/\/ select\n\n\tprintf(\" }; \/\/ %s\\n\\n\", className);\n}\n\nint usage(const char* prog) {\n\tfprintf(stderr, \"usage: %s [ options ] terark-db-schema-file namespace table-name\\n\", prog);\n\treturn 1;\n}\n\nint main(int argc, char* argv[]) {\n\tstd::vector includes;\n\tfor (;;) {\n\t\tint opt = getopt(argc, argv, \"i:\");\n\t\tswitch (opt) {\n\t\tcase -1:\n\t\t\tgoto GetoptDone;\n\t\tcase '?':\n\t\t\treturn usage(argv[0]);\n\t\tcase 'i':\n\t\t\tincludes.push_back(optarg);\n\t\t\tbreak;\n\t\t}\n\t}\nGetoptDone:\n\tif (argc - optind < 3) {\n\t\treturn usage(argv[0]);\n\t}\n\tconst char* jsonFilePath = argv[optind + 0];\n\tconst char* ns = argv[optind + 1];\n\tconst char* tabName = argv[optind + 2];\n\tSchemaConfig sconf;\n\ttry {\n\t\tsconf.loadJsonFile(jsonFilePath);\n\t}\n\tcatch (const std::exception& ex) {\n\t\tfprintf(stderr, \"ERROR: loadJsonFile(%s) failed: %s\\n\", jsonFilePath, ex.what());\n\t\treturn 1;\n\t}\n\tprintf(R\"EOS(#pragma once\n#include \n#include \n#include \n#include \n#include \n\n)EOS\");\n\tfor (const char* inc : includes) {\n\t\tprintf(\"#include \\\"%s\\\"\\n\", inc);\n\t}\n\tprintf(\"\\n\");\n\tprintf(\"namespace %s {\\n\", ns);\n\tcompileOneSchema(*sconf.m_rowSchema, tabName, tabName);\n\tfor (size_t i = 0; i < sconf.m_colgroupSchemaSet->indexNum(); ++i) {\n\t\tconst Schema& schema = *sconf.m_colgroupSchemaSet->getSchema(i);\n\t\tif (schema.columnNum() == 1)\n\t\t\tcontinue;\n\t\tstd::string cgName = schema.m_name;\n\t\tstd::transform(cgName.begin(), cgName.end(), cgName.begin(),\n\t\t\t[](unsigned char ch) -> char {\n\t\t\t\tif (isalnum(ch) || '_' == ch)\n\t\t\t\t\treturn ch;\n\t\t\t\telse\n\t\t\t\t\treturn '_';\n\t\t\t});\n\t\tstd::string className = tabName;\n\t\tclassName += \"_Colgroup_\";\n\t\tclassName += cgName;\n\t\tcompileOneSchema(schema, className.c_str(), tabName);\n\t\tif (i < sconf.m_indexSchemaSet->indexNum()) {\n\t\t\tprintf(\" typedef %s %s_Index_%s;\\n\\n\", className.c_str(), tabName, cgName.c_str());\n\t\t}\n\t}\n\tprintf(\"} \/\/ namespace %s\\n\", ns);\n return 0;\n}\n\nterark-db-schema-compile: Add checkSchema()\/\/ terark-db-schema-compile.cpp : Defines the entry point for the console application.\n\/\/\n\n#include \"stdafx.h\"\n\n#define TERARK_DB_SCHEMA_COMPILER\n#include \n\n#if defined(_WIN32) || defined(_WIN64)\n#include \n#endif\n\nusing namespace std;\nusing namespace terark;\nusing namespace terark::db;\n\nint maxColnameLen(const Schema& schema) {\n\tconst size_t colnum = schema.columnNum();\n\tint maxNameLen = 0;\n\tfor (size_t i = 0; i < colnum; ++i) {\n\t\tconst fstring colname = schema.getColumnName(i);\n\t\tmaxNameLen = std::max(maxNameLen, colname.ilen());\n\t}\n\treturn maxNameLen;\n}\n\nvoid compileOneSchema(const Schema& schema, const char* className,\n\t\t\t\t\t const char* rowClassName) {\n\tconst size_t colnum = schema.columnNum();\n\tprintf(\" struct %s {\\n\", className);\n\tfor (size_t i = 0; i < colnum; ++i) {\n\t\tconst ColumnMeta& colmeta = schema.getColumnMeta(i);\n\t\tconst fstring colname = schema.getColumnName(i);\n\t\tswitch (colmeta.type) {\n\t\tcase ColumnType::Any:\n\t\t\tassert(0); \/\/ not supported now\n\t\t\tbreak;\n\t\tcase ColumnType::Nested:\n\t\t\tassert(0); \/\/ not supported now\n\t\t\tbreak;\n\t\tcase ColumnType::Uint08:\n\t\t\tprintf(\" unsigned char %s;\\n\", colname.p);\n\t\t\tbreak;\n\t\tcase ColumnType::Sint08:\n\t\t\tprintf(\" signed char %s;\\n\", colname.p);\n\t\t\tbreak;\n\t\tcase ColumnType::Uint16:\n\t\t\tprintf(\" std::uint16_t %s;\\n\", colname.p);\n\t\t\tbreak;\n\t\tcase ColumnType::Sint16:\n\t\t\tprintf(\" std::int16_t %s;\\n\", colname.p);\n\t\t\tbreak;\n\t\tcase ColumnType::Uint32:\n\t\t\tprintf(\" std::uint32_t %s;\\n\", colname.p);\n\t\t\tbreak;\n\t\tcase ColumnType::Sint32:\n\t\t\tprintf(\" std::int32_t %s;\\n\", colname.p);\n\t\t\tbreak;\n\t\tcase ColumnType::Uint64:\n\t\t\tprintf(\" std::uint64_t %s;\\n\", colname.p);\n\t\t\tbreak;\n\t\tcase ColumnType::Sint64:\n\t\t\tprintf(\" std::int64_t %s;\\n\", colname.p);\n\t\t\tbreak;\n\t\tcase ColumnType::Uint128:\n\t\t\tprintf(\" unsigned __int128 %s;\\n\", colname.p);\n\t\t\tbreak;\n\t\tcase ColumnType::Sint128:\n\t\t\tprintf(\" signed __int128 %s;\\n\", colname.p);\n\t\t\tbreak;\n\t\tcase ColumnType::Float32:\n\t\t\tprintf(\" float %s;\\n\", colname.p);\n\t\t\tbreak;\n\t\tcase ColumnType::Float64:\n\t\t\tprintf(\" double %s;\\n\", colname.p);\n\t\t\tbreak;\n\t\tcase ColumnType::Float128:\n\t\t\tprintf(\" __float128 %s;\\n\", colname.p);\n\t\t\tbreak;\n\t\tcase ColumnType::Decimal128:\n\t\t\tprintf(\" __decimal128 %s;\\n\", colname.p);\n\t\t\tbreak;\n\t\tcase ColumnType::Uuid:\n\t\t\tprintf(\" terark::db::Schema::Fixed<16> %s;\\n\", colname.p);\n\t\t\tbreak;\n\t\tcase ColumnType::Fixed:\n\t\t\tif (colmeta.realtype.empty()) {\n\t\t\t\tprintf(\" terark::db::Schema::Fixed<%d> %s;\\n\", int(colmeta.fixedLen), colname.p);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tconst char* realtype = colmeta.realtype.c_str();\n\t\t\t\tconst int fixlen = int(colmeta.fixedLen);\n\t\t\t\tprintf(R\"EOS(\n %s %s;\n \/\/ dumpable type does not require sizeof(T)==fixlen, it only requires that\n \/\/ dump_size(T)==fixlen, but check for dump_size(T)==fixlen is cumbersome\n \/\/ and requires big changes for terark.dataio\n \/\/ so we static assert sizeof(T)==fixlen here:\n BOOST_STATIC_ASSERT(sizeof(%s) == %d);\n BOOST_STATIC_ASSERT((terark::DataIO_is_dump, %s >::value));\n\n)EOS\", realtype, colname.p, realtype, fixlen, realtype);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase ColumnType::VarSint:\n\t\t\tprintf(\" terark::var_int64_t %s;\\n\", colname.p);\n\t\t\tbreak;\n\t\tcase ColumnType::VarUint:\n\t\t\tprintf(\" terark::var_uint64_t %s;\\n\", colname.p);\n\t\t\tbreak;\n\t\tcase ColumnType::StrZero:\n\t\t\tprintf(\" std::string %s;\\n\", colname.p);\n\t\t\tbreak;\n\t\tcase ColumnType::TwoStrZero:\n\t\t\tprintf(\" terark::db::Schema::TwoStrZero %s;\\n\", colname.p);\n\t\t\tbreak;\n\t\tcase ColumnType::Binary:\n\t\t\tif (colmeta.realtype.empty()) {\n\t\t\t\tprintf(\" std::string %s;\\n\", colname.p);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tconst char* realtype = colmeta.realtype.c_str();\n\t\t\t\tprintf(\" %s %s;\\n\", realtype, colname.p);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase ColumnType::CarBin:\n\t\t\tif (colmeta.realtype.empty()) {\n\t\t\t\tprintf(\" terark::db::Schema::CarBin %s;\\n\", colname.p);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tconst char* realtype = colmeta.realtype.c_str();\n\t\t\t\tprintf(\" %s %s;\\n\", realtype, colname.p);\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t}\n\tprintf(\"\\n\");\n\tprintf(\" DATA_IO_LOAD_SAVE(%s,\\n\", className);\n\tfor (size_t i = 0; i < colnum; ++i) {\n\t\tconst ColumnMeta& colmeta = schema.getColumnMeta(i);\n\t\tconst fstring colname = schema.getColumnName(i);\n\t\tswitch (colmeta.type) {\n\t\tcase ColumnType::Any:\n\t\t\tassert(0); \/\/ not supported now\n\t\t\tbreak;\n\t\tcase ColumnType::Nested:\n\t\t\tassert(0); \/\/ not supported now\n\t\t\tbreak;\n\t\tcase ColumnType::Uint08:\n\t\tcase ColumnType::Sint08:\n\t\tcase ColumnType::Uint16:\n\t\tcase ColumnType::Sint16:\n\t\tcase ColumnType::Uint32:\n\t\tcase ColumnType::Sint32:\n\t\tcase ColumnType::Uint64:\n\t\tcase ColumnType::Sint64:\n\t\tcase ColumnType::Uint128:\n\t\tcase ColumnType::Sint128:\n\t\tcase ColumnType::Float32:\n\t\tcase ColumnType::Float64:\n\t\tcase ColumnType::Float128:\n\t\tcase ColumnType::Decimal128:\n\t\tcase ColumnType::Uuid:\n\t\tcase ColumnType::Fixed:\n\t\tcase ColumnType::VarSint:\n\t\tcase ColumnType::VarUint:\n\t\t\tprintf(\" &%s\\n\", colname.p);\n\t\t\tbreak;\n\t\tcase ColumnType::StrZero:\n\t\t\tif (i < colnum-1) {\n\t\t\t\tprintf(\" &terark::db::Schema::StrZero(%s)\\n\", colname.p);\n\t\t\t} else {\n\t\t\t\tprintf(\" &terark::RestAll(%s)\\n\", colname.p);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase ColumnType::TwoStrZero:\n\t\tcase ColumnType::Binary:\n\t\tCase_Binary:\n\t\t\tif (i < colnum-1) {\n\t\t\t\tprintf(\" &%s\\n\", colname.p);\n\t\t\t} else {\n\t\t\t\tprintf(\" &terark::RestAll(%s)\\n\", colname.p);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase ColumnType::CarBin:\n\t\t\tif (colmeta.realtype.empty()) {\n\t\t\t\tgoto Case_Binary;\n\t\t\t}\n\t\t\tif (i < colnum-1) {\n\t\t\t\t\/\/ read carbin size and check carbin size with real size\n\t\t\t\tprintf(\" &terark::db::Schema::CarBinPack(%s)\\n\", colname.p);\n\t\t\t} else {\n\t\t\t\tprintf(\" &%s\\n\", colname.p);\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t}\n\tprintf(\" )\\n\");\n\tprintf(\nR\"EOS(\n %s& decode(terark::fstring ___row) {\n terark::NativeDataInput ___dio(___row.range());\n ___dio >> *this;\n return *this;\n }\n terark::fstring\n encode(terark::NativeDataOutput& ___dio) const {\n ___dio.rewind();\n ___dio << *this;\n return ___dio.written();\n }\n)EOS\", className\n\t);\n\tif (fstring(className) != rowClassName) {\n\t\tint maxNameLen = maxColnameLen(schema);\n\t\tprintf(\" %s& select(const %s& ___row) {\\n\", className, rowClassName);\n\t\tfor (size_t i = 0; i < colnum; ++i) {\n\t\t\tconst char* colname = schema.getColumnName(i).c_str();\n\t\t\tprintf(\" %-*s = ___row.%s;\\n\", maxNameLen, colname, colname);\n\t\t}\n\t\tprintf(\" return *this;\\n\"); \/\/ select\n\t\tprintf(\" }\\n\"); \/\/ select\n\t\tprintf(\" void assign_to(%s& ___row) const {\\n\", rowClassName);\n\t\tfor (size_t i = 0; i < colnum; ++i) {\n\t\t\tconst char* colname = schema.getColumnName(i).c_str();\n\t\t\tprintf(\" ___row.%-*s = %s;\\n\", maxNameLen, colname, colname);\n\t\t}\n\t\tprintf(\" }\\n\"); \/\/ select\n\t}\n\tprintf(\nR\"EOS(\n static const terark::db::Schema& getSchema() {\n using namespace terark::db;\n static Schema schema;\n \/\/ static std::mutex mtx;\n \/\/ std::unique_lock lock(mtx);\n if (schema.columnNum() == 0) {\n)EOS\");\n\tfor (size_t i = 0; i < colnum; ++i) {\n\t\tconst char* colname = schema.getColumnName(i).c_str();\n\t\tconst auto& colmeta = schema.getColumnMeta(i);\n\t\tprintf(\nR\"EOS( {\n ColumnMeta colmeta(ColumnType::%s);\n colmeta.fixedLen = %d;\n schema.m_columnsMeta.insert_i(\"%s\", colmeta);\n }\n)EOS\", colmeta.typeNameString(), colmeta.fixedLen, colname\n\t\t);\n\t}\n\tprintf(\nR\"EOS( }\n return schema;\n }\n)EOS\"); \/\/ getSchema\n\n\tprintf(\nR\"EOS(\n static bool\n checkSchema(const terark::db::Schema& schema, bool checkColname = false) {\n using namespace terark;\n using namespace terark::db;\n if (schema.columnNum() != %zd) {\n return false;\n }\n)EOS\", colnum);\n\tfor (size_t i = 0; i < colnum; ++i) {\n\t\tconst char* colname = schema.getColumnName(i).c_str();\n\t\tconst auto& colmeta = schema.getColumnMeta(i);\n\t\tsize_t fixlen = colmeta.fixedLen;\n\t\tprintf(\nR\"EOS( {\n const fstring colname = schema.getColumnName(%zd);\n const ColumnMeta& colmeta = schema.getColumnMeta(%zd);\n if (checkColname && colname != \"%s\") {\n return false;\n }\n if (colmeta.type != ColumnType::%s) {\n return false;\n }\n if (colmeta.fixedLen != %zd) {\n assert(colmeta.type == ColumnType::Fixed);\n return false;\n }\n }\n)EOS\", i, i, colname, colmeta.typeNameString(), fixlen);\n\t}\n\tprintf(\nR\"EOS( return true;\n }\n)EOS\"); \/\/ checkSchema\n\n\tprintf(\" }; \/\/ %s\\n\\n\", className);\n}\n\nint usage(const char* prog) {\n\tfprintf(stderr, \"usage: %s [ options ] terark-db-schema-file namespace table-name\\n\", prog);\n\treturn 1;\n}\n\nint main(int argc, char* argv[]) {\n\tstd::vector includes;\n\tfor (;;) {\n\t\tint opt = getopt(argc, argv, \"i:\");\n\t\tswitch (opt) {\n\t\tcase -1:\n\t\t\tgoto GetoptDone;\n\t\tcase '?':\n\t\t\treturn usage(argv[0]);\n\t\tcase 'i':\n\t\t\tincludes.push_back(optarg);\n\t\t\tbreak;\n\t\t}\n\t}\nGetoptDone:\n\tif (argc - optind < 3) {\n\t\treturn usage(argv[0]);\n\t}\n\tconst char* jsonFilePath = argv[optind + 0];\n\tconst char* ns = argv[optind + 1];\n\tconst char* tabName = argv[optind + 2];\n\tSchemaConfig sconf;\n\ttry {\n\t\tsconf.loadJsonFile(jsonFilePath);\n\t}\n\tcatch (const std::exception& ex) {\n\t\tfprintf(stderr, \"ERROR: loadJsonFile(%s) failed: %s\\n\", jsonFilePath, ex.what());\n\t\treturn 1;\n\t}\n\tprintf(R\"EOS(#pragma once\n#include \n#include \n#include \n#include \n#include \n\n)EOS\");\n\tfor (const char* inc : includes) {\n\t\tprintf(\"#include \\\"%s\\\"\\n\", inc);\n\t}\n\tprintf(\"\\n\");\n\tprintf(\"namespace %s {\\n\", ns);\n\tcompileOneSchema(*sconf.m_rowSchema, tabName, tabName);\n\tfor (size_t i = 0; i < sconf.m_colgroupSchemaSet->indexNum(); ++i) {\n\t\tconst Schema& schema = *sconf.m_colgroupSchemaSet->getSchema(i);\n\t\tif (schema.columnNum() == 1)\n\t\t\tcontinue;\n\t\tstd::string cgName = schema.m_name;\n\t\tstd::transform(cgName.begin(), cgName.end(), cgName.begin(),\n\t\t\t[](unsigned char ch) -> char {\n\t\t\t\tif (isalnum(ch) || '_' == ch)\n\t\t\t\t\treturn ch;\n\t\t\t\telse\n\t\t\t\t\treturn '_';\n\t\t\t});\n\t\tstd::string className = tabName;\n\t\tclassName += \"_Colgroup_\";\n\t\tclassName += cgName;\n\t\tcompileOneSchema(schema, className.c_str(), tabName);\n\t\tif (i < sconf.m_indexSchemaSet->indexNum()) {\n\t\t\tprintf(\" typedef %s %s_Index_%s;\\n\\n\", className.c_str(), tabName, cgName.c_str());\n\t\t}\n\t}\n\tprintf(\"} \/\/ namespace %s\\n\", ns);\n return 0;\n}\n\n<|endoftext|>"} {"text":"\/\/=============================================================================================================\n\/**\n* @file main.cpp\n* @author Ruben Dörfel ;\n* Matti Hamalainen \n* @version 1.0\n* @date 11, 2019\n*\n* @section LICENSE\n*\n* Copyright (C) 2019, Ruben Doerrfel and Matti Hamalainen. All rights reserved.\n*\n* Redistribution and use in source and binary forms, with or without modification, are permitted provided that\n* the following conditions are met:\n* * Redistributions of source code must retain the above copyright notice, this list of conditions and the\n* following disclaimer.\n* * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and\n* the following disclaimer in the documentation and\/or other materials provided with the distribution.\n* * Neither the name of MNE-CPP authors nor the names of its contributors may be used\n* to endorse or promote products derived from this software without specific prior written permission.\n*\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED\n* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n* POSSIBILITY OF SUCH DAMAGE.\n*\n*\n* @brief Example for filtering of data with realtime filtering. This example is combined with\n* ex_read_write_raw for reading and writing fiff files. So the result of the filtering can be seen\n* in MNE-Browse.\n*\n*\/\n\n\/\/*************************************************************************************************************\n\/\/=============================================================================================================\n\/\/ INCLUDES\n\/\/=============================================================================================================\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \n\n\/\/*************************************************************************************************************\n\/\/=============================================================================================================\n\/\/ Qt INCLUDES\n\/\/=============================================================================================================\n\n#include \n#include \n#include \n\n\n\/\/*************************************************************************************************************\n\/\/=============================================================================================================\n\/\/ USED NAMESPACES\n\/\/=============================================================================================================\n\nusing namespace FIFFLIB;\nusing namespace UTILSLIB;\nusing namespace RTPROCESSINGLIB;\n\n\/\/*************************************************************************************************************\n\/\/=============================================================================================================\n\/\/ MAIN\n\/\/=============================================================================================================\n\n\/\/=============================================================================================================\n\/**\n* The function main marks the entry point of the program.\n* By default, main has the storage class extern.\n*\n* @param [in] argc (argument count) is an integer that indicates how many arguments were entered on the command line when the program was started.\n* @param [in] argv (argument vector) is an array of pointers to arrays of character objects. The array objects are null-terminated strings, representing the arguments that were entered on the command line when the program was started.\n* @return the value that was set to exit() (which is 0 if exit() is called via quit()).\n*\/\nint main(int argc, char *argv[])\n{\n QElapsedTimer timer;\n\n QCoreApplication a(argc, argv);\n\n \/\/ Command Line Parser\n QCommandLineParser parser;\n parser.setApplicationDescription(\"Read Write Raw Example\");\n parser.addHelpOption();\n\n QCommandLineOption inputOption(\"fileIn\", \"The input file .\", \"in\", QCoreApplication::applicationDirPath() + \"\/MNE-sample-data\/MEG\/sample\/sample_audvis_raw.fif\");\n QCommandLineOption outputOption(\"fileOut\", \"The output file .\", \"out\", QCoreApplication::applicationDirPath() + \"\/MNE-sample-data\/MEG\/sample\/test_output.fif\");\n\n parser.addOption(inputOption);\n parser.addOption(outputOption);\n\n parser.process(a);\n\n \/\/ Init data loading and writing\n QFile t_fileIn(parser.value(inputOption));\n QFile t_fileOut(parser.value(outputOption));\n\n FiffRawData raw(t_fileIn);\n\n \/\/ Set up pick list: MEG + STI 014 - bad channels\n bool want_meg = true;\n bool want_eeg = true;\n bool want_stim = true;\n QStringList include;\n include << \"STI 014\";\n\n MatrixXi picks = raw.info.pick_types(want_meg, want_eeg, want_stim, include, raw.info.bads);\n if(picks.cols() == 0) {\n include.clear();\n include << \"STI101\" << \"STI201\" << \"STI301\";\n picks = raw.info.pick_types(want_meg, want_eeg, want_stim, include, raw.info.bads);\n if(picks.cols() == 0) {\n printf(\"channel list may need modification\\n\");\n return -1;\n }\n }\n\n RowVectorXd cals;\n FiffStream::SPtr outfid = FiffStream::start_writing_raw(t_fileOut, raw.info, cals\/*, picks*\/);\n\n \/\/ Set up the reading parameters\n fiff_int_t from = raw.first_samp;\n fiff_int_t to = raw.last_samp;\n\n \/\/ To read the whole file at once set quantum = to - from + 1;\n fiff_int_t quantum = to - from + 1;\n\n \/\/ Read and write the data\n bool first_buffer = true;\n\n fiff_int_t first, last;\n MatrixXd data;\n MatrixXd times;\n\n \/\/ initialize filter settings\n QString filter_name = \"example_cosine\";\n FilterData::FilterType type = FilterData::BPF;\n double sFreq = raw.info.sfreq; \/\/ get Sample freq from Data\n double centerfreq = 10\/(sFreq\/2.0); \/\/ normed nyquist freq.\n double bandwidth = 10\/(sFreq\/2.0);\n double parkswidth = 1\/(sFreq\/2.0);\n\n\n RtFilter rtFilter; \/\/ filter object\n MatrixXd dataFiltered; \/\/ filter output\n\n \/\/ channel selection - in this case use every channel\n \/\/ size = number of channels; value = index channel number\n QVector channelList(raw.info.nchan);\n for (int i = 0; i < raw.info.nchan; i++){\n channelList[i] = i;\n }\n\n for(first = from; first < to; first+=quantum) {\n last = first+quantum-1;\n if (last > to) {\n last = to;\n }\n\n if(!raw.read_raw_segment(data,times,first,last\/*,picks*\/)) {\n printf(\"error during read_raw_segment\\n\");\n return -1;\n }\n\n \/\/Filtering\n printf(\"Filtering...\");\n dataFiltered = rtFilter.filterData(data,type,centerfreq,bandwidth,parkswidth,sFreq,channelList);\n printf(\"[done]\\n\");\n\n \/\/Writing\n printf(\"Writing...\");\n if(first_buffer) {\n if(first > 0) {\n outfid->write_int(FIFF_FIRST_SAMPLE, &first);\n }\n first_buffer = false;\n }\n\n outfid->write_raw_buffer(dataFiltered,cals);\n printf(\"[done]\\n\");\n }\n\n outfid->finish_writing_raw();\n\n printf(\"Finished\\n\");\n\n return 0;\n}\nex_filtering: remove Timer for performance testing\/\/=============================================================================================================\n\/**\n* @file main.cpp\n* @author Ruben Dörfel ;\n* Matti Hamalainen \n* @version 1.0\n* @date 11, 2019\n*\n* @section LICENSE\n*\n* Copyright (C) 2019, Ruben Doerrfel and Matti Hamalainen. All rights reserved.\n*\n* Redistribution and use in source and binary forms, with or without modification, are permitted provided that\n* the following conditions are met:\n* * Redistributions of source code must retain the above copyright notice, this list of conditions and the\n* following disclaimer.\n* * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and\n* the following disclaimer in the documentation and\/or other materials provided with the distribution.\n* * Neither the name of MNE-CPP authors nor the names of its contributors may be used\n* to endorse or promote products derived from this software without specific prior written permission.\n*\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED\n* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n* POSSIBILITY OF SUCH DAMAGE.\n*\n*\n* @brief Example for filtering of data with realtime filtering. This example is combined with\n* ex_read_write_raw for reading and writing fiff files. So the result of the filtering can be seen\n* in MNE-Browse.\n*\n*\/\n\n\/\/*************************************************************************************************************\n\/\/=============================================================================================================\n\/\/ INCLUDES\n\/\/=============================================================================================================\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \n\n\/\/*************************************************************************************************************\n\/\/=============================================================================================================\n\/\/ Qt INCLUDES\n\/\/=============================================================================================================\n\n#include \n#include \n#include \n\n\n\/\/*************************************************************************************************************\n\/\/=============================================================================================================\n\/\/ USED NAMESPACES\n\/\/=============================================================================================================\n\nusing namespace FIFFLIB;\nusing namespace UTILSLIB;\nusing namespace RTPROCESSINGLIB;\n\n\/\/*************************************************************************************************************\n\/\/=============================================================================================================\n\/\/ MAIN\n\/\/=============================================================================================================\n\n\/\/=============================================================================================================\n\/**\n* The function main marks the entry point of the program.\n* By default, main has the storage class extern.\n*\n* @param [in] argc (argument count) is an integer that indicates how many arguments were entered on the command line when the program was started.\n* @param [in] argv (argument vector) is an array of pointers to arrays of character objects. The array objects are null-terminated strings, representing the arguments that were entered on the command line when the program was started.\n* @return the value that was set to exit() (which is 0 if exit() is called via quit()).\n*\/\nint main(int argc, char *argv[])\n{\n QCoreApplication a(argc, argv);\n\n \/\/ Command Line Parser\n QCommandLineParser parser;\n parser.setApplicationDescription(\"Read Write Raw Example\");\n parser.addHelpOption();\n\n QCommandLineOption inputOption(\"fileIn\", \"The input file .\", \"in\", QCoreApplication::applicationDirPath() + \"\/MNE-sample-data\/MEG\/sample\/sample_audvis_raw.fif\");\n QCommandLineOption outputOption(\"fileOut\", \"The output file .\", \"out\", QCoreApplication::applicationDirPath() + \"\/MNE-sample-data\/MEG\/sample\/test_output.fif\");\n\n parser.addOption(inputOption);\n parser.addOption(outputOption);\n\n parser.process(a);\n\n \/\/ Init data loading and writing\n QFile t_fileIn(parser.value(inputOption));\n QFile t_fileOut(parser.value(outputOption));\n\n FiffRawData raw(t_fileIn);\n\n \/\/ Set up pick list: MEG + STI 014 - bad channels\n bool want_meg = true;\n bool want_eeg = true;\n bool want_stim = true;\n QStringList include;\n include << \"STI 014\";\n\n MatrixXi picks = raw.info.pick_types(want_meg, want_eeg, want_stim, include, raw.info.bads);\n if(picks.cols() == 0) {\n include.clear();\n include << \"STI101\" << \"STI201\" << \"STI301\";\n picks = raw.info.pick_types(want_meg, want_eeg, want_stim, include, raw.info.bads);\n if(picks.cols() == 0) {\n printf(\"channel list may need modification\\n\");\n return -1;\n }\n }\n\n RowVectorXd cals;\n FiffStream::SPtr outfid = FiffStream::start_writing_raw(t_fileOut, raw.info, cals\/*, picks*\/);\n\n \/\/ Set up the reading parameters\n fiff_int_t from = raw.first_samp;\n fiff_int_t to = raw.last_samp;\n\n \/\/ To read the whole file at once set quantum = to - from + 1;\n fiff_int_t quantum = to - from + 1;\n\n \/\/ Read and write the data\n bool first_buffer = true;\n\n fiff_int_t first, last;\n MatrixXd data;\n MatrixXd times;\n\n \/\/ initialize filter settings\n QString filter_name = \"example_cosine\";\n FilterData::FilterType type = FilterData::BPF;\n double sFreq = raw.info.sfreq; \/\/ get Sample freq from Data\n double centerfreq = 10\/(sFreq\/2.0); \/\/ normed nyquist freq.\n double bandwidth = 10\/(sFreq\/2.0);\n double parkswidth = 1\/(sFreq\/2.0);\n\n RtFilter rtFilter; \/\/ filter object\n MatrixXd dataFiltered; \/\/ filter output\n\n \/\/ channel selection - in this case use every channel\n \/\/ size = number of channels; value = index channel number\n QVector channelList(raw.info.nchan);\n for (int i = 0; i < raw.info.nchan; i++){\n channelList[i] = i;\n }\n\n for(first = from; first < to; first+=quantum) {\n last = first+quantum-1;\n if (last > to) {\n last = to;\n }\n\n if(!raw.read_raw_segment(data,times,first,last\/*,picks*\/)) {\n printf(\"error during read_raw_segment\\n\");\n return -1;\n }\n\n \/\/Filtering\n printf(\"Filtering...\");\n dataFiltered = rtFilter.filterData(data,type,centerfreq,bandwidth,parkswidth,sFreq,channelList);\n printf(\"[done]\\n\");\n\n \/\/Writing\n printf(\"Writing...\");\n if(first_buffer) {\n if(first > 0) {\n outfid->write_int(FIFF_FIRST_SAMPLE, &first);\n }\n first_buffer = false;\n }\n\n outfid->write_raw_buffer(dataFiltered,cals);\n printf(\"[done]\\n\");\n }\n\n outfid->finish_writing_raw();\n\n printf(\"Finished\\n\");\n\n return 0;\n}\n<|endoftext|>"} {"text":"#ifndef STAN_MATH_REV_FUN_SQUARED_DISTANCE_HPP\n#define STAN_MATH_REV_FUN_SQUARED_DISTANCE_HPP\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace stan {\nnamespace math {\n\n\/**\n * Returns the squared distance.\n *\/\ninline var squared_distance(const var& a, const var& b) {\n check_finite(\"squared_distance\", \"a\", a);\n check_finite(\"squared_distance\", \"b\", b);\n return make_callback_vari(std::pow(a.val() - b.val(), 2),\n [a, b](const auto& vi) mutable {\n const double diff = 2.0 * (a.val() - b.val());\n a.adj() += vi.adj_ * diff;\n b.adj() -= vi.adj_ * diff;\n });\n}\n\n\/**\n * Returns the squared distance.\n *\/\ninline var squared_distance(const var& a, double b) {\n check_finite(\"squared_distance\", \"a\", a);\n check_finite(\"squared_distance\", \"b\", b);\n return make_callback_vari(std::pow(a.val() - b, 2),\n [a, b](const auto& vi) mutable {\n a.adj() += vi.adj_ * 2.0 * (a.val() - b);\n });\n}\n\n\/**\n * Returns the squared distance.\n *\/\ninline var squared_distance(double a, const var& b) {\n return squared_distance(b, a);\n}\n\nnamespace internal {\n\nclass squared_distance_vv_vari : public vari {\n protected:\n vari** v1_;\n vari** v2_;\n size_t length_;\n\n public:\n template <\n typename EigVecVar1, typename EigVecVar2,\n require_all_eigen_vector_vt* = nullptr>\n squared_distance_vv_vari(const EigVecVar1& v1, const EigVecVar2& v2)\n : vari((as_column_vector_or_scalar(v1).val()\n - as_column_vector_or_scalar(v2).val())\n .squaredNorm()),\n length_(v1.size()) {\n v1_ = reinterpret_cast(\n ChainableStack::instance_->memalloc_.alloc(length_ * sizeof(vari*)));\n v2_ = reinterpret_cast(\n ChainableStack::instance_->memalloc_.alloc(length_ * sizeof(vari*)));\n Eigen::Map(v1_, length_) = v1.vi();\n Eigen::Map(v2_, length_) = v2.vi();\n }\n\n virtual void chain() {\n Eigen::Map v1_map(v1_, length_);\n Eigen::Map v2_map(v2_, length_);\n vector_d di = 2 * adj_ * (v1_map.val() - v2_map.val());\n v1_map.adj() += di;\n v2_map.adj() -= di;\n }\n};\n\nclass squared_distance_vd_vari : public vari {\n protected:\n vari** v1_;\n double* v2_;\n size_t length_;\n\n public:\n template * = nullptr,\n require_eigen_vector_vt* = nullptr>\n squared_distance_vd_vari(const EigVecVar& v1, const EigVecArith& v2)\n : vari((as_column_vector_or_scalar(v1).val()\n - as_column_vector_or_scalar(v2))\n .squaredNorm()),\n length_(v1.size()) {\n v1_ = reinterpret_cast(\n ChainableStack::instance_->memalloc_.alloc(length_ * sizeof(vari*)));\n v2_ = reinterpret_cast(\n ChainableStack::instance_->memalloc_.alloc(length_ * sizeof(double)));\n Eigen::Map(v1_, length_) = v1.vi();\n Eigen::Map(v2_, length_) = v2;\n }\n\n virtual void chain() {\n Eigen::Map v1_map(v1_, length_);\n v1_map.adj()\n += 2 * adj_ * (v1_map.val() - Eigen::Map(v2_, length_));\n }\n};\n} \/\/ namespace internal\n\ntemplate <\n typename EigVecVar1, typename EigVecVar2,\n require_all_eigen_vector_vt* = nullptr>\ninline var squared_distance(const EigVecVar1& v1, const EigVecVar2& v2) {\n check_matching_sizes(\"squared_distance\", \"v1\", v1, \"v2\", v2);\n return {new internal::squared_distance_vv_vari(to_ref(v1), to_ref(v2))};\n}\n\ntemplate * = nullptr,\n require_eigen_vector_vt* = nullptr>\ninline var squared_distance(const EigVecVar& v1, const EigVecArith& v2) {\n check_matching_sizes(\"squared_distance\", \"v1\", v1, \"v2\", v2);\n return {new internal::squared_distance_vd_vari(to_ref(v1), to_ref(v2))};\n}\n\ntemplate * = nullptr,\n require_eigen_vector_vt* = nullptr>\ninline var squared_distance(const EigVecArith& v1, const EigVecVar& v2) {\n check_matching_sizes(\"squared_distance\", \"v1\", v1, \"v2\", v2);\n return {new internal::squared_distance_vd_vari(to_ref(v2), to_ref(v1))};\n}\n\n\/**\n * Compute the squared distance between the elements in\n * two inputs.\n *\n * This overload handles arguments where one of T1 or T2 are\n * `var_value` where `T` is an Eigen type. The other type can\n * also be a `var_value` or it can be a matrix type that inherits\n * from EigenBase\n *\n * @tparam T1 type of first argument\n * @tparam T2 type of second argument\n * @param A first argument\n * @param B second argument\n * @return sum of squared difference of A and B\n *\/\ntemplate * = nullptr,\n require_any_var_vector_t* = nullptr>\ninline var squared_distance(const T1& A, const T2& B) {\n check_matching_sizes(\"squared_distance\", \"A\", A.val(), \"B\", B.val());\n if (unlikely(A.size() == 0)) {\n return var(0.0);\n } else if (!is_constant::value && !is_constant::value) {\n arena_t> arena_A = A;\n arena_t> arena_B = B;\n arena_t res_diff(arena_A.size());\n double res_val = 0.0;\n for (size_t i = 0; i < arena_A.size(); ++i) {\n const double diff = arena_A.val().coeff(i) - arena_B.val().coeff(i);\n res_diff.coeffRef(i) = diff;\n res_val += diff * diff;\n }\n return var(make_callback_vari(\n res_val, [arena_A, arena_B, res_diff](const auto& res) mutable {\n const double res_adj = 2.0 * res.adj_;\n for (size_t i = 0; i < arena_A.size(); ++i) {\n const double diff = res_adj * res_diff.coeff(i);\n arena_A.adj().coeffRef(i) += diff;\n arena_B.adj().coeffRef(i) -= diff;\n }\n }));\n } else if (!is_constant::value) {\n arena_t> arena_A = A;\n arena_t> arena_B = value_of(B);\n arena_t res_diff(arena_A.size());\n double res_val = 0.0;\n for (size_t i = 0; i < arena_A.size(); ++i) {\n const double diff = arena_A.val().coeff(i) - arena_B.coeff(i);\n res_diff.coeffRef(i) = diff;\n res_val += diff * diff;\n }\n return var(make_callback_vari(\n res_val, [arena_A, arena_B, res_diff](const auto& res) mutable {\n arena_A.adj() += 2.0 * res.adj_ * res_diff;\n }));\n } else {\n arena_t> arena_A = value_of(A);\n arena_t> arena_B = B;\n arena_t res_diff(arena_A.size());\n double res_val = 0.0;\n for (size_t i = 0; i < arena_A.size(); ++i) {\n const double diff = arena_A.coeff(i) - arena_B.val().coeff(i);\n res_diff.coeffRef(i) = diff;\n res_val += diff * diff;\n }\n return var(make_callback_vari(\n res_val, [arena_A, arena_B, res_diff](const auto& res) mutable {\n arena_B.adj() -= 2.0 * res.adj_ * res_diff;\n }));\n }\n}\n\n} \/\/ namespace math\n} \/\/ namespace stan\n#endif\nUpdate includes (Issue #2101)#ifndef STAN_MATH_REV_FUN_SQUARED_DISTANCE_HPP\n#define STAN_MATH_REV_FUN_SQUARED_DISTANCE_HPP\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace stan {\nnamespace math {\n\n\/**\n * Returns the squared distance.\n *\/\ninline var squared_distance(const var& a, const var& b) {\n check_finite(\"squared_distance\", \"a\", a);\n check_finite(\"squared_distance\", \"b\", b);\n return make_callback_vari(std::pow(a.val() - b.val(), 2),\n [a, b](const auto& vi) mutable {\n const double diff = 2.0 * (a.val() - b.val());\n a.adj() += vi.adj_ * diff;\n b.adj() -= vi.adj_ * diff;\n });\n}\n\n\/**\n * Returns the squared distance.\n *\/\ninline var squared_distance(const var& a, double b) {\n check_finite(\"squared_distance\", \"a\", a);\n check_finite(\"squared_distance\", \"b\", b);\n return make_callback_vari(std::pow(a.val() - b, 2),\n [a, b](const auto& vi) mutable {\n a.adj() += vi.adj_ * 2.0 * (a.val() - b);\n });\n}\n\n\/**\n * Returns the squared distance.\n *\/\ninline var squared_distance(double a, const var& b) {\n return squared_distance(b, a);\n}\n\nnamespace internal {\n\nclass squared_distance_vv_vari : public vari {\n protected:\n vari** v1_;\n vari** v2_;\n size_t length_;\n\n public:\n template <\n typename EigVecVar1, typename EigVecVar2,\n require_all_eigen_vector_vt* = nullptr>\n squared_distance_vv_vari(const EigVecVar1& v1, const EigVecVar2& v2)\n : vari((as_column_vector_or_scalar(v1).val()\n - as_column_vector_or_scalar(v2).val())\n .squaredNorm()),\n length_(v1.size()) {\n v1_ = reinterpret_cast(\n ChainableStack::instance_->memalloc_.alloc(length_ * sizeof(vari*)));\n v2_ = reinterpret_cast(\n ChainableStack::instance_->memalloc_.alloc(length_ * sizeof(vari*)));\n Eigen::Map(v1_, length_) = v1.vi();\n Eigen::Map(v2_, length_) = v2.vi();\n }\n\n virtual void chain() {\n Eigen::Map v1_map(v1_, length_);\n Eigen::Map v2_map(v2_, length_);\n vector_d di = 2 * adj_ * (v1_map.val() - v2_map.val());\n v1_map.adj() += di;\n v2_map.adj() -= di;\n }\n};\n\nclass squared_distance_vd_vari : public vari {\n protected:\n vari** v1_;\n double* v2_;\n size_t length_;\n\n public:\n template * = nullptr,\n require_eigen_vector_vt* = nullptr>\n squared_distance_vd_vari(const EigVecVar& v1, const EigVecArith& v2)\n : vari((as_column_vector_or_scalar(v1).val()\n - as_column_vector_or_scalar(v2))\n .squaredNorm()),\n length_(v1.size()) {\n v1_ = reinterpret_cast(\n ChainableStack::instance_->memalloc_.alloc(length_ * sizeof(vari*)));\n v2_ = reinterpret_cast(\n ChainableStack::instance_->memalloc_.alloc(length_ * sizeof(double)));\n Eigen::Map(v1_, length_) = v1.vi();\n Eigen::Map(v2_, length_) = v2;\n }\n\n virtual void chain() {\n Eigen::Map v1_map(v1_, length_);\n v1_map.adj()\n += 2 * adj_ * (v1_map.val() - Eigen::Map(v2_, length_));\n }\n};\n} \/\/ namespace internal\n\ntemplate <\n typename EigVecVar1, typename EigVecVar2,\n require_all_eigen_vector_vt* = nullptr>\ninline var squared_distance(const EigVecVar1& v1, const EigVecVar2& v2) {\n check_matching_sizes(\"squared_distance\", \"v1\", v1, \"v2\", v2);\n return {new internal::squared_distance_vv_vari(to_ref(v1), to_ref(v2))};\n}\n\ntemplate * = nullptr,\n require_eigen_vector_vt* = nullptr>\ninline var squared_distance(const EigVecVar& v1, const EigVecArith& v2) {\n check_matching_sizes(\"squared_distance\", \"v1\", v1, \"v2\", v2);\n return {new internal::squared_distance_vd_vari(to_ref(v1), to_ref(v2))};\n}\n\ntemplate * = nullptr,\n require_eigen_vector_vt* = nullptr>\ninline var squared_distance(const EigVecArith& v1, const EigVecVar& v2) {\n check_matching_sizes(\"squared_distance\", \"v1\", v1, \"v2\", v2);\n return {new internal::squared_distance_vd_vari(to_ref(v2), to_ref(v1))};\n}\n\n\/**\n * Compute the squared distance between the elements in\n * two inputs.\n *\n * This overload handles arguments where one of T1 or T2 are\n * `var_value` where `T` is an Eigen type. The other type can\n * also be a `var_value` or it can be a matrix type that inherits\n * from EigenBase\n *\n * @tparam T1 type of first argument\n * @tparam T2 type of second argument\n * @param A first argument\n * @param B second argument\n * @return sum of squared difference of A and B\n *\/\ntemplate * = nullptr,\n require_any_var_vector_t* = nullptr>\ninline var squared_distance(const T1& A, const T2& B) {\n check_matching_sizes(\"squared_distance\", \"A\", A.val(), \"B\", B.val());\n if (unlikely(A.size() == 0)) {\n return var(0.0);\n } else if (!is_constant::value && !is_constant::value) {\n arena_t> arena_A = A;\n arena_t> arena_B = B;\n arena_t res_diff(arena_A.size());\n double res_val = 0.0;\n for (size_t i = 0; i < arena_A.size(); ++i) {\n const double diff = arena_A.val().coeff(i) - arena_B.val().coeff(i);\n res_diff.coeffRef(i) = diff;\n res_val += diff * diff;\n }\n return var(make_callback_vari(\n res_val, [arena_A, arena_B, res_diff](const auto& res) mutable {\n const double res_adj = 2.0 * res.adj();\n for (size_t i = 0; i < arena_A.size(); ++i) {\n const double diff = res_adj * res_diff.coeff(i);\n arena_A.adj().coeffRef(i) += diff;\n arena_B.adj().coeffRef(i) -= diff;\n }\n }));\n } else if (!is_constant::value) {\n arena_t> arena_A = A;\n arena_t> arena_B = value_of(B);\n arena_t res_diff(arena_A.size());\n double res_val = 0.0;\n for (size_t i = 0; i < arena_A.size(); ++i) {\n const double diff = arena_A.val().coeff(i) - arena_B.coeff(i);\n res_diff.coeffRef(i) = diff;\n res_val += diff * diff;\n }\n return var(make_callback_vari(\n res_val, [arena_A, arena_B, res_diff](const auto& res) mutable {\n arena_A.adj() += 2.0 * res.adj() * res_diff;\n }));\n } else {\n arena_t> arena_A = value_of(A);\n arena_t> arena_B = B;\n arena_t res_diff(arena_A.size());\n double res_val = 0.0;\n for (size_t i = 0; i < arena_A.size(); ++i) {\n const double diff = arena_A.coeff(i) - arena_B.val().coeff(i);\n res_diff.coeffRef(i) = diff;\n res_val += diff * diff;\n }\n return var(make_callback_vari(\n res_val, [arena_A, arena_B, res_diff](const auto& res) mutable {\n arena_B.adj() -= 2.0 * res.adj() * res_diff;\n }));\n }\n}\n\n} \/\/ namespace math\n} \/\/ namespace stan\n#endif\n<|endoftext|>"} {"text":"\/* dhcpclient.hpp - dhcp client request handling\n *\n * (c) 2011-2014 Nicholas J. Kain \n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#ifndef NK_DHCPCLIENT_H\n#define NK_DHCPCLIENT_H\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \"dhcp.h\"\n\n\/\/ There are two hashtables, a 'new' and a 'marked for death' table. If these\n\/\/ tables are not empty, a timer with period t will wake up and delete all\n\/\/ entries on the 'm4d' table and move the 'new' table to replace the 'm4d'\n\/\/ table. If an entry on the 'm4d' table is accessed, it will be moved to the\n\/\/ 'new' table. New entries will be added to the 'new' table. If both tables\n\/\/ are emptied, the timer can stop until a new entry is added. We optimize\n\/\/ the scheme by not actually performing moves: instead, we store an index\n\/\/ to the 'new' table, and the 'marked for death' table is the unindexed table.\n\/\/\n\/\/ This scheme requires no timestamping and will bound the lifetime of any\n\/\/ object to be p < lifetime < 2p. A further refinement would be to scale\n\/\/ p to be inversely proportional to the number of entries on the 'new'\n\/\/ and 'm4d' tables. This change would cause the deletion rate to increase\n\/\/ smoothly under heavy load, providing resistance to OOM DoS at the cost of\n\/\/ making it so that clients will need to complete their transactions quickly.\nclass ClientStates {\npublic:\n ClientStates(boost::asio::io_service &io_service)\n : swapTimer_(io_service)\n {\n currentMap_ = 0;\n swapInterval_ = 60; \/\/ 1m\n }\n ~ClientStates() {}\n bool stateExists(uint32_t xid, const std::string &chaddr) const {\n std::string key(generateKey(xid, chaddr));\n return (map_[0].find(key) != map_[0].end()) ||\n (map_[1].find(key) != map_[1].end());\n }\n void stateAdd(uint32_t xid, const std::string &chaddr, uint8_t state)\n {\n std::string key(generateKey(xid, chaddr));\n if (!state)\n return;\n stateKill(xid, chaddr);\n map_[currentMap_][key] = state;\n if (swapTimer_.expires_from_now() <=\n boost::posix_time::time_duration(0,0,0,0))\n setTimer();\n }\n uint8_t stateGet(uint32_t xid, const std::string &chaddr) {\n std::string key(generateKey(xid, chaddr));\n auto r = map_[currentMap_].find(key);\n if (r != map_[currentMap_].end())\n return r->second;\n r = map_[!currentMap_].find(key);\n if (r != map_[!currentMap_].end()) {\n map_[!currentMap_].erase(r);\n map_[currentMap_][key] = r->second;\n return r->second;\n }\n return DHCPNULL;\n }\n void stateKill(uint32_t xid, const std::string &chaddr) {\n std::string key(generateKey(xid, chaddr));\n auto elt = map_[currentMap_].find(key);\n if (elt != map_[currentMap_].end()) {\n map_[currentMap_].erase(elt);\n return;\n }\n elt = map_[!currentMap_].find(key);\n if (elt != map_[!currentMap_].end())\n map_[!currentMap_].erase(elt);\n }\nprivate:\n std::string generateKey(uint32_t xid, const std::string &chaddr) const {\n std::string r;\n union {\n uint8_t c[4];\n uint32_t n;\n } xia;\n xia.n = xid;\n r.push_back(xia.c[0]);\n r.push_back(xia.c[1]);\n r.push_back(xia.c[2]);\n r.push_back(xia.c[3]);\n r.append(chaddr);\n return r;\n }\n void doSwap(void) {\n int killMap = !currentMap_;\n map_[killMap].clear();\n currentMap_ = killMap;\n }\n void setTimer(void) {\n swapTimer_.expires_from_now(boost::posix_time::seconds(swapInterval_));\n swapTimer_.async_wait\n ([this](const boost::system::error_code& error)\n {\n doSwap();\n if (map_[0].size() || map_[1].size())\n setTimer();\n\n });\n }\n \/\/ Key is concatenation of xid|chaddr. Neither of these need to be stored\n \/\/ in explicit fields in the state structure.\n int currentMap_; \/\/ Either 0 or 1.\n int swapInterval_;\n boost::asio::deadline_timer swapTimer_;\n std::unordered_map map_[2];\n};\n\nvoid init_client_states_v4(boost::asio::io_service &io_service);\n\nclass ClientListener\n{\npublic:\n ClientListener(boost::asio::io_service &io_service,\n const boost::asio::ip::udp::endpoint &endpoint,\n const std::string &ifname);\nprivate:\n void start_receive();\n uint64_t getNowTs(void) const;\n void dhcpmsg_init(struct dhcpmsg *dm, char type,\n uint32_t xid, const std::string &chaddr) const;\n uint32_t local_ip() const;\n std::string ipStr(uint32_t ip) const;\n void send_reply(struct dhcpmsg *dm, bool broadcast);\n void reply_discover(const std::string &chaddr);\n void reply_request(const std::string &chaddr, bool is_direct);\n void reply_inform(const std::string &chaddr);\n void do_release(const std::string &chaddr);\n std::string getChaddr(const struct dhcpmsg &dm) const;\n bool validate_dhcp(void) const;\n void handle_receive(const boost::system::error_code &error,\n std::size_t bytes_xferred);\n\n boost::asio::ip::udp::socket socket_;\n \/\/boost::asio::ip::udp::socket broadcast_socket_;\n boost::asio::ip::udp::endpoint remote_endpoint_;\n std::array recv_buffer_;\n struct dhcpmsg dhcpmsg_;\n boost::asio::ip::address local_ip_;\n};\n\n#endif \/* NK_DHCPCLIENT_H *\/\nRemove unused headers.\/* dhcpclient.hpp - dhcp client request handling\n *\n * (c) 2011-2014 Nicholas J. Kain \n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#ifndef NK_DHCPCLIENT_H\n#define NK_DHCPCLIENT_H\n\n#include \n#include \n#include \n#include \n\n#include \n\n#include \"dhcp.h\"\n\n\/\/ There are two hashtables, a 'new' and a 'marked for death' table. If these\n\/\/ tables are not empty, a timer with period t will wake up and delete all\n\/\/ entries on the 'm4d' table and move the 'new' table to replace the 'm4d'\n\/\/ table. If an entry on the 'm4d' table is accessed, it will be moved to the\n\/\/ 'new' table. New entries will be added to the 'new' table. If both tables\n\/\/ are emptied, the timer can stop until a new entry is added. We optimize\n\/\/ the scheme by not actually performing moves: instead, we store an index\n\/\/ to the 'new' table, and the 'marked for death' table is the unindexed table.\n\/\/\n\/\/ This scheme requires no timestamping and will bound the lifetime of any\n\/\/ object to be p < lifetime < 2p. A further refinement would be to scale\n\/\/ p to be inversely proportional to the number of entries on the 'new'\n\/\/ and 'm4d' tables. This change would cause the deletion rate to increase\n\/\/ smoothly under heavy load, providing resistance to OOM DoS at the cost of\n\/\/ making it so that clients will need to complete their transactions quickly.\nclass ClientStates {\npublic:\n ClientStates(boost::asio::io_service &io_service)\n : swapTimer_(io_service)\n {\n currentMap_ = 0;\n swapInterval_ = 60; \/\/ 1m\n }\n ~ClientStates() {}\n bool stateExists(uint32_t xid, const std::string &chaddr) const {\n std::string key(generateKey(xid, chaddr));\n return (map_[0].find(key) != map_[0].end()) ||\n (map_[1].find(key) != map_[1].end());\n }\n void stateAdd(uint32_t xid, const std::string &chaddr, uint8_t state)\n {\n std::string key(generateKey(xid, chaddr));\n if (!state)\n return;\n stateKill(xid, chaddr);\n map_[currentMap_][key] = state;\n if (swapTimer_.expires_from_now() <=\n boost::posix_time::time_duration(0,0,0,0))\n setTimer();\n }\n uint8_t stateGet(uint32_t xid, const std::string &chaddr) {\n std::string key(generateKey(xid, chaddr));\n auto r = map_[currentMap_].find(key);\n if (r != map_[currentMap_].end())\n return r->second;\n r = map_[!currentMap_].find(key);\n if (r != map_[!currentMap_].end()) {\n map_[!currentMap_].erase(r);\n map_[currentMap_][key] = r->second;\n return r->second;\n }\n return DHCPNULL;\n }\n void stateKill(uint32_t xid, const std::string &chaddr) {\n std::string key(generateKey(xid, chaddr));\n auto elt = map_[currentMap_].find(key);\n if (elt != map_[currentMap_].end()) {\n map_[currentMap_].erase(elt);\n return;\n }\n elt = map_[!currentMap_].find(key);\n if (elt != map_[!currentMap_].end())\n map_[!currentMap_].erase(elt);\n }\nprivate:\n std::string generateKey(uint32_t xid, const std::string &chaddr) const {\n std::string r;\n union {\n uint8_t c[4];\n uint32_t n;\n } xia;\n xia.n = xid;\n r.push_back(xia.c[0]);\n r.push_back(xia.c[1]);\n r.push_back(xia.c[2]);\n r.push_back(xia.c[3]);\n r.append(chaddr);\n return r;\n }\n void doSwap(void) {\n int killMap = !currentMap_;\n map_[killMap].clear();\n currentMap_ = killMap;\n }\n void setTimer(void) {\n swapTimer_.expires_from_now(boost::posix_time::seconds(swapInterval_));\n swapTimer_.async_wait\n ([this](const boost::system::error_code& error)\n {\n doSwap();\n if (map_[0].size() || map_[1].size())\n setTimer();\n\n });\n }\n \/\/ Key is concatenation of xid|chaddr. Neither of these need to be stored\n \/\/ in explicit fields in the state structure.\n int currentMap_; \/\/ Either 0 or 1.\n int swapInterval_;\n boost::asio::deadline_timer swapTimer_;\n std::unordered_map map_[2];\n};\n\nvoid init_client_states_v4(boost::asio::io_service &io_service);\n\nclass ClientListener\n{\npublic:\n ClientListener(boost::asio::io_service &io_service,\n const boost::asio::ip::udp::endpoint &endpoint,\n const std::string &ifname);\nprivate:\n void start_receive();\n uint64_t getNowTs(void) const;\n void dhcpmsg_init(struct dhcpmsg *dm, char type,\n uint32_t xid, const std::string &chaddr) const;\n uint32_t local_ip() const;\n std::string ipStr(uint32_t ip) const;\n void send_reply(struct dhcpmsg *dm, bool broadcast);\n void reply_discover(const std::string &chaddr);\n void reply_request(const std::string &chaddr, bool is_direct);\n void reply_inform(const std::string &chaddr);\n void do_release(const std::string &chaddr);\n std::string getChaddr(const struct dhcpmsg &dm) const;\n bool validate_dhcp(void) const;\n void handle_receive(const boost::system::error_code &error,\n std::size_t bytes_xferred);\n\n boost::asio::ip::udp::socket socket_;\n \/\/boost::asio::ip::udp::socket broadcast_socket_;\n boost::asio::ip::udp::endpoint remote_endpoint_;\n std::array recv_buffer_;\n struct dhcpmsg dhcpmsg_;\n boost::asio::ip::address local_ip_;\n};\n\n#endif \/* NK_DHCPCLIENT_H *\/\n<|endoftext|>"} {"text":"#include \n\n#include \"vtrc-server\/vtrc-application.h\"\n#include \"vtrc-server\/vtrc-listener-tcp.h\"\n\n#include \"vtrc-common\/vtrc-connection-iface.h\"\n#include \"vtrc-common\/vtrc-closure-holder.h\"\n#include \"vtrc-common\/vtrc-thread-pool.h\"\n\n#include \"protocol\/hello.pb.h\" \/\/\/ hello protocol\n#include \"google\/protobuf\/descriptor.h\" \/\/\/ for descriptor( )->full_name( )\n#include \"boost\/lexical_cast.hpp\"\n\n\nusing namespace vtrc;\n\nnamespace {\n\nclass hello_service_impl: public howto::hello_service {\n\n common::connection_iface *cl_;\n\n void send_hello(::google::protobuf::RpcController* \/*controller*\/,\n const ::howto::request_message* request,\n ::howto::response_message* response,\n ::google::protobuf::Closure* done) \/*override*\/\n {\n common::closure_holder ch( done ); \/\/\/ instead of done->Run( );\n std::ostringstream oss;\n\n oss << \"Hello \" << request->name( )\n << \" from hello_service_impl::send_hello!\\n\"\n << \"Your transport name is '\"\n << cl_->name( ) << \"'.\\nHave a nice day.\";\n\n response->set_hello( oss.str( ) );\n \/\/\/ done->Run( ); \/\/\/ ch will call it\n }\n\npublic:\n\n hello_service_impl( common::connection_iface *cl )\n :cl_(cl)\n { }\n\n static std::string const &service_name( )\n {\n return howto::hello_service::descriptor( )->full_name( );\n }\n\n};\n\nclass hello_application: public server::application {\n\n typedef common::rpc_service_wrapper wrapper_type;\n typedef vtrc::shared_ptr wrapper_sptr;\n\npublic:\n\n hello_application( common::thread_pool &tp )\n :server::application(tp.get_io_service( ))\n { }\n\n wrapper_sptr get_service_by_name( common::connection_iface* connection,\n const std::string &service_name )\n {\n if( service_name == hello_service_impl::service_name( ) ) {\n\n hello_service_impl *new_impl = new hello_service_impl(connection);\n\n return vtrc::make_shared( new_impl );\n\n }\n return wrapper_sptr( );\n }\n\n};\n\n} \/\/ namespace\n\nint main( int argc, const char **argv )\n{\n\n const char *address = \"127.0.0.1\";\n unsigned short port = 56560;\n\n if( argc > 2 ) {\n address = argv[1];\n port = boost::lexical_cast( argv[2] );\n } else if( argc > 1 ) {\n port = boost::lexical_cast( argv[1] );\n }\n\n common::thread_pool tp;\n hello_application app( tp );\n\n try {\n\n vtrc::shared_ptr\n tcp( server::listeners::tcp::create( app, address, port ) );\n\n tcp->start( );\n\n tp.attach( );\n\n } catch( const std::exception &ex ) {\n std::cerr << \"Hello, world failed: \" << ex.what( ) << \"\\n\";\n }\n\n tp.join_all( );\n\n \/\/\/ make valgrind happy.\n google::protobuf::ShutdownProtobufLibrary( );\n\n return 0;\n}\n\nhowto#include \n\n#include \"vtrc-server\/vtrc-application.h\"\n#include \"vtrc-server\/vtrc-listener-tcp.h\"\n\n#include \"vtrc-common\/vtrc-connection-iface.h\"\n#include \"vtrc-common\/vtrc-closure-holder.h\"\n#include \"vtrc-common\/vtrc-thread-pool.h\"\n\n#include \"protocol\/hello.pb.h\" \/\/\/ hello protocol\n#include \"google\/protobuf\/descriptor.h\" \/\/\/ for descriptor( )->full_name( )\n#include \"boost\/lexical_cast.hpp\"\n\nusing namespace vtrc;\n\nnamespace {\n\nclass hello_service_impl: public howto::hello_service {\n\n common::connection_iface *cl_;\n\n void send_hello(::google::protobuf::RpcController* \/*controller*\/,\n const ::howto::request_message* request,\n ::howto::response_message* response,\n ::google::protobuf::Closure* done) \/*override*\/\n {\n common::closure_holder ch( done ); \/\/\/ instead of done->Run( );\n std::ostringstream oss;\n\n oss << \"Hello \" << request->name( )\n << \" from hello_service_impl::send_hello!\\n\"\n << \"Your transport name is '\"\n << cl_->name( ) << \"'.\\nHave a nice day.\";\n\n response->set_hello( oss.str( ) );\n \/\/\/ done->Run( ); \/\/\/ ch will call it\n }\n\npublic:\n\n hello_service_impl( common::connection_iface *cl )\n :cl_(cl)\n { }\n\n static std::string const &service_name( )\n {\n return howto::hello_service::descriptor( )->full_name( );\n }\n\n};\n\nclass hello_application: public server::application {\n\n typedef common::rpc_service_wrapper wrapper_type;\n typedef vtrc::shared_ptr wrapper_sptr;\n\npublic:\n\n hello_application( common::thread_pool &tp )\n :server::application(tp.get_io_service( ))\n { }\n\n wrapper_sptr get_service_by_name( common::connection_iface* connection,\n const std::string &service_name )\n {\n if( service_name == hello_service_impl::service_name( ) ) {\n\n hello_service_impl *new_impl = new hello_service_impl(connection);\n\n return vtrc::make_shared( new_impl );\n\n }\n return wrapper_sptr( );\n }\n\n};\n\n} \/\/ namespace\n\nint main( int argc, const char **argv )\n{\n\n const char *address = \"127.0.0.1\";\n unsigned short port = 56560;\n\n if( argc > 2 ) {\n address = argv[1];\n port = boost::lexical_cast( argv[2] );\n } else if( argc > 1 ) {\n port = boost::lexical_cast( argv[1] );\n }\n\n common::thread_pool tp;\n hello_application app( tp );\n\n try {\n\n vtrc::shared_ptr\n tcp( server::listeners::tcp::create( app, address, port ) );\n\n tcp->start( );\n\n tp.attach( );\n\n } catch( const std::exception &ex ) {\n std::cerr << \"Hello, world failed: \" << ex.what( ) << \"\\n\";\n }\n\n tp.join_all( );\n\n \/\/\/ make valgrind happy.\n google::protobuf::ShutdownProtobufLibrary( );\n\n return 0;\n}\n\n<|endoftext|>"} {"text":"\/*!\n \\copyright (c) RDO-Team, 2011\n \\file calc_relevant.inl\n \\authors Барс Александр\n \\authors Урусов Андрей (rdo@rk9.bmstu.ru)\n \\date 16.04.2011\n \\brief RDOCalc для подбора релевантных ресурсов\n \\indent 4T\n*\/\n\n\/\/ ----------------------------------------------------------------------- INCLUDES\n\/\/ ----------------------------------------------------------------------- SYNOPSIS\n#include \"simulator\/runtime\/rdo_runtime.h\"\n#include \"simulator\/runtime\/rdo_activity.h\"\n\/\/ --------------------------------------------------------------------------------\n\nOPEN_RDO_RUNTIME_NAMESPACE\n\n\/\/ --------------------------------------------------------------------------------\n\/\/ -------------------- RDOSetRelResParamCalc\n\/\/ --------------------------------------------------------------------------------\ntemplate \ninline RDOSetRelResParamCalc::RDOSetRelResParamCalc(ruint relResID, ruint paramID, CREF(LPRDOCalc) pCalc)\n\t: m_relResID(relResID)\n\t, m_paramID (paramID )\n\t, m_pCalc (pCalc )\n{\n\tif (m_pCalc)\n\t{\n\t\tsetSrcInfo(m_pCalc->srcInfo());\n\t}\n}\n\ntemplate \ninline RDOSetRelResParamCalc::~RDOSetRelResParamCalc()\n{}\n\ntemplate <>\ninline RDOValue RDOSetRelResParamCalc::doCalc(CREF(LPRDORuntime) pRuntime)\n{\n\tRDOValue value = m_pCalc->calcValue(pRuntime);\n\truint resID = pRuntime->getCurrentActivity()->getResByRelRes(m_relResID);\n\tpRuntime->setResParamVal(resID, m_paramID, value);\n\treturn value;\n}\n\ntemplate <>\ninline RDOValue RDOSetRelResParamCalc::doCalc(CREF(LPRDORuntime) pRuntime)\n{\n\truint resID = pRuntime->getCurrentActivity()->getResByRelRes(m_relResID);\n\treturn pRuntime->getResParamValRaw(resID, m_paramID) += m_pCalc->calcValue(pRuntime);\n}\n\ntemplate <>\ninline RDOValue RDOSetRelResParamCalc::doCalc(CREF(LPRDORuntime) pRuntime)\n{\n\truint resID = pRuntime->getCurrentActivity()->getResByRelRes(m_relResID);\n\treturn pRuntime->getResParamValRaw(resID, m_paramID) -= m_pCalc->calcValue(pRuntime);\n}\n\ntemplate <>\ninline RDOValue RDOSetRelResParamCalc::doCalc(CREF(LPRDORuntime) pRuntime)\n{\n\truint resID = pRuntime->getCurrentActivity()->getResByRelRes(m_relResID);\n\treturn pRuntime->getResParamValRaw(resID, m_paramID) *= m_pCalc->calcValue(pRuntime);\n}\n\ntemplate <>\ninline RDOValue RDOSetRelResParamCalc::doCalc(CREF(LPRDORuntime) pRuntime)\n{\n\truint resID = pRuntime->getCurrentActivity()->getResByRelRes(m_relResID);\n\treturn pRuntime->getResParamValRaw(resID, m_paramID) \/= m_pCalc->calcValue(pRuntime);\n}\n\ntemplate <>\ninline RDOValue RDOSetRelResParamCalc::doCalc(CREF(LPRDORuntime) pRuntime)\n{\n\truint resID = pRuntime->getCurrentActivity()->getResByRelRes(m_relResID);\n\treturn pRuntime->getResParamValRaw(resID, m_paramID) += RDOValue(1);\n}\n\ntemplate <>\ninline RDOValue RDOSetRelResParamCalc::doCalc(CREF(LPRDORuntime) pRuntime)\n{\n\truint resID = pRuntime->getCurrentActivity()->getResByRelRes(m_relResID);\n\treturn pRuntime->getResParamValRaw(resID, m_paramID) -= RDOValue(1);\n}\n\nCLOSE_RDO_RUNTIME_NAMESPACE\n - добавлен NOCHANGE\/*!\n \\copyright (c) RDO-Team, 2011\n \\file calc_relevant.inl\n \\authors Барс Александр\n \\authors Урусов Андрей (rdo@rk9.bmstu.ru)\n \\date 16.04.2011\n \\brief RDOCalc для подбора релевантных ресурсов\n \\indent 4T\n*\/\n\n\/\/ ----------------------------------------------------------------------- INCLUDES\n\/\/ ----------------------------------------------------------------------- SYNOPSIS\n#include \"simulator\/runtime\/rdo_runtime.h\"\n#include \"simulator\/runtime\/rdo_activity.h\"\n\/\/ --------------------------------------------------------------------------------\n\nOPEN_RDO_RUNTIME_NAMESPACE\n\n\/\/ --------------------------------------------------------------------------------\n\/\/ -------------------- RDOSetRelResParamCalc\n\/\/ --------------------------------------------------------------------------------\ntemplate \ninline RDOSetRelResParamCalc::RDOSetRelResParamCalc(ruint relResID, ruint paramID, CREF(LPRDOCalc) pCalc)\n\t: m_relResID(relResID)\n\t, m_paramID (paramID )\n\t, m_pCalc (pCalc )\n{\n\tif (m_pCalc)\n\t{\n\t\tsetSrcInfo(m_pCalc->srcInfo());\n\t}\n}\n\ntemplate \ninline RDOSetRelResParamCalc::~RDOSetRelResParamCalc()\n{}\n\ntemplate <>\ninline RDOValue RDOSetRelResParamCalc::doCalc(CREF(LPRDORuntime) pRuntime)\n{\n\tUNUSED(pRuntime);\n\tRDOValue value(true);\n\treturn value;\n}\n\ntemplate <>\ninline RDOValue RDOSetRelResParamCalc::doCalc(CREF(LPRDORuntime) pRuntime)\n{\n\tRDOValue value = m_pCalc->calcValue(pRuntime);\n\truint resID = pRuntime->getCurrentActivity()->getResByRelRes(m_relResID);\n\tpRuntime->setResParamVal(resID, m_paramID, value);\n\treturn value;\n}\n\ntemplate <>\ninline RDOValue RDOSetRelResParamCalc::doCalc(CREF(LPRDORuntime) pRuntime)\n{\n\truint resID = pRuntime->getCurrentActivity()->getResByRelRes(m_relResID);\n\treturn pRuntime->getResParamValRaw(resID, m_paramID) += m_pCalc->calcValue(pRuntime);\n}\n\ntemplate <>\ninline RDOValue RDOSetRelResParamCalc::doCalc(CREF(LPRDORuntime) pRuntime)\n{\n\truint resID = pRuntime->getCurrentActivity()->getResByRelRes(m_relResID);\n\treturn pRuntime->getResParamValRaw(resID, m_paramID) -= m_pCalc->calcValue(pRuntime);\n}\n\ntemplate <>\ninline RDOValue RDOSetRelResParamCalc::doCalc(CREF(LPRDORuntime) pRuntime)\n{\n\truint resID = pRuntime->getCurrentActivity()->getResByRelRes(m_relResID);\n\treturn pRuntime->getResParamValRaw(resID, m_paramID) *= m_pCalc->calcValue(pRuntime);\n}\n\ntemplate <>\ninline RDOValue RDOSetRelResParamCalc::doCalc(CREF(LPRDORuntime) pRuntime)\n{\n\truint resID = pRuntime->getCurrentActivity()->getResByRelRes(m_relResID);\n\treturn pRuntime->getResParamValRaw(resID, m_paramID) \/= m_pCalc->calcValue(pRuntime);\n}\n\ntemplate <>\ninline RDOValue RDOSetRelResParamCalc::doCalc(CREF(LPRDORuntime) pRuntime)\n{\n\truint resID = pRuntime->getCurrentActivity()->getResByRelRes(m_relResID);\n\treturn pRuntime->getResParamValRaw(resID, m_paramID) += RDOValue(1);\n}\n\ntemplate <>\ninline RDOValue RDOSetRelResParamCalc::doCalc(CREF(LPRDORuntime) pRuntime)\n{\n\truint resID = pRuntime->getCurrentActivity()->getResByRelRes(m_relResID);\n\treturn pRuntime->getResParamValRaw(resID, m_paramID) -= RDOValue(1);\n}\n\nCLOSE_RDO_RUNTIME_NAMESPACE\n<|endoftext|>"} {"text":"AliAnalysisTaskCheckPerformanceCascadepp276 *AddTaskCheckPerformanceCascadepp276( Int_t minnTPCcls = 70,\n Float_t vtxlim = 10.,\n Float_t vtxlimmin = 0.,\n Bool_t fwithsdd = kFALSE,\n Bool_t kextrasel = kFALSE,\n Bool_t kacccut = kFALSE,\n Bool_t krelaunchvertexers = kFALSE,\n Bool_t ksddonselection = kFALSE,\n Float_t minptondaughtertracks = 0.0,\n Float_t etacutondaughtertracks = 0.8) {\n \n \/\/ Creates, configures and attaches to the train a cascades check task.\n \/\/ Get the pointer to the existing analysis manager via the static access method.\n \/\/==============================================================================\n AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();\n if (!mgr) {\n ::Error(\"AddTaskCheckPerformanceCascadepp276\", \"No analysis manager to connect to.\");\n return NULL;\n } \n\n \/\/ Check the analysis type using the event handlers connected to the analysis manager.\n \/\/==============================================================================\n if (!mgr->GetInputEventHandler()) {\n ::Error(\"AddTaskCheckPerformanceCascadepp276\", \"This task requires an input event handler\");\n return NULL;\n } \n TString type = mgr->GetInputEventHandler()->GetDataType(); \/\/ can be \"ESD\" or \"AOD\"\n\n \/\/ Create and configure the task\n \/\/==============================================================================\n TString tasknameperf = \"TaskCheckPerformanceCascadepp276\";\n tasknameperf += Form(\"_minnTPCcls%i_vtxlim%.1f-%.1f_minptdghtrk%.1f_etacutdghtrk%.1f\",minnTPCcls,vtxlim,vtxlimmin,minptondaughtertracks,etacutondaughtertracks);\n AliAnalysisTaskCheckPerformanceCascadepp276 *taskCheckPerfCascadepp276 = new AliAnalysisTaskCheckPerformanceCascadepp276(tasknameperf);\n taskCheckPerfCascadepp276->SetAnalysisType (type); \/\/ \"ESD\" or \"AOD\"\n taskCheckPerfCascadepp276->SetRelaunchV0CascVertexers (krelaunchvertexers); \/\/ choose if reconstruct the vertex of V0 in the cascades\n taskCheckPerfCascadepp276->SetSDDSelection (fwithsdd); \/\/ choose if apply SDD event selection\n taskCheckPerfCascadepp276->SetQualityCutZprimVtxPos (kTRUE); \/\/ choose if apply Z vtx PV position event selection\n taskCheckPerfCascadepp276->SetRejectEventPileUp (kFALSE); \/\/ choose if apply no Pileup event selection\n taskCheckPerfCascadepp276->SetQualityCutNoTPConlyPrimVtx (kTRUE); \/\/ choose if apply no TPC only event selection\n taskCheckPerfCascadepp276->SetQualityCutTPCrefit (kTRUE); \/\/ choose if apply TPC refit on daughter tracks\n taskCheckPerfCascadepp276->SetQualityCutnTPCcls (kTRUE); \/\/ choose if apply n TPC cluster selection on daughter tracks\n taskCheckPerfCascadepp276->SetWithSDDOn (ksddonselection); \/\/ which SDD selection do you want apply? [if kTRUE select SDDon events]\n taskCheckPerfCascadepp276->SetQualityCutMinnTPCcls (minnTPCcls); \/\/ which value do you want apply for the minTPCcls cut?\n taskCheckPerfCascadepp276->SetExtraSelections (kextrasel); \/\/ choose if apply the extra selection of cascade reco.\n taskCheckPerfCascadepp276->SetApplyAccCut (kacccut); \/\/ choose if apply acceptance cut\n taskCheckPerfCascadepp276->SetVertexRange (vtxlim); \/\/ which higher value do you want apply for vtx Z cut?\n taskCheckPerfCascadepp276->SetVertexRangeMin (vtxlimmin); \/\/ which lower value do you want apply for vtx Z cut?\n taskCheckPerfCascadepp276->SetMinptCutOnDaughterTracks (minptondaughtertracks); \/\/ which value do you want apply for cut on min pt daughter track?\n taskCheckPerfCascadepp276->SetEtaCutOnDaughterTracks (etacutondaughtertracks); \/\/ which value do you want apply for cut on eta daughter track?\n \n mgr->AddTask(taskCheckPerfCascadepp276);\n\n \/\/ Create ONLY the output containers for the data produced by the task.\n \/\/ Get and connect other common input\/output containers via the manager as below\n \/\/==============================================================================\n \/\/ Directory name\n TString outputFileNamePerf = Form(\"%s:PWGLFStrangeness.outputCheckPerformanceCascadepp276\", AliAnalysisManager::GetCommonFileName());\n \/\/ Objects name\n TString outputnameperf0 = \"clistCascPerf\";\n TString outputnameperf1 = \"cfcontPIDAsXiM\";\n TString outputnameperf2 = \"cfcontPIDAsXiP\";\n TString outputnameperf3 = \"cfcontPIDAsOmegaM\";\n TString outputnameperf4 = \"cfcontPIDAsOmegaP\";\n TString outputnameperf5 = \"cfcontAsCuts\";\n outputnameperf0 += Form(\"_minnTPCcls%i_vtxlim%.1f-%.1f_minptdghtrk%.1f_etacutdghtrk%.1f\",minnTPCcls,vtxlim,vtxlimmin,minptondaughtertracks,etacutondaughtertracks);\n outputnameperf1 += Form(\"_minnTPCcls%i_vtxlim%.1f-%.1f_minptdghtrk%.1f_etacutdghtrk%.1f\",minnTPCcls,vtxlim,vtxlimmin,minptondaughtertracks,etacutondaughtertracks);\n outputnameperf2 += Form(\"_minnTPCcls%i_vtxlim%.1f-%.1f_minptdghtrk%.1f_etacutdghtrk%.1f\",minnTPCcls,vtxlim,vtxlimmin,minptondaughtertracks,etacutondaughtertracks);\n outputnameperf3 += Form(\"_minnTPCcls%i_vtxlim%.1f-%.1f_minptdghtrk%.1f_etacutdghtrk%.1f\",minnTPCcls,vtxlim,vtxlimmin,minptondaughtertracks,etacutondaughtertracks);\n outputnameperf4 += Form(\"_minnTPCcls%i_vtxlim%.1f-%.1f_minptdghtrk%.1f_etacutdghtrk%.1f\",minnTPCcls,vtxlim,vtxlimmin,minptondaughtertracks,etacutondaughtertracks);\n outputnameperf5 += Form(\"_minnTPCcls%i_vtxlim%.1f-%.1f_minptdghtrk%.1f_etacutdghtrk%.1f\",minnTPCcls,vtxlim,vtxlimmin,minptondaughtertracks,etacutondaughtertracks);\n \n \n \/\/Save objects into the train common file\n AliAnalysisDataContainer *coutputperf1 = mgr->CreateContainer(outputnameperf0,\n\t\t\t\t\t\t\t TList::Class(),\n AliAnalysisManager::kOutputContainer,\n\t\t\t\t\t\t\t outputFileNamePerf );\n AliAnalysisDataContainer *coutputperf2 = mgr->CreateContainer(outputnameperf1,\n AliCFContainer::Class(),\n AliAnalysisManager::kOutputContainer,\n outputFileNamePerf );\n AliAnalysisDataContainer *coutputperf3 = mgr->CreateContainer(outputnameperf2,\n AliCFContainer::Class(),\n AliAnalysisManager::kOutputContainer,\n outputFileNamePerf );\n AliAnalysisDataContainer *coutputperf4 = mgr->CreateContainer(outputnameperf3,\n AliCFContainer::Class(),\n AliAnalysisManager::kOutputContainer,\n outputFileNamePerf );\n AliAnalysisDataContainer *coutputperf5 = mgr->CreateContainer(outputnameperf4,\n AliCFContainer::Class(),\n AliAnalysisManager::kOutputContainer,\n outputFileNamePerf );\n AliAnalysisDataContainer *coutputperf6 = mgr->CreateContainer(outputnameperf5,\n AliCFContainer::Class(),\n AliAnalysisManager::kOutputContainer,\n outputFileNamePerf );\n\n mgr->ConnectInput( taskCheckPerfCascadepp276, 0, mgr->GetCommonInputContainer());\n mgr->ConnectOutput(taskCheckPerfCascadepp276, 1, coutputperf1);\n mgr->ConnectOutput(taskCheckPerfCascadepp276, 2, coutputperf2);\n mgr->ConnectOutput(taskCheckPerfCascadepp276, 3, coutputperf3);\n mgr->ConnectOutput(taskCheckPerfCascadepp276, 4, coutputperf4);\n mgr->ConnectOutput(taskCheckPerfCascadepp276, 5, coutputperf5);\n mgr->ConnectOutput(taskCheckPerfCascadepp276, 6, coutputperf6);\n \n return taskCheckPerfCascadepp276;\n} \nFix to apply pileup selection in MC performanceAliAnalysisTaskCheckPerformanceCascadepp276 *AddTaskCheckPerformanceCascadepp276( Int_t minnTPCcls = 70,\n Float_t vtxlim = 10.,\n Float_t vtxlimmin = 0.,\n Bool_t fwithsdd = kFALSE,\n Bool_t kextrasel = kFALSE,\n Bool_t kacccut = kFALSE,\n Bool_t krelaunchvertexers = kFALSE,\n Bool_t ksddonselection = kFALSE,\n Float_t minptondaughtertracks = 0.0,\n Float_t etacutondaughtertracks = 0.8) {\n \n \/\/ Creates, configures and attaches to the train a cascades check task.\n \/\/ Get the pointer to the existing analysis manager via the static access method.\n \/\/==============================================================================\n AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();\n if (!mgr) {\n ::Error(\"AddTaskCheckPerformanceCascadepp276\", \"No analysis manager to connect to.\");\n return NULL;\n } \n\n \/\/ Check the analysis type using the event handlers connected to the analysis manager.\n \/\/==============================================================================\n if (!mgr->GetInputEventHandler()) {\n ::Error(\"AddTaskCheckPerformanceCascadepp276\", \"This task requires an input event handler\");\n return NULL;\n } \n TString type = mgr->GetInputEventHandler()->GetDataType(); \/\/ can be \"ESD\" or \"AOD\"\n\n \/\/ Create and configure the task\n \/\/==============================================================================\n TString tasknameperf = \"TaskCheckPerformanceCascadepp276\";\n tasknameperf += Form(\"_minnTPCcls%i_vtxlim%.1f-%.1f_minptdghtrk%.1f_etacutdghtrk%.1f\",minnTPCcls,vtxlim,vtxlimmin,minptondaughtertracks,etacutondaughtertracks);\n AliAnalysisTaskCheckPerformanceCascadepp276 *taskCheckPerfCascadepp276 = new AliAnalysisTaskCheckPerformanceCascadepp276(tasknameperf);\n taskCheckPerfCascadepp276->SetAnalysisType (type); \/\/ \"ESD\" or \"AOD\"\n taskCheckPerfCascadepp276->SetRelaunchV0CascVertexers (krelaunchvertexers); \/\/ choose if reconstruct the vertex of V0 in the cascades\n taskCheckPerfCascadepp276->SetSDDSelection (fwithsdd); \/\/ choose if apply SDD event selection\n taskCheckPerfCascadepp276->SetQualityCutZprimVtxPos (kTRUE); \/\/ choose if apply Z vtx PV position event selection\n taskCheckPerfCascadepp276->SetRejectEventPileUp (kTRUE); \/\/ choose if apply no Pileup event selection\n taskCheckPerfCascadepp276->SetQualityCutNoTPConlyPrimVtx (kTRUE); \/\/ choose if apply no TPC only event selection\n taskCheckPerfCascadepp276->SetQualityCutTPCrefit (kTRUE); \/\/ choose if apply TPC refit on daughter tracks\n taskCheckPerfCascadepp276->SetQualityCutnTPCcls (kTRUE); \/\/ choose if apply n TPC cluster selection on daughter tracks\n taskCheckPerfCascadepp276->SetWithSDDOn (ksddonselection); \/\/ which SDD selection do you want apply? [if kTRUE select SDDon events]\n taskCheckPerfCascadepp276->SetQualityCutMinnTPCcls (minnTPCcls); \/\/ which value do you want apply for the minTPCcls cut?\n taskCheckPerfCascadepp276->SetExtraSelections (kextrasel); \/\/ choose if apply the extra selection of cascade reco.\n taskCheckPerfCascadepp276->SetApplyAccCut (kacccut); \/\/ choose if apply acceptance cut\n taskCheckPerfCascadepp276->SetVertexRange (vtxlim); \/\/ which higher value do you want apply for vtx Z cut?\n taskCheckPerfCascadepp276->SetVertexRangeMin (vtxlimmin); \/\/ which lower value do you want apply for vtx Z cut?\n taskCheckPerfCascadepp276->SetMinptCutOnDaughterTracks (minptondaughtertracks); \/\/ which value do you want apply for cut on min pt daughter track?\n taskCheckPerfCascadepp276->SetEtaCutOnDaughterTracks (etacutondaughtertracks); \/\/ which value do you want apply for cut on eta daughter track?\n \n mgr->AddTask(taskCheckPerfCascadepp276);\n\n \/\/ Create ONLY the output containers for the data produced by the task.\n \/\/ Get and connect other common input\/output containers via the manager as below\n \/\/==============================================================================\n \/\/ Directory name\n TString outputFileNamePerf = Form(\"%s:PWGLFStrangeness.outputCheckPerformanceCascadepp276\", AliAnalysisManager::GetCommonFileName());\n \/\/ Objects name\n TString outputnameperf0 = \"clistCascPerf\";\n TString outputnameperf1 = \"cfcontPIDAsXiM\";\n TString outputnameperf2 = \"cfcontPIDAsXiP\";\n TString outputnameperf3 = \"cfcontPIDAsOmegaM\";\n TString outputnameperf4 = \"cfcontPIDAsOmegaP\";\n TString outputnameperf5 = \"cfcontAsCuts\";\n outputnameperf0 += Form(\"_minnTPCcls%i_vtxlim%.1f-%.1f_minptdghtrk%.1f_etacutdghtrk%.1f\",minnTPCcls,vtxlim,vtxlimmin,minptondaughtertracks,etacutondaughtertracks);\n outputnameperf1 += Form(\"_minnTPCcls%i_vtxlim%.1f-%.1f_minptdghtrk%.1f_etacutdghtrk%.1f\",minnTPCcls,vtxlim,vtxlimmin,minptondaughtertracks,etacutondaughtertracks);\n outputnameperf2 += Form(\"_minnTPCcls%i_vtxlim%.1f-%.1f_minptdghtrk%.1f_etacutdghtrk%.1f\",minnTPCcls,vtxlim,vtxlimmin,minptondaughtertracks,etacutondaughtertracks);\n outputnameperf3 += Form(\"_minnTPCcls%i_vtxlim%.1f-%.1f_minptdghtrk%.1f_etacutdghtrk%.1f\",minnTPCcls,vtxlim,vtxlimmin,minptondaughtertracks,etacutondaughtertracks);\n outputnameperf4 += Form(\"_minnTPCcls%i_vtxlim%.1f-%.1f_minptdghtrk%.1f_etacutdghtrk%.1f\",minnTPCcls,vtxlim,vtxlimmin,minptondaughtertracks,etacutondaughtertracks);\n outputnameperf5 += Form(\"_minnTPCcls%i_vtxlim%.1f-%.1f_minptdghtrk%.1f_etacutdghtrk%.1f\",minnTPCcls,vtxlim,vtxlimmin,minptondaughtertracks,etacutondaughtertracks);\n \n \n \/\/Save objects into the train common file\n AliAnalysisDataContainer *coutputperf1 = mgr->CreateContainer(outputnameperf0,\n\t\t\t\t\t\t\t TList::Class(),\n AliAnalysisManager::kOutputContainer,\n\t\t\t\t\t\t\t outputFileNamePerf );\n AliAnalysisDataContainer *coutputperf2 = mgr->CreateContainer(outputnameperf1,\n AliCFContainer::Class(),\n AliAnalysisManager::kOutputContainer,\n outputFileNamePerf );\n AliAnalysisDataContainer *coutputperf3 = mgr->CreateContainer(outputnameperf2,\n AliCFContainer::Class(),\n AliAnalysisManager::kOutputContainer,\n outputFileNamePerf );\n AliAnalysisDataContainer *coutputperf4 = mgr->CreateContainer(outputnameperf3,\n AliCFContainer::Class(),\n AliAnalysisManager::kOutputContainer,\n outputFileNamePerf );\n AliAnalysisDataContainer *coutputperf5 = mgr->CreateContainer(outputnameperf4,\n AliCFContainer::Class(),\n AliAnalysisManager::kOutputContainer,\n outputFileNamePerf );\n AliAnalysisDataContainer *coutputperf6 = mgr->CreateContainer(outputnameperf5,\n AliCFContainer::Class(),\n AliAnalysisManager::kOutputContainer,\n outputFileNamePerf );\n\n mgr->ConnectInput( taskCheckPerfCascadepp276, 0, mgr->GetCommonInputContainer());\n mgr->ConnectOutput(taskCheckPerfCascadepp276, 1, coutputperf1);\n mgr->ConnectOutput(taskCheckPerfCascadepp276, 2, coutputperf2);\n mgr->ConnectOutput(taskCheckPerfCascadepp276, 3, coutputperf3);\n mgr->ConnectOutput(taskCheckPerfCascadepp276, 4, coutputperf4);\n mgr->ConnectOutput(taskCheckPerfCascadepp276, 5, coutputperf5);\n mgr->ConnectOutput(taskCheckPerfCascadepp276, 6, coutputperf6);\n \n return taskCheckPerfCascadepp276;\n} \n<|endoftext|>"} {"text":"\/*\r\n * File: ft_index_data.cpp\r\n * Copyright (C) 2004 The Institute for System Programming of the Russian Academy of Sciences (ISP RAS)\r\n *\/\r\n\r\n\r\n#include \"common\/sedna.h\"\r\n\r\n#include \"tr\/ft\/ft_index_data.h\"\r\n#include \"common\/xptr.h\"\r\n#include \"tr\/crmutils\/node_utils.h\"\r\n#include \"tr\/vmm\/vmm.h\"\r\n#include \"tr\/executor\/base\/tuple.h\"\r\n#include \"tr\/ft\/FTindex.h\"\r\n#include \"tr\/log\/log.h\"\r\n#include \"tr\/structures\/schema.h\"\r\n#include \"tr\/executor\/fo\/casting_operations.h\"\r\n\/\/#include \"indexes.h\"\r\n#include \"tr\/executor\/base\/dm_accessors.h\"\r\n\r\n\r\nusing namespace std;\r\n\r\npers_sset *ft_indexdata;\r\nindex_id *ft_idx_counter;\r\nUSemaphore ft_index_sem;\/\/SEMAPHOR!!!\r\n\r\nstatic bool ft_index_initialized = false;\r\n\r\n\/\/inits metadata library\r\nvoid ft_index_on_session_begin(pers_sset * _indexdata_, index_id *_idx_counter_)\r\n{\r\n ft_indexdata = _indexdata_;\r\n ft_idx_counter = _idx_counter_;\r\n\t\/\/SEMAPHOR INIT SECTION\r\n\tif (USemaphoreOpen(&ft_index_sem, FT_INDEX_SEMAPHORE_STR, __sys_call_error) != 0)\r\n throw USER_EXCEPTION2(SE4012, \"FT_INDEX_SEMAPHORE_STR\");\r\n\r\n ft_index_initialized = true;\r\n}\r\n\r\nvoid ft_index_on_session_end()\r\n{\r\n if (!ft_index_initialized) return;\r\n\t\/\/SEMAPHOR RELEASE SECTION\r\n if (USemaphoreClose(ft_index_sem, __sys_call_error) != 0)\r\n throw USER_EXCEPTION2(SE4013, \"FT_INDEX_SEMAPHORE_STR\");\r\n ft_index_initialized = false;\r\n}\r\n\r\npers_sset::pers_sset_entry* search_ft_indexdata_cell(const char *index_title)\r\n{\r\n\treturn ft_indexdata->get(index_title,NULL);\t\r\n}\r\nft_custom_cell* ft_custom_cell::init(xml_ns* _ns, const char* _local,ft_index_type _cm,bool persistent)\r\n{\r\n\tft_custom_cell* ftc=(ft_custom_cell*)scm_malloc(sizeof(ft_custom_cell),persistent);\r\n\tftc->ns=_ns;\r\n\tif (_local!=NULL)\r\n\t{\r\n\t\tchar* z=(char*)scm_malloc(strlen(_local)+1,persistent);\r\n\t\tstrcpy(z,_local);\r\n\t\tftc->local=z;\r\n\t}\r\n\telse\r\n\t\tftc->local=NULL;\r\n\tftc->cm=_cm;\r\n\treturn ftc;\r\n}\r\nvoid ft_index_cell::delete_custom_tree (pers_sset * custom_tree)\r\n{\r\n\tpers_sset::pers_sset_entry* tmp=custom_tree->rb_minimum(custom_tree->root);\r\n\twhile (tmp!=NULL)\r\n\t{\r\n\t\t\/\/coll->free_metadata(tmp);\r\n\t\tft_custom_cell* mdc=tmp->obj;\r\n\t\tif (mdc->local)\r\n\t\t\tscm_free(mdc->local,IS_PH_PTR(mdc));\r\n\t\tscm_free(mdc,IS_PH_PTR(mdc));\r\n\t\ttmp->obj=NULL;\r\n\t\ttmp=custom_tree->rb_successor(tmp);\r\n\t}\r\n\tpers_sset::sset_free(custom_tree);\r\n}\r\nvoid inline free_ft_indexdata_cell(pers_sset::pers_sset_entry* entry)\r\n{\r\n\tft_index_cell* idc=entry->obj;\r\n\tft_indexdata->rb_delete(entry);\r\n\tif (idc->index_title!=NULL)\r\n\t\tscm_free(idc->index_title,true);\r\n\tdelete_PathExpr(idc->object);\r\n\tscm_free(idc->doc_name,true);\r\n\tif (idc->custom_tree!=NULL)\r\n\t\tft_index_cell::delete_custom_tree(idc->custom_tree);\r\n\tscm_free(idc,true);\r\n}\r\nbool ft_index_cell::fits_to_index(schema_node* snode)\r\n{\r\n\tt_scmnodes res;\r\n\tt_scmnodes objs=execute_abs_path_expr(snode->root,object);\r\n\tt_scmnodes::iterator it=objs.begin();\r\n\twhile (it!=objs.end())\r\n\t{\r\n\t\tif (*it==snode)\t\t\r\n\t\t\treturn true;\t\t\r\n\t\tit++;\r\n\t}\r\n\treturn false;\r\n}\r\nft_index_cell* ft_index_cell::create_index (PathExpr *object_path, ft_index_type it, doc_schema_node* schemaroot,const char * index_title, const char* doc_name,bool is_doc,std::vector< std::pair< std::pair,ft_index_type> >* templ, bool just_heap)\r\n{\r\n\t\/\/ I. Create and fill new index cell\r\n\tft_index_sem_down();\r\n\tif (search_ft_indexdata_cell(index_title)!=NULL)\r\n\t{\r\n\t\tft_index_sem_up();\t\r\n\t\tthrow USER_EXCEPTION(SE2033);\r\n\t}\r\n\tdown_concurrent_micro_ops_number();\r\n\tft_index_cell* idc=(ft_index_cell*)scm_malloc(sizeof(ft_index_cell),true);\r\n idc->id = *ft_idx_counter;\r\n (*ft_idx_counter)++;\r\n\tidc->schemaroot = schemaroot;\r\n\tschemaroot->create_ft_index(idc);\r\n\tidc->object = object_path;\r\n\tidc->ftype=it;\r\n\tidc->index_title=(char*)scm_malloc(strlen(index_title)+1,true);\r\n\tstrcpy(idc->index_title,index_title);\r\n\tidc->doc_name=(char*)scm_malloc(strlen(doc_name)+1,true);\r\n\tstrcpy(idc->doc_name,doc_name);\r\n\tidc->is_doc=is_doc;\r\n\tif (it==ft_customized_value && templ!=NULL)\r\n\t{\r\n\t\tidc->custom_tree= pers_sset::init();\r\n\t\tstd::vector,ft_index_type> >::iterator tmp=templ->begin();\r\n\t\twhile (tmp!=templ->end())\r\n\t\t{\r\n\t\t\t\r\n\t\t\tidc->custom_tree->put(ft_custom_cell::init((*tmp).first.first,(*tmp).first.second,(*tmp).second));\r\n\t\t\ttmp++;\r\n\t\t}\r\n\t}\r\n\t\/*idc->next = *indexdata;\r\n\tif ((*indexdata) != NULL) (*indexdata)->pred = idc;\r\n\t*indexdata = idc;*\/\r\n\tft_indexdata->put(idc);\r\n\tft_index_sem_up();\r\n hl_logical_log_ft_index(object_path, it,(char *) index_title, doc_name,is_doc,idc->custom_tree,true);\r\n\tup_concurrent_micro_ops_number();\r\n\t\/\/ ALGORITHM: indexing data\r\n\t\/\/II. Execute abs path (object_path) on the desriptive schema\r\n\tif (!just_heap)\r\n\t{\r\n\t\tt_scmnodes sobj = execute_abs_path_expr(schemaroot, object_path);\r\n\t\t\/\/III. For each schema node found (sn_obj)\r\n\t\tstd::vector start_nodes;\r\n\t\tfor (int i = 0; i < sobj.size(); i++)\r\n\t\t{\t\r\n\t\t\txptr blk= sobj[i]->bblk;\r\n\t\t\tsobj[i]->add_ft_index(idc);\r\n\t\t\tif (blk!=XNULL)\r\n\t\t\t{\r\n\t\t\tCHECKP(blk);\r\n\t\t\tstart_nodes.push_back((GETBLOCKFIRSTDESCRIPTORABSOLUTE(((node_blk_hdr*)XADDR(blk)))));\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\tSednaIndexJob sij(idc);\r\n\t\tsij.create_index(&start_nodes);\r\n\t}\r\n\treturn idc;\r\n}\r\nvoid ft_index_cell::delete_index (const char *index_title, bool just_heap)\r\n{\r\n\tft_index_sem_down();\r\n\tpers_sset::pers_sset_entry* idc=search_ft_indexdata_cell(index_title);\r\n\tif (idc!=NULL)\r\n\t{\r\n\t\t\r\n\t\tif (!just_heap)\r\n\t\t{\r\n\t\t\tSednaIndexJob sij(idc->obj);\r\n\t\t\tsij.clear_index();\t\t\r\n\t\t}\r\n\t\tdown_concurrent_micro_ops_number();\r\n\t\thl_logical_log_ft_index((idc->obj)->object,(idc->obj)->ftype,(idc->obj)->index_title,(idc->obj)->doc_name,(idc->obj)->is_doc,(idc->obj)->custom_tree,false);\r\n\t\tft_index_cell* ic=idc->obj;\r\n\t\tdoc_schema_node* sm=(idc->obj)->schemaroot;\r\n\t\tfree_ft_indexdata_cell(idc);\r\n\t\t(*ft_idx_counter)--;\r\n\t\tsm->delete_ft_index(ic);\r\n\t\tft_index_sem_up();\r\n\t\tup_concurrent_micro_ops_number();\r\n\t}\r\n\telse\r\n\t\tft_index_sem_up();\r\n}\r\nft_index_cell* ft_index_cell::find_index(const char* title)\r\n{\r\n\txptr res;\r\n ft_index_sem_down();\r\n\tpers_sset::pers_sset_entry* idc=search_ft_indexdata_cell(title);\r\n\tif (idc==NULL)\r\n\t{\r\n\t\tft_index_sem_up();\t\r\n\t\treturn NULL;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tft_index_sem_up();\t\r\n\t\treturn idc->obj;\r\n\t}\r\n}\r\nvoid ft_index_cell::update_index(xptr_sequence* upserted)\r\n{\r\n\tSednaIndexJob sij(this);\r\n\tsij.update_index(upserted);\r\n\r\n}\r\nvoid ft_index_cell::insert_to_index(xptr_sequence* upserted)\r\n{\r\n\tSednaIndexJob sij(this);\r\n\tsij.insert_into_index(upserted);\r\n\r\n}\r\nvoid ft_index_cell::delete_from_index(xptr_sequence* deleted)\r\n{\r\n\tSednaIndexJob sij(this);\r\n\tsij.delete_from_index(deleted);\r\n}\r\nvoid ft_index_cell::change_index(xptr_sequence* inserted,xptr_sequence* updated,xptr_sequence* deleted)\r\n{\r\n\tSednaIndexJob sij(this);\r\n\tsij.insert_into_index(inserted);\r\n\tsij.update_index(updated);\r\n\tsij.delete_from_index(deleted);\r\n}\r\nftindex fix\/*\r\n * File: ft_index_data.cpp\r\n * Copyright (C) 2004 The Institute for System Programming of the Russian Academy of Sciences (ISP RAS)\r\n *\/\r\n\r\n\r\n#include \"common\/sedna.h\"\r\n\r\n#include \"tr\/ft\/ft_index_data.h\"\r\n#include \"common\/xptr.h\"\r\n#include \"tr\/crmutils\/node_utils.h\"\r\n#include \"tr\/vmm\/vmm.h\"\r\n#include \"tr\/executor\/base\/tuple.h\"\r\n#include \"tr\/ft\/FTindex.h\"\r\n#include \"tr\/log\/log.h\"\r\n#include \"tr\/structures\/schema.h\"\r\n#include \"tr\/executor\/fo\/casting_operations.h\"\r\n\/\/#include \"indexes.h\"\r\n#include \"tr\/executor\/base\/dm_accessors.h\"\r\n\r\n\r\nusing namespace std;\r\n\r\npers_sset *ft_indexdata;\r\nindex_id *ft_idx_counter;\r\nUSemaphore ft_index_sem;\/\/SEMAPHOR!!!\r\n\r\nstatic bool ft_index_initialized = false;\r\n\r\n\/\/inits metadata library\r\nvoid ft_index_on_session_begin(pers_sset * _indexdata_, index_id *_idx_counter_)\r\n{\r\n ft_indexdata = _indexdata_;\r\n ft_idx_counter = _idx_counter_;\r\n\t\/\/SEMAPHOR INIT SECTION\r\n\tif (USemaphoreOpen(&ft_index_sem, FT_INDEX_SEMAPHORE_STR, __sys_call_error) != 0)\r\n throw USER_EXCEPTION2(SE4012, \"FT_INDEX_SEMAPHORE_STR\");\r\n\r\n ft_index_initialized = true;\r\n}\r\n\r\nvoid ft_index_on_session_end()\r\n{\r\n if (!ft_index_initialized) return;\r\n\t\/\/SEMAPHOR RELEASE SECTION\r\n if (USemaphoreClose(ft_index_sem, __sys_call_error) != 0)\r\n throw USER_EXCEPTION2(SE4013, \"FT_INDEX_SEMAPHORE_STR\");\r\n ft_index_initialized = false;\r\n}\r\n\r\npers_sset::pers_sset_entry* search_ft_indexdata_cell(const char *index_title)\r\n{\r\n\treturn ft_indexdata->get(index_title,NULL);\t\r\n}\r\nft_custom_cell* ft_custom_cell::init(xml_ns* _ns, const char* _local,ft_index_type _cm,bool persistent)\r\n{\r\n\tft_custom_cell* ftc=(ft_custom_cell*)scm_malloc(sizeof(ft_custom_cell),persistent);\r\n\tftc->ns=_ns;\r\n\tif (_local!=NULL)\r\n\t{\r\n\t\tchar* z=(char*)scm_malloc(strlen(_local)+1,persistent);\r\n\t\tstrcpy(z,_local);\r\n\t\tftc->local=z;\r\n\t}\r\n\telse\r\n\t\tftc->local=NULL;\r\n\tftc->cm=_cm;\r\n\treturn ftc;\r\n}\r\nvoid ft_index_cell::delete_custom_tree (pers_sset * custom_tree)\r\n{\r\n\tpers_sset::pers_sset_entry* tmp=custom_tree->rb_minimum(custom_tree->root);\r\n\twhile (tmp!=NULL)\r\n\t{\r\n\t\t\/\/coll->free_metadata(tmp);\r\n\t\tft_custom_cell* mdc=tmp->obj;\r\n\t\tif (mdc->local)\r\n\t\t\tscm_free(mdc->local,IS_PH_PTR(mdc));\r\n\t\tscm_free(mdc,IS_PH_PTR(mdc));\r\n\t\ttmp->obj=NULL;\r\n\t\ttmp=custom_tree->rb_successor(tmp);\r\n\t}\r\n\tpers_sset::sset_free(custom_tree);\r\n}\r\nvoid inline free_ft_indexdata_cell(pers_sset::pers_sset_entry* entry)\r\n{\r\n\tft_index_cell* idc=entry->obj;\r\n\tft_indexdata->rb_delete(entry);\r\n\tif (idc->index_title!=NULL)\r\n\t\tscm_free(idc->index_title,true);\r\n\tdelete_PathExpr(idc->object);\r\n\tscm_free(idc->doc_name,true);\r\n\tif (idc->custom_tree!=NULL)\r\n\t\tft_index_cell::delete_custom_tree(idc->custom_tree);\r\n\tscm_free(idc,true);\r\n}\r\nbool ft_index_cell::fits_to_index(schema_node* snode)\r\n{\r\n\tt_scmnodes res;\r\n\tt_scmnodes objs=execute_abs_path_expr(snode->root,object);\r\n\tt_scmnodes::iterator it=objs.begin();\r\n\twhile (it!=objs.end())\r\n\t{\r\n\t\tif (*it==snode)\t\t\r\n\t\t\treturn true;\t\t\r\n\t\tit++;\r\n\t}\r\n\treturn false;\r\n}\r\nft_index_cell* ft_index_cell::create_index (PathExpr *object_path, ft_index_type it, doc_schema_node* schemaroot,const char * index_title, const char* doc_name,bool is_doc,std::vector< std::pair< std::pair,ft_index_type> >* templ, bool just_heap)\r\n{\r\n\t\/\/ I. Create and fill new index cell\r\n\tft_index_sem_down();\r\n\tif (search_ft_indexdata_cell(index_title)!=NULL)\r\n\t{\r\n\t\tft_index_sem_up();\t\r\n\t\tthrow USER_EXCEPTION(SE2033);\r\n\t}\r\n\tdown_concurrent_micro_ops_number();\r\n\tft_index_cell* idc=(ft_index_cell*)scm_malloc(sizeof(ft_index_cell),true);\r\n idc->id = *ft_idx_counter;\r\n (*ft_idx_counter)++;\r\n\tidc->schemaroot = schemaroot;\r\n\tschemaroot->create_ft_index(idc);\r\n\tidc->object = object_path;\r\n\tidc->ftype=it;\r\n\tidc->index_title=(char*)scm_malloc(strlen(index_title)+1,true);\r\n\tstrcpy(idc->index_title,index_title);\r\n\tidc->doc_name=(char*)scm_malloc(strlen(doc_name)+1,true);\r\n\tstrcpy(idc->doc_name,doc_name);\r\n\tidc->is_doc=is_doc;\r\n\tif (it==ft_customized_value && templ!=NULL)\r\n\t{\r\n\t\tidc->custom_tree= pers_sset::init();\r\n\t\tstd::vector,ft_index_type> >::iterator tmp=templ->begin();\r\n\t\twhile (tmp!=templ->end())\r\n\t\t{\r\n\t\t\t\r\n\t\t\tidc->custom_tree->put(ft_custom_cell::init((*tmp).first.first,(*tmp).first.second,(*tmp).second));\r\n\t\t\ttmp++;\r\n\t\t}\r\n\t}\r\n\t\/*idc->next = *indexdata;\r\n\tif ((*indexdata) != NULL) (*indexdata)->pred = idc;\r\n\t*indexdata = idc;*\/\r\n\tft_indexdata->put(idc);\r\n\tft_index_sem_up();\r\n hl_logical_log_ft_index(object_path, it,(char *) index_title, doc_name,is_doc,idc->custom_tree,true);\r\n\tup_concurrent_micro_ops_number();\r\n\t\/\/ ALGORITHM: indexing data\r\n\t\/\/II. Execute abs path (object_path) on the desriptive schema\r\n\tif (!just_heap)\r\n\t{\r\n\t\tt_scmnodes sobj = execute_abs_path_expr(schemaroot, object_path);\r\n\t\t\/\/III. For each schema node found (sn_obj)\r\n\t\tstd::vector start_nodes;\r\n\t\tfor (int i = 0; i < sobj.size(); i++)\r\n\t\t{\t\r\n\t\t\txptr blk= sobj[i]->bblk;\r\n\t\t\tsobj[i]->add_ft_index(idc);\r\n\t\t\tif (blk!=XNULL)\r\n\t\t\t{\r\n\t\t\tCHECKP(blk);\r\n\t\t\tstart_nodes.push_back((GETBLOCKFIRSTDESCRIPTORABSOLUTE(((node_blk_hdr*)XADDR(blk)))));\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\tSednaIndexJob sij(idc);\r\n\t\tsij.create_index(&start_nodes);\r\n\t}\r\n\treturn idc;\r\n}\r\nvoid ft_index_cell::delete_index (const char *index_title, bool just_heap)\r\n{\r\n\tft_index_sem_down();\r\n\tpers_sset::pers_sset_entry* idc=search_ft_indexdata_cell(index_title);\r\n\tif (idc!=NULL)\r\n\t{\r\n\t\t\r\n\t\tdown_concurrent_micro_ops_number();\r\n\t\thl_logical_log_ft_index((idc->obj)->object,(idc->obj)->ftype,(idc->obj)->index_title,(idc->obj)->doc_name,(idc->obj)->is_doc,(idc->obj)->custom_tree,false);\r\n\t\tif (!just_heap) \/\/FIXME: mb move out of down_concurrent_micro_ops_number() block\r\n\t\t{\r\n\t\t\tSednaIndexJob sij(idc->obj);\r\n\t\t\tsij.clear_index();\t\t\r\n\t\t}\r\n\t\tft_index_cell* ic=idc->obj;\r\n\t\tdoc_schema_node* sm=(idc->obj)->schemaroot;\r\n\t\tfree_ft_indexdata_cell(idc);\r\n\t\t(*ft_idx_counter)--;\r\n\t\tsm->delete_ft_index(ic);\r\n\t\tft_index_sem_up();\r\n\t\tup_concurrent_micro_ops_number();\r\n\t}\r\n\telse\r\n\t\tft_index_sem_up();\r\n}\r\nft_index_cell* ft_index_cell::find_index(const char* title)\r\n{\r\n\txptr res;\r\n ft_index_sem_down();\r\n\tpers_sset::pers_sset_entry* idc=search_ft_indexdata_cell(title);\r\n\tif (idc==NULL)\r\n\t{\r\n\t\tft_index_sem_up();\t\r\n\t\treturn NULL;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tft_index_sem_up();\t\r\n\t\treturn idc->obj;\r\n\t}\r\n}\r\nvoid ft_index_cell::update_index(xptr_sequence* upserted)\r\n{\r\n\tSednaIndexJob sij(this);\r\n\tsij.update_index(upserted);\r\n\r\n}\r\nvoid ft_index_cell::insert_to_index(xptr_sequence* upserted)\r\n{\r\n\tSednaIndexJob sij(this);\r\n\tsij.insert_into_index(upserted);\r\n\r\n}\r\nvoid ft_index_cell::delete_from_index(xptr_sequence* deleted)\r\n{\r\n\tSednaIndexJob sij(this);\r\n\tsij.delete_from_index(deleted);\r\n}\r\nvoid ft_index_cell::change_index(xptr_sequence* inserted,xptr_sequence* updated,xptr_sequence* deleted)\r\n{\r\n\tSednaIndexJob sij(this);\r\n\tsij.insert_into_index(inserted);\r\n\tsij.update_index(updated);\r\n\tsij.delete_from_index(deleted);\r\n}\r\n<|endoftext|>"} {"text":"#include \"QmitkSimpleExampleFunctionality.h\"\n#include \"QmitkStdMultiWidget.h\"\n#include \"QmitkSelectableGLWidget.h\"\n\n#include \"QmitkSimpleExampleControls.h\"\n\n#include \n#include \n\n#include \"slicer.xpm\"\n\n#include \"mitkPlaneGeometry.h\"\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \n\n#if (defined(_MSC_VER) && (_MSC_VER <= 1200))\n #include \n#else\n #define _MAX\tmax\n #define _MIN\tmin\n#endif\n\nQmitkSimpleExampleFunctionality::QmitkSimpleExampleFunctionality(QObject *parent, const char *name, QmitkStdMultiWidget *mitkStdMultiWidget, mitk::DataTreeIterator * it) : QmitkFunctionality(parent, name, it) ,\ncontrols(NULL), multiWidget(mitkStdMultiWidget), opacityprop(NULL), lookupTableProp(NULL)\n{\n setAvailability(true);\n\n mitk::GlobalInteraction* globalInteraction = dynamic_cast(mitk::EventMapper::GetGlobalStateMachine());\n if(globalInteraction!=NULL)\n {\n\t globalInteraction->AddStateMachine(new mitk::CoordinateSupplier(\"navigation\", this));\/\/sends PointOperations\n\t globalInteraction->AddStateMachine(new mitk::DisplayVectorInteractor(\"move\", this));\/\/sends DisplayCoordinateOperation\n\t globalInteraction->AddStateMachine(new mitk::DisplayVectorInteractor(\"zoom\", this));\/\/sends DisplayCoordinateOperation\n }\n\n m_DataTreeIterator->getTree()->addTreeChangeListener(this);\n}\n\nQmitkSimpleExampleFunctionality::~QmitkSimpleExampleFunctionality()\n{\n}\n\nQString QmitkSimpleExampleFunctionality::getFunctionalityName()\n{\n return \"simple example\";\n}\n\nQWidget * QmitkSimpleExampleFunctionality::createMainWidget(QWidget *parent)\n{\n if (multiWidget == NULL) \n {\n return multiWidget = new QmitkStdMultiWidget(parent);\n }\n else\n return NULL;\n}\n\nQWidget * QmitkSimpleExampleFunctionality::createControlWidget(QWidget *parent)\n{\n if (controls == NULL)\n {\n controls = new QmitkSimpleExampleControls(parent);\n\n sliceNavigatorTransversal = mitk::SliceNavigationController::New();\n sliceNavigatorTransversal->SetViewDirection(mitk::SliceNavigationController::Transversal);\n sliceNavigatorTransversal->ConnectGeometrySliceEvent(multiWidget->mitkWidget1->GetRenderer().GetPointer());\n new QmitkStepperAdapter(controls->getSliceNavigatorTransversal(), sliceNavigatorTransversal->GetSlice(), \"sliceNavigatorTransversalFromSimpleExample\");\n\n sliceNavigatorSagittal = mitk::SliceNavigationController::New();\n sliceNavigatorSagittal->SetViewDirection(mitk::SliceNavigationController::Sagittal);\n sliceNavigatorSagittal->ConnectGeometrySliceEvent(multiWidget->mitkWidget2->GetRenderer().GetPointer());\n new QmitkStepperAdapter(controls->getSliceNavigatorSagittal(), sliceNavigatorSagittal->GetSlice(), \"sliceNavigatorSagittalFromSimpleExample\");\n\n sliceNavigatorFrontal = mitk::SliceNavigationController::New();\n sliceNavigatorFrontal->SetViewDirection(mitk::SliceNavigationController::Frontal);\n sliceNavigatorFrontal->ConnectGeometrySliceEvent(multiWidget->mitkWidget3->GetRenderer().GetPointer());\n new QmitkStepperAdapter(controls->getSliceNavigatorFrontal(), sliceNavigatorFrontal->GetSlice(), \"sliceNavigatorFrontalFromSimpleExample\");\n\n sliceNavigatorTime = mitk::SliceNavigationController::New();\n sliceNavigatorTime->ConnectGeometryTimeEvent(multiWidget->mitkWidget1->GetRenderer().GetPointer());\n new QmitkStepperAdapter(controls->getSliceNavigatorTime(), sliceNavigatorTime->GetTime(), \"sliceNavigatorTimeFromSimpleExample\");\n }\n return controls;\n}\n\nvoid QmitkSimpleExampleFunctionality::createConnections()\n{\n connect(controls, SIGNAL(xySliderChanged(int)), this, SLOT(selectSliceWidgetXY(int)) );\n connect(controls, SIGNAL(yzSliderChanged(int)), this, SLOT(selectSliceWidgetYZ(int)) );\n connect(controls, SIGNAL(xzSliderChanged(int)), this, SLOT(selectSliceWidgetXZ(int)) );\n connect(controls, SIGNAL(fpSliderChanged(int)), this, SLOT(selectSliceWidgetFP(int)) );\n}\n\nQAction * QmitkSimpleExampleFunctionality::createAction(QActionGroup *parent)\n{\n QAction* action;\n action = new QAction( tr( \"Left\" ), QPixmap((const char**)slicer_xpm), tr( \"&Left\" ), CTRL + Key_L, parent, \"simple example\" );\n \/\/ action = new QAction( tr( \"Left\" ), QPixmap(textleft_xpm), tr( \"&Left\" ), CTRL + Key_L, parent, \"simple example\" );\n return action;\n}\nvoid QmitkSimpleExampleFunctionality::initNavigators()\n{\n const mitk::BoundingBox::Pointer boundingbox = mitk::DataTree::ComputeVisibleBoundingBox(m_DataTreeIterator, NULL, \"includeInBoundingBox\");\n if(boundingbox->GetPoints()->Size()>0)\n {\n mitk::Geometry3D::Pointer geometry = mitk::Geometry3D::New();\n geometry->Initialize();\n geometry->SetBoundingBox(boundingbox);\n sliceNavigatorTransversal->SetInputWorldGeometry(geometry.GetPointer()); sliceNavigatorTransversal->Update();\n sliceNavigatorFrontal->SetInputWorldGeometry(geometry.GetPointer()); sliceNavigatorFrontal->Update();\n sliceNavigatorSagittal->SetInputWorldGeometry(geometry.GetPointer()); sliceNavigatorSagittal->Update();\n }\n}\n\nvoid QmitkSimpleExampleFunctionality::treeChanged(mitk::DataTreeIterator& itpos)\n{\n if(isActivated())\n initNavigators();\n}\n\nvoid QmitkSimpleExampleFunctionality::activated()\n{\n QmitkFunctionality::activated();\n assert( multiWidget != NULL );\n \/\/ init widget 4 as a 3D widget\n multiWidget->mitkWidget4->GetRenderer()->SetMapperID(2);\n\n initNavigators();\n}\n\n\/\/void QmitkSimpleExampleFunctionality::deactivated()\n\/\/{\n\/\/\n\/\/}\n\nvoid QmitkSimpleExampleFunctionality::selectSliceWidgetXY( int z )\n{\n const mitk::Geometry2D* g2d = multiWidget->mitkWidget1->GetRenderer()->GetCurrentWorldGeometry2D();\n const mitk::PlaneGeometry* pg = dynamic_cast(g2d);\n mitk::PlaneView pv = pg->GetPlaneView();\n pv.point.z = z;\n mitk::PlaneGeometry::Pointer plane = mitk::PlaneGeometry::New(); \n plane->SetPlaneView(pv);\n multiWidget->mitkWidget1->GetRenderer()->SetWorldGeometry(plane);\n multiWidget->updateMitkWidgets();\n \/\/std::cout << \"Slider:\" << z << std::endl;\n}\n\nvoid QmitkSimpleExampleFunctionality::selectSliceWidgetXZ(int y)\n{\n const mitk::Geometry2D* g2d = multiWidget->mitkWidget3->GetRenderer()->GetCurrentWorldGeometry2D();\n const mitk::PlaneGeometry* pg = dynamic_cast(g2d);\n mitk::PlaneView pv = pg->GetPlaneView();\n pv.point.y=y;\n mitk::PlaneGeometry::Pointer plane = mitk::PlaneGeometry::New(); \n plane->SetPlaneView(pv);\n multiWidget->mitkWidget3->GetRenderer()->SetWorldGeometry(plane);\n multiWidget->updateMitkWidgets();\n \/\/std::cout << \"Slider:\" << y << std::endl;\n}\n\nvoid QmitkSimpleExampleFunctionality::selectSliceWidgetYZ(int x)\n{\n const mitk::Geometry2D* g2d = multiWidget->mitkWidget2->GetRenderer()->GetCurrentWorldGeometry2D();\n const mitk::PlaneGeometry* pg = dynamic_cast(g2d);\n mitk::PlaneView pv = pg->GetPlaneView();\n pv.point.x = x;\n mitk::PlaneGeometry::Pointer plane = mitk::PlaneGeometry::New(); \n plane->SetPlaneView(pv);\n multiWidget->mitkWidget2->GetRenderer()->SetWorldGeometry(plane);\n multiWidget->updateMitkWidgets();\n \/\/std::cout << \"Slider:\" << x << std::endl;\n}\n\nvoid QmitkSimpleExampleFunctionality::selectSliceWidgetFP( int p )\n{\n bool update=false;\n if( opacityprop.IsNotNull() ) \n {\n\t\topacityprop->SetValue(p\/100.0);\n update = true;\n\t}\n if(lookupTableProp.IsNotNull())\n {\n\t\tlookupTableProp->GetLookupTable().ChangeOpacityForAll(p\/100.0);\n update = true;\n\t}\n\n if(update)\n multiWidget->updateMitkWidgets();\n}\n\nvoid QmitkSimpleExampleFunctionality::initWidgets()\n{\n\tint count = 0;\n\tmitk::DataTreeIterator* it=m_DataTreeIterator->clone();\n\twhile (it->hasNext()) {\n\t\tit->next();\n\t\tprintf(\"\\nrequesting boundingbox\\n\"); \n\t\tmitk::DataTreeNode::Pointer node = it->get();\n\t\tmitk::BaseData::Pointer data=node->GetData();\n if((data.IsNotNull()) && (dynamic_cast(node->GetData()) == NULL ))\n\t\t{\n\t\t\t\/\/ get \n\t\t\tif ((data->GetUpdatedGeometry())!=NULL ) \n\t\t\t{\n\t\t\t\tmitk::BoundingBox::ConstPointer bb = data->GetGeometry()->GetBoundingBox();\n\t\t\t\tprintf(\"boundsArrayType\\n\");\n\t\t\t\tconst mitk::BoundingBox::BoundsArrayType bounds = bb->GetBounds();\n\t\t\t\tprintf(\"\\nboundingbox\\n\");\n\n\t\t\t\t\/\/ init slider limits\n\t\t\t\tcontrols->sliderYZ->setMinValue(std::_MIN(bounds[0],controls->sliderYZ->minValue()));\n\t\t\t\tcontrols->sliderYZ->setMaxValue(std::_MAX(bounds[1],controls->sliderYZ->maxValue()));\n\t\t\t\tcontrols->sliderXZ->setMinValue(std::_MIN(bounds[2],controls->sliderXZ->minValue()));\n\t\t\t\tcontrols->sliderXZ->setMaxValue(std::_MAX(bounds[3],controls->sliderXZ->maxValue()));\n\t\t\t\tcontrols->sliderXY->setMinValue(std::_MIN(bounds[4],controls->sliderXY->minValue()));\n\t\t\t\tcontrols->sliderXY->setMaxValue(std::_MAX(bounds[5],controls->sliderXY->maxValue()));\n\t\t\t\tcount++;\n\t\t\t}\n\n lookupTableProp=NULL;\n\t\t}\n\t}\n\tdelete it;\n}\n\n\nvoid QmitkSimpleExampleFunctionality::ExecuteOperation(mitk::Operation* operation)\n{\n bool ok;\/\/as return\n\n mitk::PointOperation* pointoperation=dynamic_cast(operation);\n if(pointoperation!=NULL)\n {\n \/****NAVIGATION inside the volume****\/\n switch (operation->GetOperationType())\n {\n case mitk::OpMOVE:\n {\n mitk::ITKPoint3D point;\n mitk::Point3D seed;\n\n point = pointoperation->GetPoint();\n mitk::itk2vm(point, seed);\n\n const mitk::Geometry2D* g2d;\n const mitk::PlaneGeometry* pg;\n mitk::PlaneView pv;\n mitk::PlaneGeometry::Pointer plane;\n \n int v;\n v=(int)seed.x;\n if(controls->getSliderYZ()->value()!=v)\n {\n g2d = multiWidget->mitkWidget2->GetRenderer()->GetCurrentWorldGeometry2D();\n pg = dynamic_cast(g2d);\n pv = pg->GetPlaneView();\n pv.point.x = v; \n plane = mitk::PlaneGeometry::New(); \n plane->SetPlaneView(pv);\n multiWidget->mitkWidget2->GetRenderer()->SetWorldGeometry(plane);\n controls->getSliderYZ()->blockSignals(true);\n controls->getSliderYZ()->setValue(v);\n controls->getSliderYZ()->blockSignals(false);\n }\n v=(int)seed.y;\n if(controls->getSliderXZ()->value()!=v)\n {\n g2d = multiWidget->mitkWidget3->GetRenderer()->GetCurrentWorldGeometry2D();\n pg = dynamic_cast(g2d);\n pv = pg->GetPlaneView();\n pv.point.y = v;\n plane = mitk::PlaneGeometry::New(); \n plane->SetPlaneView(pv);\n multiWidget->mitkWidget3->GetRenderer()->SetWorldGeometry(plane);\n controls->getSliderXZ()->blockSignals(true);\n controls->getSliderXZ()->setValue(v);\n controls->getSliderXZ()->blockSignals(false);\n }\n\n v=(int)seed.z;\n if(controls->getSliderXY()->value()!=v)\n {\n g2d = multiWidget->mitkWidget1->GetRenderer()->GetCurrentWorldGeometry2D();\n pg = dynamic_cast(g2d);\n pv = pg->GetPlaneView();\n pv.point.z = v;\n plane = mitk::PlaneGeometry::New(); \n plane->SetPlaneView(pv);\n multiWidget->mitkWidget1->GetRenderer()->SetWorldGeometry(plane);\n controls->getSliderXY()->blockSignals(true);\n controls->getSliderXY()->setValue(v);\n controls->getSliderXY()->blockSignals(false);\n }\n multiWidget->updateMitkWidgets();\n ok = true;\n }\n break;\n case mitk::OpNOTHING:\n break;\n default:\n ;\n }\n }\n mitk::DisplayCoordinateOperation* dcOperation=dynamic_cast(operation);\n if( dcOperation != NULL )\n {\n \/****ZOOM & MOVE of the whole volume****\/\n mitk::BaseRenderer* renderer = dcOperation->GetRenderer();\n if( renderer == NULL )\n return;\n switch (operation->GetOperationType())\n {\n case mitk::OpMOVE :\n {\n renderer->GetDisplayGeometry()->MoveBy(dcOperation->GetLastToCurrentDisplayVector()*(-1.0));\n renderer->GetRenderWindow()->Update();\n ok = true;\n }\n break;\n case mitk::OpZOOM :\n {\n float distance = dcOperation->GetLastToCurrentDisplayVector().y;\n distance = (distance > 0 ? 1 : (distance < 0 ? -1 : 0));\n float factor= 1.0 + distance * 0.05;\n renderer->GetDisplayGeometry()->Zoom(factor, dcOperation->GetStartDisplayCoordinate());\n renderer->GetRenderWindow()->Update();\n ok = true;\n }\n break;\n default:\n ;\n }\n }\n}\ninitialization of time-slicenavigationcontroller. works a bit.#include \"QmitkSimpleExampleFunctionality.h\"\n#include \"QmitkStdMultiWidget.h\"\n#include \"QmitkSelectableGLWidget.h\"\n\n#include \"QmitkSimpleExampleControls.h\"\n\n#include \n#include \n\n#include \"slicer.xpm\"\n\n#include \"mitkPlaneGeometry.h\"\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \n\n#if (defined(_MSC_VER) && (_MSC_VER <= 1200))\n #include \n#else\n #define _MAX\tmax\n #define _MIN\tmin\n#endif\n\nQmitkSimpleExampleFunctionality::QmitkSimpleExampleFunctionality(QObject *parent, const char *name, QmitkStdMultiWidget *mitkStdMultiWidget, mitk::DataTreeIterator * it) : QmitkFunctionality(parent, name, it) ,\ncontrols(NULL), multiWidget(mitkStdMultiWidget), opacityprop(NULL), lookupTableProp(NULL)\n{\n setAvailability(true);\n\n mitk::GlobalInteraction* globalInteraction = dynamic_cast(mitk::EventMapper::GetGlobalStateMachine());\n if(globalInteraction!=NULL)\n {\n\t globalInteraction->AddStateMachine(new mitk::CoordinateSupplier(\"navigation\", this));\/\/sends PointOperations\n\t globalInteraction->AddStateMachine(new mitk::DisplayVectorInteractor(\"move\", this));\/\/sends DisplayCoordinateOperation\n\t globalInteraction->AddStateMachine(new mitk::DisplayVectorInteractor(\"zoom\", this));\/\/sends DisplayCoordinateOperation\n }\n\n m_DataTreeIterator->getTree()->addTreeChangeListener(this);\n}\n\nQmitkSimpleExampleFunctionality::~QmitkSimpleExampleFunctionality()\n{\n}\n\nQString QmitkSimpleExampleFunctionality::getFunctionalityName()\n{\n return \"simple example\";\n}\n\nQWidget * QmitkSimpleExampleFunctionality::createMainWidget(QWidget *parent)\n{\n if (multiWidget == NULL) \n {\n return multiWidget = new QmitkStdMultiWidget(parent);\n }\n else\n return NULL;\n}\n\nQWidget * QmitkSimpleExampleFunctionality::createControlWidget(QWidget *parent)\n{\n if (controls == NULL)\n {\n controls = new QmitkSimpleExampleControls(parent);\n\n sliceNavigatorTransversal = mitk::SliceNavigationController::New();\n sliceNavigatorTransversal->SetViewDirection(mitk::SliceNavigationController::Transversal);\n sliceNavigatorTransversal->ConnectGeometrySliceEvent(multiWidget->mitkWidget1->GetRenderer().GetPointer());\n new QmitkStepperAdapter(controls->getSliceNavigatorTransversal(), sliceNavigatorTransversal->GetSlice(), \"sliceNavigatorTransversalFromSimpleExample\");\n\n sliceNavigatorSagittal = mitk::SliceNavigationController::New();\n sliceNavigatorSagittal->SetViewDirection(mitk::SliceNavigationController::Sagittal);\n sliceNavigatorSagittal->ConnectGeometrySliceEvent(multiWidget->mitkWidget2->GetRenderer().GetPointer());\n new QmitkStepperAdapter(controls->getSliceNavigatorSagittal(), sliceNavigatorSagittal->GetSlice(), \"sliceNavigatorSagittalFromSimpleExample\");\n\n sliceNavigatorFrontal = mitk::SliceNavigationController::New();\n sliceNavigatorFrontal->SetViewDirection(mitk::SliceNavigationController::Frontal);\n sliceNavigatorFrontal->ConnectGeometrySliceEvent(multiWidget->mitkWidget3->GetRenderer().GetPointer());\n new QmitkStepperAdapter(controls->getSliceNavigatorFrontal(), sliceNavigatorFrontal->GetSlice(), \"sliceNavigatorFrontalFromSimpleExample\");\n\n sliceNavigatorTime = mitk::SliceNavigationController::New();\n sliceNavigatorTime->ConnectGeometryTimeEvent(multiWidget->mitkWidget1->GetRenderer().GetPointer());\n new QmitkStepperAdapter(controls->getSliceNavigatorTime(), sliceNavigatorTime->GetTime(), \"sliceNavigatorTimeFromSimpleExample\");\n }\n return controls;\n}\n\nvoid QmitkSimpleExampleFunctionality::createConnections()\n{\n connect(controls, SIGNAL(xySliderChanged(int)), this, SLOT(selectSliceWidgetXY(int)) );\n connect(controls, SIGNAL(yzSliderChanged(int)), this, SLOT(selectSliceWidgetYZ(int)) );\n connect(controls, SIGNAL(xzSliderChanged(int)), this, SLOT(selectSliceWidgetXZ(int)) );\n connect(controls, SIGNAL(fpSliderChanged(int)), this, SLOT(selectSliceWidgetFP(int)) );\n}\n\nQAction * QmitkSimpleExampleFunctionality::createAction(QActionGroup *parent)\n{\n QAction* action;\n action = new QAction( tr( \"Left\" ), QPixmap((const char**)slicer_xpm), tr( \"&Left\" ), CTRL + Key_L, parent, \"simple example\" );\n \/\/ action = new QAction( tr( \"Left\" ), QPixmap(textleft_xpm), tr( \"&Left\" ), CTRL + Key_L, parent, \"simple example\" );\n return action;\n}\nvoid QmitkSimpleExampleFunctionality::initNavigators()\n{\n const mitk::BoundingBox::Pointer boundingbox = mitk::DataTree::ComputeVisibleBoundingBox(m_DataTreeIterator, NULL, \"includeInBoundingBox\");\n if(boundingbox->GetPoints()->Size()>0)\n {\n \/\/ const mitk::BoundingBox::Pointer bb=boundingbox;\n \/\/const mitk::BoundingBox::BoundsArrayType bounds = bb->GetBounds();\n \/\/ float boundingbox[6]={-2*bounds[1],2*bounds[1],-2*bounds[3],2*bounds[3],-2*bounds[5],2*bounds[5]};\n mitk::Geometry3D::Pointer geometry = mitk::Geometry3D::New();\n geometry->Initialize();\n geometry->SetBoundingBox(boundingbox);\n\n \/\/lets see if we have data with a limited live-span ...\n mitk::TimeBounds timebounds = mitk::DataTree::ComputeTimeBoundsInMS(m_DataTreeIterator, NULL, \"includeInBoundingBox\");\n if(timebounds[1]Initialize(10);\n timegeometry->SetTimeBoundsInMS(timebounds); \/\/@bug really required?\n timegeometry->SetEvenlyTimed();\n mitk::ScalarType duration = timebounds[1]-timebounds[0];\n timebounds[1] = timebounds[0]+duration\/10.0;\n\n timegeometry->SetGeometry3D(geometry, 0);\n geometry->SetTimeBoundsInMS(timebounds);\n\n geometry=timegeometry;\n }\n\n sliceNavigatorTransversal->SetInputWorldGeometry(geometry.GetPointer()); sliceNavigatorTransversal->Update();\n sliceNavigatorFrontal->SetInputWorldGeometry(geometry.GetPointer()); sliceNavigatorFrontal->Update();\n sliceNavigatorSagittal->SetInputWorldGeometry(geometry.GetPointer()); sliceNavigatorSagittal->Update();\n sliceNavigatorTime->SetInputWorldGeometry(geometry.GetPointer()); sliceNavigatorTime->Update();\n }\n}\n\nvoid QmitkSimpleExampleFunctionality::treeChanged(mitk::DataTreeIterator& itpos)\n{\n if(isActivated())\n initNavigators();\n}\n\nvoid QmitkSimpleExampleFunctionality::activated()\n{\n QmitkFunctionality::activated();\n assert( multiWidget != NULL );\n \/\/ init widget 4 as a 3D widget\n multiWidget->mitkWidget4->GetRenderer()->SetMapperID(2);\n\n initNavigators();\n}\n\n\/\/void QmitkSimpleExampleFunctionality::deactivated()\n\/\/{\n\/\/\n\/\/}\n\nvoid QmitkSimpleExampleFunctionality::selectSliceWidgetXY( int z )\n{\n const mitk::Geometry2D* g2d = multiWidget->mitkWidget1->GetRenderer()->GetCurrentWorldGeometry2D();\n const mitk::PlaneGeometry* pg = dynamic_cast(g2d);\n mitk::PlaneView pv = pg->GetPlaneView();\n pv.point.z = z;\n mitk::PlaneGeometry::Pointer plane = mitk::PlaneGeometry::New(); \n plane->SetPlaneView(pv);\n multiWidget->mitkWidget1->GetRenderer()->SetWorldGeometry(plane);\n multiWidget->updateMitkWidgets();\n \/\/std::cout << \"Slider:\" << z << std::endl;\n}\n\nvoid QmitkSimpleExampleFunctionality::selectSliceWidgetXZ(int y)\n{\n const mitk::Geometry2D* g2d = multiWidget->mitkWidget3->GetRenderer()->GetCurrentWorldGeometry2D();\n const mitk::PlaneGeometry* pg = dynamic_cast(g2d);\n mitk::PlaneView pv = pg->GetPlaneView();\n pv.point.y=y;\n mitk::PlaneGeometry::Pointer plane = mitk::PlaneGeometry::New(); \n plane->SetPlaneView(pv);\n multiWidget->mitkWidget3->GetRenderer()->SetWorldGeometry(plane);\n multiWidget->updateMitkWidgets();\n \/\/std::cout << \"Slider:\" << y << std::endl;\n}\n\nvoid QmitkSimpleExampleFunctionality::selectSliceWidgetYZ(int x)\n{\n const mitk::Geometry2D* g2d = multiWidget->mitkWidget2->GetRenderer()->GetCurrentWorldGeometry2D();\n const mitk::PlaneGeometry* pg = dynamic_cast(g2d);\n mitk::PlaneView pv = pg->GetPlaneView();\n pv.point.x = x;\n mitk::PlaneGeometry::Pointer plane = mitk::PlaneGeometry::New(); \n plane->SetPlaneView(pv);\n multiWidget->mitkWidget2->GetRenderer()->SetWorldGeometry(plane);\n multiWidget->updateMitkWidgets();\n \/\/std::cout << \"Slider:\" << x << std::endl;\n}\n\nvoid QmitkSimpleExampleFunctionality::selectSliceWidgetFP( int p )\n{\n bool update=false;\n if( opacityprop.IsNotNull() ) \n {\n\t\topacityprop->SetValue(p\/100.0);\n update = true;\n\t}\n if(lookupTableProp.IsNotNull())\n {\n\t\tlookupTableProp->GetLookupTable().ChangeOpacityForAll(p\/100.0);\n update = true;\n\t}\n\n if(update)\n multiWidget->updateMitkWidgets();\n}\n\nvoid QmitkSimpleExampleFunctionality::initWidgets()\n{\n\tint count = 0;\n\tmitk::DataTreeIterator* it=m_DataTreeIterator->clone();\n\twhile (it->hasNext()) {\n\t\tit->next();\n\t\tprintf(\"\\nrequesting boundingbox\\n\"); \n\t\tmitk::DataTreeNode::Pointer node = it->get();\n\t\tmitk::BaseData::Pointer data=node->GetData();\n if((data.IsNotNull()) && (dynamic_cast(node->GetData()) == NULL ))\n\t\t{\n\t\t\t\/\/ get \n\t\t\tif ((data->GetUpdatedGeometry())!=NULL ) \n\t\t\t{\n\t\t\t\tmitk::BoundingBox::ConstPointer bb = data->GetGeometry()->GetBoundingBox();\n\t\t\t\tprintf(\"boundsArrayType\\n\");\n\t\t\t\tconst mitk::BoundingBox::BoundsArrayType bounds = bb->GetBounds();\n\t\t\t\tprintf(\"\\nboundingbox\\n\");\n\n\t\t\t\t\/\/ init slider limits\n\t\t\t\tcontrols->sliderYZ->setMinValue(std::_MIN(bounds[0],controls->sliderYZ->minValue()));\n\t\t\t\tcontrols->sliderYZ->setMaxValue(std::_MAX(bounds[1],controls->sliderYZ->maxValue()));\n\t\t\t\tcontrols->sliderXZ->setMinValue(std::_MIN(bounds[2],controls->sliderXZ->minValue()));\n\t\t\t\tcontrols->sliderXZ->setMaxValue(std::_MAX(bounds[3],controls->sliderXZ->maxValue()));\n\t\t\t\tcontrols->sliderXY->setMinValue(std::_MIN(bounds[4],controls->sliderXY->minValue()));\n\t\t\t\tcontrols->sliderXY->setMaxValue(std::_MAX(bounds[5],controls->sliderXY->maxValue()));\n\t\t\t\tcount++;\n\t\t\t}\n\n lookupTableProp=NULL;\n\t\t}\n\t}\n\tdelete it;\n}\n\n\nvoid QmitkSimpleExampleFunctionality::ExecuteOperation(mitk::Operation* operation)\n{\n bool ok;\/\/as return\n\n mitk::PointOperation* pointoperation=dynamic_cast(operation);\n if(pointoperation!=NULL)\n {\n \/****NAVIGATION inside the volume****\/\n switch (operation->GetOperationType())\n {\n case mitk::OpMOVE:\n {\n mitk::ITKPoint3D point;\n mitk::Point3D seed;\n\n point = pointoperation->GetPoint();\n mitk::itk2vm(point, seed);\n\n const mitk::Geometry2D* g2d;\n const mitk::PlaneGeometry* pg;\n mitk::PlaneView pv;\n mitk::PlaneGeometry::Pointer plane;\n \n int v;\n v=(int)seed.x;\n if(controls->getSliderYZ()->value()!=v)\n {\n g2d = multiWidget->mitkWidget2->GetRenderer()->GetCurrentWorldGeometry2D();\n pg = dynamic_cast(g2d);\n pv = pg->GetPlaneView();\n pv.point.x = v; \n plane = mitk::PlaneGeometry::New(); \n plane->SetPlaneView(pv);\n multiWidget->mitkWidget2->GetRenderer()->SetWorldGeometry(plane);\n controls->getSliderYZ()->blockSignals(true);\n controls->getSliderYZ()->setValue(v);\n controls->getSliderYZ()->blockSignals(false);\n }\n v=(int)seed.y;\n if(controls->getSliderXZ()->value()!=v)\n {\n g2d = multiWidget->mitkWidget3->GetRenderer()->GetCurrentWorldGeometry2D();\n pg = dynamic_cast(g2d);\n pv = pg->GetPlaneView();\n pv.point.y = v;\n plane = mitk::PlaneGeometry::New(); \n plane->SetPlaneView(pv);\n multiWidget->mitkWidget3->GetRenderer()->SetWorldGeometry(plane);\n controls->getSliderXZ()->blockSignals(true);\n controls->getSliderXZ()->setValue(v);\n controls->getSliderXZ()->blockSignals(false);\n }\n\n v=(int)seed.z;\n if(controls->getSliderXY()->value()!=v)\n {\n g2d = multiWidget->mitkWidget1->GetRenderer()->GetCurrentWorldGeometry2D();\n pg = dynamic_cast(g2d);\n pv = pg->GetPlaneView();\n pv.point.z = v;\n plane = mitk::PlaneGeometry::New(); \n plane->SetPlaneView(pv);\n multiWidget->mitkWidget1->GetRenderer()->SetWorldGeometry(plane);\n controls->getSliderXY()->blockSignals(true);\n controls->getSliderXY()->setValue(v);\n controls->getSliderXY()->blockSignals(false);\n }\n multiWidget->updateMitkWidgets();\n ok = true;\n }\n break;\n case mitk::OpNOTHING:\n break;\n default:\n ;\n }\n }\n mitk::DisplayCoordinateOperation* dcOperation=dynamic_cast(operation);\n if( dcOperation != NULL )\n {\n \/****ZOOM & MOVE of the whole volume****\/\n mitk::BaseRenderer* renderer = dcOperation->GetRenderer();\n if( renderer == NULL )\n return;\n switch (operation->GetOperationType())\n {\n case mitk::OpMOVE :\n {\n renderer->GetDisplayGeometry()->MoveBy(dcOperation->GetLastToCurrentDisplayVector()*(-1.0));\n renderer->GetRenderWindow()->Update();\n ok = true;\n }\n break;\n case mitk::OpZOOM :\n {\n float distance = dcOperation->GetLastToCurrentDisplayVector().y;\n distance = (distance > 0 ? 1 : (distance < 0 ? -1 : 0));\n float factor= 1.0 + distance * 0.05;\n renderer->GetDisplayGeometry()->Zoom(factor, dcOperation->GetStartDisplayCoordinate());\n renderer->GetRenderWindow()->Update();\n ok = true;\n }\n break;\n default:\n ;\n }\n }\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: AccessibleSlideSorterObject.cxx,v $\n *\n * $Revision: 1.8 $\n *\n * last change: $Author: ihi $ $Date: 2006-11-14 14:23:53 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sd.hxx\"\n\n#include \"AccessibleSlideSorterObject.hxx\"\n\n#include \"controller\/SlideSorterController.hxx\"\n#include \"controller\/SlsPageSelector.hxx\"\n#include \"controller\/SlsFocusManager.hxx\"\n#include \"model\/SlideSorterModel.hxx\"\n#include \"model\/SlsPageDescriptor.hxx\"\n#include \"view\/SlideSorterView.hxx\"\n\n#ifndef _COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLEROLE_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLESTATETYPE_HPP_\n#include \n#endif\n#ifndef COMPHELPER_ACCESSIBLE_EVENT_NOTIFIER\n#include \n#endif\n#include \n\n#include \"sdpage.hxx\"\n#include \"sdresid.hxx\"\n\n#ifndef _SV_SVAPP_HXX\n#include \n#endif\n\n#include \"glob.hrc\"\n\nusing ::rtl::OUString;\nusing namespace ::com::sun::star;\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::accessibility;\n\n\nnamespace accessibility {\n\n\nAccessibleSlideSorterObject::AccessibleSlideSorterObject(\n const Reference& rxParent,\n ::sd::slidesorter::controller::SlideSorterController& rSlideSorterController,\n sal_uInt16 nPageNumber)\n : AccessibleSlideSorterObjectBase(::sd::MutexOwner::maMutex),\n mxParent(rxParent),\n mnPageNumber(nPageNumber),\n mrSlideSorterController(rSlideSorterController),\n mnClientId(0)\n{\n}\n\n\n\n\nAccessibleSlideSorterObject::~AccessibleSlideSorterObject (void)\n{\n if ( ! IsDisposed())\n dispose();\n}\n\n\n\n\nsal_uInt16 AccessibleSlideSorterObject::GetPageNumber (void) const\n{\n return mnPageNumber;\n}\n\n\n\n\nvoid AccessibleSlideSorterObject::FireAccessibleEvent (\n short nEventId,\n const uno::Any& rOldValue,\n const uno::Any& rNewValue)\n{\n if (mnClientId != 0)\n {\n AccessibleEventObject aEventObject;\n\n aEventObject.Source = Reference(this);\n aEventObject.EventId = nEventId;\n aEventObject.NewValue = rNewValue;\n aEventObject.OldValue = rOldValue;\n\n comphelper::AccessibleEventNotifier::addEvent(mnClientId, aEventObject);\n }\n}\n\n\n\n\nvoid SAL_CALL AccessibleSlideSorterObject::disposing (void)\n{\n const vos::OGuard aSolarGuard (Application::GetSolarMutex());\n\n \/\/ Send a disposing to all listeners.\n if (mnClientId != 0)\n {\n comphelper::AccessibleEventNotifier::revokeClientNotifyDisposing(mnClientId, *this);\n mnClientId = 0;\n }\n}\n\n\n\n\/\/===== XAccessible ===========================================================\n\nReference SAL_CALL\n AccessibleSlideSorterObject::getAccessibleContext (void)\n throw (uno::RuntimeException)\n{\n ThrowIfDisposed();\n return this;\n}\n\n\n\n\/\/===== XAccessibleContext ====================================================\n\nsal_Int32 SAL_CALL AccessibleSlideSorterObject::getAccessibleChildCount (void)\n throw (uno::RuntimeException)\n{\n ThrowIfDisposed();\n return 0;\n}\n\n\n\n\nReference SAL_CALL AccessibleSlideSorterObject::getAccessibleChild (sal_Int32 i)\n throw (lang::IndexOutOfBoundsException, RuntimeException)\n{\n ThrowIfDisposed();\n throw lang::IndexOutOfBoundsException();\n return Reference();\n}\n\n\n\n\nReference SAL_CALL AccessibleSlideSorterObject::getAccessibleParent (void)\n throw (uno::RuntimeException)\n{\n ThrowIfDisposed();\n return mxParent;\n}\n\n\n\n\nsal_Int32 SAL_CALL AccessibleSlideSorterObject::getAccessibleIndexInParent()\n throw (uno::RuntimeException)\n{\n ThrowIfDisposed();\n const vos::OGuard aSolarGuard (Application::GetSolarMutex());\n sal_Int32 nIndexInParent(-1);\n\n if (mxParent.is())\n {\n Reference xParentContext (mxParent->getAccessibleContext());\n if (xParentContext.is())\n {\n sal_Int32 nChildCount (xParentContext->getAccessibleChildCount());\n for (sal_Int32 i=0; igetAccessibleChild(i).get()\n == static_cast(this))\n {\n nIndexInParent = i;\n break;\n }\n }\n }\n\n return nIndexInParent;\n}\n\n\n\n\nsal_Int16 SAL_CALL AccessibleSlideSorterObject::getAccessibleRole (void)\n throw (uno::RuntimeException)\n{\n ThrowIfDisposed();\n static sal_Int16 nRole = AccessibleRole::LIST_ITEM;\n return nRole;\n}\n\n\n\n\n::rtl::OUString SAL_CALL AccessibleSlideSorterObject::getAccessibleDescription (void)\n throw (uno::RuntimeException)\n{\n ThrowIfDisposed();\n return String(SdResId(STR_PAGE));\n}\n\n\n\n\n::rtl::OUString SAL_CALL AccessibleSlideSorterObject::getAccessibleName (void)\n throw (uno::RuntimeException)\n{\n ThrowIfDisposed();\n const vos::OGuard aSolarGuard (Application::GetSolarMutex());\n\n SdPage* pPage = GetPage();\n if (pPage != NULL)\n return pPage->GetName();\n else\n return String();\n}\n\n\n\n\nReference SAL_CALL\n AccessibleSlideSorterObject::getAccessibleRelationSet (void)\n throw (uno::RuntimeException)\n{\n ThrowIfDisposed();\n return Reference();\n}\n\n\n\n\nReference SAL_CALL\n AccessibleSlideSorterObject::getAccessibleStateSet (void)\n throw (uno::RuntimeException)\n{\n ThrowIfDisposed();\n const vos::OGuard aSolarGuard (Application::GetSolarMutex());\n ::utl::AccessibleStateSetHelper* pStateSet = new ::utl::AccessibleStateSetHelper();\n\n if (mxParent.is())\n {\n \/\/ SELECTABLE\n pStateSet->AddState(AccessibleStateType::SELECTABLE);\n\n \/\/ SELECTED\n if (mrSlideSorterController.GetPageSelector().IsPageSelected(mnPageNumber))\n pStateSet->AddState(AccessibleStateType::SELECTED);\n\n \/\/ FOCUSABLE\n pStateSet->AddState(AccessibleStateType::FOCUSABLE);\n\n \/\/ FOCUSED\n if (mrSlideSorterController.GetFocusManager().GetFocusedPageIndex() == mnPageNumber)\n if (mrSlideSorterController.GetFocusManager().IsFocusShowing())\n pStateSet->AddState(AccessibleStateType::FOCUSED);\n\n pStateSet->AddState(AccessibleStateType::ENABLED);\n pStateSet->AddState(AccessibleStateType::VISIBLE);\n pStateSet->AddState(AccessibleStateType::SHOWING);\n pStateSet->AddState(AccessibleStateType::ACTIVE);\n }\n\n return pStateSet;\n}\n\n\n\n\nlang::Locale SAL_CALL AccessibleSlideSorterObject::getLocale (void)\n throw (IllegalAccessibleComponentStateException,\n RuntimeException)\n{\n ThrowIfDisposed();\n \/\/ Delegate request to parent.\n if (mxParent.is())\n {\n Reference xParentContext (mxParent->getAccessibleContext());\n if (xParentContext.is())\n return xParentContext->getLocale ();\n }\n\n \/\/ No locale and no parent. Therefore throw exception to indicate this\n \/\/ cluelessness.\n throw IllegalAccessibleComponentStateException();\n}\n\n\n\n\n\n\/\/===== XAccessibleEventBroadcaster ===========================================\n\nvoid SAL_CALL AccessibleSlideSorterObject::addEventListener(\n const Reference& rxListener)\n throw (RuntimeException)\n{\n if (rxListener.is())\n {\n const osl::MutexGuard aGuard(maMutex);\n\n if (IsDisposed())\n {\n uno::Reference x ((lang::XComponent *)this, uno::UNO_QUERY);\n rxListener->disposing (lang::EventObject (x));\n }\n else\n {\n if (mnClientId == 0)\n mnClientId = comphelper::AccessibleEventNotifier::registerClient();\n comphelper::AccessibleEventNotifier::addEventListener(mnClientId, rxListener);\n }\n }\n}\n\n\n\n\nvoid SAL_CALL AccessibleSlideSorterObject::removeEventListener(\n const Reference& rxListener)\n throw (uno::RuntimeException)\n{\n ThrowIfDisposed();\n if (rxListener.is())\n {\n const osl::MutexGuard aGuard(maMutex);\n\n sal_Int32 nListenerCount = comphelper::AccessibleEventNotifier::removeEventListener( mnClientId, rxListener );\n if ( !nListenerCount )\n {\n \/\/ no listeners anymore\n \/\/ -> revoke ourself. This may lead to the notifier thread dying (if we were the last client),\n \/\/ and at least to us not firing any events anymore, in case somebody calls\n \/\/ NotifyAccessibleEvent, again\n comphelper::AccessibleEventNotifier::revokeClient( mnClientId );\n mnClientId = 0;\n }\n }\n}\n\n\n\n\n\/\/===== XAccessibleComponent ==================================================\n\nsal_Bool SAL_CALL AccessibleSlideSorterObject::containsPoint(const awt::Point& aPoint)\n throw (uno::RuntimeException)\n{\n ThrowIfDisposed();\n const awt::Size aSize (getSize());\n return (aPoint.X >= 0)\n && (aPoint.X < aSize.Width)\n && (aPoint.Y >= 0)\n && (aPoint.Y < aSize.Height);\n}\n\n\n\n\nReference SAL_CALL\n AccessibleSlideSorterObject::getAccessibleAtPoint(const awt::Point& aPoint)\n throw (uno::RuntimeException)\n{\n return NULL;\n}\n\n\n\n\nawt::Rectangle SAL_CALL AccessibleSlideSorterObject::getBounds (void)\n throw (RuntimeException)\n{\n const vos::OGuard aSolarGuard( Application::GetSolarMutex() );\n\n Rectangle aBBox (mrSlideSorterController.GetView().GetPageBoundingBox (\n mnPageNumber,\n ::sd::slidesorter::view::SlideSorterView::CS_SCREEN,\n ::sd::slidesorter::view::SlideSorterView::BBT_INFO));\n\n if (mxParent.is())\n {\n Reference xParentComponent(mxParent->getAccessibleContext(), UNO_QUERY);\n if (xParentComponent.is())\n {\n awt::Rectangle aParentBBox (xParentComponent->getBounds());\n aBBox.Intersection(Rectangle(\n aParentBBox.X,\n aParentBBox.Y,\n aParentBBox.Width,\n aParentBBox.Height));\n }\n }\n\n return awt::Rectangle(\n aBBox.Left(),\n aBBox.Top(),\n aBBox.GetWidth(),\n aBBox.GetHeight());\n}\n\n\n\n\nawt::Point SAL_CALL AccessibleSlideSorterObject::getLocation ()\n throw (RuntimeException)\n{\n const awt::Rectangle aBBox (getBounds());\n return awt::Point(aBBox.X, aBBox.Y);\n}\n\n\n\n\nawt::Point SAL_CALL AccessibleSlideSorterObject::getLocationOnScreen (void)\n throw (RuntimeException)\n{\n const vos::OGuard aSolarGuard( Application::GetSolarMutex() );\n\n awt::Point aLocation (getLocation());\n\n if (mxParent.is())\n {\n Reference xParentComponent(mxParent->getAccessibleContext(),UNO_QUERY);\n if (xParentComponent.is())\n {\n const awt::Point aParentLocationOnScreen(xParentComponent->getLocationOnScreen());\n aLocation.X += aParentLocationOnScreen.X;\n aLocation.Y += aParentLocationOnScreen.Y;\n }\n }\n\n return aLocation;\n}\n\n\n\n\nawt::Size SAL_CALL AccessibleSlideSorterObject::getSize (void)\n throw (RuntimeException)\n{\n const awt::Rectangle aBBox (getBounds());\n return awt::Size(aBBox.Width,aBBox.Height);\n}\n\n\n\n\nvoid SAL_CALL AccessibleSlideSorterObject::grabFocus (void)\n throw (RuntimeException)\n{\n \/\/ nothing to do\n}\n\n\n\n\nsal_Int32 SAL_CALL AccessibleSlideSorterObject::getForeground (void)\n throw (::com::sun::star::uno::RuntimeException)\n{\n svtools::ColorConfig aColorConfig;\n UINT32 nColor = aColorConfig.GetColorValue( svtools::FONTCOLOR ).nColor;\n return static_cast(nColor);\n}\n\n\n\n\nsal_Int32 SAL_CALL AccessibleSlideSorterObject::getBackground (void)\n throw (::com::sun::star::uno::RuntimeException)\n{\n UINT32 nColor = Application::GetSettings().GetStyleSettings().GetWindowColor().GetColor();\n return static_cast(nColor);\n}\n\n\n\n\n\n\/\/===== XServiceInfo ========================================================\n\n::rtl::OUString SAL_CALL\n AccessibleSlideSorterObject::getImplementationName (void)\n throw (::com::sun::star::uno::RuntimeException)\n{\n return OUString(RTL_CONSTASCII_USTRINGPARAM(\"AccessibleSlideSorterObject\"));\n}\n\n\n\n\nsal_Bool SAL_CALL\n AccessibleSlideSorterObject::supportsService (const OUString& sServiceName)\n throw (::com::sun::star::uno::RuntimeException)\n{\n \/\/ Iterate over all supported service names and return true if on of them\n \/\/ matches the given name.\n uno::Sequence< ::rtl::OUString> aSupportedServices (\n getSupportedServiceNames ());\n for (int i=0; i SAL_CALL\n AccessibleSlideSorterObject::getSupportedServiceNames (void)\n throw (::com::sun::star::uno::RuntimeException)\n{\n static const OUString sServiceNames[2] = {\n OUString(RTL_CONSTASCII_USTRINGPARAM(\n \"com.sun.star.accessibility.Accessible\")),\n OUString(RTL_CONSTASCII_USTRINGPARAM(\n \"com.sun.star.accessibility.AccessibleContext\"))\n };\n return uno::Sequence (sServiceNames, 2);\n}\n\n\n\n\nvoid AccessibleSlideSorterObject::ThrowIfDisposed (void)\n throw (lang::DisposedException)\n{\n if (rBHelper.bDisposed || rBHelper.bInDispose)\n {\n OSL_TRACE (\"Calling disposed object. Throwing exception:\");\n throw lang::DisposedException (\n OUString(RTL_CONSTASCII_USTRINGPARAM(\"object has been already disposed\")),\n static_cast(this));\n }\n}\n\n\n\nsal_Bool AccessibleSlideSorterObject::IsDisposed (void)\n{\n return (rBHelper.bDisposed || rBHelper.bInDispose);\n}\n\n\n\n\nSdPage* AccessibleSlideSorterObject::GetPage (void) const\n{\n ::sd::slidesorter::model::SharedPageDescriptor pDescriptor(\n mrSlideSorterController.GetModel().GetPageDescriptor(mnPageNumber));\n if (pDescriptor.get() != NULL)\n return pDescriptor->GetPage();\n else\n return NULL;\n}\n\n\n} \/\/ end of namespace ::accessibility\nINTEGRATION: CWS sdwarningsbegone (1.7.36); FILE MERGED 2006\/11\/22 15:00:03 cl 1.7.36.2: RESYNC: (1.7-1.8); FILE MERGED 2006\/11\/22 12:41:40 cl 1.7.36.1: #i69285# warning free code changes for unxlngi6.pro\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: AccessibleSlideSorterObject.cxx,v $\n *\n * $Revision: 1.9 $\n *\n * last change: $Author: kz $ $Date: 2006-12-12 16:49:05 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sd.hxx\"\n\n#include \"AccessibleSlideSorterObject.hxx\"\n\n#include \"controller\/SlideSorterController.hxx\"\n#include \"controller\/SlsPageSelector.hxx\"\n#include \"controller\/SlsFocusManager.hxx\"\n#include \"model\/SlideSorterModel.hxx\"\n#include \"model\/SlsPageDescriptor.hxx\"\n#include \"view\/SlideSorterView.hxx\"\n\n#ifndef _COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLEROLE_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLESTATETYPE_HPP_\n#include \n#endif\n#ifndef COMPHELPER_ACCESSIBLE_EVENT_NOTIFIER\n#include \n#endif\n#include \n\n#include \"sdpage.hxx\"\n#include \"sdresid.hxx\"\n\n#ifndef _SV_SVAPP_HXX\n#include \n#endif\n\n#include \"glob.hrc\"\n\nusing ::rtl::OUString;\nusing namespace ::com::sun::star;\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::accessibility;\n\n\nnamespace accessibility {\n\n\nAccessibleSlideSorterObject::AccessibleSlideSorterObject(\n const Reference& rxParent,\n ::sd::slidesorter::controller::SlideSorterController& rSlideSorterController,\n sal_uInt16 nPageNumber)\n : AccessibleSlideSorterObjectBase(::sd::MutexOwner::maMutex),\n mxParent(rxParent),\n mnPageNumber(nPageNumber),\n mrSlideSorterController(rSlideSorterController),\n mnClientId(0)\n{\n}\n\n\n\n\nAccessibleSlideSorterObject::~AccessibleSlideSorterObject (void)\n{\n if ( ! IsDisposed())\n dispose();\n}\n\n\n\n\nsal_uInt16 AccessibleSlideSorterObject::GetPageNumber (void) const\n{\n return mnPageNumber;\n}\n\n\n\n\nvoid AccessibleSlideSorterObject::FireAccessibleEvent (\n short nEventId,\n const uno::Any& rOldValue,\n const uno::Any& rNewValue)\n{\n if (mnClientId != 0)\n {\n AccessibleEventObject aEventObject;\n\n aEventObject.Source = Reference(this);\n aEventObject.EventId = nEventId;\n aEventObject.NewValue = rNewValue;\n aEventObject.OldValue = rOldValue;\n\n comphelper::AccessibleEventNotifier::addEvent(mnClientId, aEventObject);\n }\n}\n\n\n\n\nvoid SAL_CALL AccessibleSlideSorterObject::disposing (void)\n{\n const vos::OGuard aSolarGuard (Application::GetSolarMutex());\n\n \/\/ Send a disposing to all listeners.\n if (mnClientId != 0)\n {\n comphelper::AccessibleEventNotifier::revokeClientNotifyDisposing(mnClientId, *this);\n mnClientId = 0;\n }\n}\n\n\n\n\/\/===== XAccessible ===========================================================\n\nReference SAL_CALL\n AccessibleSlideSorterObject::getAccessibleContext (void)\n throw (uno::RuntimeException)\n{\n ThrowIfDisposed();\n return this;\n}\n\n\n\n\/\/===== XAccessibleContext ====================================================\n\nsal_Int32 SAL_CALL AccessibleSlideSorterObject::getAccessibleChildCount (void)\n throw (uno::RuntimeException)\n{\n ThrowIfDisposed();\n return 0;\n}\n\n\n\n\nReference SAL_CALL AccessibleSlideSorterObject::getAccessibleChild (sal_Int32 )\n throw (lang::IndexOutOfBoundsException, RuntimeException)\n{\n ThrowIfDisposed();\n throw lang::IndexOutOfBoundsException();\n}\n\n\n\n\nReference SAL_CALL AccessibleSlideSorterObject::getAccessibleParent (void)\n throw (uno::RuntimeException)\n{\n ThrowIfDisposed();\n return mxParent;\n}\n\n\n\n\nsal_Int32 SAL_CALL AccessibleSlideSorterObject::getAccessibleIndexInParent()\n throw (uno::RuntimeException)\n{\n ThrowIfDisposed();\n const vos::OGuard aSolarGuard (Application::GetSolarMutex());\n sal_Int32 nIndexInParent(-1);\n\n if (mxParent.is())\n {\n Reference xParentContext (mxParent->getAccessibleContext());\n if (xParentContext.is())\n {\n sal_Int32 nChildCount (xParentContext->getAccessibleChildCount());\n for (sal_Int32 i=0; igetAccessibleChild(i).get()\n == static_cast(this))\n {\n nIndexInParent = i;\n break;\n }\n }\n }\n\n return nIndexInParent;\n}\n\n\n\n\nsal_Int16 SAL_CALL AccessibleSlideSorterObject::getAccessibleRole (void)\n throw (uno::RuntimeException)\n{\n ThrowIfDisposed();\n static sal_Int16 nRole = AccessibleRole::LIST_ITEM;\n return nRole;\n}\n\n\n\n\n::rtl::OUString SAL_CALL AccessibleSlideSorterObject::getAccessibleDescription (void)\n throw (uno::RuntimeException)\n{\n ThrowIfDisposed();\n return String(SdResId(STR_PAGE));\n}\n\n\n\n\n::rtl::OUString SAL_CALL AccessibleSlideSorterObject::getAccessibleName (void)\n throw (uno::RuntimeException)\n{\n ThrowIfDisposed();\n const vos::OGuard aSolarGuard (Application::GetSolarMutex());\n\n SdPage* pPage = GetPage();\n if (pPage != NULL)\n return pPage->GetName();\n else\n return String();\n}\n\n\n\n\nReference SAL_CALL\n AccessibleSlideSorterObject::getAccessibleRelationSet (void)\n throw (uno::RuntimeException)\n{\n ThrowIfDisposed();\n return Reference();\n}\n\n\n\n\nReference SAL_CALL\n AccessibleSlideSorterObject::getAccessibleStateSet (void)\n throw (uno::RuntimeException)\n{\n ThrowIfDisposed();\n const vos::OGuard aSolarGuard (Application::GetSolarMutex());\n ::utl::AccessibleStateSetHelper* pStateSet = new ::utl::AccessibleStateSetHelper();\n\n if (mxParent.is())\n {\n \/\/ SELECTABLE\n pStateSet->AddState(AccessibleStateType::SELECTABLE);\n\n \/\/ SELECTED\n if (mrSlideSorterController.GetPageSelector().IsPageSelected(mnPageNumber))\n pStateSet->AddState(AccessibleStateType::SELECTED);\n\n \/\/ FOCUSABLE\n pStateSet->AddState(AccessibleStateType::FOCUSABLE);\n\n \/\/ FOCUSED\n if (mrSlideSorterController.GetFocusManager().GetFocusedPageIndex() == mnPageNumber)\n if (mrSlideSorterController.GetFocusManager().IsFocusShowing())\n pStateSet->AddState(AccessibleStateType::FOCUSED);\n\n pStateSet->AddState(AccessibleStateType::ENABLED);\n pStateSet->AddState(AccessibleStateType::VISIBLE);\n pStateSet->AddState(AccessibleStateType::SHOWING);\n pStateSet->AddState(AccessibleStateType::ACTIVE);\n }\n\n return pStateSet;\n}\n\n\n\n\nlang::Locale SAL_CALL AccessibleSlideSorterObject::getLocale (void)\n throw (IllegalAccessibleComponentStateException,\n RuntimeException)\n{\n ThrowIfDisposed();\n \/\/ Delegate request to parent.\n if (mxParent.is())\n {\n Reference xParentContext (mxParent->getAccessibleContext());\n if (xParentContext.is())\n return xParentContext->getLocale ();\n }\n\n \/\/ No locale and no parent. Therefore throw exception to indicate this\n \/\/ cluelessness.\n throw IllegalAccessibleComponentStateException();\n}\n\n\n\n\n\n\/\/===== XAccessibleEventBroadcaster ===========================================\n\nvoid SAL_CALL AccessibleSlideSorterObject::addEventListener(\n const Reference& rxListener)\n throw (RuntimeException)\n{\n if (rxListener.is())\n {\n const osl::MutexGuard aGuard(maMutex);\n\n if (IsDisposed())\n {\n uno::Reference x ((lang::XComponent *)this, uno::UNO_QUERY);\n rxListener->disposing (lang::EventObject (x));\n }\n else\n {\n if (mnClientId == 0)\n mnClientId = comphelper::AccessibleEventNotifier::registerClient();\n comphelper::AccessibleEventNotifier::addEventListener(mnClientId, rxListener);\n }\n }\n}\n\n\n\n\nvoid SAL_CALL AccessibleSlideSorterObject::removeEventListener(\n const Reference& rxListener)\n throw (uno::RuntimeException)\n{\n ThrowIfDisposed();\n if (rxListener.is())\n {\n const osl::MutexGuard aGuard(maMutex);\n\n sal_Int32 nListenerCount = comphelper::AccessibleEventNotifier::removeEventListener( mnClientId, rxListener );\n if ( !nListenerCount )\n {\n \/\/ no listeners anymore\n \/\/ -> revoke ourself. This may lead to the notifier thread dying (if we were the last client),\n \/\/ and at least to us not firing any events anymore, in case somebody calls\n \/\/ NotifyAccessibleEvent, again\n comphelper::AccessibleEventNotifier::revokeClient( mnClientId );\n mnClientId = 0;\n }\n }\n}\n\n\n\n\n\/\/===== XAccessibleComponent ==================================================\n\nsal_Bool SAL_CALL AccessibleSlideSorterObject::containsPoint(const awt::Point& aPoint)\n throw (uno::RuntimeException)\n{\n ThrowIfDisposed();\n const awt::Size aSize (getSize());\n return (aPoint.X >= 0)\n && (aPoint.X < aSize.Width)\n && (aPoint.Y >= 0)\n && (aPoint.Y < aSize.Height);\n}\n\n\n\n\nReference SAL_CALL\n AccessibleSlideSorterObject::getAccessibleAtPoint(const awt::Point& )\n throw (uno::RuntimeException)\n{\n return NULL;\n}\n\n\n\n\nawt::Rectangle SAL_CALL AccessibleSlideSorterObject::getBounds (void)\n throw (RuntimeException)\n{\n const vos::OGuard aSolarGuard( Application::GetSolarMutex() );\n\n Rectangle aBBox (mrSlideSorterController.GetView().GetPageBoundingBox (\n mnPageNumber,\n ::sd::slidesorter::view::SlideSorterView::CS_SCREEN,\n ::sd::slidesorter::view::SlideSorterView::BBT_INFO));\n\n if (mxParent.is())\n {\n Reference xParentComponent(mxParent->getAccessibleContext(), UNO_QUERY);\n if (xParentComponent.is())\n {\n awt::Rectangle aParentBBox (xParentComponent->getBounds());\n aBBox.Intersection(Rectangle(\n aParentBBox.X,\n aParentBBox.Y,\n aParentBBox.Width,\n aParentBBox.Height));\n }\n }\n\n return awt::Rectangle(\n aBBox.Left(),\n aBBox.Top(),\n aBBox.GetWidth(),\n aBBox.GetHeight());\n}\n\n\n\n\nawt::Point SAL_CALL AccessibleSlideSorterObject::getLocation ()\n throw (RuntimeException)\n{\n const awt::Rectangle aBBox (getBounds());\n return awt::Point(aBBox.X, aBBox.Y);\n}\n\n\n\n\nawt::Point SAL_CALL AccessibleSlideSorterObject::getLocationOnScreen (void)\n throw (RuntimeException)\n{\n const vos::OGuard aSolarGuard( Application::GetSolarMutex() );\n\n awt::Point aLocation (getLocation());\n\n if (mxParent.is())\n {\n Reference xParentComponent(mxParent->getAccessibleContext(),UNO_QUERY);\n if (xParentComponent.is())\n {\n const awt::Point aParentLocationOnScreen(xParentComponent->getLocationOnScreen());\n aLocation.X += aParentLocationOnScreen.X;\n aLocation.Y += aParentLocationOnScreen.Y;\n }\n }\n\n return aLocation;\n}\n\n\n\n\nawt::Size SAL_CALL AccessibleSlideSorterObject::getSize (void)\n throw (RuntimeException)\n{\n const awt::Rectangle aBBox (getBounds());\n return awt::Size(aBBox.Width,aBBox.Height);\n}\n\n\n\n\nvoid SAL_CALL AccessibleSlideSorterObject::grabFocus (void)\n throw (RuntimeException)\n{\n \/\/ nothing to do\n}\n\n\n\n\nsal_Int32 SAL_CALL AccessibleSlideSorterObject::getForeground (void)\n throw (::com::sun::star::uno::RuntimeException)\n{\n svtools::ColorConfig aColorConfig;\n UINT32 nColor = aColorConfig.GetColorValue( svtools::FONTCOLOR ).nColor;\n return static_cast(nColor);\n}\n\n\n\n\nsal_Int32 SAL_CALL AccessibleSlideSorterObject::getBackground (void)\n throw (::com::sun::star::uno::RuntimeException)\n{\n UINT32 nColor = Application::GetSettings().GetStyleSettings().GetWindowColor().GetColor();\n return static_cast(nColor);\n}\n\n\n\n\n\n\/\/===== XServiceInfo ========================================================\n\n::rtl::OUString SAL_CALL\n AccessibleSlideSorterObject::getImplementationName (void)\n throw (::com::sun::star::uno::RuntimeException)\n{\n return OUString(RTL_CONSTASCII_USTRINGPARAM(\"AccessibleSlideSorterObject\"));\n}\n\n\n\n\nsal_Bool SAL_CALL\n AccessibleSlideSorterObject::supportsService (const OUString& sServiceName)\n throw (::com::sun::star::uno::RuntimeException)\n{\n \/\/ Iterate over all supported service names and return true if on of them\n \/\/ matches the given name.\n uno::Sequence< ::rtl::OUString> aSupportedServices (\n getSupportedServiceNames ());\n for (int i=0; i SAL_CALL\n AccessibleSlideSorterObject::getSupportedServiceNames (void)\n throw (::com::sun::star::uno::RuntimeException)\n{\n static const OUString sServiceNames[2] = {\n OUString(RTL_CONSTASCII_USTRINGPARAM(\n \"com.sun.star.accessibility.Accessible\")),\n OUString(RTL_CONSTASCII_USTRINGPARAM(\n \"com.sun.star.accessibility.AccessibleContext\"))\n };\n return uno::Sequence (sServiceNames, 2);\n}\n\n\n\n\nvoid AccessibleSlideSorterObject::ThrowIfDisposed (void)\n throw (lang::DisposedException)\n{\n if (rBHelper.bDisposed || rBHelper.bInDispose)\n {\n OSL_TRACE (\"Calling disposed object. Throwing exception:\");\n throw lang::DisposedException (\n OUString(RTL_CONSTASCII_USTRINGPARAM(\"object has been already disposed\")),\n static_cast(this));\n }\n}\n\n\n\nsal_Bool AccessibleSlideSorterObject::IsDisposed (void)\n{\n return (rBHelper.bDisposed || rBHelper.bInDispose);\n}\n\n\n\n\nSdPage* AccessibleSlideSorterObject::GetPage (void) const\n{\n ::sd::slidesorter::model::SharedPageDescriptor pDescriptor(\n mrSlideSorterController.GetModel().GetPageDescriptor(mnPageNumber));\n if (pDescriptor.get() != NULL)\n return pDescriptor->GetPage();\n else\n return NULL;\n}\n\n\n} \/\/ end of namespace ::accessibility\n<|endoftext|>"} {"text":"#include \n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\nnamespace osgUtil\n{\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ MISC MATH FUNCTIONS\n\n\n\/\/ Compute the circumcircle of a triangle (only x and y coordinates are used),\n\/\/ return (Cx, Cy, r^2)\n\ninline osg::Vec3 compute_circumcircle(\n const osg::Vec3 &a, \n const osg::Vec3 &b, \n const osg::Vec3 &c)\n{\n float D = \n (a.x() - c.x()) * (b.y() - c.y()) - \n (b.x() - c.x()) * (a.y() - c.y());\n\n float cx = \n (((a.x() - c.x()) * (a.x() + c.x()) + \n (a.y() - c.y()) * (a.y() + c.y())) \/ 2 * (b.y() - c.y()) -\n ((b.x() - c.x()) * (b.x() + c.x()) +\n (b.y() - c.y()) * (b.y() + c.y())) \/ 2 * (a.y() - c.y())) \/ D;\n\n float cy = \n (((b.x() - c.x()) * (b.x() + c.x()) + \n (b.y() - c.y()) * (b.y() + c.y())) \/ 2 * (a.x() - c.x()) -\n ((a.x() - c.x()) * (a.x() + c.x()) +\n (a.y() - c.y()) * (a.y() + c.y())) \/ 2 * (b.x() - c.x())) \/ D;\n\n float r2 = (c.x() - cx) * (c.x() - cx) + (c.y() - cy) * (c.y() - cy);\n\n return osg::Vec3(cx, cy, r2);\n}\n\n\n\/\/ Test whether a point (only the x and y coordinates are used) lies inside\n\/\/ a circle; the circle is passed as a vector: (Cx, Cy, r^2).\n\ninline bool point_in_circle(const osg::Vec3 &point, const osg::Vec3 &circle)\n{\n float r2 = \n (point.x() - circle.x()) * (point.x() - circle.x()) + \n (point.y() - circle.y()) * (point.y() - circle.y());\n return r2 <= circle.z();\n}\n\n\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n\/\/ data type for vertex indices\ntypedef GLuint Vertex_index;\n\n\n\/\/ CLASS: Edge\n\/\/ This class describes an edge of a triangle (it stores vertex indices to the two\n\/\/ endpoints).\n\nclass Edge {\npublic:\n\n \/\/ Comparison object (for sorting)\n struct Less {\n inline bool operator()(const Edge &e1, const Edge &e2) const\n {\n if (e1.ibs() < e2.ibs()) return true;\n if (e1.ibs() > e2.ibs()) return false;\n if (e1.ies() < e2.ies()) return true;\n return false;\n }\n };\n\n Edge() {}\n Edge(Vertex_index ib, Vertex_index ie) : ib_(ib), ie_(ie), ibs_(osg::minimum(ib, ie)), ies_(osg::maximum(ib, ie)), duplicate_(false) {}\n\n \/\/ first endpoint\n inline Vertex_index ib() const { return ib_; }\n\n \/\/ second endpoint\n inline Vertex_index ie() const { return ie_; }\n\n \/\/ first sorted endpoint\n inline Vertex_index ibs() const { return ibs_; }\n\n \/\/ second sorted endpoint\n inline Vertex_index ies() const { return ies_; }\n\n \/\/ get the \"duplicate\" flag\n inline bool get_duplicate() const { return duplicate_; }\n\n \/\/ set the \"duplicate\" flag\n inline void set_duplicate(bool v) { duplicate_ = v; }\n\nprivate:\n Vertex_index ib_, ie_;\n Vertex_index ibs_, ies_;\n bool duplicate_;\n};\n\n\n\/\/ CLASS: Triangle\n\nclass Triangle {\npublic:\n Triangle(Vertex_index a, Vertex_index b, Vertex_index c, osg::Vec3Array *points)\n : a_(a), \n b_(b), \n c_(c), \n cc_(compute_circumcircle((*points)[a_], (*points)[b_], (*points)[c_]))\n {\n edge_[0] = Edge(a_, b_);\n edge_[1] = Edge(b_, c_);\n edge_[2] = Edge(c_, a_);\n }\n\n inline Vertex_index a() const { return a_; }\n inline Vertex_index b() const { return b_; }\n inline Vertex_index c() const { return c_; }\n\n inline const Edge &get_edge(int idx) const { return edge_[idx]; }\n inline const osg::Vec3 &get_circumcircle() const { return cc_; }\n\n inline osg::Vec3 compute_normal(osg::Vec3Array *points) const\n {\n osg::Vec3 N = ((*points)[b_] - (*points)[a_]) ^ ((*points)[c_] - (*points)[a_]);\n return N \/ N.length();\n }\n\n\nprivate:\n Vertex_index a_;\n Vertex_index b_;\n Vertex_index c_;\n osg::Vec3 cc_; \n Edge edge_[3];\n};\n\n\n\/\/ comparison function for sorting sample points by the X coordinate\nbool Sample_point_compare(const osg::Vec3 &p1, const osg::Vec3 &p2)\n{\n return p1.x() < p2.x();\n}\n\n\n\/\/ container types\ntypedef std::set Edge_set;\ntypedef std::list Triangle_list;\n\n\n\nDelaunayTriangulator::DelaunayTriangulator():\n osg::Referenced()\n{\n}\n\nDelaunayTriangulator::DelaunayTriangulator(osg::Vec3Array *points, osg::Vec3Array *normals):\n osg::Referenced(),\n points_(points),\n normals_(normals)\n{\n}\n\nDelaunayTriangulator::DelaunayTriangulator(const DelaunayTriangulator ©, const osg::CopyOp ©op):\n osg::Referenced(copy),\n points_(static_cast(copyop(copy.points_.get()))),\n normals_(static_cast(copyop(copy.normals_.get()))),\n prim_tris_(static_cast(copyop(copy.prim_tris_.get())))\n{\n}\n\nDelaunayTriangulator::~DelaunayTriangulator()\n{\n}\n\nbool DelaunayTriangulator::triangulate()\n{\n \/\/ check validity of input array\n if (!points_.valid()) {\n osg::notify(osg::WARN) << \"Warning: DelaunayTriangulator::triangulate(): invalid sample point array\" << std::endl;\n return false;\n }\n\n osg::Vec3Array *points = points_.get();\n\n if (points->size() < 1) {\n osg::notify(osg::WARN) << \"Warning: DelaunayTriangulator::triangulate(): too few sample points\" << std::endl;\n return false;\n }\n\n \/\/ initialize storage structures\n Triangle_list triangles;\n Triangle_list discarded_tris; \n\n \/\/ pre-sort sample points\n osg::notify(osg::INFO) << \"DelaunayTriangulator: pre-sorting sample points\\n\";\n std::sort(points->begin(), points->end(), Sample_point_compare); \n\n \/\/ set the last valid index for the point list\n GLuint last_valid_index = points->size() - 1; \n\n \/\/ find the minimum and maximum x values in the point list\n float minx = (*points)[0].x();\n float maxx = (*points)[last_valid_index].x();\n\n\n \/\/ find the minimum and maximum x values in the point list \n float miny = (*points)[0].y();\n float maxy = miny;\n \n osg::notify(osg::INFO) << \"DelaunayTriangulator: finding minimum and maximum Y values\\n\";\n osg::Vec3Array::const_iterator mmi;\n for (mmi=points->begin(); mmi!=points->end(); ++mmi) {\n if (mmi->y() < miny) miny = mmi->y();\n if (mmi->y() > maxy) maxy = mmi->y();\n }\n \n \/\/ add supertriangle vertices to the point list\n points->push_back(osg::Vec3(minx - (maxx - minx), miny, 0));\n points->push_back(osg::Vec3(maxx, miny, 0));\n points->push_back(osg::Vec3(maxx, maxy + (maxy - miny), 0));\n\n \/\/ add supertriangle to triangle list\n triangles.push_back(Triangle(last_valid_index+1, last_valid_index+2, last_valid_index+3, points));\n\n \n \/\/ begin triangulation \n GLuint pidx = 0;\n osg::Vec3Array::const_iterator i; \n \n osg::notify(osg::INFO) << \"DelaunayTriangulator: triangulating vertex grid (\" << (points->size()-3) <<\" points)\\n\"; \n\n for (i=points->begin(); i!=points->end(); ++i, ++pidx) {\n\n \/\/ don't process supertriangle vertices\n if (pidx > last_valid_index) break;\n\n Edge_set edges;\n\n \/\/ iterate through triangles\n Triangle_list::iterator j, next_j;\n for (j=triangles.begin(); j!=triangles.end(); j = next_j) {\n\n next_j = j;\n ++next_j;\n\n \/\/ compute the circumcircle\n osg::Vec3 cc = j->get_circumcircle();\n\n \/\/ OPTIMIZATION: since points are pre-sorted by the X component,\n \/\/ check whether we can discard this triangle for future operations\n float xdist = i->x() - cc.x();\n if ((xdist * xdist) > cc.z() && i->x() > cc.x()) {\n discarded_tris.push_back(*j);\n triangles.erase(j);\n } else {\n\n \/\/ if the point lies in the triangle's circumcircle then add\n \/\/ its edges to the edge list and remove the triangle\n if (point_in_circle(*i, cc))\n {\n for (int ei=0; ei<3; ++ei)\n {\n std::pair result = edges.insert(j->get_edge(ei));\n if (!result.second)\n {\n \/\/ cast away constness of a set element, which is\n \/\/ safe in this case since the set_duplicate is\n \/\/ not used as part of the Less operator.\n Edge& edge = const_cast(*(result.first));\n edge.set_duplicate(true);\n }\n } \n triangles.erase(j);\n }\n }\n }\n\n \/\/ remove duplicate edges and add new triangles\n Edge_set::iterator ci;\n for (ci=edges.begin(); ci!=edges.end(); ++ci) {\n if (!ci->get_duplicate()) {\n triangles.push_back(Triangle(pidx, ci->ib(), ci->ie(), points));\n }\n }\n }\n\n osg::notify(osg::INFO) << \"DelaunayTriangulator: finalizing and cleaning up structures\\n\";\n\n \/\/ remove supertriangle vertices\n points->pop_back();\n points->pop_back();\n points->pop_back();\n\n \/\/ rejoin the two triangle lists\n triangles.insert(triangles.begin(), discarded_tris.begin(), discarded_tris.end());\n\n \/\/ initialize index storage vector\n std::vector pt_indices;\n pt_indices.reserve(triangles.size() * 3);\n\n \/\/ build osg primitive\n osg::notify(osg::INFO) << \"DelaunayTriangulator: building primitive(s)\\n\";\n Triangle_list::const_iterator ti;\n for (ti=triangles.begin(); ti!=triangles.end(); ++ti) {\n\n \/\/ don't add this triangle to the primitive if it shares any vertex with\n \/\/ the supertriangle\n if (ti->a() <= last_valid_index && ti->b() <= last_valid_index && ti->c() <= last_valid_index) {\n\n if (normals_.valid()) {\n (normals_.get())->push_back(ti->compute_normal(points));\n }\n\n pt_indices.push_back(ti->a());\n pt_indices.push_back(ti->b());\n pt_indices.push_back(ti->c());\n }\n }\n\n prim_tris_ = new osg::DrawElementsUInt(GL_TRIANGLES, pt_indices.size(), &(pt_indices.front()));\n\n osg::notify(osg::INFO) << \"DelaunayTriangulator: process done, \" << (pt_indices.size() \/ 3) << \" triangles created\\n\";\n \n return true;\n}\n\n\n}\nFrom David Spilling, fixed the incircle test so it handles colinear points.#include \n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\nnamespace osgUtil\n{\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ MISC MATH FUNCTIONS\n\n\n\/\/ Compute the circumcircle of a triangle (only x and y coordinates are used),\n\/\/ return (Cx, Cy, r^2)\ninline osg::Vec3 compute_circumcircle(\n const osg::Vec3 &a, \n const osg::Vec3 &b, \n const osg::Vec3 &c)\n{\n float D = \n (a.x() - c.x()) * (b.y() - c.y()) - \n (b.x() - c.x()) * (a.y() - c.y());\n\n float cx, cy, r2;\n\n if(D==0.0)\n {\n \/\/ (Nearly) degenerate condition - either two of the points are equal (which we discount)\n \/\/ or the three points are colinear. In this case we just determine the average of\n \/\/ the three points as the centre for correctness, but squirt out a zero radius.\n \/\/ This method will produce a triangulation with zero area, so we have to check later\n cx = (a.x()+b.x()+c.x())\/3.0;\n cy = (a.y()+b.y()+c.y())\/3.0;\n r2 = 0.0;\n }\n else\n {\n cx = \n (((a.x() - c.x()) * (a.x() + c.x()) + \n (a.y() - c.y()) * (a.y() + c.y())) \/ 2 * (b.y() - c.y()) -\n ((b.x() - c.x()) * (b.x() + c.x()) +\n (b.y() - c.y()) * (b.y() + c.y())) \/ 2 * (a.y() - c.y())) \/ D;\n\n cy = \n (((b.x() - c.x()) * (b.x() + c.x()) + \n (b.y() - c.y()) * (b.y() + c.y())) \/ 2 * (a.x() - c.x()) -\n ((a.x() - c.x()) * (a.x() + c.x()) +\n (a.y() - c.y()) * (a.y() + c.y())) \/ 2 * (b.x() - c.x())) \/ D;\n\n r2 = (c.x() - cx) * (c.x() - cx) + (c.y() - cy) * (c.y() - cy);\n }\n return osg::Vec3(cx, cy, r2);\n}\n\n\/\/ Test whether a point (only the x and y coordinates are used) lies inside\n\/\/ a circle; the circle is passed as a vector: (Cx, Cy, r^2).\n\ninline bool point_in_circle(const osg::Vec3 &point, const osg::Vec3 &circle)\n{\n float r2 = \n (point.x() - circle.x()) * (point.x() - circle.x()) + \n (point.y() - circle.y()) * (point.y() - circle.y());\n return r2 <= circle.z();\n}\n\n\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n\/\/ data type for vertex indices\ntypedef GLuint Vertex_index;\n\n\n\/\/ CLASS: Edge\n\/\/ This class describes an edge of a triangle (it stores vertex indices to the two\n\/\/ endpoints).\n\nclass Edge {\npublic:\n\n \/\/ Comparison object (for sorting)\n struct Less {\n inline bool operator()(const Edge &e1, const Edge &e2) const\n {\n if (e1.ibs() < e2.ibs()) return true;\n if (e1.ibs() > e2.ibs()) return false;\n if (e1.ies() < e2.ies()) return true;\n return false;\n }\n };\n\n Edge() {}\n Edge(Vertex_index ib, Vertex_index ie) : ib_(ib), ie_(ie), ibs_(osg::minimum(ib, ie)), ies_(osg::maximum(ib, ie)), duplicate_(false) {}\n\n \/\/ first endpoint\n inline Vertex_index ib() const { return ib_; }\n\n \/\/ second endpoint\n inline Vertex_index ie() const { return ie_; }\n\n \/\/ first sorted endpoint\n inline Vertex_index ibs() const { return ibs_; }\n\n \/\/ second sorted endpoint\n inline Vertex_index ies() const { return ies_; }\n\n \/\/ get the \"duplicate\" flag\n inline bool get_duplicate() const { return duplicate_; }\n\n \/\/ set the \"duplicate\" flag\n inline void set_duplicate(bool v) { duplicate_ = v; }\n\nprivate:\n Vertex_index ib_, ie_;\n Vertex_index ibs_, ies_;\n bool duplicate_;\n};\n\n\n\/\/ CLASS: Triangle\n\nclass Triangle {\npublic:\n Triangle(Vertex_index a, Vertex_index b, Vertex_index c, osg::Vec3Array *points)\n : a_(a), \n b_(b), \n c_(c), \n cc_(compute_circumcircle((*points)[a_], (*points)[b_], (*points)[c_]))\n {\n edge_[0] = Edge(a_, b_);\n edge_[1] = Edge(b_, c_);\n edge_[2] = Edge(c_, a_);\n }\n\n inline Vertex_index a() const { return a_; }\n inline Vertex_index b() const { return b_; }\n inline Vertex_index c() const { return c_; }\n\n inline const Edge &get_edge(int idx) const { return edge_[idx]; }\n inline const osg::Vec3 &get_circumcircle() const { return cc_; }\n\n inline osg::Vec3 compute_normal(osg::Vec3Array *points) const\n {\n osg::Vec3 N = ((*points)[b_] - (*points)[a_]) ^ ((*points)[c_] - (*points)[a_]);\n return N \/ N.length();\n }\n\n\nprivate:\n Vertex_index a_;\n Vertex_index b_;\n Vertex_index c_;\n osg::Vec3 cc_; \n Edge edge_[3];\n};\n\n\n\/\/ comparison function for sorting sample points by the X coordinate\nbool Sample_point_compare(const osg::Vec3 &p1, const osg::Vec3 &p2)\n{\n return p1.x() < p2.x();\n}\n\n\n\/\/ container types\ntypedef std::set Edge_set;\ntypedef std::list Triangle_list;\n\n\n\nDelaunayTriangulator::DelaunayTriangulator():\n osg::Referenced()\n{\n}\n\nDelaunayTriangulator::DelaunayTriangulator(osg::Vec3Array *points, osg::Vec3Array *normals):\n osg::Referenced(),\n points_(points),\n normals_(normals)\n{\n}\n\nDelaunayTriangulator::DelaunayTriangulator(const DelaunayTriangulator ©, const osg::CopyOp ©op):\n osg::Referenced(copy),\n points_(static_cast(copyop(copy.points_.get()))),\n normals_(static_cast(copyop(copy.normals_.get()))),\n prim_tris_(static_cast(copyop(copy.prim_tris_.get())))\n{\n}\n\nDelaunayTriangulator::~DelaunayTriangulator()\n{\n}\n\nbool DelaunayTriangulator::triangulate()\n{\n \/\/ check validity of input array\n if (!points_.valid()) {\n osg::notify(osg::WARN) << \"Warning: DelaunayTriangulator::triangulate(): invalid sample point array\" << std::endl;\n return false;\n }\n\n osg::Vec3Array *points = points_.get();\n\n if (points->size() < 1) {\n osg::notify(osg::WARN) << \"Warning: DelaunayTriangulator::triangulate(): too few sample points\" << std::endl;\n return false;\n }\n\n \/\/ initialize storage structures\n Triangle_list triangles;\n Triangle_list discarded_tris; \n\n \/\/ pre-sort sample points\n osg::notify(osg::INFO) << \"DelaunayTriangulator: pre-sorting sample points\\n\";\n std::sort(points->begin(), points->end(), Sample_point_compare); \n\n \/\/ set the last valid index for the point list\n GLuint last_valid_index = points->size() - 1; \n\n \/\/ find the minimum and maximum x values in the point list\n float minx = (*points)[0].x();\n float maxx = (*points)[last_valid_index].x();\n\n\n \/\/ find the minimum and maximum x values in the point list \n float miny = (*points)[0].y();\n float maxy = miny;\n \n osg::notify(osg::INFO) << \"DelaunayTriangulator: finding minimum and maximum Y values\\n\";\n osg::Vec3Array::const_iterator mmi;\n for (mmi=points->begin(); mmi!=points->end(); ++mmi) {\n if (mmi->y() < miny) miny = mmi->y();\n if (mmi->y() > maxy) maxy = mmi->y();\n }\n \n \/\/ add supertriangle vertices to the point list\n points->push_back(osg::Vec3(minx - (maxx - minx), miny, 0));\n points->push_back(osg::Vec3(maxx, miny, 0));\n points->push_back(osg::Vec3(maxx, maxy + (maxy - miny), 0));\n\n \/\/ add supertriangle to triangle list\n triangles.push_back(Triangle(last_valid_index+1, last_valid_index+2, last_valid_index+3, points));\n\n \n \/\/ begin triangulation \n GLuint pidx = 0;\n osg::Vec3Array::const_iterator i; \n \n osg::notify(osg::INFO) << \"DelaunayTriangulator: triangulating vertex grid (\" << (points->size()-3) <<\" points)\\n\"; \n\n for (i=points->begin(); i!=points->end(); ++i, ++pidx) {\n\n \/\/ don't process supertriangle vertices\n if (pidx > last_valid_index) break;\n\n Edge_set edges;\n\n \/\/ iterate through triangles\n Triangle_list::iterator j, next_j;\n for (j=triangles.begin(); j!=triangles.end(); j = next_j) {\n\n next_j = j;\n ++next_j;\n\n \/\/ compute the circumcircle\n osg::Vec3 cc = j->get_circumcircle();\n\n \/\/ OPTIMIZATION: since points are pre-sorted by the X component,\n \/\/ check whether we can discard this triangle for future operations\n float xdist = i->x() - cc.x();\n if ((xdist * xdist) > cc.z() && i->x() > cc.x()) {\n discarded_tris.push_back(*j);\n triangles.erase(j);\n } else {\n\n \/\/ if the point lies in the triangle's circumcircle then add\n \/\/ its edges to the edge list and remove the triangle\n if (point_in_circle(*i, cc))\n {\n for (int ei=0; ei<3; ++ei)\n {\n std::pair result = edges.insert(j->get_edge(ei));\n if (!result.second)\n {\n \/\/ cast away constness of a set element, which is\n \/\/ safe in this case since the set_duplicate is\n \/\/ not used as part of the Less operator.\n Edge& edge = const_cast(*(result.first));\n edge.set_duplicate(true);\n }\n } \n triangles.erase(j);\n }\n }\n }\n\n \/\/ remove duplicate edges and add new triangles\n Edge_set::iterator ci;\n for (ci=edges.begin(); ci!=edges.end(); ++ci) {\n if (!ci->get_duplicate()) {\n triangles.push_back(Triangle(pidx, ci->ib(), ci->ie(), points));\n }\n }\n }\n\n osg::notify(osg::INFO) << \"DelaunayTriangulator: finalizing and cleaning up structures\\n\";\n\n \/\/ remove supertriangle vertices\n points->pop_back();\n points->pop_back();\n points->pop_back();\n\n \/\/ rejoin the two triangle lists\n triangles.insert(triangles.begin(), discarded_tris.begin(), discarded_tris.end());\n\n \/\/ initialize index storage vector\n std::vector pt_indices;\n pt_indices.reserve(triangles.size() * 3);\n\n \/\/ build osg primitive\n osg::notify(osg::INFO) << \"DelaunayTriangulator: building primitive(s)\\n\";\n Triangle_list::const_iterator ti;\n for (ti=triangles.begin(); ti!=triangles.end(); ++ti) {\n\n \/\/ don't add this triangle to the primitive if it shares any vertex with\n \/\/ the supertriangle\n \/\/ Also don't add degenerate (zero radius) triangles\n if (ti->a() <= last_valid_index && ti->b() <= last_valid_index && ti->c() <= last_valid_index && ti->get_circumcircle().z()>0.0) {\n\n if (normals_.valid()) {\n (normals_.get())->push_back(ti->compute_normal(points));\n }\n\n pt_indices.push_back(ti->a());\n pt_indices.push_back(ti->b());\n pt_indices.push_back(ti->c());\n }\n }\n\n prim_tris_ = new osg::DrawElementsUInt(GL_TRIANGLES, pt_indices.size(), &(pt_indices.front()));\n\n osg::notify(osg::INFO) << \"DelaunayTriangulator: process done, \" << (pt_indices.size() \/ 3) << \" triangles created\\n\";\n \n return true;\n}\n\n\n}\n<|endoftext|>"} {"text":"\n#include \"TStopwatch.h\"\n#include \"TUnuran.h\"\n\n#include \"TH1.h\"\n\n#include \"TRandom.h\"\n#include \"TSystem.h\"\n\/\/#include \"TApplication.h\"\n#include \"TVirtualFitter.h\"\n#include \"Math\/ProbFunc.h\"\n\n#include \n\nusing std::cout; \nusing std::endl; \n\nvoid unuranSimple() { \n\n \/\/ simple test of unuran\n\n\n TUnuran unr; \n if (! unr.Init( \"normal()\", \"method=arou\") ) {\n cout << \"Error initializing unuran\" << endl;\n return;\n }\n\n int n = 1000000;\n TStopwatch w; \n w.Start(); \n\n for (int i = 0; i < n; ++i) \n unr.Sample(); \n\n w.Stop(); \n cout << \"Time using Unuran =\\t\\t \" << w.CpuTime() << endl;\n\n w.Start();\n for (int i = 0; i < n; ++i) \n gRandom->Gaus(0,1); \n\n w.Stop(); \n cout << \"Time using TRandom::Gaus =\\t \" << w.CpuTime() << endl;\n\n \/\/ test the quality by looking at the cdf\n\n TH1D * h1 = new TH1D(\"h1\",\"cdf on the data \",100,0,1);\n for (int i = 0; i < n; ++i) {\n double x = unr.Sample();\n \/\/ x = gRandom->Gaus(0,1); \n h1->Fill( ROOT::Math::normal_quant( x , 1.0) ); \n }\n\/\/ gSystem->Load(\"libMinuit2\");\n\/\/ TVirtualFitter::SetDefaultFitter(\"Minuit2\");\n std::cout << \"Result of fitting a cdf to a constant function : \" << std::endl;\n h1->Fit(\"pol0\",\"Q\");\n TF1 * f = (TF1*)gROOT->GetFunction(\"pol0\");\n std::cout << \"Fit chi2 = \" << f->GetChisquare() << \" ndf = \" << f->GetNDF() << std::endl;\n std::cout << \"Fit Prob = \" << f->GetProb() << std::endl;\n\n h1->Draw();\n\n\n\n}\n\n#ifndef __CINT__\nint main(int \/* argc *\/, char ** \/* argv *\/)\n{\n\/\/ TApplication theApp(\"App\", &argc, argv);\n unuranSimple();\n\/\/ theApp.Run();\n return 0;\n}\n#endif\n\nfix problem in finding the TFitter on Windows by setting it explicitly\n#include \"TStopwatch.h\"\n#include \"TUnuran.h\"\n\n#include \"TH1.h\"\n\n#include \"TRandom.h\"\n#include \"TSystem.h\"\n\/\/#include \"TApplication.h\"\n\/\/#include \"TRint.h\"\n#include \"TVirtualFitter.h\"\n#include \"TFitter.h\"\n#include \"Math\/ProbFunc.h\"\n\n#include \n\nusing std::cout; \nusing std::endl; \n\nvoid unuranSimple() { \n\n \/\/ simple test of unuran\n\n\n TUnuran unr; \n if (! unr.Init( \"normal()\", \"method=arou\") ) {\n cout << \"Error initializing unuran\" << endl;\n return;\n }\n\n int n = 1000000;\n TStopwatch w; \n w.Start(); \n\n for (int i = 0; i < n; ++i) \n unr.Sample(); \n\n w.Stop(); \n cout << \"Time using Unuran =\\t\\t \" << w.CpuTime() << endl;\n\n w.Start();\n for (int i = 0; i < n; ++i) \n gRandom->Gaus(0,1); \n\n w.Stop(); \n cout << \"Time using TRandom::Gaus =\\t \" << w.CpuTime() << endl;\n\n \/\/ test the quality by looking at the cdf\n\n TH1D * h1 = new TH1D(\"h1\",\"cdf on the data \",100,0,1);\n for (int i = 0; i < n; ++i) {\n double x = unr.Sample();\n \/\/ x = gRandom->Gaus(0,1); \n h1->Fill( ROOT::Math::normal_quant( x , 1.0) ); \n }\n\/\/ gSystem->Load(\"libMinuit2\");\n\/\/ TVirtualFitter::SetDefaultFitter(\"Minuit2\");\n std::cout << \"Result of fitting a cdf to a constant function : \" << std::endl;\n \/\/ need TRint();\n TFitter * fitter = new TFitter(); \n TVirtualFitter::SetFitter(fitter);\n h1->Fit(\"pol0\",\"Q\");\n TF1 * f = (TF1*)gROOT->GetFunction(\"pol0\");\n std::cout << \"Fit chi2 = \" << f->GetChisquare() << \" ndf = \" << f->GetNDF() << std::endl;\n std::cout << \"Fit Prob = \" << f->GetProb() << std::endl;\n\n h1->Draw();\n\n \/\/delete fitter; \n\n\n}\n\n#ifndef __CINT__\nint main()\n{\n\/\/ TApplication theApp(\"App\", &argc, argv);\n \/\/TRint theApp(\"TRint\",&argc, argv);\n \/\/theApp.Run();\n unuranSimple();\n return 0;\n}\n#endif\n\n<|endoftext|>"} {"text":"#ifdef _WIN32\n\n#include \n#include \n#include \n#include \n#include \n\nstruct DbgEngPlugin\n{\n\tPDDebugState state = PDDebugState_noTarget;\n\tbool hasValidTarget = false;\n\n\tstd::string targetName;\n\n\tIDebugClient* debugClient = nullptr;\n\tIDebugControl* debugControl = nullptr;\n};\n\nvoid onRun(DbgEngPlugin* plugin)\n{\n\t\n}\n\nvoid onStop(DbgEngPlugin* plugin)\n{\n\n}\n\nstatic void onBreak(DbgEngPlugin* plugin)\n{\n\n}\n\nstatic void onStep(DbgEngPlugin* plugin)\n{\n\n}\n\nstatic void onStepOver(DbgEngPlugin* plugin)\n{\n\n}\n\nstatic void onStepOut(DbgEngPlugin* plugin)\n{\n\n}\n\nstatic void doAction(DbgEngPlugin* plugin, PDAction action)\n{\n\tswitch (action)\n\t{\n\tcase PDAction_stop: onStop(plugin); break;\n\tcase PDAction_break: onBreak(plugin); break;\n\tcase PDAction_run: onRun(plugin); break;\n\tcase PDAction_step: onStep(plugin); break;\n\tcase PDAction_stepOut: onStepOut(plugin); break;\n\tcase PDAction_stepOver: onStepOver(plugin); break;\n\t}\n}\n\nstatic void setExceptionLocation(DbgEngPlugin* plugin, PDWriter* writer)\n{\n\n}\n\nstatic void setCallstack(DbgEngPlugin* plugin, PDWriter* writer)\n{\n\n}\n\nstatic void setExecutable(DbgEngPlugin* plugin, PDReader* reader)\n{\n\tconst char* filename = 0;\n\n\tPDRead_findString(reader, &filename, \"filename\", 0);\n\n\tif (!filename)\n\t{\n\t\tprintf(\"Unable to find filename which is required when starting a LLDB debug session\\n\");\n\t\treturn;\n\t}\n\n\tprintf(\"found filename \\\"%s\\\"\\n\", filename);\n\n\tplugin->targetName = filename;\n\n\tHRESULT hr = plugin->debugClient->CreateProcess(0, PSTR(filename), DEBUG_PROCESS);\n\tassert(SUCCEEDED(hr));\n\t\n\tprintf(\"Valid target %s\\n\", filename);\n}\n\nstatic void setLocals(DbgEngPlugin* plugin, PDWriter* writer)\n{\n\n}\n\nstatic void setBreakpoint(DbgEngPlugin* plugin, PDReader* reader, PDWriter* writer)\n{\n\n}\n\nstatic void eventAction(DbgEngPlugin* plugin, PDReader* reader)\n{\n\tuint32_t action = 0;\n\n\tprintf(\"DbgEngPlugin; %d\\n\", (PDRead_findU32(reader, &action, \"action\", 0) & 0xff) >> 8);\n\tprintf(\"DbgEngPlugin: got action (from event) %d\\n\", action);\n\n\tdoAction(plugin, (PDAction)action);\n}\n\nstatic void processEvents(DbgEngPlugin* plugin, PDReader* reader, PDWriter* writer)\n{\n\tPDEventType event;\n\n\twhile ((event = (PDEventType)PDRead_getEvent(reader)))\n\t{\n\t\tswitch (event)\n\t\t{\n\t\tcase PDEventType_getExceptionLocation: setExceptionLocation(plugin, writer); break;\n\t\tcase PDEventType_getCallstack: setCallstack(plugin, writer); break;\n\t\tcase PDEventType_setExecutable: setExecutable(plugin, reader); break;\n\t\tcase PDEventType_getLocals: setLocals(plugin, writer); break;\n\t\tcase PDEventType_setBreakpoint: setBreakpoint(plugin, reader, writer); break;\n\t\tcase PDEventType_action: eventAction(plugin, reader); break;\n\t\t}\n\t}\n}\n\n\nvoid* createInstance(ServiceFunc* serviceFunc)\n{\n\tDbgEngPlugin* plugin = new DbgEngPlugin;\n\n\tHRESULT hr = DebugCreate(__uuidof(IDebugClient), (void**)&plugin->debugClient);\n\tassert(SUCCEEDED(hr));\n\n\thr = plugin->debugClient->QueryInterface(__uuidof(IDebugControl), (void**)&plugin->debugControl);\n\tassert(SUCCEEDED(hr));\n\n\treturn plugin;\n}\n\nvoid destroyInstance(void* userData)\n{\n\tDbgEngPlugin* plugin = reinterpret_cast(userData);\n\n\tif (plugin->debugControl)\n\t{\n\t\tplugin->debugControl->Release();\n\t\tplugin->debugControl = nullptr;\n\t}\n\n\tif (plugin->debugClient)\n\t{\n\t\tplugin->debugClient->Release();\n\t\tplugin->debugClient = nullptr;\n\t}\n\t\t\n\tdelete plugin;\n}\n\nstatic PDDebugState update(void* userData, PDAction action, PDReader* reader, PDWriter* writer)\n{\n\tDbgEngPlugin* plugin = reinterpret_cast(userData);\n\n\tprocessEvents(plugin, reader, writer);\n\n\tdoAction(plugin, action);\n\n\t\/*\n\tif (plugin->state == PDDebugState_running)\n\t\tupdateDbgEngEvent(plugin, writer);\n\t*\/\n\n\treturn plugin->state;\n}\n\nstatic PDBackendPlugin plugin =\n{\n\t\"Microsoft Debugger Engine\",\n\tcreateInstance,\n\tdestroyInstance,\n\tupdate,\n};\n\nextern \"C\" PD_EXPORT void InitPlugin(RegisterPlugin* registerPlugin, void* privateData)\n{\n\tregisterPlugin(PD_BACKEND_API_VERSION, &plugin, privateData);\n}\n\n#endif\nAdded stubs for DebugBaseEventCallbacks interfaces#ifdef _WIN32\n\n#include \n#include \n#include \n#include \n#include \n\nstruct DbgEngPlugin : public DebugBaseEventCallbacks\n{\n\tPDDebugState state = PDDebugState_noTarget;\n\tbool hasValidTarget = false;\n\n\tstd::string targetName;\n\n\tIDebugClient* debugClient = nullptr;\n\tIDebugControl* debugControl = nullptr;\n\n\t\/\/ IUnknown\n\tSTDMETHOD_(ULONG, AddRef)(THIS);\n\tSTDMETHOD_(ULONG, Release)(THIS);\n\n\t\/\/ IDebugEventCallbacks\n\tSTDMETHOD(GetInterestMask)(THIS_\n\t\tOUT PULONG Mask);\n\tSTDMETHOD(Breakpoint)(THIS_\n\t\tIN PDEBUG_BREAKPOINT Bp);\n\tSTDMETHOD(Exception)(THIS_\n\t\tIN PEXCEPTION_RECORD64 Exception, IN ULONG FirstChance);\n\tSTDMETHOD(CreateProcess)(THIS_\n\t\tIN ULONG64 ImageFileHandle,\n\t\tIN ULONG64 Handle,\n\t\tIN ULONG64 BaseOffset,\n\t\tIN ULONG ModuleSize,\n\t\tIN PCSTR ModuleName,\n\t\tIN PCSTR ImageName,\n\t\tIN ULONG CheckSum,\n\t\tIN ULONG TimeDateStamp,\n\t\tIN ULONG64 InitialThreadHandle,\n\t\tIN ULONG64 ThreadDataOffset,\n\t\tIN ULONG64 StartOffset);\n\tSTDMETHOD(LoadModule)(THIS_\n\t\tIN ULONG64 ImageFileHandle,\n\t\tIN ULONG64 BaseOffset,\n\t\tIN ULONG ModuleSize,\n\t\tIN PCSTR ModuleName,\n\t\tIN PCSTR ImageName,\n\t\tIN ULONG CheckSum,\n\t\tIN ULONG TimeDateStamp);\n\tSTDMETHOD(SessionStatus)(THIS_\n\t\tIN ULONG Status);\n};\n\nSTDMETHODIMP_(ULONG) DbgEngPlugin::AddRef(THIS)\n{\n\treturn 1;\n}\n\nSTDMETHODIMP_(ULONG) DbgEngPlugin::Release(THIS)\n{\n\treturn 0;\n}\n\nSTDMETHODIMP DbgEngPlugin::GetInterestMask(THIS_\n\tOUT PULONG Mask)\n{\n\t*Mask =\n\t\tDEBUG_EVENT_BREAKPOINT |\n\t\tDEBUG_EVENT_EXCEPTION |\n\t\tDEBUG_EVENT_CREATE_PROCESS |\n\t\tDEBUG_EVENT_LOAD_MODULE |\n\t\tDEBUG_EVENT_SESSION_STATUS;\n\treturn S_OK;\n}\n\nSTDMETHODIMP DbgEngPlugin::Breakpoint(THIS_\n\tIN PDEBUG_BREAKPOINT Bp)\n{\n\treturn S_OK;\n}\n\nSTDMETHODIMP DbgEngPlugin::Exception(THIS_\n\tIN PEXCEPTION_RECORD64 Exception,\n\tIN ULONG FirstChance)\n{\n\treturn S_OK;\n}\n\nSTDMETHODIMP DbgEngPlugin::CreateProcess(THIS_\n\tIN ULONG64 ImageFileHandle,\n\tIN ULONG64 Handle,\n\tIN ULONG64 BaseOffset,\n\tIN ULONG ModuleSize,\n\tIN PCSTR ModuleName,\n\tIN PCSTR ImageName,\n\tIN ULONG CheckSum,\n\tIN ULONG TimeDateStamp,\n\tIN ULONG64 InitialThreadHandle,\n\tIN ULONG64 ThreadDataOffset,\n\tIN ULONG64 StartOffset)\n{\n\treturn S_OK;\n}\n\nSTDMETHODIMP DbgEngPlugin::LoadModule(THIS_\n\tIN ULONG64 ImageFileHandle,\n\tIN ULONG64 BaseOffset,\n\tIN ULONG ModuleSize,\n\tIN PCSTR ModuleName,\n\tIN PCSTR ImageName,\n\tIN ULONG CheckSum,\n\tIN ULONG TimeDateStamp)\n{\n\treturn S_OK;\n}\n\nSTDMETHODIMP DbgEngPlugin::SessionStatus(THIS_\n\tIN ULONG Status)\n{\n\treturn S_OK;\n}\n\nstatic void updateDbgEngEvent(DbgEngPlugin* plugin, PDWriter* writer)\n{\n\tHRESULT hr = plugin->debugControl->WaitForEvent(DEBUG_WAIT_DEFAULT, 100);\n\n\tif (hr == S_FALSE)\n\t{\n\t\t\/\/ WaitForEvent timeout occurred\n\t\treturn;\n\t}\n\n\t\/\/ TODO: check and handle execution status\n}\n\nvoid onRun(DbgEngPlugin* plugin)\n{\n\tprintf(\"DbgEngPlugin: onRun\\n\");\n\n\tif (plugin->state == PDDebugState_noTarget)\n\t{\n\t\tassert(!plugin->targetName.empty());\n\n\t\tHRESULT hr = plugin->debugClient->CreateProcess(0, PSTR(plugin->targetName.c_str()), DEBUG_ONLY_THIS_PROCESS);\n\t\tassert(SUCCEEDED(hr));\n\n\t\tif (SUCCEEDED(hr))\n\t\t{\n\t\t\tprintf(\"Error: could not create process '%s'\\n\", plugin->targetName.c_str());\n\t\t}\n\t\telse\n\t\t{\n\t\t\tprintf(\"Valid target %s\\n\", plugin->targetName.c_str());\n\t\t}\n\n\t\tplugin->state = PDDebugState_running;\n\t}\n}\n\nvoid onStop(DbgEngPlugin* plugin)\n{\n\tprintf(\"DbgEngPlugin: onStop\\n\");\n}\n\nstatic void onBreak(DbgEngPlugin* plugin)\n{\n\tprintf(\"DbgEngPlugin: onBreak\\n\");\n}\n\nstatic void onStep(DbgEngPlugin* plugin)\n{\n\tprintf(\"DbgEngPlugin: onStep\\n\");\n}\n\nstatic void onStepOver(DbgEngPlugin* plugin)\n{\n\tprintf(\"DbgEngPlugin: onStepOver\\n\");\n}\n\nstatic void onStepOut(DbgEngPlugin* plugin)\n{\n\tprintf(\"DbgEngPlugin: onStepOut\\n\");\n}\n\nstatic void doAction(DbgEngPlugin* plugin, PDAction action)\n{\n\tprintf(\"DbgEngPlugin: doAction\\n\");\n\n\tswitch (action)\n\t{\n\tcase PDAction_stop: onStop(plugin); break;\n\tcase PDAction_break: onBreak(plugin); break;\n\tcase PDAction_run: onRun(plugin); break;\n\tcase PDAction_step: onStep(plugin); break;\n\tcase PDAction_stepOut: onStepOut(plugin); break;\n\tcase PDAction_stepOver: onStepOver(plugin); break;\n\t}\n}\n\nstatic void setExceptionLocation(DbgEngPlugin* plugin, PDWriter* writer)\n{\n\tprintf(\"DbgEngPlugin: setExceptionLocation\\n\");\n}\n\nstatic void setCallstack(DbgEngPlugin* plugin, PDWriter* writer)\n{\n\tprintf(\"DbgEngPlugin: setCallstack\\n\");\n}\n\nstatic void setExecutable(DbgEngPlugin* plugin, PDReader* reader)\n{\n\tprintf(\"DbgEngPlugin: setExecutable\\n\");\n\n\tconst char* filename = 0;\n\n\tPDRead_findString(reader, &filename, \"filename\", 0);\n\n\tif (!filename)\n\t{\n\t\tprintf(\"Unable to find filename which is required when starting a LLDB debug session\\n\");\n\t\treturn;\n\t}\n\n\tprintf(\"found filename \\\"%s\\\"\\n\", filename);\n\n\tplugin->targetName = filename;\n}\n\nstatic void setLocals(DbgEngPlugin* plugin, PDWriter* writer)\n{\n\tprintf(\"DbgEngPlugin: setLocals\\n\");\n}\n\nstatic void setBreakpoint(DbgEngPlugin* plugin, PDReader* reader, PDWriter* writer)\n{\n\tprintf(\"DbgEngPlugin: setBreakpoint\\n\");\n}\n\nstatic void eventAction(DbgEngPlugin* plugin, PDReader* reader)\n{\n\tprintf(\"DbgEngPlugin: eventAction\\n\");\n\n\tuint32_t action = 0;\n\n\tprintf(\"DbgEngPlugin; %d\\n\", (PDRead_findU32(reader, &action, \"action\", 0) & 0xff) >> 8);\n\tprintf(\"DbgEngPlugin: got action (from event) %d\\n\", action);\n\n\tdoAction(plugin, (PDAction)action);\n}\n\nstatic const char* eventTypes[] =\n{\n\t\"PDEventType_none\",\n\t\"PDEventType_getLocals\",\n\t\"PDEventType_setLocals\",\n\t\"PDEventType_getCallstack\",\n\t\"PDEventType_setCallstack\",\n\t\"PDEventType_getWatch\",\n\t\"PDEventType_setWatch\",\n\t\"PDEventType_getRegisters\",\n\t\"PDEventType_setRegisters\",\n\t\"PDEventType_getMemory\",\n\t\"PDEventType_setMemory\",\n\t\"PDEventType_getTty\",\n\t\"PDEventType_setTty\",\n\t\"PDEventType_getExceptionLocation\",\n\t\"PDEventType_setExceptionLocation\",\n\t\"PDEventType_getDisassembly\",\n\t\"PDEventType_setDisassembly\",\n\t\"PDEventType_setBreakpoint\",\n\t\"PDEventType_getBreakpoint\",\n\t\"PDEventType_setExecutable\",\n\t\"PDEventType_attachToProcess\",\n\t\"PDEventType_attachToRemoteSession\",\n\t\"PDEventType_action\",\n};\n\nstatic void processEvents(DbgEngPlugin* plugin, PDReader* reader, PDWriter* writer)\n{\n\tprintf(\"DbgEngPlugin: processEvents\\n\");\n\n\tPDEventType event;\n\n\twhile ((event = (PDEventType)PDRead_getEvent(reader)))\n\t{\n\t\tprintf(\"DbgEngPlugin: %d Got event %s\\n\", (int)event, eventTypes[event]);\n\n\t\tswitch (event)\n\t\t{\n\t\tcase PDEventType_getExceptionLocation: setExceptionLocation(plugin, writer); break;\n\t\tcase PDEventType_getCallstack: setCallstack(plugin, writer); break;\n\t\tcase PDEventType_setExecutable: setExecutable(plugin, reader); break;\n\t\tcase PDEventType_getLocals: setLocals(plugin, writer); break;\n\t\tcase PDEventType_setBreakpoint: setBreakpoint(plugin, reader, writer); break;\n\t\tcase PDEventType_action: eventAction(plugin, reader); break;\n\t\t}\n\t}\n}\n\nvoid* createInstance(ServiceFunc* serviceFunc)\n{\n\tDbgEngPlugin* plugin = new DbgEngPlugin;\n\n\tHRESULT hr = DebugCreate(__uuidof(IDebugClient), (void**)&plugin->debugClient);\n\tassert(SUCCEEDED(hr));\n\n\thr = plugin->debugClient->SetEventCallbacks(plugin);\n\tassert(SUCCEEDED(hr));\n\n\thr = plugin->debugClient->QueryInterface(__uuidof(IDebugControl), (void**)&plugin->debugControl);\n\tassert(SUCCEEDED(hr));\n\n\treturn plugin;\n}\n\nvoid destroyInstance(void* userData)\n{\n\tDbgEngPlugin* plugin = reinterpret_cast(userData);\n\n\tif (plugin->debugControl)\n\t{\n\t\tplugin->debugControl->Release();\n\t\tplugin->debugControl = nullptr;\n\t}\n\n\tif (plugin->debugClient)\n\t{\n\t\tplugin->debugClient->Release();\n\t\tplugin->debugClient = nullptr;\n\t}\n\n\tdelete plugin;\n}\n\nstatic PDDebugState update(void* userData, PDAction action, PDReader* reader, PDWriter* writer)\n{\n\tDbgEngPlugin* plugin = reinterpret_cast(userData);\n\n\tprocessEvents(plugin, reader, writer);\n\n\tdoAction(plugin, action);\n\n\tif (plugin->state == PDDebugState_running)\n\t{\n\t\tupdateDbgEngEvent(plugin, writer);\n\t}\n\n\treturn plugin->state;\n}\n\nstatic PDBackendPlugin plugin =\n{\n\t\"Microsoft Debugger Engine\",\n\tcreateInstance,\n\tdestroyInstance,\n\tupdate,\n};\n\nextern \"C\" PD_EXPORT void InitPlugin(RegisterPlugin* registerPlugin, void* privateData)\n{\n\tregisterPlugin(PD_BACKEND_API_VERSION, &plugin, privateData);\n}\n\n#endif\n<|endoftext|>"} {"text":"\/****************************************************************************\n**\n** Copyright (C) 2012 Digia Plc and\/or its subsidiary(-ies).\n** Contact: http:\/\/www.qt-project.org\/legal\n**\n** This file is part of the QtSensors module of the Qt Toolkit.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** Commercial License Usage\n** Licensees holding valid commercial Qt licenses may use this file in\n** accordance with the commercial license agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Digia. For licensing terms and\n** conditions see http:\/\/qt.digia.com\/licensing. For further information\n** use the contact form at http:\/\/qt.digia.com\/contact-us.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Digia gives you certain additional\n** rights. These rights are described in the Digia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** GNU General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU\n** General Public License version 3.0 as published by the Free Software\n** Foundation and appearing in the file LICENSE.GPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU General Public License version 3.0 requirements will be\n** met: http:\/\/www.gnu.org\/copyleft\/gpl.html.\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#ifndef Q_OS_BLACKBERRY\n#include \"genericorientationsensor.h\"\n#include \"genericrotationsensor.h\"\n#include \"genericalssensor.h\"\n#endif\n#include \"generictiltsensor.h\"\n#include \n#include \n#include \n#include \n#include \n\nclass genericSensorPlugin : public QObject, public QSensorPluginInterface, public QSensorChangesInterface, public QSensorBackendFactory\n{\n Q_OBJECT\n Q_PLUGIN_METADATA(IID \"com.nokia.Qt.QSensorPluginInterface\/1.0\" FILE \"plugin.json\")\n Q_INTERFACES(QSensorPluginInterface QSensorChangesInterface)\npublic:\n void registerSensors()\n {\n qDebug() << \"loaded the Generic plugin\";\n \/\/ Nothing to register here\n }\n\n void sensorsChanged()\n {\n if (!QSensor::defaultSensorForType(QAccelerometer::type).isEmpty()) {\n \/\/ There is an accelerometer available. Register the backends\n#ifndef Q_OS_BLACKBERRY\n if (!QSensorManager::isBackendRegistered(QOrientationSensor::type, genericorientationsensor::id))\n QSensorManager::registerBackend(QOrientationSensor::type, genericorientationsensor::id, this);\n if (!QSensorManager::isBackendRegistered(QRotationSensor::type, genericrotationsensor::id))\n QSensorManager::registerBackend(QRotationSensor::type, genericrotationsensor::id, this);\n if (!QSensorManager::isBackendRegistered(QAmbientLightSensor::type, genericalssensor::id))\n QSensorManager::registerBackend(QAmbientLightSensor::type, genericalssensor::id, this);\n#endif\n if (!QSensorManager::isBackendRegistered(QTiltSensor::type, GenericTiltSensor::id))\n QSensorManager::registerBackend(QTiltSensor::type, GenericTiltSensor::id, this);\n } else {\n#ifndef Q_OS_BLACKBERRY\n if (QSensorManager::isBackendRegistered(QOrientationSensor::type, genericorientationsensor::id))\n QSensorManager::unregisterBackend(QOrientationSensor::type, genericorientationsensor::id);\n if (QSensorManager::isBackendRegistered(QRotationSensor::type, genericrotationsensor::id))\n QSensorManager::unregisterBackend(QRotationSensor::type, genericrotationsensor::id);\n if (QSensorManager::isBackendRegistered(QAmbientLightSensor::type, genericalssensor::id))\n QSensorManager::unregisterBackend(QAmbientLightSensor::type, genericalssensor::id);\n#endif\n if (QSensorManager::isBackendRegistered(QTiltSensor::type, GenericTiltSensor::id))\n QSensorManager::unregisterBackend(QTiltSensor::type, GenericTiltSensor::id);\n }\n }\n\n QSensorBackend *createBackend(QSensor *sensor)\n {\n#ifndef Q_OS_BLACKBERRY\n if (sensor->identifier() == genericorientationsensor::id)\n return new genericorientationsensor(sensor);\n\n if (sensor->identifier() == genericrotationsensor::id)\n return new genericrotationsensor(sensor);\n\n if (sensor->identifier() == genericalssensor::id)\n return new genericalssensor(sensor);\n#endif\n if (sensor->identifier() == GenericTiltSensor::id)\n return new GenericTiltSensor(sensor);\n\n return 0;\n }\n};\n\n#include \"main.moc\"\n\nGeneric plugin: Remove debug message noise.\/****************************************************************************\n**\n** Copyright (C) 2012 Digia Plc and\/or its subsidiary(-ies).\n** Contact: http:\/\/www.qt-project.org\/legal\n**\n** This file is part of the QtSensors module of the Qt Toolkit.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** Commercial License Usage\n** Licensees holding valid commercial Qt licenses may use this file in\n** accordance with the commercial license agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Digia. For licensing terms and\n** conditions see http:\/\/qt.digia.com\/licensing. For further information\n** use the contact form at http:\/\/qt.digia.com\/contact-us.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Digia gives you certain additional\n** rights. These rights are described in the Digia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** GNU General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU\n** General Public License version 3.0 as published by the Free Software\n** Foundation and appearing in the file LICENSE.GPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU General Public License version 3.0 requirements will be\n** met: http:\/\/www.gnu.org\/copyleft\/gpl.html.\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#ifndef Q_OS_BLACKBERRY\n#include \"genericorientationsensor.h\"\n#include \"genericrotationsensor.h\"\n#include \"genericalssensor.h\"\n#endif\n#include \"generictiltsensor.h\"\n#include \n#include \n#include \n#include \n#include \n\nclass genericSensorPlugin : public QObject, public QSensorPluginInterface, public QSensorChangesInterface, public QSensorBackendFactory\n{\n Q_OBJECT\n Q_PLUGIN_METADATA(IID \"com.nokia.Qt.QSensorPluginInterface\/1.0\" FILE \"plugin.json\")\n Q_INTERFACES(QSensorPluginInterface QSensorChangesInterface)\npublic:\n void registerSensors()\n {\n \/\/ Nothing to register here\n }\n\n void sensorsChanged()\n {\n if (!QSensor::defaultSensorForType(QAccelerometer::type).isEmpty()) {\n \/\/ There is an accelerometer available. Register the backends\n#ifndef Q_OS_BLACKBERRY\n if (!QSensorManager::isBackendRegistered(QOrientationSensor::type, genericorientationsensor::id))\n QSensorManager::registerBackend(QOrientationSensor::type, genericorientationsensor::id, this);\n if (!QSensorManager::isBackendRegistered(QRotationSensor::type, genericrotationsensor::id))\n QSensorManager::registerBackend(QRotationSensor::type, genericrotationsensor::id, this);\n if (!QSensorManager::isBackendRegistered(QAmbientLightSensor::type, genericalssensor::id))\n QSensorManager::registerBackend(QAmbientLightSensor::type, genericalssensor::id, this);\n#endif\n if (!QSensorManager::isBackendRegistered(QTiltSensor::type, GenericTiltSensor::id))\n QSensorManager::registerBackend(QTiltSensor::type, GenericTiltSensor::id, this);\n } else {\n#ifndef Q_OS_BLACKBERRY\n if (QSensorManager::isBackendRegistered(QOrientationSensor::type, genericorientationsensor::id))\n QSensorManager::unregisterBackend(QOrientationSensor::type, genericorientationsensor::id);\n if (QSensorManager::isBackendRegistered(QRotationSensor::type, genericrotationsensor::id))\n QSensorManager::unregisterBackend(QRotationSensor::type, genericrotationsensor::id);\n if (QSensorManager::isBackendRegistered(QAmbientLightSensor::type, genericalssensor::id))\n QSensorManager::unregisterBackend(QAmbientLightSensor::type, genericalssensor::id);\n#endif\n if (QSensorManager::isBackendRegistered(QTiltSensor::type, GenericTiltSensor::id))\n QSensorManager::unregisterBackend(QTiltSensor::type, GenericTiltSensor::id);\n }\n }\n\n QSensorBackend *createBackend(QSensor *sensor)\n {\n#ifndef Q_OS_BLACKBERRY\n if (sensor->identifier() == genericorientationsensor::id)\n return new genericorientationsensor(sensor);\n\n if (sensor->identifier() == genericrotationsensor::id)\n return new genericrotationsensor(sensor);\n\n if (sensor->identifier() == genericalssensor::id)\n return new genericalssensor(sensor);\n#endif\n if (sensor->identifier() == GenericTiltSensor::id)\n return new GenericTiltSensor(sensor);\n\n return 0;\n }\n};\n\n#include \"main.moc\"\n\n<|endoftext|>"} {"text":"\/****************************************************************************\n**\n** Copyright (C) 2012 Digia Plc and\/or its subsidiary(-ies).\n** Contact: http:\/\/www.qt-project.org\/legal\n**\n** This file is part of the V4VM module of the Qt Toolkit.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** Commercial License Usage\n** Licensees holding valid commercial Qt licenses may use this file in\n** accordance with the commercial license agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Digia. For licensing terms and\n** conditions see http:\/\/qt.digia.com\/licensing. For further information\n** use the contact form at http:\/\/qt.digia.com\/contact-us.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Digia gives you certain additional\n** rights. These rights are described in the Digia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** GNU General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU\n** General Public License version 3.0 as published by the Free Software\n** Foundation and appearing in the file LICENSE.GPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU General Public License version 3.0 requirements will be\n** met: http:\/\/www.gnu.org\/copyleft\/gpl.html.\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n#include \"qv4objectiterator_p.h\"\n#include \"qv4object_p.h\"\n#include \"qv4stringobject_p.h\"\n#include \"qv4identifier_p.h\"\n\nusing namespace QV4;\n\nObjectIterator::ObjectIterator(Object *o, uint flags)\n : object(o)\n , current(o)\n , arrayNode(0)\n , arrayIndex(0)\n , memberIndex(0)\n , flags(flags)\n{\n tmpDynamicProperty.value = Value::undefinedValue();\n}\n\nProperty *ObjectIterator::next(String **name, uint *index, PropertyAttributes *attrs)\n{\n Property *p = 0;\n *name = 0;\n *index = UINT_MAX;\n while (1) {\n if (!current)\n break;\n\n p = current->advanceIterator(this, name, index, attrs);\n if (p)\n return p;\n\n if (flags & WithProtoChain)\n current = current->prototype;\n else\n current = 0;\n\n arrayIndex = 0;\n memberIndex = 0;\n }\n return 0;\n}\n\nValue ObjectIterator::nextPropertyName(Value *value)\n{\n PropertyAttributes attrs;\n uint index;\n String *name;\n Property *p = next(&name, &index, &attrs);\n if (!p)\n return Value::nullValue();\n\n if (value)\n *value = object->getValue(object->engine()->current, p, attrs);\n\n if (name)\n return Value::fromString(name);\n assert(index < UINT_MAX);\n return Value::fromDouble(index);\n}\n\nValue ObjectIterator::nextPropertyNameAsString(Value *value)\n{\n PropertyAttributes attrs;\n uint index;\n String *name;\n Property *p = next(&name, &index, &attrs);\n if (!p)\n return Value::nullValue();\n\n if (value)\n *value = object->getValue(object->engine()->current, p, attrs);\n\n if (name)\n return Value::fromString(name);\n assert(index < UINT_MAX);\n return Value::fromString(object->engine()->newString(QString::number(index)));\n}\nFix for..in with duplicated properties\/****************************************************************************\n**\n** Copyright (C) 2012 Digia Plc and\/or its subsidiary(-ies).\n** Contact: http:\/\/www.qt-project.org\/legal\n**\n** This file is part of the V4VM module of the Qt Toolkit.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** Commercial License Usage\n** Licensees holding valid commercial Qt licenses may use this file in\n** accordance with the commercial license agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Digia. For licensing terms and\n** conditions see http:\/\/qt.digia.com\/licensing. For further information\n** use the contact form at http:\/\/qt.digia.com\/contact-us.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Digia gives you certain additional\n** rights. These rights are described in the Digia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** GNU General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU\n** General Public License version 3.0 as published by the Free Software\n** Foundation and appearing in the file LICENSE.GPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU General Public License version 3.0 requirements will be\n** met: http:\/\/www.gnu.org\/copyleft\/gpl.html.\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n#include \"qv4objectiterator_p.h\"\n#include \"qv4object_p.h\"\n#include \"qv4stringobject_p.h\"\n#include \"qv4identifier_p.h\"\n\nusing namespace QV4;\n\nObjectIterator::ObjectIterator(Object *o, uint flags)\n : object(o)\n , current(o)\n , arrayNode(0)\n , arrayIndex(0)\n , memberIndex(0)\n , flags(flags)\n{\n tmpDynamicProperty.value = Value::undefinedValue();\n}\n\nProperty *ObjectIterator::next(String **name, uint *index, PropertyAttributes *attrs)\n{\n Property *p = 0;\n *name = 0;\n *index = UINT_MAX;\n while (1) {\n if (!current)\n break;\n\n while (p = current->advanceIterator(this, name, index, attrs)) {\n \/\/ check the property is not already defined earlier in the proto chain\n if (current != object) {\n Property *pp;\n if (*name) {\n pp = object->__getPropertyDescriptor__(*name);\n } else {\n assert (*index != UINT_MAX);\n pp = object->__getPropertyDescriptor__(*index);\n }\n if (pp != p)\n continue;\n }\n return p;\n }\n\n if (flags & WithProtoChain)\n current = current->prototype;\n else\n current = 0;\n\n arrayIndex = 0;\n memberIndex = 0;\n }\n return 0;\n}\n\nValue ObjectIterator::nextPropertyName(Value *value)\n{\n PropertyAttributes attrs;\n uint index;\n String *name;\n Property *p = next(&name, &index, &attrs);\n if (!p)\n return Value::nullValue();\n\n if (value)\n *value = object->getValue(object->engine()->current, p, attrs);\n\n if (name)\n return Value::fromString(name);\n assert(index < UINT_MAX);\n return Value::fromDouble(index);\n}\n\nValue ObjectIterator::nextPropertyNameAsString(Value *value)\n{\n PropertyAttributes attrs;\n uint index;\n String *name;\n Property *p = next(&name, &index, &attrs);\n if (!p)\n return Value::nullValue();\n\n if (value)\n *value = object->getValue(object->engine()->current, p, attrs);\n\n if (name)\n return Value::fromString(name);\n assert(index < UINT_MAX);\n return Value::fromString(object->engine()->newString(QString::number(index)));\n}\n<|endoftext|>"} {"text":"#include \"rdb_protocol\/terms\/terms.hpp\"\n\n#include \n\n#include \"rdb_protocol\/op.hpp\"\n#include \"rdb_protocol\/error.hpp\"\n#include \"rdb_protocol\/pb_utils.hpp\"\n\nnamespace ql {\n\n\/\/ This term is used for functions that are polymorphic on objects and\n\/\/ sequences, like `pluck`. It will handle the polymorphism; terms inheriting\n\/\/ from it just need to implement evaluation on objects (`obj_eval`).\nclass obj_or_seq_op_term_t : public op_term_t {\npublic:\n enum poly_type_t {\n MAP = 0,\n FILTER = 1\n };\n obj_or_seq_op_term_t(env_t *env, protob_t term,\n poly_type_t _poly_type, argspec_t argspec)\n : op_term_t(env, term, argspec), poly_type(_poly_type),\n func(make_counted_term()) {\n int varnum = env->gensym();\n Term *body = pb::set_func(func.get(), varnum);\n *body = *term;\n pb::set_var(pb::reset(body->mutable_args(0)), varnum);\n prop_bt(func.get());\n }\nprivate:\n virtual counted_t obj_eval() = 0;\n virtual counted_t eval_impl() {\n counted_t v0 = arg(0);\n if (v0->get_type().is_convertible(val_t::type_t::DATUM)) {\n if (v0->as_datum()->get_type() == datum_t::R_OBJECT) return obj_eval();\n }\n if (v0->get_type().is_convertible(val_t::type_t::SEQUENCE)) {\n switch (poly_type) {\n case MAP:\n return new_val(v0->as_seq()->map(make_counted(env, func)));\n case FILTER:\n return new_val(v0->as_seq()->filter(make_counted(env, func)));\n default: unreachable();\n }\n unreachable();\n }\n rfail(\"Cannot perform %s on a non-object non-sequence.\", name());\n unreachable();\n }\n\n poly_type_t poly_type;\n protob_t func;\n};\n\nclass pluck_term_t : public obj_or_seq_op_term_t {\npublic:\n pluck_term_t(env_t *env, protob_t term) :\n obj_or_seq_op_term_t(env, term, MAP, argspec_t(1, -1)) { }\nprivate:\n virtual counted_t obj_eval() {\n counted_t obj = arg(0)->as_datum();\n r_sanity_check(obj->get_type() == datum_t::R_OBJECT);\n\n scoped_ptr_t out(new datum_t(datum_t::R_OBJECT));\n for (size_t i = 1; i < num_args(); ++i) {\n const std::string &key = arg(i)->as_str();\n counted_t el = obj->get(key);\n if (el.has()) {\n bool conflict = out->add(key, el);\n r_sanity_check(!conflict);\n }\n }\n return new_val(counted_t(out.release()));\n }\n virtual const char *name() const { return \"pluck\"; }\n};\n\nclass without_term_t : public obj_or_seq_op_term_t {\npublic:\n without_term_t(env_t *env, protob_t term) :\n obj_or_seq_op_term_t(env, term, MAP, argspec_t(1, -1)) { }\nprivate:\n virtual counted_t obj_eval() {\n counted_t obj = arg(0)->as_datum();\n r_sanity_check(obj->get_type() == datum_t::R_OBJECT);\n\n scoped_ptr_t out(new datum_t(obj->as_object()));\n for (size_t i = 1; i < num_args(); ++i) {\n const std::string &key = arg(i)->as_str();\n UNUSED bool b = out->delete_key(key);\n }\n return new_val(counted_t(out.release()));\n }\n virtual const char *name() const { return \"without\"; }\n};\n\nclass merge_term_t : public obj_or_seq_op_term_t {\npublic:\n merge_term_t(env_t *env, protob_t term) :\n obj_or_seq_op_term_t(env, term, MAP, argspec_t(1, -1)) { }\nprivate:\n virtual counted_t obj_eval() {\n counted_t d = arg(0)->as_datum();\n for (size_t i = 1; i < num_args(); ++i) {\n d = d->merge(arg(i)->as_datum());\n }\n return new_val(d);\n }\n virtual const char *name() const { return \"merge\"; }\n};\n\nclass has_fields_term_t : public obj_or_seq_op_term_t {\npublic:\n has_fields_term_t(env_t *env, protob_t term)\n : obj_or_seq_op_term_t(env, term, FILTER, argspec_t(1, -1)) { }\nprivate:\n virtual counted_t obj_eval() {\n counted_t obj = arg(0)->as_datum();\n for (size_t i = 1; i < num_args(); ++i) {\n counted_t el = obj->get(arg(i)->as_str(), NOTHROW);\n if (!el.has() || el->get_type() == datum_t::R_NULL) {\n return new_val_bool(false);\n }\n }\n return new_val_bool(true);\n }\n virtual const char *name() const { return \"has_fields\"; }\n};\n\ncounted_t make_has_fields_term(env_t *env, protob_t term) {\n return make_counted(env, term);\n}\n\ncounted_t make_pluck_term(env_t *env, protob_t term) {\n return make_counted(env, term);\n}\ncounted_t make_without_term(env_t *env, protob_t term) {\n return make_counted(env, term);\n}\ncounted_t make_merge_term(env_t *env, protob_t term) {\n return make_counted(env, term);\n}\n\n} \/\/ namespace ql\nfixed pluck and without to not be quadratic#include \"rdb_protocol\/terms\/terms.hpp\"\n\n#include \n\n#include \"rdb_protocol\/op.hpp\"\n#include \"rdb_protocol\/error.hpp\"\n#include \"rdb_protocol\/pb_utils.hpp\"\n\nnamespace ql {\n\n\/\/ This term is used for functions that are polymorphic on objects and\n\/\/ sequences, like `pluck`. It will handle the polymorphism; terms inheriting\n\/\/ from it just need to implement evaluation on objects (`obj_eval`).\nclass obj_or_seq_op_term_t : public op_term_t {\npublic:\n enum poly_type_t {\n MAP = 0,\n FILTER = 1\n };\n obj_or_seq_op_term_t(env_t *env, protob_t term,\n poly_type_t _poly_type, argspec_t argspec)\n : op_term_t(env, term, argspec), poly_type(_poly_type),\n func(make_counted_term()) {\n int varnum = env->gensym();\n Term *body = pb::set_func(func.get(), varnum);\n *body = *term;\n pb::set_var(pb::reset(body->mutable_args(0)), varnum);\n prop_bt(func.get());\n }\nprivate:\n virtual counted_t obj_eval(counted_t v0) = 0;\n virtual counted_t eval_impl() {\n counted_t v0 = arg(0);\n if (v0->get_type().is_convertible(val_t::type_t::DATUM)) {\n if (v0->as_datum()->get_type() == datum_t::R_OBJECT) return obj_eval(v0);\n }\n if (v0->get_type().is_convertible(val_t::type_t::SEQUENCE)) {\n switch (poly_type) {\n case MAP:\n return new_val(v0->as_seq()->map(make_counted(env, func)));\n case FILTER:\n return new_val(v0->as_seq()->filter(make_counted(env, func)));\n default: unreachable();\n }\n unreachable();\n }\n rfail(\"Cannot perform %s on a non-object non-sequence.\", name());\n unreachable();\n }\n\n poly_type_t poly_type;\n protob_t func;\n};\n\nclass pluck_term_t : public obj_or_seq_op_term_t {\npublic:\n pluck_term_t(env_t *env, protob_t term) :\n obj_or_seq_op_term_t(env, term, MAP, argspec_t(1, -1)) { }\nprivate:\n virtual counted_t obj_eval(counted_t v0) {\n counted_t obj = v0->as_datum();\n r_sanity_check(obj->get_type() == datum_t::R_OBJECT);\n\n scoped_ptr_t out(new datum_t(datum_t::R_OBJECT));\n for (size_t i = 1; i < num_args(); ++i) {\n const std::string &key = arg(i)->as_str();\n counted_t el = obj->get(key);\n if (el.has()) {\n bool conflict = out->add(key, el);\n r_sanity_check(!conflict);\n }\n }\n return new_val(counted_t(out.release()));\n }\n virtual const char *name() const { return \"pluck\"; }\n};\n\nclass without_term_t : public obj_or_seq_op_term_t {\npublic:\n without_term_t(env_t *env, protob_t term) :\n obj_or_seq_op_term_t(env, term, MAP, argspec_t(1, -1)) { }\nprivate:\n virtual counted_t obj_eval(counted_t v0) {\n counted_t obj = v0->as_datum();\n r_sanity_check(obj->get_type() == datum_t::R_OBJECT);\n\n scoped_ptr_t out(new datum_t(obj->as_object()));\n for (size_t i = 1; i < num_args(); ++i) {\n const std::string &key = arg(i)->as_str();\n UNUSED bool b = out->delete_key(key);\n }\n return new_val(counted_t(out.release()));\n }\n virtual const char *name() const { return \"without\"; }\n};\n\nclass merge_term_t : public obj_or_seq_op_term_t {\npublic:\n merge_term_t(env_t *env, protob_t term) :\n obj_or_seq_op_term_t(env, term, MAP, argspec_t(1, -1)) { }\nprivate:\n virtual counted_t obj_eval(counted_t v0) {\n counted_t d = v0->as_datum();\n for (size_t i = 1; i < num_args(); ++i) {\n d = d->merge(arg(i)->as_datum());\n }\n return new_val(d);\n }\n virtual const char *name() const { return \"merge\"; }\n};\n\nclass has_fields_term_t : public obj_or_seq_op_term_t {\npublic:\n has_fields_term_t(env_t *env, protob_t term)\n : obj_or_seq_op_term_t(env, term, FILTER, argspec_t(1, -1)) { }\nprivate:\n virtual counted_t obj_eval(counted_t v0) {\n counted_t obj = v0->as_datum();\n for (size_t i = 1; i < num_args(); ++i) {\n counted_t el = obj->get(arg(i)->as_str(), NOTHROW);\n if (!el.has() || el->get_type() == datum_t::R_NULL) {\n return new_val_bool(false);\n }\n }\n return new_val_bool(true);\n }\n virtual const char *name() const { return \"has_fields\"; }\n};\n\ncounted_t make_has_fields_term(env_t *env, protob_t term) {\n return make_counted(env, term);\n}\n\ncounted_t make_pluck_term(env_t *env, protob_t term) {\n return make_counted(env, term);\n}\ncounted_t make_without_term(env_t *env, protob_t term) {\n return make_counted(env, term);\n}\ncounted_t make_merge_term(env_t *env, protob_t term) {\n return make_counted(env, term);\n}\n\n} \/\/ namespace ql\n<|endoftext|>"} {"text":"\/\/=======================================================================\n\/\/ Copyright (c) 2014-2016 Baptiste Wicht\n\/\/ Distributed under the terms of the MIT License.\n\/\/ (See accompanying file LICENSE or copy at\n\/\/ http:\/\/opensource.org\/licenses\/MIT)\n\/\/=======================================================================\n\n#include \n\n#include \"catch.hpp\"\n\n#include \"dll\/dbn.hpp\"\n#include \"dll\/text_reader.hpp\"\n\n#include \"mnist\/mnist_reader.hpp\"\n#include \"mnist\/mnist_utils.hpp\"\n\nTEST_CASE(\"dbn\/mnist_1\", \"dbn::simple\") {\n typedef dll::dbn_desc<\n dll::dbn_layers<\n dll::rbm_desc<28 * 28, 100, dll::momentum, dll::batch_size<25>, dll::init_weights>::layer_t,\n dll::rbm_desc<100, 200, dll::momentum, dll::batch_size<25>>::layer_t,\n dll::rbm_desc<200, 10, dll::momentum, dll::batch_size<25>, dll::hidden>::layer_t>,\n dll::batch_size<50>>::dbn_t dbn_t;\n\n auto dataset = mnist::read_dataset_direct>(500);\n\n REQUIRE(!dataset.training_images.empty());\n\n mnist::binarize_dataset(dataset);\n\n auto dbn = std::make_unique();\n\n dbn->pretrain(dataset.training_images, 20);\n auto error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 10);\n\n REQUIRE(error < 5e-2);\n\n auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor());\n\n std::cout << \"test_error:\" << test_error << std::endl;\n\n REQUIRE(test_error < 0.2);\n}\n\nTEST_CASE(\"dbn\/mnist_2\", \"dbn::containers\") {\n typedef dll::dbn_desc<\n dll::dbn_layers<\n dll::rbm_desc<28 * 28, 100, dll::momentum, dll::batch_size<25>, dll::init_weights>::layer_t,\n dll::rbm_desc<100, 200, dll::momentum, dll::batch_size<25>>::layer_t,\n dll::rbm_desc<200, 10, dll::momentum, dll::batch_size<25>, dll::hidden>::layer_t>,\n dll::batch_size<50>>::dbn_t dbn_t;\n\n auto dataset = mnist::read_dataset_direct>(500);\n\n REQUIRE(!dataset.training_images.empty());\n dataset.training_images.resize(200);\n dataset.training_labels.resize(200);\n\n mnist::binarize_dataset(dataset);\n\n auto dbn = std::make_unique();\n\n dbn->pretrain(dataset.training_images, 5);\n auto error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 5);\n\n REQUIRE(error < 5e-2);\n}\n\nTEST_CASE(\"dbn\/mnist_3\", \"dbn::labels\") {\n auto dataset = mnist::read_dataset_direct>(1000);\n REQUIRE(!dataset.training_images.empty());\n\n mnist::binarize_dataset(dataset);\n\n typedef dll::dbn_desc<\n dll::dbn_label_layers<\n dll::rbm_desc<28 * 28, 200, dll::batch_size<50>, dll::init_weights, dll::momentum>::layer_t,\n dll::rbm_desc<200, 300, dll::batch_size<50>, dll::momentum>::layer_t,\n dll::rbm_desc<310, 500, dll::batch_size<50>, dll::momentum>::layer_t>,\n dll::batch_size<10>>::dbn_t dbn_t;\n\n auto dbn = std::make_unique();\n\n dbn->train_with_labels(dataset.training_images, dataset.training_labels, 10, 10);\n\n auto error = dll::test_set(dbn, dataset.training_images, dataset.training_labels, dll::label_predictor());\n std::cout << \"test_error:\" << error << std::endl;\n REQUIRE(error < 0.3);\n}\n\nTEST_CASE(\"dbn\/mnist_6\", \"dbn::cg_gaussian\") {\n typedef dll::dbn_desc<\n dll::dbn_layers<\n dll::rbm_desc<28 * 28, 200, dll::momentum, dll::batch_size<25>, dll::visible>::layer_t,\n dll::rbm_desc<200, 500, dll::momentum, dll::batch_size<25>>::layer_t,\n dll::rbm_desc<500, 10, dll::momentum, dll::batch_size<25>, dll::hidden>::layer_t>,\n dll::batch_size<50>>::dbn_t dbn_t;\n\n auto dataset = mnist::read_dataset_direct>(1000);\n\n REQUIRE(!dataset.training_images.empty());\n\n mnist::normalize_dataset(dataset);\n\n auto dbn = std::make_unique();\n\n dbn->pretrain(dataset.training_images, 20);\n auto error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 10);\n\n REQUIRE(error < 5e-2);\n\n auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor());\n\n std::cout << \"test_error:\" << test_error << std::endl;\n\n REQUIRE(test_error < 0.2);\n}\n\n\/\/This test should not perform well, but should not fail\nTEST_CASE(\"dbn\/mnist_8\", \"dbn::cg_relu\") {\n typedef dll::dbn_desc<\n dll::dbn_layers<\n dll::rbm_desc<28 * 28, 100, dll::momentum, dll::batch_size<25>, dll::hidden, dll::init_weights>::layer_t,\n dll::rbm_desc<100, 200, dll::momentum, dll::batch_size<25>>::layer_t,\n dll::rbm_desc<200, 10, dll::momentum, dll::batch_size<25>, dll::hidden>::layer_t>,\n dll::batch_size<50>>::dbn_t dbn_t;\n\n auto dataset = mnist::read_dataset_direct>(200);\n\n REQUIRE(!dataset.training_images.empty());\n\n mnist::binarize_dataset(dataset);\n\n auto dbn = std::make_unique();\n\n dbn->pretrain(dataset.training_images, 20);\n auto error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 10);\n\n REQUIRE(std::isfinite(error));\n\n auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor());\n\n std::cout << \"test_error:\" << test_error << std::endl;\n}\n\nTEST_CASE(\"dbn\/mnist_15\", \"dbn::parallel\") {\n typedef dll::dbn_desc<\n dll::dbn_layers<\n dll::rbm_desc<28 * 28, 100, dll::momentum, dll::parallel_mode, dll::batch_size<25>, dll::init_weights>::layer_t,\n dll::rbm_desc<100, 200, dll::momentum, dll::parallel_mode, dll::batch_size<25>>::layer_t,\n dll::rbm_desc<200, 10, dll::momentum, dll::parallel_mode, dll::batch_size<25>, dll::hidden>::layer_t>,\n dll::batch_size<50>>::dbn_t dbn_t;\n\n auto dataset = mnist::read_dataset_direct>(500);\n\n REQUIRE(!dataset.training_images.empty());\n\n mnist::binarize_dataset(dataset);\n\n auto dbn = std::make_unique();\n\n dbn->pretrain(dataset.training_images, 20);\n auto error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 10);\n\n REQUIRE(error < 5e-2);\n\n auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor());\n\n std::cout << \"test_error:\" << test_error << std::endl;\n\n REQUIRE(test_error < 0.2);\n}\n\nTEST_CASE(\"dbn\/mnist_17\", \"dbn::memory\") {\n typedef dll::dbn_desc<\n dll::dbn_layers<\n dll::rbm_desc<28 * 28, 100, dll::momentum, dll::batch_size<25>, dll::init_weights>::layer_t,\n dll::rbm_desc<100, 200, dll::momentum, dll::batch_size<25>>::layer_t,\n dll::rbm_desc<200, 10, dll::momentum, dll::batch_size<25>, dll::hidden>::layer_t>,\n dll::batch_mode, dll::batch_size<50>, dll::big_batch_size<3>>::dbn_t dbn_t;\n\n auto dataset = mnist::read_dataset_direct>(1078);\n\n REQUIRE(!dataset.training_images.empty());\n\n mnist::binarize_dataset(dataset);\n\n auto dbn = std::make_unique();\n\n dbn->pretrain(dataset.training_images, 20);\n auto error = dbn->fine_tune(\n dataset.training_images.begin(), dataset.training_images.end(),\n dataset.training_labels.begin(), dataset.training_labels.end(),\n 10);\n\n REQUIRE(error < 5e-2);\n\n auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor());\n\n std::cout << \"test_error:\" << test_error << std::endl;\n\n REQUIRE(test_error < 0.2);\n\n \/\/Mostly here to ensure compilation\n auto out = dbn->prepare_one_output>();\n REQUIRE(out.size() > 0);\n}\n\nTEST_CASE(\"dbn\/mnist\/text\/1\", \"dbn::simple\") {\n typedef dll::dbn_desc<\n dll::dbn_layers<\n dll::rbm_desc<28 * 28, 100, dll::momentum, dll::batch_size<25>, dll::init_weights>::layer_t,\n dll::rbm_desc<100, 200, dll::momentum, dll::batch_size<25>>::layer_t,\n dll::rbm_desc<200, 10, dll::momentum, dll::batch_size<25>, dll::hidden>::layer_t>,\n dll::batch_size<50>>::dbn_t dbn_t;\n\n auto training_images = dll::text::read_images>(\n \"\/home\/wichtounet\/datasets\/mnist_text\/train\/images\", 500,\n [](){ return etl::dyn_matrix(28 * 28);});\n\n auto test_images = dll::text::read_images>(\n \"\/home\/wichtounet\/datasets\/mnist_text\/test\/images\", 500,\n [](){ return etl::dyn_matrix(28 * 28);});\n\n auto training_labels = dll::text::read_labels(\"\/home\/wichtounet\/datasets\/mnist_text\/train\/labels\", 500);\n auto test_labels = dll::text::read_labels(\"\/home\/wichtounet\/datasets\/mnist_text\/test\/labels\", 500);\n\n REQUIRE(training_images.size() == 500);\n REQUIRE(test_images.size() == 500);\n REQUIRE(training_labels.size() == 500);\n REQUIRE(test_labels.size() == 500);\n\n mnist::binarize_each(training_images);\n mnist::binarize_each(test_images);\n\n auto dbn = std::make_unique();\n\n dbn->pretrain(training_images, 20);\n auto error = dbn->fine_tune(training_images, training_labels, 10);\n\n REQUIRE(error < 5e-2);\n\n auto test_error = dll::test_set(dbn, test_images, test_labels, dll::predictor());\n\n std::cout << \"test_error:\" << test_error << std::endl;\n\n REQUIRE(test_error < 0.2);\n}\nReview the test\/\/=======================================================================\n\/\/ Copyright (c) 2014-2016 Baptiste Wicht\n\/\/ Distributed under the terms of the MIT License.\n\/\/ (See accompanying file LICENSE or copy at\n\/\/ http:\/\/opensource.org\/licenses\/MIT)\n\/\/=======================================================================\n\n#include \n\n#include \"catch.hpp\"\n\n#include \"dll\/dbn.hpp\"\n#include \"dll\/text_reader.hpp\"\n\n#include \"mnist\/mnist_reader.hpp\"\n#include \"mnist\/mnist_utils.hpp\"\n\nTEST_CASE(\"dbn\/mnist_1\", \"dbn::simple\") {\n typedef dll::dbn_desc<\n dll::dbn_layers<\n dll::rbm_desc<28 * 28, 100, dll::momentum, dll::batch_size<25>, dll::init_weights>::layer_t,\n dll::rbm_desc<100, 200, dll::momentum, dll::batch_size<25>>::layer_t,\n dll::rbm_desc<200, 10, dll::momentum, dll::batch_size<25>, dll::hidden>::layer_t>,\n dll::batch_size<50>>::dbn_t dbn_t;\n\n auto dataset = mnist::read_dataset_direct>(500);\n\n REQUIRE(!dataset.training_images.empty());\n\n mnist::binarize_dataset(dataset);\n\n auto dbn = std::make_unique();\n\n dbn->pretrain(dataset.training_images, 20);\n auto error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 10);\n\n REQUIRE(error < 5e-2);\n\n auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor());\n\n std::cout << \"test_error:\" << test_error << std::endl;\n\n REQUIRE(test_error < 0.2);\n}\n\nTEST_CASE(\"dbn\/mnist_2\", \"dbn::containers\") {\n typedef dll::dbn_desc<\n dll::dbn_layers<\n dll::rbm_desc<28 * 28, 100, dll::momentum, dll::batch_size<25>, dll::init_weights>::layer_t,\n dll::rbm_desc<100, 200, dll::momentum, dll::batch_size<25>>::layer_t,\n dll::rbm_desc<200, 10, dll::momentum, dll::batch_size<25>, dll::hidden>::layer_t>,\n dll::batch_size<50>>::dbn_t dbn_t;\n\n auto dataset = mnist::read_dataset_direct>(500);\n\n REQUIRE(!dataset.training_images.empty());\n dataset.training_images.resize(200);\n dataset.training_labels.resize(200);\n\n mnist::binarize_dataset(dataset);\n\n auto dbn = std::make_unique();\n\n dbn->pretrain(dataset.training_images, 5);\n auto error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 5);\n\n REQUIRE(error < 5e-2);\n}\n\nTEST_CASE(\"dbn\/mnist_3\", \"dbn::labels\") {\n auto dataset = mnist::read_dataset_direct>(1000);\n REQUIRE(!dataset.training_images.empty());\n\n mnist::binarize_dataset(dataset);\n\n typedef dll::dbn_desc<\n dll::dbn_label_layers<\n dll::rbm_desc<28 * 28, 200, dll::batch_size<50>, dll::init_weights, dll::momentum>::layer_t,\n dll::rbm_desc<200, 300, dll::batch_size<50>, dll::momentum>::layer_t,\n dll::rbm_desc<310, 500, dll::batch_size<50>, dll::momentum>::layer_t>,\n dll::batch_size<10>>::dbn_t dbn_t;\n\n auto dbn = std::make_unique();\n\n dbn->train_with_labels(dataset.training_images, dataset.training_labels, 10, 10);\n\n auto error = dll::test_set(dbn, dataset.training_images, dataset.training_labels, dll::label_predictor());\n std::cout << \"test_error:\" << error << std::endl;\n REQUIRE(error < 0.3);\n}\n\nTEST_CASE(\"dbn\/mnist_6\", \"dbn::cg_gaussian\") {\n typedef dll::dbn_desc<\n dll::dbn_layers<\n dll::rbm_desc<28 * 28, 200, dll::momentum, dll::batch_size<25>, dll::visible>::layer_t,\n dll::rbm_desc<200, 500, dll::momentum, dll::batch_size<25>>::layer_t,\n dll::rbm_desc<500, 10, dll::momentum, dll::batch_size<25>, dll::hidden>::layer_t>,\n dll::batch_size<50>>::dbn_t dbn_t;\n\n auto dataset = mnist::read_dataset_direct>(1000);\n\n REQUIRE(!dataset.training_images.empty());\n\n mnist::normalize_dataset(dataset);\n\n auto dbn = std::make_unique();\n\n dbn->pretrain(dataset.training_images, 20);\n auto error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 10);\n\n REQUIRE(error < 5e-2);\n\n auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor());\n\n std::cout << \"test_error:\" << test_error << std::endl;\n\n REQUIRE(test_error < 0.2);\n}\n\n\/\/This test should not perform well, but should not fail\nTEST_CASE(\"dbn\/mnist_8\", \"dbn::cg_relu\") {\n typedef dll::dbn_desc<\n dll::dbn_layers<\n dll::rbm_desc<28 * 28, 100, dll::momentum, dll::batch_size<25>, dll::hidden, dll::init_weights>::layer_t,\n dll::rbm_desc<100, 200, dll::momentum, dll::batch_size<25>>::layer_t,\n dll::rbm_desc<200, 10, dll::momentum, dll::batch_size<25>, dll::hidden>::layer_t>,\n dll::batch_size<50>>::dbn_t dbn_t;\n\n auto dataset = mnist::read_dataset_direct>(200);\n\n REQUIRE(!dataset.training_images.empty());\n\n mnist::binarize_dataset(dataset);\n\n auto dbn = std::make_unique();\n\n dbn->pretrain(dataset.training_images, 20);\n auto error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 10);\n\n REQUIRE(std::isfinite(error));\n\n auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor());\n\n std::cout << \"test_error:\" << test_error << std::endl;\n}\n\nTEST_CASE(\"dbn\/mnist_15\", \"dbn::parallel\") {\n typedef dll::dbn_desc<\n dll::dbn_layers<\n dll::rbm_desc<28 * 28, 100, dll::momentum, dll::parallel_mode, dll::batch_size<25>, dll::init_weights>::layer_t,\n dll::rbm_desc<100, 200, dll::momentum, dll::parallel_mode, dll::batch_size<25>>::layer_t,\n dll::rbm_desc<200, 10, dll::momentum, dll::parallel_mode, dll::batch_size<25>, dll::hidden>::layer_t>,\n dll::batch_size<50>>::dbn_t dbn_t;\n\n auto dataset = mnist::read_dataset_direct>(500);\n\n REQUIRE(!dataset.training_images.empty());\n\n mnist::binarize_dataset(dataset);\n\n auto dbn = std::make_unique();\n\n dbn->pretrain(dataset.training_images, 20);\n auto error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 10);\n\n REQUIRE(error < 5e-2);\n\n auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor());\n\n std::cout << \"test_error:\" << test_error << std::endl;\n\n REQUIRE(test_error < 0.2);\n}\n\nTEST_CASE(\"dbn\/mnist_17\", \"dbn::memory\") {\n typedef dll::dbn_desc<\n dll::dbn_layers<\n dll::rbm_desc<28 * 28, 100, dll::momentum, dll::batch_size<25>, dll::init_weights>::layer_t,\n dll::rbm_desc<100, 200, dll::momentum, dll::batch_size<25>>::layer_t,\n dll::rbm_desc<200, 10, dll::momentum, dll::batch_size<25>, dll::hidden>::layer_t>,\n dll::batch_mode, dll::batch_size<50>, dll::big_batch_size<3>>::dbn_t dbn_t;\n\n auto dataset = mnist::read_dataset_direct>(1078);\n\n REQUIRE(!dataset.training_images.empty());\n\n mnist::binarize_dataset(dataset);\n\n auto dbn = std::make_unique();\n\n dbn->pretrain(dataset.training_images, 20);\n auto error = dbn->fine_tune(\n dataset.training_images.begin(), dataset.training_images.end(),\n dataset.training_labels.begin(), dataset.training_labels.end(),\n 10);\n\n REQUIRE(error < 5e-2);\n\n auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor());\n\n std::cout << \"test_error:\" << test_error << std::endl;\n\n REQUIRE(test_error < 0.2);\n\n \/\/Mostly here to ensure compilation\n auto out = dbn->prepare_one_output>();\n REQUIRE(out.size() > 0);\n}\n\nTEST_CASE(\"dbn\/mnist\/text\/1\", \"dbn::simple\") {\n typedef dll::dbn_desc<\n dll::dbn_layers<\n dll::rbm_desc<28 * 28, 100, dll::momentum, dll::batch_size<25>, dll::init_weights>::layer_t,\n dll::rbm_desc<100, 200, dll::momentum, dll::batch_size<25>>::layer_t,\n dll::rbm_desc<200, 10, dll::momentum, dll::batch_size<25>, dll::hidden>::layer_t>,\n dll::batch_size<50>>::dbn_t dbn_t;\n\n auto training_images = dll::text::read_images, false>(\n \"\/home\/wichtounet\/datasets\/mnist_text\/train\/images\", 500);\n\n auto test_images = dll::text::read_images, false>(\n \"\/home\/wichtounet\/datasets\/mnist_text\/test\/images\", 500);\n\n auto training_labels = dll::text::read_labels(\"\/home\/wichtounet\/datasets\/mnist_text\/train\/labels\", 500);\n auto test_labels = dll::text::read_labels(\"\/home\/wichtounet\/datasets\/mnist_text\/test\/labels\", 500);\n\n REQUIRE(training_images.size() == 500);\n REQUIRE(test_images.size() == 500);\n REQUIRE(training_labels.size() == 500);\n REQUIRE(test_labels.size() == 500);\n\n mnist::binarize_each(training_images);\n mnist::binarize_each(test_images);\n\n auto dbn = std::make_unique();\n\n dbn->pretrain(training_images, 20);\n auto error = dbn->fine_tune(training_images, training_labels, 10);\n\n REQUIRE(error < 5e-2);\n\n auto test_error = dll::test_set(dbn, test_images, test_labels, dll::predictor());\n\n std::cout << \"test_error:\" << test_error << std::endl;\n\n REQUIRE(test_error < 0.2);\n}\n<|endoftext|>"} {"text":"\/\/ This file is part of Eigen, a lightweight C++ template library\n\/\/ for linear algebra.\n\/\/\n\/\/ Copyright (C) 2008 Benoit Jacob \n\/\/ Copyright (C) 2010 Hauke Heibel \n\/\/\n\/\/ Eigen is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 3 of the License, or (at your option) any later version.\n\/\/\n\/\/ Alternatively, you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU General Public License as\n\/\/ published by the Free Software Foundation; either version 2 of\n\/\/ the License, or (at your option) any later version.\n\/\/\n\/\/ Eigen is distributed in the hope that it will be useful, but WITHOUT ANY\n\/\/ WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n\/\/ FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the\n\/\/ GNU General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License and a copy of the GNU General Public License along with\n\/\/ Eigen. If not, see .\n\n#include \"main.h\"\n#include \n#include \n\ntemplate\nvoid check_stdlist_matrix(const MatrixType& m)\n{\n int rows = m.rows();\n int cols = m.cols();\n MatrixType x = MatrixType::Random(rows,cols), y = MatrixType::Random(rows,cols);\n std::list > v(10, MatrixType(rows,cols)), w(20, y);\n v.front() = x;\n w.front() = w.back();\n VERIFY_IS_APPROX(w.front(), w.back());\n v = w;\n\n typename std::list >::iterator vi = v.begin();\n typename std::list >::iterator wi = w.begin();\n for(int i = 0; i < 20; i++)\n {\n VERIFY_IS_APPROX(*vi, *wi);\n ++vi;\n ++wi;\n }\n\n v.resize(21); \n v.back() = x;\n if (!test_ei_isApprox(v.back(),x))\n {\n std::cout << x << std::endl;\n std::cout << v.back() << std::endl;\n }\n VERIFY_IS_APPROX(v.back(), x);\n v.resize(22,y);\n VERIFY_IS_APPROX(v.back(), y);\n v.push_back(x);\n VERIFY_IS_APPROX(v.back(), x);\n}\n\ntemplate\nvoid check_stdlist_transform(const TransformType&)\n{\n typedef typename TransformType::MatrixType MatrixType;\n TransformType x(MatrixType::Random()), y(MatrixType::Random());\n std::list > v(10), w(20, y);\n v.front() = x;\n w.front() = w.back();\n VERIFY_IS_APPROX(w.front(), w.back());\n v = w;\n\n typename std::list >::iterator vi = v.begin();\n typename std::list >::iterator wi = w.begin();\n for(int i = 0; i < 20; i++)\n {\n VERIFY_IS_APPROX(*vi, *wi);\n ++vi;\n ++wi;\n }\n\n v.resize(21);\n v.back() = x;\n VERIFY_IS_APPROX(v.back(), x);\n v.resize(22,y);\n VERIFY_IS_APPROX(v.back(), y);\n v.push_back(x);\n VERIFY_IS_APPROX(v.back(), x);\n}\n\ntemplate\nvoid check_stdlist_quaternion(const QuaternionType&)\n{\n typedef typename QuaternionType::Coefficients Coefficients;\n QuaternionType x(Coefficients::Random()), y(Coefficients::Random());\n std::list > v(10), w(20, y);\n v.front() = x;\n w.front() = w.back();\n VERIFY_IS_APPROX(w.front(), w.back());\n v = w;\n\n typename std::list >::iterator vi = v.begin();\n typename std::list >::iterator wi = w.begin();\n for(int i = 0; i < 20; i++)\n {\n VERIFY_IS_APPROX(*vi, *wi);\n ++vi;\n ++wi;\n }\n\n v.resize(21);\n v.back() = x;\n VERIFY_IS_APPROX(v.back(), x);\n v.resize(22,y);\n VERIFY_IS_APPROX(v.back(), y);\n v.push_back(x);\n if (!test_ei_isApprox(v.back(),x))\n {\n std::cout << x << std::endl;\n std::cout << v.back() << std::endl;\n }\n VERIFY_IS_APPROX(v.back(), x);\n}\n\nvoid test_stdlist()\n{\n \/\/ some non vectorizable fixed sizes\n CALL_SUBTEST_1(check_stdlist_matrix(Vector2f()));\n CALL_SUBTEST_1(check_stdlist_matrix(Matrix3f()));\n CALL_SUBTEST_2(check_stdlist_matrix(Matrix3d()));\n\n \/\/ some vectorizable fixed sizes\n CALL_SUBTEST_1(check_stdlist_matrix(Matrix2f()));\n CALL_SUBTEST_1(check_stdlist_matrix(Vector4f()));\n CALL_SUBTEST_1(check_stdlist_matrix(Matrix4f()));\n CALL_SUBTEST_2(check_stdlist_matrix(Matrix4d()));\n\n \/\/ some dynamic sizes\n CALL_SUBTEST_3(check_stdlist_matrix(MatrixXd(1,1)));\n CALL_SUBTEST_3(check_stdlist_matrix(VectorXd(20)));\n CALL_SUBTEST_3(check_stdlist_matrix(RowVectorXf(20)));\n CALL_SUBTEST_3(check_stdlist_matrix(MatrixXcf(10,10)));\n\n \/\/ some Transform\n CALL_SUBTEST_4(check_stdlist_transform(Transform2f()));\n CALL_SUBTEST_4(check_stdlist_transform(Transform3f()));\n CALL_SUBTEST_4(check_stdlist_transform(Transform3d()));\n \/\/CALL_SUBTEST(heck_stdvector_transform(Transform4d()));\n\n \/\/ some Quaternion\n CALL_SUBTEST_5(check_stdlist_quaternion(Quaternionf()));\n CALL_SUBTEST_5(check_stdlist_quaternion(Quaterniond()));\n}\nRemove printouts.\/\/ This file is part of Eigen, a lightweight C++ template library\n\/\/ for linear algebra.\n\/\/\n\/\/ Copyright (C) 2008 Benoit Jacob \n\/\/ Copyright (C) 2010 Hauke Heibel \n\/\/\n\/\/ Eigen is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 3 of the License, or (at your option) any later version.\n\/\/\n\/\/ Alternatively, you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU General Public License as\n\/\/ published by the Free Software Foundation; either version 2 of\n\/\/ the License, or (at your option) any later version.\n\/\/\n\/\/ Eigen is distributed in the hope that it will be useful, but WITHOUT ANY\n\/\/ WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n\/\/ FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the\n\/\/ GNU General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License and a copy of the GNU General Public License along with\n\/\/ Eigen. If not, see .\n\n#include \"main.h\"\n#include \n#include \n\ntemplate\nvoid check_stdlist_matrix(const MatrixType& m)\n{\n int rows = m.rows();\n int cols = m.cols();\n MatrixType x = MatrixType::Random(rows,cols), y = MatrixType::Random(rows,cols);\n std::list > v(10, MatrixType(rows,cols)), w(20, y);\n v.front() = x;\n w.front() = w.back();\n VERIFY_IS_APPROX(w.front(), w.back());\n v = w;\n\n typename std::list >::iterator vi = v.begin();\n typename std::list >::iterator wi = w.begin();\n for(int i = 0; i < 20; i++)\n {\n VERIFY_IS_APPROX(*vi, *wi);\n ++vi;\n ++wi;\n }\n\n v.resize(21); \n v.back() = x;\n VERIFY_IS_APPROX(v.back(), x);\n v.resize(22,y);\n VERIFY_IS_APPROX(v.back(), y);\n v.push_back(x);\n VERIFY_IS_APPROX(v.back(), x);\n}\n\ntemplate\nvoid check_stdlist_transform(const TransformType&)\n{\n typedef typename TransformType::MatrixType MatrixType;\n TransformType x(MatrixType::Random()), y(MatrixType::Random());\n std::list > v(10), w(20, y);\n v.front() = x;\n w.front() = w.back();\n VERIFY_IS_APPROX(w.front(), w.back());\n v = w;\n\n typename std::list >::iterator vi = v.begin();\n typename std::list >::iterator wi = w.begin();\n for(int i = 0; i < 20; i++)\n {\n VERIFY_IS_APPROX(*vi, *wi);\n ++vi;\n ++wi;\n }\n\n v.resize(21);\n v.back() = x;\n VERIFY_IS_APPROX(v.back(), x);\n v.resize(22,y);\n VERIFY_IS_APPROX(v.back(), y);\n v.push_back(x);\n VERIFY_IS_APPROX(v.back(), x);\n}\n\ntemplate\nvoid check_stdlist_quaternion(const QuaternionType&)\n{\n typedef typename QuaternionType::Coefficients Coefficients;\n QuaternionType x(Coefficients::Random()), y(Coefficients::Random());\n std::list > v(10), w(20, y);\n v.front() = x;\n w.front() = w.back();\n VERIFY_IS_APPROX(w.front(), w.back());\n v = w;\n\n typename std::list >::iterator vi = v.begin();\n typename std::list >::iterator wi = w.begin();\n for(int i = 0; i < 20; i++)\n {\n VERIFY_IS_APPROX(*vi, *wi);\n ++vi;\n ++wi;\n }\n\n v.resize(21);\n v.back() = x;\n VERIFY_IS_APPROX(v.back(), x);\n v.resize(22,y);\n VERIFY_IS_APPROX(v.back(), y);\n v.push_back(x);\n VERIFY_IS_APPROX(v.back(), x);\n}\n\nvoid test_stdlist()\n{\n \/\/ some non vectorizable fixed sizes\n CALL_SUBTEST_1(check_stdlist_matrix(Vector2f()));\n CALL_SUBTEST_1(check_stdlist_matrix(Matrix3f()));\n CALL_SUBTEST_2(check_stdlist_matrix(Matrix3d()));\n\n \/\/ some vectorizable fixed sizes\n CALL_SUBTEST_1(check_stdlist_matrix(Matrix2f()));\n CALL_SUBTEST_1(check_stdlist_matrix(Vector4f()));\n CALL_SUBTEST_1(check_stdlist_matrix(Matrix4f()));\n CALL_SUBTEST_2(check_stdlist_matrix(Matrix4d()));\n\n \/\/ some dynamic sizes\n CALL_SUBTEST_3(check_stdlist_matrix(MatrixXd(1,1)));\n CALL_SUBTEST_3(check_stdlist_matrix(VectorXd(20)));\n CALL_SUBTEST_3(check_stdlist_matrix(RowVectorXf(20)));\n CALL_SUBTEST_3(check_stdlist_matrix(MatrixXcf(10,10)));\n\n \/\/ some Transform\n CALL_SUBTEST_4(check_stdlist_transform(Transform2f()));\n CALL_SUBTEST_4(check_stdlist_transform(Transform3f()));\n CALL_SUBTEST_4(check_stdlist_transform(Transform3d()));\n \/\/CALL_SUBTEST(heck_stdvector_transform(Transform4d()));\n\n \/\/ some Quaternion\n CALL_SUBTEST_5(check_stdlist_quaternion(Quaternionf()));\n CALL_SUBTEST_5(check_stdlist_quaternion(Quaterniond()));\n}\n<|endoftext|>"} {"text":"#pragma once\n\n\/\/ASSERT_TRUE();\n\/\/ASSERT_STREQ(test.c_str(), ans.c_str());\n\n\/\/-----------------------------------------------------------------------------------------------------------------------------------------------\n\nTEST(strEdit, theOthers){\n printf(\"■ strEdit\\n\");\n printf(\" □ readAll_bin\\n\");\n std::vector raw = sstd::readAll_bin(\".\/test\/test.png\");\n sstd::printn_all(raw.size());\n printf(\" □ writeAll_bin\\n\");\n if(!sstd::writeAll_bin(\".\/test__writeAll_bin_char.png\", raw)){ sstd::pdbg(\"ERROR: sstd::writeAll_bin()\\n\"); }\n if(!sstd::writeAll_bin(std::string(\".\/test__writeAll_bin_str.png\"), raw)){ sstd::pdbg(\"ERROR: sstd::writeAll_bin()\\n\"); }\n \n printf(\" □ readAll_withoutBOM & splitByLine\\n\");\n\/\/ std::string str_tI = sstd::readAll_withoutBOM(R\"(.\/test\/tinyInterpreter.txt)\");\n std::string str_tI = sstd::readAll_withoutBOM(std::string(R\"(.\/test\/tinyInterpreter.txt)\"));\n std::vector splitLList = sstd::splitByLine(str_tI);\n printf(\"\\n\");\n printf(\" .\/test\/tinyInterpreter.txt\\n\");\n printf(\"+----+---------------------------------------------------------------------+\\n\");\n for(uint i=0; i vecRow;\n vecRow = sstd::split(\"ABC DEF\", ' '); sstd::printn(vecRow); \/\/ \"ABC DEF\" -> [\"ABC\", \"DEF\"]\n vecRow = sstd::split(\" ABC D EF \", ' '); sstd::printn(vecRow); \/\/ \" ABC D EF \" -> [\"ABC\", \"D\", \"EF\"]\n \n vecRow = sstd::split(\"ABC,DEF\", ','); sstd::printn(vecRow); \/\/ \"ABC,DEF\" -> [\"ABC\", \"DEF\"]\n vecRow = sstd::split(\" ABC , D, EF ,GH \", ','); sstd::printn(vecRow); \/\/ \" ABC , D, EF ,GH \" -> [\"ABC\", \"D\", \"EF\", \"GH\"]\n}\n\n\/\/-----------------------------------------------------------------------------------------------------------------------------------------------\n\nTEST(strEdit, lstrip){\n std::string str_in = \" \\t abcd \\t \";\n std::string str_ans = \"abcd \\t \";\n ASSERT_TRUE(sstd::lstrip(str_in.c_str()) == str_ans);\n ASSERT_TRUE(sstd::lstrip(str_in ) == str_ans);\n}\nTEST(strEdit, lstrip_ow){\n std::string str_in = \" \\t abcd \\t \";\n std::string str_ans = \"abcd \\t \";\n sstd::lstrip_ow(str_in);\n ASSERT_TRUE(str_in == str_ans);\n}\nTEST(strEdit, rstrip){\n std::string str_in = \" \\t abcd \\t \";\n std::string str_ans = \" \\t abcd\";\n ASSERT_TRUE(sstd::rstrip(str_in.c_str()) == str_ans);\n ASSERT_TRUE(sstd::rstrip(str_in ) == str_ans);\n}\nTEST(strEdit, rstrip_ow){\n std::string str_in = \" \\t abcd \\t \";\n std::string str_ans = \" \\t abcd\";\n sstd::rstrip_ow(str_in);\n ASSERT_TRUE(str_in == str_ans);\n}\nTEST(strEdit, strip){\n std::string str_in = \" \\t abcd \\t \";\n std::string str_ans = \"abcd\";\n ASSERT_TRUE(sstd::strip(str_in.c_str()) == str_ans);\n ASSERT_TRUE(sstd::strip(str_in ) == str_ans);\n}\nTEST(strEdit, strip_ow){\n std::string str_in = \" \\t abcd \\t \";\n std::string str_ans = \"abcd\";\n sstd::strip_ow(str_in);\n ASSERT_TRUE(str_in == str_ans);\n}\nTEST(strEdit, strip_vec){\n std::vector vecStr_in = {\" \\t abcd01 \\t \", \" \\t abcd02 \\t \", \" \\t abcd03 \\t \"};\n std::vector vecStr_ans = {\"abcd01\", \"abcd02\", \"abcd03\"};\n ASSERT_TRUE(sstd::strip(vecStr_in) == vecStr_ans);\n}\n\n\/\/-----------------------------------------------------------------------------------------------------------------------------------------------\n\/*\n\/\/ 実装完了 (処理時間短縮のため,コメントアウト)\nTEST(strEdit, strIn){\n {\n std::string lhs = \"\";\n std::string rhs = \"\";\n bool ret=sstd::strIn(lhs, rhs); ASSERT_TRUE(ret);\n }\n {\n std::string lhs = \"ABCD\";\n std::string rhs = \"ABCDEFG\";\n bool ret=sstd::strIn(lhs, rhs); ASSERT_TRUE(ret);\n }\n {\n std::string lhs = \"BCD\";\n std::string rhs = \"ABCDEFG\";\n bool ret=sstd::strIn(lhs, rhs); ASSERT_TRUE(ret);\n }\n {\n std::string lhs = \"DEFG\";\n std::string rhs = \"ABCDEFG\";\n bool ret=sstd::strIn(lhs, rhs); ASSERT_TRUE(ret);\n }\n {\n std::string lhs = \"ABCDEFG\";\n std::string rhs = \"ABCDEFG\";\n bool ret=sstd::strIn(lhs, rhs); ASSERT_TRUE(ret);\n }\n {\n std::string lhs = \"AXCDEFG\";\n std::string rhs = \"ABCDEFG\";\n bool ret=sstd::strIn(lhs, rhs); ASSERT_TRUE(!ret);\n }\n}\n\/\/*\/\n\n\/\/-----------------------------------------------------------------------------------------------------------------------------------------------\ntest sort#pragma once\n\n\/\/ASSERT_TRUE();\n\/\/ASSERT_STREQ(test.c_str(), ans.c_str());\n\n\/\/-----------------------------------------------------------------------------------------------------------------------------------------------\n\nTEST(strEdit, theOthers){\n printf(\"■ strEdit\\n\");\n printf(\" □ readAll_bin\\n\");\n std::vector raw = sstd::readAll_bin(\".\/test\/test.png\");\n sstd::printn_all(raw.size());\n printf(\" □ writeAll_bin\\n\");\n if(!sstd::writeAll_bin(\".\/test__writeAll_bin_char.png\", raw)){ sstd::pdbg(\"ERROR: sstd::writeAll_bin()\\n\"); }\n if(!sstd::writeAll_bin(std::string(\".\/test__writeAll_bin_str.png\"), raw)){ sstd::pdbg(\"ERROR: sstd::writeAll_bin()\\n\"); }\n \n printf(\" □ readAll_withoutBOM & splitByLine\\n\");\n\/\/ std::string str_tI = sstd::readAll_withoutBOM(R\"(.\/test\/tinyInterpreter.txt)\");\n std::string str_tI = sstd::readAll_withoutBOM(std::string(R\"(.\/test\/tinyInterpreter.txt)\"));\n std::vector splitLList = sstd::splitByLine(str_tI);\n printf(\"\\n\");\n printf(\" .\/test\/tinyInterpreter.txt\\n\");\n printf(\"+----+---------------------------------------------------------------------+\\n\");\n for(uint i=0; i vecRow;\n vecRow = sstd::split(\"ABC DEF\", ' '); sstd::printn(vecRow); \/\/ \"ABC DEF\" -> [\"ABC\", \"DEF\"]\n vecRow = sstd::split(\" ABC D EF \", ' '); sstd::printn(vecRow); \/\/ \" ABC D EF \" -> [\"ABC\", \"D\", \"EF\"]\n \n vecRow = sstd::split(\"ABC,DEF\", ','); sstd::printn(vecRow); \/\/ \"ABC,DEF\" -> [\"ABC\", \"DEF\"]\n vecRow = sstd::split(\" ABC , D, EF ,GH \", ','); sstd::printn(vecRow); \/\/ \" ABC , D, EF ,GH \" -> [\"ABC\", \"D\", \"EF\", \"GH\"]\n}\n\n\/\/-----------------------------------------------------------------------------------------------------------------------------------------------\n\nTEST(strEdit, lstrip){\n std::string str_in = \" \\t abcd \\t \";\n std::string str_ans = \"abcd \\t \";\n ASSERT_TRUE(sstd::lstrip(str_in.c_str()) == str_ans);\n ASSERT_TRUE(sstd::lstrip(str_in ) == str_ans);\n}\nTEST(strEdit, lstrip_ow){\n std::string str_in = \" \\t abcd \\t \";\n std::string str_ans = \"abcd \\t \";\n sstd::lstrip_ow(str_in);\n ASSERT_TRUE(str_in == str_ans);\n}\nTEST(strEdit, rstrip){\n std::string str_in = \" \\t abcd \\t \";\n std::string str_ans = \" \\t abcd\";\n ASSERT_TRUE(sstd::rstrip(str_in.c_str()) == str_ans);\n ASSERT_TRUE(sstd::rstrip(str_in ) == str_ans);\n}\nTEST(strEdit, rstrip_ow){\n std::string str_in = \" \\t abcd \\t \";\n std::string str_ans = \" \\t abcd\";\n sstd::rstrip_ow(str_in);\n ASSERT_TRUE(str_in == str_ans);\n}\nTEST(strEdit, strip){\n std::string str_in = \" \\t abcd \\t \";\n std::string str_ans = \"abcd\";\n ASSERT_TRUE(sstd::strip(str_in.c_str()) == str_ans);\n ASSERT_TRUE(sstd::strip(str_in ) == str_ans);\n}\nTEST(strEdit, strip_ow){\n std::string str_in = \" \\t abcd \\t \";\n std::string str_ans = \"abcd\";\n sstd::strip_ow(str_in);\n ASSERT_TRUE(str_in == str_ans);\n}\nTEST(strEdit, strip_vec){\n std::vector vecStr_in = {\" \\t abcd01 \\t \", \" \\t abcd02 \\t \", \" \\t abcd03 \\t \"};\n std::vector vecStr_ans = {\"abcd01\", \"abcd02\", \"abcd03\"};\n ASSERT_TRUE(sstd::strip(vecStr_in) == vecStr_ans);\n}\n\n\/\/-----------------------------------------------------------------------------------------------------------------------------------------------\n\/*\n\/\/ 実装完了 (処理時間短縮のため,コメントアウト)\nTEST(strEdit, strIn){\n {\n std::string lhs = \"\";\n std::string rhs = \"\";\n bool ret=sstd::strIn(lhs, rhs); ASSERT_TRUE(ret);\n }\n {\n std::string lhs = \"ABCD\";\n std::string rhs = \"ABCDEFG\";\n bool ret=sstd::strIn(lhs, rhs); ASSERT_TRUE(ret);\n }\n {\n std::string lhs = \"BCD\";\n std::string rhs = \"ABCDEFG\";\n bool ret=sstd::strIn(lhs, rhs); ASSERT_TRUE(ret);\n }\n {\n std::string lhs = \"DEFG\";\n std::string rhs = \"ABCDEFG\";\n bool ret=sstd::strIn(lhs, rhs); ASSERT_TRUE(ret);\n }\n {\n std::string lhs = \"ABCDEFG\";\n std::string rhs = \"ABCDEFG\";\n bool ret=sstd::strIn(lhs, rhs); ASSERT_TRUE(ret);\n }\n {\n std::string lhs = \"AXCDEFG\";\n std::string rhs = \"ABCDEFG\";\n bool ret=sstd::strIn(lhs, rhs); ASSERT_TRUE(!ret);\n }\n}\n\/\/*\/\n\n\/\/-----------------------------------------------------------------------------------------------------------------------------------------------\n<|endoftext|>"} {"text":"\/* Copyright (c) 2008-2021 the MRtrix3 contributors.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * Covered Software is provided under this License on an \"as is\"\n * basis, without warranty of any kind, either expressed, implied, or\n * statutory, including, without limitation, warranties that the\n * Covered Software is free of defects, merchantable, fit for a\n * particular purpose or non-infringing.\n * See the Mozilla Public License v. 2.0 for more details.\n *\n * For more details, see http:\/\/www.mrtrix.org\/.\n *\/\n\n#include \"command.h\"\n#include \"progressbar.h\"\n#include \"math\/rng.h\"\n#include \"math\/SH.h\"\n#include \"dwi\/gradient.h\"\n#include \"dwi\/directions\/file.h\"\n\n#include \n#include \n\nusing namespace MR;\nusing namespace App;\n\nvoid usage ()\n{\n AUTHOR = \"J-Donald Tournier (jdtournier@gmail.com)\";\n\n SYNOPSIS = \"Reorder a set of directions to ensure near-uniformity upon truncation\";\n\n DESCRIPTION\n + \"The intent of this command is to reorder a set of gradient directions such that \"\n \"if a scan is terminated prematurely, at any point, the acquired directions will \"\n \"still be close to optimally distributed on the half-sphere.\";\n\n ARGUMENTS\n + Argument (\"input\", \"the input directions file\").type_file_in()\n + Argument (\"output\", \"the output directions file\").type_file_out();\n\n OPTIONS\n + Option (\"cartesian\", \"Output the directions in Cartesian coordinates [x y z] instead of [az el].\");\n}\n\n\n\nusing value_type = double;\n\n\n\nvector optimise (const Eigen::MatrixXd& directions, const size_t first_volume)\n{\n vector indices (1, first_volume);\n vector remaining;\n for (size_t n = 0; n < size_t(directions.rows()); ++n)\n if (n != indices[0])\n remaining.push_back (n);\n\n while (remaining.size()) {\n ssize_t best = 0;\n value_type best_E = std::numeric_limits::max();\n\n for (size_t n = 0; n < remaining.size(); ++n) {\n value_type E = 0.0;\n ssize_t a = remaining[n];\n for (size_t i = 0; i < indices.size(); ++i) {\n ssize_t b = indices[i];\n E += 1.0 \/ (directions.row(a) - directions.row(b)).norm();\n E += 1.0 \/ (directions.row(a) + directions.row(b)).norm();\n }\n if (E < best_E) {\n best_E = E;\n best = n;\n }\n }\n\n indices.push_back (remaining[best]);\n remaining.erase (remaining.begin()+best);\n }\n\n return indices;\n}\n\n\n\n\nvalue_type calc_cost (const Eigen::MatrixXd& directions, const vector& order)\n{\n const size_t start = Math::SH::NforL (2);\n if (directions.rows() <= start)\n return value_type(0);\n Eigen::MatrixXd subset (start, 3);\n for (size_t i = 0; i != start; ++i)\n subset.row(i) = directions.row(order[i]);\n value_type cost = value_type(0);\n for (size_t N = start+1; N < size_t(directions.rows()); ++N) {\n \/\/ Don't include condition numbers where precisely the number of coefficients\n \/\/ for that spherical harmonic degree are included, as these tend to\n \/\/ be outliers\n const size_t lmax = Math::SH::LforN (N-1);\n subset.conservativeResize (N, 3);\n subset.row(N-1) = directions.row(order[N-1]);\n const value_type cond = DWI::condition_number_for_lmax (subset, lmax);\n cost += cond;\n }\n return cost;\n}\n\n\n\n\nvoid run ()\n{\n auto directions = DWI::Directions::load_cartesian (argument[0]);\n\n size_t last_candidate_first_volume = directions.rows();\n if (directions.rows() <= Math::SH::NforL (2)) {\n WARN (\"Very few directions in input (\"\n + str(directions.rows())\n + \"); selection of first direction cannot be optimised\"\n + \" (first direction in input will be first direction in output)\");\n last_candidate_first_volume = 1;\n }\n\n value_type min_cost = std::numeric_limits::infinity();\n vector best_order;\n ProgressBar progress (\"Determining best reordering\", directions.rows());\n for (size_t first_volume = 0; first_volume != last_candidate_first_volume; ++first_volume) {\n const vector order = optimise (directions, first_volume);\n const value_type cost = calc_cost (directions, order);\n if (cost < min_cost) {\n min_cost = cost;\n best_order = order;\n }\n ++progress;\n }\n\n decltype(directions) output (directions.rows(), 3);\n for (ssize_t n = 0; n < directions.rows(); ++n)\n output.row(n) = directions.row (best_order[n]);\n\n DWI::Directions::save (output, argument[1], get_options(\"cartesian\").size());\n}\n\n\n\n\n\ndiroder: Fix compiler warning\/* Copyright (c) 2008-2021 the MRtrix3 contributors.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * Covered Software is provided under this License on an \"as is\"\n * basis, without warranty of any kind, either expressed, implied, or\n * statutory, including, without limitation, warranties that the\n * Covered Software is free of defects, merchantable, fit for a\n * particular purpose or non-infringing.\n * See the Mozilla Public License v. 2.0 for more details.\n *\n * For more details, see http:\/\/www.mrtrix.org\/.\n *\/\n\n#include \"command.h\"\n#include \"progressbar.h\"\n#include \"math\/rng.h\"\n#include \"math\/SH.h\"\n#include \"dwi\/gradient.h\"\n#include \"dwi\/directions\/file.h\"\n\n#include \n#include \n\nusing namespace MR;\nusing namespace App;\n\nvoid usage ()\n{\n AUTHOR = \"J-Donald Tournier (jdtournier@gmail.com)\";\n\n SYNOPSIS = \"Reorder a set of directions to ensure near-uniformity upon truncation\";\n\n DESCRIPTION\n + \"The intent of this command is to reorder a set of gradient directions such that \"\n \"if a scan is terminated prematurely, at any point, the acquired directions will \"\n \"still be close to optimally distributed on the half-sphere.\";\n\n ARGUMENTS\n + Argument (\"input\", \"the input directions file\").type_file_in()\n + Argument (\"output\", \"the output directions file\").type_file_out();\n\n OPTIONS\n + Option (\"cartesian\", \"Output the directions in Cartesian coordinates [x y z] instead of [az el].\");\n}\n\n\n\nusing value_type = double;\n\n\n\nvector optimise (const Eigen::MatrixXd& directions, const size_t first_volume)\n{\n vector indices (1, first_volume);\n vector remaining;\n for (size_t n = 0; n < size_t(directions.rows()); ++n)\n if (n != indices[0])\n remaining.push_back (n);\n\n while (remaining.size()) {\n ssize_t best = 0;\n value_type best_E = std::numeric_limits::max();\n\n for (size_t n = 0; n < remaining.size(); ++n) {\n value_type E = 0.0;\n ssize_t a = remaining[n];\n for (size_t i = 0; i < indices.size(); ++i) {\n ssize_t b = indices[i];\n E += 1.0 \/ (directions.row(a) - directions.row(b)).norm();\n E += 1.0 \/ (directions.row(a) + directions.row(b)).norm();\n }\n if (E < best_E) {\n best_E = E;\n best = n;\n }\n }\n\n indices.push_back (remaining[best]);\n remaining.erase (remaining.begin()+best);\n }\n\n return indices;\n}\n\n\n\n\nvalue_type calc_cost (const Eigen::MatrixXd& directions, const vector& order)\n{\n const size_t start = Math::SH::NforL (2);\n if (size_t(directions.rows()) <= start)\n return value_type(0);\n Eigen::MatrixXd subset (start, 3);\n for (size_t i = 0; i != start; ++i)\n subset.row(i) = directions.row(order[i]);\n value_type cost = value_type(0);\n for (size_t N = start+1; N < size_t(directions.rows()); ++N) {\n \/\/ Don't include condition numbers where precisely the number of coefficients\n \/\/ for that spherical harmonic degree are included, as these tend to\n \/\/ be outliers\n const size_t lmax = Math::SH::LforN (N-1);\n subset.conservativeResize (N, 3);\n subset.row(N-1) = directions.row(order[N-1]);\n const value_type cond = DWI::condition_number_for_lmax (subset, lmax);\n cost += cond;\n }\n return cost;\n}\n\n\n\n\nvoid run ()\n{\n auto directions = DWI::Directions::load_cartesian (argument[0]);\n\n size_t last_candidate_first_volume = directions.rows();\n if (size_t(directions.rows()) <= Math::SH::NforL (2)) {\n WARN (\"Very few directions in input (\"\n + str(directions.rows())\n + \"); selection of first direction cannot be optimised\"\n + \" (first direction in input will be first direction in output)\");\n last_candidate_first_volume = 1;\n }\n\n value_type min_cost = std::numeric_limits::infinity();\n vector best_order;\n ProgressBar progress (\"Determining best reordering\", directions.rows());\n for (size_t first_volume = 0; first_volume != last_candidate_first_volume; ++first_volume) {\n const vector order = optimise (directions, first_volume);\n const value_type cost = calc_cost (directions, order);\n if (cost < min_cost) {\n min_cost = cost;\n best_order = order;\n }\n ++progress;\n }\n\n decltype(directions) output (directions.rows(), 3);\n for (ssize_t n = 0; n < directions.rows(); ++n)\n output.row(n) = directions.row (best_order[n]);\n\n DWI::Directions::save (output, argument[1], get_options(\"cartesian\").size());\n}\n\n\n\n\n\n<|endoftext|>"} {"text":"\/\/ ======================================================================== \/\/\n\/\/ Copyright 2009-2017 Intel Corporation \/\/\n\/\/ \/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\"); \/\/\n\/\/ you may not use this file except in compliance with the License. \/\/\n\/\/ You may obtain a copy of the License at \/\/\n\/\/ \/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0 \/\/\n\/\/ \/\/\n\/\/ Unless required by applicable law or agreed to in writing, software \/\/\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS, \/\/\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. \/\/\n\/\/ See the License for the specific language governing permissions and \/\/\n\/\/ limitations under the License. \/\/\n\/\/ ======================================================================== \/\/\n\n\/\/ own\n#include \"Importer.h\"\n\/\/ ospcommon\n#include \"ospcommon\/FileName.h\"\n\/\/ tinyxml\n#include \"TinyXML2.h\"\n\/\/ std\n#include \n\nnamespace ospray {\n namespace importer {\n\n void importVolumeRAW(const FileName &fileName, Volume *volume);\n void importVolumeRM(const FileName &fileName, Volume *volume);\n\n void importVolume(const FileName &fileName, Volume *volume)\n {\n const std::string ext = fileName.ext();\n if (ext == \"raw\" || ext == \"gz\") {\n importVolumeRAW(fileName, volume);\n } else if (ext == \"bob\") {\n importVolumeRM(fileName, volume);\n } else {\n throw std::runtime_error(\"unknown volume format '\"+ext+\"'\");\n }\n\n \/\/ post-checks\n assert(volume->handle != nullptr);\n assert(!volume->bounds.empty());\n }\n\n vec2i parseInt2(const tinyxml2::XMLNode *node)\n {\n vec2i v;\n int rc = sscanf(node->ToElement()->GetText(),\"%i %i\",&v.x,&v.y);\n (void)rc;\n assert(rc == 2);\n return v;\n }\n vec3i parseInt3(const tinyxml2::XMLNode *node)\n {\n vec3i v;\n int rc = sscanf(node->ToElement()->GetText(),\"%i %i %i\",&v.x,&v.y,&v.z);\n (void)rc;\n assert(rc == 3);\n return v;\n }\n\n float parseFloat1(const tinyxml2::XMLNode *node)\n {\n float v;\n int rc = sscanf(node->ToElement()->GetText(),\"%f\",&v);\n (void)rc;\n assert(rc == 1);\n return v;\n }\n vec2f parseFloat2(const tinyxml2::XMLNode *node)\n {\n vec2f v;\n int rc = sscanf(node->ToElement()->GetText(),\"%f %f\",&v.x,&v.y);\n (void)rc;\n assert(rc == 2);\n return v;\n }\n vec3f parseFloat3(const tinyxml2::XMLNode *node)\n {\n vec3f v;\n int rc = sscanf(node->ToElement()->GetText(),\"%f %f %f\",&v.x,&v.y,&v.z);\n (void)rc;\n assert(rc == 3);\n return v;\n }\n\n void importVolume(const FileName &orgFileName,\n Group *group,\n const tinyxml2::XMLNode *root)\n {\n auto dpFromEnv = getEnvVar(\"OSPRAY_DATA_PARALLEL\");\n \n Volume *volume = new Volume;\n if (dpFromEnv.first) {\n \/\/ Create the OSPRay object.\n osp::vec3i blockDims;\n int rc = sscanf(dpFromEnv.second.c_str(), \"%dx%dx%d\",\n &blockDims.x, &blockDims.y, &blockDims.z);\n if (rc != 3) {\n throw std::runtime_error(\"could not parse OSPRAY_DATA_PARALLEL \"\n \"env-var. Must be of format xx<>Z \"\n \"(e.g., '4x4x4'\");\n }\n volume->handle = ospNewVolume(\"data_distributed_volume\");\n if (volume->handle == nullptr) {\n throw std::runtime_error(\"#loaders.ospObjectFile: could not create \"\n \"volume ...\");\n }\n ospSetVec3i(volume->handle, \"num_dp_blocks\", blockDims);\n } else {\n \/\/ Create the OSPRay object.\n std::string volumeType = \"block_bricked_volume\";\n\n auto volTypeFromEnv = getEnvVar(\"OSPRAY_USE_VOLUME_TYPE\");\n if (volTypeFromEnv.first)\n volumeType = volTypeFromEnv.second;\n\n volume->handle = ospNewVolume(volumeType.c_str());\n }\n\n if (volume->handle == nullptr) {\n throw std::runtime_error(\"#loaders.ospObjectFile: could not create \"\n \"volume ...\");\n }\n \n \/\/ Temporary storage for the file name attribute if specified.\n const char *volumeFilename = nullptr;\n \n \/\/ Iterate over object attributes.\n for (const tinyxml2::XMLNode *node = root->FirstChild();\n node;\n node = node->NextSibling()) {\n \n \/\/ Volume size in voxels per dimension.\n if (!strcmp(node->ToElement()->Name(), \"dimensions\")) {\n volume->dimensions = parseInt3(node);\n continue;\n }\n \n \/\/ File containing a volume specification and \/ or voxel data.\n if (!strcmp(node->ToElement()->Name(), \"filename\")) {\n volumeFilename = node->ToElement()->GetText();\n continue;\n }\n \n \/\/ Grid origin in world coordinates.\n if (!strcmp(node->ToElement()->Name(), \"gridOrigin\")) {\n volume->gridOrigin = parseFloat3(node);\n ospSetVec3f(volume->handle, \"gridOrigin\", (osp::vec3f&)volume->gridOrigin);\n continue;\n }\n \n \/\/ Grid spacing in each dimension in world coordinates.\n if (!strcmp(node->ToElement()->Name(), \"gridSpacing\")) {\n volume->gridSpacing = parseFloat3(node);\n ospSetVec3f(volume->handle, \"gridSpacing\", (osp::vec3f&)volume->gridSpacing);\n continue;\n }\n \n \/\/ Sampling rate for ray casting based renderers.\n if (!strcmp(node->ToElement()->Name(), \"samplingRate\")) {\n volume->samplingRate = parseFloat1(node);\n ospSet1f(volume->handle, \"samplingRate\", volume->samplingRate);\n continue;\n }\n\n \/\/ Volume scale factor.\n if (!strcmp(node->ToElement()->Name(), \"scaleFactor\")) {\n volume->scaleFactor = parseFloat3(node);\n std::cout << \"Got scaleFactor = \" << volume->scaleFactor << std::endl;\n ospSetVec3f(volume->handle, \"scaleFactor\", (osp::vec3f&)volume->scaleFactor);\n continue;\n }\n \n \/\/ Subvolume offset from origin within the full volume.\n if (!strcmp(node->ToElement()->Name(), \"subvolumeOffsets\")) {\n volume->subVolumeOffsets = parseInt3(node);\n continue;\n }\n \n \/\/ Subvolume dimensions within the full volume.\n if (!strcmp(node->ToElement()->Name(), \"subvolumeDimensions\")) {\n volume->subVolumeDimensions = parseInt3(node);\n continue;\n }\n \n \/\/ Subvolume steps in each dimension; can be used to subsample.\n if (!strcmp(node->ToElement()->Name(), \"subvolumeSteps\")) {\n volume->subVolumeSteps = parseInt3(node);\n continue;\n }\n \n \/\/ Voxel value range.\n if (!strcmp(node->ToElement()->Name(), \"voxelRange\")) {\n volume->voxelRange = parseFloat2(node);\n continue;\n }\n \n \/\/ Voxel type string.\n if (!strcmp(node->ToElement()->Name(), \"voxelType\")) {\n volume->voxelType = node->ToElement()->GetText();\n continue;\n }\n \n \/\/ Error check.\n exitOnCondition(true, \"unrecognized XML element type '\" + \n std::string(node->ToElement()->Name()) + \"'\");\n }\n \n \/\/ Load the contents of the volume file if specified.\n if (volumeFilename != nullptr) {\n \/\/ The volume file path is absolute.\n if (volumeFilename[0] == '\/') \n importVolume(volumeFilename, volume);\n else {\n importVolume((orgFileName.path().str()\n + \"\/\" + volumeFilename).c_str(), volume);\n }\n }\n \n group->volume.push_back(volume);\n }\n \n void importTriangleMesh(Group *group, const tinyxml2::XMLNode *node)\n {\n throw std::runtime_error(\"importTriangleMesh: not yet implemented\");\n }\n\n void importLight(Group *group, const tinyxml2::XMLNode *node)\n {\n throw std::runtime_error(\"importLight: not yet implemented\");\n }\n \n void importObject(const FileName &orgFileName,\n Group *group,\n const tinyxml2::XMLNode *node)\n {\n \/\/ OSPRay light object.\n if (!strcmp(node->ToElement()->Name(), \"light\")) \n importLight(group,node);\n \n \/\/ OSPRay triangle mesh object.\n else if (!strcmp(node->ToElement()->Name(), \"triangleMesh\")) \n importTriangleMesh(group,node);\n \n \/\/ OSPRay volume object.\n else if (!strcmp(node->ToElement()->Name(), \"volume\")) \n importVolume(orgFileName,group,node);\n \n \/\/ No other object types are currently supported.\n else \n exitOnCondition(true, \"unrecognized XML element type '\" \n + std::string(node->ToElement()->Name()) + \"'\"); \n }\n\n void importOSP(const FileName &fileName, Group *existingGroupToAddTo)\n {\n \/\/ The XML document container.\n tinyxml2::XMLDocument xml(true, tinyxml2::COLLAPSE_WHITESPACE);\n \n \/\/ Read the XML object file.\n exitOnCondition(xml.LoadFile(fileName.str().c_str()) != tinyxml2::XML_SUCCESS, \n \"unable to read object file '\" + fileName.str() + \"'\");\n \n Group *group = existingGroupToAddTo ? existingGroupToAddTo : new Group;\n\n \/\/ Iterate over the object entries, skip the XML declaration and comments.\n for (const tinyxml2::XMLNode *node = xml.FirstChild();\n node;\n node = node->NextSibling()) {\n if (node->ToElement()) \n importObject(fileName,group,node); \n }\n\n \/\/ post-checks:\n for (size_t i = 0; i < group->volume.size(); i++) {\n assert(group->volume[i]->handle != nullptr);\n assert(!group->volume[i]->bounds.empty());\n }\n }\n }\n}\nWorks on mac\/\/ ======================================================================== \/\/\n\/\/ Copyright 2009-2017 Intel Corporation \/\/\n\/\/ \/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\"); \/\/\n\/\/ you may not use this file except in compliance with the License. \/\/\n\/\/ You may obtain a copy of the License at \/\/\n\/\/ \/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0 \/\/\n\/\/ \/\/\n\/\/ Unless required by applicable law or agreed to in writing, software \/\/\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS, \/\/\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. \/\/\n\/\/ See the License for the specific language governing permissions and \/\/\n\/\/ limitations under the License. \/\/\n\/\/ ======================================================================== \/\/\n\n\/\/ own\n#include \"Importer.h\"\n\/\/ ospcommon\n#include \"ospcommon\/FileName.h\"\n\/\/ tinyxml\n#include \"TinyXML2.h\"\n\/\/ std\n#include \n\nnamespace ospray {\n namespace importer {\n\n void importVolumeRAW(const FileName &fileName, Volume *volume);\n void importVolumeRM(const FileName &fileName, Volume *volume);\n\n void importVolume(const FileName &fileName, Volume *volume)\n {\n const std::string ext = fileName.ext();\n if (ext == \"raw\" || ext == \"gz\") {\n importVolumeRAW(fileName, volume);\n } else if (ext == \"bob\") {\n importVolumeRM(fileName, volume);\n } else {\n throw std::runtime_error(\"unknown volume format '\"+ext+\"'\");\n }\n\n \/\/ post-checks\n assert(volume->handle != nullptr);\n assert(!volume->bounds.empty());\n }\n\n vec2i parseInt2(const tinyxml2::XMLNode *node)\n {\n vec2i v;\n int rc = sscanf(node->ToElement()->GetText(),\"%i %i\",&v.x,&v.y);\n (void)rc;\n assert(rc == 2);\n return v;\n }\n vec3i parseInt3(const tinyxml2::XMLNode *node)\n {\n vec3i v;\n int rc = sscanf(node->ToElement()->GetText(),\"%i %i %i\",&v.x,&v.y,&v.z);\n (void)rc;\n assert(rc == 3);\n return v;\n }\n\n float parseFloat1(const tinyxml2::XMLNode *node)\n {\n float v;\n int rc = sscanf(node->ToElement()->GetText(),\"%f\",&v);\n (void)rc;\n assert(rc == 1);\n return v;\n }\n vec2f parseFloat2(const tinyxml2::XMLNode *node)\n {\n vec2f v;\n int rc = sscanf(node->ToElement()->GetText(),\"%f %f\",&v.x,&v.y);\n (void)rc;\n assert(rc == 2);\n return v;\n }\n vec3f parseFloat3(const tinyxml2::XMLNode *node)\n {\n vec3f v;\n int rc = sscanf(node->ToElement()->GetText(),\"%f %f %f\",&v.x,&v.y,&v.z);\n (void)rc;\n assert(rc == 3);\n return v;\n }\n\n void importVolume(const FileName &orgFileName,\n Group *group,\n const tinyxml2::XMLNode *root)\n {\n auto dpFromEnv = std::make_pair(false, std::string());\/\/getEnvVar(\"OSPRAY_DATA_PARALLEL\");\n\n Volume *volume = new Volume;\n if (dpFromEnv.first) {\n \/\/ Create the OSPRay object.\n osp::vec3i blockDims;\n int rc = sscanf(dpFromEnv.second.c_str(), \"%dx%dx%d\",\n &blockDims.x, &blockDims.y, &blockDims.z);\n if (rc != 3) {\n throw std::runtime_error(\"could not parse OSPRAY_DATA_PARALLEL \"\n \"env-var. Must be of format xx<>Z \"\n \"(e.g., '4x4x4'\");\n }\n volume->handle = ospNewVolume(\"data_distributed_volume\");\n if (volume->handle == nullptr) {\n throw std::runtime_error(\"#loaders.ospObjectFile: could not create \"\n \"volume ...\");\n }\n ospSetVec3i(volume->handle, \"num_dp_blocks\", blockDims);\n } else {\n \/\/ Create the OSPRay object.\n std::string volumeType = \"block_bricked_volume\";\n\n auto volTypeFromEnv = std::make_pair(false, std::string());\/\/getEnvVar(\"OSPRAY_USE_VOLUME_TYPE\");\n if (volTypeFromEnv.first)\n volumeType = volTypeFromEnv.second;\n\n volume->handle = ospNewVolume(volumeType.c_str());\n }\n\n if (volume->handle == nullptr) {\n throw std::runtime_error(\"#loaders.ospObjectFile: could not create \"\n \"volume ...\");\n }\n\n \/\/ Temporary storage for the file name attribute if specified.\n const char *volumeFilename = nullptr;\n\n \/\/ Iterate over object attributes.\n for (const tinyxml2::XMLNode *node = root->FirstChild();\n node;\n node = node->NextSibling()) {\n\n \/\/ Volume size in voxels per dimension.\n if (!strcmp(node->ToElement()->Name(), \"dimensions\")) {\n volume->dimensions = parseInt3(node);\n continue;\n }\n\n \/\/ File containing a volume specification and \/ or voxel data.\n if (!strcmp(node->ToElement()->Name(), \"filename\")) {\n volumeFilename = node->ToElement()->GetText();\n continue;\n }\n\n \/\/ Grid origin in world coordinates.\n if (!strcmp(node->ToElement()->Name(), \"gridOrigin\")) {\n volume->gridOrigin = parseFloat3(node);\n ospSetVec3f(volume->handle, \"gridOrigin\", (osp::vec3f&)volume->gridOrigin);\n continue;\n }\n\n \/\/ Grid spacing in each dimension in world coordinates.\n if (!strcmp(node->ToElement()->Name(), \"gridSpacing\")) {\n volume->gridSpacing = parseFloat3(node);\n ospSetVec3f(volume->handle, \"gridSpacing\", (osp::vec3f&)volume->gridSpacing);\n continue;\n }\n\n \/\/ Sampling rate for ray casting based renderers.\n if (!strcmp(node->ToElement()->Name(), \"samplingRate\")) {\n volume->samplingRate = parseFloat1(node);\n ospSet1f(volume->handle, \"samplingRate\", volume->samplingRate);\n continue;\n }\n\n \/\/ Volume scale factor.\n if (!strcmp(node->ToElement()->Name(), \"scaleFactor\")) {\n volume->scaleFactor = parseFloat3(node);\n std::cout << \"Got scaleFactor = \" << volume->scaleFactor << std::endl;\n ospSetVec3f(volume->handle, \"scaleFactor\", (osp::vec3f&)volume->scaleFactor);\n continue;\n }\n\n \/\/ Subvolume offset from origin within the full volume.\n if (!strcmp(node->ToElement()->Name(), \"subvolumeOffsets\")) {\n volume->subVolumeOffsets = parseInt3(node);\n continue;\n }\n\n \/\/ Subvolume dimensions within the full volume.\n if (!strcmp(node->ToElement()->Name(), \"subvolumeDimensions\")) {\n volume->subVolumeDimensions = parseInt3(node);\n continue;\n }\n\n \/\/ Subvolume steps in each dimension; can be used to subsample.\n if (!strcmp(node->ToElement()->Name(), \"subvolumeSteps\")) {\n volume->subVolumeSteps = parseInt3(node);\n continue;\n }\n\n \/\/ Voxel value range.\n if (!strcmp(node->ToElement()->Name(), \"voxelRange\")) {\n volume->voxelRange = parseFloat2(node);\n continue;\n }\n\n \/\/ Voxel type string.\n if (!strcmp(node->ToElement()->Name(), \"voxelType\")) {\n volume->voxelType = node->ToElement()->GetText();\n continue;\n }\n\n \/\/ Error check.\n exitOnCondition(true, \"unrecognized XML element type '\" +\n std::string(node->ToElement()->Name()) + \"'\");\n }\n\n \/\/ Load the contents of the volume file if specified.\n if (volumeFilename != nullptr) {\n \/\/ The volume file path is absolute.\n if (volumeFilename[0] == '\/')\n importVolume(volumeFilename, volume);\n else {\n importVolume((orgFileName.path()\n + \"\/\" + volumeFilename).c_str(), volume);\n }\n }\n\n group->volume.push_back(volume);\n }\n\n void importTriangleMesh(Group *group, const tinyxml2::XMLNode *node)\n {\n throw std::runtime_error(\"importTriangleMesh: not yet implemented\");\n }\n\n void importLight(Group *group, const tinyxml2::XMLNode *node)\n {\n throw std::runtime_error(\"importLight: not yet implemented\");\n }\n\n void importObject(const FileName &orgFileName,\n Group *group,\n const tinyxml2::XMLNode *node)\n {\n \/\/ OSPRay light object.\n if (!strcmp(node->ToElement()->Name(), \"light\"))\n importLight(group,node);\n\n \/\/ OSPRay triangle mesh object.\n else if (!strcmp(node->ToElement()->Name(), \"triangleMesh\"))\n importTriangleMesh(group,node);\n\n \/\/ OSPRay volume object.\n else if (!strcmp(node->ToElement()->Name(), \"volume\"))\n importVolume(orgFileName,group,node);\n\n \/\/ No other object types are currently supported.\n else\n exitOnCondition(true, \"unrecognized XML element type '\"\n + std::string(node->ToElement()->Name()) + \"'\");\n }\n\n void importOSP(const FileName &fileName, Group *existingGroupToAddTo)\n {\n \/\/ The XML document container.\n tinyxml2::XMLDocument xml(true, tinyxml2::COLLAPSE_WHITESPACE);\n\n \/\/ Read the XML object file.\n exitOnCondition(xml.LoadFile(fileName.str().c_str()) != tinyxml2::XML_SUCCESS,\n \"unable to read object file '\" + fileName.str() + \"'\");\n\n Group *group = existingGroupToAddTo ? existingGroupToAddTo : new Group;\n\n \/\/ Iterate over the object entries, skip the XML declaration and comments.\n for (const tinyxml2::XMLNode *node = xml.FirstChild();\n node;\n node = node->NextSibling()) {\n if (node->ToElement())\n importObject(fileName,group,node);\n }\n\n \/\/ post-checks:\n for (size_t i = 0; i < group->volume.size(); i++) {\n assert(group->volume[i]->handle != nullptr);\n assert(!group->volume[i]->bounds.empty());\n }\n }\n }\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \"synthetic.hpp\"\n#include \"network.hpp\"\n#include \"tclap\/ValueArg.h\"\n\nWARPED_REGISTER_POLYMORPHIC_SERIALIZABLE_CLASS(InternalEvent)\nWARPED_REGISTER_POLYMORPHIC_SERIALIZABLE_CLASS(ExternalEvent)\n\ninline std::string Node::lpName(const unsigned int lp_index) {\n\n return std::string(\"Node_\") + std::to_string(lp_index);\n}\n\nstd::vector > Node::initializeLP() {\n\n std::vector > events;\n\n \/* Register random number generator *\/\n registerRNG(rng_);\n\n for (unsigned int i = 0; i < num_nodes_; i++) {\n unsigned int time = send_distribution_->nextTimeDelta(*rng_);\n events.emplace_back(new InternalEvent {time});\n }\n return events;\n}\n\nstd::vector > Node::receiveEvent(const warped::Event& event) {\n\n std::vector > response_events;\n assert (event.sender_name_ == event.receiverName());\n#if 0\n std::exponential_distribution time_expo(1.0\/mean_time_);\n std::uniform_int_distribution ext_node(0, adjacency_list_.size()-1);\n\n \/* Check if event received is a self\/internal timer event *\/\n if (event.sender_name_ == event.receiverName()) {\n\n \/* Restart the timer\/internal event *\/\n unsigned int time = (unsigned int)std::ceil(time_expo(*rng_));\n response_events.emplace_back(new InternalEvent {time});\n\n \/* Send an external event to one of the nodes in its adjacency list *\/\n auto id = (unsigned int) ext_node(*rng_);\n response_events.emplace_back(\n new ExternalEvent { adjacency_list_[id],\n 1,\n time });\n\n } else { \/* Event received from other LPs\/nodes *\/\n\n }\n#endif\n return response_events;\n}\n\nint main(int argc, const char** argv) {\n\n unsigned int num_nodes = 100000;\n std::string network = \"Watts-Strogatz,30,0.1\";\n std::string node_selection = \"exponential,3.5\";\n std::string event_processing_time = \"1000,1000\";\n std::string state_size = \"100,100\";\n std::string event_send = \"geometric,0.5,10\";\n\n TCLAP::ValueArg num_nodes_arg(\"n\", \"num-nodes\",\n \"Number of nodes\", false, num_nodes, \"unsigned int\");\n TCLAP::ValueArg network_arg(\"t\", \"network-params\",\n \"Network details - \", false, network, \"string\");\n TCLAP::ValueArg node_selection_arg(\"o\", \"node-selection-params\",\n \"Node selection details - >\",\n false, node_selection, \"string\");\n TCLAP::ValueArg event_processing_time_arg(\"e\", \"event-processing-time-range\",\n \"Event processing time (as floating-point calculation count) range - \",\n false, event_processing_time, \"string\");\n TCLAP::ValueArg state_size_arg(\"s\", \"state-size-range\",\n \"Size range (in bytes) for the LP state - \",\n false, state_size, \"string\");\n TCLAP::ValueArg event_send_arg(\"p\", \"send-params\",\n \"Event send details - ,ceiling-value>\",\n \"false\", event_send, \"string\");\n\n std::vector args = { &num_nodes_arg,\n &network_arg,\n &node_selection_arg,\n &event_processing_time_arg,\n &state_size_arg,\n &event_send_arg\n };\n\n warped::Simulation synthetic_sim {\"Synthetic Simulation\", argc, argv, args};\n\n num_nodes = num_nodes_arg.getValue();\n network = network_arg.getValue();\n node_selection = node_selection_arg.getValue();\n event_processing_time = event_processing_time_arg.getValue();\n state_size = state_size_arg.getValue();\n event_send = event_send_arg.getValue();\n\n std::vector lps;\n std::vector lp_names;\n\n \/* Create uniform distribution for event processing time *\/\n std::string delimiter = \",\";\n size_t pos = event_processing_time.find(delimiter);\n unsigned int min_processing_time =\n (unsigned int) std::stoul(event_processing_time.substr(0, pos));\n unsigned int max_processing_time =\n (unsigned int) std::stoul(event_processing_time.substr(pos+1));\n std::uniform_int_distribution\n event_processing_time_dist( min_processing_time, max_processing_time );\n\n \/* Create uniform distribution for the state size *\/\n pos = state_size.find(delimiter);\n unsigned int min_state_size = (unsigned int) std::stoul(state_size.substr(0, pos));\n unsigned int max_state_size = (unsigned int) std::stoul(state_size.substr(pos+1));\n std::uniform_int_distribution\n state_size_dist( min_state_size, max_state_size );\n\n \/* Create the LPs *\/\n std::default_random_engine generator (num_nodes);\n for (unsigned int i = 0; i < num_nodes; i++) {\n auto name = Node::lpName(i);\n lp_names.push_back(name);\n lps.emplace_back( name,\n num_nodes,\n event_processing_time_dist(generator),\n state_size_dist(generator),\n i\n );\n }\n\n std::vector lp_pointers;\n for (auto& lp : lps) {\n lp_pointers.push_back(&lp);\n }\n\n \/* Create the Network *\/\n Network *ntwrk = nullptr;\n pos = network.find(delimiter);\n std::string type = network.substr(0, pos);\n network.erase(0, pos + delimiter.length());\n if (type == \"Watts-Strogatz\") { \/\/ If the choice is Watts-Strogatz\n pos = network.find(delimiter);\n std::string token = network.substr(0, pos);\n unsigned int k = (unsigned int) std::stoul(token);\n network.erase(0, pos + delimiter.length());\n double beta = std::stod(network);\n ntwrk = new WattsStrogatz(lp_names, k, beta);\n\n } else if (type == \"Barabasi-Albert\") { \/\/ If the choice is Barabasi-Albert\n pos = network.find(delimiter);\n std::string token = network.substr(0, pos);\n unsigned int m = (unsigned int) std::stoul(token);\n network.erase(0, pos + delimiter.length());\n double a = std::stod(network);\n ntwrk = new BarabasiAlbert(lp_names, m, a);\n\n } else { \/\/ Invalid choice\n std::cerr << \"Invalid choice of network.\" << std::endl;\n abort();\n }\n\n \/* Parse the event send distribution type and parameters *\/\n pos = event_send.find(delimiter);\n std::string distribution_type = event_send.substr(0, pos);\n event_send.erase(0, pos + delimiter.length());\n\n for (auto& lp : lps) {\n\n \/* Create the send time distributions *\/\n if (distribution_type == \"geometric\") {\n lp.send_distribution_ = new Geometric(event_send);\n\n } else if (distribution_type == \"exponential\") {\n lp.send_distribution_ = new Exponential(event_send);\n\n } else if (distribution_type == \"binomial\") {\n lp.send_distribution_ = new Binomial(event_send);\n\n } else {\n std::cerr << \"Invalid choice of event send distribution.\" << std::endl;\n abort();\n }\n\n \/* Fetch the adjacency list for each node *\/\n lp.adjacency_list_ = ntwrk->adjacencyList(lp.name_);\n assert(lp.adjacency_list_.size());\n }\n delete ntwrk;\n\n \/* Parse the node selection distribution type and parameters *\/\n pos = node_selection.find(delimiter);\n distribution_type = node_selection.substr(0, pos);\n node_selection.erase(0, pos + delimiter.length());\n\n for (auto& lp : lps) {\n node_selection += \",\" + lp.adjacency_list_.size();\n\n \/* Create the node selection distributions *\/\n if (distribution_type == \"geometric\") {\n lp.node_sel_distribution_ = new Geometric(node_selection);\n\n } else if (distribution_type == \"exponential\") {\n lp.node_sel_distribution_ = new Exponential(node_selection);\n\n } else if (distribution_type == \"binomial\") {\n lp.node_sel_distribution_ = new Binomial(node_selection);\n\n } else {\n std::cerr << \"Invalid choice of node select distribution.\" << std::endl;\n abort();\n }\n }\n\n \/* Simulate the synthetic model *\/\n synthetic_sim.simulate(lp_pointers);\n\n return 0;\n}\n\ncompleted receiveEvent()#include \n#include \n#include \"synthetic.hpp\"\n#include \"network.hpp\"\n#include \"tclap\/ValueArg.h\"\n\nWARPED_REGISTER_POLYMORPHIC_SERIALIZABLE_CLASS(InternalEvent)\nWARPED_REGISTER_POLYMORPHIC_SERIALIZABLE_CLASS(ExternalEvent)\n\ninline std::string Node::lpName(const unsigned int lp_index) {\n\n return std::string(\"Node_\") + std::to_string(lp_index);\n}\n\nstd::vector > Node::initializeLP() {\n\n std::vector > events;\n\n \/* Register random number generator *\/\n registerRNG(rng_);\n\n for (unsigned int i = 0; i < num_nodes_; i++) {\n unsigned int time = send_distribution_->nextTimeDelta(*rng_);\n events.emplace_back(new InternalEvent {time});\n }\n return events;\n}\n\nstd::vector > Node::receiveEvent(const warped::Event& event) {\n\n std::vector > response_events;\n\n \/* Register random number generator *\/\n registerRNG(rng_);\n\n \/* Check if event received is a self\/internal timer event *\/\n if (event.sender_name_ == event.receiverName()) {\n\n \/* Restart the processing_timer\/internal event *\/\n unsigned int processing_time = send_distribution_->nextTimeDelta(*rng_);\n response_events.emplace_back(new InternalEvent {processing_time});\n\n \/* Send an external event to one of the nodes in its adjacency list *\/\n\n \/* selecting node using distribution *\/\n auto id = (unsigned int) node_sel_distribution_->nextTimeDelta(*rng_);\n\n \/* Restart the timer\/external event *\/\n unsigned int ts = send_distribution_->nextTimeDelta(*rng_);\n\n response_events.emplace_back(\n new ExternalEvent { adjacency_list_[id],\n processing_time,\n ts });\n\n } else { \/* Event received from other LPs\/nodes *\/\n\n }\n return response_events;\n}\n\nint main(int argc, const char** argv) {\n\n unsigned int num_nodes = 100000;\n std::string network = \"Watts-Strogatz,30,0.1\";\n std::string node_selection = \"exponential,3.5\";\n std::string event_processing_time = \"1000,1000\";\n std::string state_size = \"100,100\";\n std::string event_send = \"geometric,0.5,10\";\n\n TCLAP::ValueArg num_nodes_arg(\"n\", \"num-nodes\",\n \"Number of nodes\", false, num_nodes, \"unsigned int\");\n TCLAP::ValueArg network_arg(\"t\", \"network-params\",\n \"Network details - \", false, network, \"string\");\n TCLAP::ValueArg node_selection_arg(\"o\", \"node-selection-params\",\n \"Node selection details - >\",\n false, node_selection, \"string\");\n TCLAP::ValueArg event_processing_time_arg(\"e\", \"event-processing-time-range\",\n \"Event processing time (as floating-point calculation count) range - \",\n false, event_processing_time, \"string\");\n TCLAP::ValueArg state_size_arg(\"s\", \"state-size-range\",\n \"Size range (in bytes) for the LP state - \",\n false, state_size, \"string\");\n TCLAP::ValueArg event_send_arg(\"p\", \"send-params\",\n \"Event send details - ,ceiling-value>\",\n \"false\", event_send, \"string\");\n\n std::vector args = { &num_nodes_arg,\n &network_arg,\n &node_selection_arg,\n &event_processing_time_arg,\n &state_size_arg,\n &event_send_arg\n };\n\n warped::Simulation synthetic_sim {\"Synthetic Simulation\", argc, argv, args};\n\n num_nodes = num_nodes_arg.getValue();\n network = network_arg.getValue();\n node_selection = node_selection_arg.getValue();\n event_processing_time = event_processing_time_arg.getValue();\n state_size = state_size_arg.getValue();\n event_send = event_send_arg.getValue();\n\n std::vector lps;\n std::vector lp_names;\n\n \/* Create uniform distribution for event processing time *\/\n std::string delimiter = \",\";\n size_t pos = event_processing_time.find(delimiter);\n unsigned int min_processing_time =\n (unsigned int) std::stoul(event_processing_time.substr(0, pos));\n unsigned int max_processing_time =\n (unsigned int) std::stoul(event_processing_time.substr(pos+1));\n std::uniform_int_distribution\n event_processing_time_dist( min_processing_time, max_processing_time );\n\n \/* Create uniform distribution for the state size *\/\n pos = state_size.find(delimiter);\n unsigned int min_state_size = (unsigned int) std::stoul(state_size.substr(0, pos));\n unsigned int max_state_size = (unsigned int) std::stoul(state_size.substr(pos+1));\n std::uniform_int_distribution\n state_size_dist( min_state_size, max_state_size );\n\n \/* Create the LPs *\/\n std::default_random_engine generator (num_nodes);\n for (unsigned int i = 0; i < num_nodes; i++) {\n auto name = Node::lpName(i);\n lp_names.push_back(name);\n lps.emplace_back( name,\n num_nodes,\n event_processing_time_dist(generator),\n state_size_dist(generator),\n i\n );\n }\n\n std::vector lp_pointers;\n for (auto& lp : lps) {\n lp_pointers.push_back(&lp);\n }\n\n \/* Create the Network *\/\n Network *ntwrk = nullptr;\n pos = network.find(delimiter);\n std::string type = network.substr(0, pos);\n network.erase(0, pos + delimiter.length());\n if (type == \"Watts-Strogatz\") { \/\/ If the choice is Watts-Strogatz\n pos = network.find(delimiter);\n std::string token = network.substr(0, pos);\n unsigned int k = (unsigned int) std::stoul(token);\n network.erase(0, pos + delimiter.length());\n double beta = std::stod(network);\n ntwrk = new WattsStrogatz(lp_names, k, beta);\n\n } else if (type == \"Barabasi-Albert\") { \/\/ If the choice is Barabasi-Albert\n pos = network.find(delimiter);\n std::string token = network.substr(0, pos);\n unsigned int m = (unsigned int) std::stoul(token);\n network.erase(0, pos + delimiter.length());\n double a = std::stod(network);\n ntwrk = new BarabasiAlbert(lp_names, m, a);\n\n } else { \/\/ Invalid choice\n std::cerr << \"Invalid choice of network.\" << std::endl;\n abort();\n }\n\n \/* Parse the event send distribution type and parameters *\/\n pos = event_send.find(delimiter);\n std::string distribution_type = event_send.substr(0, pos);\n event_send.erase(0, pos + delimiter.length());\n\n for (auto& lp : lps) {\n\n \/* Create the send time distributions *\/\n if (distribution_type == \"geometric\") {\n lp.send_distribution_ = new Geometric(event_send);\n\n } else if (distribution_type == \"exponential\") {\n lp.send_distribution_ = new Exponential(event_send);\n\n } else if (distribution_type == \"binomial\") {\n lp.send_distribution_ = new Binomial(event_send);\n\n } else {\n std::cerr << \"Invalid choice of event send distribution.\" << std::endl;\n abort();\n }\n\n \/* Fetch the adjacency list for each node *\/\n lp.adjacency_list_ = ntwrk->adjacencyList(lp.name_);\n assert(lp.adjacency_list_.size());\n }\n delete ntwrk;\n\n \/* Parse the node selection distribution type and parameters *\/\n pos = node_selection.find(delimiter);\n distribution_type = node_selection.substr(0, pos);\n node_selection.erase(0, pos + delimiter.length());\n\n for (auto& lp : lps) {\n node_selection += \",\" + lp.adjacency_list_.size();\n\n \/* Create the node selection distributions *\/\n if (distribution_type == \"geometric\") {\n lp.node_sel_distribution_ = new Geometric(node_selection);\n\n } else if (distribution_type == \"exponential\") {\n lp.node_sel_distribution_ = new Exponential(node_selection);\n\n } else if (distribution_type == \"binomial\") {\n lp.node_sel_distribution_ = new Binomial(node_selection);\n\n } else {\n std::cerr << \"Invalid choice of node select distribution.\" << std::endl;\n abort();\n }\n }\n\n \/* Simulate the synthetic model *\/\n synthetic_sim.simulate(lp_pointers);\n\n return 0;\n}\n\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nvoid readpgm( const std::string &fn,\n unsigned char* &data,\n int &width,\n int &height ) {\n\n FILE* stream = 0;\n\n stream = fopen(fn.c_str(),\"r\");\n if ( !stream ) {\n std::cerr << \" Failed to read pgm.\" << std::endl;\n exit(-1);\n }\n\n\n int bsize;\n int read = fscanf(stream,\"P5\\n%d %d\\n%d%*[\\n]\",&width,&height,&bsize);\n if ( read < 3 ) {\n std::cerr << \" Failed to read pgm header.\" << std::endl;\n exit(-1);\n }\n\n data = new unsigned char[width*height];\n\n read = fread(data,1,width*height,stream);\n if ( read != width*height ) {\n std::cerr << \" Failed to read pgm data.\" << std::endl;\n std::cerr << \" Read \" << read << \" expected \" << width*height\n << \".\" << std::endl;\n exit(-1);\n }\n\n fclose(stream);\n\n\n}\n\nvoid writepgm( const std::string &fn,\n unsigned char* &data,\n int &width,\n int &height ) {\n\n FILE* stream = 0;\n\n stream = fopen(fn.c_str(),\"w\");\n if ( !stream ) {\n std::cerr << \" Failed to write pgm.\" << std::endl;\n exit(-1);\n }\n\n\n int wrote = fprintf(stream,\"P5\\n%d %d\\n%d\\n\",width,height,255);\n if ( wrote < 3 ) {\n std::cerr << \" Failed to write pgm header.\" << std::endl;\n exit(-1);\n }\n\n wrote = fwrite(data,1,width*height,stream);\n if ( wrote != width*height ) {\n std::cerr << \" Failed to write pgm data.\" << std::endl;\n std::cerr << \" Wrote \" << wrote << \" expected \" << width*height\n << \".\" << std::endl;\n exit(-1);\n }\n\n fclose(stream);\n\n\n}\n\ntypedef struct _im {\n\n unsigned char *data;\n int width, height;\n\n} im_t;\n\ninline double smoothing_term( int *displut, unsigned char *disp, int width, int\n height, int y, int x, int thisdisp, double p1, double p2 ) {\n\n if ( y < 0 || y >= height || x < 0 || x >= width ) {\n return 0; \/* TODO: Is this the correct behaviour? *\/\n }\n\n double smoothterm = 0;\n int absdisp = std::abs(displut[disp[y*width+x]] - thisdisp);\n if ( absdisp == 0 ) {\n smoothterm = 0;\n } else if ( absdisp == 1 ) {\n smoothterm = p1;\n } else { \n smoothterm = p2;\n }\n return smoothterm;\n}\n\ninline int sample_distribution( int n, double *prob, double norm ) {\n\n double unirand = (double) std::rand() \/ (double) RAND_MAX;\n\n double cumsum = 0;\n double invnorm = 1\/norm;\n\n int reti = -1;\n\n for ( int i = 0; i < n; ++i ) {\n cumsum += prob[i] * invnorm;\n if ( unirand <= cumsum ) { \/* This must eventually be true of any prob.\n dist. *\/\n reti = i;\n break;\n }\n }\n\n assert( reti >= 0 );\n\n return reti;\n\n}\n\ndouble calculate_energy( int ndisp,\n int mindisp,\n double p1,\n double p2,\n double temperature,\n int width, \/* Image width *\/\n int height, \/* Image width *\/\n unsigned char *ref,\n unsigned char *match,\n unsigned char *disp \/* Disparity *\/) {\n\n int* displut = new int[ndisp];\n for ( int idisp = 0; idisp < ndisp; ++idisp ) {\n displut[idisp] = idisp + mindisp; \n }\n\n const double invtemperature = 1\/temperature;\n\n double energy = 0;\n for ( int irow = 0; irow < height; ++irow ) {\n for ( int icol = 0; icol < width; ++icol ) {\n int refidx = irow * width + icol;\n int thisdisp = disp[irow*width + icol];\n int matchx = icol + thisdisp;\n if ( matchx < 0 || matchx >= width ) {\n continue;\n }\n int matchidx = irow*width + matchx;\n double dataterm = std::abs((int)(ref[refidx]) - (int)(match[matchidx])) * invtemperature ;\n double smoothterm = 0;\n smoothterm += smoothing_term(displut,disp,width,height,irow+1,icol,thisdisp,p1,p2);\n smoothterm += smoothing_term(displut,disp,width,height,irow,icol+1,thisdisp,p1,p2);\n energy += dataterm + smoothterm;\n }\n }\n\n delete[] displut;\n\n return energy;\n\n}\n\n\nvoid block_gibbs_iter( bool smooth,\n int partition, \/* 0 or 1 *\/\n int ndisp,\n int mindisp,\n double p1,\n double p2,\n double temperature,\n int width, \/* Image width *\/\n int height, \/* Image width *\/\n unsigned char *ref,\n unsigned char *match,\n unsigned char *disp \/* Disparity *\/) {\n\n\n int* displut = new int[ndisp];\n for ( int idisp = 0; idisp < ndisp; ++idisp ) {\n displut[idisp] = idisp + mindisp; \n }\n\n const double invtemperature = 1\/temperature;\n\n\n\n int nthread = 1;\n#pragma omp parallel\n {\n nthread = omp_get_num_threads();\n }\n double **probs = new double*[nthread];\n for ( int i = 0; i < nthread; ++i ){\n probs[i] = new double[ndisp];\n }\n#pragma omp parallel for\n for ( int irow = 0; irow < height; ++irow ) {\n int omptid = omp_get_thread_num();\n double* prob = probs[omptid];\n int shift = (partition + irow) % 2; \/* 0 or 1 aternating between rows *\/\n for ( int icol = shift; icol < width; icol += 2 ) {\n int refidx = irow * width + icol; \/* Every second element *\/\n\n \n \/\/Need to compute the energy for every possible disparity:\n for ( int idisp = 0; idisp < ndisp; ++idisp ) {\n int thisdisp = displut[idisp];\n int matchx = icol + thisdisp;\n if ( matchx < 0 || matchx >= width ) {\n prob[idisp] = -1;\n continue;\n }\n int matchidx = irow*width + matchx;\n double dataterm = std::abs((int)(ref[refidx]) - (int)(match[matchidx])) * invtemperature;\n\n \/\/Smoothing term of the four neighbours.\n double smoothterm = 0;\n if ( smooth ) {\n smoothterm += smoothing_term(displut,disp,width,height,irow+1,icol,thisdisp,p1,p2);\n smoothterm += smoothing_term(displut,disp,width,height,irow-1,icol,thisdisp,p1,p2);\n smoothterm += smoothing_term(displut,disp,width,height,irow,icol+1,thisdisp,p1,p2);\n smoothterm += smoothing_term(displut,disp,width,height,irow,icol-1,thisdisp,p1,p2);\n }\n\n\n prob[idisp] = dataterm + smoothterm;\n }\n\n double partitionfunc = 0;\n for ( int idisp = 0; idisp < ndisp; ++idisp ) {\n if ( prob[idisp] >= 0 ) {\n prob[idisp] = std::exp( - (prob[idisp]) );\n partitionfunc += prob[idisp];\n } else {\n prob[idisp] = 0;\n }\n }\n\n assert ( partitionfunc > 0 ); \/* There must be some disparity with non-zero prob.*\/\n\n disp[ refidx ] = sample_distribution(ndisp,prob,partitionfunc);\n\n }\n }\n\n delete[] displut;\n for ( int i = 0; i < nthread; ++i ) {\n delete[] probs[i];\n }\n delete[] probs;\n\n\n}\n\n\nvoid block_gibbs( int niter,\n int ndisp,\n int mindisp,\n double _p1,\n double _p2,\n double temperature,\n im_t &im1,\n im_t &im2,\n im_t &disp) {\n\n if ( !(im1.width == im2.width && im1.height == im2.height ) ) {\n std::cerr << \" Images are not same dimensions.\" << std::endl;\n exit(-1);\n }\n\n int width = im1.width;\n int height = im1.height;\n\n double p1,p2;\n p1 = _p1 \/ temperature;\n p2 = _p2 \/ temperature;\n\n unsigned char *ref = im1.data;\n unsigned char *match = im2.data;\n unsigned char *out = disp.data;\n\n for ( int iter = 0; iter < niter;\n ++iter ) {\n for ( int k = 0; k < 2; ++k ) {\n int partition = k;\n block_gibbs_iter( true, partition, ndisp, mindisp, p1, p2, temperature, width,\n height, ref, match, out);\n }\n double energy = calculate_energy( ndisp, mindisp, p1, p2, temperature, width,\n height, ref, match, out );\n\n writepgm(\"disp_inprogress.pgm\",\n disp.data,\n disp.width,\n disp.height);\n\n std::cout << \" done block gibbs iter \" << iter+1 << \" of \" <<\n niter << \" energy: \" << energy << std::endl;\n\n }\n\n}\n\n\nint main( int argc, char *argv[] ) {\n\n std::srand(time(NULL));\n\n\n im_t im1, im2, disp;\n\n std::cout << \" Reading im1 \" << std::endl;\n readpgm(\"cones_left.pgm\",\n im1.data,\n im1.width,\n im1.height);\n\n std::cout << \" Reading im2 \" << std::endl;\n readpgm(\"cones_right.pgm\",\n im2.data,\n im2.width,\n im2.height);\n\n disp.width = im1.width;\n disp.height = im1.height;\n disp.data = new unsigned char[disp.width*disp.height];\n\n std::fill(disp.data,disp.data+disp.width*disp.height,0);\n\n int niter1 = 0;\n int ndisp = 128;\n int mindisp = -(ndisp-1);\n double temperature = 10.; \/* Temperature is unfortunately critical to\n methods based on block gibbs sampling. Higher\n temperature induces more variability and\n possibly non convergence, lower temperatures\n cause numeric instabilities as well as poor\n solutions that refuse to shift from their\n locally optimal solution. *\/\n\n std::cout << \" ndisp: \" << ndisp << std::endl;\n std::cout << \" mindisp: \" << mindisp << std::endl;\n std::cout << \" temperature: \" << temperature << std::endl;\n\n double p1, p2; \/* The model that is minimized uses the same p1, p2\n penalties as SGM and countless other stereo algorithms.\n *\/\n int niter;\n\n std::cout << \" calculating prior: \" << std::endl;\n p1 = 0;\n p2 = 0;\n niter = 10;\n block_gibbs(niter,ndisp,mindisp,p1,p2,temperature,im1,im2,disp);\n std::cout << \" done calculating prior \" << std::endl;\n\n std::cout << \" calculating posterior: \" << std::endl;\n p1 = 5.;\n p2 = 50.;\n niter = 10000;\n block_gibbs(niter,ndisp,mindisp,p1,p2,temperature,im1,im2,disp);\n std::cout << \" done calculating posterior \" << std::endl;\n\n writepgm(\"disp.pgm\",\n disp.data,\n disp.width,\n disp.height);\n\n\n delete[] im1.data;\n delete[] im2.data;\n delete[] disp.data;\n\n\n return 0;\n}\nGibbs stereo working, but can be tweaked a lot more.#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nvoid readpgm( const std::string &fn,\n unsigned char* &data,\n int &width,\n int &height ) {\n\n FILE* stream = 0;\n\n stream = fopen(fn.c_str(),\"r\");\n if ( !stream ) {\n std::cerr << \" Failed to read pgm.\" << std::endl;\n exit(-1);\n }\n\n\n int bsize;\n int read = fscanf(stream,\"P5\\n%d %d\\n%d%*[\\n]\",&width,&height,&bsize);\n if ( read < 3 ) {\n std::cerr << \" Failed to read pgm header.\" << std::endl;\n exit(-1);\n }\n\n data = new unsigned char[width*height];\n\n read = fread(data,1,width*height,stream);\n if ( read != width*height ) {\n std::cerr << \" Failed to read pgm data.\" << std::endl;\n std::cerr << \" Read \" << read << \" expected \" << width*height\n << \".\" << std::endl;\n exit(-1);\n }\n\n fclose(stream);\n\n\n}\n\nvoid writepgm( const std::string &fn,\n unsigned char* &data,\n int &width,\n int &height ) {\n\n FILE* stream = 0;\n\n stream = fopen(fn.c_str(),\"w\");\n if ( !stream ) {\n std::cerr << \" Failed to write pgm.\" << std::endl;\n exit(-1);\n }\n\n\n int wrote = fprintf(stream,\"P5\\n%d %d\\n%d\\n\",width,height,255);\n if ( wrote < 3 ) {\n std::cerr << \" Failed to write pgm header.\" << std::endl;\n exit(-1);\n }\n\n wrote = fwrite(data,1,width*height,stream);\n if ( wrote != width*height ) {\n std::cerr << \" Failed to write pgm data.\" << std::endl;\n std::cerr << \" Wrote \" << wrote << \" expected \" << width*height\n << \".\" << std::endl;\n exit(-1);\n }\n\n fclose(stream);\n\n\n}\n\ntypedef struct _im {\n\n unsigned char *data;\n int width, height;\n\n} im_t;\n\ninline double smoothing_term( int *displut, unsigned char *disp, int width, int\n height, int y, int x, int thisdisp, double p1, double p2 ) {\n\n if ( y < 0 || y >= height || x < 0 || x >= width ) {\n return 0; \/* TODO: Is this the correct behaviour? *\/\n }\n\n double smoothterm = 0;\n int absdisp = std::abs(displut[disp[y*width+x]] - thisdisp);\n if ( absdisp == 0 ) {\n smoothterm = 0;\n } else if ( absdisp == 1 ) {\n smoothterm = p1;\n } else { \n smoothterm = p2;\n }\n return smoothterm;\n}\n\ninline int sample_distribution( int n, double *prob, double norm ) {\n\n double unirand = (double) std::rand() \/ (double) RAND_MAX;\n\n double cumsum = 0;\n double invnorm = 1\/norm;\n\n int reti = -1;\n\n for ( int i = 0; i < n; ++i ) {\n cumsum += prob[i] * invnorm;\n if ( unirand <= cumsum ) { \/* This must eventually be true of any prob.\n dist. *\/\n reti = i;\n break;\n }\n }\n\n if ( reti < 0 ){ \/* This seems to happen only in the case when the\n comparison above fails which is extremely unlikely. *\/\n printf(\" ****warning corner case in sampling detected:\\n\"\n \" cumsum=%g\\n unirand=%g\\n\", cumsum, unirand);\n reti = n-1; \/* It almost always seems to be the case that unirand == 1\n && cumsum == 1 but it is a precision error that fails\n the comparison above. *\/\n }\n\n assert( reti >= 0 );\n\n return reti;\n\n}\n\ndouble calculate_energy( int ndisp,\n int mindisp,\n double p1,\n double p2,\n double temperature,\n int width, \/* Image width *\/\n int height, \/* Image width *\/\n unsigned char *dataterms,\n unsigned char *ref,\n unsigned char *match,\n unsigned char *disp \/* Disparity *\/) {\n\n int* displut = new int[ndisp];\n for ( int idisp = 0; idisp < ndisp; ++idisp ) {\n displut[idisp] = idisp + mindisp; \n }\n\n const double invtemperature = 1\/temperature;\n\n double energy = 0;\n for ( int irow = 0; irow < height; ++irow ) {\n for ( int icol = 0; icol < width; ++icol ) {\n int refidx = irow * width + icol;\n int idisp = disp[irow*width + icol];\n int thisdisp = displut[idisp];\n int matchx = icol + thisdisp;\n if ( matchx < 0 || matchx >= width ) {\n continue;\n }\n int matchidx = irow*width + matchx;\n double dataterm = dataterms[(irow*width+icol)*ndisp + idisp] * invtemperature;\n double smoothterm = 0;\n smoothterm += smoothing_term(displut,disp,width,height,irow+1,icol,thisdisp,p1,p2);\n smoothterm += smoothing_term(displut,disp,width,height,irow,icol+1,thisdisp,p1,p2);\n energy += dataterm + smoothterm;\n }\n }\n\n delete[] displut;\n\n return energy;\n\n}\n\n\nvoid block_gibbs_iter( bool smooth,\n int partition, \/* 0 or 1 *\/\n int ndisp,\n int mindisp,\n double p1,\n double p2,\n double temperature,\n int width, \/* Image width *\/\n int height, \/* Image width *\/\n unsigned char *dataterms,\n unsigned char *ref,\n unsigned char *match,\n unsigned char *disp \/* Disparity *\/) {\n\n\n int* displut = new int[ndisp];\n for ( int idisp = 0; idisp < ndisp; ++idisp ) {\n displut[idisp] = idisp + mindisp; \n }\n\n const double invtemperature = 1\/temperature;\n\n\n\n int nthread = 1;\n#pragma omp parallel\n {\n nthread = omp_get_num_threads();\n }\n double **probs = new double*[nthread];\n for ( int i = 0; i < nthread; ++i ){\n probs[i] = new double[ndisp];\n }\n#pragma omp parallel for\n for ( int irow = 0; irow < height; ++irow ) {\n int omptid = omp_get_thread_num();\n double* prob = probs[omptid];\n int shift = (partition + irow) % 2; \/* 0 or 1 aternating between rows *\/\n for ( int icol = shift; icol < width; icol += 2 ) {\n int refidx = irow * width + icol; \/* Every second element *\/\n\n \/\/Need to compute the energy for every possible disparity:\n for ( int idisp = 0; idisp < ndisp; ++idisp ) {\n int thisdisp = displut[idisp];\n int matchx = icol + thisdisp;\n if ( matchx < 0 || matchx >= width ) {\n prob[idisp] = -1;\n continue;\n }\n int matchidx = irow*width + matchx;\n double dataterm = dataterms[(irow*width+icol)*ndisp + idisp] * invtemperature;\n\n\n \/\/Smoothing term of the four neighbours.\n double smoothterm = 0;\n if ( smooth ) {\n smoothterm += smoothing_term(displut,disp,width,height,irow+1,icol,thisdisp,p1,p2);\n smoothterm += smoothing_term(displut,disp,width,height,irow-1,icol,thisdisp,p1,p2);\n smoothterm += smoothing_term(displut,disp,width,height,irow,icol+1,thisdisp,p1,p2);\n smoothterm += smoothing_term(displut,disp,width,height,irow,icol-1,thisdisp,p1,p2);\n }\n\n\n prob[idisp] = dataterm + smoothterm;\n\n }\n\n double partitionfunc = 0;\n for ( int idisp = 0; idisp < ndisp; ++idisp ) {\n if ( prob[idisp] >= 0 ) {\n prob[idisp] = std::exp( - (prob[idisp]) );\n partitionfunc += prob[idisp];\n } else {\n prob[idisp] = 0;\n }\n }\n\n assert ( partitionfunc > 0 ); \/* There must be some disparity with non-zero prob.*\/\n\n disp[ refidx ] = sample_distribution(ndisp,prob,partitionfunc);\n\n }\n }\n\n delete[] displut;\n for ( int i = 0; i < nthread; ++i ) {\n delete[] probs[i];\n }\n delete[] probs;\n\n\n}\n\n\nvoid block_gibbs( int niter,\n int ndisp,\n int mindisp,\n double _p1,\n double _p2,\n double temperature,\n unsigned char *dataterms,\n im_t &im1,\n im_t &im2,\n im_t &disp) {\n\n if ( !(im1.width == im2.width && im1.height == im2.height ) ) {\n std::cerr << \" Images are not same dimensions.\" << std::endl;\n exit(-1);\n }\n\n int width = im1.width;\n int height = im1.height;\n\n double p1,p2;\n p1 = _p1 \/ temperature;\n p2 = _p2 \/ temperature;\n\n unsigned char *ref = im1.data;\n unsigned char *match = im2.data;\n unsigned char *out = disp.data;\n\n for ( int iter = 0; iter < niter;\n ++iter ) {\n for ( int k = 0; k < 2; ++k ) {\n int partition = k;\n block_gibbs_iter( true, partition, ndisp, mindisp, p1, p2, temperature, width,\n height, dataterms, ref, match, out);\n }\n double energy = calculate_energy( ndisp, mindisp, p1, p2, temperature, width,\n height, dataterms, ref, match, out );\n\n if ( iter % 2 == 0 ) {\n writepgm(\"disp_inprogress.pgm\",\n disp.data,\n disp.width,\n disp.height);\n }\n\n std::cout << \" done block gibbs iter \" << iter+1 << \" of \" <<\n niter << \" energy: \" << energy << std::endl;\n\n }\n\n}\n\nvoid calculate_dataterms( int ndisp,\n int mindisp,\n int rady,\n int radx,\n im_t &im1,\n im_t &im2,\n unsigned char *dataterms ) {\n\n if ( !(im1.width == im2.width && im1.height == im2.height ) ) {\n std::cerr << \" Images are not same dimensions.\" << std::endl;\n exit(-1);\n }\n\n int width = im1.width;\n int height = im1.height;\n\n unsigned char *ref = im1.data;\n unsigned char *match = im2.data;\n\n int* displut = new int[ndisp];\n for ( int idisp = 0; idisp < ndisp; ++idisp ) {\n displut[idisp] = idisp + mindisp; \n }\n\n#pragma omp parallel for\n for ( int irow = 0; irow < height; ++irow ) {\n\n int rsizey = 2*rady+1;\n int rsizex = 2*radx+1;\n double *refpx = new double[rsizey*rsizex];\n double *matchpx = new double[rsizey*rsizex];\n\n for ( int icol = 0; icol < width; ++icol ) {\n\n int refidx = irow * width + icol;\n\n for ( int idisp = 0; idisp < ndisp; ++idisp ) {\n int thisdisp = displut[idisp];\n int matchx = icol + thisdisp;\n if ( matchx < 0 || matchx >= width ) {\n continue;\n }\n int matchidx = irow*width + matchx;\n\n refpx[0] = ref[refidx];\n matchpx[0] = match[matchidx];\n\n double refaggrterm = refpx[0];\n double matchaggrterm = matchpx[0];\n int countfound = 1;\n for ( int dy = -rady; dy <= rady; ++dy ) {\n for ( int dx = -radx; dx <= radx; ++dx ) {\n if ( dx == 0 && dy == 0 ) {\n continue;\n }\n int x0, y0, x1, y1;\n y0 = irow + dy;\n x0 = matchx + dx;\n y1 = y0;\n x1 = icol + dx;\n if ( x0 < 0 || x0 >= width || x1 < 0 || x1 >= width ||\n y0 < 0 || y0 >= height ) {\n continue;\n }\n refpx[countfound] = ref[y1*width+x1];\n matchpx[countfound] = match[y0*width+x0];\n refaggrterm += refpx[countfound];\n matchaggrterm += matchpx[countfound];\n countfound++;\n }\n }\n\n \/\/Compute means & std\n double refmean = refaggrterm \/ countfound;\n double matchmean = matchaggrterm \/ countfound;\n\n double refstd = 0;\n double matchstd = 0;\n\n for ( int ipx = 0; ipx < countfound; ++ipx ) {\n double t;\n t = (refpx[ipx] - refmean );\n refstd += t*t;\n t = (matchpx[ipx] - matchmean );\n matchstd += t*t;\n }\n refstd = std::sqrt(refstd);\n matchstd = std::sqrt(matchstd);\n\n int stdthresh = 0;\n \n double norm = 1. \/ refstd \/ matchstd;\n double ncc = 0;\n for ( int ipx = 0; ipx < countfound; ++ipx ) {\n ncc += (refpx[ipx] - refmean) * (matchpx[ipx] - matchmean ) * norm;\n }\n\n if ( matchstd > stdthresh && refstd > stdthresh ) {\n if ( !( ncc <= 1+1e-6 && ncc >= -1-1e-6) ) {\n std::cout << \" countfound: \" << countfound << std::endl;\n std::cout << \" ncc: \" << ncc << std::endl;\n printf(\"nccp: %lf\\n\",ncc);\n std::cout << \" refstd: \" << refstd << std::endl;\n std::cout << \" matchstd: \" << matchstd << std::endl;\n std::cout << \" refmean: \" << refmean << std::endl;\n std::cout << \" matchmean: \" << matchmean << std::endl;\n std::cout << \" refpx: \";\n for ( int ipx = 0; ipx < countfound; ++ipx ) {\n std::cout << refpx[ipx] << \", \";\n }\n std::cout << std::endl;\n std::cout << \" matchpx: \";\n for ( int ipx = 0; ipx < countfound; ++ipx ) {\n std::cout << matchpx[ipx] << \", \";\n }\n std::cout << std::endl;\n }\n assert( ncc <= 1.+1e-6 && ncc >= -1.-1e-6);\n\n double output = (1-ncc) * 128;\n output = output < 0 ? 0 : output > 255 ? 255 : output;\n dataterms[ (irow*width + icol)*ndisp + idisp ] = output;\n } else {\n dataterms[ (irow*width + icol)*ndisp + idisp ] = 255;\n }\n\n }\n\n }\n\n delete[] refpx;\n delete[] matchpx;\n }\n\n delete[] displut;\n\n\n}\n\n\nint main( int argc, char *argv[] ) {\n\n std::srand(time(NULL));\n\n\n im_t im1, im2, disp;\n\n std::cout << \" Reading im1 \" << std::endl;\n readpgm(\"cones_left.pgm\",\n im1.data,\n im1.width,\n im1.height);\n\n std::cout << \" Reading im2 \" << std::endl;\n readpgm(\"cones_right.pgm\",\n im2.data,\n im2.width,\n im2.height);\n\n disp.width = im1.width;\n disp.height = im1.height;\n disp.data = new unsigned char[disp.width*disp.height];\n\n\n bool usecheckpoint = false;\n std::string checkpointfile = \"\";\n if ( usecheckpoint ) {\n readpgm(checkpointfile,\n disp.data,\n disp.width,\n disp.height);\n } else {\n std::fill(disp.data,disp.data+disp.width*disp.height,0);\n }\n\n int ndisp = 128;\n int mindisp = -(ndisp-1);\n double temperature; \/* Temperature is unfortunately critical to\n methods based on block gibbs sampling. Higher\n temperature induces more variability and\n possibly non convergence, lower temperatures\n cause numeric instabilities as well as poor\n solutions that refuse to shift from their\n locally optimal solution. *\/\n\n std::cout << \" ndisp: \" << ndisp << std::endl;\n std::cout << \" mindisp: \" << mindisp << std::endl;\n\n double p1, p2; \/* The model that is minimized uses the same p1, p2\n penalties as SGM and countless other stereo algorithms.\n *\/\n\n \/* Precompute the dataterms based on radius size *\/\n int drady = 1;\n int dradx = 1;\n unsigned char *dataterms = new unsigned char[im1.width*im1.height*ndisp];\n std::cout << \" precomputing dataterms ... \" << std::endl;\n calculate_dataterms(ndisp,mindisp,drady,dradx,im1,im2,dataterms);\n std::cout << \" done precomputing dataterms \" << std::endl;\n\n int niter;\n\n if ( !usecheckpoint ) {\n std::cout << \" calculating prior ... \" << std::endl;\n p1 = 0;\n p2 = 0;\n niter = 1;\n temperature = 1.;\n block_gibbs(niter,ndisp,mindisp,p1,p2,temperature,dataterms,im1,im2,disp);\n std::cout << \" done calculating prior \" << std::endl;\n }\n\n \/* A very reasonable set of settings is:\n *\n * p1 = 10; p2 = 215; temperature = 80;\n *\n *\/\n\n std::cout << \" calculating posterior ... \" << std::endl;\n p1 = 10;\n p2 = 215;\n niter = 2000;\n temperature = 20.;\n block_gibbs(niter,ndisp,mindisp,p1,p2,temperature,dataterms,im1,im2,disp);\n\n writepgm(\"disp.pgm\",\n disp.data,\n disp.width,\n disp.height);\n\n\n delete[] im1.data;\n delete[] im2.data;\n delete[] disp.data;\n delete[] dataterms;\n\n\n return 0;\n}\n<|endoftext|>"} {"text":"\/\/-------------------------------------------------------------------------------\n\/\/\/\n\/\/\/ \\file scene.cpp\n\/\/\/ \\author Cem Yuksel (www.cemyuksel.com)\n\/\/\/ \\version 1.0\n\/\/\/ \\date August 26, 2013\n\/\/\/\n\/\/\/ \\brief Example source for CS 6620 - University of Utah.\n\/\/\/\n\/\/-------------------------------------------------------------------------------\n\n#ifndef _SCENE_CPP_INCLUDED_\n#define _SCENE_CPP_INCLUDED_\n\n\/\/-------------------------------------------------------------------------------\n\n#include \n\n#include \"library\/cyPoint.h\"\ntypedef cyPoint3f Point3;\n\n#include \"library\/cyMatrix3.h\"\ntypedef cyMatrix3f Matrix3;\n\n\/\/-------------------------------------------------------------------------------\n\n#ifndef min\n# define min(a,b) ((a)<(b)?(a):(b))\n#endif\n\n#ifndef max\n# define max(a,b) ((a)>(b)?(a):(b))\n#endif\n\n#define BIGFLOAT 1.0e30f\n\nnamespace scene{\n\n\/\/-------------------------------------------------------------------------------\n\nclass Ray\n{\npublic:\n Point3 p, dir;\n\n Ray() {}\n Ray(const Point3 &_p, const Point3 &_dir) : p(_p), dir(_dir) {}\n void Normalize() { dir.Normalize(); }\n};\n\n\/\/-------------------------------------------------------------------------------\n\nclass Node;\n\n#define HIT_NONE 0\n#define HIT_FRONT 1\n#define HIT_BACK 2\n#define HIT_FRONT_AND_BACK (HIT_FRONT|HIT_BACK)\n\nstruct HitInfo\n{\n float z; \/\/ the distance from the ray center to the hit point\n const Node *node; \/\/ the object node that was hit\n bool front; \/\/ true if the ray hits the front side, false if the ray hits the back side\n\n HitInfo() { Init(); }\n void Init() { z=BIGFLOAT; node=NULL; front=true; }\n};\n\n\/\/-------------------------------------------------------------------------------\n\nclass ItemBase\n{\nprivate:\n char *name; \/\/ The name of the item\n\npublic:\n ItemBase() : name(NULL) {}\n virtual ~ItemBase() { if ( name ) delete [] name; }\n\n const char* GetName() const { return name ? name : \"\"; }\n void SetName(const char *newName)\n {\n if ( name ) delete [] name;\n if ( newName ) {\n int n = strlen(newName);\n name = new char[n+1];\n for ( int i=0; i class ItemList : public std::vector\n{\npublic:\n virtual ~ItemList() { DeleteAll(); }\n void DeleteAll() { int n=this->size(); for ( int i=0; iat(i) ) delete this->at(i); }\n};\n\n\ntemplate class ItemFileList\n{\npublic:\n void Clear() { list.DeleteAll(); }\n void Append( T* item, const char *name ) { list.push_back( new FileInfo(item,name) ); }\n T* Find( const char *name ) const { int n=list.size(); for ( int i=0; iGetName())==0 ) return list[i]->GetObj(); return NULL; }\n\nprivate:\n class FileInfo : public ItemBase\n {\n private:\n T *item;\n public:\n FileInfo() : item(NULL) {}\n FileInfo(T *_item, const char *name) : item(_item) { SetName(name); }\n ~FileInfo() { Delete(); }\n void Delete() { if (item) delete item; item=NULL; }\n void SetObj(T *_item) { Delete(); item=_item; }\n T* GetObj() { return item; }\n };\n\n ItemList list;\n};\n\n\/\/-------------------------------------------------------------------------------\n\nclass Transformation\n{\nprivate:\n Matrix3 tm; \/\/ Transformation matrix to the local space\n Point3 pos; \/\/ Translation part of the transformation matrix\n mutable Matrix3 itm; \/\/ Inverse of the transformation matrix (cached)\npublic:\n Transformation() : pos(0,0,0) { tm.SetIdentity(); itm.SetIdentity(); }\n const Matrix3& GetTransform() const { return tm; }\n const Point3& GetPosition() const { return pos; }\n const Matrix3& GetInverseTransform() const { return itm; }\n\n Point3 TransformTo( const Point3 &p ) const { return itm * (p - pos); } \/\/ Transform to the local coordinate system\n Point3 TransformFrom( const Point3 &p ) const { return tm*p + pos; } \/\/ Transform from the local coordinate system\n\n \/\/ Transforms a vector to the local coordinate system (same as multiplication with the inverse transpose of the transformation)\n Point3 VectorTransformTo( const Point3 &dir ) const { return TransposeMult(tm,dir); }\n\n \/\/ Transforms a vector from the local coordinate system (same as multiplication with the inverse transpose of the transformation)\n Point3 VectorTransformFrom( const Point3 &dir ) const { return TransposeMult(itm,dir); }\n\n void Translate(Point3 p) { pos+=p; }\n void Rotate(Point3 axis, float degree) { Matrix3 m; m.SetRotation(axis,degree*(float)M_PI\/180.0f); Transform(m); }\n void Scale(float sx, float sy, float sz) { Matrix3 m; m.Zero(); m[0]=sx; m[4]=sy; m[8]=sz; Transform(m); }\n void Transform(const Matrix3 &m) { tm*=m; pos=m*pos; tm.GetInverse(itm); }\n\n void InitTransform() { pos.Zero(); tm.SetIdentity(); itm.SetIdentity(); }\n\nprivate:\n \/\/ Multiplies the given vector with the transpose of the given matrix\n static Point3 TransposeMult( const Matrix3 &m, const Point3 &dir )\n {\n Point3 d;\n d.x = m.GetColumn(0) % dir;\n d.y = m.GetColumn(1) % dir;\n d.z = m.GetColumn(2) % dir;\n return d;\n }\n};\n\n\/\/-------------------------------------------------------------------------------\n\n\/\/ Base class for all object types\nclass Object\n{\npublic:\n virtual ~Object()=0;\n virtual bool IntersectRay( const Ray &ray, HitInfo &hit, int face=HIT_FRONT ) const=0;\n \/\/void ViewportDisplay() const {} \/\/ used for OpenGL display\n};\nObject::~Object(){}\n\ntypedef ItemFileList ObjFileList;\n\n\/\/-------------------------------------------------------------------------------\n\nclass Node : public ItemBase, public Transformation\n{\nprivate:\n Node **child; \/\/ Child nodes\n int numChild; \/\/ The number of child nodes\n Object *obj; \/\/ Object reference (merely points to the object, but does not own the object, so it doesn't get deleted automatically)\npublic:\n Node() : child(NULL), numChild(0), obj(NULL) {}\n\n void Init() { DeleteAllChildNodes(); obj=NULL; SetName(NULL); InitTransform(); } \/\/ Initialize the node deleting all child nodes\n\n \/\/ Hierarchy management\n int GetNumChild() const { return numChild; }\n void SetNumChild(int n, int keepOld=false)\n {\n if ( n < 0 ) n=0; \/\/ just to be sure\n Node **nc = NULL; \/\/ new child pointer\n if ( n > 0 ) nc = new Node*[n];\n for ( int i=0; iDeleteAllChildNodes(); delete child[i]; } SetNumChild(0); }\n\n \/\/ Object management\n const Object* GetObject() const { return obj; }\n Object* GetObject() { return obj; }\n void SetObject(Object *object) { obj=object; }\n\n \/\/ Transformations\n Ray ToNodeCoords( const Ray &ray ) const\n {\n Ray r;\n r.p = TransformTo(ray.p);\n r.dir = TransformTo(ray.p + ray.dir) - r.p;\n return r;\n }\n};\n\n\/\/-------------------------------------------------------------------------------\n\nclass Camera\n{\npublic:\n Point3 pos, dir, up;\n float fov;\n int imgWidth, imgHeight;\n\n void Init()\n {\n pos.Set(0,0,0);\n dir.Set(0,0,-1);\n up.Set(0,1,0);\n fov = 40;\n imgWidth = 200;\n imgHeight = 150;\n }\n};\n\n\/\/-------------------------------------------------------------------------------\n\ntypedef unsigned char uchar;\n\nstruct Color24\n{\n uchar r, g, b;\n};\n\n\/\/-------------------------------------------------------------------------------\n\nclass RenderImage\n{\nprivate:\n Color24 *img;\n float *zbuffer;\n uchar *zbuffer8;\n int width, height;\n int numRenderedPixels;\npublic:\n RenderImage() : img(NULL), zbuffer(NULL), zbuffer8(NULL), width(0), height(0), numRenderedPixels(0) {}\n void Init(int w, int h)\n {\n width=w;\n height=h;\n if (img) delete [] img;\n img = new Color24[width*height];\n if (zbuffer) delete [] zbuffer;\n zbuffer = new float[width*height];\n for(int i = 0; i < width * height; i++)\n zbuffer[i] = BIGFLOAT;\n if (zbuffer8) delete [] zbuffer8;\n zbuffer8 = NULL;\n ResetNumRenderedPixels();\n }\n void setBackground(Color24 c){\n for(int i = 0; i < width * height; i++)\n img[i] = c;\n }\n int GetWidth() const { return width; }\n int GetHeight() const { return height; }\n Color24* GetPixels() { return img; }\n float* GetZBuffer() { return zbuffer; }\n uchar* GetZBufferImage() { return zbuffer8; }\n\n void ResetNumRenderedPixels() { numRenderedPixels=0; }\n int GetNumRenderedPixels() const { return numRenderedPixels; }\n void IncrementNumRenderPixel() { numRenderedPixels++; }\n void IncrementNumRenderPixel(int n) { numRenderedPixels+=n; } \/\/ not thread-safe\n bool IsRenderDone() const { return numRenderedPixels >= width*height; }\n\n void ComputeZBufferImage()\n {\n int size = width * height;\n if (zbuffer8) delete [] zbuffer8;\n zbuffer8 = new unsigned char[size];\n\n float zmin=BIGFLOAT, zmax=0;\n for ( int i=0; i zbuffer[i] ) zmin = zbuffer[i];\n if ( zmax < zbuffer[i] ) zmax = zbuffer[i];\n }\n for ( int i=0; i 200 ) f = 200;\n zbuffer8[i] = c + 47;\n }\n }\n }\n\n bool SaveImage(const char *filename) const { return SavePPM(filename,&img[0].r,3); }\n bool SaveZImage(const char *filename) const { return SavePPM(filename,zbuffer8,1); }\n\nprivate:\n bool SavePPM(const char *filename, uchar *data, int compCount) const\n {\n FILE *fp = fopen(filename,\"wb\");\n if ( !fp ) return false;\n fprintf(fp,\"P6\\n%d %d\\n255\\n\", width, height);\n switch( compCount ) {\n case 1:\n for ( int i=0; imajor rewrite of scene class, need to clean up and refactor majorly next\/\/ Copyright 2013 Sean McKenna\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\n\/\/ scene class (nodes, objects, transformation, camera, rendering, etc.)\n\/\/ originally adapted from code provided by Cem Yuksel\n\n\n\/\/ libraries, namespace\n#ifndef _SCENE_CPP_INCLUDED_\n#define _SCENE_CPP_INCLUDED_\n#include \n#include \"library\/cyPoint.h\"\ntypedef cyPoint3f Point3;\n#include \"library\/cyMatrix3.h\"\ntypedef cyMatrix3f Matrix3;\nusing namespace std;\n\n\n\/\/ custom functions\n#ifndef min\n# define min(a, b) ((a) < (b) ? (a):(b))\n#endif\n#ifndef max\n# define max(a, b) ((a) > (b) ? (a):(b))\n#endif\n#define BIGFLOAT 1.0e30f\n\n\n\/\/ declare namespace\nnamespace scene{\n\n\n\/\/ Ray definition (point & direction)\nclass Ray{\n public:\n Point3 p, dir;\n Ray(){}\n Ray(const Point3 &_p, const Point3 &_dir): p(_p), dir(_dir) {}\n void Normalize(){\n dir.Normalize();\n }\n};\n\n\n\/\/ Node definition\nclass Node;\n\n\n\/\/ Hit Info definition (for each node)\n#define HIT_NONE 0\n#define HIT_FRONT 1\n#define HIT_BACK 2\n#define HIT_FRONT_AND_BACK (HIT_FRONT | HIT_BACK)\nstruct HitInfo{\n \n \/\/ distance from ray to the hit point\n float z;\n \n \/\/ object node that is hit\n const Node *node;\n \n \/\/ returns true if the object is hit on a front face, false if back face\n bool front;\n \n \/\/ initialization\n HitInfo(){\n Init();\n }\n void Init(){\n z = BIGFLOAT;\n node = NULL;\n front = true;\n }\n};\n\n\n\/\/ Item Base definition\nclass ItemBase{\n private:\n \n \/\/ name of the item\n char *name;\n \n public:\n ItemBase(): name(NULL) {}\n virtual ~ItemBase(){\n if(name)\n delete [] name;\n }\n \n const char* GetName() const{\n return name ? name: \"\";\n }\n \n void SetName(const char *newName){\n if(name)\n delete [] name;\n if(newName){\n int n = strlen(newName);\n name = new char[n + 1];\n for(int i = 0; i < n; i++)\n name[i] = newName[i];\n name[n] = '\\0';\n }else{\n name = NULL;\n }\n }\n};\n\n\/\/ ItemList template definition\ntemplate class ItemList: public vector {\n public:\n virtual ~ItemList(){\n DeleteAll();\n }\n void DeleteAll(){\n int n = this->size();\n for(int i = 0; i < n; i++)\n if(this->at(i))\n delete this->at(i);\n }\n};\n\n\n\/\/ ItemFileList template definition\ntemplate class ItemFileList{\n public:\n void Clear(){\n list.DeleteAll();\n }\n void Append(T* item, const char *name){\n list.push_back(new FileInfo(item, name));\n }\n T* Find(const char *name) const{\n int n = list.size();\n for(int i = 0; i < n; i++)\n if(list[i] && strcmp(name, list[i]->GetName()) == 0)\n return list[i]->GetObj();\n return NULL;\n }\n \n private:\n class FileInfo: public ItemBase{\n private:\n T *item;\n \n public:\n FileInfo(): item(NULL) {}\n FileInfo(T *_item, const char *name): item(_item){\n SetName(name);\n }\n ~FileInfo(){\n Delete();\n }\n void Delete(){\n if(item)\n delete item;\n item = NULL;\n }\n void SetObj(T *_item){\n Delete();\n item = _item;\n }\n T* GetObj(){\n return item;\n }\n };\n \n ItemList list;\n};\n\n\n\/\/ Transformation definition\nclass Transformation{\n private:\n \n \/\/ transformation matrix (to local space)\n Matrix3 tm;\n \n \/\/ translation part of transformation\n Point3 pos;\n \n \/\/ inverse of transformation matrix (cached)\n mutable Matrix3 itm;\n \n public:\n Transformation(): pos(0, 0, 0){\n tm.SetIdentity();\n itm.SetIdentity();\n }\n const Matrix3& GetTransform() const{\n return tm;\n }\n const Point3& GetPosition() const{\n return pos;\n }\n const Matrix3& GetInverseTransform() const{\n return itm;\n }\n \n \/\/ transform into local space\n Point3 TransformTo(const Point3 &p) const{\n return itm * (p - pos);\n }\n \n \/\/ transform from local space\n Point3 TransformFrom(const Point3 &p) const{\n return tm * p + pos;\n }\n \n \/\/ transform vector to local space\n Point3 VectorTransformTo(const Point3 &dir) const{\n return TransposeMult(tm, dir);\n }\n \n \/\/ transform vector from local space\n Point3 VectorTransformFrom(const Point3 &dir) const{\n return TransposeMult(itm, dir);\n }\n \n void Translate(Point3 p){\n pos += p;\n }\n void Rotate(Point3 axis, float degree){\n Matrix3 m;\n m.SetRotation(axis, degree * (float) M_PI \/ 180.0);\n Transform(m);\n }\n void Scale(float sx, float sy, float sz){\n Matrix3 m;\n m.Zero();\n m[0] = sx;\n m[4] = sy;\n m[8] = sz;\n Transform(m);\n }\n void Transform(const Matrix3 &m){\n tm *= m;\n pos = m * pos;\n tm.GetInverse(itm);\n }\n void InitTransform(){\n pos.Zero();\n tm.SetIdentity();\n itm.SetIdentity();\n }\n \n private:\n \n \/\/ multiples given vector with transpose of the matrix\n static Point3 TransposeMult(const Matrix3 &m, const Point3 &dir){\n Point3 d;\n d.x = m.GetColumn(0) % dir;\n d.y = m.GetColumn(1) % dir;\n d.z = m.GetColumn(2) % dir;\n return d;\n }\n};\n\n\n\/\/ Object definition (extended for all kinds of objects attached to a node)\nclass Object{\n public:\n virtual ~Object() = 0;\n virtual bool IntersectRay(const Ray &ray, HitInfo &hit, int face = HIT_FRONT) const = 0;\n};\nObject::~Object(){}\n\n\n\/\/ ObjectFileList definition\ntypedef ItemFileList ObjFileList;\n\n\n\/\/ Node definition (stores objects)\nclass Node: public ItemBase, public Transformation{\n private:\n \n \/\/ child nodes\n Node **child;\n \n \/\/ number of child nodes\n int numChild;\n \n \/\/ object reference\n Object *obj;\n \n public:\n Node(): child(NULL), numChild(0), obj(NULL) {}\n \n \/\/ initialize the node, by deleting all its children\n void Init(){\n DeleteAllChildNodes();\n obj = NULL;\n SetName(NULL);\n InitTransform();\n }\n \n \/\/ managing hierarchy of nodes\n int GetNumChild() const{\n return numChild;\n }\n void SetNumChild(int n, int keepOld = false){\n if(n < 0)\n n = 0;\n \n \/\/ create a new child pointer\n Node **nc = NULL;\n \n if(n > 0)\n nc = new Node*[n];\n for(int i = 0; i < n; i++)\n nc[i] = NULL;\n if(keepOld){\n int sn = min(n, numChild);\n for(int i = 0; i < sn; i++)\n nc[i] = child[i];\n }\n if(child)\n delete [] child;\n child = nc;\n numChild = n;\n }\n \n const Node* GetChild(int i) const{\n return child[i];\n }\n Node* GetChild(int i){\n return child[i];\n }\n void SetChild(int i, Node *node){\n child[i] = node;\n }\n void AppendChild(Node *node){\n SetNumChild(numChild + 1, true);\n SetChild(numChild - 1, node);\n }\n void RemoveChild(int i){\n for(int j = i; j < numChild - 1; j++)\n child[j] = child[j - 1];\n SetNumChild(numChild - 1);\n }\n void DeleteAllChildNodes(){\n for(int i = 0; i < numChild; i++){\n child[i]->DeleteAllChildNodes();\n delete child[i];\n }\n SetNumChild(0);\n }\n \n \/\/ managing node objects\n const Object* GetObject() const{\n return obj;\n }\n Object* GetObject(){\n return obj;\n }\n void SetObject(Object *object){\n obj = object;\n }\n \n \/\/ transformations\n Ray ToNodeCoords(const Ray &ray) const{\n Ray r;\n r.p = TransformTo(ray.p);\n r.dir = TransformTo(ray.p + ray.dir) - r.p;\n return r;\n }\n};\n\n\n\/\/ Camera definition\nclass Camera{\n public:\n Point3 pos, dir, up;\n float fov;\n int imgWidth, imgHeight;\n \n void Init(){\n pos.Set(0, 0, 0);\n dir.Set(0, 0, -1);\n up.Set(0, 1, 0);\n fov = 40;\n imgWidth = 200;\n imgHeight = 150;\n }\n};\n\n\n\/\/ Color definition\ntypedef unsigned char uchar;\nstruct Color24{\n uchar r, g, b;\n};\n\n\n\/\/ RenderImage definition\nclass RenderImage{\n private:\n Color24 *img;\n float *zbuffer;\n uchar *zbuffer8;\n int width, height;\n int numRenderedPixels;\n \n public:\n RenderImage(): img(NULL), zbuffer(NULL), zbuffer8(NULL), width(0), height(0), numRenderedPixels(0) {}\n void Init(int w, int h){\n width = w;\n height = h;\n if(img)\n delete [] img;\n img = new Color24[width * height];\n if(zbuffer)\n delete [] zbuffer;\n zbuffer = new float[width * height];\n for(int i = 0; i < width * height; i++)\n zbuffer[i] = BIGFLOAT;\n if(zbuffer8)\n delete [] zbuffer8;\n zbuffer8 = NULL;\n ResetNumRenderedPixels();\n }\n void setBackground(Color24 c){\n for(int i = 0; i < width * height; i++)\n img[i] = c;\n }\n \n int GetWidth() const{\n return width;\n }\n int GetHeight() const{\n return height;\n }\n Color24* GetPixels(){\n return img;\n }\n float* GetZBuffer(){\n return zbuffer;\n }\n uchar* GetZBufferImage(){\n return zbuffer8;\n }\n \n void ResetNumRenderedPixels(){\n numRenderedPixels = 0;\n }\n int GetNumRenderedPixels() const{\n return numRenderedPixels;\n }\n void IncrementNumRenderPixel(){\n numRenderedPixels++;\n }\n void IncrementNumRenderPixel(int n){\n numRenderedPixels += n;\n }\n bool IsRenderDone() const{\n return numRenderedPixels >= width * height;\n }\n \n void ComputeZBufferImage(){\n int size = width * height;\n if(zbuffer8)\n delete [] zbuffer8;\n zbuffer8 = new unsigned char[size];\n \n float zmin = BIGFLOAT, zmax = 0;\n for(int i = 0; i < size; i++){\n if(zbuffer[i] == BIGFLOAT)\n continue;\n if(zmin > zbuffer[i])\n zmin = zbuffer[i];\n if(zmax < zbuffer[i])\n zmax = zbuffer[i];\n }\n for(int i = 0; i < size; i++){\n if(zbuffer[i] == BIGFLOAT)\n zbuffer8[i] = 33;\n else{\n float f = (zmax - zbuffer[i]) \/ (zmax - zmin);\n int c = int(f * 200);\n if(c < 0)\n f = 0;\n if(c > 200)\n f = 200;\n zbuffer8[i] = c + 47;\n }\n }\n }\n \n bool SaveImage(const char *filename) const{\n return SavePPM(filename, &img[0].r, 3);\n }\n bool SaveZImage(const char *filename) const{\n return SavePPM(filename, zbuffer8, 1);\n }\n \n private:\n bool SavePPM(const char *filename, uchar *data, int compCount) const{\n FILE *fp = fopen(filename, \"wb\");\n if(!fp)\n return false;\n fprintf(fp, \"P6\\n%d %d\\n255\\n\", width, height);\n switch(compCount){\n case 1:\n for(int i = 0; i < width * height; i++){\n uchar d[3] = {data[i], data[i], data[i]};\n fwrite(d, 1, 3, fp);\n }\n break;\n case 3:\n fwrite(data, width * height, 3, fp);\n break;\n }\n fclose(fp);\n return true;\n } \n};\n\n\n}\n#endif\n<|endoftext|>"} {"text":"#include \"process.h\"\n\n\/\/ POSIX\n#include \n#include \n#include \n#include \n\n\/\/ POSIX++\n#include \n#include \n#include \n#include \n\n\/\/ PDTK\n#include \n#include \n#include \n#include \n\n\nenum class command : uint8_t\n{\n invoke = 0,\n executable,\n arguments,\n environment,\n environmentvar,\n workingdir,\n priority,\n uid,\n gid,\n euid,\n egid,\n resource\n};\n\nstatic inline vfifo& operator << (vfifo& vq, command cmd) noexcept\n{ return vq << static_cast(cmd); }\n\nstatic std::unordered_map process_map; \/\/ do not try to own Process memory\n\nvoid Process::init_once(void) noexcept\n{\n static bool ok = true;\n if(ok)\n {\n ok = false;\n struct sigaction actions;\n actions.sa_handler = &reaper;\n ::sigemptyset(&actions.sa_mask);\n actions.sa_flags = SA_RESTART | SA_NOCLDSTOP;\n\n flaw(::sigaction(SIGCHLD, &actions, nullptr) == posix::error_response, posix::critical, , std::exit(1),\n \"An 'impossible' situation has occurred.\")\n }\n}\n\nvoid Process::reaper(int sig) noexcept\n{\n flaw(sig != SIGCHLD, posix::warning, posix::error(std::errc::invalid_argument),,\n \"Process::reaper() has been called improperly\")\n\n pid_t pid = posix::error_response; \/\/ set value just in case\n int status = 0;\n while((pid = ::waitpid(pid_t(-1), &status, WNOHANG)) != posix::error_response) \/\/ get the next dead process (if there is one)... while the currently reaped process was valid\n {\n auto process_map_iter = process_map.find(pid); \/\/ find dead process\n if(process_map_iter != process_map.end()) \/\/ if the dead process exists...\n {\n Process* p = process_map_iter->second;\n#ifndef ENABLE_PROCESS_EVENT_TRACKING\n Object::enqueue_copy(p->finished, posix::invalid_descriptor, EventData_t(EventFlags::ExitEvent, p->processId(), p->processId(), status, sig));\n#endif\n EventBackend::remove(p->getStdOut());\n EventBackend::remove(p->getStdErr());\n posix::close(p->getStdOut());\n posix::close(p->getStdErr());\n posix::close(p->getStdIn());\n p->m_state = Process::State::Finished;\n process_map.erase(process_map_iter); \/\/ remove finished process from the process map\n }\n }\n}\n\nProcess::Process(void) noexcept\n : m_state(State::Initializing)\n{\n init_once();\n process_map.emplace(processId(), this); \/\/ add self to process map\n#ifdef ENABLE_PROCESS_EVENT_TRACKING\n Object::connect(processId(), EventFlags::ExecEvent, started);\n Object::connect(processId(), EventFlags::ExitEvent, finished);\n#endif\n}\n\nProcess::~Process(void) noexcept\n{\n if(m_state == State::Running)\n sendSignal(posix::signal::Kill);\n\n Object::disconnect(getStdOut(), EventFlags::Readable);\n Object::disconnect(getStdErr(), EventFlags::Readable);\n Object::disconnect(processId(), EventFlags::ExecEvent);\n Object::disconnect(processId(), EventFlags::ExitEvent);\n m_state = State::Invalid;\n}\n\nbool Process::write_then_read(void) noexcept\n{\n if(m_iobuf.empty() || \/\/ ensure there is data to write\n !writeStdIn(m_iobuf) || \/\/ write data to pipe\n !waitReadStdOut(1000) || \/\/ wait to read pipe\n !readStdOut(m_iobuf) || \/\/ read data from pipe\n (m_iobuf >> errno).hadError()) \/\/ read return value\n return false;\n return errno == posix::success_response;\n}\n\nbool Process::setArguments(const std::vector& arguments) noexcept\n{\n m_iobuf.reset();\n m_iobuf << command::arguments;\n for(const std::string& arg : arguments)\n m_iobuf << arg;\n return write_then_read();\n}\n\nbool Process::setEnvironment(const std::unordered_map& environment) noexcept\n{\n m_iobuf.reset();\n m_iobuf << command::environment;\n for(const std::pair& p : environment)\n m_iobuf << p.first << p.second;\n return write_then_read();\n}\n\nbool Process::setEnvironmentVariable(const std::string& name, const std::string& value) noexcept\n{\n m_iobuf.reset();\n m_iobuf << command::environment << name << value;\n return write_then_read();\n}\n\nbool Process::setResourceLimit(Process::Resource which, rlim_t limit) noexcept\n{\n m_iobuf.reset();\n m_iobuf << command::resource\n << static_cast(which)\n << static_cast(RLIM_SAVED_CUR)\n << limit;\n return write_then_read();\n}\n\nbool Process::setWorkingDirectory(const std::string& dir) noexcept\n{\n m_iobuf.reset();\n m_iobuf << command::workingdir << dir;\n return write_then_read();\n}\n\nbool Process::setExecutable(const std::string& executable) noexcept\n{\n m_iobuf.reset();\n m_iobuf << command::executable << executable;\n return write_then_read();\n}\n\nbool Process::setUserID(uid_t id) noexcept\n{\n if(posix::getpwuid(id) == nullptr)\n return false;\n\n m_iobuf.reset();\n m_iobuf << command::uid << id;\n return write_then_read();\n}\n\nbool Process::setGroupID(gid_t id) noexcept\n{\n if(posix::getgrgid(id) == nullptr)\n return false;\n\n m_iobuf.reset();\n m_iobuf << command::gid << id;\n return write_then_read();\n}\n\nbool Process::setEffectiveUserID(uid_t id) noexcept\n{\n if(posix::getpwuid(id) == nullptr)\n return false;\n\n m_iobuf.reset();\n m_iobuf << command::euid << id;\n return write_then_read();\n}\n\nbool Process::setEffectiveGroupID(gid_t id) noexcept\n{\n if(posix::getgrgid(id) == nullptr)\n return false;\n\n m_iobuf.reset();\n m_iobuf << command::egid << id;\n return write_then_read();\n}\n\nbool Process::setPriority(int nval) noexcept\n{\n#if defined(PRIO_MIN) && defined(PRIO_MAX)\n if(nval < PRIO_MIN || nval > PRIO_MAX)\n return false;\n#else\n#warning PRIO_MIN or PRIO_MAX is not defined. The safegaurd in Process::setPriority() is disabled.\n#endif\n\n m_iobuf.reset();\n m_iobuf << command::priority << nval;\n return write_then_read();\n}\n\n#ifdef _XOPEN_SOURCE_EXTENDED\nbool Process::sendSignal(posix::signal::EId id, int value) const noexcept\n{\n return posix::signal::send(processId(), id, value);\n}\n#endif\n\nbool Process::invoke(void) noexcept\n{\n flaw(m_state != State::Initializing, posix::severe, posix::error(std::errc::device_or_resource_busy), false,\n \"Called Process::invoke() on an active process!\")\n\n m_iobuf.reset();\n m_iobuf << command::invoke;\n\n if(!writeStdIn(m_iobuf))\n return false;\n\n m_state = State::Invalid;\n state();\n\n#ifndef ENABLE_PROCESS_EVENT_TRACKING\n Object::enqueue_copy(started, posix::invalid_descriptor, EventData_t(EventFlags::ExecEvent, processId(), processId()));\n#endif\n\n Object::connect(getStdOut(), EventFlags::Readable, stdoutMessage);\n Object::connect(getStdErr(), EventFlags::Readable, stderrMessage);\n\n m_state = State::Running;\n return errno == posix::success_response;\n}\n\nProcess::State Process::state(void) noexcept\n{\n switch(m_state)\n {\n case State::Finished:\n case State::Initializing:\n break;\n default:\n process_state_t data;\n flaw(::procstat(processId(), &data) == posix::error_response, posix::severe, m_state = State::Invalid, m_state,\n \"Process %i does not exist.\", processId()); \/\/ process _must_ exist\n switch (data.state)\n {\n case WaitingInterruptable:\n case WaitingUninterruptable:\n m_state = State::Waiting; break;\n case Zombie : m_state = State::Zombie ; break;\n case Stopped: m_state = State::Stopped; break;\n case Running: m_state = State::Running; break;\n }\n }\n return m_state;\n}\nportability fixes#include \"process.h\"\n\n\/\/ POSIX\n#include \n#include \n#include \n#include \n\n\/\/ POSIX++\n#include \n#include \n#include \n#include \n\n\/\/ PDTK\n#include \n#include \n#include \n#include \n\n\nenum class command : uint8_t\n{\n invoke = 0,\n executable,\n arguments,\n environment,\n environmentvar,\n workingdir,\n priority,\n uid,\n gid,\n euid,\n egid,\n resource\n};\n\nstatic inline vfifo& operator << (vfifo& vq, command cmd) noexcept\n{ return vq << static_cast(cmd); }\n\nstatic std::unordered_map process_map; \/\/ do not try to own Process memory\n\nvoid Process::init_once(void) noexcept\n{\n static bool ok = true;\n if(ok)\n {\n ok = false;\n struct sigaction actions;\n actions.sa_handler = &reaper;\n ::sigemptyset((&actions.sa_mask));\n actions.sa_flags = SA_RESTART | SA_NOCLDSTOP;\n\n flaw(::sigaction(SIGCHLD, &actions, nullptr) == posix::error_response, posix::critical, , std::exit(1),\n \"An 'impossible' situation has occurred.\")\n }\n}\n\nvoid Process::reaper(int sig) noexcept\n{\n flaw(sig != SIGCHLD, posix::warning, posix::error(std::errc::invalid_argument),,\n \"Process::reaper() has been called improperly\")\n\n pid_t pid = posix::error_response; \/\/ set value just in case\n int status = 0;\n while((pid = ::waitpid(pid_t(-1), &status, WNOHANG)) != posix::error_response) \/\/ get the next dead process (if there is one)... while the currently reaped process was valid\n {\n auto process_map_iter = process_map.find(pid); \/\/ find dead process\n if(process_map_iter != process_map.end()) \/\/ if the dead process exists...\n {\n Process* p = process_map_iter->second;\n#ifndef ENABLE_PROCESS_EVENT_TRACKING\n Object::enqueue_copy(p->finished, posix::invalid_descriptor, EventData_t(EventFlags::ExitEvent, p->processId(), p->processId(), status, sig));\n#endif\n EventBackend::remove(p->getStdOut());\n EventBackend::remove(p->getStdErr());\n posix::close(p->getStdOut());\n posix::close(p->getStdErr());\n posix::close(p->getStdIn());\n p->m_state = Process::State::Finished;\n process_map.erase(process_map_iter); \/\/ remove finished process from the process map\n }\n }\n}\n\nProcess::Process(void) noexcept\n : m_state(State::Initializing)\n{\n init_once();\n process_map.emplace(processId(), this); \/\/ add self to process map\n#ifdef ENABLE_PROCESS_EVENT_TRACKING\n Object::connect(processId(), EventFlags::ExecEvent, started);\n Object::connect(processId(), EventFlags::ExitEvent, finished);\n#endif\n}\n\nProcess::~Process(void) noexcept\n{\n#ifdef _XOPEN_SOURCE_EXTENDED\n if(m_state == State::Running)\n sendSignal(posix::signal::Kill);\n#endif\n\n Object::disconnect(getStdOut(), EventFlags::Readable);\n Object::disconnect(getStdErr(), EventFlags::Readable);\n Object::disconnect(processId(), EventFlags::ExecEvent);\n Object::disconnect(processId(), EventFlags::ExitEvent);\n m_state = State::Invalid;\n}\n\nbool Process::write_then_read(void) noexcept\n{\n if(m_iobuf.empty() || \/\/ ensure there is data to write\n !writeStdIn(m_iobuf) || \/\/ write data to pipe\n !waitReadStdOut(1000) || \/\/ wait to read pipe\n !readStdOut(m_iobuf) || \/\/ read data from pipe\n (m_iobuf >> errno).hadError()) \/\/ read return value\n return false;\n return errno == posix::success_response;\n}\n\nbool Process::setArguments(const std::vector& arguments) noexcept\n{\n m_iobuf.reset();\n m_iobuf << command::arguments;\n for(const std::string& arg : arguments)\n m_iobuf << arg;\n return write_then_read();\n}\n\nbool Process::setEnvironment(const std::unordered_map& environment) noexcept\n{\n m_iobuf.reset();\n m_iobuf << command::environment;\n for(const std::pair& p : environment)\n m_iobuf << p.first << p.second;\n return write_then_read();\n}\n\nbool Process::setEnvironmentVariable(const std::string& name, const std::string& value) noexcept\n{\n m_iobuf.reset();\n m_iobuf << command::environment << name << value;\n return write_then_read();\n}\n\nbool Process::setResourceLimit(Process::Resource which, rlim_t limit) noexcept\n{\n m_iobuf.reset();\n m_iobuf << command::resource\n << static_cast(which)\n << static_cast(RLIM_SAVED_CUR)\n << limit;\n return write_then_read();\n}\n\nbool Process::setWorkingDirectory(const std::string& dir) noexcept\n{\n m_iobuf.reset();\n m_iobuf << command::workingdir << dir;\n return write_then_read();\n}\n\nbool Process::setExecutable(const std::string& executable) noexcept\n{\n m_iobuf.reset();\n m_iobuf << command::executable << executable;\n return write_then_read();\n}\n\nbool Process::setUserID(uid_t id) noexcept\n{\n if(posix::getpwuid(id) == nullptr)\n return false;\n\n m_iobuf.reset();\n m_iobuf << command::uid << id;\n return write_then_read();\n}\n\nbool Process::setGroupID(gid_t id) noexcept\n{\n if(posix::getgrgid(id) == nullptr)\n return false;\n\n m_iobuf.reset();\n m_iobuf << command::gid << id;\n return write_then_read();\n}\n\nbool Process::setEffectiveUserID(uid_t id) noexcept\n{\n if(posix::getpwuid(id) == nullptr)\n return false;\n\n m_iobuf.reset();\n m_iobuf << command::euid << id;\n return write_then_read();\n}\n\nbool Process::setEffectiveGroupID(gid_t id) noexcept\n{\n if(posix::getgrgid(id) == nullptr)\n return false;\n\n m_iobuf.reset();\n m_iobuf << command::egid << id;\n return write_then_read();\n}\n\nbool Process::setPriority(int nval) noexcept\n{\n#if defined(PRIO_MIN) && defined(PRIO_MAX)\n if(nval < PRIO_MIN || nval > PRIO_MAX)\n return false;\n#else\n#warning PRIO_MIN or PRIO_MAX is not defined. The safegaurd in Process::setPriority() is disabled.\n#endif\n\n m_iobuf.reset();\n m_iobuf << command::priority << nval;\n return write_then_read();\n}\n\n#ifdef _XOPEN_SOURCE_EXTENDED\nbool Process::sendSignal(posix::signal::EId id, int value) const noexcept\n{\n return posix::signal::send(processId(), id, value);\n}\n#endif\n\nbool Process::invoke(void) noexcept\n{\n flaw(m_state != State::Initializing, posix::severe, posix::error(std::errc::device_or_resource_busy), false,\n \"Called Process::invoke() on an active process!\")\n\n m_iobuf.reset();\n m_iobuf << command::invoke;\n\n if(!writeStdIn(m_iobuf))\n return false;\n\n m_state = State::Invalid;\n state();\n\n#ifndef ENABLE_PROCESS_EVENT_TRACKING\n Object::enqueue_copy(started, posix::invalid_descriptor, EventData_t(EventFlags::ExecEvent, processId(), processId()));\n#endif\n\n Object::connect(getStdOut(), EventFlags::Readable, stdoutMessage);\n Object::connect(getStdErr(), EventFlags::Readable, stderrMessage);\n\n m_state = State::Running;\n return errno == posix::success_response;\n}\n\nProcess::State Process::state(void) noexcept\n{\n switch(m_state)\n {\n case State::Finished:\n case State::Initializing:\n break;\n default:\n process_state_t data;\n flaw(::procstat(processId(), &data) == posix::error_response, posix::severe, m_state = State::Invalid, m_state,\n \"Process %i does not exist.\", processId()); \/\/ process _must_ exist\n switch (data.state)\n {\n case WaitingInterruptable:\n case WaitingUninterruptable:\n m_state = State::Waiting; break;\n case Zombie : m_state = State::Zombie ; break;\n case Stopped: m_state = State::Stopped; break;\n case Running: m_state = State::Running; break;\n }\n }\n return m_state;\n}\n<|endoftext|>"} {"text":"\/*\n Copyright 2003-2009 John Plevyak, All Rights Reserved\n*\/\n#define EXTERN\n#include \n#include \n#include \"defs.h\"\n\nint do_unit_tests = 0;\nstatic char pyc_ifa_log[256];\n\nstatic void\nhelp(ArgumentState *arg_state, char *arg_unused) {\n char ver[30];\n get_version(ver);\n fprintf(stderr, \"PYC Version %s \", ver);\n fprintf(stderr, \n#include \"COPYRIGHT.i\"\n);\n usage(arg_state, arg_unused);\n}\n\nstatic void\nversion(ArgumentState *arg_state, char *arg_unused) {\n char ver[30];\n get_version(ver);\n fprintf(stderr, \"PYC Version %s \", ver);\n fprintf(stderr, \n#include \"COPYRIGHT.i\"\n);\n exit(0);\n}\n\nstatic void\nlicense(ArgumentState *arg_state, char *arg_unused) {\n fprintf(stderr,\n#include \"LICENSE.i\"\n);\n exit(0);\n}\n\nstatic ArgumentDescription arg_desc[] = {\n {\"debug_info\", 'g', \"Produce Debugging Information\", \"F\", &codegen_debug, \"PYC_DEBUG_INFO\", NULL},\n {\"optimize\", 'O', \"Optimize\", \"F\", &codegen_optimize, \"PYC_OPTIMIZE\", NULL},\n#ifdef DEBUG\n {\"test\", 't', \"Unit Test\", \"F\", &do_unit_tests, \"PYC_TEST\", NULL},\n {\"test_scoping\", ' ', \"Test Scoping\", \"F\", &test_scoping, \"PYC_TEST_SCOPING\", NULL},\n#endif\n {\"html\", ' ', \"Output as HTML\", \"F\", &fdump_html, \"PYC_HTML\", NULL},\n {\"ifalog\", 'l', \"IFA Log\", \"S256\", pyc_ifa_log, \"PYC_IFA_LOG\", log_flags_arg},\n {\"system_directory\", 'D', \"System Directory\", \"S511\", system_dir, \"PYC_SYSTEM_DIRECTORY\", NULL},\n {\"verbose\", 'v', \"Verbosity Level\", \"+\", &verbose_level, \"PYC_VERBOSE\", NULL},\n {\"debug\", 'd', \"Debugging Level\", \"+\", &debug_level, \"PYC_DEBUG\", NULL},\n {\"license\", ' ', \"Show License\", NULL, NULL, NULL, license},\n {\"version\", ' ', \"Version\", NULL, NULL, NULL, version},\n {\"help\", 'h', \"Help\", NULL, NULL, NULL, help},\n {0}\n};\n\nstatic ArgumentState arg_state(\"pyc\", arg_desc);\n\nstatic void init_system() {\n struct rlimit nfiles;\n assert(!getrlimit(RLIMIT_NOFILE, &nfiles));\n nfiles.rlim_cur = nfiles.rlim_max;\n assert(!setrlimit(RLIMIT_NOFILE, &nfiles));\n assert(!getrlimit(RLIMIT_NOFILE, &nfiles));\n}\n\nvoid compile(cchar *fn) {\n if (ifa_analyze(fn) < 0)\n fail(\"program does not type\");\n if (ifa_optimize() < 0)\n fail(\"unable to optimize program\");\n if (fgraph)\n ifa_graph(fn);\n if (fdump_html) {\n char mktree_dir[512];\n strcpy(mktree_dir, system_dir);\n ifa_html(fn, mktree_dir);\n }\n if (fcg) {\n c_codegen_write_c(pdb->fa, if1->top->fun, fn);\n c_codegen_compile(fn);\n }\n return;\n}\n\ncchar *mod_name_from_filename(cchar *n) {\n cchar *start = strrchr(n, '\/');\n if (!start) start = n; else start++;\n cchar *end = strrchr(n, '.');\n assert(end);\n return dupstr(start,end);\n}\n\nint main(int argc, char *argv[]) {\n MEM_INIT();\n INIT_RAND64(0x1234567);\n process_args(&arg_state, argc, argv);\n ifa_verbose = verbose_level;\n ifa_debug = debug_level;\n if (arg_state.nfile_arguments < 1)\n usage(&arg_state, 0);\n init_system();\n init_config();\n if (pyc_ifa_log[0])\n init_logs();\n Service::start_all();\n if (do_unit_tests) {\n int r = UnitTest::run_all();\n Service::stop_all();\n _exit(r);\n }\n Py_Initialize();\n PyEval_InitThreads();\n PyArena *arena = PyArena_New();\n cchar *first_filename = 0;\n Vec mods;\n for (int i = -1; i < arg_state.nfile_arguments; i++) {\n cchar *filename = 0;\n if (i < 0) {\n char fn[256];\n strcpy(fn, system_dir);\n strcat(fn, \"\/__pyc__.py\");\n filename = dupstr(fn);\n } else\n filename = arg_state.file_argument[i];\n if (!i)\n first_filename = filename;\n mod_ty mod = file_to_mod(filename, arena);\n if (mod)\n mods.add(new PycModule(mod, filename, i < 0));\n }\n if (mods.n > 1) {\n ast_to_if1(mods, arena);\n compile(first_filename);\n }\n PyArena_Free(arena);\n Py_Finalize();\n Service::stop_all();\n exit(0);\n return 0;\n}\nreturn error code from c_compile as exit() value\/*\n Copyright 2003-2009 John Plevyak, All Rights Reserved\n*\/\n#define EXTERN\n#include \n#include \n#include \"defs.h\"\n\nint do_unit_tests = 0;\nstatic char pyc_ifa_log[256];\n\nstatic void\nhelp(ArgumentState *arg_state, char *arg_unused) {\n char ver[30];\n get_version(ver);\n fprintf(stderr, \"PYC Version %s \", ver);\n fprintf(stderr, \n#include \"COPYRIGHT.i\"\n);\n usage(arg_state, arg_unused);\n}\n\nstatic void\nversion(ArgumentState *arg_state, char *arg_unused) {\n char ver[30];\n get_version(ver);\n fprintf(stderr, \"PYC Version %s \", ver);\n fprintf(stderr, \n#include \"COPYRIGHT.i\"\n);\n exit(0);\n}\n\nstatic void\nlicense(ArgumentState *arg_state, char *arg_unused) {\n fprintf(stderr,\n#include \"LICENSE.i\"\n);\n exit(0);\n}\n\nstatic ArgumentDescription arg_desc[] = {\n {\"debug_info\", 'g', \"Produce Debugging Information\", \"F\", &codegen_debug, \"PYC_DEBUG_INFO\", NULL},\n {\"optimize\", 'O', \"Optimize\", \"F\", &codegen_optimize, \"PYC_OPTIMIZE\", NULL},\n#ifdef DEBUG\n {\"test\", 't', \"Unit Test\", \"F\", &do_unit_tests, \"PYC_TEST\", NULL},\n {\"test_scoping\", ' ', \"Test Scoping\", \"F\", &test_scoping, \"PYC_TEST_SCOPING\", NULL},\n#endif\n {\"html\", ' ', \"Output as HTML\", \"F\", &fdump_html, \"PYC_HTML\", NULL},\n {\"ifalog\", 'l', \"IFA Log\", \"S256\", pyc_ifa_log, \"PYC_IFA_LOG\", log_flags_arg},\n {\"system_directory\", 'D', \"System Directory\", \"S511\", system_dir, \"PYC_SYSTEM_DIRECTORY\", NULL},\n {\"verbose\", 'v', \"Verbosity Level\", \"+\", &verbose_level, \"PYC_VERBOSE\", NULL},\n {\"debug\", 'd', \"Debugging Level\", \"+\", &debug_level, \"PYC_DEBUG\", NULL},\n {\"license\", ' ', \"Show License\", NULL, NULL, NULL, license},\n {\"version\", ' ', \"Version\", NULL, NULL, NULL, version},\n {\"help\", 'h', \"Help\", NULL, NULL, NULL, help},\n {0}\n};\n\nstatic ArgumentState arg_state(\"pyc\", arg_desc);\n\nstatic void init_system() {\n struct rlimit nfiles;\n assert(!getrlimit(RLIMIT_NOFILE, &nfiles));\n nfiles.rlim_cur = nfiles.rlim_max;\n assert(!setrlimit(RLIMIT_NOFILE, &nfiles));\n assert(!getrlimit(RLIMIT_NOFILE, &nfiles));\n}\n\nvoid compile(cchar *fn) {\n if (ifa_analyze(fn) < 0)\n fail(\"program does not type\");\n if (ifa_optimize() < 0)\n fail(\"unable to optimize program\");\n if (fgraph)\n ifa_graph(fn);\n if (fdump_html) {\n char mktree_dir[512];\n strcpy(mktree_dir, system_dir);\n ifa_html(fn, mktree_dir);\n }\n if (fcg) {\n c_codegen_write_c(pdb->fa, if1->top->fun, fn);\n if (c_codegen_compile(fn))\n fail(\"compilation failure\");\n }\n return;\n}\n\ncchar *mod_name_from_filename(cchar *n) {\n cchar *start = strrchr(n, '\/');\n if (!start) start = n; else start++;\n cchar *end = strrchr(n, '.');\n assert(end);\n return dupstr(start,end);\n}\n\nint main(int argc, char *argv[]) {\n MEM_INIT();\n INIT_RAND64(0x1234567);\n process_args(&arg_state, argc, argv);\n ifa_verbose = verbose_level;\n ifa_debug = debug_level;\n if (arg_state.nfile_arguments < 1)\n usage(&arg_state, 0);\n init_system();\n init_config();\n if (pyc_ifa_log[0])\n init_logs();\n Service::start_all();\n if (do_unit_tests) {\n int r = UnitTest::run_all();\n Service::stop_all();\n _exit(r);\n }\n Py_Initialize();\n PyEval_InitThreads();\n PyArena *arena = PyArena_New();\n cchar *first_filename = 0;\n Vec mods;\n for (int i = -1; i < arg_state.nfile_arguments; i++) {\n cchar *filename = 0;\n if (i < 0) {\n char fn[256];\n strcpy(fn, system_dir);\n strcat(fn, \"\/__pyc__.py\");\n filename = dupstr(fn);\n } else\n filename = arg_state.file_argument[i];\n if (!i)\n first_filename = filename;\n mod_ty mod = file_to_mod(filename, arena);\n if (mod)\n mods.add(new PycModule(mod, filename, i < 0));\n }\n if (mods.n > 1) {\n ast_to_if1(mods, arena);\n compile(first_filename);\n }\n PyArena_Free(arena);\n Py_Finalize();\n Service::stop_all();\n exit(0);\n return 0;\n}\n<|endoftext|>"} {"text":"\/\/ [WriteFile Name=LineOfSightGeoElement, Category=Analysis]\n\/\/ [Legal]\n\/\/ Copyright 2019 Esri.\n\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/ [Legal]\n\n#include \"LineOfSightGeoElement.h\"\n\n#include \"ArcGISSceneLayer.h\"\n#include \"ArcGISTiledElevationSource.h\"\n#include \"GeoElementLineOfSight.h\"\n#include \"GeometryEngine.h\"\n#include \"GraphicsOverlay.h\"\n#include \"ModelSceneSymbol.h\"\n#include \"PointBuilder.h\"\n#include \"Scene.h\"\n#include \"SceneQuickView.h\"\n#include \"SimpleMarkerSymbol.h\"\n#include \"SimpleRenderer.h\"\n\n#include \n#include \n\nusing namespace Esri::ArcGISRuntime;\n\nnamespace\n{\n\n\/\/ Initial fixed point to observe taxi.\nconst Point observationPoint(-73.9853, 40.7484, 200, SpatialReference::wgs84());\n\n\/\/ Waypoints around the block for taxi to drive.\nconst std::array waypoints = {{\n { -73.984513, 40.748469, 2, SpatialReference::wgs84() },\n { -73.985068, 40.747786, 2, SpatialReference::wgs84() },\n { -73.983452, 40.747091, 2, SpatialReference::wgs84() },\n { -73.982961, 40.747762, 2, SpatialReference::wgs84() }\n }};\n\n\/\/ Path of Taxi 3D CAD model.\nQString dolmusPath()\n{\n auto homepath = QStandardPaths::standardLocations(QStandardPaths::HomeLocation).last();\n return QDir(homepath).filePath(\"ArcGIS\/Runtime\/Data\/3D\/dolmus_3ds\/dolmus.3ds\");\n}\n\n}\n\nLineOfSightGeoElement::LineOfSightGeoElement(QObject* parent \/* = nullptr *\/):\n QObject(parent),\n m_scene(new Scene(Basemap::imagery(this), this))\n{\n \/\/ create a new elevation source from Terrain3D rest service\n ArcGISTiledElevationSource* elevationSource = new ArcGISTiledElevationSource(\n QUrl(\"https:\/\/elevation3d.arcgis.com\/arcgis\/rest\/services\/WorldElevation3D\/Terrain3D\/ImageServer\"), this);\n\n \/\/ add the elevation source to the scene to display elevation\n m_scene->baseSurface()->elevationSources()->append(elevationSource);\n\n \/\/ Load up the buildings that will block the line of sight.\n ArcGISSceneLayer* buildings = new ArcGISSceneLayer(\n QUrl(\"https:\/\/tiles.arcgis.com\/tiles\/z2tnIkrLQ2BRzr6P\/arcgis\/rest\/services\/New_York_LoD2_3D_Buildings\/SceneServer\/layers\/0\"));\n m_scene->operationalLayers()->append(buildings);\n\n \/\/ Trigger animation of taxi every 100ms.\n m_animation.setInterval(100);\n m_animation.callOnTimeout(this, &LineOfSightGeoElement::animate);\n}\n\nLineOfSightGeoElement::~LineOfSightGeoElement() = default;\n\nvoid LineOfSightGeoElement::init()\n{\n \/\/ Register classes for QML\n qmlRegisterType(\"Esri.Samples\", 1, 0, \"SceneView\");\n qmlRegisterType(\"Esri.Samples\", 1, 0, \"LineOfSightGeoElementSample\");\n}\n\ndouble LineOfSightGeoElement::heightZ() const\n{\n if (m_observer)\n {\n const Point p = geometry_cast(m_observer->geometry());\n return p.isValid() ? p.z() : 0.0;\n }\n else\n {\n return 0.0;\n }\n}\nvoid LineOfSightGeoElement::setHeightZ(double z)\n{\n if (!m_observer)\n return;\n\n const Point p = geometry_cast(m_observer->geometry());\n if (p.isValid())\n {\n PointBuilder builder(p);\n builder.setZ(z);\n m_observer->setGeometry(builder.toGeometry());\n emit heightZChanged();\n }\n}\n\nSceneQuickView* LineOfSightGeoElement::sceneView() const\n{\n return m_sceneView;\n}\n\n\/\/ Set the view (created in QML)\nvoid LineOfSightGeoElement::setSceneView(SceneQuickView* sceneView)\n{\n if (!sceneView || sceneView == m_sceneView)\n {\n return;\n }\n\n m_sceneView = sceneView;\n m_sceneView->setArcGISScene(m_scene);\n emit sceneViewChanged();\n\n \/\/ Setup the graphics overlay - ensure that all z-position are relative to the height of the surface.\n GraphicsOverlay* graphicsOverlay = new GraphicsOverlay(this);\n {\n LayerSceneProperties properties = graphicsOverlay->sceneProperties();\n properties.setSurfacePlacement(SurfacePlacement::Relative);\n graphicsOverlay->setSceneProperties(properties);\n }\n m_sceneView->graphicsOverlays()->append(graphicsOverlay);\n\n \/\/ Set up the renderer so that we can orient the taxi using the `HEADING` attribute.\n SimpleRenderer* renderer3D = new SimpleRenderer(this);\n {\n RendererSceneProperties properties = renderer3D->sceneProperties();\n properties.setHeadingExpression(\"[HEADING]\");\n renderer3D->setSceneProperties(properties);\n }\n graphicsOverlay->setRenderer(renderer3D);\n\n \/\/ Create our observation point as a red sphere.\n m_observer = new Graphic(observationPoint, new SimpleMarkerSymbol(SimpleMarkerSymbolStyle::Circle, Qt::red, 5.f), this);\n emit heightZChanged(); \/\/ We now have a point to extract the Z-height from.\n graphicsOverlay->graphics()->append(m_observer);\n\n \/\/ Get our Taxi model. We will attempt to load it and continue our setup after it has loaded.\n ModelSceneSymbol* taxiSymbol = new ModelSceneSymbol(dolmusPath(), 1.0, this);\n taxiSymbol->setAnchorPosition(SceneSymbolAnchorPosition::Bottom);\n\n connect(taxiSymbol, &ModelSceneSymbol::doneLoading, this,\n [this, graphicsOverlay, taxiSymbol](Error error)\n {\n if (!error.isEmpty())\n {\n return;\n }\n\n \/\/ Create taxi from loaded taxi symbol, with an initial \"HEADING\" attribute for orientation.\n m_taxi = new Graphic(waypoints.front(), taxiSymbol, this);\n m_taxi->attributes()->insertAttribute(\"HEADING\", 0.0);\n graphicsOverlay->graphics()->append(m_taxi);\n\n \/\/ Set up our line of sight analysis.\n AnalysisOverlay* analysisOverlay = new AnalysisOverlay(this);\n m_sceneView->analysisOverlays()->append(analysisOverlay);\n\n GeoElementLineOfSight* lineOfSight = new GeoElementLineOfSight(m_observer, m_taxi, this);\n analysisOverlay->analyses()->append(lineOfSight);\n\n connect(lineOfSight, &GeoElementLineOfSight::targetVisibilityChanged, this,\n [this](LineOfSightTargetVisibility targetVisibility)\n {\n \/\/ Select taxi whenever there is a clear line of sight from observer position.\n m_taxi->setSelected(targetVisibility == LineOfSightTargetVisibility::Visible);\n });\n\n Camera camera(observationPoint, 700, -30, 45, 0);\n m_sceneView->setViewpointCamera(camera, 0);\n\n m_animation.start();\n });\n\n taxiSymbol->load();\n}\n\nvoid LineOfSightGeoElement::animate()\n{\n \/\/ Goal point to travel to\n Point waypoint = waypoints.at(m_waypointIndex);\n\n \/\/ Calculate azimuth between current location and goal location for taxi.\n Point location = geometry_cast(m_taxi->geometry());\n\n if (!location.isValid())\n return;\n\n GeodeticDistanceResult distance = GeometryEngine::distanceGeodetic(\n location, waypoint, LinearUnit::meters(), AngularUnit::degrees(), GeodeticCurveType::Geodesic);\n\n \/\/ Move taxi one metre along the line between its current position and the goal location.\n QList newPoints = GeometryEngine::moveGeodetic(\n { location }, 1.0, LinearUnit::meters(), distance.azimuth1(), AngularUnit::degrees(), GeodeticCurveType::Geodesic);\n if (newPoints.size() > 0)\n {\n location = newPoints.last();\n }\n\n \/\/ Update taxi position and orientation.\n m_taxi->setGeometry(geometry_cast(location));\n m_taxi->attributes()->replaceAttribute(\"HEADING\", distance.azimuth1());\n\n \/\/ When taxi is close enough to the waypoint then increment the index for a new goal next animation step.\n \/\/ Index is cyclic and an element of [0, 3].\n if (distance.distance() <= 2) {\n m_waypointIndex = (m_waypointIndex + 1) % waypoints.size();\n }\n}\nIncluded missing import for mac.\/\/ [WriteFile Name=LineOfSightGeoElement, Category=Analysis]\n\/\/ [Legal]\n\/\/ Copyright 2019 Esri.\n\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/ [Legal]\n\n#include \"LineOfSightGeoElement.h\"\n\n#include \"ArcGISSceneLayer.h\"\n#include \"ArcGISTiledElevationSource.h\"\n#include \"GeoElementLineOfSight.h\"\n#include \"GeometryEngine.h\"\n#include \"GraphicsOverlay.h\"\n#include \"ModelSceneSymbol.h\"\n#include \"PointBuilder.h\"\n#include \"Scene.h\"\n#include \"SceneQuickView.h\"\n#include \"SimpleMarkerSymbol.h\"\n#include \"SimpleRenderer.h\"\n\n#include \n\n#include \n#include \n\nusing namespace Esri::ArcGISRuntime;\n\nnamespace\n{\n\n\/\/ Initial fixed point to observe taxi.\nconst Point observationPoint(-73.9853, 40.7484, 200, SpatialReference::wgs84());\n\n\/\/ Waypoints around the block for taxi to drive.\nconst std::array waypoints = {{\n { -73.984513, 40.748469, 2, SpatialReference::wgs84() },\n { -73.985068, 40.747786, 2, SpatialReference::wgs84() },\n { -73.983452, 40.747091, 2, SpatialReference::wgs84() },\n { -73.982961, 40.747762, 2, SpatialReference::wgs84() }\n }};\n\n\/\/ Path of Taxi 3D CAD model.\nQString dolmusPath()\n{\n auto homepath = QStandardPaths::standardLocations(QStandardPaths::HomeLocation).last();\n return QDir(homepath).filePath(\"ArcGIS\/Runtime\/Data\/3D\/dolmus_3ds\/dolmus.3ds\");\n}\n\n}\n\nLineOfSightGeoElement::LineOfSightGeoElement(QObject* parent \/* = nullptr *\/):\n QObject(parent),\n m_scene(new Scene(Basemap::imagery(this), this))\n{\n \/\/ create a new elevation source from Terrain3D rest service\n ArcGISTiledElevationSource* elevationSource = new ArcGISTiledElevationSource(\n QUrl(\"https:\/\/elevation3d.arcgis.com\/arcgis\/rest\/services\/WorldElevation3D\/Terrain3D\/ImageServer\"), this);\n\n \/\/ add the elevation source to the scene to display elevation\n m_scene->baseSurface()->elevationSources()->append(elevationSource);\n\n \/\/ Load up the buildings that will block the line of sight.\n ArcGISSceneLayer* buildings = new ArcGISSceneLayer(\n QUrl(\"https:\/\/tiles.arcgis.com\/tiles\/z2tnIkrLQ2BRzr6P\/arcgis\/rest\/services\/New_York_LoD2_3D_Buildings\/SceneServer\/layers\/0\"));\n m_scene->operationalLayers()->append(buildings);\n\n \/\/ Trigger animation of taxi every 100ms.\n m_animation.setInterval(100);\n m_animation.callOnTimeout(this, &LineOfSightGeoElement::animate);\n}\n\nLineOfSightGeoElement::~LineOfSightGeoElement() = default;\n\nvoid LineOfSightGeoElement::init()\n{\n \/\/ Register classes for QML\n qmlRegisterType(\"Esri.Samples\", 1, 0, \"SceneView\");\n qmlRegisterType(\"Esri.Samples\", 1, 0, \"LineOfSightGeoElementSample\");\n}\n\ndouble LineOfSightGeoElement::heightZ() const\n{\n if (m_observer)\n {\n const Point p = geometry_cast(m_observer->geometry());\n return p.isValid() ? p.z() : 0.0;\n }\n else\n {\n return 0.0;\n }\n}\nvoid LineOfSightGeoElement::setHeightZ(double z)\n{\n if (!m_observer)\n return;\n\n const Point p = geometry_cast(m_observer->geometry());\n if (p.isValid())\n {\n PointBuilder builder(p);\n builder.setZ(z);\n m_observer->setGeometry(builder.toGeometry());\n emit heightZChanged();\n }\n}\n\nSceneQuickView* LineOfSightGeoElement::sceneView() const\n{\n return m_sceneView;\n}\n\n\/\/ Set the view (created in QML)\nvoid LineOfSightGeoElement::setSceneView(SceneQuickView* sceneView)\n{\n if (!sceneView || sceneView == m_sceneView)\n {\n return;\n }\n\n m_sceneView = sceneView;\n m_sceneView->setArcGISScene(m_scene);\n emit sceneViewChanged();\n\n \/\/ Setup the graphics overlay - ensure that all z-position are relative to the height of the surface.\n GraphicsOverlay* graphicsOverlay = new GraphicsOverlay(this);\n {\n LayerSceneProperties properties = graphicsOverlay->sceneProperties();\n properties.setSurfacePlacement(SurfacePlacement::Relative);\n graphicsOverlay->setSceneProperties(properties);\n }\n m_sceneView->graphicsOverlays()->append(graphicsOverlay);\n\n \/\/ Set up the renderer so that we can orient the taxi using the `HEADING` attribute.\n SimpleRenderer* renderer3D = new SimpleRenderer(this);\n {\n RendererSceneProperties properties = renderer3D->sceneProperties();\n properties.setHeadingExpression(\"[HEADING]\");\n renderer3D->setSceneProperties(properties);\n }\n graphicsOverlay->setRenderer(renderer3D);\n\n \/\/ Create our observation point as a red sphere.\n m_observer = new Graphic(observationPoint, new SimpleMarkerSymbol(SimpleMarkerSymbolStyle::Circle, Qt::red, 5.f), this);\n emit heightZChanged(); \/\/ We now have a point to extract the Z-height from.\n graphicsOverlay->graphics()->append(m_observer);\n\n \/\/ Get our Taxi model. We will attempt to load it and continue our setup after it has loaded.\n ModelSceneSymbol* taxiSymbol = new ModelSceneSymbol(dolmusPath(), 1.0, this);\n taxiSymbol->setAnchorPosition(SceneSymbolAnchorPosition::Bottom);\n\n connect(taxiSymbol, &ModelSceneSymbol::doneLoading, this,\n [this, graphicsOverlay, taxiSymbol](Error error)\n {\n if (!error.isEmpty())\n {\n return;\n }\n\n \/\/ Create taxi from loaded taxi symbol, with an initial \"HEADING\" attribute for orientation.\n m_taxi = new Graphic(waypoints.front(), taxiSymbol, this);\n m_taxi->attributes()->insertAttribute(\"HEADING\", 0.0);\n graphicsOverlay->graphics()->append(m_taxi);\n\n \/\/ Set up our line of sight analysis.\n AnalysisOverlay* analysisOverlay = new AnalysisOverlay(this);\n m_sceneView->analysisOverlays()->append(analysisOverlay);\n\n GeoElementLineOfSight* lineOfSight = new GeoElementLineOfSight(m_observer, m_taxi, this);\n analysisOverlay->analyses()->append(lineOfSight);\n\n connect(lineOfSight, &GeoElementLineOfSight::targetVisibilityChanged, this,\n [this](LineOfSightTargetVisibility targetVisibility)\n {\n \/\/ Select taxi whenever there is a clear line of sight from observer position.\n m_taxi->setSelected(targetVisibility == LineOfSightTargetVisibility::Visible);\n });\n\n Camera camera(observationPoint, 700, -30, 45, 0);\n m_sceneView->setViewpointCamera(camera, 0);\n\n m_animation.start();\n });\n\n taxiSymbol->load();\n}\n\nvoid LineOfSightGeoElement::animate()\n{\n \/\/ Goal point to travel to\n Point waypoint = waypoints.at(m_waypointIndex);\n\n \/\/ Calculate azimuth between current location and goal location for taxi.\n Point location = geometry_cast(m_taxi->geometry());\n\n if (!location.isValid())\n return;\n\n GeodeticDistanceResult distance = GeometryEngine::distanceGeodetic(\n location, waypoint, LinearUnit::meters(), AngularUnit::degrees(), GeodeticCurveType::Geodesic);\n\n \/\/ Move taxi one metre along the line between its current position and the goal location.\n QList newPoints = GeometryEngine::moveGeodetic(\n { location }, 1.0, LinearUnit::meters(), distance.azimuth1(), AngularUnit::degrees(), GeodeticCurveType::Geodesic);\n if (newPoints.size() > 0)\n {\n location = newPoints.last();\n }\n\n \/\/ Update taxi position and orientation.\n m_taxi->setGeometry(geometry_cast(location));\n m_taxi->attributes()->replaceAttribute(\"HEADING\", distance.azimuth1());\n\n \/\/ When taxi is close enough to the waypoint then increment the index for a new goal next animation step.\n \/\/ Index is cyclic and an element of [0, 3].\n if (distance.distance() <= 2) {\n m_waypointIndex = (m_waypointIndex + 1) % waypoints.size();\n }\n}\n<|endoftext|>"} {"text":"\/\/ ========================================================================== \/\/\n\/\/ This file is part of DO++, a basic set of libraries in C++ for computer \n\/\/ vision.\n\/\/\n\/\/ Copyright (C) 2014 David Ok \n\/\/\n\/\/ This Source Code Form is subject to the terms of the Mozilla Public \n\/\/ License v. 2.0. If a copy of the MPL was not distributed with this file, \n\/\/ you can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\/\/ ========================================================================== \/\/\n\n#include \n#include \n#include \n\n#include \n\n#include \"AssertHelpers.hpp\"\n#include \"pixel.hpp\"\n#include \"color_conversion.hpp\"\n\n\nusing namespace std;\nusing namespace DO;\n\n\n\/\/ ========================================================================== \/\/\n\/\/ Define the set of integral channel types, which we will test.\ntypedef testing::Types FloatingPointChannelTypes;\n\n\n\/\/ ========================================================================== \/\/\n\/\/ Define the parameterized test case.\ntemplate \nclass TestConvertColorConversion : public testing::Test {};\nTYPED_TEST_CASE_P(TestConvertColorConversion);\n\n\n\/\/ ========================================================================== \/\/\n\/\/ RGB <-> RGBA.\nTEST(TestConvertColorConversionBetweenRGB, test_rgb_to_rgba)\n{\n Pixel rgb(1,1,1);\n Pixel rgba;\n convert_color(rgb, rgba);\n EXPECT_EQ(Vector4d(1,1,1,1), rgba);\n}\n\nTEST(TestConvertColorConversionBetweenRGB, test_rgb_to_rgba)\n{\n Pixel rgba(1,1,1,1);\n Pixel rgb;\n convert_color(rgba, rgb);\n EXPECT_EQ(Vector3d(1,1,1), rgb);\n}\n\n\/\/ ========================================================================== \/\/\n\/\/ RGB <-> grayscale.\nTYPED_TEST_P(TestConvertColorConversion, test_rgb_to_gray)\n{\n typedef TypeParam T;\n \/\/ Using the explicit function.\n {\n Matrix rgb(1,1,1);\n T gray;\n rgb_to_gray(rgb, gray);\n EXPECT_NEAR(gray, 1, T(1e-3));\n }\n \/\/ Using the unified API.\n {\n Pixel rgb(1,1,1);\n T gray;\n convert_color(rgb, gray);\n EXPECT_NEAR(gray, 1, T(1e-3));\n }\n}\n\nTYPED_TEST_P(TestConvertColorConversion, test_gray_to_rgb)\n{\n \/\/ Using the explicit function.\n typedef TypeParam T;\n {\n const T src_gray = T(0.5);\n const Matrix expected_rgb(src_gray, src_gray, src_gray);\n Matrix actual_rgb;\n gray_to_rgb(src_gray, actual_rgb);\n EXPECT_EQ(expected_rgb, actual_rgb);\n }\n \/\/ Using the unified API.\n {\n const T src_gray = T(0.5);\n const Pixel expected_rgb(src_gray, src_gray, src_gray);\n Pixel actual_rgb;\n convert_color(src_gray, actual_rgb);\n EXPECT_EQ(expected_rgb, actual_rgb);\n }\n}\n\n\n\/\/ ========================================================================== \/\/\n\/\/ RGB <-> YUV.\nTYPED_TEST_P(TestConvertColorConversion, test_rgb_to_yuv)\n{\n typedef TypeParam T;\n typedef Matrix Vec3;\n const Vec3 rgb[] = {\n Vec3(1, 0, 0),\n Vec3(0, 1, 0),\n Vec3(0, 0, 1)\n };\n const Vec3 expected_yuv[] = {\n Vec3(0.299, 0.492*(0-0.299), 0.877*(1-0.299)),\n Vec3(0.587, 0.492*(0-0.587), 0.877*(0-0.587)),\n Vec3(0.114, 0.492*(1-0.114), 0.877*(0-0.114))\n };\n \/\/ Using the explicit function.\n for (int i = 0; i < 3; ++i)\n {\n Vec3 actual_yuv;\n rgb_to_yuv(rgb[i], actual_yuv);\n EXPECT_MATRIX_NEAR(expected_yuv[i], actual_yuv, T(1e-3));\n }\n \/\/ Using the unified API.\n for (int i = 0; i < 3; ++i)\n {\n const Pixel rgb_pixel(rgb[i]);\n const Pixel expected_yuv_pixel(expected_yuv[i]);\n Pixel actual_yuv_pixel;\n convert_color(rgb_pixel, actual_yuv_pixel);\n EXPECT_MATRIX_NEAR(expected_yuv_pixel, actual_yuv_pixel, T(1e-3));\n }\n}\n\nTYPED_TEST_P(TestConvertColorConversion, test_yuv_to_rgb)\n{\n typedef TypeParam T;\n typedef Matrix Vec3;\n const Vec3 yuv[] = {\n Vec3(1, 0 , 0 ),\n Vec3(0, 0.436, 0 ),\n Vec3(0, 0 , 0.615)\n };\n const Vec3 expected_rgb[] = {\n Vec3(1 , 1 , 1 ),\n Vec3(0 , -0.39465*0.436, 2.03211*0.436),\n Vec3(1.13983*0.615, -0.58060*0.615, 0 )\n };\n \/\/ Using the explicit function.\n for (int i = 0; i < 3; ++i)\n {\n Vec3 actual_rgb;\n yuv_to_rgb(yuv[i], actual_rgb);\n EXPECT_MATRIX_NEAR(expected_rgb[i], actual_rgb, T(1e-3));\n }\n \/\/ Using the unified API.\n for (int i = 0; i < 3; ++i)\n {\n const Pixel yuv_pixel(yuv[i]);\n const Pixel expected_rgb_pixel(expected_rgb[i]);\n Pixel actual_rgb_pixel;\n convert_color(yuv_pixel, actual_rgb_pixel);\n EXPECT_MATRIX_NEAR(expected_rgb_pixel, actual_rgb_pixel, T(1e-3));\n }\n}\n\n\n\/\/ ========================================================================== \/\/\n\/\/ YUV <-> Gray\nTYPED_TEST_P(TestConvertColorConversion, test_yuv_to_gray)\n{\n typedef TypeParam T;\n typedef Matrix Vec3;\n const Vec3 yuv(1, 0, 0);\n {\n T gray;\n yuv_to_gray(yuv, gray);\n EXPECT_EQ(1, gray);\n }\n {\n Pixel yuv_pixel(yuv);\n T gray;\n convert_color(yuv, gray);\n EXPECT_EQ(1, gray);\n }\n}\n\nTYPED_TEST_P(TestConvertColorConversion, test_gray_to_yuv)\n{\n typedef TypeParam T;\n typedef Matrix Vec3;\n T gray = T(0.5);\n {\n Vec3 yuv;\n const Vec3 expected_yuv(0.5, 0, 0);\n gray_to_yuv(gray, yuv);\n EXPECT_EQ(expected_yuv, yuv);\n }\n {\n Pixel yuv;\n const Pixel expected_yuv(0.5, 0, 0);\n convert_color(gray, yuv);\n EXPECT_EQ(expected_yuv, yuv);\n }\n}\n\n\n\/\/ ========================================================================== \/\/\n\/\/ Register all typed tests and instantiate them.\nREGISTER_TYPED_TEST_CASE_P(TestConvertColorConversion,\n test_rgb_to_gray,\n test_gray_to_rgb,\n test_rgb_to_yuv,\n test_yuv_to_rgb,\n test_yuv_to_gray,\n test_gray_to_yuv);\nINSTANTIATE_TYPED_TEST_CASE_P(Core_Pixel_ColorConversion,\n TestConvertColorConversion,\n FloatingPointChannelTypes);\n\n\n\/\/ ========================================================================== \/\/\n\/\/ Run the tests.\nint main(int argc, char** argv) \n{\n testing::InitGoogleTest(&argc, argv); \n return RUN_ALL_TESTS();\n}Fix test names.\/\/ ========================================================================== \/\/\n\/\/ This file is part of DO++, a basic set of libraries in C++ for computer \n\/\/ vision.\n\/\/\n\/\/ Copyright (C) 2014 David Ok \n\/\/\n\/\/ This Source Code Form is subject to the terms of the Mozilla Public \n\/\/ License v. 2.0. If a copy of the MPL was not distributed with this file, \n\/\/ you can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\/\/ ========================================================================== \/\/\n\n#include \n#include \n#include \n\n#include \n\n#include \"AssertHelpers.hpp\"\n#include \"pixel.hpp\"\n#include \"color_conversion.hpp\"\n\n\nusing namespace std;\nusing namespace DO;\n\n\n\/\/ ========================================================================== \/\/\n\/\/ Define the set of integral channel types, which we will test.\ntypedef testing::Types FloatingPointChannelTypes;\n\n\n\/\/ ========================================================================== \/\/\n\/\/ Define the parameterized test case.\ntemplate \nclass TestConvertColorConversion : public testing::Test {};\nTYPED_TEST_CASE_P(TestConvertColorConversion);\n\n\n\/\/ ========================================================================== \/\/\n\/\/ RGB <-> RGBA.\nTEST(TestConvertColorConversion, test_rgb_to_rgba)\n{\n Pixel rgb(1,1,1);\n Pixel rgba;\n convert_color(rgb, rgba);\n EXPECT_EQ(Vector4d(1,1,1,1), rgba);\n}\n\nTEST(TestConvertColorConversion, test_rgba_to_rgb)\n{\n Pixel rgba(1,1,1,1);\n Pixel rgb;\n convert_color(rgba, rgb);\n EXPECT_EQ(Vector3d(1,1,1), rgb);\n}\n\n\/\/ ========================================================================== \/\/\n\/\/ RGB <-> grayscale.\nTYPED_TEST_P(TestConvertColorConversion, test_rgb_to_gray)\n{\n typedef TypeParam T;\n \/\/ Using the explicit function.\n {\n Matrix rgb(1,1,1);\n T gray;\n rgb_to_gray(rgb, gray);\n EXPECT_NEAR(gray, 1, T(1e-3));\n }\n \/\/ Using the unified API.\n {\n Pixel rgb(1,1,1);\n T gray;\n convert_color(rgb, gray);\n EXPECT_NEAR(gray, 1, T(1e-3));\n }\n}\n\nTYPED_TEST_P(TestConvertColorConversion, test_gray_to_rgb)\n{\n \/\/ Using the explicit function.\n typedef TypeParam T;\n {\n const T src_gray = T(0.5);\n const Matrix expected_rgb(src_gray, src_gray, src_gray);\n Matrix actual_rgb;\n gray_to_rgb(src_gray, actual_rgb);\n EXPECT_EQ(expected_rgb, actual_rgb);\n }\n \/\/ Using the unified API.\n {\n const T src_gray = T(0.5);\n const Pixel expected_rgb(src_gray, src_gray, src_gray);\n Pixel actual_rgb;\n convert_color(src_gray, actual_rgb);\n EXPECT_EQ(expected_rgb, actual_rgb);\n }\n}\n\n\n\/\/ ========================================================================== \/\/\n\/\/ RGB <-> YUV.\nTYPED_TEST_P(TestConvertColorConversion, test_rgb_to_yuv)\n{\n typedef TypeParam T;\n typedef Matrix Vec3;\n const Vec3 rgb[] = {\n Vec3(1, 0, 0),\n Vec3(0, 1, 0),\n Vec3(0, 0, 1)\n };\n const Vec3 expected_yuv[] = {\n Vec3(0.299, 0.492*(0-0.299), 0.877*(1-0.299)),\n Vec3(0.587, 0.492*(0-0.587), 0.877*(0-0.587)),\n Vec3(0.114, 0.492*(1-0.114), 0.877*(0-0.114))\n };\n \/\/ Using the explicit function.\n for (int i = 0; i < 3; ++i)\n {\n Vec3 actual_yuv;\n rgb_to_yuv(rgb[i], actual_yuv);\n EXPECT_MATRIX_NEAR(expected_yuv[i], actual_yuv, T(1e-3));\n }\n \/\/ Using the unified API.\n for (int i = 0; i < 3; ++i)\n {\n const Pixel rgb_pixel(rgb[i]);\n const Pixel expected_yuv_pixel(expected_yuv[i]);\n Pixel actual_yuv_pixel;\n convert_color(rgb_pixel, actual_yuv_pixel);\n EXPECT_MATRIX_NEAR(expected_yuv_pixel, actual_yuv_pixel, T(1e-3));\n }\n}\n\nTYPED_TEST_P(TestConvertColorConversion, test_yuv_to_rgb)\n{\n typedef TypeParam T;\n typedef Matrix Vec3;\n const Vec3 yuv[] = {\n Vec3(1, 0 , 0 ),\n Vec3(0, 0.436, 0 ),\n Vec3(0, 0 , 0.615)\n };\n const Vec3 expected_rgb[] = {\n Vec3(1 , 1 , 1 ),\n Vec3(0 , -0.39465*0.436, 2.03211*0.436),\n Vec3(1.13983*0.615, -0.58060*0.615, 0 )\n };\n \/\/ Using the explicit function.\n for (int i = 0; i < 3; ++i)\n {\n Vec3 actual_rgb;\n yuv_to_rgb(yuv[i], actual_rgb);\n EXPECT_MATRIX_NEAR(expected_rgb[i], actual_rgb, T(1e-3));\n }\n \/\/ Using the unified API.\n for (int i = 0; i < 3; ++i)\n {\n const Pixel yuv_pixel(yuv[i]);\n const Pixel expected_rgb_pixel(expected_rgb[i]);\n Pixel actual_rgb_pixel;\n convert_color(yuv_pixel, actual_rgb_pixel);\n EXPECT_MATRIX_NEAR(expected_rgb_pixel, actual_rgb_pixel, T(1e-3));\n }\n}\n\n\n\/\/ ========================================================================== \/\/\n\/\/ YUV <-> Gray\nTYPED_TEST_P(TestConvertColorConversion, test_yuv_to_gray)\n{\n typedef TypeParam T;\n typedef Matrix Vec3;\n const Vec3 yuv(1, 0, 0);\n {\n T gray;\n yuv_to_gray(yuv, gray);\n EXPECT_EQ(1, gray);\n }\n {\n Pixel yuv_pixel(yuv);\n T gray;\n convert_color(yuv, gray);\n EXPECT_EQ(1, gray);\n }\n}\n\nTYPED_TEST_P(TestConvertColorConversion, test_gray_to_yuv)\n{\n typedef TypeParam T;\n typedef Matrix Vec3;\n T gray = T(0.5);\n {\n Vec3 yuv;\n const Vec3 expected_yuv(0.5, 0, 0);\n gray_to_yuv(gray, yuv);\n EXPECT_EQ(expected_yuv, yuv);\n }\n {\n Pixel yuv;\n const Pixel expected_yuv(0.5, 0, 0);\n convert_color(gray, yuv);\n EXPECT_EQ(expected_yuv, yuv);\n }\n}\n\n\n\/\/ ========================================================================== \/\/\n\/\/ Register all typed tests and instantiate them.\nREGISTER_TYPED_TEST_CASE_P(TestConvertColorConversion,\n test_rgb_to_gray,\n test_gray_to_rgb,\n test_rgb_to_yuv,\n test_yuv_to_rgb,\n test_yuv_to_gray,\n test_gray_to_yuv);\nINSTANTIATE_TYPED_TEST_CASE_P(Core_Pixel_ColorConversion,\n TestConvertColorConversion,\n FloatingPointChannelTypes);\n\n\n\/\/ ========================================================================== \/\/\n\/\/ Run the tests.\nint main(int argc, char** argv) \n{\n testing::InitGoogleTest(&argc, argv); \n return RUN_ALL_TESTS();\n}<|endoftext|>"} {"text":"\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/command_line.h\"\n#include \"chrome\/browser\/extensions\/extension_apitest.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, Popup) {\n CommandLine::ForCurrentProcess()->AppendSwitch(\n switches::kEnableExperimentalExtensionApis);\n ASSERT_TRUE(RunExtensionTest(\"popup_api\")) << message_;\n}\nDisable flaky (crashing) ExtensionApiTest.Popup\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/command_line.h\"\n#include \"chrome\/browser\/extensions\/extension_apitest.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n\n\/\/ This test has been disabled because it was crashing \n\/\/ browsertests. crbug.com\/26599\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_Popup) {\n CommandLine::ForCurrentProcess()->AppendSwitch(\n switches::kEnableExperimentalExtensionApis);\n ASSERT_TRUE(RunExtensionTest(\"popup_api\")) << message_;\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: cacheoptions.cxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: ka $ $Date: 2001-04-19 12:15:57 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#pragma hdrstop\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ includes\n\/\/_________________________________________________________________________________________________________________\n\n#include \"cacheoptions.hxx\"\n\n#ifndef _UTL_CONFIGMGR_HXX_\n#include \n#endif\n#ifndef _UTL_CONFIGITEM_HXX_\n#include \n#endif\n#ifndef _TOOLS_DEBUG_HXX\n#include \n#endif\n#ifndef _COM_SUN_STAR_UNO_ANY_HXX_\n#include \n#endif\n#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_\n#include \n#endif\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ namespaces\n\/\/_________________________________________________________________________________________________________________\n\nusing namespace ::utl;\nusing namespace ::rtl;\nusing namespace ::osl;\nusing namespace ::com::sun::star::uno;\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ const\n\/\/_________________________________________________________________________________________________________________\n\n#define ROOTNODE_START OUString(RTL_CONSTASCII_USTRINGPARAM(\"Office.Common\/Cache\" ))\n#define DEFAULT_WRITEROLE 20\n#define DEFAULT_DRAWINGOLE 20\n#define DEFAULT_GRFMGR_TOTALSIZE 10000000\n#define DEFAULT_GRFMGR_OBJECTSIZE 2400000\n\n#define PROPERTYNAME_WRITEROLE OUString(RTL_CONSTASCII_USTRINGPARAM(\"Writer\/OLE_Objects\"))\n#define PROPERTYNAME_DRAWINGOLE OUString(RTL_CONSTASCII_USTRINGPARAM(\"DrawingEngine\/OLE_Objects\"))\n#define PROPERTYNAME_GRFMGR_TOTALSIZE OUString(RTL_CONSTASCII_USTRINGPARAM(\"GraphicManager\/TotalCacheSize\"))\n#define PROPERTYNAME_GRFMGR_OBJECTSIZE OUString(RTL_CONSTASCII_USTRINGPARAM(\"GraphicManager\/ObjectCacheSize\"))\n\n#define PROPERTYHANDLE_WRITEROLE 0\n#define PROPERTYHANDLE_DRAWINGOLE 1\n#define PROPERTYHANDLE_GRFMGR_TOTALSIZE 2\n#define PROPERTYHANDLE_GRFMGR_OBJECTSIZE 3\n\n#define PROPERTYCOUNT 4\n\nclass SvtCacheOptions_Impl : public ConfigItem\n{\npublic:\n\n\/\/---------------------------------------------------------------------------------------------------------\n\/\/ constructor \/ destructor\n\/\/---------------------------------------------------------------------------------------------------------\n\n SvtCacheOptions_Impl();\n ~SvtCacheOptions_Impl();\n\n\/\/---------------------------------------------------------------------------------------------------------\n\/\/ overloaded methods of baseclass\n\/\/---------------------------------------------------------------------------------------------------------\n\n virtual void Commit();\n\n\/\/---------------------------------------------------------------------------------------------------------\n\/\/ public interface\n\/\/---------------------------------------------------------------------------------------------------------\n\n sal_Int32 GetWriterOLE_Objects() const;\n sal_Int32 GetDrawingEngineOLE_Objects() const;\n sal_Int32 GetGraphicManagerTotalCacheSize() const;\n sal_Int32 GetGraphicManagerObjectCacheSize() const;\n\n void SetWriterOLE_Objects( sal_Int32 nObjects );\n void SetDrawingEngineOLE_Objects( sal_Int32 nObjects );\n void SetGraphicManagerTotalCacheSize( sal_Int32 nTotalCacheSize );\n void SetGraphicManagerObjectCacheSize( sal_Int32 nObjectCacheSize );\n\n\/\/-------------------------------------------------------------------------------------------------------------\n\/\/ private methods\n\/\/-------------------------------------------------------------------------------------------------------------\n\nprivate:\n\n static Sequence< OUString > impl_GetPropertyNames();\n\n\/\/-------------------------------------------------------------------------------------------------------------\n\/\/ private member\n\/\/-------------------------------------------------------------------------------------------------------------\n\nprivate:\n\n sal_Int32 mnWriterOLE;\n sal_Int32 mnDrawingOLE;\n sal_Int32 mnGrfMgrTotalSize;\n sal_Int32 mnGrfMgrObjectSize;\n};\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ definitions\n\/\/_________________________________________________________________________________________________________________\n\n\/\/*****************************************************************************************************************\n\/\/ constructor\n\/\/*****************************************************************************************************************\nSvtCacheOptions_Impl::SvtCacheOptions_Impl() :\n ConfigItem( ROOTNODE_START ),\n mnWriterOLE( DEFAULT_WRITEROLE ),\n mnDrawingOLE( DEFAULT_DRAWINGOLE ),\n mnGrfMgrTotalSize( DEFAULT_GRFMGR_TOTALSIZE ),\n mnGrfMgrObjectSize( DEFAULT_GRFMGR_OBJECTSIZE )\n{\n Sequence< OUString > seqNames( impl_GetPropertyNames() );\n Sequence< Any > seqValues = GetProperties( seqNames ) ;\n\n DBG_ASSERT( !(seqNames.getLength()!=seqValues.getLength()), \"SvtCacheOptions_Impl::SvtCacheOptions_Impl()\\nI miss some values of configuration keys!\\n\" );\n\n \/\/ Copy values from list in right order to ouer internal member.\n sal_Int32 nPropertyCount = seqValues.getLength();\n sal_Int32 nProperty = 0;\n\n for( nProperty=0; nProperty>= mnWriterOLE;\n }\n break;\n\n case PROPERTYHANDLE_DRAWINGOLE:\n {\n if( seqValues[ nProperty ].getValueTypeClass() == TypeClass_LONG )\n seqValues[nProperty] >>= mnDrawingOLE;\n }\n break;\n\n case PROPERTYHANDLE_GRFMGR_TOTALSIZE:\n {\n if( seqValues[ nProperty ].getValueTypeClass() == TypeClass_LONG )\n seqValues[nProperty] >>= mnGrfMgrTotalSize;\n }\n break;\n\n case PROPERTYHANDLE_GRFMGR_OBJECTSIZE:\n {\n if( seqValues[ nProperty ].getValueTypeClass() == TypeClass_LONG )\n seqValues[nProperty] >>= mnGrfMgrObjectSize;\n }\n break;\n }\n }\n}\n\n\/\/*****************************************************************************************************************\n\/\/ destructor\n\/\/*****************************************************************************************************************\nSvtCacheOptions_Impl::~SvtCacheOptions_Impl()\n{\n if( IsModified() )\n Commit();\n}\n\n\/\/*****************************************************************************************************************\n\/\/ Commit\n\/\/*****************************************************************************************************************\nvoid SvtCacheOptions_Impl::Commit()\n{\n Sequence< OUString > aSeqNames( impl_GetPropertyNames() );\n Sequence< Any > aSeqValues( aSeqNames.getLength() );\n\n for( sal_Int32 nProperty = 0, nCount = aSeqNames.getLength(); nProperty < nCount; ++nProperty )\n {\n switch( nProperty )\n {\n case PROPERTYHANDLE_WRITEROLE:\n aSeqValues[nProperty] <<= mnWriterOLE;\n break;\n\n case PROPERTYHANDLE_DRAWINGOLE:\n aSeqValues[nProperty] <<= mnDrawingOLE;\n break;\n\n case PROPERTYHANDLE_GRFMGR_TOTALSIZE:\n aSeqValues[nProperty] <<= mnGrfMgrTotalSize;\n break;\n\n case PROPERTYHANDLE_GRFMGR_OBJECTSIZE:\n aSeqValues[nProperty] <<= mnGrfMgrObjectSize;\n break;\n }\n }\n\n PutProperties( aSeqNames, aSeqValues );\n}\n\n\/\/*****************************************************************************************************************\n\/\/ public method\n\/\/*****************************************************************************************************************\nsal_Int32 SvtCacheOptions_Impl::GetWriterOLE_Objects() const\n{\n return mnWriterOLE;\n}\n\n\/\/*****************************************************************************************************************\n\/\/ public method\n\/\/*****************************************************************************************************************\nsal_Int32 SvtCacheOptions_Impl::GetDrawingEngineOLE_Objects() const\n{\n return mnDrawingOLE;\n}\n\n\/\/*****************************************************************************************************************\n\/\/ public method\n\/\/*****************************************************************************************************************\nsal_Int32 SvtCacheOptions_Impl::GetGraphicManagerTotalCacheSize() const\n{\n return mnGrfMgrTotalSize;\n}\n\n\/\/*****************************************************************************************************************\n\/\/ public method\n\/\/*****************************************************************************************************************\nsal_Int32 SvtCacheOptions_Impl::GetGraphicManagerObjectCacheSize() const\n{\n return mnGrfMgrObjectSize;\n}\n\n\/\/*****************************************************************************************************************\n\/\/ public method\n\/\/*****************************************************************************************************************\nvoid SvtCacheOptions_Impl::SetWriterOLE_Objects( sal_Int32 nWriterOLE )\n{\n mnWriterOLE = nWriterOLE;\n SetModified();\n}\n\n\/\/*****************************************************************************************************************\n\/\/ public method\n\/\/*****************************************************************************************************************\nvoid SvtCacheOptions_Impl::SetDrawingEngineOLE_Objects( sal_Int32 nDrawingOLE )\n{\n mnDrawingOLE = nDrawingOLE;\n SetModified();\n}\n\n\/\/*****************************************************************************************************************\n\/\/ public method\n\/\/*****************************************************************************************************************\nvoid SvtCacheOptions_Impl::SetGraphicManagerTotalCacheSize( sal_Int32 nGrfMgrTotalSize )\n{\n mnGrfMgrTotalSize = nGrfMgrTotalSize;\n SetModified();\n}\n\n\/\/*****************************************************************************************************************\n\/\/ public method\n\/\/*****************************************************************************************************************\nvoid SvtCacheOptions_Impl::SetGraphicManagerObjectCacheSize( sal_Int32 nGrfMgrObjectSize )\n{\n mnGrfMgrObjectSize = nGrfMgrObjectSize;\n SetModified();\n}\n\n\/\/*****************************************************************************************************************\n\/\/ private method\n\/\/*****************************************************************************************************************\nSequence< OUString > SvtCacheOptions_Impl::impl_GetPropertyNames()\n{\n \/\/ Build static list of configuration key names.\n static const OUString pProperties[] =\n {\n PROPERTYNAME_WRITEROLE,\n PROPERTYNAME_DRAWINGOLE,\n PROPERTYNAME_GRFMGR_TOTALSIZE,\n PROPERTYNAME_GRFMGR_OBJECTSIZE\n };\n \/\/ Initialize return sequence with these list ...\n static const Sequence< OUString > seqPropertyNames( pProperties, PROPERTYCOUNT );\n \/\/ ... and return it.\n return seqPropertyNames;\n}\n\n\/\/*****************************************************************************************************************\n\/\/ initialize static member\n\/\/ DON'T DO IT IN YOUR HEADER!\n\/\/ see definition for further informations\n\/\/*****************************************************************************************************************\nSvtCacheOptions_Impl* SvtCacheOptions::m_pDataContainer = NULL;\nsal_Int32 SvtCacheOptions::m_nRefCount = 0;\n\n\/\/*****************************************************************************************************************\n\/\/ constructor\n\/\/*****************************************************************************************************************\nSvtCacheOptions::SvtCacheOptions()\n{\n \/\/ Global access, must be guarded (multithreading!).\n MutexGuard aGuard( GetOwnStaticMutex() );\n \/\/ Increase ouer refcount ...\n ++m_nRefCount;\n \/\/ ... and initialize ouer data container only if it not already!\n if( m_pDataContainer == NULL )\n {\n m_pDataContainer = new SvtCacheOptions_Impl();\n }\n}\n\n\/\/*****************************************************************************************************************\n\/\/ destructor\n\/\/*****************************************************************************************************************\nSvtCacheOptions::~SvtCacheOptions()\n{\n \/\/ Global access, must be guarded (multithreading!)\n MutexGuard aGuard( GetOwnStaticMutex() );\n \/\/ Decrease ouer refcount.\n --m_nRefCount;\n \/\/ If last instance was deleted ...\n \/\/ we must destroy ouer static data container!\n if( m_nRefCount <= 0 )\n {\n delete m_pDataContainer;\n m_pDataContainer = NULL;\n }\n}\n\n\/\/*****************************************************************************************************************\n\/\/ public method\n\/\/*****************************************************************************************************************\nsal_Int32 SvtCacheOptions::GetWriterOLE_Objects() const\n{\n MutexGuard aGuard( GetOwnStaticMutex() );\n return m_pDataContainer->GetWriterOLE_Objects();\n}\n\n\/\/*****************************************************************************************************************\n\/\/ public method\n\/\/*****************************************************************************************************************\nsal_Int32 SvtCacheOptions::GetDrawingEngineOLE_Objects() const\n{\n MutexGuard aGuard( GetOwnStaticMutex() );\n return m_pDataContainer->GetDrawingEngineOLE_Objects();\n}\n\n\/\/*****************************************************************************************************************\n\/\/ public method\n\/\/*****************************************************************************************************************\nsal_Int32 SvtCacheOptions::GetGraphicManagerTotalCacheSize() const\n{\n MutexGuard aGuard( GetOwnStaticMutex() );\n return m_pDataContainer->GetGraphicManagerTotalCacheSize();\n}\n\n\/\/*****************************************************************************************************************\n\/\/ public method\n\/\/*****************************************************************************************************************\nsal_Int32 SvtCacheOptions::GetGraphicManagerObjectCacheSize() const\n{\n MutexGuard aGuard( GetOwnStaticMutex() );\n return m_pDataContainer->GetGraphicManagerObjectCacheSize();\n}\n\n\/\/*****************************************************************************************************************\n\/\/ public method\n\/\/*****************************************************************************************************************\nvoid SvtCacheOptions::SetWriterOLE_Objects( sal_Int32 nWriterOLE )\n{\n MutexGuard aGuard( GetOwnStaticMutex() );\n m_pDataContainer->SetWriterOLE_Objects( nWriterOLE );\n}\n\n\/\/*****************************************************************************************************************\n\/\/ public method\n\/\/*****************************************************************************************************************\nvoid SvtCacheOptions::SetDrawingEngineOLE_Objects( sal_Int32 nDrawingOLE )\n{\n MutexGuard aGuard( GetOwnStaticMutex() );\n m_pDataContainer->SetDrawingEngineOLE_Objects( nDrawingOLE );\n}\n\n\/\/*****************************************************************************************************************\n\/\/ public method\n\/\/*****************************************************************************************************************\nvoid SvtCacheOptions::SetGraphicManagerTotalCacheSize( sal_Int32 nGrfMgrTotalSize )\n{\n MutexGuard aGuard( GetOwnStaticMutex() );\n m_pDataContainer->SetGraphicManagerTotalCacheSize( nGrfMgrTotalSize );\n}\n\n\/\/*****************************************************************************************************************\n\/\/ public method\n\/\/*****************************************************************************************************************\nvoid SvtCacheOptions::SetGraphicManagerObjectCacheSize( sal_Int32 nGrfMgrObjectSize )\n{\n MutexGuard aGuard( GetOwnStaticMutex() );\n m_pDataContainer->SetGraphicManagerObjectCacheSize( nGrfMgrObjectSize );\n}\n\n\/\/*****************************************************************************************************************\n\/\/ private method\n\/\/*****************************************************************************************************************\nMutex& SvtCacheOptions::GetOwnStaticMutex()\n{\n \/\/ Initialize static mutex only for one time!\n static Mutex* pMutex = NULL;\n \/\/ If these method first called (Mutex not already exist!) ...\n if( pMutex == NULL )\n {\n \/\/ ... we must create a new one. Protect follow code with the global mutex -\n \/\/ It must be - we create a static variable!\n MutexGuard aGuard( Mutex::getGlobalMutex() );\n \/\/ We must check our pointer again - because it can be that another instance of ouer class will be fastr then these!\n if( pMutex == NULL )\n {\n \/\/ Create the new mutex and set it for return on static variable.\n static Mutex aMutex;\n pMutex = &aMutex;\n }\n }\n \/\/ Return new created or already existing mutex object.\n return *pMutex;\n}\n#86165#: assertions removed\/*************************************************************************\n *\n * $RCSfile: cacheoptions.cxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: ka $ $Date: 2001-04-19 12:24:50 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#pragma hdrstop\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ includes\n\/\/_________________________________________________________________________________________________________________\n\n#include \"cacheoptions.hxx\"\n\n#ifndef _UTL_CONFIGMGR_HXX_\n#include \n#endif\n#ifndef _UTL_CONFIGITEM_HXX_\n#include \n#endif\n#ifndef _TOOLS_DEBUG_HXX\n#include \n#endif\n#ifndef _COM_SUN_STAR_UNO_ANY_HXX_\n#include \n#endif\n#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_\n#include \n#endif\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ namespaces\n\/\/_________________________________________________________________________________________________________________\n\nusing namespace ::utl;\nusing namespace ::rtl;\nusing namespace ::osl;\nusing namespace ::com::sun::star::uno;\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ const\n\/\/_________________________________________________________________________________________________________________\n\n#define ROOTNODE_START OUString(RTL_CONSTASCII_USTRINGPARAM(\"Office.Common\/Cache\" ))\n#define DEFAULT_WRITEROLE 20\n#define DEFAULT_DRAWINGOLE 20\n#define DEFAULT_GRFMGR_TOTALSIZE 10000000\n#define DEFAULT_GRFMGR_OBJECTSIZE 2400000\n\n#define PROPERTYNAME_WRITEROLE OUString(RTL_CONSTASCII_USTRINGPARAM(\"Writer\/OLE_Objects\"))\n#define PROPERTYNAME_DRAWINGOLE OUString(RTL_CONSTASCII_USTRINGPARAM(\"DrawingEngine\/OLE_Objects\"))\n#define PROPERTYNAME_GRFMGR_TOTALSIZE OUString(RTL_CONSTASCII_USTRINGPARAM(\"GraphicManager\/TotalCacheSize\"))\n#define PROPERTYNAME_GRFMGR_OBJECTSIZE OUString(RTL_CONSTASCII_USTRINGPARAM(\"GraphicManager\/ObjectCacheSize\"))\n\n#define PROPERTYHANDLE_WRITEROLE 0\n#define PROPERTYHANDLE_DRAWINGOLE 1\n#define PROPERTYHANDLE_GRFMGR_TOTALSIZE 2\n#define PROPERTYHANDLE_GRFMGR_OBJECTSIZE 3\n\n#define PROPERTYCOUNT 4\n\nclass SvtCacheOptions_Impl : public ConfigItem\n{\npublic:\n\n\/\/---------------------------------------------------------------------------------------------------------\n\/\/ constructor \/ destructor\n\/\/---------------------------------------------------------------------------------------------------------\n\n SvtCacheOptions_Impl();\n ~SvtCacheOptions_Impl();\n\n\/\/---------------------------------------------------------------------------------------------------------\n\/\/ overloaded methods of baseclass\n\/\/---------------------------------------------------------------------------------------------------------\n\n virtual void Commit();\n\n\/\/---------------------------------------------------------------------------------------------------------\n\/\/ public interface\n\/\/---------------------------------------------------------------------------------------------------------\n\n sal_Int32 GetWriterOLE_Objects() const;\n sal_Int32 GetDrawingEngineOLE_Objects() const;\n sal_Int32 GetGraphicManagerTotalCacheSize() const;\n sal_Int32 GetGraphicManagerObjectCacheSize() const;\n\n void SetWriterOLE_Objects( sal_Int32 nObjects );\n void SetDrawingEngineOLE_Objects( sal_Int32 nObjects );\n void SetGraphicManagerTotalCacheSize( sal_Int32 nTotalCacheSize );\n void SetGraphicManagerObjectCacheSize( sal_Int32 nObjectCacheSize );\n\n\/\/-------------------------------------------------------------------------------------------------------------\n\/\/ private methods\n\/\/-------------------------------------------------------------------------------------------------------------\n\nprivate:\n\n static Sequence< OUString > impl_GetPropertyNames();\n\n\/\/-------------------------------------------------------------------------------------------------------------\n\/\/ private member\n\/\/-------------------------------------------------------------------------------------------------------------\n\nprivate:\n\n sal_Int32 mnWriterOLE;\n sal_Int32 mnDrawingOLE;\n sal_Int32 mnGrfMgrTotalSize;\n sal_Int32 mnGrfMgrObjectSize;\n};\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ definitions\n\/\/_________________________________________________________________________________________________________________\n\n\/\/*****************************************************************************************************************\n\/\/ constructor\n\/\/*****************************************************************************************************************\nSvtCacheOptions_Impl::SvtCacheOptions_Impl() :\n ConfigItem( ROOTNODE_START ),\n mnWriterOLE( DEFAULT_WRITEROLE ),\n mnDrawingOLE( DEFAULT_DRAWINGOLE ),\n mnGrfMgrTotalSize( DEFAULT_GRFMGR_TOTALSIZE ),\n mnGrfMgrObjectSize( DEFAULT_GRFMGR_OBJECTSIZE )\n{\n Sequence< OUString > seqNames( impl_GetPropertyNames() );\n Sequence< Any > seqValues = GetProperties( seqNames ) ;\n\n DBG_ASSERT( !(seqNames.getLength()!=seqValues.getLength()), \"SvtCacheOptions_Impl::SvtCacheOptions_Impl()\\nI miss some values of configuration keys!\\n\" );\n\n \/\/ Copy values from list in right order to ouer internal member.\n sal_Int32 nPropertyCount = seqValues.getLength();\n sal_Int32 nProperty = 0;\n\n for( nProperty=0; nProperty>= mnWriterOLE;\n }\n break;\n\n case PROPERTYHANDLE_DRAWINGOLE:\n {\n if( seqValues[ nProperty ].getValueTypeClass() == TypeClass_LONG )\n seqValues[nProperty] >>= mnDrawingOLE;\n }\n break;\n\n case PROPERTYHANDLE_GRFMGR_TOTALSIZE:\n {\n if( seqValues[ nProperty ].getValueTypeClass() == TypeClass_LONG )\n seqValues[nProperty] >>= mnGrfMgrTotalSize;\n }\n break;\n\n case PROPERTYHANDLE_GRFMGR_OBJECTSIZE:\n {\n if( seqValues[ nProperty ].getValueTypeClass() == TypeClass_LONG )\n seqValues[nProperty] >>= mnGrfMgrObjectSize;\n }\n break;\n }\n }\n }\n}\n\n\/\/*****************************************************************************************************************\n\/\/ destructor\n\/\/*****************************************************************************************************************\nSvtCacheOptions_Impl::~SvtCacheOptions_Impl()\n{\n if( IsModified() )\n Commit();\n}\n\n\/\/*****************************************************************************************************************\n\/\/ Commit\n\/\/*****************************************************************************************************************\nvoid SvtCacheOptions_Impl::Commit()\n{\n Sequence< OUString > aSeqNames( impl_GetPropertyNames() );\n Sequence< Any > aSeqValues( aSeqNames.getLength() );\n\n for( sal_Int32 nProperty = 0, nCount = aSeqNames.getLength(); nProperty < nCount; ++nProperty )\n {\n switch( nProperty )\n {\n case PROPERTYHANDLE_WRITEROLE:\n aSeqValues[nProperty] <<= mnWriterOLE;\n break;\n\n case PROPERTYHANDLE_DRAWINGOLE:\n aSeqValues[nProperty] <<= mnDrawingOLE;\n break;\n\n case PROPERTYHANDLE_GRFMGR_TOTALSIZE:\n aSeqValues[nProperty] <<= mnGrfMgrTotalSize;\n break;\n\n case PROPERTYHANDLE_GRFMGR_OBJECTSIZE:\n aSeqValues[nProperty] <<= mnGrfMgrObjectSize;\n break;\n }\n }\n\n PutProperties( aSeqNames, aSeqValues );\n}\n\n\/\/*****************************************************************************************************************\n\/\/ public method\n\/\/*****************************************************************************************************************\nsal_Int32 SvtCacheOptions_Impl::GetWriterOLE_Objects() const\n{\n return mnWriterOLE;\n}\n\n\/\/*****************************************************************************************************************\n\/\/ public method\n\/\/*****************************************************************************************************************\nsal_Int32 SvtCacheOptions_Impl::GetDrawingEngineOLE_Objects() const\n{\n return mnDrawingOLE;\n}\n\n\/\/*****************************************************************************************************************\n\/\/ public method\n\/\/*****************************************************************************************************************\nsal_Int32 SvtCacheOptions_Impl::GetGraphicManagerTotalCacheSize() const\n{\n return mnGrfMgrTotalSize;\n}\n\n\/\/*****************************************************************************************************************\n\/\/ public method\n\/\/*****************************************************************************************************************\nsal_Int32 SvtCacheOptions_Impl::GetGraphicManagerObjectCacheSize() const\n{\n return mnGrfMgrObjectSize;\n}\n\n\/\/*****************************************************************************************************************\n\/\/ public method\n\/\/*****************************************************************************************************************\nvoid SvtCacheOptions_Impl::SetWriterOLE_Objects( sal_Int32 nWriterOLE )\n{\n mnWriterOLE = nWriterOLE;\n SetModified();\n}\n\n\/\/*****************************************************************************************************************\n\/\/ public method\n\/\/*****************************************************************************************************************\nvoid SvtCacheOptions_Impl::SetDrawingEngineOLE_Objects( sal_Int32 nDrawingOLE )\n{\n mnDrawingOLE = nDrawingOLE;\n SetModified();\n}\n\n\/\/*****************************************************************************************************************\n\/\/ public method\n\/\/*****************************************************************************************************************\nvoid SvtCacheOptions_Impl::SetGraphicManagerTotalCacheSize( sal_Int32 nGrfMgrTotalSize )\n{\n mnGrfMgrTotalSize = nGrfMgrTotalSize;\n SetModified();\n}\n\n\/\/*****************************************************************************************************************\n\/\/ public method\n\/\/*****************************************************************************************************************\nvoid SvtCacheOptions_Impl::SetGraphicManagerObjectCacheSize( sal_Int32 nGrfMgrObjectSize )\n{\n mnGrfMgrObjectSize = nGrfMgrObjectSize;\n SetModified();\n}\n\n\/\/*****************************************************************************************************************\n\/\/ private method\n\/\/*****************************************************************************************************************\nSequence< OUString > SvtCacheOptions_Impl::impl_GetPropertyNames()\n{\n \/\/ Build static list of configuration key names.\n static const OUString pProperties[] =\n {\n PROPERTYNAME_WRITEROLE,\n PROPERTYNAME_DRAWINGOLE,\n PROPERTYNAME_GRFMGR_TOTALSIZE,\n PROPERTYNAME_GRFMGR_OBJECTSIZE\n };\n \/\/ Initialize return sequence with these list ...\n static const Sequence< OUString > seqPropertyNames( pProperties, PROPERTYCOUNT );\n \/\/ ... and return it.\n return seqPropertyNames;\n}\n\n\/\/*****************************************************************************************************************\n\/\/ initialize static member\n\/\/ DON'T DO IT IN YOUR HEADER!\n\/\/ see definition for further informations\n\/\/*****************************************************************************************************************\nSvtCacheOptions_Impl* SvtCacheOptions::m_pDataContainer = NULL;\nsal_Int32 SvtCacheOptions::m_nRefCount = 0;\n\n\/\/*****************************************************************************************************************\n\/\/ constructor\n\/\/*****************************************************************************************************************\nSvtCacheOptions::SvtCacheOptions()\n{\n \/\/ Global access, must be guarded (multithreading!).\n MutexGuard aGuard( GetOwnStaticMutex() );\n \/\/ Increase ouer refcount ...\n ++m_nRefCount;\n \/\/ ... and initialize ouer data container only if it not already!\n if( m_pDataContainer == NULL )\n {\n m_pDataContainer = new SvtCacheOptions_Impl();\n }\n}\n\n\/\/*****************************************************************************************************************\n\/\/ destructor\n\/\/*****************************************************************************************************************\nSvtCacheOptions::~SvtCacheOptions()\n{\n \/\/ Global access, must be guarded (multithreading!)\n MutexGuard aGuard( GetOwnStaticMutex() );\n \/\/ Decrease ouer refcount.\n --m_nRefCount;\n \/\/ If last instance was deleted ...\n \/\/ we must destroy ouer static data container!\n if( m_nRefCount <= 0 )\n {\n delete m_pDataContainer;\n m_pDataContainer = NULL;\n }\n}\n\n\/\/*****************************************************************************************************************\n\/\/ public method\n\/\/*****************************************************************************************************************\nsal_Int32 SvtCacheOptions::GetWriterOLE_Objects() const\n{\n MutexGuard aGuard( GetOwnStaticMutex() );\n return m_pDataContainer->GetWriterOLE_Objects();\n}\n\n\/\/*****************************************************************************************************************\n\/\/ public method\n\/\/*****************************************************************************************************************\nsal_Int32 SvtCacheOptions::GetDrawingEngineOLE_Objects() const\n{\n MutexGuard aGuard( GetOwnStaticMutex() );\n return m_pDataContainer->GetDrawingEngineOLE_Objects();\n}\n\n\/\/*****************************************************************************************************************\n\/\/ public method\n\/\/*****************************************************************************************************************\nsal_Int32 SvtCacheOptions::GetGraphicManagerTotalCacheSize() const\n{\n MutexGuard aGuard( GetOwnStaticMutex() );\n return m_pDataContainer->GetGraphicManagerTotalCacheSize();\n}\n\n\/\/*****************************************************************************************************************\n\/\/ public method\n\/\/*****************************************************************************************************************\nsal_Int32 SvtCacheOptions::GetGraphicManagerObjectCacheSize() const\n{\n MutexGuard aGuard( GetOwnStaticMutex() );\n return m_pDataContainer->GetGraphicManagerObjectCacheSize();\n}\n\n\/\/*****************************************************************************************************************\n\/\/ public method\n\/\/*****************************************************************************************************************\nvoid SvtCacheOptions::SetWriterOLE_Objects( sal_Int32 nWriterOLE )\n{\n MutexGuard aGuard( GetOwnStaticMutex() );\n m_pDataContainer->SetWriterOLE_Objects( nWriterOLE );\n}\n\n\/\/*****************************************************************************************************************\n\/\/ public method\n\/\/*****************************************************************************************************************\nvoid SvtCacheOptions::SetDrawingEngineOLE_Objects( sal_Int32 nDrawingOLE )\n{\n MutexGuard aGuard( GetOwnStaticMutex() );\n m_pDataContainer->SetDrawingEngineOLE_Objects( nDrawingOLE );\n}\n\n\/\/*****************************************************************************************************************\n\/\/ public method\n\/\/*****************************************************************************************************************\nvoid SvtCacheOptions::SetGraphicManagerTotalCacheSize( sal_Int32 nGrfMgrTotalSize )\n{\n MutexGuard aGuard( GetOwnStaticMutex() );\n m_pDataContainer->SetGraphicManagerTotalCacheSize( nGrfMgrTotalSize );\n}\n\n\/\/*****************************************************************************************************************\n\/\/ public method\n\/\/*****************************************************************************************************************\nvoid SvtCacheOptions::SetGraphicManagerObjectCacheSize( sal_Int32 nGrfMgrObjectSize )\n{\n MutexGuard aGuard( GetOwnStaticMutex() );\n m_pDataContainer->SetGraphicManagerObjectCacheSize( nGrfMgrObjectSize );\n}\n\n\/\/*****************************************************************************************************************\n\/\/ private method\n\/\/*****************************************************************************************************************\nMutex& SvtCacheOptions::GetOwnStaticMutex()\n{\n \/\/ Initialize static mutex only for one time!\n static Mutex* pMutex = NULL;\n \/\/ If these method first called (Mutex not already exist!) ...\n if( pMutex == NULL )\n {\n \/\/ ... we must create a new one. Protect follow code with the global mutex -\n \/\/ It must be - we create a static variable!\n MutexGuard aGuard( Mutex::getGlobalMutex() );\n \/\/ We must check our pointer again - because it can be that another instance of ouer class will be fastr then these!\n if( pMutex == NULL )\n {\n \/\/ Create the new mutex and set it for return on static variable.\n static Mutex aMutex;\n pMutex = &aMutex;\n }\n }\n \/\/ Return new created or already existing mutex object.\n return *pMutex;\n}\n<|endoftext|>"} {"text":"\/*\n * yosys -- Yosys Open SYnthesis Suite\n *\n * Copyright (C) 2012 Clifford Wolf \n *\n * Permission to use, copy, modify, and\/or distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\n *\/\n\n#include \"kernel\/yosys.h\"\n#include \"kernel\/sigtools.h\"\n\nUSING_YOSYS_NAMESPACE\nPRIVATE_NAMESPACE_BEGIN\n\nstruct MemoryDffWorker\n{\n\tModule *module;\n\tSigMap sigmap;\n\n\tvector dff_cells;\n\tdict invbits;\n\tdict sigbit_users_count;\n\tdict mux_cells_a, mux_cells_b;\n\tpool forward_merged_dffs, candidate_dffs;\n\tpool init_bits;\n\n\tMemoryDffWorker(Module *module) : module(module), sigmap(module)\n\t{\n\t\tfor (auto wire : module->wires()) {\n\t\t\tif (wire->attributes.count(\"\\\\init\") == 0)\n\t\t\t\tcontinue;\n\t\t\tSigSpec sig = sigmap(wire);\n\t\t\tConst initval = wire->attributes.count(\"\\\\init\");\n\t\t\tfor (int i = 0; i < GetSize(sig) && i < GetSize(initval); i++)\n\t\t\t\tif (initval[i] == State::S0 || initval[i] == State::S1)\n\t\t\t\t\tinit_bits.insert(sig[i]);\n\t\t}\n\t}\n\n\tbool find_sig_before_dff(RTLIL::SigSpec &sig, RTLIL::SigSpec &clk, bool &clk_polarity, bool after = false)\n\t{\n\t\tsigmap.apply(sig);\n\n\t\tfor (auto &bit : sig)\n\t\t{\n\t\t\tif (bit.wire == NULL)\n\t\t\t\tcontinue;\n\n\t\t\tif (!after && init_bits.count(sigmap(bit)))\n\t\t\t\treturn false;\n\n\t\t\tfor (auto cell : dff_cells)\n\t\t\t{\n\t\t\t\tif (after && forward_merged_dffs.count(cell))\n\t\t\t\t\tcontinue;\n\n\t\t\t\tSigSpec this_clk = cell->getPort(\"\\\\CLK\");\n\t\t\t\tbool this_clk_polarity = cell->parameters[\"\\\\CLK_POLARITY\"].as_bool();\n\n\t\t\t\tif (invbits.count(this_clk)) {\n\t\t\t\t\tthis_clk = invbits.at(this_clk);\n\t\t\t\t\tthis_clk_polarity = !this_clk_polarity;\n\t\t\t\t}\n\n\t\t\t\tif (clk != RTLIL::SigSpec(RTLIL::State::Sx)) {\n\t\t\t\t\tif (this_clk != clk)\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\tif (this_clk_polarity != clk_polarity)\n\t\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tRTLIL::SigSpec q_norm = cell->getPort(after ? \"\\\\D\" : \"\\\\Q\");\n\t\t\t\tsigmap.apply(q_norm);\n\n\t\t\t\tRTLIL::SigSpec d = q_norm.extract(bit, &cell->getPort(after ? \"\\\\Q\" : \"\\\\D\"));\n\t\t\t\tif (d.size() != 1)\n\t\t\t\t\tcontinue;\n\n\t\t\t\tif (after && init_bits.count(d))\n\t\t\t\t\treturn false;\n\n\t\t\t\tbit = d;\n\t\t\t\tclk = this_clk;\n\t\t\t\tclk_polarity = this_clk_polarity;\n\t\t\t\tcandidate_dffs.insert(cell);\n\t\t\t\tgoto replaced_this_bit;\n\t\t\t}\n\n\t\t\treturn false;\n\t\treplaced_this_bit:;\n\t\t}\n\n\t\treturn true;\n\t}\n\n\tvoid handle_wr_cell(RTLIL::Cell *cell)\n\t{\n\t\tlog(\"Checking cell `%s' in module `%s': \", cell->name.c_str(), module->name.c_str());\n\n\t\tRTLIL::SigSpec clk = RTLIL::SigSpec(RTLIL::State::Sx);\n\t\tbool clk_polarity = 0;\n\t\tcandidate_dffs.clear();\n\n\t\tRTLIL::SigSpec sig_addr = cell->getPort(\"\\\\ADDR\");\n\t\tif (!find_sig_before_dff(sig_addr, clk, clk_polarity)) {\n\t\t\tlog(\"no (compatible) $dff for address input found.\\n\");\n\t\t\treturn;\n\t\t}\n\n\t\tRTLIL::SigSpec sig_data = cell->getPort(\"\\\\DATA\");\n\t\tif (!find_sig_before_dff(sig_data, clk, clk_polarity)) {\n\t\t\tlog(\"no (compatible) $dff for data input found.\\n\");\n\t\t\treturn;\n\t\t}\n\n\t\tRTLIL::SigSpec sig_en = cell->getPort(\"\\\\EN\");\n\t\tif (!find_sig_before_dff(sig_en, clk, clk_polarity)) {\n\t\t\tlog(\"no (compatible) $dff for enable input found.\\n\");\n\t\t\treturn;\n\t\t}\n\n\t\tif (clk != RTLIL::SigSpec(RTLIL::State::Sx))\n\t\t{\n\t\t\tfor (auto cell : candidate_dffs)\n\t\t\t\tforward_merged_dffs.insert(cell);\n\n\t\t\tcell->setPort(\"\\\\CLK\", clk);\n\t\t\tcell->setPort(\"\\\\ADDR\", sig_addr);\n\t\t\tcell->setPort(\"\\\\DATA\", sig_data);\n\t\t\tcell->setPort(\"\\\\EN\", sig_en);\n\t\t\tcell->parameters[\"\\\\CLK_ENABLE\"] = RTLIL::Const(1);\n\t\t\tcell->parameters[\"\\\\CLK_POLARITY\"] = RTLIL::Const(clk_polarity);\n\n\t\t\tlog(\"merged $dff to cell.\\n\");\n\t\t\treturn;\n\t\t}\n\n\t\tlog(\"no (compatible) $dff found.\\n\");\n\t}\n\n\tvoid disconnect_dff(RTLIL::SigSpec sig)\n\t{\n\t\tsigmap.apply(sig);\n\t\tsig.sort_and_unify();\n\n\t\tstd::stringstream sstr;\n\t\tsstr << \"$memory_dff_disconnected$\" << (autoidx++);\n\n\t\tRTLIL::SigSpec new_sig = module->addWire(sstr.str(), sig.size());\n\n\t\tfor (auto cell : module->cells())\n\t\t\tif (cell->type == \"$dff\") {\n\t\t\t\tRTLIL::SigSpec new_q = cell->getPort(\"\\\\Q\");\n\t\t\t\tnew_q.replace(sig, new_sig);\n\t\t\t\tcell->setPort(\"\\\\Q\", new_q);\n\t\t\t}\n\t}\n\n\tvoid handle_rd_cell(RTLIL::Cell *cell)\n\t{\n\t\tlog(\"Checking cell `%s' in module `%s': \", cell->name.c_str(), module->name.c_str());\n\n\t\tbool clk_polarity = 0;\n\n\t\tRTLIL::SigSpec clk_data = RTLIL::SigSpec(RTLIL::State::Sx);\n\t\tRTLIL::SigSpec sig_data = cell->getPort(\"\\\\DATA\");\n\n\t\tfor (auto bit : sigmap(sig_data))\n\t\t\tif (sigbit_users_count[bit] > 1)\n\t\t\t\tgoto skip_ff_after_read_merging;\n\n\t\tif (mux_cells_a.count(sig_data) || mux_cells_b.count(sig_data))\n\t\t{\n\t\t\tbool enable_invert = mux_cells_a.count(sig_data) != 0;\n\t\t\tCell *mux = enable_invert ? mux_cells_a.at(sig_data) : mux_cells_b.at(sig_data);\n\t\t\tSigSpec check_q = sigmap(mux->getPort(enable_invert ? \"\\\\B\" : \"\\\\A\"));\n\n\t\t\tsig_data = sigmap(mux->getPort(\"\\\\Y\"));\n\t\t\tfor (auto bit : sig_data)\n\t\t\t\tif (sigbit_users_count[bit] > 1)\n\t\t\t\t\tgoto skip_ff_after_read_merging;\n\n\t\t\tif (find_sig_before_dff(sig_data, clk_data, clk_polarity, true) && clk_data != RTLIL::SigSpec(RTLIL::State::Sx) && sig_data == check_q)\n\t\t\t{\n\t\t\t\tdisconnect_dff(sig_data);\n\t\t\t\tcell->setPort(\"\\\\CLK\", clk_data);\n\t\t\t\tcell->setPort(\"\\\\EN\", enable_invert ? module->LogicNot(NEW_ID, mux->getPort(\"\\\\S\")) : mux->getPort(\"\\\\S\"));\n\t\t\t\tcell->setPort(\"\\\\DATA\", sig_data);\n\t\t\t\tcell->parameters[\"\\\\CLK_ENABLE\"] = RTLIL::Const(1);\n\t\t\t\tcell->parameters[\"\\\\CLK_POLARITY\"] = RTLIL::Const(clk_polarity);\n\t\t\t\tcell->parameters[\"\\\\TRANSPARENT\"] = RTLIL::Const(0);\n\t\t\t\tlog(\"merged data $dff with rd enable to cell.\\n\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif (find_sig_before_dff(sig_data, clk_data, clk_polarity, true) && clk_data != RTLIL::SigSpec(RTLIL::State::Sx))\n\t\t\t{\n\t\t\t\tdisconnect_dff(sig_data);\n\t\t\t\tcell->setPort(\"\\\\CLK\", clk_data);\n\t\t\t\tcell->setPort(\"\\\\EN\", State::S1);\n\t\t\t\tcell->setPort(\"\\\\DATA\", sig_data);\n\t\t\t\tcell->parameters[\"\\\\CLK_ENABLE\"] = RTLIL::Const(1);\n\t\t\t\tcell->parameters[\"\\\\CLK_POLARITY\"] = RTLIL::Const(clk_polarity);\n\t\t\t\tcell->parameters[\"\\\\TRANSPARENT\"] = RTLIL::Const(0);\n\t\t\t\tlog(\"merged data $dff to cell.\\n\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\tskip_ff_after_read_merging:;\n\t\tRTLIL::SigSpec clk_addr = RTLIL::SigSpec(RTLIL::State::Sx);\n\t\tRTLIL::SigSpec sig_addr = cell->getPort(\"\\\\ADDR\");\n\t\tif (find_sig_before_dff(sig_addr, clk_addr, clk_polarity) &&\n\t\t\t\tclk_addr != RTLIL::SigSpec(RTLIL::State::Sx))\n\t\t{\n\t\t\tcell->setPort(\"\\\\CLK\", clk_addr);\n\t\t\tcell->setPort(\"\\\\EN\", State::S1);\n\t\t\tcell->setPort(\"\\\\ADDR\", sig_addr);\n\t\t\tcell->parameters[\"\\\\CLK_ENABLE\"] = RTLIL::Const(1);\n\t\t\tcell->parameters[\"\\\\CLK_POLARITY\"] = RTLIL::Const(clk_polarity);\n\t\t\tcell->parameters[\"\\\\TRANSPARENT\"] = RTLIL::Const(1);\n\t\t\tlog(\"merged address $dff to cell.\\n\");\n\t\t\treturn;\n\t\t}\n\n\t\tlog(\"no (compatible) $dff found.\\n\");\n\t}\n\n\tvoid run(bool flag_wr_only)\n\t{\n\t\tfor (auto wire : module->wires()) {\n\t\t\tif (wire->port_output)\n\t\t\t\tfor (auto bit : sigmap(wire))\n\t\t\t\t\tsigbit_users_count[bit]++;\n\t\t}\n\n\t\tfor (auto cell : module->cells()) {\n\t\t\tif (cell->type == \"$dff\")\n\t\t\t\tdff_cells.push_back(cell);\n\t\t\tif (cell->type == \"$mux\") {\n\t\t\t\tmux_cells_a[sigmap(cell->getPort(\"\\\\A\"))] = cell;\n\t\t\t\tmux_cells_b[sigmap(cell->getPort(\"\\\\B\"))] = cell;\n\t\t\t}\n\t\t\tif (cell->type == \"$not\" || cell->type == \"$_NOT_\" || (cell->type == \"$logic_not\" && GetSize(cell->getPort(\"\\\\A\")) == 1)) {\n\t\t\t\tSigSpec sig_a = cell->getPort(\"\\\\A\");\n\t\t\t\tSigSpec sig_y = cell->getPort(\"\\\\Y\");\n\t\t\t\tif (cell->type == \"$not\")\n\t\t\t\t\tsig_a.extend_u0(GetSize(sig_y), cell->getParam(\"\\\\A_SIGNED\").as_bool());\n\t\t\t\tif (cell->type == \"$logic_not\")\n\t\t\t\t\tsig_y.extend_u0(1);\n\t\t\t\tfor (int i = 0; i < GetSize(sig_y); i++)\n\t\t\t\t\tinvbits[sig_y[i]] = sig_a[i];\n\t\t\t}\n\t\t\tfor (auto &conn : cell->connections())\n\t\t\t\tif (!cell->known() || cell->input(conn.first))\n\t\t\t\t\tfor (auto bit : sigmap(conn.second))\n\t\t\t\t\t\tsigbit_users_count[bit]++;\n\t\t}\n\n\t\tfor (auto cell : module->selected_cells())\n\t\t\tif (cell->type == \"$memwr\" && !cell->parameters[\"\\\\CLK_ENABLE\"].as_bool())\n\t\t\t\thandle_wr_cell(cell);\n\n\t\tif (!flag_wr_only)\n\t\t\tfor (auto cell : module->selected_cells())\n\t\t\t\tif (cell->type == \"$memrd\" && !cell->parameters[\"\\\\CLK_ENABLE\"].as_bool())\n\t\t\t\t\thandle_rd_cell(cell);\n\t}\n};\n\nstruct MemoryDffPass : public Pass {\n\tMemoryDffPass() : Pass(\"memory_dff\", \"merge input\/output DFFs into memories\") { }\n\tvoid help() YS_OVERRIDE\n\t{\n\t\t\/\/ |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|\n\t\tlog(\"\\n\");\n\t\tlog(\" memory_dff [options] [selection]\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\"This pass detects DFFs at memory ports and merges them into the memory port.\\n\");\n\t\tlog(\"I.e. it consumes an asynchronous memory port and the flip-flops at its\\n\");\n\t\tlog(\"interface and yields a synchronous memory port.\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\" -nordfff\\n\");\n\t\tlog(\" do not merge registers on read ports\\n\");\n\t\tlog(\"\\n\");\n\t}\n\tvoid execute(std::vector args, RTLIL::Design *design) YS_OVERRIDE\n\t{\n\t\tbool flag_wr_only = false;\n\n\t\tlog_header(design, \"Executing MEMORY_DFF pass (merging $dff cells to $memrd and $memwr).\\n\");\n\n\t\tsize_t argidx;\n\t\tfor (argidx = 1; argidx < args.size(); argidx++) {\n\t\t\tif (args[argidx] == \"-nordff\" || args[argidx] == \"-wr_only\") {\n\t\t\t\tflag_wr_only = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\textra_args(args, argidx, design);\n\n\t\tfor (auto mod : design->selected_modules()) {\n\t\t\tMemoryDffWorker worker(mod);\n\t\t\tworker.run(flag_wr_only);\n\t\t}\n\t}\n} MemoryDffPass;\n\nPRIVATE_NAMESPACE_END\nmemory_dff: Fix typo when checking init value\/*\n * yosys -- Yosys Open SYnthesis Suite\n *\n * Copyright (C) 2012 Clifford Wolf \n *\n * Permission to use, copy, modify, and\/or distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\n *\/\n\n#include \"kernel\/yosys.h\"\n#include \"kernel\/sigtools.h\"\n\nUSING_YOSYS_NAMESPACE\nPRIVATE_NAMESPACE_BEGIN\n\nstruct MemoryDffWorker\n{\n\tModule *module;\n\tSigMap sigmap;\n\n\tvector dff_cells;\n\tdict invbits;\n\tdict sigbit_users_count;\n\tdict mux_cells_a, mux_cells_b;\n\tpool forward_merged_dffs, candidate_dffs;\n\tpool init_bits;\n\n\tMemoryDffWorker(Module *module) : module(module), sigmap(module)\n\t{\n\t\tfor (auto wire : module->wires()) {\n\t\t\tif (wire->attributes.count(\"\\\\init\") == 0)\n\t\t\t\tcontinue;\n\t\t\tSigSpec sig = sigmap(wire);\n\t\t\tConst initval = wire->attributes.at(\"\\\\init\");\n\t\t\tfor (int i = 0; i < GetSize(sig) && i < GetSize(initval); i++)\n\t\t\t\tif (initval[i] == State::S0 || initval[i] == State::S1)\n\t\t\t\t\tinit_bits.insert(sig[i]);\n\t\t}\n\t}\n\n\tbool find_sig_before_dff(RTLIL::SigSpec &sig, RTLIL::SigSpec &clk, bool &clk_polarity, bool after = false)\n\t{\n\t\tsigmap.apply(sig);\n\n\t\tfor (auto &bit : sig)\n\t\t{\n\t\t\tif (bit.wire == NULL)\n\t\t\t\tcontinue;\n\n\t\t\tif (!after && init_bits.count(sigmap(bit)))\n\t\t\t\treturn false;\n\n\t\t\tfor (auto cell : dff_cells)\n\t\t\t{\n\t\t\t\tif (after && forward_merged_dffs.count(cell))\n\t\t\t\t\tcontinue;\n\n\t\t\t\tSigSpec this_clk = cell->getPort(\"\\\\CLK\");\n\t\t\t\tbool this_clk_polarity = cell->parameters[\"\\\\CLK_POLARITY\"].as_bool();\n\n\t\t\t\tif (invbits.count(this_clk)) {\n\t\t\t\t\tthis_clk = invbits.at(this_clk);\n\t\t\t\t\tthis_clk_polarity = !this_clk_polarity;\n\t\t\t\t}\n\n\t\t\t\tif (clk != RTLIL::SigSpec(RTLIL::State::Sx)) {\n\t\t\t\t\tif (this_clk != clk)\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\tif (this_clk_polarity != clk_polarity)\n\t\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tRTLIL::SigSpec q_norm = cell->getPort(after ? \"\\\\D\" : \"\\\\Q\");\n\t\t\t\tsigmap.apply(q_norm);\n\n\t\t\t\tRTLIL::SigSpec d = q_norm.extract(bit, &cell->getPort(after ? \"\\\\Q\" : \"\\\\D\"));\n\t\t\t\tif (d.size() != 1)\n\t\t\t\t\tcontinue;\n\n\t\t\t\tif (after && init_bits.count(d))\n\t\t\t\t\treturn false;\n\n\t\t\t\tbit = d;\n\t\t\t\tclk = this_clk;\n\t\t\t\tclk_polarity = this_clk_polarity;\n\t\t\t\tcandidate_dffs.insert(cell);\n\t\t\t\tgoto replaced_this_bit;\n\t\t\t}\n\n\t\t\treturn false;\n\t\treplaced_this_bit:;\n\t\t}\n\n\t\treturn true;\n\t}\n\n\tvoid handle_wr_cell(RTLIL::Cell *cell)\n\t{\n\t\tlog(\"Checking cell `%s' in module `%s': \", cell->name.c_str(), module->name.c_str());\n\n\t\tRTLIL::SigSpec clk = RTLIL::SigSpec(RTLIL::State::Sx);\n\t\tbool clk_polarity = 0;\n\t\tcandidate_dffs.clear();\n\n\t\tRTLIL::SigSpec sig_addr = cell->getPort(\"\\\\ADDR\");\n\t\tif (!find_sig_before_dff(sig_addr, clk, clk_polarity)) {\n\t\t\tlog(\"no (compatible) $dff for address input found.\\n\");\n\t\t\treturn;\n\t\t}\n\n\t\tRTLIL::SigSpec sig_data = cell->getPort(\"\\\\DATA\");\n\t\tif (!find_sig_before_dff(sig_data, clk, clk_polarity)) {\n\t\t\tlog(\"no (compatible) $dff for data input found.\\n\");\n\t\t\treturn;\n\t\t}\n\n\t\tRTLIL::SigSpec sig_en = cell->getPort(\"\\\\EN\");\n\t\tif (!find_sig_before_dff(sig_en, clk, clk_polarity)) {\n\t\t\tlog(\"no (compatible) $dff for enable input found.\\n\");\n\t\t\treturn;\n\t\t}\n\n\t\tif (clk != RTLIL::SigSpec(RTLIL::State::Sx))\n\t\t{\n\t\t\tfor (auto cell : candidate_dffs)\n\t\t\t\tforward_merged_dffs.insert(cell);\n\n\t\t\tcell->setPort(\"\\\\CLK\", clk);\n\t\t\tcell->setPort(\"\\\\ADDR\", sig_addr);\n\t\t\tcell->setPort(\"\\\\DATA\", sig_data);\n\t\t\tcell->setPort(\"\\\\EN\", sig_en);\n\t\t\tcell->parameters[\"\\\\CLK_ENABLE\"] = RTLIL::Const(1);\n\t\t\tcell->parameters[\"\\\\CLK_POLARITY\"] = RTLIL::Const(clk_polarity);\n\n\t\t\tlog(\"merged $dff to cell.\\n\");\n\t\t\treturn;\n\t\t}\n\n\t\tlog(\"no (compatible) $dff found.\\n\");\n\t}\n\n\tvoid disconnect_dff(RTLIL::SigSpec sig)\n\t{\n\t\tsigmap.apply(sig);\n\t\tsig.sort_and_unify();\n\n\t\tstd::stringstream sstr;\n\t\tsstr << \"$memory_dff_disconnected$\" << (autoidx++);\n\n\t\tRTLIL::SigSpec new_sig = module->addWire(sstr.str(), sig.size());\n\n\t\tfor (auto cell : module->cells())\n\t\t\tif (cell->type == \"$dff\") {\n\t\t\t\tRTLIL::SigSpec new_q = cell->getPort(\"\\\\Q\");\n\t\t\t\tnew_q.replace(sig, new_sig);\n\t\t\t\tcell->setPort(\"\\\\Q\", new_q);\n\t\t\t}\n\t}\n\n\tvoid handle_rd_cell(RTLIL::Cell *cell)\n\t{\n\t\tlog(\"Checking cell `%s' in module `%s': \", cell->name.c_str(), module->name.c_str());\n\n\t\tbool clk_polarity = 0;\n\n\t\tRTLIL::SigSpec clk_data = RTLIL::SigSpec(RTLIL::State::Sx);\n\t\tRTLIL::SigSpec sig_data = cell->getPort(\"\\\\DATA\");\n\n\t\tfor (auto bit : sigmap(sig_data))\n\t\t\tif (sigbit_users_count[bit] > 1)\n\t\t\t\tgoto skip_ff_after_read_merging;\n\n\t\tif (mux_cells_a.count(sig_data) || mux_cells_b.count(sig_data))\n\t\t{\n\t\t\tbool enable_invert = mux_cells_a.count(sig_data) != 0;\n\t\t\tCell *mux = enable_invert ? mux_cells_a.at(sig_data) : mux_cells_b.at(sig_data);\n\t\t\tSigSpec check_q = sigmap(mux->getPort(enable_invert ? \"\\\\B\" : \"\\\\A\"));\n\n\t\t\tsig_data = sigmap(mux->getPort(\"\\\\Y\"));\n\t\t\tfor (auto bit : sig_data)\n\t\t\t\tif (sigbit_users_count[bit] > 1)\n\t\t\t\t\tgoto skip_ff_after_read_merging;\n\n\t\t\tif (find_sig_before_dff(sig_data, clk_data, clk_polarity, true) && clk_data != RTLIL::SigSpec(RTLIL::State::Sx) && sig_data == check_q)\n\t\t\t{\n\t\t\t\tdisconnect_dff(sig_data);\n\t\t\t\tcell->setPort(\"\\\\CLK\", clk_data);\n\t\t\t\tcell->setPort(\"\\\\EN\", enable_invert ? module->LogicNot(NEW_ID, mux->getPort(\"\\\\S\")) : mux->getPort(\"\\\\S\"));\n\t\t\t\tcell->setPort(\"\\\\DATA\", sig_data);\n\t\t\t\tcell->parameters[\"\\\\CLK_ENABLE\"] = RTLIL::Const(1);\n\t\t\t\tcell->parameters[\"\\\\CLK_POLARITY\"] = RTLIL::Const(clk_polarity);\n\t\t\t\tcell->parameters[\"\\\\TRANSPARENT\"] = RTLIL::Const(0);\n\t\t\t\tlog(\"merged data $dff with rd enable to cell.\\n\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif (find_sig_before_dff(sig_data, clk_data, clk_polarity, true) && clk_data != RTLIL::SigSpec(RTLIL::State::Sx))\n\t\t\t{\n\t\t\t\tdisconnect_dff(sig_data);\n\t\t\t\tcell->setPort(\"\\\\CLK\", clk_data);\n\t\t\t\tcell->setPort(\"\\\\EN\", State::S1);\n\t\t\t\tcell->setPort(\"\\\\DATA\", sig_data);\n\t\t\t\tcell->parameters[\"\\\\CLK_ENABLE\"] = RTLIL::Const(1);\n\t\t\t\tcell->parameters[\"\\\\CLK_POLARITY\"] = RTLIL::Const(clk_polarity);\n\t\t\t\tcell->parameters[\"\\\\TRANSPARENT\"] = RTLIL::Const(0);\n\t\t\t\tlog(\"merged data $dff to cell.\\n\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\tskip_ff_after_read_merging:;\n\t\tRTLIL::SigSpec clk_addr = RTLIL::SigSpec(RTLIL::State::Sx);\n\t\tRTLIL::SigSpec sig_addr = cell->getPort(\"\\\\ADDR\");\n\t\tif (find_sig_before_dff(sig_addr, clk_addr, clk_polarity) &&\n\t\t\t\tclk_addr != RTLIL::SigSpec(RTLIL::State::Sx))\n\t\t{\n\t\t\tcell->setPort(\"\\\\CLK\", clk_addr);\n\t\t\tcell->setPort(\"\\\\EN\", State::S1);\n\t\t\tcell->setPort(\"\\\\ADDR\", sig_addr);\n\t\t\tcell->parameters[\"\\\\CLK_ENABLE\"] = RTLIL::Const(1);\n\t\t\tcell->parameters[\"\\\\CLK_POLARITY\"] = RTLIL::Const(clk_polarity);\n\t\t\tcell->parameters[\"\\\\TRANSPARENT\"] = RTLIL::Const(1);\n\t\t\tlog(\"merged address $dff to cell.\\n\");\n\t\t\treturn;\n\t\t}\n\n\t\tlog(\"no (compatible) $dff found.\\n\");\n\t}\n\n\tvoid run(bool flag_wr_only)\n\t{\n\t\tfor (auto wire : module->wires()) {\n\t\t\tif (wire->port_output)\n\t\t\t\tfor (auto bit : sigmap(wire))\n\t\t\t\t\tsigbit_users_count[bit]++;\n\t\t}\n\n\t\tfor (auto cell : module->cells()) {\n\t\t\tif (cell->type == \"$dff\")\n\t\t\t\tdff_cells.push_back(cell);\n\t\t\tif (cell->type == \"$mux\") {\n\t\t\t\tmux_cells_a[sigmap(cell->getPort(\"\\\\A\"))] = cell;\n\t\t\t\tmux_cells_b[sigmap(cell->getPort(\"\\\\B\"))] = cell;\n\t\t\t}\n\t\t\tif (cell->type == \"$not\" || cell->type == \"$_NOT_\" || (cell->type == \"$logic_not\" && GetSize(cell->getPort(\"\\\\A\")) == 1)) {\n\t\t\t\tSigSpec sig_a = cell->getPort(\"\\\\A\");\n\t\t\t\tSigSpec sig_y = cell->getPort(\"\\\\Y\");\n\t\t\t\tif (cell->type == \"$not\")\n\t\t\t\t\tsig_a.extend_u0(GetSize(sig_y), cell->getParam(\"\\\\A_SIGNED\").as_bool());\n\t\t\t\tif (cell->type == \"$logic_not\")\n\t\t\t\t\tsig_y.extend_u0(1);\n\t\t\t\tfor (int i = 0; i < GetSize(sig_y); i++)\n\t\t\t\t\tinvbits[sig_y[i]] = sig_a[i];\n\t\t\t}\n\t\t\tfor (auto &conn : cell->connections())\n\t\t\t\tif (!cell->known() || cell->input(conn.first))\n\t\t\t\t\tfor (auto bit : sigmap(conn.second))\n\t\t\t\t\t\tsigbit_users_count[bit]++;\n\t\t}\n\n\t\tfor (auto cell : module->selected_cells())\n\t\t\tif (cell->type == \"$memwr\" && !cell->parameters[\"\\\\CLK_ENABLE\"].as_bool())\n\t\t\t\thandle_wr_cell(cell);\n\n\t\tif (!flag_wr_only)\n\t\t\tfor (auto cell : module->selected_cells())\n\t\t\t\tif (cell->type == \"$memrd\" && !cell->parameters[\"\\\\CLK_ENABLE\"].as_bool())\n\t\t\t\t\thandle_rd_cell(cell);\n\t}\n};\n\nstruct MemoryDffPass : public Pass {\n\tMemoryDffPass() : Pass(\"memory_dff\", \"merge input\/output DFFs into memories\") { }\n\tvoid help() YS_OVERRIDE\n\t{\n\t\t\/\/ |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|\n\t\tlog(\"\\n\");\n\t\tlog(\" memory_dff [options] [selection]\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\"This pass detects DFFs at memory ports and merges them into the memory port.\\n\");\n\t\tlog(\"I.e. it consumes an asynchronous memory port and the flip-flops at its\\n\");\n\t\tlog(\"interface and yields a synchronous memory port.\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\" -nordfff\\n\");\n\t\tlog(\" do not merge registers on read ports\\n\");\n\t\tlog(\"\\n\");\n\t}\n\tvoid execute(std::vector args, RTLIL::Design *design) YS_OVERRIDE\n\t{\n\t\tbool flag_wr_only = false;\n\n\t\tlog_header(design, \"Executing MEMORY_DFF pass (merging $dff cells to $memrd and $memwr).\\n\");\n\n\t\tsize_t argidx;\n\t\tfor (argidx = 1; argidx < args.size(); argidx++) {\n\t\t\tif (args[argidx] == \"-nordff\" || args[argidx] == \"-wr_only\") {\n\t\t\t\tflag_wr_only = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\textra_args(args, argidx, design);\n\n\t\tfor (auto mod : design->selected_modules()) {\n\t\t\tMemoryDffWorker worker(mod);\n\t\t\tworker.run(flag_wr_only);\n\t\t}\n\t}\n} MemoryDffPass;\n\nPRIVATE_NAMESPACE_END\n<|endoftext|>"} {"text":"AliAnalysisTaskQASym * AddTaskQAsym(Int_t runNumber)\n\n{\n \/\/ Creates a QA task exploiting simple symmetries phi, eta +\/-, charge ...\n \n \/\/ Get the pointer to the existing analysis manager via the static access method.\n \/\/==============================================================================\n AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();\n if (!mgr) {\n ::Error(\"AddTaskQAsym\", \"No analysis manager to connect to.\");\n return NULL;\n } \n \n \/\/ Check the analysis type using the event handlers connected to the analysis manager.\n \/\/==============================================================================\n if (!mgr->GetInputEventHandler()) {\n ::Error(\"AddTasQAsym\", \"This task requires an input event handler\");\n return NULL;\n }\n TString inputDataType = mgr->GetInputEventHandler()->GetDataType(); \/\/ can be \"ESD\" or \"AOD\"\n \n \/\/ Configure analysis\n \/\/===========================================================================\n \n \n \/\/Task for global tracks\n AliAnalysisTaskQASym *task0 = new AliAnalysisTaskQASym(\"AliAnalysisTaskQASym_Global\");\n task0->SetTrackType(0);\n task0->SelectCollisionCandidates(); \/\/ default setting: kMB = min bias trigger\n task0->SetNChargedRange(30,50); \/\/ comparison of different trigger settings\n \/\/Task for global tracks (high multiplicity)\n AliAnalysisTaskQASym *task0HM = new AliAnalysisTaskQASym(\"AliAnalysisTaskQASym_Global_HighMult\");\n task0HM->SetTrackType(0);\n task0HM->SelectCollisionCandidates(AliVEvent::kHighMult);\n task0HM->SetNChargedRange(30,50); \n \/\/Task for ITS tracks \n AliAnalysisTaskQASym *task1 = new AliAnalysisTaskQASym(\"AliAnalysisTaskQASym_ITS\");\n task1->SetTrackType(1);\n task1->SetStandAloneTrack(kFALSE);\n task1->SelectCollisionCandidates();\n task1->SetNChargedRange(30,50); \n \/\/Task for ITS tracks SA\n AliAnalysisTaskQASym *task1sa = new AliAnalysisTaskQASym(\"AliAnalysisTaskQASym_ITS_SA\");\n task1sa->SetTrackType(1);\n task1sa->SetStandAloneTrack(kTRUE);\n task1sa->SelectCollisionCandidates();\n task1sa->SetNChargedRange(30,50); \n \/\/Task for TPC tracks \n AliAnalysisTaskQASym *task2 = new AliAnalysisTaskQASym(\"AliAnalysisTaskQASym_TPC\");\n task2->SetTrackType(2);\n task2->SelectCollisionCandidates();\n task2->SetNChargedRange(30,50); \n\n \/\/cuts for global tracks\n AliESDtrackCuts* esdTrackCutsL0 = new AliESDtrackCuts(\"AliESDtrackCuts0\",\"Global\");\n esdTrackCutsL0->SetMinNClustersTPC(70);\n esdTrackCutsL0->SetRequireTPCRefit(kTRUE);\n esdTrackCutsL0->SetRequireITSRefit(kTRUE);\n esdTrackCutsL0->SetMaxDCAToVertexXY(3.);\n esdTrackCutsL0->SetMaxDCAToVertexZ(3.);\n esdTrackCutsL0->SetAcceptKinkDaughters(kFALSE);\n \n \/\/cuts for ITS tracks\n AliESDtrackCuts* esdTrackCutsL1 = new AliESDtrackCuts(\"AliESDtrackCuts1\",\"ITS\");\n esdTrackCutsL1->SetMaxDCAToVertexXY(3.);\n esdTrackCutsL1->SetMaxDCAToVertexZ(3.);\n esdTrackCutsL1->SetAcceptKinkDaughters(kFALSE);\n esdTrackCutsL1->SetRequireITSRefit(kTRUE);\n esdTrackCutsL1->SetRequireITSStandAlone(kTRUE); \n\n \/\/cuts for ITS tracks SA\n AliESDtrackCuts* esdTrackCutsL1sa = new AliESDtrackCuts(\"AliESDtrackCuts1\",\"ITS_SA\");\n esdTrackCutsL1sa->SetMaxDCAToVertexXY(3.);\n esdTrackCutsL1sa->SetMaxDCAToVertexZ(3.);\n esdTrackCutsL1sa->SetAcceptKinkDaughters(kFALSE);\n esdTrackCutsL1sa->SetRequireITSRefit(kTRUE);\n esdTrackCutsL1sa->SetRequireITSPureStandAlone(kTRUE);\n \n \/\/cuts for TPC tracks\n AliESDtrackCuts* esdTrackCutsL2 = new AliESDtrackCuts(\"AliESDtrackCuts2\",\"TPC\");\n esdTrackCutsL2->SetRequireTPCRefit(kFALSE);\n esdTrackCutsL2->SetAcceptKinkDaughters(kFALSE);\n \/\/jacek's cuts:\n esdTrackCutsL2->SetMinNClustersTPC(70);\n \/\/ cut on max ncl=160 in Task\n esdTrackCutsL2->SetMaxDCAToVertexXY(3.);\n esdTrackCutsL2->SetMaxDCAToVertexZ(3.);\n esdTrackCutsL2->SetMaxChi2PerClusterTPC(3.999);\n \/\/cut minChi=0 in task\n \/\/esdTrackCutsL2->SetPRange(0.15,16); \/\/ not needed for QA\n \/\/esdTrackCutsL2->SetEtaRange(-0.8, 0.7999); \/\/ not needed for QA\n \n\n task0->SetCuts(esdTrackCutsL0);\n task0HM->SetCuts(esdTrackCutsL0);\n task1->SetCuts(esdTrackCutsL1);\n task1sa->SetCuts(esdTrackCutsL1sa);\n task2->SetCuts(esdTrackCutsL2);\n\n mgr->AddTask(task0);\n mgr->AddTask(task0HM);\n mgr->AddTask(task1);\n mgr->AddTask(task1sa);\n mgr->AddTask(task2);\n \n AliAnalysisDataContainer *cout0 = 0;\n AliAnalysisDataContainer *cout0HM = 0;\n AliAnalysisDataContainer *cout1 = 0;\n AliAnalysisDataContainer *cout1sa = 0;\n AliAnalysisDataContainer *cout2 = 0;\n \n if(runNumber>0){ \n cout0 = mgr->CreateContainer(\"QAsymHists_Global\",TList::Class(),\n\t\t\t\t AliAnalysisManager::kOutputContainer, Form(\"run%d.root\",runNumber));\n cout0HM = mgr->CreateContainer(\"QAsymHists_Global_HighMult\",TList::Class(),\n\t\t\t\t AliAnalysisManager::kOutputContainer, Form(\"run%d.root\",runNumber));\n cout1 = mgr->CreateContainer(\"QAsymHists_ITS\",TList::Class(),\n\t\t\t\t AliAnalysisManager::kOutputContainer, Form(\"run%d.root\",runNumber));\n cout1sa = mgr->CreateContainer(\"QAsymHists_ITS_SA\",TList::Class(),\n\t\t\t\t AliAnalysisManager::kOutputContainer, Form(\"run%d.root\",runNumber));\n cout2 = mgr->CreateContainer(\"QAsymHists_TPC\",TList::Class(),\n\t\t\t\t AliAnalysisManager::kOutputContainer, Form(\"run%d.root\",runNumber));\n }\n \n else{\n cout0 = mgr->CreateContainer(\"QAsymHists_Global\",TList::Class(),\n\t\t\t\t AliAnalysisManager::kOutputContainer, \n\t\t\t\t Form(\"%s:PWG1_QAsymHists\",AliAnalysisManager::GetCommonFileName()));\n cout0HM = mgr->CreateContainer(\"QAsymHists_Global_HighMult\",TList::Class(),\n\t\t\t\t AliAnalysisManager::kOutputContainer, \n\t\t\t\t Form(\"%s:PWG1_QAsymHists\",AliAnalysisManager::GetCommonFileName()));\n cout1 = mgr->CreateContainer(\"QAsymHists_ITS\",TList::Class(),\n\t\t\t\t AliAnalysisManager::kOutputContainer, \n\t\t\t\t Form(\"%s:PWG1_QAsymHists\",AliAnalysisManager::GetCommonFileName()));\n cout1sa = mgr->CreateContainer(\"QAsymHists_ITS_SA\",TList::Class(),\n\t\t\t\t AliAnalysisManager::kOutputContainer, \n\t\t\t\t Form(\"%s:PWG1_QAsymHists\",AliAnalysisManager::GetCommonFileName()));\n cout2 = mgr->CreateContainer(\"QAsymHists_TPC\",TList::Class(),\n\t\t\t\t AliAnalysisManager::kOutputContainer, \n\t\t\t\t Form(\"%s:PWG1_QAsymHists\",AliAnalysisManager::GetCommonFileName()));\n }\n\n\n mgr->ConnectInput (task0, 0, mgr->GetCommonInputContainer());\n mgr->ConnectInput (task0HM, 0, mgr->GetCommonInputContainer());\n mgr->ConnectInput (task1, 0, mgr->GetCommonInputContainer());\n mgr->ConnectInput (task1sa, 0, mgr->GetCommonInputContainer());\n mgr->ConnectInput (task2, 0, mgr->GetCommonInputContainer());\n\n mgr->ConnectOutput (task0, 1, cout0);\n mgr->ConnectOutput (task0HM, 1, cout0HM);\n mgr->ConnectOutput (task1, 1, cout1);\n mgr->ConnectOutput (task1sa, 1, cout1sa);\n mgr->ConnectOutput (task2, 1, cout2);\n \n return task0;\n\n}\n\n\nAllow to pass trigger mask value as parameter to AddTaskQAsymAliAnalysisTaskQASym * AddTaskQAsym(Int_t runNumber, UInt_t maskMB, UInt_t maskHM)\n\n{\n \/\/ Creates a QA task exploiting simple symmetries phi, eta +\/-, charge ...\n \n \/\/ Get the pointer to the existing analysis manager via the static access method.\n \/\/==============================================================================\n AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();\n if (!mgr) {\n ::Error(\"AddTaskQAsym\", \"No analysis manager to connect to.\");\n return NULL;\n } \n \n \/\/ Check the analysis type using the event handlers connected to the analysis manager.\n \/\/==============================================================================\n if (!mgr->GetInputEventHandler()) {\n ::Error(\"AddTasQAsym\", \"This task requires an input event handler\");\n return NULL;\n }\n TString inputDataType = mgr->GetInputEventHandler()->GetDataType(); \/\/ can be \"ESD\" or \"AOD\"\n \n \/\/ Configure analysis\n \/\/===========================================================================\n \n \n \/\/Task for global tracks\n AliAnalysisTaskQASym *task0 = new AliAnalysisTaskQASym(\"AliAnalysisTaskQASym_Global\");\n task0->SetTrackType(0);\n task0->SelectCollisionCandidates(maskMB); \/\/ default setting: kMB = min bias trigger\n task0->SetNChargedRange(30,50); \/\/ comparison of different trigger settings\n \/\/Task for global tracks (high multiplicity)\n AliAnalysisTaskQASym *task0HM = new AliAnalysisTaskQASym(\"AliAnalysisTaskQASym_Global_HighMult\");\n task0HM->SetTrackType(0);\n task0HM->SelectCollisionCandidates(maskHM);\n task0HM->SetNChargedRange(30,50); \n \/\/Task for ITS tracks \n AliAnalysisTaskQASym *task1 = new AliAnalysisTaskQASym(\"AliAnalysisTaskQASym_ITS\");\n task1->SetTrackType(1);\n task1->SetStandAloneTrack(kFALSE);\n task1->SelectCollisionCandidates(maskMB);\n task1->SetNChargedRange(30,50); \n \/\/Task for ITS tracks SA\n AliAnalysisTaskQASym *task1sa = new AliAnalysisTaskQASym(\"AliAnalysisTaskQASym_ITS_SA\");\n task1sa->SetTrackType(1);\n task1sa->SetStandAloneTrack(kTRUE);\n task1sa->SelectCollisionCandidates(maskMB);\n task1sa->SetNChargedRange(30,50); \n \/\/Task for TPC tracks \n AliAnalysisTaskQASym *task2 = new AliAnalysisTaskQASym(\"AliAnalysisTaskQASym_TPC\");\n task2->SetTrackType(2);\n task2->SelectCollisionCandidates(maskMB);\n task2->SetNChargedRange(30,50); \n\n \/\/cuts for global tracks\n AliESDtrackCuts* esdTrackCutsL0 = new AliESDtrackCuts(\"AliESDtrackCuts0\",\"Global\");\n esdTrackCutsL0->SetMinNClustersTPC(70);\n esdTrackCutsL0->SetRequireTPCRefit(kTRUE);\n esdTrackCutsL0->SetRequireITSRefit(kTRUE);\n esdTrackCutsL0->SetMaxDCAToVertexXY(3.);\n esdTrackCutsL0->SetMaxDCAToVertexZ(3.);\n esdTrackCutsL0->SetAcceptKinkDaughters(kFALSE);\n \n \/\/cuts for ITS tracks\n AliESDtrackCuts* esdTrackCutsL1 = new AliESDtrackCuts(\"AliESDtrackCuts1\",\"ITS\");\n esdTrackCutsL1->SetMaxDCAToVertexXY(3.);\n esdTrackCutsL1->SetMaxDCAToVertexZ(3.);\n esdTrackCutsL1->SetAcceptKinkDaughters(kFALSE);\n esdTrackCutsL1->SetRequireITSRefit(kTRUE);\n esdTrackCutsL1->SetRequireITSStandAlone(kTRUE); \n\n \/\/cuts for ITS tracks SA\n AliESDtrackCuts* esdTrackCutsL1sa = new AliESDtrackCuts(\"AliESDtrackCuts1sa\",\"ITS_SA\");\n esdTrackCutsL1sa->SetMaxDCAToVertexXY(3.);\n esdTrackCutsL1sa->SetMaxDCAToVertexZ(3.);\n esdTrackCutsL1sa->SetAcceptKinkDaughters(kFALSE);\n esdTrackCutsL1sa->SetRequireITSRefit(kTRUE);\n esdTrackCutsL1sa->SetRequireITSPureStandAlone(kTRUE);\n \n \/\/cuts for TPC tracks\n AliESDtrackCuts* esdTrackCutsL2 = new AliESDtrackCuts(\"AliESDtrackCuts2\",\"TPC\");\n esdTrackCutsL2->SetRequireTPCRefit(kFALSE);\n esdTrackCutsL2->SetAcceptKinkDaughters(kFALSE);\n \/\/jacek's cuts:\n esdTrackCutsL2->SetMinNClustersTPC(70);\n \/\/ cut on max ncl=160 in Task\n esdTrackCutsL2->SetMaxDCAToVertexXY(3.);\n esdTrackCutsL2->SetMaxDCAToVertexZ(3.);\n esdTrackCutsL2->SetMaxChi2PerClusterTPC(3.999);\n \/\/cut minChi=0 in task\n \/\/esdTrackCutsL2->SetPRange(0.15,16); \/\/ not needed for QA\n \/\/esdTrackCutsL2->SetEtaRange(-0.8, 0.7999); \/\/ not needed for QA\n \n\n task0->SetCuts(esdTrackCutsL0);\n task0HM->SetCuts(esdTrackCutsL0);\n task1->SetCuts(esdTrackCutsL1);\n task1sa->SetCuts(esdTrackCutsL1sa);\n task2->SetCuts(esdTrackCutsL2);\n\n mgr->AddTask(task0);\n mgr->AddTask(task0HM);\n mgr->AddTask(task1);\n mgr->AddTask(task1sa);\n mgr->AddTask(task2);\n \n AliAnalysisDataContainer *cout0 = 0;\n AliAnalysisDataContainer *cout0HM = 0;\n AliAnalysisDataContainer *cout1 = 0;\n AliAnalysisDataContainer *cout1sa = 0;\n AliAnalysisDataContainer *cout2 = 0;\n \n if(runNumber>0){ \n cout0 = mgr->CreateContainer(\"QAsymHists_Global\",TList::Class(),\n\t\t\t\t AliAnalysisManager::kOutputContainer, Form(\"run%d.root\",runNumber));\n cout0HM = mgr->CreateContainer(\"QAsymHists_Global_HighMult\",TList::Class(),\n\t\t\t\t AliAnalysisManager::kOutputContainer, Form(\"run%d.root\",runNumber));\n cout1 = mgr->CreateContainer(\"QAsymHists_ITS\",TList::Class(),\n\t\t\t\t AliAnalysisManager::kOutputContainer, Form(\"run%d.root\",runNumber));\n cout1sa = mgr->CreateContainer(\"QAsymHists_ITS_SA\",TList::Class(),\n\t\t\t\t AliAnalysisManager::kOutputContainer, Form(\"run%d.root\",runNumber));\n cout2 = mgr->CreateContainer(\"QAsymHists_TPC\",TList::Class(),\n\t\t\t\t AliAnalysisManager::kOutputContainer, Form(\"run%d.root\",runNumber));\n }\n \n else{\n cout0 = mgr->CreateContainer(\"QAsymHists_Global\",TList::Class(),\n\t\t\t\t AliAnalysisManager::kOutputContainer, \n\t\t\t\t Form(\"%s:PWG1_QAsymHists\",AliAnalysisManager::GetCommonFileName()));\n cout0HM = mgr->CreateContainer(\"QAsymHists_Global_HighMult\",TList::Class(),\n\t\t\t\t AliAnalysisManager::kOutputContainer, \n\t\t\t\t Form(\"%s:PWG1_QAsymHists\",AliAnalysisManager::GetCommonFileName()));\n cout1 = mgr->CreateContainer(\"QAsymHists_ITS\",TList::Class(),\n\t\t\t\t AliAnalysisManager::kOutputContainer, \n\t\t\t\t Form(\"%s:PWG1_QAsymHists\",AliAnalysisManager::GetCommonFileName()));\n cout1sa = mgr->CreateContainer(\"QAsymHists_ITS_SA\",TList::Class(),\n\t\t\t\t AliAnalysisManager::kOutputContainer, \n\t\t\t\t Form(\"%s:PWG1_QAsymHists\",AliAnalysisManager::GetCommonFileName()));\n cout2 = mgr->CreateContainer(\"QAsymHists_TPC\",TList::Class(),\n\t\t\t\t AliAnalysisManager::kOutputContainer, \n\t\t\t\t Form(\"%s:PWG1_QAsymHists\",AliAnalysisManager::GetCommonFileName()));\n }\n\n\n mgr->ConnectInput (task0, 0, mgr->GetCommonInputContainer());\n mgr->ConnectInput (task0HM, 0, mgr->GetCommonInputContainer());\n mgr->ConnectInput (task1, 0, mgr->GetCommonInputContainer());\n mgr->ConnectInput (task1sa, 0, mgr->GetCommonInputContainer());\n mgr->ConnectInput (task2, 0, mgr->GetCommonInputContainer());\n\n mgr->ConnectOutput (task0, 1, cout0);\n mgr->ConnectOutput (task0HM, 1, cout0HM);\n mgr->ConnectOutput (task1, 1, cout1);\n mgr->ConnectOutput (task1sa, 1, cout1sa);\n mgr->ConnectOutput (task2, 1, cout2);\n \n return task0;\n\n}\n\n\n<|endoftext|>"} {"text":"\/** @file\n\n @section license License\n\n Licensed to the Apache Software Foundation (ASF) under one\n or more contributor license agreements. See the NOTICE file\n distributed with this work for additional information\n regarding copyright ownership. The ASF licenses this file\n to you under the Apache License, Version 2.0 (the\n \"License\"); you may not use this file except in compliance\n with the License. You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ collapsed_forwarding::\n\/\/\n\/\/ ATS plugin to allow collapsed forwarding of concurrent requests for the same\n\/\/ object. This plugin is based on open_write_fail_action feature, which detects\n\/\/ cache open write failure on a cache miss and returns a 502 error along with a\n\/\/ special @-header indicating the reason for 502 error. The plugin acts on the\n\/\/ error by using an internal redirect follow back to itself, essentially blocking\n\/\/ the request until a response arrives, at which point, relies on read-while-writer\n\/\/ feature to start downloading the object to all waiting clients. The following\n\/\/ config parameters are assumed to be set for this plugin to work:\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ proxy.config.http.cache.open_write_fail_action 1 \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ proxy.config.cache.enable_read_while_writer 1 \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ proxy.config.http.redirection_enabled 1 \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ proxy.config.http.number_of_redirections 10 \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ proxy.config.http.redirect_use_orig_cache_key 1 \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ proxy.config.http.background_fill_active_timeout 0 \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ proxy.config.http.background_fill_completed_threshold 0 \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Additionally, given that collapsed forwarding works based on cache write\n\/\/ lock failure detection, the plugin requires cache to be enabled and ready.\n\/\/ On a restart, Traffic Server typically takes a few seconds to initialize\n\/\/ the cache depending on the cache size and number of dirents. While the\n\/\/ cache is not ready yet, collapsed forwarding can not detect the write lock\n\/\/ contention and so can not work. The setting proxy.config.http.wait_for_cache\n\/\/ may be enabled which allows blocking incoming connections from being\n\/\/ accepted until cache is ready.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ This plugin currently supports only per-remap mode activation.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nstatic const char *DEBUG_TAG = (char *)\"collapsed_forwarding\";\n\nstatic const char *LOCATION_HEADER = \"Location\";\nstatic const char *REDIRECT_REASON = \"See Other\";\nstatic const char *ATS_INTERNAL_MESSAGE = \"@Ats-Internal\";\n\nstatic int OPEN_WRITE_FAIL_MAX_REQ_DELAY_RETRIES = 5;\nstatic int OPEN_WRITE_FAIL_REQ_DELAY_TIMEOUT = 500;\n\ntypedef struct _RequestData {\n TSHttpTxn txnp;\n int wl_retry; \/\/ write lock failure retry count\n std::string req_url;\n} RequestData;\n\nstatic int\nadd_redirect_header(TSMBuffer &bufp, TSMLoc &hdr_loc, const std::string &location)\n{\n \/\/ This is needed in case the response already contains a Location header\n TSMLoc field_loc = TSMimeHdrFieldFind(bufp, hdr_loc, LOCATION_HEADER, strlen(LOCATION_HEADER));\n\n if (field_loc == TS_NULL_MLOC) {\n TSMimeHdrFieldCreateNamed(bufp, hdr_loc, LOCATION_HEADER, strlen(LOCATION_HEADER), &field_loc);\n }\n\n if (TS_SUCCESS == TSMimeHdrFieldValueStringSet(bufp, hdr_loc, field_loc, -1, location.c_str(), location.size())) {\n TSDebug(DEBUG_TAG, \"Adding Location header %s\", LOCATION_HEADER);\n TSMimeHdrFieldAppend(bufp, hdr_loc, field_loc);\n }\n\n TSHandleMLocRelease(bufp, hdr_loc, field_loc);\n\n TSHttpHdrStatusSet(bufp, hdr_loc, TS_HTTP_STATUS_SEE_OTHER);\n TSHttpHdrReasonSet(bufp, hdr_loc, REDIRECT_REASON, strlen(REDIRECT_REASON));\n return TS_SUCCESS;\n}\n\nstatic bool\ncheck_internal_message_hdr(TSHttpTxn &txnp)\n{\n TSMBuffer bufp;\n TSMLoc hdr_loc;\n bool found = false;\n\n if (TSHttpTxnClientRespGet(txnp, &bufp, &hdr_loc) != TS_SUCCESS) {\n TSError(\"check_internal_message_hdr: couldn't retrieve client response header\");\n return false;\n }\n\n TSMLoc header_loc = TSMimeHdrFieldFind(bufp, hdr_loc, ATS_INTERNAL_MESSAGE, strlen(ATS_INTERNAL_MESSAGE));\n if (header_loc) {\n found = true;\n \/\/ found the header, remove it now..\n TSMimeHdrFieldDestroy(bufp, hdr_loc, header_loc);\n TSHandleMLocRelease(bufp, hdr_loc, header_loc);\n }\n\n TSHandleMLocRelease(bufp, TS_NULL_MLOC, hdr_loc);\n\n return found;\n}\n\nstatic int\non_OS_DNS(const RequestData *req, TSHttpTxn &txnp)\n{\n if (req->wl_retry > 0) {\n TSDebug(DEBUG_TAG, \"OS_DNS request delayed %d times, block origin req for url: %s\", req->wl_retry, req->req_url.c_str());\n TSHttpTxnReenable(txnp, TS_EVENT_HTTP_ERROR);\n return TS_SUCCESS;\n }\n\n TSHttpTxnReenable(txnp, TS_EVENT_HTTP_CONTINUE);\n return TS_SUCCESS;\n}\n\nstatic int\non_send_request_header(const RequestData *req, TSHttpTxn &txnp)\n{\n if (req->wl_retry > 0) {\n TSDebug(DEBUG_TAG, \"Send_Req request delayed %d times, block origin req for url: %s\", req->wl_retry, req->req_url.c_str());\n TSHttpTxnReenable(txnp, TS_EVENT_HTTP_ERROR);\n return TS_SUCCESS;\n }\n\n TSHttpTxnReenable(txnp, TS_EVENT_HTTP_CONTINUE);\n return TS_SUCCESS;\n}\n\nstatic int\non_read_response_header(TSHttpTxn &txnp)\n{\n TSHttpTxnReenable(txnp, TS_EVENT_HTTP_CONTINUE);\n return TS_SUCCESS;\n}\n\nstatic int\non_immediate(RequestData *req, TSCont &contp)\n{\n if (!req) {\n TSError(\"%s: invalid req_data\", DEBUG_TAG);\n return TS_SUCCESS;\n }\n\n TSDebug(DEBUG_TAG, \"continuation delayed, scheduling now..for url: %s\", req->req_url.c_str());\n\n \/\/ add retry_done header to prevent looping\n std::string value;\n TSMBuffer bufp;\n TSMLoc hdr_loc;\n if (TSHttpTxnClientRespGet(req->txnp, &bufp, &hdr_loc) != TS_SUCCESS) {\n TSError(\"plugin=%s, level=error, error_code=could_not_retrieve_client_response_header for url %s\", DEBUG_TAG,\n req->req_url.c_str());\n TSHttpTxnReenable(req->txnp, TS_EVENT_HTTP_ERROR);\n return TS_SUCCESS;\n }\n\n add_redirect_header(bufp, hdr_loc, req->req_url);\n TSHandleMLocRelease(bufp, TS_NULL_MLOC, hdr_loc);\n TSHttpTxnReenable(req->txnp, TS_EVENT_HTTP_CONTINUE);\n return TS_SUCCESS;\n}\n\nstatic int\non_send_response_header(RequestData *req, TSHttpTxn &txnp, TSCont &contp)\n{\n TSMBuffer bufp;\n TSMLoc hdr_loc;\n if (TSHttpTxnClientRespGet(txnp, &bufp, &hdr_loc) != TS_SUCCESS) {\n TSError(\"plugin=%s, level=error, error_code=could_not_retrieve_client_response_header\", DEBUG_TAG);\n return TS_SUCCESS;\n }\n\n TSHttpStatus status = TSHttpHdrStatusGet(bufp, hdr_loc);\n TSDebug(DEBUG_TAG, \"Response code: %d\", status);\n\n if ((status == TS_HTTP_STATUS_BAD_GATEWAY) || (status == TS_HTTP_STATUS_SEE_OTHER) ||\n status == TS_HTTP_STATUS_INTERNAL_SERVER_ERROR) {\n bool is_internal_message_hdr = check_internal_message_hdr(txnp);\n bool delay_request =\n is_internal_message_hdr || ((req->wl_retry > 0) && (req->wl_retry < OPEN_WRITE_FAIL_MAX_REQ_DELAY_RETRIES));\n\n if (delay_request) {\n req->wl_retry++;\n TSDebug(DEBUG_TAG, \"delaying request, url@%p: {{%s}} on retry: %d time\", txnp, req->req_url.c_str(), req->wl_retry);\n TSContSchedule(contp, OPEN_WRITE_FAIL_REQ_DELAY_TIMEOUT, TS_THREAD_POOL_TASK);\n TSHandleMLocRelease(bufp, TS_NULL_MLOC, hdr_loc);\n return TS_SUCCESS;\n }\n }\n\n if (req->wl_retry > 0) {\n TSDebug(DEBUG_TAG, \"request delayed, but unsuccessful, url@%p: {{%s}} on retry: %d time\", txnp, req->req_url.c_str(),\n req->wl_retry);\n req->wl_retry = 0;\n }\n\n \/\/ done..cleanup\n delete req;\n TSContDestroy(contp);\n\n TSHandleMLocRelease(bufp, TS_NULL_MLOC, hdr_loc);\n TSHttpTxnReenable(txnp, TS_EVENT_HTTP_CONTINUE);\n return TS_SUCCESS;\n}\n\nstatic int\ncollapsed_cont(TSCont contp, TSEvent event, void *edata)\n{\n TSHttpTxn txnp = static_cast(edata);\n RequestData *my_req = static_cast(TSContDataGet(contp));\n\n switch (event) {\n case TS_EVENT_HTTP_OS_DNS: {\n return on_OS_DNS(my_req, txnp);\n }\n\n case TS_EVENT_HTTP_SEND_REQUEST_HDR: {\n return on_send_request_header(my_req, txnp);\n }\n\n case TS_EVENT_HTTP_READ_RESPONSE_HDR: {\n return on_read_response_header(txnp);\n }\n case TS_EVENT_IMMEDIATE:\n case TS_EVENT_TIMEOUT: {\n return on_immediate(my_req, contp);\n }\n case TS_EVENT_HTTP_SEND_RESPONSE_HDR: {\n return on_send_response_header(my_req, txnp, contp);\n }\n default: {\n TSDebug(DEBUG_TAG, \"Unexpected event: %d\", event);\n break;\n }\n }\n\n TSHttpTxnReenable(txnp, TS_EVENT_HTTP_CONTINUE);\n return TS_SUCCESS;\n}\n\nTSReturnCode\nTSRemapInit(TSRemapInterface * \/* api_info *\/, char * \/* errbuf *\/, int \/* errbuf_size *\/)\n{\n TSDebug(DEBUG_TAG, \"plugin is succesfully initialized\");\n return TS_SUCCESS;\n}\n\nTSReturnCode\nTSRemapNewInstance(int argc, char *argv[], void ** \/* ih *\/, char * \/* errbuf *\/, int \/* errbuf_size *\/)\n{\n \/\/ basic argv processing..\n for (int i = 2; i < argc; ++i) {\n if (strncmp(argv[i], \"--delay=\", 8) == 0) {\n OPEN_WRITE_FAIL_REQ_DELAY_TIMEOUT = atoi((char *)(argv[i] + 8));\n } else if (strncmp(argv[i], \"--retries=\", 10) == 0) {\n OPEN_WRITE_FAIL_MAX_REQ_DELAY_RETRIES = atoi((char *)(argv[i] + 10));\n }\n }\n\n return TS_SUCCESS;\n}\n\nTSRemapStatus\nTSRemapDoRemap(void *ih, TSHttpTxn rh, TSRemapRequestInfo *rri)\n{\n TSCont cont = TSContCreate(collapsed_cont, TSMutexCreate());\n\n RequestData *req_data = new RequestData();\n\n req_data->txnp = rh;\n req_data->wl_retry = 0;\n\n int url_len = 0;\n char *url = TSHttpTxnEffectiveUrlStringGet(rh, &url_len);\n req_data->req_url.assign(url, url_len);\n\n TSfree(url);\n TSContDataSet(cont, req_data);\n\n TSHttpTxnHookAdd(rh, TS_HTTP_SEND_REQUEST_HDR_HOOK, cont);\n TSHttpTxnHookAdd(rh, TS_HTTP_SEND_RESPONSE_HDR_HOOK, cont);\n TSHttpTxnHookAdd(rh, TS_HTTP_READ_RESPONSE_HDR_HOOK, cont);\n TSHttpTxnHookAdd(rh, TS_HTTP_OS_DNS_HOOK, cont);\n\n return TSREMAP_DID_REMAP;\n}\nTS-4888: Modified collapsed_forwarding plugin to return TSREMAP_NO_REMAP.\/** @file\n\n @section license License\n\n Licensed to the Apache Software Foundation (ASF) under one\n or more contributor license agreements. See the NOTICE file\n distributed with this work for additional information\n regarding copyright ownership. The ASF licenses this file\n to you under the Apache License, Version 2.0 (the\n \"License\"); you may not use this file except in compliance\n with the License. You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ collapsed_forwarding::\n\/\/\n\/\/ ATS plugin to allow collapsed forwarding of concurrent requests for the same\n\/\/ object. This plugin is based on open_write_fail_action feature, which detects\n\/\/ cache open write failure on a cache miss and returns a 502 error along with a\n\/\/ special @-header indicating the reason for 502 error. The plugin acts on the\n\/\/ error by using an internal redirect follow back to itself, essentially blocking\n\/\/ the request until a response arrives, at which point, relies on read-while-writer\n\/\/ feature to start downloading the object to all waiting clients. The following\n\/\/ config parameters are assumed to be set for this plugin to work:\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ proxy.config.http.cache.open_write_fail_action 1 \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ proxy.config.cache.enable_read_while_writer 1 \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ proxy.config.http.redirection_enabled 1 \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ proxy.config.http.number_of_redirections 10 \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ proxy.config.http.redirect_use_orig_cache_key 1 \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ proxy.config.http.background_fill_active_timeout 0 \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ proxy.config.http.background_fill_completed_threshold 0 \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Additionally, given that collapsed forwarding works based on cache write\n\/\/ lock failure detection, the plugin requires cache to be enabled and ready.\n\/\/ On a restart, Traffic Server typically takes a few seconds to initialize\n\/\/ the cache depending on the cache size and number of dirents. While the\n\/\/ cache is not ready yet, collapsed forwarding can not detect the write lock\n\/\/ contention and so can not work. The setting proxy.config.http.wait_for_cache\n\/\/ may be enabled which allows blocking incoming connections from being\n\/\/ accepted until cache is ready.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ This plugin currently supports only per-remap mode activation.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nstatic const char *DEBUG_TAG = (char *)\"collapsed_forwarding\";\n\nstatic const char *LOCATION_HEADER = \"Location\";\nstatic const char *REDIRECT_REASON = \"See Other\";\nstatic const char *ATS_INTERNAL_MESSAGE = \"@Ats-Internal\";\n\nstatic int OPEN_WRITE_FAIL_MAX_REQ_DELAY_RETRIES = 5;\nstatic int OPEN_WRITE_FAIL_REQ_DELAY_TIMEOUT = 500;\n\ntypedef struct _RequestData {\n TSHttpTxn txnp;\n int wl_retry; \/\/ write lock failure retry count\n std::string req_url;\n} RequestData;\n\nstatic int\nadd_redirect_header(TSMBuffer &bufp, TSMLoc &hdr_loc, const std::string &location)\n{\n \/\/ This is needed in case the response already contains a Location header\n TSMLoc field_loc = TSMimeHdrFieldFind(bufp, hdr_loc, LOCATION_HEADER, strlen(LOCATION_HEADER));\n\n if (field_loc == TS_NULL_MLOC) {\n TSMimeHdrFieldCreateNamed(bufp, hdr_loc, LOCATION_HEADER, strlen(LOCATION_HEADER), &field_loc);\n }\n\n if (TS_SUCCESS == TSMimeHdrFieldValueStringSet(bufp, hdr_loc, field_loc, -1, location.c_str(), location.size())) {\n TSDebug(DEBUG_TAG, \"Adding Location header %s\", LOCATION_HEADER);\n TSMimeHdrFieldAppend(bufp, hdr_loc, field_loc);\n }\n\n TSHandleMLocRelease(bufp, hdr_loc, field_loc);\n\n TSHttpHdrStatusSet(bufp, hdr_loc, TS_HTTP_STATUS_SEE_OTHER);\n TSHttpHdrReasonSet(bufp, hdr_loc, REDIRECT_REASON, strlen(REDIRECT_REASON));\n return TS_SUCCESS;\n}\n\nstatic bool\ncheck_internal_message_hdr(TSHttpTxn &txnp)\n{\n TSMBuffer bufp;\n TSMLoc hdr_loc;\n bool found = false;\n\n if (TSHttpTxnClientRespGet(txnp, &bufp, &hdr_loc) != TS_SUCCESS) {\n TSError(\"check_internal_message_hdr: couldn't retrieve client response header\");\n return false;\n }\n\n TSMLoc header_loc = TSMimeHdrFieldFind(bufp, hdr_loc, ATS_INTERNAL_MESSAGE, strlen(ATS_INTERNAL_MESSAGE));\n if (header_loc) {\n found = true;\n \/\/ found the header, remove it now..\n TSMimeHdrFieldDestroy(bufp, hdr_loc, header_loc);\n TSHandleMLocRelease(bufp, hdr_loc, header_loc);\n }\n\n TSHandleMLocRelease(bufp, TS_NULL_MLOC, hdr_loc);\n\n return found;\n}\n\nstatic int\non_OS_DNS(const RequestData *req, TSHttpTxn &txnp)\n{\n if (req->wl_retry > 0) {\n TSDebug(DEBUG_TAG, \"OS_DNS request delayed %d times, block origin req for url: %s\", req->wl_retry, req->req_url.c_str());\n TSHttpTxnReenable(txnp, TS_EVENT_HTTP_ERROR);\n return TS_SUCCESS;\n }\n\n TSHttpTxnReenable(txnp, TS_EVENT_HTTP_CONTINUE);\n return TS_SUCCESS;\n}\n\nstatic int\non_send_request_header(const RequestData *req, TSHttpTxn &txnp)\n{\n if (req->wl_retry > 0) {\n TSDebug(DEBUG_TAG, \"Send_Req request delayed %d times, block origin req for url: %s\", req->wl_retry, req->req_url.c_str());\n TSHttpTxnReenable(txnp, TS_EVENT_HTTP_ERROR);\n return TS_SUCCESS;\n }\n\n TSHttpTxnReenable(txnp, TS_EVENT_HTTP_CONTINUE);\n return TS_SUCCESS;\n}\n\nstatic int\non_read_response_header(TSHttpTxn &txnp)\n{\n TSHttpTxnReenable(txnp, TS_EVENT_HTTP_CONTINUE);\n return TS_SUCCESS;\n}\n\nstatic int\non_immediate(RequestData *req, TSCont &contp)\n{\n if (!req) {\n TSError(\"%s: invalid req_data\", DEBUG_TAG);\n return TS_SUCCESS;\n }\n\n TSDebug(DEBUG_TAG, \"continuation delayed, scheduling now..for url: %s\", req->req_url.c_str());\n\n \/\/ add retry_done header to prevent looping\n std::string value;\n TSMBuffer bufp;\n TSMLoc hdr_loc;\n if (TSHttpTxnClientRespGet(req->txnp, &bufp, &hdr_loc) != TS_SUCCESS) {\n TSError(\"plugin=%s, level=error, error_code=could_not_retrieve_client_response_header for url %s\", DEBUG_TAG,\n req->req_url.c_str());\n TSHttpTxnReenable(req->txnp, TS_EVENT_HTTP_ERROR);\n return TS_SUCCESS;\n }\n\n add_redirect_header(bufp, hdr_loc, req->req_url);\n TSHandleMLocRelease(bufp, TS_NULL_MLOC, hdr_loc);\n TSHttpTxnReenable(req->txnp, TS_EVENT_HTTP_CONTINUE);\n return TS_SUCCESS;\n}\n\nstatic int\non_send_response_header(RequestData *req, TSHttpTxn &txnp, TSCont &contp)\n{\n TSMBuffer bufp;\n TSMLoc hdr_loc;\n if (TSHttpTxnClientRespGet(txnp, &bufp, &hdr_loc) != TS_SUCCESS) {\n TSError(\"plugin=%s, level=error, error_code=could_not_retrieve_client_response_header\", DEBUG_TAG);\n return TS_SUCCESS;\n }\n\n TSHttpStatus status = TSHttpHdrStatusGet(bufp, hdr_loc);\n TSDebug(DEBUG_TAG, \"Response code: %d\", status);\n\n if ((status == TS_HTTP_STATUS_BAD_GATEWAY) || (status == TS_HTTP_STATUS_SEE_OTHER) ||\n status == TS_HTTP_STATUS_INTERNAL_SERVER_ERROR) {\n bool is_internal_message_hdr = check_internal_message_hdr(txnp);\n bool delay_request =\n is_internal_message_hdr || ((req->wl_retry > 0) && (req->wl_retry < OPEN_WRITE_FAIL_MAX_REQ_DELAY_RETRIES));\n\n if (delay_request) {\n req->wl_retry++;\n TSDebug(DEBUG_TAG, \"delaying request, url@%p: {{%s}} on retry: %d time\", txnp, req->req_url.c_str(), req->wl_retry);\n TSContSchedule(contp, OPEN_WRITE_FAIL_REQ_DELAY_TIMEOUT, TS_THREAD_POOL_TASK);\n TSHandleMLocRelease(bufp, TS_NULL_MLOC, hdr_loc);\n return TS_SUCCESS;\n }\n }\n\n if (req->wl_retry > 0) {\n TSDebug(DEBUG_TAG, \"request delayed, but unsuccessful, url@%p: {{%s}} on retry: %d time\", txnp, req->req_url.c_str(),\n req->wl_retry);\n req->wl_retry = 0;\n }\n\n \/\/ done..cleanup\n delete req;\n TSContDestroy(contp);\n\n TSHandleMLocRelease(bufp, TS_NULL_MLOC, hdr_loc);\n TSHttpTxnReenable(txnp, TS_EVENT_HTTP_CONTINUE);\n return TS_SUCCESS;\n}\n\nstatic int\ncollapsed_cont(TSCont contp, TSEvent event, void *edata)\n{\n TSHttpTxn txnp = static_cast(edata);\n RequestData *my_req = static_cast(TSContDataGet(contp));\n\n switch (event) {\n case TS_EVENT_HTTP_OS_DNS: {\n return on_OS_DNS(my_req, txnp);\n }\n\n case TS_EVENT_HTTP_SEND_REQUEST_HDR: {\n return on_send_request_header(my_req, txnp);\n }\n\n case TS_EVENT_HTTP_READ_RESPONSE_HDR: {\n return on_read_response_header(txnp);\n }\n case TS_EVENT_IMMEDIATE:\n case TS_EVENT_TIMEOUT: {\n return on_immediate(my_req, contp);\n }\n case TS_EVENT_HTTP_SEND_RESPONSE_HDR: {\n return on_send_response_header(my_req, txnp, contp);\n }\n default: {\n TSDebug(DEBUG_TAG, \"Unexpected event: %d\", event);\n break;\n }\n }\n\n TSHttpTxnReenable(txnp, TS_EVENT_HTTP_CONTINUE);\n return TS_SUCCESS;\n}\n\nTSReturnCode\nTSRemapInit(TSRemapInterface * \/* api_info *\/, char * \/* errbuf *\/, int \/* errbuf_size *\/)\n{\n TSDebug(DEBUG_TAG, \"plugin is succesfully initialized\");\n return TS_SUCCESS;\n}\n\nTSReturnCode\nTSRemapNewInstance(int argc, char *argv[], void ** \/* ih *\/, char * \/* errbuf *\/, int \/* errbuf_size *\/)\n{\n \/\/ basic argv processing..\n for (int i = 2; i < argc; ++i) {\n if (strncmp(argv[i], \"--delay=\", 8) == 0) {\n OPEN_WRITE_FAIL_REQ_DELAY_TIMEOUT = atoi((char *)(argv[i] + 8));\n } else if (strncmp(argv[i], \"--retries=\", 10) == 0) {\n OPEN_WRITE_FAIL_MAX_REQ_DELAY_RETRIES = atoi((char *)(argv[i] + 10));\n }\n }\n\n return TS_SUCCESS;\n}\n\nTSRemapStatus\nTSRemapDoRemap(void *ih, TSHttpTxn rh, TSRemapRequestInfo *rri)\n{\n TSCont cont = TSContCreate(collapsed_cont, TSMutexCreate());\n\n RequestData *req_data = new RequestData();\n\n req_data->txnp = rh;\n req_data->wl_retry = 0;\n\n int url_len = 0;\n char *url = TSHttpTxnEffectiveUrlStringGet(rh, &url_len);\n req_data->req_url.assign(url, url_len);\n\n TSfree(url);\n TSContDataSet(cont, req_data);\n\n TSHttpTxnHookAdd(rh, TS_HTTP_SEND_REQUEST_HDR_HOOK, cont);\n TSHttpTxnHookAdd(rh, TS_HTTP_SEND_RESPONSE_HDR_HOOK, cont);\n TSHttpTxnHookAdd(rh, TS_HTTP_READ_RESPONSE_HDR_HOOK, cont);\n TSHttpTxnHookAdd(rh, TS_HTTP_OS_DNS_HOOK, cont);\n\n return TSREMAP_NO_REMAP;\n}\n\nvoid\nTSRemapDeleteInstance(void *ih)\n{\n \/\/ To resolve run time error\n}\n<|endoftext|>"} {"text":"enum libModes {mLocal,mLocalSource};\n\/\/mLocal: Analyze data on your computer using aliroot\n\/\/mLocalSource: Analyze data on your computer using root + source files\n\nvoid mergeOutput(const Int_t nRuns=-1, TString type=\"\",Int_t mode=mLocal)\n{ \n \/\/ load needed libraries: \n LoadSpreadLibraries(mode); \n \n \/\/ file mergers for the output file of each method separately: \n \/\/ MCEP: \n TFileMerger *mcepFileMerger = new TFileMerger();\n TString mergedFileNameMCEP(\"outputMCEPanalysis.root\");\n mcepFileMerger->OutputFile(mergedFileNameMCEP);\n \n \/\/ SP: \n TFileMerger *spFileMerger = new TFileMerger();\n TString mergedFileNameSP(\"outputSPanalysis.root\");\n spFileMerger->OutputFile(mergedFileNameSP);\n\n \/\/ GFC: \n TFileMerger *gfcFileMerger = new TFileMerger();\n TString mergedFileNameGFC(\"outputGFCanalysis.root\");\n gfcFileMerger->OutputFile(mergedFileNameGFC);\n \n \/\/ QC: \n TFileMerger *qcFileMerger = new TFileMerger();\n TString mergedFileNameQC(\"outputQCanalysis.root\");\n qcFileMerger->OutputFile(mergedFileNameQC);\n \n \/\/ FQD: \n TFileMerger *fqdFileMerger = new TFileMerger();\n TString mergedFileNameFQD(\"outputFQDanalysis.root\");\n fqdFileMerger->OutputFile(mergedFileNameFQD);\n \n \/\/ LYZ1: \n TFileMerger *lyz1FileMerger = new TFileMerger();\n TString mergedFileNameLYZ1(\"outputLYZ1analysis.root\");\n lyz1FileMerger->OutputFile(mergedFileNameLYZ1);\n \n \/\/ LYZ2: \n TFileMerger *lyz2FileMerger = new TFileMerger();\n TString mergedFileNameLYZ2(\"outputLYZ2analysis.root\");\n lyz2FileMerger->OutputFile(mergedFileNameLYZ2);\n \n \/\/ LYZEP: \n TFileMerger *lyzepFileMerger = new TFileMerger();\n TString mergedFileNameLYZEP(\"outputLYZEPanalysis.root\");\n lyzepFileMerger->OutputFile(mergedFileNameLYZEP);\n \n \/\/ standard magic:\n TString execDir(gSystem->pwd()); \n TSystemDirectory* baseDir = new TSystemDirectory(\".\",execDir.Data()); \n TList* dirList = baseDir->GetListOfFiles();\n Int_t nDirs = dirList->GetEntries();\n gSystem->cd(execDir); \n\n Int_t counter = 0;\n \n for(Int_t iDir=0;iDirAt(iDir);\n if(!presentDir || !presentDir->IsDirectory() || strcmp(presentDir->GetName(), \".\") == 0 || \n strcmp(presentDir->GetName(), \"..\") == 0) continue; \n \n if(nRuns != -1)\n { \n if (counter >= nRuns) break; \n } \n \n TString presentDirName(gSystem->pwd()); \n presentDirName += \"\/\";\n presentDirName += presentDir->GetName();\n presentDirName += \"\/\";\n \n \/\/ accessing the output .root files from independent analysis for each method:\n \/\/ MCEP: \n TString fileNameMCEP = presentDirName; \n fileNameMCEP+=\"outputMCEPanalysis.root\";\n mcepFileMerger->AddFile(fileNameMCEP.Data());\n \/\/ SP: \n TString fileNameSP = presentDirName; \n fileNameSP+=\"outputSPanalysis.root\";\n spFileMerger->AddFile(fileNameSP.Data());\n \/\/ GFC: \n TString fileNameGFC = presentDirName; \n fileNameGFC+=\"outputGFCanalysis.root\";\n gfcFileMerger->AddFile(fileNameGFC.Data());\n \/\/ QC: \n TString fileNameQC = presentDirName; \n fileNameQC+=\"outputQCanalysis.root\";\n qcFileMerger->AddFile(fileNameQC.Data());\n \/\/ FQD: \n TString fileNameFQD = presentDirName; \n fileNameFQD+=\"outputFQDanalysis.root\";\n fqdFileMerger->AddFile(fileNameFQD.Data());\n \/\/ LYZ1: \n TString fileNameLYZ1 = presentDirName; \n fileNameLYZ1+=\"outputLYZ1analysis.root\";\n lyz1FileMerger->AddFile(fileNameLYZ1.Data());\n \/\/ LYZ2: \n TString fileNameLYZ2 = presentDirName; \n fileNameLYZ2+=\"outputLYZ2analysis.root\";\n lyz2FileMerger->AddFile(fileNameLYZ2.Data());\n \/\/ LYZEP: \n TString fileNameLYZEP = presentDirName; \n fileNameLYZEP+=\"outputLYZEPanalysis.root\";\n lyzepFileMerger->AddFile(fileNameLYZEP.Data());\n \n counter++;\n \n } \/\/ end of for(Int_t iDir=0;iDirMerge();\n spFileMerger->Merge();\n gfcFileMerger->Merge();\n qcFileMerger->Merge();\n fqdFileMerger->Merge();\n lyz1FileMerger->Merge();\n lyz2FileMerger->Merge();\n lyzepFileMerger->Merge();\n}\n\n\nvoid LoadSpreadLibraries(const libModes mode) {\n \n \/\/--------------------------------------\n \/\/ Load the needed libraries most of them already loaded by aliroot\n \/\/--------------------------------------\n gSystem->Load(\"libTree.so\");\n gSystem->Load(\"libGeom.so\");\n gSystem->Load(\"libVMC.so\");\n gSystem->Load(\"libXMLIO.so\");\n gSystem->Load(\"libPhysics.so\");\n \n \/\/----------------------------------------------------------\n \/\/ >>>>>>>>>>> Local mode <<<<<<<<<<<<<< \n \/\/----------------------------------------------------------\n if (mode==mLocal) {\n \/\/--------------------------------------------------------\n \/\/ If you want to use already compiled libraries \n \/\/ in the aliroot distribution\n \/\/--------------------------------------------------------\n\n \/\/================================================================================== \n \/\/load needed libraries:\n gSystem->AddIncludePath(\"-I$ROOTSYS\/include\");\n gSystem->Load(\"libTree.so\");\n\n \/\/ for AliRoot\n gSystem->AddIncludePath(\"-I$ALICE_ROOT\/include\");\n gSystem->Load(\"libANALYSIS.so\");\n gSystem->Load(\"libPWG2flowCommon.so\");\n cerr<<\"libPWG2flowCommon.so loaded ...\"<LoadMacro(\"AliFlowCommon\/AliFlowCommonConstants.cxx+\");\n gROOT->LoadMacro(\"AliFlowCommon\/AliFlowLYZConstants.cxx+\");\n gROOT->LoadMacro(\"AliFlowCommon\/AliFlowCumuConstants.cxx+\");\n \n \/\/ Flow event\n gROOT->LoadMacro(\"AliFlowCommon\/AliFlowVector.cxx+\"); \n gROOT->LoadMacro(\"AliFlowCommon\/AliFlowTrackSimple.cxx+\"); \n gROOT->LoadMacro(\"AliFlowCommon\/AliFlowEventSimple.cxx+\");\n \n \/\/ Cuts\n gROOT->LoadMacro(\"AliFlowCommon\/AliFlowTrackSimpleCuts.cxx+\"); \n \n \/\/ Output histosgrams\n gROOT->LoadMacro(\"AliFlowCommon\/AliFlowCommonHist.cxx+\");\n gROOT->LoadMacro(\"AliFlowCommon\/AliFlowCommonHistResults.cxx+\");\n gROOT->LoadMacro(\"AliFlowCommon\/AliFlowLYZHist1.cxx+\");\n gROOT->LoadMacro(\"AliFlowCommon\/AliFlowLYZHist2.cxx+\");\n \n cout << \"finished loading macros!\" << endl; \n \n } \n \n}\n\n\nAdded some protectionenum libModes {mLocal,mLocalSource};\n\/\/mLocal: Analyze data on your computer using aliroot\n\/\/mLocalSource: Analyze data on your computer using root + source files\n\nvoid mergeOutput(const Int_t nRuns=-1, TString type=\"\",Int_t mode=mLocal)\n{ \n \/\/ load needed libraries: \n LoadSpreadLibraries(mode); \n\n TString pwd(gSystem->pwd());\n \n \/\/ file mergers for the output file of each method separately: \n \/\/ MCEP: \n TFileMerger *mcepFileMerger = new TFileMerger();\n TString mergedFileNameMCEP(\"outputMCEPanalysis.root\");\n if(!(gSystem->AccessPathName(((pwd+=\"\/\")+=mergedFileNameMCEP).Data(),kFileExists)))\n {\n cout<<\"WARNING: You already have a merged output for MCEP !!!!\"<OutputFile(mergedFileNameMCEP);\n \n \/\/ SP: \n TFileMerger *spFileMerger = new TFileMerger();\n TString mergedFileNameSP(\"outputSPanalysis.root\");\n pwd=gSystem->pwd();\n if(!(gSystem->AccessPathName(((pwd+=\"\/\")+=mergedFileNameSP).Data(),kFileExists)))\n {\n cout<<\"WARNING: You already have a merged output for SP !!!!\"<OutputFile(mergedFileNameSP);\n\n \/\/ GFC: \n TFileMerger *gfcFileMerger = new TFileMerger();\n TString mergedFileNameGFC(\"outputGFCanalysis.root\");\n pwd=gSystem->pwd();\n if(!(gSystem->AccessPathName(((pwd+=\"\/\")+=mergedFileNameGFC).Data(),kFileExists)))\n {\n cout<<\"WARNING: You already have a merged output for GFC !!!!\"<OutputFile(mergedFileNameGFC);\n \n \/\/ QC: \n TFileMerger *qcFileMerger = new TFileMerger();\n TString mergedFileNameQC(\"outputQCanalysis.root\");\n pwd=gSystem->pwd();\n if(!(gSystem->AccessPathName(((pwd+=\"\/\")+=mergedFileNameQC).Data(),kFileExists)))\n {\n cout<<\"WARNING: You already have a merged output for QC !!!!\"<OutputFile(mergedFileNameQC);\n \n \/\/ FQD: \n TFileMerger *fqdFileMerger = new TFileMerger();\n TString mergedFileNameFQD(\"outputFQDanalysis.root\");\n pwd=gSystem->pwd();\n if(!(gSystem->AccessPathName(((pwd+=\"\/\")+=mergedFileNameFQD).Data(),kFileExists)))\n {\n cout<<\"WARNING: You already have a merged output for FQD !!!!\"<OutputFile(mergedFileNameFQD);\n \n \/\/ LYZ1: \n TFileMerger *lyz1FileMerger = new TFileMerger();\n TString mergedFileNameLYZ1(\"outputLYZ1analysis.root\");\n pwd=gSystem->pwd();\n if(!(gSystem->AccessPathName(((pwd+=\"\/\")+=mergedFileNameLYZ1).Data(),kFileExists)))\n {\n cout<<\"WARNING: You already have a merged output for LYZ1 !!!!\"<OutputFile(mergedFileNameLYZ1);\n \n \/\/ LYZ2: \n TFileMerger *lyz2FileMerger = new TFileMerger();\n TString mergedFileNameLYZ2(\"outputLYZ2analysis.root\");\n pwd=gSystem->pwd();\n if(!(gSystem->AccessPathName(((pwd+=\"\/\")+=mergedFileNameLYZ2).Data(),kFileExists)))\n {\n cout<<\"WARNING: You already have a merged output for LYZ2 !!!!\"<OutputFile(mergedFileNameLYZ2);\n \n \/\/ LYZEP: \n TFileMerger *lyzepFileMerger = new TFileMerger();\n TString mergedFileNameLYZEP(\"outputLYZEPanalysis.root\");\n pwd=gSystem->pwd();\n if(!(gSystem->AccessPathName(((pwd+=\"\/\")+=mergedFileNameLYZEP).Data(),kFileExists)))\n {\n cout<<\"WARNING: You already have a merged output for LYZEP !!!!\"<OutputFile(mergedFileNameLYZEP);\n \n \/\/ standard magic:\n TString execDir(gSystem->pwd()); \n TSystemDirectory* baseDir = new TSystemDirectory(\".\",execDir.Data()); \n TList* dirList = baseDir->GetListOfFiles();\n Int_t nDirs = dirList->GetEntries();\n gSystem->cd(execDir); \n\n Int_t counter = 0;\n \n for(Int_t iDir=0;iDirAt(iDir);\n if(!presentDir || !presentDir->IsDirectory() || strcmp(presentDir->GetName(), \".\") == 0 || \n strcmp(presentDir->GetName(), \"..\") == 0) continue; \n \n if(nRuns != -1)\n { \n if (counter >= nRuns) break; \n } \n \n TString presentDirName(gSystem->pwd()); \n presentDirName += \"\/\";\n presentDirName += presentDir->GetName();\n presentDirName += \"\/\";\n \n \/\/ accessing the output .root files from independent analysis for each method:\n \/\/ MCEP: \n TString fileNameMCEP = presentDirName; \n fileNameMCEP+=\"outputMCEPanalysis.root\";\n if(!(gSystem->AccessPathName(fileNameMCEP.Data(),kFileExists)))\n {\n mcepFileMerger->AddFile(fileNameMCEP.Data());\n } \n \/\/ SP: \n TString fileNameSP = presentDirName; \n fileNameSP+=\"outputSPanalysis.root\";\n if(!(gSystem->AccessPathName(fileNameSP.Data(),kFileExists)))\n {\n spFileMerger->AddFile(fileNameSP.Data());\n } \n \/\/ GFC: \n TString fileNameGFC = presentDirName; \n fileNameGFC+=\"outputGFCanalysis.root\";\n if(!(gSystem->AccessPathName(fileNameGFC.Data(),kFileExists)))\n { \n gfcFileMerger->AddFile(fileNameGFC.Data());\n } \n \/\/ QC: \n TString fileNameQC = presentDirName; \n fileNameQC+=\"outputQCanalysis.root\";\n if(!(gSystem->AccessPathName(fileNameQC.Data(),kFileExists)))\n { \n qcFileMerger->AddFile(fileNameQC.Data());\n } \n \/\/ FQD: \n TString fileNameFQD = presentDirName; \n fileNameFQD+=\"outputFQDanalysis.root\";\n if(!(gSystem->AccessPathName(fileNameFQD.Data(),kFileExists)))\n { \n fqdFileMerger->AddFile(fileNameFQD.Data());\n } \n \/\/ LYZ1: \n TString fileNameLYZ1 = presentDirName; \n fileNameLYZ1+=\"outputLYZ1analysis.root\";\n if(!(gSystem->AccessPathName(fileNameLYZ1.Data(),kFileExists)))\n { \n lyz1FileMerger->AddFile(fileNameLYZ1.Data());\n } \n \/\/ LYZ2: \n TString fileNameLYZ2 = presentDirName; \n fileNameLYZ2+=\"outputLYZ2analysis.root\";\n if(!(gSystem->AccessPathName(fileNameLYZ2.Data(),kFileExists)))\n { \n lyz2FileMerger->AddFile(fileNameLYZ2.Data());\n } \n \/\/ LYZEP: \n TString fileNameLYZEP = presentDirName; \n fileNameLYZEP+=\"outputLYZEPanalysis.root\";\n if(!(gSystem->AccessPathName(fileNameLYZEP.Data(),kFileExists)))\n { \n lyzepFileMerger->AddFile(fileNameLYZEP.Data());\n }\n \n counter++;\n \n } \/\/ end of for(Int_t iDir=0;iDirMerge();\n spFileMerger->Merge();\n gfcFileMerger->Merge();\n qcFileMerger->Merge();\n fqdFileMerger->Merge();\n lyz1FileMerger->Merge();\n lyz2FileMerger->Merge();\n lyzepFileMerger->Merge();\n}\n\n\nvoid LoadSpreadLibraries(const libModes mode) {\n \n \/\/--------------------------------------\n \/\/ Load the needed libraries most of them already loaded by aliroot\n \/\/--------------------------------------\n gSystem->Load(\"libTree.so\");\n gSystem->Load(\"libGeom.so\");\n gSystem->Load(\"libVMC.so\");\n gSystem->Load(\"libXMLIO.so\");\n gSystem->Load(\"libPhysics.so\");\n \n \/\/----------------------------------------------------------\n \/\/ >>>>>>>>>>> Local mode <<<<<<<<<<<<<< \n \/\/----------------------------------------------------------\n if (mode==mLocal) {\n \/\/--------------------------------------------------------\n \/\/ If you want to use already compiled libraries \n \/\/ in the aliroot distribution\n \/\/--------------------------------------------------------\n\n \/\/================================================================================== \n \/\/load needed libraries:\n gSystem->AddIncludePath(\"-I$ROOTSYS\/include\");\n gSystem->Load(\"libTree.so\");\n\n \/\/ for AliRoot\n gSystem->AddIncludePath(\"-I$ALICE_ROOT\/include\");\n gSystem->Load(\"libANALYSIS.so\");\n gSystem->Load(\"libPWG2flowCommon.so\");\n cerr<<\"libPWG2flowCommon.so loaded ...\"<LoadMacro(\"AliFlowCommon\/AliFlowCommonConstants.cxx+\");\n gROOT->LoadMacro(\"AliFlowCommon\/AliFlowLYZConstants.cxx+\");\n gROOT->LoadMacro(\"AliFlowCommon\/AliFlowCumuConstants.cxx+\");\n \n \/\/ Flow event\n gROOT->LoadMacro(\"AliFlowCommon\/AliFlowVector.cxx+\"); \n gROOT->LoadMacro(\"AliFlowCommon\/AliFlowTrackSimple.cxx+\"); \n gROOT->LoadMacro(\"AliFlowCommon\/AliFlowEventSimple.cxx+\");\n \n \/\/ Cuts\n gROOT->LoadMacro(\"AliFlowCommon\/AliFlowTrackSimpleCuts.cxx+\"); \n \n \/\/ Output histosgrams\n gROOT->LoadMacro(\"AliFlowCommon\/AliFlowCommonHist.cxx+\");\n gROOT->LoadMacro(\"AliFlowCommon\/AliFlowCommonHistResults.cxx+\");\n gROOT->LoadMacro(\"AliFlowCommon\/AliFlowLYZHist1.cxx+\");\n gROOT->LoadMacro(\"AliFlowCommon\/AliFlowLYZHist2.cxx+\");\n \n cout << \"finished loading macros!\" << endl; \n \n } \n \n}\n\n\n<|endoftext|>"} {"text":"\/\/ Copyright 2016-2020 Google LLC\n\/\/\n\/\/ Use of this source code is governed by an MIT-style\n\/\/ license that can be found in the LICENSE file or at\n\/\/ https:\/\/opensource.org\/licenses\/MIT.\n\n#include \"field.h\"\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \"proto2-descriptor-extensions.pb.h\"\n#include \"literals.h\"\n#include \"names.h\"\n\nnamespace google {\nnamespace protobuf {\nnamespace cl_protobufs {\n\nnamespace {\nconst std::string FieldLispType(const FieldDescriptor* field) {\n std::string type;\n if (field->options().HasExtension(lisp_type)) {\n type = field->options().GetExtension(lisp_type);\n } else {\n switch (field->type()) {\n case FieldDescriptor::TYPE_DOUBLE:\n type = \"cl:double-float\";\n break;\n case FieldDescriptor::TYPE_FLOAT:\n type = \"cl:float\";\n break;\n case FieldDescriptor::TYPE_INT64:\n type = \"proto:int64\";\n break;\n case FieldDescriptor::TYPE_UINT64:\n type = \"proto:uint64\";\n break;\n case FieldDescriptor::TYPE_INT32:\n type = \"proto:int32\";\n break;\n case FieldDescriptor::TYPE_FIXED64:\n type = \"proto:fixed64\";\n break;\n case FieldDescriptor::TYPE_FIXED32:\n type = \"proto:fixed32\";\n break;\n case FieldDescriptor::TYPE_BOOL:\n type = \"cl:boolean\";\n break;\n case FieldDescriptor::TYPE_STRING:\n type = \"cl:string\";\n break;\n case FieldDescriptor::TYPE_MESSAGE:\n type = QualifiedMessageLispName(field->message_type(), field->file());\n break;\n case FieldDescriptor::TYPE_BYTES:\n type = \"proto:byte-vector\";\n break;\n case FieldDescriptor::TYPE_UINT32:\n type = \"proto:uint32\";\n break;\n case FieldDescriptor::TYPE_ENUM:\n type = QualifiedEnumLispName(field->enum_type(), field->file());\n break;\n case FieldDescriptor::TYPE_SFIXED32:\n type = \"proto:sfixed32\";\n break;\n case FieldDescriptor::TYPE_SFIXED64:\n type = \"proto:sfixed64\";\n break;\n case FieldDescriptor::TYPE_SINT32:\n type = \"proto:sint32\";\n break;\n case FieldDescriptor::TYPE_SINT64:\n type = \"proto:sint64\";\n break;\n default:\n GOOGLE_LOG(FATAL) << \"Unsupported FileDescriptorType: \"\n << field->DebugString();\n break;\n }\n }\n\n if (field->type() == FieldDescriptor::TYPE_MESSAGE && !field->is_repeated())\n return StrCat(\"(cl:or cl:null \", type, \")\");\n if (field->is_required() || field->is_optional()) return type;\n if (field->is_repeated()) {\n if (field->options().HasExtension(lisp_container)) {\n switch (field->options().GetExtension(lisp_container)) {\n case LIST:\n return StrCat(\"(proto:list-of \", type, \")\");\n case VECTOR:\n return StrCat(\"(proto:vector-of \", type, \")\");\n }\n } else {\n return StrCat(\"(proto:list-of \", type, \")\");\n }\n }\n GOOGLE_LOG(FATAL) << \"Error determining field type: \" << field->DebugString();\n return \":error\";\n}\n\n\/\/ Return the \"arity\" of the field, i.e. whether it's required, optional, or\n\/\/ repeated, and if repeated the type of repeated.\nconst std::string FieldLispLabel(const FieldDescriptor* field) {\n switch (field->label()) {\n case FieldDescriptor::Label::LABEL_REQUIRED:\n return \"(:required)\";\n case FieldDescriptor::Label::LABEL_OPTIONAL:\n return \"(:optional)\";\n case FieldDescriptor::Label::LABEL_REPEATED:\n if (field->options().HasExtension(lisp_container)) {\n switch (field->options().GetExtension(lisp_container)) {\n case LIST:\n return \"(:repeated :list)\";\n case VECTOR:\n return \"(:repeated :vector)\";\n }\n } else {\n return \"(:repeated :list)\";\n }\n }\n\n GOOGLE_LOG(FATAL) << \"Error determining field arity: \" << field->DebugString();\n return \"(:error)\";\n}\n\nconst std::string FieldLispDefault(const FieldDescriptor* field) {\n switch (field->cpp_type()) {\n case FieldDescriptor::CPPTYPE_DOUBLE:\n return LispSimpleDtoa(field->default_value_double());\n case FieldDescriptor::CPPTYPE_FLOAT:\n return LispSimpleFtoa(field->default_value_float());\n case FieldDescriptor::CPPTYPE_BOOL:\n return LispBool(field->default_value_bool());\n case FieldDescriptor::CPPTYPE_ENUM: {\n const EnumValueDescriptor* value = field->default_value_enum();\n return StrCat(\":\", ToLispName(value->name()));\n }\n case FieldDescriptor::CPPTYPE_INT32:\n return StrCat(field->default_value_int32());\n case FieldDescriptor::CPPTYPE_UINT32:\n return StrCat(field->default_value_uint32());\n case FieldDescriptor::CPPTYPE_INT64:\n return StrCat(field->default_value_int64());\n case FieldDescriptor::CPPTYPE_UINT64:\n return StrCat(field->default_value_uint64());\n case FieldDescriptor::CPPTYPE_STRING: {\n switch (field->type()) {\n case FieldDescriptor::TYPE_BYTES:\n return StrCat(\n \"#.(cl:make-array \", field->default_value_string().size(),\n \" :element-type '(cl:unsigned-byte 8)\", \" :initial-contents '(\",\n StringOctets(field->default_value_string()), \"))\");\n case FieldDescriptor::TYPE_STRING:\n return LispEscapeString(field->default_value_string());\n default: break;\n }\n break;\n }\n default: break;\n }\n \/\/ Unsupported by cl_protobufs.\n \/\/ case FieldDescriptor::CPPTYPE_MESSAGE:\n \/\/ Report errors as early as possible.\n GOOGLE_LOG(FATAL) << \"Unsupported FileDescriptorType: \" << field->DebugString();\n return \"\";\n}\n\nconst std::string FieldTypeName(const FieldDescriptor* field) {\n switch (field->type()) {\n case FieldDescriptor::TYPE_ENUM:\n return (field->enum_type()->file() == field->file() &&\n (field->enum_type()->containing_type() ==\n field->containing_type() ||\n field->enum_type()->containing_type() ==\n field->containing_type()->containing_type())) ?\n field->enum_type()->name():\n field->enum_type()->full_name();\n case FieldDescriptor::TYPE_MESSAGE:\n return (field->message_type()->file() == field->file() &&\n (field->message_type()->containing_type() ==\n field->containing_type() ||\n field->message_type()->containing_type() ==\n field->containing_type()->containing_type())) ?\n field->message_type()->name():\n field->message_type()->full_name();\n default:\n return field->type_name();\n }\n}\n} \/\/ namespace\n\nconst std::string FieldLispName(const FieldDescriptor* field) {\n if (field->options().HasExtension(lisp_slot)) {\n return field->options().GetExtension(lisp_slot);\n } else {\n return ToLispName(field->name());\n }\n}\n\nvoid GenerateField(io::Printer* printer, const FieldDescriptor* field) {\n std::map vars;\n vars[\"name\"] = FieldLispName(field);\n vars[\"tag\"] = StrCat(field->number());\n vars[\"type\"] = FieldLispType(field);\n vars[\"label\"] = FieldLispLabel(field);\n vars[\"typename\"] = FieldTypeName(field);\n vars[\"packed\"] = field->options().packed() ? \" :packed cl:t\" : \"\";\n vars[\"lazy\"] = field->options().lazy() ? \" :lazy cl:t\" : \"\";\n vars[\"default\"] = field->has_default_value()\n ? StrCat(\" :default \", FieldLispDefault(field))\n : \"\";\n printer->Print(vars,\n \"\\n($name$ \"\n \" :index $tag$ \"\n \" :type $type$\"\n \" :label $label$\"\n \" :typename \\\"$typename$\\\"\"\n \"$default$\"\n \"$packed$\"\n \"$lazy$)\");\n printer->Annotate(\"name\", field);\n}\n\nvoid GenerateExtension(io::Printer* printer,\n const FieldDescriptor* extension,\n const FileDescriptor* file) {\n printer->Print(\n \"\\n(proto:define-extend $name$ ()\",\n \"name\", QualifiedMessageLispName(extension->containing_type(), file));\n printer->Indent();\n GenerateField(printer, extension);\n printer->Print(\")\");\n printer->Outdent();\n}\n\n} \/\/ namespace cl_protobufs\n} \/\/ namespace protobuf\n} \/\/ namespace google\nAdd protoc handling of map fields\/\/ Copyright 2016-2020 Google LLC\n\/\/\n\/\/ Use of this source code is governed by an MIT-style\n\/\/ license that can be found in the LICENSE file or at\n\/\/ https:\/\/opensource.org\/licenses\/MIT.\n\n#include \"field.h\"\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \"proto2-descriptor-extensions.pb.h\"\n#include \"literals.h\"\n#include \"names.h\"\n\nnamespace google {\nnamespace protobuf {\nnamespace cl_protobufs {\n\nnamespace {\nconst std::string FieldLispType(const FieldDescriptor* field) {\n std::string type;\n if (field->options().HasExtension(lisp_type)) {\n type = field->options().GetExtension(lisp_type);\n } else {\n switch (field->type()) {\n case FieldDescriptor::TYPE_DOUBLE:\n type = \"cl:double-float\";\n break;\n case FieldDescriptor::TYPE_FLOAT:\n type = \"cl:float\";\n break;\n case FieldDescriptor::TYPE_INT64:\n type = \"proto:int64\";\n break;\n case FieldDescriptor::TYPE_UINT64:\n type = \"proto:uint64\";\n break;\n case FieldDescriptor::TYPE_INT32:\n type = \"proto:int32\";\n break;\n case FieldDescriptor::TYPE_FIXED64:\n type = \"proto:fixed64\";\n break;\n case FieldDescriptor::TYPE_FIXED32:\n type = \"proto:fixed32\";\n break;\n case FieldDescriptor::TYPE_BOOL:\n type = \"cl:boolean\";\n break;\n case FieldDescriptor::TYPE_STRING:\n type = \"cl:string\";\n break;\n case FieldDescriptor::TYPE_MESSAGE:\n type = QualifiedMessageLispName(field->message_type(), field->file());\n break;\n case FieldDescriptor::TYPE_BYTES:\n type = \"proto:byte-vector\";\n break;\n case FieldDescriptor::TYPE_UINT32:\n type = \"proto:uint32\";\n break;\n case FieldDescriptor::TYPE_ENUM:\n type = QualifiedEnumLispName(field->enum_type(), field->file());\n break;\n case FieldDescriptor::TYPE_SFIXED32:\n type = \"proto:sfixed32\";\n break;\n case FieldDescriptor::TYPE_SFIXED64:\n type = \"proto:sfixed64\";\n break;\n case FieldDescriptor::TYPE_SINT32:\n type = \"proto:sint32\";\n break;\n case FieldDescriptor::TYPE_SINT64:\n type = \"proto:sint64\";\n break;\n default:\n GOOGLE_LOG(FATAL) << \"Unsupported FileDescriptorType: \"\n << field->DebugString();\n break;\n }\n }\n\n if (field->type() == FieldDescriptor::TYPE_MESSAGE && !field->is_repeated())\n return StrCat(\"(cl:or cl:null \", type, \")\");\n if (field->is_required() || field->is_optional()) return type;\n if (field->is_repeated()) {\n if (field->options().HasExtension(lisp_container)) {\n switch (field->options().GetExtension(lisp_container)) {\n case LIST:\n return StrCat(\"(proto:list-of \", type, \")\");\n case VECTOR:\n return StrCat(\"(proto:vector-of \", type, \")\");\n }\n } else {\n return StrCat(\"(proto:list-of \", type, \")\");\n }\n }\n GOOGLE_LOG(FATAL) << \"Error determining field type: \" << field->DebugString();\n return \":error\";\n}\n\n\/\/ Return the \"arity\" of the field, i.e. whether it's required, optional, or\n\/\/ repeated, and if repeated the type of repeated.\nconst std::string FieldLispLabel(const FieldDescriptor* field) {\n switch (field->label()) {\n case FieldDescriptor::Label::LABEL_REQUIRED:\n return \"(:required)\";\n case FieldDescriptor::Label::LABEL_OPTIONAL:\n return \"(:optional)\";\n case FieldDescriptor::Label::LABEL_REPEATED:\n if (field->options().HasExtension(lisp_container)) {\n switch (field->options().GetExtension(lisp_container)) {\n case LIST:\n return \"(:repeated :list)\";\n case VECTOR:\n return \"(:repeated :vector)\";\n }\n } else {\n return \"(:repeated :list)\";\n }\n }\n\n GOOGLE_LOG(FATAL) << \"Error determining field arity: \" << field->DebugString();\n return \"(:error)\";\n}\n\nconst std::string FieldLispDefault(const FieldDescriptor* field) {\n switch (field->cpp_type()) {\n case FieldDescriptor::CPPTYPE_DOUBLE:\n return LispSimpleDtoa(field->default_value_double());\n case FieldDescriptor::CPPTYPE_FLOAT:\n return LispSimpleFtoa(field->default_value_float());\n case FieldDescriptor::CPPTYPE_BOOL:\n return LispBool(field->default_value_bool());\n case FieldDescriptor::CPPTYPE_ENUM: {\n const EnumValueDescriptor* value = field->default_value_enum();\n return StrCat(\":\", ToLispName(value->name()));\n }\n case FieldDescriptor::CPPTYPE_INT32:\n return StrCat(field->default_value_int32());\n case FieldDescriptor::CPPTYPE_UINT32:\n return StrCat(field->default_value_uint32());\n case FieldDescriptor::CPPTYPE_INT64:\n return StrCat(field->default_value_int64());\n case FieldDescriptor::CPPTYPE_UINT64:\n return StrCat(field->default_value_uint64());\n case FieldDescriptor::CPPTYPE_STRING: {\n switch (field->type()) {\n case FieldDescriptor::TYPE_BYTES:\n return StrCat(\n \"#.(cl:make-array \", field->default_value_string().size(),\n \" :element-type '(cl:unsigned-byte 8)\", \" :initial-contents '(\",\n StringOctets(field->default_value_string()), \"))\");\n case FieldDescriptor::TYPE_STRING:\n return LispEscapeString(field->default_value_string());\n default: break;\n }\n break;\n }\n default: break;\n }\n \/\/ Unsupported by cl_protobufs.\n \/\/ case FieldDescriptor::CPPTYPE_MESSAGE:\n \/\/ Report errors as early as possible.\n GOOGLE_LOG(FATAL) << \"Unsupported FileDescriptorType: \" << field->DebugString();\n return \"\";\n}\n\nconst std::string FieldTypeName(const FieldDescriptor* field) {\n switch (field->type()) {\n case FieldDescriptor::TYPE_ENUM:\n return (field->enum_type()->file() == field->file() &&\n (field->enum_type()->containing_type() ==\n field->containing_type() ||\n field->enum_type()->containing_type() ==\n field->containing_type()->containing_type())) ?\n field->enum_type()->name():\n field->enum_type()->full_name();\n case FieldDescriptor::TYPE_MESSAGE:\n return (field->message_type()->file() == field->file() &&\n (field->message_type()->containing_type() ==\n field->containing_type() ||\n field->message_type()->containing_type() ==\n field->containing_type()->containing_type())) ?\n field->message_type()->name():\n field->message_type()->full_name();\n default:\n return field->type_name();\n }\n}\n} \/\/ namespace\n\nconst std::string FieldLispName(const FieldDescriptor* field) {\n if (field->options().HasExtension(lisp_slot)) {\n return field->options().GetExtension(lisp_slot);\n } else {\n return ToLispName(field->name());\n }\n}\n\nvoid GenerateField(io::Printer* printer, const FieldDescriptor* field) {\n std::map vars;\n vars[\"name\"] = FieldLispName(field);\n vars[\"tag\"] = StrCat(field->number());\n if(field->is_map()) {\n vars[\"type\"] = QualifiedMessageLispName(field->message_type(), field->file());\n printer->Print(vars,\n \"\\n(proto:define-map $name$\\n\"\n \" (:map-desc $type$\\n\"\n \" :index $tag$))\");\n } else {\n vars[\"type\"] = FieldLispType(field);\n vars[\"label\"] = FieldLispLabel(field);\n vars[\"typename\"] = FieldTypeName(field);\n vars[\"packed\"] = field->options().packed() ? \" :packed cl:t\" : \"\";\n vars[\"lazy\"] = field->options().lazy() ? \" :lazy cl:t\" : \"\";\n vars[\"default\"] = field->has_default_value()\n ? StrCat(\" :default \", FieldLispDefault(field))\n : \"\";\n printer->Print(vars,\n \"\\n($name$ \"\n \" :index $tag$ \"\n \" :type $type$\"\n \" :label $label$\"\n \" :typename \\\"$typename$\\\"\"\n \"$default$\"\n \"$packed$\"\n \"$lazy$)\");\n }\n printer->Annotate(\"name\", field);\n}\n\nvoid GenerateExtension(io::Printer* printer,\n const FieldDescriptor* extension,\n const FileDescriptor* file) {\n printer->Print(\n \"\\n(proto:define-extend $name$ ()\",\n \"name\", QualifiedMessageLispName(extension->containing_type(), file));\n printer->Indent();\n GenerateField(printer, extension);\n printer->Print(\")\");\n printer->Outdent();\n}\n\n} \/\/ namespace cl_protobufs\n} \/\/ namespace protobuf\n} \/\/ namespace google\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: mmoutputtypepage.cxx,v $\n *\n * $Revision: 1.8 $\n *\n * last change: $Author: kz $ $Date: 2007-09-06 14:06:48 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sw.hxx\"\n\n#ifdef SW_DLLIMPLEMENTATION\n#undef SW_DLLIMPLEMENTATION\n#endif\n\n\n#ifndef _MAILMERGEOUTPUTTYPEPAGE_HXX\n#include \n#endif\n#ifndef _MAILMERGEWIZARD_HXX\n#include \n#endif\n#ifndef _MMCONFIGITEM_HXX\n#include \n#endif\n#ifndef _SV_MSGBOX_HXX\n#include \n#endif\n#ifndef _DBUI_HRC\n#include \n#endif\n#ifndef _SWTYPES_HXX\n#include \n#endif\n#include \n#include \n\n\/*-- 02.04.2004 11:06:55---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nSwMailMergeOutputTypePage::SwMailMergeOutputTypePage( SwMailMergeWizard* _pParent) :\n svt::OWizardPage( _pParent, SW_RES(DLG_MM_OUTPUTTYPE_PAGE)),\n#ifdef _MSC_VER\n#pragma warning (disable : 4355)\n#endif\n m_aHeaderFI( this, SW_RES( FI_HEADER )),\n m_aTypeFT( this, SW_RES( FT_TYPE )),\n m_aLetterRB( this, SW_RES( RB_LETTER )),\n m_aMailRB( this, SW_RES( RB_MAIL )),\n m_aHintHeaderFI(this, SW_RES( FI_HINTHEADER)),\n m_aHintFI( this, SW_RES( FI_HINT)),\n m_aNoMailHintFI(this, SW_RES( FT_NOMAILHINT)),\n#ifdef _MSC_VER\n#pragma warning (default : 4355)\n#endif\n m_pWizard(_pParent),\n m_sLetterHintHeader( SW_RES( ST_LETTERHINTHEADER)),\n m_sMailHintHeader( SW_RES( ST_MAILHINTHEADER)),\n m_sLetterHint( SW_RES( ST_LETTERHINT)),\n m_sMailHint( SW_RES( ST_MAILHINT))\n{\n FreeResource();\n Link aLink = LINK(this, SwMailMergeOutputTypePage, TypeHdl_Impl);\n m_aLetterRB.SetClickHdl(aLink);\n m_aMailRB.SetClickHdl(aLink);\n\n SwMailMergeConfigItem& rConfigItem = m_pWizard->GetConfigItem();\n m_pWizard->EnterWait();\n bool bMailAvailable = rConfigItem.IsMailAvailable();\n m_pWizard->LeaveWait();\n if(rConfigItem.IsOutputToLetter())\n m_aLetterRB.Check();\n else\n m_aMailRB.Check();\n if(!bMailAvailable)\n {\n m_aNoMailHintFI.Show();\n m_aMailRB.Enable(sal_False);\n m_aLetterRB.Check();\n }\n TypeHdl_Impl(&m_aLetterRB);\n\n}\n\/*-- 02.04.2004 11:06:55---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nSwMailMergeOutputTypePage::~SwMailMergeOutputTypePage()\n{\n}\n\/*-- 14.04.2004 14:44:07---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nIMPL_LINK( SwMailMergeOutputTypePage, TypeHdl_Impl, RadioButton*, EMPTYARG )\n{\n bool bLetter = m_aLetterRB.IsChecked();\n m_aHintHeaderFI.SetText(bLetter ? m_sLetterHintHeader : m_sMailHintHeader);\n m_aHintFI.SetText(bLetter ? m_sLetterHint : m_sMailHint);\n m_pWizard->GetConfigItem().SetOutputToLetter(bLetter);\n m_pWizard->updateRoadmapItemLabel( MM_ADDRESSBLOCKPAGE );\n m_pWizard->UpdateRoadmap();\n return 0;\n}\n\n\nINTEGRATION: CWS swwarnings (1.6.222); FILE MERGED 2007\/05\/29 12:19:23 os 1.6.222.2: RESYNC: (1.6-1.7); FILE MERGED 2007\/02\/26 15:59:13 os 1.6.222.1: #i69287# warnings removed\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: mmoutputtypepage.cxx,v $\n *\n * $Revision: 1.9 $\n *\n * last change: $Author: hr $ $Date: 2007-09-27 11:35:12 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sw.hxx\"\n\n#ifdef SW_DLLIMPLEMENTATION\n#undef SW_DLLIMPLEMENTATION\n#endif\n\n\n#ifndef _MAILMERGEOUTPUTTYPEPAGE_HXX\n#include \n#endif\n#ifndef _MAILMERGEWIZARD_HXX\n#include \n#endif\n#ifndef _MMCONFIGITEM_HXX\n#include \n#endif\n#ifndef _SV_MSGBOX_HXX\n#include \n#endif\n#ifndef _DBUI_HRC\n#include \n#endif\n#ifndef _SWTYPES_HXX\n#include \n#endif\n#include \n#include \n\n\/*-- 02.04.2004 11:06:55---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nSwMailMergeOutputTypePage::SwMailMergeOutputTypePage( SwMailMergeWizard* _pParent) :\n svt::OWizardPage( _pParent, SW_RES(DLG_MM_OUTPUTTYPE_PAGE)),\n#ifdef MSC\n#pragma warning (disable : 4355)\n#endif\n m_aHeaderFI( this, SW_RES( FI_HEADER )),\n m_aTypeFT( this, SW_RES( FT_TYPE )),\n m_aLetterRB( this, SW_RES( RB_LETTER )),\n m_aMailRB( this, SW_RES( RB_MAIL )),\n m_aHintHeaderFI(this, SW_RES( FI_HINTHEADER)),\n m_aHintFI( this, SW_RES( FI_HINT)),\n m_aNoMailHintFI(this, SW_RES( FT_NOMAILHINT)),\n#ifdef MSC\n#pragma warning (default : 4355)\n#endif\n m_sLetterHintHeader( SW_RES( ST_LETTERHINTHEADER)),\n m_sMailHintHeader( SW_RES( ST_MAILHINTHEADER)),\n m_sLetterHint( SW_RES( ST_LETTERHINT)),\n m_sMailHint( SW_RES( ST_MAILHINT)),\n m_pWizard(_pParent)\n{\n FreeResource();\n Link aLink = LINK(this, SwMailMergeOutputTypePage, TypeHdl_Impl);\n m_aLetterRB.SetClickHdl(aLink);\n m_aMailRB.SetClickHdl(aLink);\n\n SwMailMergeConfigItem& rConfigItem = m_pWizard->GetConfigItem();\n m_pWizard->EnterWait();\n bool bMailAvailable = rConfigItem.IsMailAvailable();\n m_pWizard->LeaveWait();\n if(rConfigItem.IsOutputToLetter())\n m_aLetterRB.Check();\n else\n m_aMailRB.Check();\n if(!bMailAvailable)\n {\n m_aNoMailHintFI.Show();\n m_aMailRB.Enable(sal_False);\n m_aLetterRB.Check();\n }\n TypeHdl_Impl(&m_aLetterRB);\n\n}\n\/*-- 02.04.2004 11:06:55---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nSwMailMergeOutputTypePage::~SwMailMergeOutputTypePage()\n{\n}\n\/*-- 14.04.2004 14:44:07---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nIMPL_LINK( SwMailMergeOutputTypePage, TypeHdl_Impl, RadioButton*, EMPTYARG )\n{\n bool bLetter = m_aLetterRB.IsChecked();\n m_aHintHeaderFI.SetText(bLetter ? m_sLetterHintHeader : m_sMailHintHeader);\n m_aHintFI.SetText(bLetter ? m_sLetterHint : m_sMailHint);\n m_pWizard->GetConfigItem().SetOutputToLetter(bLetter);\n m_pWizard->updateRoadmapItemLabel( MM_ADDRESSBLOCKPAGE );\n m_pWizard->UpdateRoadmap();\n return 0;\n}\n\n\n<|endoftext|>"} {"text":"#include \n#include \n#include \n\n#include \"rotater.h\"\n\nusing namespace qReal::interpreters::robots;\nusing namespace details::d2Model;\nusing namespace graphicsUtils;\n\nRotater::Rotater() : AbstractItem()\n{\n\tsetFlags(ItemIsSelectable | ItemIsMovable);\n\n\tsetAcceptHoverEvents(true);\n\tsetAcceptDrops(true);\n\tsetCursor(QCursor(Qt::PointingHandCursor));\n\tsetZValue(2);\n\n\tmPen.setColor(Qt::blue);\n\tmPen.setWidth(3);\n\tmBrush.setStyle(Qt::NoBrush);\n}\n\nvoid Rotater::setMasterItem(RotateItem *masterItem)\n{\n\tmMaster = masterItem;\n\n\tmLength = 30; \/\/mMaster->horizontalRadius();\/\/asd\n\tmDrift = drift > mMaster->horizontalRadius() ? drift \/ 2 : drift;\n\tmResizeDrift = drift > mMaster->horizontalRadius() ? resizeDrift \/ 2 : resizeDrift;\n\n\tQRectF const rect = mMaster->rect();\n\n\tmMaster->setFlag(ItemClipsToShape, false);\n\tsetParentItem(mMaster);\n\n\t\/\/ TODO: Dispose of hardcoding\n\tmX1 = rect.right();\n\t\/\/ Placing rotater into the center of item`s rigth side\n\tmY1 = rect.y() + rect.height() \/ 2;\n\tmX2 = mX1 + mLength;\n\tmY2 = mY1;\n}\n\nvoid Rotater::drawItem(QPainter *painter, const QStyleOptionGraphicsItem *style, QWidget *widget)\n{\n\tQ_UNUSED(style)\n\tQ_UNUSED(widget)\n\n\tpainter->setOpacity(0.5);\n\tconst int addLength = mLength \/ 3;\n\tqreal const angle = addAngle;\n\t\/\/ Must be equal to mLength\n\tqreal const checkLength = sqrt((mX2 - mX1) * (mX2 - mX1) + (mY2 - mY1) * (mY2 - mY1));\n\tqreal const x0 = ((checkLength - addLength) * mX2 + addLength * mX1) \/ checkLength;\n\tqreal const y0 = ((checkLength - addLength) * mY2 + addLength * mY1) \/ checkLength;\n\tQPointF const first = QTransform().translate(mX2 - x0, mY2 - y0).rotate(- angle).translate(- mX2 + x0, - mY2 + y0).rotate(angle).map(QPointF(x0, y0));\n\tQPointF const second = QTransform().translate(mX2 - x0, mY2 - y0).rotate(angle).translate(- mX2 + x0, - mY2 + y0).rotate(- angle).map(QPointF(x0, y0));\n\n\tmLineImpl.drawItem(painter, mX1, mY1, mX2, mY2);\n\tmLineImpl.drawItem(painter, mX2, mY2, first.x(), first.y());\n\tmLineImpl.drawItem(painter, mX2, mY2, second.x(), second.y());\n}\n\nvoid Rotater::setPenBrushForExtraxtion(QPainter* painter, const QStyleOptionGraphicsItem* option)\n{\n\tQ_UNUSED(option)\n\tQPen pen(Qt::red);\n\tpen.setWidth(2);\n\tpainter->setPen(pen);\n}\n\nvoid Rotater::drawExtractionForItem(QPainter* painter)\n{\n\tmLineImpl.drawExtractionForItem(painter, mX1, mY1, mX2, mY2, mDrift);\n\tdrawFieldForResizeItem(painter);\n}\n\nvoid Rotater::drawFieldForResizeItem(QPainter* painter)\n{\n\tpainter->drawEllipse(QPointF(mX2, mY2), mResizeDrift, mResizeDrift);\n}\n\nQRectF Rotater::boundingRect() const\n{\n\treturn mLineImpl.boundingRect(mX1, mY1, mX2, mY2, mPen.width(), drift);\n}\n\n\/\/qreal Rotater::distance(qreal x1, qreal y1, qreal x2, qreal y2) const\n\/\/{\n\/\/\treturn sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));\n\/\/}\n\n\/\/qreal Rotater::distance(QPointF const &p1, QPointF const &p2) const\n\/\/{\n\/\/\treturn distance(p1.x(), p1.y(), p2.x(), p2.y());\n\/\/}\n\nvoid Rotater::calcResizeItem(QGraphicsSceneMouseEvent *event)\n{\n\t\/\/ Cosine theorem\n\tqreal const x1 = event->pos().x() - mX1 \/ 2;\n\tqreal const y1 = event->pos().y() - mY1 \/ 2;\n\tqreal const x2 = event->lastPos().x() - mX1 \/ 2;\n\tqreal const y2 = event->lastPos().y() - mY1 \/ 2;\n\tqreal const len = sqrt((x1 * x1 + y1 * y1) * (x2 * x2 + y2 * y2));\n\n\t\/\/ Rotation sign is the sign of the vector product\n\tqreal const vectorProduct = x1 * y2 - x2 * y1;\n\tint const sign = vectorProduct < 0 ? -1 : 1;\n\n\tqreal const eps = 10e-8;\n\tqreal const dalpha = len < eps ? 0 : acos((x1 * x2 + y1 * y2) \/ len);\n\tmMaster->rotate(mMaster->rotation() - sign * dalpha * 180 \/ M_PI);\n}\n\nvoid Rotater::resizeItem(QGraphicsSceneMouseEvent *event)\n{\n\tif (mDragState == BottomRight) {\n\t\tsetFlag(ItemIsMovable, false);\n\t\tAbstractItem::resizeItem(event);\n\t}\n}\n\nvoid Rotater::mousePressEvent(QGraphicsSceneMouseEvent * event)\n{\n\tAbstractItem::mousePressEvent(event);\n\tmMaster->setSelected(true);\n}\n\nvoid Rotater::mouseMoveEvent(QGraphicsSceneMouseEvent * event)\n{\n\tAbstractItem::mouseMoveEvent(event);\n\tmMaster->setSelected(true);\n}\n\nvoid Rotater::mouseReleaseEvent(QGraphicsSceneMouseEvent * event)\n{\n\tAbstractItem::mouseReleaseEvent(event);\n}\nNow rotaters are ok#include \n#include \n#include \n\n#include \"rotater.h\"\n\nusing namespace qReal::interpreters::robots;\nusing namespace details::d2Model;\nusing namespace graphicsUtils;\n\nRotater::Rotater() : AbstractItem()\n{\n\tsetFlags(ItemIsSelectable | ItemIsMovable);\n\n\tsetAcceptHoverEvents(true);\n\tsetAcceptDrops(true);\n\tsetCursor(QCursor(Qt::PointingHandCursor));\n\tsetZValue(2);\n\n\tmPen.setColor(Qt::blue);\n\tmPen.setWidth(3);\n\tmBrush.setStyle(Qt::NoBrush);\n}\n\nvoid Rotater::setMasterItem(RotateItem *masterItem)\n{\n\tmMaster = masterItem;\n\n\tmLength = 30; \/\/mMaster->horizontalRadius();\/\/asd\n\tmDrift = drift > mMaster->horizontalRadius() ? drift \/ 2 : drift;\n\tmResizeDrift = drift > mMaster->horizontalRadius() ? resizeDrift \/ 2 : resizeDrift;\n\n\tQRectF const rect = mMaster->rect();\n\n\tmMaster->setFlag(ItemClipsToShape, false);\n\tsetParentItem(mMaster);\n\n\t\/\/ TODO: Dispose of hardcoding\n\tmX1 = rect.right();\n\t\/\/ Placing rotater into the center of item`s rigth side\n\tmY1 = rect.y() + rect.height() \/ 2;\n\tmX2 = mX1 + mLength;\n\tmY2 = mY1;\n}\n\nvoid Rotater::drawItem(QPainter *painter, const QStyleOptionGraphicsItem *style, QWidget *widget)\n{\n\tQ_UNUSED(style)\n\tQ_UNUSED(widget)\n\n\tpainter->setOpacity(0.5);\n\tconst int addLength = mLength \/ 3;\n\tqreal const angle = addAngle;\n\t\/\/ Must be equal to mLength\n\tqreal const checkLength = sqrt((mX2 - mX1) * (mX2 - mX1) + (mY2 - mY1) * (mY2 - mY1));\n\tqreal const x0 = ((checkLength - addLength) * mX2 + addLength * mX1) \/ checkLength;\n\tqreal const y0 = ((checkLength - addLength) * mY2 + addLength * mY1) \/ checkLength;\n\tQPointF const first = QTransform().translate(mX2 - x0, mY2 - y0).rotate(- angle).translate(- mX2 + x0, - mY2 + y0).rotate(angle).map(QPointF(x0, y0));\n\tQPointF const second = QTransform().translate(mX2 - x0, mY2 - y0).rotate(angle).translate(- mX2 + x0, - mY2 + y0).rotate(- angle).map(QPointF(x0, y0));\n\n\tmLineImpl.drawItem(painter, mX1, mY1, mX2, mY2);\n\tmLineImpl.drawItem(painter, mX2, mY2, first.x(), first.y());\n\tmLineImpl.drawItem(painter, mX2, mY2, second.x(), second.y());\n}\n\nvoid Rotater::setPenBrushForExtraxtion(QPainter* painter, const QStyleOptionGraphicsItem* option)\n{\n\tQ_UNUSED(option)\n\tQPen pen(Qt::red);\n\tpen.setWidth(2);\n\tpainter->setPen(pen);\n}\n\nvoid Rotater::drawExtractionForItem(QPainter* painter)\n{\n\tmLineImpl.drawExtractionForItem(painter, mX1, mY1, mX2, mY2, mDrift);\n\tdrawFieldForResizeItem(painter);\n}\n\nvoid Rotater::drawFieldForResizeItem(QPainter* painter)\n{\n\tpainter->drawEllipse(QPointF(mX2, mY2), mResizeDrift, mResizeDrift);\n}\n\nQRectF Rotater::boundingRect() const\n{\n\treturn mLineImpl.boundingRect(mX1, mY1, mX2, mY2, mPen.width(), drift);\n}\n\nvoid Rotater::calcResizeItem(QGraphicsSceneMouseEvent *event)\n{\n\tqreal const eps = 0.000000001;\n\tQPointF const masterCenter(mMaster->mapToScene(mMaster->rect().center()));\n\tQPointF const zeroRotationVector(mLength, 0);\n\n\tqreal const mouseX = event->scenePos().x() - masterCenter.x();\n\tqreal const mouseY = event->scenePos().y() - masterCenter.y();\n\n\t\/\/ Master rotation is signed angle between initial and mouse vector.\n\t\/\/ Calculating it from theese vectors product and cosine theorem\n\tqreal const vectorProduct = zeroRotationVector.x() * mouseY\n\t\t\t- zeroRotationVector.y() * mouseX;\n\tqreal const mouseVectorLength = sqrt(mouseX * mouseX + mouseY * mouseY);\n\tif (mouseVectorLength < eps) {\n\t\treturn;\n\t}\n\n\tqreal const translationX = mouseX - zeroRotationVector.x();\n\tqreal const translationY = mouseY - zeroRotationVector.y();\n\tqreal const translation = translationX * translationX + translationY * translationY;\n\n\tqreal const sin = vectorProduct \/ (mouseVectorLength * mLength);\n\tbool const cosIsNegative = mouseVectorLength * mouseVectorLength + mLength * mLength < translation;\n\n\tqreal const angleInWrongQuarter = asin(sin);\n\tqreal const angle = cosIsNegative ? M_PI - angleInWrongQuarter : angleInWrongQuarter;\n\n\tmMaster->rotate(angle * 180 \/ M_PI);\n}\n\nvoid Rotater::resizeItem(QGraphicsSceneMouseEvent *event)\n{\n\tif (mDragState == BottomRight) {\n\t\tsetFlag(ItemIsMovable, false);\n\t\tAbstractItem::resizeItem(event);\n\t}\n}\n\nvoid Rotater::mousePressEvent(QGraphicsSceneMouseEvent * event)\n{\n\tAbstractItem::mousePressEvent(event);\n\tmMaster->setSelected(true);\n}\n\nvoid Rotater::mouseMoveEvent(QGraphicsSceneMouseEvent * event)\n{\n\tAbstractItem::mouseMoveEvent(event);\n\tmMaster->setSelected(true);\n}\n\nvoid Rotater::mouseReleaseEvent(QGraphicsSceneMouseEvent * event)\n{\n\tAbstractItem::mouseReleaseEvent(event);\n}\n<|endoftext|>"} {"text":"Fix Typo<|endoftext|>"} {"text":"#include \"physics\/transforms.hpp\"\n\n#include \n\n#include \"gmock\/gmock.h\"\n#include \"gtest\/gtest.h\"\n#include \"physics\/degrees_of_freedom.hpp\"\n#include \"physics\/frame.hpp\"\n#include \"physics\/massive_body.hpp\"\n#include \"physics\/massless_body.hpp\"\n#include \"quantities\/named_quantities.hpp\"\n#include \"quantities\/quantities.hpp\"\n#include \"testing_utilities\/almost_equals.hpp\"\n#include \"testing_utilities\/numerics.hpp\"\n\nusing principia::quantities::Length;\nusing principia::quantities::Mass;\nusing principia::quantities::SIUnit;\nusing principia::quantities::Speed;\nusing principia::quantities::Time;\nusing principia::testing_utilities::AbsoluteError;\nusing principia::testing_utilities::AlmostEquals;\nusing testing::Eq;\nusing testing::Lt;\n\nnamespace principia {\nnamespace physics {\n\nnamespace {\nconst int kNumberOfPoints = 20;\n} \/\/ namespace\n\nclass TransformsTest : public testing::Test {\n protected:\n enum class Tag {\n kFrom,\n kThrough,\n kTo,\n };\n using From = Frame;\n using Through = Frame;\n using To = Frame;\n\n void SetUp() override {\n body1_ = std::make_unique(1 * SIUnit());\n body2_ = std::make_unique(3 * SIUnit());\n satellite_from_ = std::make_unique>(satellite_);\n body1_from_ = std::make_unique>(*body1_);\n body2_from_ = std::make_unique>(*body2_);\n body1_to_ = std::make_unique>(*body1_);\n body2_to_ = std::make_unique>(*body2_);\n\n \/\/ The various bodies move have both a position and a velocity that\n \/\/ increases linearly with time. This is not a situation that's physically\n \/\/ possible, but we don't care, all we want is to make sure that the\n \/\/ transforms are properly performed: |Transforms| doesn't know anything\n \/\/ about physics. Also, the trajectories were chosen so that we are not in\n \/\/ any \"special case\" with respect to the positions or the velocities.\n for (int i = 1; i <= kNumberOfPoints; ++i) {\n body1_from_->Append(\n Instant(i * SIUnit