<commit_before>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit (ITK)
  Module:
  Language:  C++
  Date:
  Version:

Copyright (c) 2000 National Library of Medicine
All rights reserved.

See COPYRIGHT.txt for copyright details.

=========================================================================*/
#include <iostream>
// This file has been generated by BuildHeaderTest.tcl
// Test to include each header file for Insight

#include "itkAcosImageAdaptor.h"
#include "itkAffineRegistrationTransform.h"
#include "itkAffineTransform.h"
#include "itkAffineTransformation.h"
#include "itkArray.h"
#include "itkAsinImageAdaptor.h"
#include "itkAtanImageAdaptor.h"
#include "itkBackwardDifferenceOperator.h"
#include "itkBlueDataAccessor.h"
#include "itkBoundingBox.h"
#include "itkByteSwapper.h"
#include "itkCellBoundary.h"
#include "itkCellInterface.h"
#include "itkCellInterfaceVisitor.h"
#include "itkCentralDerivativeImageFunction.h"
#include "itkColorTable.h"
#include "itkCommand.h"
#include "itkConceptChecking.h"
#include "itkConstSliceIterator.h"
#include "itkConstantBoundaryCondition.h"
#include "itkContinuousImageFunction.h"
#include "itkContinuousIndex.h"
#include "itkCosImageAdaptor.h"
#include "itkCovariantVector.h"
#include "itkCreateObjectFunction.h"
#include "itkDataAccessor.h"
#include "itkDataObject.h"
#include "itkDefaultDataAccessor.h"
#include "itkDefaultDynamicMeshTraits.h"
#include "itkDefaultImageTraits.h"
#include "itkDefaultStaticMeshTraits.h"
#include "itkDerivativeOperator.h"
#include "itkDirectory.h"
#include "itkDynamicLoader.h"
#include "itkElasticBodySplineKernelTransform.h"
#include "itkEntropyPreservingGradientMagnitudeImageFunction.h"
#include "itkExceptionObject.h"
#include "itkExpImageAdaptor.h"
#include "itkFastMutexLock.h"
#include "itkForwardDifferenceOperator.h"
#include "itkGaussianOperator.h"
#include "itkGreenDataAccessor.h"
#include "itkHexahedronCell.h"
#include "itkImage.h"
#include "itkImageAdaptor.h"
#include "itkImageBase.h"
#include "itkImageBoundaryCondition.h"
#include "itkImageBufferIterator.h"
#include "itkImageConstIteratorWithIndex.h"
#include "itkImageContainerInterface.h"
#include "itkImageFunction.h"
#include "itkImageIO.h"
#include "itkImageIOCommon.h"
#include "itkImageIterator.h"
#include "itkImageIteratorWithIndex.h"
#include "itkImageLinearConstIterator.h"
#include "itkImageLinearIterator.h"
#include "itkImageRegion.h"
#include "itkImageRegionIterator.h"
#include "itkImageSliceConstIterator.h"
#include "itkImageSliceIterator.h"
#include "itkImageSource.h"
#include "itkImageToImageFilter.h"
#include "itkImportImageContainer.h"
#include "itkIndent.h"
#include "itkIndex.h"
#include "itkIndexedContainerInterface.h"
#include "itkIntTypes.h"
#include "itkKernelTransform.h"
#include "itkLevelSetCurvatureFunction.h"
#include "itkLightObject.h"
#include "itkLightProcessObject.h"
#include "itkLineCell.h"
#include "itkLinearInterpolateImageFunction.h"
#include "itkLog10ImageAdaptor.h"
#include "itkLogImageAdaptor.h"
#include "itkMacro.h"
#include "itkMapContainer.h"
#include "itkMatrix.h"
#include "itkMesh.h"
#include "itkMeshRegion.h"
#include "itkMultiThreader.h"
#include "itkMutexLock.h"
#include "itkNeighborhood.h"
#include "itkNeighborhoodAlgorithm.h"
#include "itkNeighborhoodAllocator.h"
#include "itkNeighborhoodIterator.h"
#include "itkNeighborhoodOperator.h"
#include "itkNthElementDataAccessor.h"
#include "itkNthElementImageAdaptor.h"
#include "itkNumericTraits.h"
#include "itkObject.h"
#include "itkObjectFactory.h"
#include "itkObjectFactoryBase.h"
#include "itkOffset.h"
#include "itkOutputWindow.h"
#include "itkPhysicalImage.h"
#include "itkPhysicalImageAdaptor.h"
#include "itkPixelTraits.h"
#include "itkPoint.h"
#include "itkPointLocator.h"
#include "itkPointSet.h"
#include "itkProcessObject.h"
#include "itkQuadrilateralCell.h"
#include "itkRGBPixel.h"
#include "itkRandomAccessNeighborhoodIterator.h"
#include "itkRedDataAccessor.h"
#include "itkRegion.h"
#include "itkRegionBoundaryNeighborhoodIterator.h"
#include "itkRegionNeighborhoodIterator.h"
#include "itkRegionNonBoundaryNeighborhoodIterator.h"
#include "itkRigid3DRegistrationTransform.h"
#include "itkRigid3DTransform.h"
#include "itkScalar.h"
#include "itkScalarImageRegionIterator.h"
#include "itkScalarVector.h"
#include "itkSimpleImageRegionConstIterator.h"
#include "itkSimpleImageRegionIterator.h"
#include "itkSinImageAdaptor.h"
#include "itkSize.h"
#include "itkSliceIterator.h"
#include "itkSmartPointer.h"
#include "itkSmartPointerForwardReference.h"
#include "itkSmartRegionNeighborhoodIterator.h"
#include "itkSqrtImageAdaptor.h"
#include "itkStatDenseHistogram.h"
#include "itkStatHistogram.h"
#include "itkStatSparseHistogram.h"
#include "itkTanImageAdaptor.h"
#include "itkTetrahedronCell.h"
#include "itkThinPlateSplineKernelTransform.h"
#include "itkTimeStamp.h"
#include "itkTransformation.h"
#include "itkTranslationRegistrationTransform.h"
#include "itkTranslationTransform.h"
#include "itkTriangleCell.h"
#include "itkUpwindDerivativeImageFunction.h"
#include "itkValarrayImageContainer.h"
#include "itkVector.h"
#include "itkVectorContainer.h"
#include "itkVersion.h"
#include "itkVertexCell.h"
#include "itkWeakPointer.h"
#include "itkWin32Header.h"
#include "itkWin32OutputWindow.h"
#include "itkZeroFluxNeumannBoundaryCondition.h"
#include "itk_alloc.h"
#include "itk_hash_map.h"
#include "itk_hash_set.h"
#include "itk_hashtable.h"
#include "vcl_alloc.h"

int main ( int argc, char* argv )
{

  return 0;
}

<commit_msg>ENH: Updated to latest headers<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit (ITK)
  Module:
  Language:  C++
  Date:
  Version:

Copyright (c) 2000 National Library of Medicine
All rights reserved.

See COPYRIGHT.txt for copyright details.

=========================================================================*/
#include <iostream>
// This file has been generated by BuildHeaderTest.tcl
// Test to include each header file for Insight

#include "itkAcosImageAdaptor.h"
#include "itkAffineRegistrationTransform.h"
#include "itkAffineTransform.h"
#include "itkAffineTransformation.h"
#include "itkArray.h"
#include "itkAsinImageAdaptor.h"
#include "itkAtanImageAdaptor.h"
#include "itkBackwardDifferenceOperator.h"
#include "itkBlueDataAccessor.h"
#include "itkBoundingBox.h"
#include "itkByteSwapper.h"
#include "itkCellBoundary.h"
#include "itkCellInterface.h"
#include "itkCellInterfaceVisitor.h"
#include "itkCentralDerivativeImageFunction.h"
#include "itkColorTable.h"
#include "itkCommand.h"
#include "itkConceptChecking.h"
#include "itkConstSliceIterator.h"
#include "itkConstantBoundaryCondition.h"
#include "itkContinuousImageFunction.h"
#include "itkContinuousIndex.h"
#include "itkCosImageAdaptor.h"
#include "itkCovariantVector.h"
#include "itkCreateObjectFunction.h"
#include "itkDataAccessor.h"
#include "itkDataObject.h"
#include "itkDefaultDataAccessor.h"
#include "itkDefaultDynamicMeshTraits.h"
#include "itkDefaultImageTraits.h"
#include "itkDefaultStaticMeshTraits.h"
#include "itkDerivativeOperator.h"
#include "itkDirectory.h"
#include "itkDynamicLoader.h"
#include "itkElasticBodySplineKernelTransform.h"
#include "itkEntropyPreservingGradientMagnitudeImageFunction.h"
#include "itkExceptionObject.h"
#include "itkExpImageAdaptor.h"
#include "itkFastMutexLock.h"
#include "itkForwardDifferenceOperator.h"
#include "itkGaussianOperator.h"
#include "itkGreenDataAccessor.h"
#include "itkHexahedronCell.h"
#include "itkImage.h"
#include "itkImageAdaptor.h"
#include "itkImageBase.h"
#include "itkImageBoundaryCondition.h"
#include "itkImageBufferIterator.h"
#include "itkImageConstIteratorWithIndex.h"
#include "itkImageContainerInterface.h"
#include "itkImageFunction.h"
#include "itkImageIO.h"
#include "itkImageIOCommon.h"
#include "itkImageIterator.h"
#include "itkImageIteratorWithIndex.h"
#include "itkImageLinearConstIterator.h"
#include "itkImageLinearIterator.h"
#include "itkImageRegion.h"
#include "itkImageRegionIterator.h"
#include "itkImageSliceConstIterator.h"
#include "itkImageSliceIterator.h"
#include "itkImageSource.h"
#include "itkImageToImageFilter.h"
#include "itkImportImageContainer.h"
#include "itkIndent.h"
#include "itkIndex.h"
#include "itkIndexedContainerInterface.h"
#include "itkIntTypes.h"
#include "itkKernelTransform.h"
#include "itkLevelSetCurvatureFunction.h"
#include "itkLightObject.h"
#include "itkLightProcessObject.h"
#include "itkLineCell.h"
#include "itkLinearInterpolateImageFunction.h"
#include "itkLog10ImageAdaptor.h"
#include "itkLogImageAdaptor.h"
#include "itkMacro.h"
#include "itkMapContainer.h"
#include "itkMatrix.h"
#include "itkMesh.h"
#include "itkMeshRegion.h"
#include "itkMultiThreader.h"
#include "itkMutexLock.h"
#include "itkNeighborhood.h"
#include "itkNeighborhoodAlgorithm.h"
#include "itkNeighborhoodAllocator.h"
#include "itkNeighborhoodIterator.h"
#include "itkNeighborhoodOperator.h"
#include "itkNthElementDataAccessor.h"
#include "itkNthElementImageAdaptor.h"
#include "itkNumericTraits.h"
#include "itkObject.h"
#include "itkObjectFactory.h"
#include "itkObjectFactoryBase.h"
#include "itkOffset.h"
#include "itkOutputWindow.h"
#include "itkPhysicalImage.h"
#include "itkPhysicalImageAdaptor.h"
#include "itkPixelTraits.h"
#include "itkPoint.h"
#include "itkPointLocator.h"
#include "itkPointSet.h"
#include "itkProcessObject.h"
#include "itkQuadrilateralCell.h"
#include "itkRGBPixel.h"
#include "itkRandomAccessNeighborhoodIterator.h"
#include "itkRedDataAccessor.h"
#include "itkRegion.h"
#include "itkRegionBoundaryNeighborhoodIterator.h"
#include "itkRegionNeighborhoodIterator.h"
#include "itkRegionNonBoundaryNeighborhoodIterator.h"
#include "itkRigid3DRegistrationTransform.h"
#include "itkRigid3DTransform.h"
#include "itkScalar.h"
#include "itkScalarImageRegionIterator.h"
#include "itkScalarVector.h"
#include "itkSimpleImageRegionConstIterator.h"
#include "itkSimpleImageRegionIterator.h"
#include "itkSinImageAdaptor.h"
#include "itkSize.h"
#include "itkSliceIterator.h"
#include "itkSmartPointer.h"
#include "itkSmartPointerForwardReference.h"
#include "itkSmartRegionNeighborhoodIterator.h"
#include "itkSqrtImageAdaptor.h"
#include "itkStatDenseHistogram.h"
#include "itkStatHistogram.h"
#include "itkStatSparseHistogram.h"
#include "itkTanImageAdaptor.h"
#include "itkTetrahedronCell.h"
#include "itkThinPlateSplineKernelTransform.h"
#include "itkTimeStamp.h"
#include "itkTransformation.h"
#include "itkTranslationRegistrationTransform.h"
#include "itkTranslationTransform.h"
#include "itkTriangleCell.h"
#include "itkUpwindDerivativeImageFunction.h"
#include "itkValarrayImageContainer.h"
#include "itkVector.h"
#include "itkVectorContainer.h"
#include "itkVersion.h"
#include "itkVertexCell.h"
#include "itkWeakPointer.h"
#include "itkZeroFluxNeumannBoundaryCondition.h"
#include "itk_alloc.h"
#include "itk_hash_map.h"
#include "itk_hash_set.h"
#include "itk_hashtable.h"
#include "vcl_alloc.h"

int main ( int argc, char* argv )
{

  return 0;
}

<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit (ITK)
  Module:    itkSmartPointerTest.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

Copyright (c) 2000 National Library of Medicine
All rights reserved.

See COPYRIGHT.txt for copyright details.

=========================================================================*/
#include <iostream>
#include "itkSmartPointer.h"

class itkTestObject
{
public:
  typedef itk::SmartPointer<itkTestObject> Pointer;
  static itkTestObject::Pointer New();
  virtual void Register()
    {
    std::cout << "Register " << *this << " count:"
              << (m_ReferenceCount+1) << "  " << std::endl;
    m_ReferenceCount++;
    }
  virtual void UnRegister()
    {
    std::cout << "UnRegister " << this << " count:"
              << (m_ReferenceCount-1) << "  " << std::endl;

    m_ReferenceCount--;
    if ( m_ReferenceCount == 0 )
      {
      delete this;
      }
    }
    inline friend std::ostream &operator << (std::ostream &os,
                                             itkTestObject const& o)
    {
      os << "itkTestObject " << (void*)&o << " " << o.m_ReferenceCount;
      return os;
    }

  std::ostream& Print(std::ostream& os) const
    {
    os << "itkTestObject " << (void*)this << " " << this->m_ReferenceCount;
    return os;
    }

protected:
  itkTestObject()
    {
    m_ReferenceCount = 0;
    std::cout << "construct itkTestObject " << *this << std::endl;
    }
  ~itkTestObject()
    {
    std::cout << "destruct itkTestObject " << *this << std::endl;
    }

private:
  unsigned int m_ReferenceCount;
};

itkTestObject::Pointer itkTestObject::New()
{
  return itkTestObject::Pointer(new itkTestObject);
}

class itkTestObjectSubClass : public itkTestObject
{
public:
  typedef itk::SmartPointer<itkTestObjectSubClass> Pointer;
  static Pointer New();
};

itkTestObjectSubClass::Pointer itkTestObjectSubClass::New()
{
  return itkTestObjectSubClass::Pointer(new itkTestObjectSubClass);
}

void TestUpCastPointer(itkTestObject::Pointer p)
{
}

void TestUpCast(itkTestObject* p)
{
}

int main()
{
  itkTestObject::Pointer to(itkTestObjectSubClass::New());
  itkTestObjectSubClass::Pointer sc = dynamic_cast<itkTestObjectSubClass*>((itkTestObject*)to);
  TestUpCast(sc);
  TestUpCastPointer(sc.GetPointer());
  std::cout <<"second test" << std::endl;
  {
  itkTestObject::Pointer o1 = itkTestObject::New();
  std::cout << "o1 " << &o1 << std::endl;
  itkTestObject::Pointer o2 = itkTestObject::New();
  std::cout << "o2 " << &o2 << std::endl;
  itkTestObject::Pointer o3 = itkTestObject::New();
  std::cout << "o3 " << &o3 << std::endl;
  itkTestObject::Pointer o4 = itkTestObject::New();
  std::cout << "o4 " << &o4 << std::endl;

  o1 = o2;
  o2 = o3;
  o4 = o1;
  if ( o1 < o2 )
    {
    std::cout << "o1 is < o2 " << o1 << " " << o2 << std::endl;
    }
  else
    {
    std::cout << "o1 is not < o2 " << &o1 << " " << &o2 << std::endl;
    }
  }
  std::cout <<"end second test" << std::endl << std::endl;

  std::cout <<"first test" << std::endl;
  {
  itkTestObject::Pointer o1 = itkTestObject::New();
  }
  std::cout <<"end first test" << std::endl << std::endl;
  return 0;
}

<commit_msg>ENH: better comments/examples on smart pointer usage<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit (ITK)
  Module:    itkSmartPointerTest.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

Copyright (c) 2000 National Library of Medicine
All rights reserved.

See COPYRIGHT.txt for copyright details.

=========================================================================*/
#include <iostream>
#include "itkSmartPointer.h"

class itkTestObject
{
public:
  typedef itk::SmartPointer<itkTestObject> Pointer;
  static itkTestObject::Pointer New();
  virtual void Register()
    {
    std::cout << "Register " << *this << " count:"
              << (m_ReferenceCount+1) << "  " << std::endl;
    m_ReferenceCount++;
    }
  virtual void UnRegister()
    {
    std::cout << "UnRegister " << this << " count:"
              << (m_ReferenceCount-1) << "  " << std::endl;

    m_ReferenceCount--;
    if ( m_ReferenceCount == 0 )
      {
      delete this;
      }
    }
    inline friend std::ostream &operator << (std::ostream &os,
                                             itkTestObject const& o)
    {
      os << "itkTestObject " << (void*)&o << " " << o.m_ReferenceCount;
      return os;
    }

  std::ostream& Print(std::ostream& os) const
    {
    os << "itkTestObject " << (void*)this << " " << this->m_ReferenceCount;
    return os;
    }

protected:
  itkTestObject()
    {
    m_ReferenceCount = 0;
    std::cout << "construct itkTestObject " << *this << std::endl;
    }
  ~itkTestObject()
    {
    std::cout << "destruct itkTestObject " << *this << std::endl;
    }

private:
  unsigned int m_ReferenceCount;
};

itkTestObject::Pointer itkTestObject::New()
{
  return itkTestObject::Pointer(new itkTestObject);
}

class itkTestObjectSubClass : public itkTestObject
{
public:
  typedef itk::SmartPointer<itkTestObjectSubClass> Pointer;
  static Pointer New();
};

itkTestObjectSubClass::Pointer itkTestObjectSubClass::New()
{
  return itkTestObjectSubClass::Pointer(new itkTestObjectSubClass);
}

// This SHOULD NOT be used in ITK, all functions
// should take raw pointers as arguments
void TestUpCastPointer(itkTestObject::Pointer p)
{
}

// Test a function that takes an itkTestObject raw pointer
void TestUpCast(itkTestObject* p)
{
}

int main()
{
  // Create a base class pointer to a child class
  itkTestObject::Pointer to(itkTestObjectSubClass::New());
  // test the safe down cast and create a child class Pointer object
  itkTestObjectSubClass::Pointer sc
    = dynamic_cast<itkTestObjectSubClass*>(to.GetPointer());
  // Test the up cast with a function that takes a pointer
  TestUpCast(sc);
  // Test calling a function that takes a SmartPointer as
  // an argument, note, that you have to get the raw pointer
  // for this to work
  TestUpCastPointer(sc.GetPointer());

  // Test casting up the tree, note no explict cast is required
  itkTestObject::Pointer p = sc;

  std::cout <<"second test" << std::endl;
  {
  itkTestObject::Pointer o1 = itkTestObject::New();
  std::cout << "o1 " << &o1 << std::endl;
  itkTestObject::Pointer o2 = itkTestObject::New();
  std::cout << "o2 " << &o2 << std::endl;
  itkTestObject::Pointer o3 = itkTestObject::New();
  std::cout << "o3 " << &o3 << std::endl;
  itkTestObject::Pointer o4 = itkTestObject::New();
  std::cout << "o4 " << &o4 << std::endl;

  o1 = o2;
  o2 = o3;
  o4 = o1;
  if ( o1 < o2 )
    {
    std::cout << "o1 is < o2 " << o1 << " " << o2 << std::endl;
    }
  else
    {
    std::cout << "o1 is not < o2 " << &o1 << " " << &o2 << std::endl;
    }
  }
  std::cout <<"end second test" << std::endl << std::endl;

  std::cout <<"first test" << std::endl;
  {
  itkTestObject::Pointer o1 = itkTestObject::New();
  }
  std::cout <<"end first test" << std::endl << std::endl;
  return 0;
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: thesdsp.cxx,v $
 *
 *  $Revision: 1.12 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 03:56:17 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

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

#ifndef INCLUDED_I18NPOOL_LANG_H
#include <i18npool/lang.h>
#endif
#ifndef _TOOLS_DEBUG_HXX //autogen wg. DBG_ASSERT
#include <tools/debug.hxx>
#endif
#ifndef _SVTOOLS_LNGMISC_HXX_
#include <svtools/lngmisc.hxx>
#endif

#include <cppuhelper/factory.hxx>   // helper for factories
#include <com/sun/star/registry/XRegistryKey.hpp>
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif

#ifndef _UNOTOOLS_PROCESSFACTORY_HXX_
#include <unotools/processfactory.hxx>
#endif
#ifndef _OSL_MUTEX_HXX_
#include <osl/mutex.hxx>
#endif

#include "thesdsp.hxx"
#include "lngprops.hxx"

using namespace utl;
using namespace osl;
using namespace rtl;
using namespace com::sun::star;
using namespace com::sun::star::beans;
using namespace com::sun::star::lang;
using namespace com::sun::star::uno;
using namespace com::sun::star::linguistic2;
using namespace linguistic;

///////////////////////////////////////////////////////////////////////////

static BOOL SvcListHasLanguage(
        const Sequence< Reference< XThesaurus > > &rRefs,
        const Locale &rLocale )
{
    BOOL bHasLanguage = FALSE;

    const Reference< XThesaurus > *pRef = rRefs.getConstArray();
    INT32 nLen = rRefs.getLength();
    for (INT32 k = 0;  k < nLen  &&  !bHasLanguage;  ++k)
    {
        if (pRef[k].is())
            bHasLanguage = pRef[k]->hasLocale( rLocale );
    }

    return bHasLanguage;
}

///////////////////////////////////////////////////////////////////////////

SeqLangSvcEntry_Thes::~SeqLangSvcEntry_Thes()
{
}

SeqLangSvcEntry_Thes::SeqLangSvcEntry_Thes(
        const Sequence< OUString > &rSvcImplNames ) :
    aSvcImplNames   ( rSvcImplNames ),
    aSvcRefs        ( rSvcImplNames.getLength() )
{
}

///////////////////////////////////////////////////////////////////////////

ThesaurusDispatcher::ThesaurusDispatcher()
{
}

ThesaurusDispatcher::~ThesaurusDispatcher()
{
    ClearSvcList();
}

void ThesaurusDispatcher::ClearSvcList()
{
    // release memory for each table entry
    SeqLangSvcEntry_Thes *pItem = aSvcList.First();
    while (pItem)
    {
        SeqLangSvcEntry_Thes *pTmp = pItem;
        pItem = aSvcList.Next();
        delete pTmp;
    }
}

Sequence< Locale > SAL_CALL
    ThesaurusDispatcher::getLocales()
        throw(RuntimeException)
{
    MutexGuard  aGuard( GetLinguMutex() );

    ULONG nCnt = aSvcList.Count();
    Sequence< Locale > aLocales( nCnt );
    Locale *pItem = aLocales.getArray();
    SeqLangSvcEntry_Thes *pEntry = aSvcList.First();
    for (ULONG i = 0;  i < nCnt;  i++)
    {
        DBG_ASSERT( pEntry, "lng : pEntry is NULL pointer" );
        pItem[i] = CreateLocale( (LanguageType) aSvcList.GetKey( pEntry ) );
        pEntry = aSvcList.Next();
    }
    return aLocales;
}

sal_Bool SAL_CALL
    ThesaurusDispatcher::hasLocale( const Locale& rLocale )
        throw(RuntimeException)
{
    MutexGuard  aGuard( GetLinguMutex() );
    return 0 != aSvcList.Get( LocaleToLanguage( rLocale ) );
}

Sequence< Reference< XMeaning > > SAL_CALL
    ThesaurusDispatcher::queryMeanings(
            const OUString& rTerm, const Locale& rLocale,
            const PropertyValues& rProperties )
        throw(IllegalArgumentException, RuntimeException)
{
    MutexGuard  aGuard( GetLinguMutex() );

    Sequence< Reference< XMeaning > >   aMeanings;

    INT16 nLanguage = LocaleToLanguage( rLocale );
    if (nLanguage == LANGUAGE_NONE  || !rTerm.getLength())
        return aMeanings;

    // search for entry with that language
    SeqLangSvcEntry_Thes *pEntry = aSvcList.Get( nLanguage );

    if (!pEntry)
    {
#ifdef LINGU_EXCEPTIONS
        throw IllegalArgumentException();
#endif
    }
    else
    {
        OUString aChkWord( rTerm );
        aChkWord = aChkWord.replace( SVT_HARD_SPACE, ' ' );
        RemoveHyphens( aChkWord );
        if (IsIgnoreControlChars( rProperties, GetPropSet() ))
            RemoveControlChars( aChkWord );

        INT32 nLen = pEntry->aSvcRefs.getLength();
        DBG_ASSERT( nLen == pEntry->aSvcImplNames.getLength(),
                "lng : sequence length mismatch");
        DBG_ASSERT( pEntry->aFlags.nLastTriedSvcIndex < nLen,
                "lng : index out of range");

        INT32 i = 0;

        // try already instantiated services first
        {
            const Reference< XThesaurus > *pRef = pEntry->aSvcRefs.getConstArray();
            while (i <= pEntry->aFlags.nLastTriedSvcIndex
                   &&  aMeanings.getLength() == 0)
            {
                if (pRef[i].is()  &&  pRef[i]->hasLocale( rLocale ))
                    aMeanings = pRef[i]->queryMeanings( aChkWord, rLocale, rProperties );
                ++i;
            }
        }

        // if still no result instantiate new services and try those
        if (aMeanings.getLength() == 0
            &&  pEntry->aFlags.nLastTriedSvcIndex < nLen - 1)
        {
            const OUString *pImplNames = pEntry->aSvcImplNames.getConstArray();
            Reference< XThesaurus > *pRef = pEntry->aSvcRefs.getArray();

            Reference< XMultiServiceFactory >  xMgr( getProcessServiceFactory() );
            if (xMgr.is())
            {
                // build service initialization argument
                Sequence< Any > aArgs(1);
                aArgs.getArray()[0] <<= GetPropSet();

                while (i < nLen  &&  aMeanings.getLength() == 0)
                {
                    // create specific service via it's implementation name
                    Reference< XThesaurus > xThes(
                            xMgr->createInstanceWithArguments(
                                pImplNames[i], aArgs ),
                            UNO_QUERY );
                    pRef[i] = xThes;

                    if (xThes.is()  &&  xThes->hasLocale( rLocale ))
                        aMeanings = xThes->queryMeanings( aChkWord, rLocale, rProperties );

                    pEntry->aFlags.nLastTriedSvcIndex = (INT16) i;
                    ++i;
                }

                // if language is not supported by any of the services
                // remove it from the list.
                if (i == nLen  &&  aMeanings.getLength() == 0)
                {
                    if (!SvcListHasLanguage( pEntry->aSvcRefs, rLocale ))
                        aSvcList.Remove( nLanguage );
                }
            }
        }
    }

    return aMeanings;
}

void ThesaurusDispatcher::SetServiceList( const Locale &rLocale,
        const Sequence< OUString > &rSvcImplNames )
{
    MutexGuard  aGuard( GetLinguMutex() );

    INT16 nLanguage = LocaleToLanguage( rLocale );

    if (0 == rSvcImplNames.getLength())
        // remove entry
        aSvcList.Remove( nLanguage );
    else
    {
        // modify/add entry
        SeqLangSvcEntry_Thes *pEntry = aSvcList.Get( nLanguage );
        if (pEntry)
        {
            pEntry->aSvcImplNames = rSvcImplNames;
            pEntry->aSvcRefs = Sequence< Reference < XThesaurus > >(
                                    rSvcImplNames.getLength() );
            pEntry->aFlags = SvcFlags();
        }
        else
        {
            pEntry = new SeqLangSvcEntry_Thes( rSvcImplNames );
            aSvcList.Insert( nLanguage, pEntry );
            DBG_ASSERT( aSvcList.Get( nLanguage ), "lng : Insert failed" );
        }
    }
}

Sequence< OUString >
    ThesaurusDispatcher::GetServiceList( const Locale &rLocale ) const
{
    MutexGuard  aGuard( GetLinguMutex() );

    Sequence< OUString > aRes;

    // search for entry with that language and use data from that
    INT16 nLanguage = LocaleToLanguage( rLocale );
    ThesaurusDispatcher         *pThis = (ThesaurusDispatcher *) this;
    const SeqLangSvcEntry_Thes  *pEntry = pThis->aSvcList.Get( nLanguage );
    if (pEntry)
        aRes = pEntry->aSvcImplNames;

    return aRes;
}

ThesaurusDispatcher::DspType
    ThesaurusDispatcher::GetDspType() const
{
    return DSP_THES;
}

///////////////////////////////////////////////////////////////////////////

<commit_msg>INTEGRATION: 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<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: thesdsp.cxx,v $
 *
 *  $Revision: 1.13 $
 *
 *  last change: $Author: obo $ $Date: 2008-03-26 09:06:37 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

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

#ifndef INCLUDED_I18NPOOL_LANG_H
#include <i18npool/lang.h>
#endif
#ifndef _TOOLS_DEBUG_HXX //autogen wg. DBG_ASSERT
#include <tools/debug.hxx>
#endif
#ifndef _SVTOOLS_LNGMISC_HXX_
#include <svtools/lngmisc.hxx>
#endif

#include <cppuhelper/factory.hxx>   // helper for factories
#include <com/sun/star/registry/XRegistryKey.hpp>
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif

#ifndef _UNOTOOLS_PROCESSFACTORY_HXX_
#include <unotools/processfactory.hxx>
#endif
#ifndef _OSL_MUTEX_HXX_
#include <osl/mutex.hxx>
#endif

#include "thesdsp.hxx"
#include "lngprops.hxx"

using namespace utl;
using namespace osl;
using namespace rtl;
using namespace com::sun::star;
using namespace com::sun::star::beans;
using namespace com::sun::star::lang;
using namespace com::sun::star::uno;
using namespace com::sun::star::linguistic2;
using namespace linguistic;

///////////////////////////////////////////////////////////////////////////

static BOOL SvcListHasLanguage(
        const Sequence< Reference< XThesaurus > > &rRefs,
        const Locale &rLocale )
{
    BOOL bHasLanguage = FALSE;

    const Reference< XThesaurus > *pRef = rRefs.getConstArray();
    INT32 nLen = rRefs.getLength();
    for (INT32 k = 0;  k < nLen  &&  !bHasLanguage;  ++k)
    {
        if (pRef[k].is())
            bHasLanguage = pRef[k]->hasLocale( rLocale );
    }

    return bHasLanguage;
}

///////////////////////////////////////////////////////////////////////////

SeqLangSvcEntry_Thes::~SeqLangSvcEntry_Thes()
{
}

SeqLangSvcEntry_Thes::SeqLangSvcEntry_Thes(
        const Sequence< OUString > &rSvcImplNames ) :
    aSvcImplNames   ( rSvcImplNames ),
    aSvcRefs        ( rSvcImplNames.getLength() )
{
}

///////////////////////////////////////////////////////////////////////////

ThesaurusDispatcher::ThesaurusDispatcher()
{
}

ThesaurusDispatcher::~ThesaurusDispatcher()
{
    ClearSvcList();
}

void ThesaurusDispatcher::ClearSvcList()
{
    // release memory for each table entry
    SeqLangSvcEntry_Thes *pItem = aSvcList.First();
    while (pItem)
    {
        SeqLangSvcEntry_Thes *pTmp = pItem;
        pItem = aSvcList.Next();
        delete pTmp;
    }
}

Sequence< Locale > SAL_CALL
    ThesaurusDispatcher::getLocales()
        throw(RuntimeException)
{
    MutexGuard  aGuard( GetLinguMutex() );

    ULONG nCnt = aSvcList.Count();
    Sequence< Locale > aLocales( nCnt );
    Locale *pItem = aLocales.getArray();
    SeqLangSvcEntry_Thes *pEntry = aSvcList.First();
    for (ULONG i = 0;  i < nCnt;  i++)
    {
        DBG_ASSERT( pEntry, "lng : pEntry is NULL pointer" );
        pItem[i] = CreateLocale( (LanguageType) aSvcList.GetKey( pEntry ) );
        pEntry = aSvcList.Next();
    }
    return aLocales;
}

sal_Bool SAL_CALL
    ThesaurusDispatcher::hasLocale( const Locale& rLocale )
        throw(RuntimeException)
{
    MutexGuard  aGuard( GetLinguMutex() );
    return 0 != aSvcList.Get( LocaleToLanguage( rLocale ) );
}

Sequence< Reference< XMeaning > > SAL_CALL
    ThesaurusDispatcher::queryMeanings(
            const OUString& rTerm, const Locale& rLocale,
            const PropertyValues& rProperties )
        throw(IllegalArgumentException, RuntimeException)
{
    MutexGuard  aGuard( GetLinguMutex() );

    Sequence< Reference< XMeaning > >   aMeanings;

    INT16 nLanguage = LocaleToLanguage( rLocale );
    if (nLanguage == LANGUAGE_NONE  || !rTerm.getLength())
        return aMeanings;

    // search for entry with that language
    SeqLangSvcEntry_Thes *pEntry = aSvcList.Get( nLanguage );

    if (!pEntry)
    {
#ifdef LINGU_EXCEPTIONS
        throw IllegalArgumentException();
#endif
    }
    else
    {
        OUString aChkWord( rTerm );
        aChkWord = aChkWord.replace( SVT_HARD_SPACE, ' ' );
        RemoveHyphens( aChkWord );
        if (IsIgnoreControlChars( rProperties, GetPropSet() ))
            RemoveControlChars( aChkWord );

        INT32 nLen = pEntry->aSvcRefs.getLength();
        DBG_ASSERT( nLen == pEntry->aSvcImplNames.getLength(),
                "lng : sequence length mismatch");
        DBG_ASSERT( pEntry->aFlags.nLastTriedSvcIndex < nLen,
                "lng : index out of range");

        INT32 i = 0;

        // try already instantiated services first
        {
            const Reference< XThesaurus > *pRef = pEntry->aSvcRefs.getConstArray();
            while (i <= pEntry->aFlags.nLastTriedSvcIndex
                   &&  aMeanings.getLength() == 0)
            {
                if (pRef[i].is()  &&  pRef[i]->hasLocale( rLocale ))
                    aMeanings = pRef[i]->queryMeanings( aChkWord, rLocale, rProperties );
                ++i;
            }
        }

        // if still no result instantiate new services and try those
        if (aMeanings.getLength() == 0
            &&  pEntry->aFlags.nLastTriedSvcIndex < nLen - 1)
        {
            const OUString *pImplNames = pEntry->aSvcImplNames.getConstArray();
            Reference< XThesaurus > *pRef = pEntry->aSvcRefs.getArray();

            Reference< XMultiServiceFactory >  xMgr( getProcessServiceFactory() );
            if (xMgr.is())
            {
                // build service initialization argument
                Sequence< Any > aArgs(1);
                aArgs.getArray()[0] <<= GetPropSet();

                while (i < nLen  &&  aMeanings.getLength() == 0)
                {
                    // create specific service via it's implementation name
                    Reference< XThesaurus > xThes;
                    try
                    {
                        xThes = Reference< XThesaurus >(
                                xMgr->createInstanceWithArguments(
                                pImplNames[i], aArgs ), UNO_QUERY );
                    }
                    catch (uno::Exception &)
                    {
                        DBG_ERROR( "createInstanceWithArguments failed" );
                    }
                    pRef[i] = xThes;

                    if (xThes.is()  &&  xThes->hasLocale( rLocale ))
                        aMeanings = xThes->queryMeanings( aChkWord, rLocale, rProperties );

                    pEntry->aFlags.nLastTriedSvcIndex = (INT16) i;
                    ++i;
                }

                // if language is not supported by any of the services
                // remove it from the list.
                if (i == nLen  &&  aMeanings.getLength() == 0)
                {
                    if (!SvcListHasLanguage( pEntry->aSvcRefs, rLocale ))
                        aSvcList.Remove( nLanguage );
                }
            }
        }
    }

    return aMeanings;
}

void ThesaurusDispatcher::SetServiceList( const Locale &rLocale,
        const Sequence< OUString > &rSvcImplNames )
{
    MutexGuard  aGuard( GetLinguMutex() );

    INT16 nLanguage = LocaleToLanguage( rLocale );

    if (0 == rSvcImplNames.getLength())
        // remove entry
        aSvcList.Remove( nLanguage );
    else
    {
        // modify/add entry
        SeqLangSvcEntry_Thes *pEntry = aSvcList.Get( nLanguage );
        if (pEntry)
        {
            pEntry->aSvcImplNames = rSvcImplNames;
            pEntry->aSvcRefs = Sequence< Reference < XThesaurus > >(
                                    rSvcImplNames.getLength() );
            pEntry->aFlags = SvcFlags();
        }
        else
        {
            pEntry = new SeqLangSvcEntry_Thes( rSvcImplNames );
            aSvcList.Insert( nLanguage, pEntry );
            DBG_ASSERT( aSvcList.Get( nLanguage ), "lng : Insert failed" );
        }
    }
}

Sequence< OUString >
    ThesaurusDispatcher::GetServiceList( const Locale &rLocale ) const
{
    MutexGuard  aGuard( GetLinguMutex() );

    Sequence< OUString > aRes;

    // search for entry with that language and use data from that
    INT16 nLanguage = LocaleToLanguage( rLocale );
    ThesaurusDispatcher         *pThis = (ThesaurusDispatcher *) this;
    const SeqLangSvcEntry_Thes  *pEntry = pThis->aSvcList.Get( nLanguage );
    if (pEntry)
        aRes = pEntry->aSvcImplNames;

    return aRes;
}

ThesaurusDispatcher::DspType
    ThesaurusDispatcher::GetDspType() const
{
    return DSP_THES;
}

///////////////////////////////////////////////////////////////////////////

<|endoftext|>


<commit_before>/**
  \file
  Microscope task.  Acquire stacks for each marked tile in a plane.

  \author Nathan Clack <clackn@janelia.hhmi.org>

  \copyright
  Copyright 2010 Howard Hughes Medical Institute.
  All rights reserved.
  Use is subject to Janelia Farm Research Campus Software Copyright 1.1
  license terms (http://license.janelia.org/license/jfrc_copyright_1_1.html).
 */

#include "common.h"
#include "AdaptiveTiledAcquisition.h"
#include "StackAcquisition.h"
#include "Video.h"
#include "frame.h"
#include "devices\digitizer.h"
#include "devices\Microscope.h"
#include "devices\tiling.h"
#include "tasks\SurfaceFind.h"

#if 1 // PROFILING
#define TS_OPEN(name)   timestream_t ts__=timestream_open(name)
#define TS_TIC          timestream_tic(ts__)
#define TS_TOC          timestream_toc(ts__)
#define TS_CLOSE        timestream_close(ts__)
#else
#define TS_OPEN(name)
#define TS_TIC
#define TS_TOC
#define TS_CLOSE
#endif

#define CHKJMP(expr) if(!(expr)) {warning("%s(%d)"ENDL"\tExpression indicated failure:"ENDL"\t%s"ENDL,__FILE__,__LINE__,#expr); goto Error;}

namespace fetch
{

  namespace task
  {

    //
    // AdaptiveTiledAcquisition -  microscope task
    //

    namespace microscope {

      //Upcasting
      unsigned int AdaptiveTiledAcquisition::config(IDevice *d) {return config(dynamic_cast<device::Microscope*>(d));}
      unsigned int AdaptiveTiledAcquisition::run   (IDevice *d) {return run   (dynamic_cast<device::Microscope*>(d));}

      unsigned int AdaptiveTiledAcquisition::config(device::Microscope *d)
      {
        static task::scanner::ScanStack<u16> grabstack;
        std::string filename;

        Guarded_Assert(d);

        //Assemble pipeline here
        IDevice *cur;
        cur = d->configPipeline();

        CHKJMP(d->file_series.ensurePathExists());
        d->file_series.inc();
        filename = d->stack_filename();
        IDevice::connect(&d->disk,0,cur,0);
        Guarded_Assert( d->disk.close()==0 );
        //Guarded_Assert( d->disk.open(filename,"w")==0);

        d->__scan_agent.disarm(10000/*timeout_ms*/);
        int isok=d->__scan_agent.arm(&grabstack,&d->scanner)==0;
        d->stage()->tiling()->resetCursor();          // this is here so that run/stop cycles will pick up where they left off

        return isok; //success
Error:
        return 0;
      }

      static int _handle_wait_for_result(DWORD result, const char *msg)
      {
          return_val_if( result == WAIT_OBJECT_0  , 0 );
          return_val_if( result == WAIT_OBJECT_0+1, 1 );
          Guarded_Assert_WinErr( result != WAIT_FAILED );
          if(result == WAIT_ABANDONED_0)   warning("%s(%d)"ENDL "\tAdaptiveTiledAcquisition: Wait 0 abandoned"ENDL "\t%s"ENDL, __FILE__, __LINE__, msg);
          if(result == WAIT_ABANDONED_0+1) warning("%s(%d)"ENDL "\tAdaptiveTiledAcquisition: Wait 1 abandoned"ENDL "\t%s"ENDL, __FILE__, __LINE__, msg);
          if(result == WAIT_TIMEOUT)       warning("%s(%d)"ENDL "\tAdaptiveTiledAcquisition: Wait timeout"ENDL     "\t%s"ENDL, __FILE__, __LINE__, msg);

          Guarded_Assert_WinErr( result !=WAIT_FAILED );

          return -1;
      }

      unsigned int AdaptiveTiledAcquisition::run(device::Microscope *dc)
      {
        SurfaceFind surface_find;
        std::string filename;
        unsigned int eflag = 0; // success
        Vector3f tilepos;
        float tiling_offset_acc_mm=0.0f;
        float nsamp=0;
        int adapt_count=0;
        int adapt_thresh=dc->get_config().adaptive_tiling().every();
        int adapt_mindist=dc->get_config().adaptive_tiling().mindist();
        TS_OPEN("timer-tiles.f32");
        CHKJMP(dc->__scan_agent.is_runnable());

        device::StageTiling* tiling = dc->stage()->tiling();

        // 1. iterate over tiles to measure the average tile offset
        tiling->resetCursor();
        while(eflag==0 && !dc->_agent->is_stopping() && tiling->nextInPlanePosition(tilepos))
        {
          if(adapt_mindist<=tiling->minDistTo( 0,0,  // domain query   -- do not restrict to a particular tile type
                     device::StageTiling::Active,0)) // boundary query -- this is defines what is "outside"
          {
            if(++adapt_count>adapt_thresh) // is it time to try?
            {
              // M O V E
              Vector3f curpos = dc->stage()->getTarget(); // use current target z for tilepos z
              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);
              dc->stage()->setPos(0.001f*tilepos);        // convert um to mm
              curpos = dc->stage()->getTarget(); // use current target z for tilepos z
              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);

              // A D A P T I V E
#if 0
              if (adapt_count>2*adapt_thresh) // have too many detections been missed
              { warning("Could not track surface.  Giving up.\n");
                goto Error;
              }
#endif

              //surface_find.config();  -- arms stack task as scan agent...redundant
              eflag |= surface_find.run(dc);
              if(surface_find.hit())
              { adapt_count=0;
                tiling_offset_acc_mm+=dc->stage()->tiling_z_offset_mm();
                ++nsamp;
              }

            }
          }
        }
        if(nsamp==0)
        { warning("Could not track surface.  Giving up.\n");
          goto Error;
        }
        debug("%s(%d)"ENDL "\t[Adaptive Tiling Task] Average tile offset (samples: %5d) %f"ENDL,__FILE__,__LINE__,(int)nsamp,tiling_offset_acc_mm/nsamp);
        dc->stage()->set_tiling_z_offset_mm(tiling_offset_acc_mm/nsamp);

        // retore connection between end of pipeline and disk
        IDevice::connect(&dc->disk,0,dc->_end_of_pipeline,0);

        // 2. iterate over tiles to image
        tiling->resetCursor();
        while(eflag==0 && !dc->_agent->is_stopping() && tiling->nextInPlanePosition(tilepos))
        { TS_TIC;
          debug("%s(%d)"ENDL "\t[Adaptive Tiling Task] tilepos: %5.1f %5.1f %5.1f"ENDL,__FILE__,__LINE__,tilepos[0],tilepos[1],tilepos[2]);
          filename = dc->stack_filename();
          dc->file_series.ensurePathExists();
          dc->disk.set_nchan(dc->scanner.get2d()->digitizer()->nchan());
          eflag |= dc->disk.open(filename,"w");
          if(eflag)
          {
            warning("Couldn't open file: %s"ENDL, filename.c_str());
            return eflag;
          }

          // Move stage
          Vector3f curpos = dc->stage()->getTarget(); // use current target z for tilepos z
          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);
          dc->stage()->setPos(0.001f*tilepos);        // convert um to mm
          curpos = dc->stage()->getTarget(); // use current target z for tilepos z
          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);

          eflag |= dc->runPipeline();
          eflag |= dc->__scan_agent.run() != 1;

          { // Wait for stack to finish
            HANDLE hs[] = {
              dc->__scan_agent._thread,
              dc->__self_agent._notify_stop};
            DWORD res;
            int   t;

            // wait for scan to complete (or cancel)
            res = WaitForMultipleObjects(2,hs,FALSE,INFINITE);
            t = _handle_wait_for_result(res,"AdaptiveTiledAcquisition::run - Wait for scanner to finish.");
            switch(t)
            {
            case 0:                            // in this case, the scanner thread stopped.  Nothing left to do.
              eflag |= dc->__scan_agent.last_run_result(); // check the run result
              eflag |= dc->__io_agent.last_run_result();
              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
                tiling->markDone(eflag==0);      // only mark the tile done if the scanner task completed normally
            case 1:                            // in this case, the stop event triggered and must be propagated.
              eflag |= dc->__scan_agent.stop(SCANNER2D_DEFAULT_TIMEOUT) != 1;
              break;
            default:                           // in this case, there was a timeout or abandoned wait
              eflag |= 1;                      // failure
            }
          } // end waiting block

          // Output and Increment files
          dc->write_stack_metadata();          // write the metadata
          eflag |= dc->disk.close();
          dc->file_series.inc();               // increment regardless of completion status
          eflag |= dc->stopPipeline();         // wait till everything stops

          TS_TOC;
        } // end loop over tiles
        eflag |= dc->stopPipeline();           // wait till the  pipeline stops
        TS_CLOSE;
        return eflag;
Error:
        TS_CLOSE;
        return 1;
      }

    } // namespace microscope

  }   // namespace task
}     // namespace fetch
<commit_msg>[AdaptiveTiling] bug fix. retries to much on miss.<commit_after>/**
  \file
  Microscope task.  Acquire stacks for each marked tile in a plane.

  \author Nathan Clack <clackn@janelia.hhmi.org>

  \copyright
  Copyright 2010 Howard Hughes Medical Institute.
  All rights reserved.
  Use is subject to Janelia Farm Research Campus Software Copyright 1.1
  license terms (http://license.janelia.org/license/jfrc_copyright_1_1.html).
 */

#include "common.h"
#include "AdaptiveTiledAcquisition.h"
#include "StackAcquisition.h"
#include "Video.h"
#include "frame.h"
#include "devices\digitizer.h"
#include "devices\Microscope.h"
#include "devices\tiling.h"
#include "tasks\SurfaceFind.h"

#if 1 // PROFILING
#define TS_OPEN(name)   timestream_t ts__=timestream_open(name)
#define TS_TIC          timestream_tic(ts__)
#define TS_TOC          timestream_toc(ts__)
#define TS_CLOSE        timestream_close(ts__)
#else
#define TS_OPEN(name)
#define TS_TIC
#define TS_TOC
#define TS_CLOSE
#endif

#define CHKJMP(expr) if(!(expr)) {warning("%s(%d)"ENDL"\tExpression indicated failure:"ENDL"\t%s"ENDL,__FILE__,__LINE__,#expr); goto Error;}

namespace fetch
{

  namespace task
  {

    //
    // AdaptiveTiledAcquisition -  microscope task
    //

    namespace microscope {

      //Upcasting
      unsigned int AdaptiveTiledAcquisition::config(IDevice *d) {return config(dynamic_cast<device::Microscope*>(d));}
      unsigned int AdaptiveTiledAcquisition::run   (IDevice *d) {return run   (dynamic_cast<device::Microscope*>(d));}

      unsigned int AdaptiveTiledAcquisition::config(device::Microscope *d)
      {
        static task::scanner::ScanStack<u16> grabstack;
        std::string filename;

        Guarded_Assert(d);

        //Assemble pipeline here
        IDevice *cur;
        cur = d->configPipeline();

        CHKJMP(d->file_series.ensurePathExists());
        d->file_series.inc();
        filename = d->stack_filename();
        IDevice::connect(&d->disk,0,cur,0);
        Guarded_Assert( d->disk.close()==0 );
        //Guarded_Assert( d->disk.open(filename,"w")==0);

        d->__scan_agent.disarm(10000/*timeout_ms*/);
        int isok=d->__scan_agent.arm(&grabstack,&d->scanner)==0;
        d->stage()->tiling()->resetCursor();          // this is here so that run/stop cycles will pick up where they left off

        return isok; //success
Error:
        return 0;
      }

      static int _handle_wait_for_result(DWORD result, const char *msg)
      {
          return_val_if( result == WAIT_OBJECT_0  , 0 );
          return_val_if( result == WAIT_OBJECT_0+1, 1 );
          Guarded_Assert_WinErr( result != WAIT_FAILED );
          if(result == WAIT_ABANDONED_0)   warning("%s(%d)"ENDL "\tAdaptiveTiledAcquisition: Wait 0 abandoned"ENDL "\t%s"ENDL, __FILE__, __LINE__, msg);
          if(result == WAIT_ABANDONED_0+1) warning("%s(%d)"ENDL "\tAdaptiveTiledAcquisition: Wait 1 abandoned"ENDL "\t%s"ENDL, __FILE__, __LINE__, msg);
          if(result == WAIT_TIMEOUT)       warning("%s(%d)"ENDL "\tAdaptiveTiledAcquisition: Wait timeout"ENDL     "\t%s"ENDL, __FILE__, __LINE__, msg);

          Guarded_Assert_WinErr( result !=WAIT_FAILED );

          return -1;
      }

      unsigned int AdaptiveTiledAcquisition::run(device::Microscope *dc)
      {
        SurfaceFind surface_find;
        std::string filename;
        unsigned int eflag = 0; // success
        Vector3f tilepos;
        float tiling_offset_acc_mm=0.0f;
        float nsamp=0;
        int adapt_count=0;
        int adapt_thresh=dc->get_config().adaptive_tiling().every();
        int adapt_mindist=dc->get_config().adaptive_tiling().mindist();
        TS_OPEN("timer-tiles.f32");
        CHKJMP(dc->__scan_agent.is_runnable());

        device::StageTiling* tiling = dc->stage()->tiling();

        // 1. iterate over tiles to measure the average tile offset
        tiling->resetCursor();
        while(eflag==0 && !dc->_agent->is_stopping() && tiling->nextInPlanePosition(tilepos))
        {
          if(adapt_mindist<=tiling->minDistTo( 0,0,  // domain query   -- do not restrict to a particular tile type
                     device::StageTiling::Active,0)) // boundary query -- this is defines what is "outside"
          {
            if(++adapt_count>adapt_thresh) // is it time to try?
            { adapt_count=0;
              // M O V E
              Vector3f curpos = dc->stage()->getTarget(); // use current target z for tilepos z
              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);
              dc->stage()->setPos(0.001f*tilepos);        // convert um to mm
              curpos = dc->stage()->getTarget(); // use current target z for tilepos z
              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);

              // A D A P T I V E
#if 0
              if (adapt_count>2*adapt_thresh) // have too many detections been missed
              { warning("Could not track surface.  Giving up.\n");
                goto Error;
              }
#endif
              //surface_find.config();  -- arms stack task as scan agent...redundant
              eflag |= surface_find.run(dc);
              if(surface_find.hit())
              { tiling_offset_acc_mm+=dc->stage()->tiling_z_offset_mm();
                ++nsamp;
              }

            }
          }
        }
        if(nsamp==0)
        { warning("Could not track surface.  Giving up.\n");
          goto Error;
        }
        debug("%s(%d)"ENDL "\t[Adaptive Tiling Task] Average tile offset (samples: %5d) %f"ENDL,__FILE__,__LINE__,(int)nsamp,tiling_offset_acc_mm/nsamp);
        dc->stage()->set_tiling_z_offset_mm(tiling_offset_acc_mm/nsamp);

        // retore connection between end of pipeline and disk
        IDevice::connect(&dc->disk,0,dc->_end_of_pipeline,0);

        // 2. iterate over tiles to image
        tiling->resetCursor();
        while(eflag==0 && !dc->_agent->is_stopping() && tiling->nextInPlanePosition(tilepos))
        { TS_TIC;
          debug("%s(%d)"ENDL "\t[Adaptive Tiling Task] tilepos: %5.1f %5.1f %5.1f"ENDL,__FILE__,__LINE__,tilepos[0],tilepos[1],tilepos[2]);
          filename = dc->stack_filename();
          dc->file_series.ensurePathExists();
          dc->disk.set_nchan(dc->scanner.get2d()->digitizer()->nchan());
          eflag |= dc->disk.open(filename,"w");
          if(eflag)
          {
            warning("Couldn't open file: %s"ENDL, filename.c_str());
            return eflag;
          }

          // Move stage
          Vector3f curpos = dc->stage()->getTarget(); // use current target z for tilepos z
          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);
          dc->stage()->setPos(0.001f*tilepos);        // convert um to mm
          curpos = dc->stage()->getTarget(); // use current target z for tilepos z
          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);

          eflag |= dc->runPipeline();
          eflag |= dc->__scan_agent.run() != 1;

          { // Wait for stack to finish
            HANDLE hs[] = {
              dc->__scan_agent._thread,
              dc->__self_agent._notify_stop};
            DWORD res;
            int   t;

            // wait for scan to complete (or cancel)
            res = WaitForMultipleObjects(2,hs,FALSE,INFINITE);
            t = _handle_wait_for_result(res,"AdaptiveTiledAcquisition::run - Wait for scanner to finish.");
            switch(t)
            {
            case 0:                            // in this case, the scanner thread stopped.  Nothing left to do.
              eflag |= dc->__scan_agent.last_run_result(); // check the run result
              eflag |= dc->__io_agent.last_run_result();
              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
                tiling->markDone(eflag==0);      // only mark the tile done if the scanner task completed normally
            case 1:                            // in this case, the stop event triggered and must be propagated.
              eflag |= dc->__scan_agent.stop(SCANNER2D_DEFAULT_TIMEOUT) != 1;
              break;
            default:                           // in this case, there was a timeout or abandoned wait
              eflag |= 1;                      // failure
            }
          } // end waiting block

          // Output and Increment files
          dc->write_stack_metadata();          // write the metadata
          eflag |= dc->disk.close();
          dc->file_series.inc();               // increment regardless of completion status
          eflag |= dc->stopPipeline();         // wait till everything stops

          TS_TOC;
        } // end loop over tiles
        eflag |= dc->stopPipeline();           // wait till the  pipeline stops
        TS_CLOSE;
        return eflag;
Error:
        TS_CLOSE;
        return 1;
      }

    } // namespace microscope

  }   // namespace task
}     // namespace fetch
<|endoftext|>


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

#include "storeddockey.h"
#include <mcbp/protocol/unsigned_leb128.h>
#include <iomanip>
#include <iostream>
#include <sstream>

StoredDocKey::StoredDocKey(const std::string& key, CollectionID cid) {
    cb::mcbp::unsigned_leb128<CollectionIDType> leb128(cid);
    keydata.resize(key.size() + leb128.size());
    std::copy(key.begin(),
              key.end(),
              std::copy(leb128.begin(), leb128.end(), keydata.begin()));
}

CollectionID StoredDocKey::getCollectionID() const {
    return cb::mcbp::decode_unsigned_leb128<CollectionIDType>({data(), size()})
            .first;
}

DocKey StoredDocKey::makeDocKeyWithoutCollectionID() const {
    auto decoded = cb::mcbp::decode_unsigned_leb128<CollectionIDType>(
            {data(), size()});
    return {decoded.second.data(),
            decoded.second.size(),
            DocKeyEncodesCollectionId::No};
}

std::string StoredDocKey::to_string() const {
    std::stringstream ss;
    auto leb128 = cb::mcbp::decode_unsigned_leb128<CollectionIDType>(
            {reinterpret_cast<const uint8_t*>(keydata.data()), keydata.size()});
    ss << "cid:0x" << std::hex << leb128.first << ":"
       << std::string(reinterpret_cast<const char*>(leb128.second.data()),
                      leb128.second.size());
    ss << ", size:" << size();
    return ss.str();
}

const char* StoredDocKey::c_str() const {
    // Locate the leb128 stop byte, and return pointer after that
    auto key = cb::mcbp::skip_unsigned_leb128<CollectionIDType>(
            {reinterpret_cast<const uint8_t*>(keydata.data()), keydata.size()});

    if (key.size()) {
        return &keydata.c_str()[keydata.size() - key.size()];
    }
    return nullptr;
}

std::ostream& operator<<(std::ostream& os, const StoredDocKey& key) {
    return os << key.to_string();
}

CollectionID SerialisedDocKey::getCollectionID() const {
    return cb::mcbp::decode_unsigned_leb128<CollectionIDType>({bytes, length})
            .first;
}

bool SerialisedDocKey::operator==(const DocKey& rhs) const {
    auto rhsIdAndData = rhs.getIdAndKey();
    auto lhsIdAndData = cb::mcbp::decode_unsigned_leb128<CollectionIDType>(
            {data(), size()});
    return lhsIdAndData.first == rhsIdAndData.first &&
           lhsIdAndData.second.size() == rhsIdAndData.second.size() &&
           std::equal(lhsIdAndData.second.begin(),
                      lhsIdAndData.second.end(),
                      rhsIdAndData.second.begin());
}

SerialisedDocKey::SerialisedDocKey(cb::const_byte_buffer key,
                                   CollectionID cid) {
    cb::mcbp::unsigned_leb128<CollectionIDType> leb128(cid);
    length = gsl::narrow_cast<uint8_t>(key.size() + leb128.size());
    std::copy(key.begin(),
              key.end(),
              std::copy(leb128.begin(), leb128.end(), bytes));
}

std::ostream& operator<<(std::ostream& os, const SerialisedDocKey& key) {
    auto leb128 = cb::mcbp::decode_unsigned_leb128<CollectionIDType>(
            {reinterpret_cast<const uint8_t*>(key.data()), key.size()});
    os << "cid:0x" << std::hex << leb128.first << ":"
       << std::string(reinterpret_cast<const char*>(leb128.second.data()),
                      leb128.second.size());
    os << ", size:" << key.size();
    return os;
}
<commit_msg>StoredDocKey::to_string: don't print size<commit_after>/*
 *     Copyright 2016 Couchbase, Inc
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */

#include "storeddockey.h"
#include <mcbp/protocol/unsigned_leb128.h>
#include <iomanip>
#include <iostream>
#include <sstream>

StoredDocKey::StoredDocKey(const std::string& key, CollectionID cid) {
    cb::mcbp::unsigned_leb128<CollectionIDType> leb128(cid);
    keydata.resize(key.size() + leb128.size());
    std::copy(key.begin(),
              key.end(),
              std::copy(leb128.begin(), leb128.end(), keydata.begin()));
}

CollectionID StoredDocKey::getCollectionID() const {
    return cb::mcbp::decode_unsigned_leb128<CollectionIDType>({data(), size()})
            .first;
}

DocKey StoredDocKey::makeDocKeyWithoutCollectionID() const {
    auto decoded = cb::mcbp::decode_unsigned_leb128<CollectionIDType>(
            {data(), size()});
    return {decoded.second.data(),
            decoded.second.size(),
            DocKeyEncodesCollectionId::No};
}

std::string StoredDocKey::to_string() const {
    std::stringstream ss;
    auto leb128 = cb::mcbp::decode_unsigned_leb128<CollectionIDType>(
            {reinterpret_cast<const uint8_t*>(keydata.data()), keydata.size()});
    ss << "cid:0x" << std::hex << leb128.first << std::dec << ":"
       << std::string(reinterpret_cast<const char*>(leb128.second.data()),
                      leb128.second.size());
    return ss.str();
}

const char* StoredDocKey::c_str() const {
    // Locate the leb128 stop byte, and return pointer after that
    auto key = cb::mcbp::skip_unsigned_leb128<CollectionIDType>(
            {reinterpret_cast<const uint8_t*>(keydata.data()), keydata.size()});

    if (key.size()) {
        return &keydata.c_str()[keydata.size() - key.size()];
    }
    return nullptr;
}

std::ostream& operator<<(std::ostream& os, const StoredDocKey& key) {
    return os << key.to_string();
}

CollectionID SerialisedDocKey::getCollectionID() const {
    return cb::mcbp::decode_unsigned_leb128<CollectionIDType>({bytes, length})
            .first;
}

bool SerialisedDocKey::operator==(const DocKey& rhs) const {
    auto rhsIdAndData = rhs.getIdAndKey();
    auto lhsIdAndData = cb::mcbp::decode_unsigned_leb128<CollectionIDType>(
            {data(), size()});
    return lhsIdAndData.first == rhsIdAndData.first &&
           lhsIdAndData.second.size() == rhsIdAndData.second.size() &&
           std::equal(lhsIdAndData.second.begin(),
                      lhsIdAndData.second.end(),
                      rhsIdAndData.second.begin());
}

SerialisedDocKey::SerialisedDocKey(cb::const_byte_buffer key,
                                   CollectionID cid) {
    cb::mcbp::unsigned_leb128<CollectionIDType> leb128(cid);
    length = gsl::narrow_cast<uint8_t>(key.size() + leb128.size());
    std::copy(key.begin(),
              key.end(),
              std::copy(leb128.begin(), leb128.end(), bytes));
}

std::ostream& operator<<(std::ostream& os, const SerialisedDocKey& key) {
    auto leb128 = cb::mcbp::decode_unsigned_leb128<CollectionIDType>(
            {reinterpret_cast<const uint8_t*>(key.data()), key.size()});
    os << "cid:0x" << std::hex << leb128.first << ":"
       << std::string(reinterpret_cast<const char*>(leb128.second.data()),
                      leb128.second.size());
    os << ", size:" << key.size();
    return os;
}
<|endoftext|>


<commit_before>#ifndef STAN_MATH_OPENCL_KERNELS_DEVICE_FUNCTIONS_BINOMIAL_COEFFICIENT_LOG_HPP
#define STAN_MATH_OPENCL_KERNELS_DEVICE_FUNCTIONS_BINOMIAL_COEFFICIENT_LOG_HPP
#ifdef STAN_OPENCL

#include <stan/math/opencl/stringify.hpp>
#include <string>

namespace stan {
namespace math {
namespace opencl_kernels {

// \cond
static const char* binomial_coefficient_log_device_function
    = "\n"
      "#ifndef "
      "STAN_MATH_OPENCL_KERNELS_DEVICE_FUNCTIONS_BINOMIAL_COEFFICIENT_LOG\n"
      "#define "
      "STAN_MATH_OPENCL_KERNELS_DEVICE_FUNCTIONS_BINOMIAL_COEFFICIENT_"
      "LOG\n" STRINGIFY(
          // \endcond
          /**
           * Return the log of the binomial coefficient for the specified
           * arguments.
           *
           * The binomial coefficient, \f${n \choose k}\f$, read "n choose k",
           is
           * defined for \f$0 \leq k \leq n\f$ by
           *
           * \f${n \choose k} = \frac{n!}{k! (n-k)!}\f$.
           *
           * This function uses Gamma functions to define the log
           * and generalize the arguments to continuous n and k.
           *
           * \f$ \log {n \choose k}
           * = \log \ \Gamma(n+1) - \log \Gamma(k+1) - \log \Gamma(n-k+1)\f$.
           *
           *
             \f[
             \mbox{binomial\_coefficient\_log}(x, y) =
             \begin{cases}
               \textrm{error} & \mbox{if } y > x + 1 \textrm{ or } y < -1
           \textrm{ or } x
           < -1\\
               \ln\Gamma(x+1) & \mbox{if } -1 < y < x + 1 \\
               \quad -\ln\Gamma(y+1)& \\
               \quad -\ln\Gamma(x-y+1)& \\[6pt]
               \textrm{NaN} & \mbox{if } x = \textrm{NaN or } y = \textrm{NaN}
             \end{cases}
             \f]

             \f[
             \frac{\partial\, \mbox{binomial\_coefficient\_log}(x, y)}{\partial
           x} = \begin{cases} \textrm{error} & \mbox{if } y > x + 1 \textrm{ or
           } y < -1 \textrm{ or } x
           < -1\\
               \Psi(x+1) & \mbox{if } 0\leq y \leq x \\
               \quad -\Psi(x-y+1)& \\[6pt]
               \textrm{NaN} & \mbox{if } x = \textrm{NaN or } y = \textrm{NaN}
             \end{cases}
             \f]

             \f[
             \frac{\partial\, \mbox{binomial\_coefficient\_log}(x, y)}{\partial
           y} = \begin{cases} \textrm{error} & \mbox{if } y > x + 1 \textrm{ or
           } y < -1 \textrm{ or } x
           < -1\\
               -\Psi(y+1) & \mbox{if } 0\leq y \leq x \\
               \quad +\Psi(x-y+1)& \\[6pt]
               \textrm{NaN} & \mbox{if } x = \textrm{NaN or } y = \textrm{NaN}
             \end{cases}
             \f]
           *
           *  This function is numerically more stable than naive evaluation via
           lgamma.
           *
           * @param n total number of objects.
           * @param k number of objects chosen.
           * @return log (n choose k).
           */
          double binomial_coefficient_log(double n, double k) {
            if (isnan(n) || isnan(k)) {
              return NAN;
            }

            // Choosing the more stable of the symmetric branches
            if (n > -1 && k > n / 2.0 + 1e-8) {
              return binomial_coefficient_log(n, n - k);
            }

            double n_plus_1 = n + 1;
            double n_plus_1_mk = n_plus_1 - k;

            if (k == 0) {
              return 0;
            } else if (n_plus_1 < LGAMMA_STIRLING_DIFF_USEFUL) {
              return lgamma(n_plus_1) - lgamma(k + 1) - lgamma(n_plus_1_mk);
            } else {
              return -lbeta(n_plus_1_mk, k + 1) - log1p(n);
            }
          }
          // \cond
          ) "\n#endif\n";  // NOLINT
// \endcond

}  // namespace opencl_kernels
}  // namespace math
}  // namespace stan

#endif
#endif  // BINOMIAL_COEFFICIENT_LOG_HPP
<commit_msg>remove recursion<commit_after>#ifndef STAN_MATH_OPENCL_KERNELS_DEVICE_FUNCTIONS_BINOMIAL_COEFFICIENT_LOG_HPP
#define STAN_MATH_OPENCL_KERNELS_DEVICE_FUNCTIONS_BINOMIAL_COEFFICIENT_LOG_HPP
#ifdef STAN_OPENCL

#include <stan/math/opencl/stringify.hpp>
#include <string>

namespace stan {
namespace math {
namespace opencl_kernels {

// \cond
static const char* binomial_coefficient_log_device_function
    = "\n"
      "#ifndef "
      "STAN_MATH_OPENCL_KERNELS_DEVICE_FUNCTIONS_BINOMIAL_COEFFICIENT_LOG\n"
      "#define "
      "STAN_MATH_OPENCL_KERNELS_DEVICE_FUNCTIONS_BINOMIAL_COEFFICIENT_"
      "LOG\n" STRINGIFY(
          // \endcond
          /**
           * Return the log of the binomial coefficient for the specified
           * arguments.
           *
           * The binomial coefficient, \f${n \choose k}\f$, read "n choose k",
           is
           * defined for \f$0 \leq k \leq n\f$ by
           *
           * \f${n \choose k} = \frac{n!}{k! (n-k)!}\f$.
           *
           * This function uses Gamma functions to define the log
           * and generalize the arguments to continuous n and k.
           *
           * \f$ \log {n \choose k}
           * = \log \ \Gamma(n+1) - \log \Gamma(k+1) - \log \Gamma(n-k+1)\f$.
           *
           *
             \f[
             \mbox{binomial\_coefficient\_log}(x, y) =
             \begin{cases}
               \textrm{error} & \mbox{if } y > x + 1 \textrm{ or } y < -1
           \textrm{ or } x
           < -1\\
               \ln\Gamma(x+1) & \mbox{if } -1 < y < x + 1 \\
               \quad -\ln\Gamma(y+1)& \\
               \quad -\ln\Gamma(x-y+1)& \\[6pt]
               \textrm{NaN} & \mbox{if } x = \textrm{NaN or } y = \textrm{NaN}
             \end{cases}
             \f]

             \f[
             \frac{\partial\, \mbox{binomial\_coefficient\_log}(x, y)}{\partial
           x} = \begin{cases} \textrm{error} & \mbox{if } y > x + 1 \textrm{ or
           } y < -1 \textrm{ or } x
           < -1\\
               \Psi(x+1) & \mbox{if } 0\leq y \leq x \\
               \quad -\Psi(x-y+1)& \\[6pt]
               \textrm{NaN} & \mbox{if } x = \textrm{NaN or } y = \textrm{NaN}
             \end{cases}
             \f]

             \f[
             \frac{\partial\, \mbox{binomial\_coefficient\_log}(x, y)}{\partial
           y} = \begin{cases} \textrm{error} & \mbox{if } y > x + 1 \textrm{ or
           } y < -1 \textrm{ or } x
           < -1\\
               -\Psi(y+1) & \mbox{if } 0\leq y \leq x \\
               \quad +\Psi(x-y+1)& \\[6pt]
               \textrm{NaN} & \mbox{if } x = \textrm{NaN or } y = \textrm{NaN}
             \end{cases}
             \f]
           *
           *  This function is numerically more stable than naive evaluation via
           lgamma.
           *
           * @param n total number of objects.
           * @param k number of objects chosen.
           * @return log (n choose k).
           */
          double binomial_coefficient_log(double n, double k) {
            if (isnan(n) || isnan(k)) {
              return NAN;
            }

            // Choosing the more stable of the symmetric branches
            if (n > -1 && k > n / 2.0 + 1e-8) {
              k = n - k;
            }

            double n_plus_1 = n + 1;
            double n_plus_1_mk = n_plus_1 - k;

            if (k == 0) {
              return 0;
            } else if (n_plus_1 < LGAMMA_STIRLING_DIFF_USEFUL) {
              return lgamma(n_plus_1) - lgamma(k + 1) - lgamma(n_plus_1_mk);
            } else {
              return -lbeta(n_plus_1_mk, k + 1) - log1p(n);
            }
          }
          // \cond
          ) "\n#endif\n";  // NOLINT
// \endcond

}  // namespace opencl_kernels
}  // namespace math
}  // namespace stan

#endif
#endif  // BINOMIAL_COEFFICIENT_LOG_HPP
<|endoftext|>


<commit_before>/**
 *  @file
 *  @copyright defined in eos/LICENSE.txt
 */
#include <eos/chain_api_plugin/chain_api_plugin.hpp>
#include <eos/chain/exceptions.hpp>

#include <fc/io/json.hpp>

namespace eos {

using namespace eos;

class chain_api_plugin_impl {
public:
   chain_api_plugin_impl(chain_controller& db)
      : db(db) {}

   chain_controller& db;
};

chain_api_plugin::chain_api_plugin(){}
chain_api_plugin::~chain_api_plugin(){}

void chain_api_plugin::set_program_options(options_description&, options_description&) {}
void chain_api_plugin::plugin_initialize(const variables_map&) {}

#define CALL(api_name, api_handle, api_namespace, call_name) \
{std::string("/v1/" #api_name "/" #call_name), \
   [this, api_handle](string, string body, url_response_callback cb) mutable { \
          try { \
             if (body.empty()) body = "{}"; \
             auto result = api_handle.call_name(fc::json::from_string(body).as<api_namespace::call_name ## _params>()); \
             cb(201, fc::json::to_string(result)); \
          } catch (chain::tx_missing_sigs& e) { \
             error_results results{401, "UnAuthorized", e.to_string()}; \
             cb(401, fc::json::to_string(results)); \
          } catch (chain::tx_duplicate& e) { \
             error_results results{409, "Conflict", e.to_string()}; \
             cb(409, fc::json::to_string(results)); \
          } catch (chain::transaction_exception& e) { \
             error_results results{400, "Bad Request", e.to_string()}; \
             cb(400, fc::json::to_string(results)); \
          } catch (fc::eof_exception& e) { \
             error_results results{400, "Bad Request", e.to_string()}; \
             cb(400, fc::json::to_string(results)); \
             elog("Unable to parse arguments: ${args}", ("args", body)); \
          } catch (fc::exception& e) { \
             error_results results{500, "Internal Service Error", e.to_detail_string()}; \
             cb(500, fc::json::to_string(results)); \
             elog("Exception encountered while processing ${call}: ${e}", ("call", #api_name "." #call_name)("e", e)); \
          } \
       }}

#define CHAIN_RO_CALL(call_name) CALL(chain, ro_api, chain_apis::read_only, call_name)
#define CHAIN_RW_CALL(call_name) CALL(chain, rw_api, chain_apis::read_write, call_name)

void chain_api_plugin::plugin_startup() {
   ilog( "starting chain_api_plugin" );
   my.reset(new chain_api_plugin_impl(app().get_plugin<chain_plugin>().chain()));
   auto ro_api = app().get_plugin<chain_plugin>().get_read_only_api();
   auto rw_api = app().get_plugin<chain_plugin>().get_read_write_api();

   app().get_plugin<http_plugin>().add_api({
      CHAIN_RO_CALL(get_info),
      CHAIN_RO_CALL(get_block),
      CHAIN_RO_CALL(get_account),
      CHAIN_RO_CALL(get_code),
      CHAIN_RO_CALL(get_table_rows),
      CHAIN_RO_CALL(abi_json_to_bin),
      CHAIN_RO_CALL(abi_bin_to_json),
      CHAIN_RO_CALL(get_required_keys),
      CHAIN_RW_CALL(push_block),
      CHAIN_RW_CALL(push_transaction),
      CHAIN_RW_CALL(push_transactions)
   });
}

void chain_api_plugin::plugin_shutdown() {}

}
<commit_msg>Revise chain API to return http response 200 or 202, as appropriate.<commit_after>/**
 *  @file
 *  @copyright defined in eos/LICENSE.txt
 */
#include <eos/chain_api_plugin/chain_api_plugin.hpp>
#include <eos/chain/exceptions.hpp>

#include <fc/io/json.hpp>

namespace eos {

using namespace eos;

class chain_api_plugin_impl {
public:
   chain_api_plugin_impl(chain_controller& db)
      : db(db) {}

   chain_controller& db;
};

chain_api_plugin::chain_api_plugin(){}
chain_api_plugin::~chain_api_plugin(){}

void chain_api_plugin::set_program_options(options_description&, options_description&) {}
void chain_api_plugin::plugin_initialize(const variables_map&) {}

#define CALL(api_name, api_handle, api_namespace, call_name, http_response_code) \
{std::string("/v1/" #api_name "/" #call_name), \
   [this, api_handle](string, string body, url_response_callback cb) mutable { \
          try { \
             if (body.empty()) body = "{}"; \
             auto result = api_handle.call_name(fc::json::from_string(body).as<api_namespace::call_name ## _params>()); \
             cb(http_response_code, fc::json::to_string(result)); \
          } catch (chain::tx_missing_sigs& e) { \
             error_results results{401, "UnAuthorized", e.to_string()}; \
             cb(401, fc::json::to_string(results)); \
          } catch (chain::tx_duplicate& e) { \
             error_results results{409, "Conflict", e.to_string()}; \
             cb(409, fc::json::to_string(results)); \
          } catch (chain::transaction_exception& e) { \
             error_results results{400, "Bad Request", e.to_string()}; \
             cb(400, fc::json::to_string(results)); \
          } catch (fc::eof_exception& e) { \
             error_results results{400, "Bad Request", e.to_string()}; \
             cb(400, fc::json::to_string(results)); \
             elog("Unable to parse arguments: ${args}", ("args", body)); \
          } catch (fc::exception& e) { \
             error_results results{500, "Internal Service Error", e.to_detail_string()}; \
             cb(500, fc::json::to_string(results)); \
             elog("Exception encountered while processing ${call}: ${e}", ("call", #api_name "." #call_name)("e", e)); \
          } \
       }}

#define CHAIN_RO_CALL(call_name, http_response_code) CALL(chain, ro_api, chain_apis::read_only, call_name, http_response_code)
#define CHAIN_RW_CALL(call_name, http_response_code) CALL(chain, rw_api, chain_apis::read_write, call_name, http_response_code)

void chain_api_plugin::plugin_startup() {
   ilog( "starting chain_api_plugin" );
   my.reset(new chain_api_plugin_impl(app().get_plugin<chain_plugin>().chain()));
   auto ro_api = app().get_plugin<chain_plugin>().get_read_only_api();
   auto rw_api = app().get_plugin<chain_plugin>().get_read_write_api();

   app().get_plugin<http_plugin>().add_api({
      CHAIN_RO_CALL(get_info, 200),
      CHAIN_RO_CALL(get_block, 200),
      CHAIN_RO_CALL(get_account, 200),
      CHAIN_RO_CALL(get_code, 200),
      CHAIN_RO_CALL(get_table_rows, 200),
      CHAIN_RO_CALL(abi_json_to_bin, 200),
      CHAIN_RO_CALL(abi_bin_to_json, 200),
      CHAIN_RO_CALL(get_required_keys, 200),
      CHAIN_RW_CALL(push_block, 202),
      CHAIN_RW_CALL(push_transaction, 202),
      CHAIN_RW_CALL(push_transactions, 202)
   });
}

void chain_api_plugin::plugin_shutdown() {}

}
<|endoftext|>


<commit_before>/*
Copyright (c) 2016 Barrett Adair

Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)

HEADER GUARDS INTENTIONALLY OMITTED
DO NOT INCLUDE THIS HEADER DIRECTLY

BOOST_CLBL_TRTS_INCLUDE_QUALIFIERS - the function-level qualifiers for the
    current inclusion (combinations of `const` `volatile` `&` `&&`, or nothing)

BOOST_CLBL_TRTS_INCLUDE_TRANSACTION_SAFE - the transaction_safe specifier for
    the current include (`transaction_safe` or nothing)

BOOST_CLBL_TRTS_IS_TRANSACTION_SAFE - `std::true_type` or `std::false_type`,
    tied on whether BOOST_CLBL_TRTS_INCLUDE_TRANSACTION_SAFE is `transaction_safe`

BOOST_CLBL_TRTS_TRANSACTION_SAFE_SPECIFIER - `transaction_safe` when
    BOOST_CLBL_TRTS_ENABLE_TRANSACTION_SAFE is defined, otherwise nothing

BOOST_CLBL_TRTS_NOEXCEPT_SPEC - the noexcept specifier for
    the current include (`noexcept` or nothing)

BOOST_CLBL_TRTS_IS_NOEXCEPT - `std::true_type` or `std::false_type`,
    tied on whether BOOST_CLBL_TRTS_NOEXCEPT_SPEC is `noexcept`

BOOST_CLBL_TRTS_NOEXCEPT_SPECIFIER - `noexcept` if
    BOOST_CLBL_TRTS_ENABLE_NOEXCEPT_TYPES is defined, otherwise nothing
*/

template<typename Return, typename T, typename... Args>
struct pmf<Return(BOOST_CLBL_TRTS_CC T::*)(Args...)
    BOOST_CLBL_TRTS_INCLUDE_QUALIFIERS
    BOOST_CLBL_TRTS_INCLUDE_TRANSACTION_SAFE
    BOOST_CLBL_TRTS_NOEXCEPT_SPEC>
    : default_callable_traits<dummy BOOST_CLBL_TRTS_INCLUDE_QUALIFIERS> {

    static constexpr bool value = true;

    using traits = pmf;

    using return_type = Return;

    using type = Return(BOOST_CLBL_TRTS_CC T::*)(Args...)
        BOOST_CLBL_TRTS_INCLUDE_QUALIFIERS
        BOOST_CLBL_TRTS_INCLUDE_TRANSACTION_SAFE
        BOOST_CLBL_TRTS_NOEXCEPT_SPEC;

    using invoke_type = typename std::conditional<
        std::is_rvalue_reference<T BOOST_CLBL_TRTS_INCLUDE_QUALIFIERS>::value,
        T BOOST_CLBL_TRTS_INCLUDE_QUALIFIERS,
        typename std::add_lvalue_reference<T BOOST_CLBL_TRTS_INCLUDE_QUALIFIERS>::type
    >::type;

    using arg_types = std::tuple<invoke_type, Args...>;
    using non_invoke_arg_types = std::tuple<Args...>;

    using function_object_signature = Return(Args...);

    using function_type = Return(invoke_type, Args...);

    using qualified_function_type = Return(Args...)
        BOOST_CLBL_TRTS_INCLUDE_ABOMINABLE_QUALIFIERS
        BOOST_CLBL_TRTS_INCLUDE_TRANSACTION_SAFE
        BOOST_CLBL_TRTS_NOEXCEPT_SPEC;

    using remove_varargs = type;

    using add_varargs =
        Return(BOOST_CLBL_TRTS_VARARGS_CC T::*)(Args..., ...)
            BOOST_CLBL_TRTS_INCLUDE_QUALIFIERS
            BOOST_CLBL_TRTS_INCLUDE_TRANSACTION_SAFE
            BOOST_CLBL_TRTS_NOEXCEPT_SPEC;

    using is_noexcept = BOOST_CLBL_TRTS_IS_NOEXCEPT;

    using remove_noexcept = Return(BOOST_CLBL_TRTS_CC T::*)(Args...)
        BOOST_CLBL_TRTS_INCLUDE_QUALIFIERS
        BOOST_CLBL_TRTS_INCLUDE_TRANSACTION_SAFE;

    using add_noexcept = Return(BOOST_CLBL_TRTS_CC T::*)(Args...)
        BOOST_CLBL_TRTS_INCLUDE_QUALIFIERS
        BOOST_CLBL_TRTS_INCLUDE_TRANSACTION_SAFE
        BOOST_CLBL_TRTS_NOEXCEPT_SPECIFIER;

    using is_transaction_safe = BOOST_CLBL_TRTS_IS_TRANSACTION_SAFE;

    using remove_transaction_safe = Return(BOOST_CLBL_TRTS_CC T::*)(Args...)
        BOOST_CLBL_TRTS_INCLUDE_QUALIFIERS
        BOOST_CLBL_TRTS_NOEXCEPT_SPEC;

    using add_transaction_safe = Return(BOOST_CLBL_TRTS_CC T::*)(Args...)
        BOOST_CLBL_TRTS_INCLUDE_QUALIFIERS
        BOOST_CLBL_TRTS_TRANSACTION_SAFE_SPECIFIER
        BOOST_CLBL_TRTS_NOEXCEPT_SPEC;

    using class_type = T;

    using qualifiers = default_callable_traits<dummy BOOST_CLBL_TRTS_INCLUDE_QUALIFIERS>;

    template<qualifier_flags Flags>
    using set_qualifiers = set_member_function_qualifiers<
            Flags, is_transaction_safe::value, is_noexcept::value,
            BOOST_CLBL_TRTS_CC_TAG, T, Return, Args...>;

    using remove_member_reference = set_qualifiers<qualifiers::cv_flags>;

    using add_member_lvalue_reference = set_qualifiers<
        collapse_flags<qualifiers::q_flags, lref_>::value>;

    using add_member_rvalue_reference = set_qualifiers<
        collapse_flags<qualifiers::q_flags, rref_>::value>;

    using add_member_const = set_qualifiers<qualifiers::q_flags | const_>;

    using add_member_volatile = set_qualifiers<qualifiers::q_flags | volatile_>;

    using add_member_cv = set_qualifiers<qualifiers::q_flags | cv_>;

    using remove_member_const = set_qualifiers<
        qualifiers::ref_flags | remove_const_flag<qualifiers::cv_flags>::value>;

    using remove_member_volatile = set_qualifiers<
        qualifiers::ref_flags | remove_volatile_flag<qualifiers::cv_flags>::value>;

    using remove_member_cv = set_qualifiers<qualifiers::ref_flags>;

    template<typename U>
    using apply_member_pointer =
        Return(BOOST_CLBL_TRTS_CC U::*)(Args...)
            BOOST_CLBL_TRTS_INCLUDE_QUALIFIERS
            BOOST_CLBL_TRTS_INCLUDE_TRANSACTION_SAFE
            BOOST_CLBL_TRTS_NOEXCEPT_SPEC;

    template<typename NewReturn>
    using apply_return =
        NewReturn(BOOST_CLBL_TRTS_CC T::*)(Args...)
            BOOST_CLBL_TRTS_INCLUDE_QUALIFIERS
            BOOST_CLBL_TRTS_INCLUDE_TRANSACTION_SAFE
            BOOST_CLBL_TRTS_NOEXCEPT_SPEC;

    template<template<class...> class Container>
    using expand_args = Container<invoke_type, Args...>;

    using is_member_pointer = std::true_type;
};
<commit_msg>Delete pmf_4.hpp<commit_after><|endoftext|>


<commit_before>/*

@Copyright Barrett Adair 2015-2017
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)

*/

#ifndef BOOST_CLBL_TRTS_REMOVE_MEMBER_VOLATILE_HPP
#define BOOST_CLBL_TRTS_REMOVE_MEMBER_VOLATILE_HPP

#include <boost/callable_traits/detail/core.hpp>

namespace boost { namespace callable_traits {

//[ remove_member_volatile_hpp
/*`
[section:ref_remove_member_volatile remove_member_volatile]
[heading Header]
``#include <boost/callable_traits/remove_member_volatile.hpp>``
[heading Definition]
*/

template<typename T>
using remove_member_volatile_t = //see below
//<-
    detail::try_but_fail_if_invalid<
        typename detail::traits<T>::remove_member_volatile,
        member_qualifiers_are_illegal_for_this_type>;

namespace detail {

    template<typename T, typename = std::false_type>
    struct remove_member_volatile_impl {};

    template<typename T>
    struct remove_member_volatile_impl <T, typename std::is_same<
        remove_member_volatile_t<T>, detail::dummy>::type>
    {
        using type = remove_member_volatile_t<T>;
    };
}

//->

template<typename T>
struct remove_member_volatile : detail::remove_member_volatile_impl<T> {};

//<-
}} // namespace boost::callable_traits
//->

/*`
[heading Constraints]
* `T` must be a function type or a member function pointer type
* If `T` is a pointer, it may not be cv/ref qualified

[heading Behavior]
* A substitution failure occurs if the constraints are violated.
* Removes the member `volatile` qualifier from `T`, if present.

[heading Input/Output Examples]
[table
    [[`T`]                              [`remove_member_volatile_t<T>`]]
    [[`int() volatile`]                 [`int()`]]
    [[`int(foo::*)() volatile`]         [`int(foo::*)()`]]
    [[`int(foo::*)() volatile &`]       [`int(foo::*)() &`]]
    [[`int(foo::*)() volatile &&`]      [`int(foo::*)() &&`]]
    [[`int(foo::*)() volatile`]         [`int(foo::*)()`]]
    [[`int(foo::*)() const volatile`]   [`int(foo::*)() const`]]
    [[`int`]                            [(substitution failure)]]
    [[`int (&)()`]                      [(substitution failure)]]
    [[`int (*)()`]                      [(substitution failure)]]
    [[`int foo::*`]                     [(substitution failure)]]
    [[`int (foo::* const)()`]           [(substitution failure)]]
]

[heading Example Program]
[import ../example/remove_member_volatile.cpp]
[remove_member_volatile]
[endsect]
*/
//]

#endif // #ifndef BOOST_CLBL_TRTS_REMOVE_MEMBER_VOLATILE_HPP
<commit_msg>Delete remove_member_volatile.hpp<commit_after><|endoftext|>


<commit_before>// Python module for playing audio
// part of MusicPlayer, https://github.com/albertz/music-player
// Copyright (c) 2012, Albert Zeyer, www.az2000.de
// All rights reserved.
// This code is under the 2-clause BSD license, see License.txt in the root directory of this project.

// compile:
// gcc -c musicplayer*.{c,cpp} -I /System/Library/Frameworks/Python.framework/Headers/
// libtool -dynamic -o musicplayer.so musicplayer*.o -framework Python -lavformat -lavutil -lavcodec -lswresample -lportaudio -lc

// loosely based on ffplay.c
// https://github.com/FFmpeg/ffmpeg/blob/master/ffplay.c

// Similar to PyFFmpeg. http://code.google.com/p/pyffmpeg/
// This module is intended to be much simpler/high-level, though.

// Pyton interface:
//	createPlayer() -> player object with:
//		queue: song generator
//		peekQueue(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.
//		playing: True or False, initially False
//		volume: 1.0 is norm; this is just a factor to each sample. default is 0.9
//		volumeSmoothClip: smooth clipping, see below. set to (1,1) to disable. default is (0.95,10)
//		curSong: current song (read only)
//		curSongPos: current song pos (read only)
//		curSongLen: current song len (read only)
//		curSongGainFactor: current song gain. read from song.gain (see below). can also be written
//		seekAbs(t) / seekRel(t): seeking functions (t in seconds, accepts float)
//		nextSong(): skip to next song function
//	song object expected interface:
//		readPacket(bufSize): should return some string
//		seekRaw(offset, whence): should seek and return the current pos
//		gain: some gain in decible, e.g. calculated by calcReplayGain. if not present, is ignored
//		url: some url, can be anything printable (not used at the moment)
//	and other functions, see their embedded doc ...

#include "musicplayer.h"

static PyMethodDef module_methods[] = {
	{"createPlayer",	(PyCFunction)pyCreatePlayer,	METH_NOARGS,	"creates new player"},
	{"getSoundDevices", (PyCFunction)pyGetSoundDevices, METH_NOARGS,	"get list of sound device names"},
	{"getMetadata",		pyGetMetadata,	METH_VARARGS,	"get metadata for Song"},
	{"calcAcoustIdFingerprint",		pyCalcAcoustIdFingerprint,	METH_VARARGS,	"calculate AcoustID fingerprint for Song"},
	{"calcBitmapThumbnail",		(PyCFunction)pyCalcBitmapThumbnail,	METH_VARARGS|METH_KEYWORDS,	"calculate bitmap thumbnail for Song"},
	{"calcReplayGain",		(PyCFunction)pyCalcReplayGain,	METH_VARARGS|METH_KEYWORDS,	"calculate ReplayGain for Song"},
	{"setFfmpegLogLevel",		pySetFfmpegLogLevel,	METH_VARARGS,	"set FFmpeg log level (av_log_set_level)"},
	{"enableDebugLog",	(PyCFunction)pyEnableDebugLog,	METH_VARARGS,	"enable/disable debug log"},
	{NULL,				NULL}	/* sentinel */
};

PyDoc_STRVAR(module_doc,
"Music player.");

static PyObject* EventClass = NULL;

static void init() {
	PyEval_InitThreads(); /* Start the interpreter's thread-awareness */
	initPlayerOutput();
	initPlayerDecoder();
}

PyMODINIT_FUNC
initmusicplayer(void)
{
	//printf("initmusicplayer\n");
	init();
	if (PyType_Ready(&Player_Type) < 0)
		Py_FatalError("Can't initialize player type");
	PyObject* m = Py_InitModule3("musicplayer", module_methods, module_doc);
	if(!m) {
		Py_FatalError("Can't initialize musicplayer module");
		return;
	}

	if(EventClass == NULL) {
		PyObject* classDict = PyDict_New();
		assert(classDict);
		PyObject* className = PyString_FromString("Event");
		assert(className);
		EventClass = PyClass_New(NULL, classDict, className);
		assert(EventClass);
		Py_XDECREF(classDict); classDict = NULL;
		Py_XDECREF(className); className = NULL;
	}

	if(EventClass) {
		Py_INCREF(EventClass);
		PyModule_AddObject(m, "Event", EventClass); // takes the ref
	}
}
<commit_msg>comment update<commit_after>// Python module for playing audio
// part of MusicPlayer, https://github.com/albertz/music-player
// Copyright (c) 2012, Albert Zeyer, www.az2000.de
// All rights reserved.
// This code is under the 2-clause BSD license, see License.txt in the root directory of this project.

// compile:
// gcc -c musicplayer*.cpp -I /System/Library/Frameworks/Python.framework/Headers/
// libtool -dynamic -o musicplayer.so musicplayer*.o -framework Python -lavformat -lavutil -lavcodec -lswresample -lportaudio -lc

// loosely based on ffplay.c
// https://github.com/FFmpeg/ffmpeg/blob/master/ffplay.c

// Similar to PyFFmpeg. http://code.google.com/p/pyffmpeg/
// This module is intended to be much simpler/high-level, though.

// Pyton interface:
//	createPlayer() -> player object with:
//		queue: song generator
//		peekQueue(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.
//		playing: True or False, initially False
//		volume: 1.0 is norm; this is just a factor to each sample. default is 0.9
//		volumeSmoothClip: smooth clipping, see below. set to (1,1) to disable. default is (0.95,10)
//		curSong: current song (read only)
//		curSongPos: current song pos (read only)
//		curSongLen: current song len (read only)
//		curSongGainFactor: current song gain. read from song.gain (see below). can also be written
//		seekAbs(t) / seekRel(t): seeking functions (t in seconds, accepts float)
//		nextSong(): skip to next song function
//	song object expected interface:
//		readPacket(bufSize): should return some string
//		seekRaw(offset, whence): should seek and return the current pos
//		gain: some gain in decible, e.g. calculated by calcReplayGain. if not present, is ignored
//		url: some url, can be anything printable (not used at the moment)
//	and other functions, see their embedded doc ...

#include "musicplayer.h"

static PyMethodDef module_methods[] = {
	{"createPlayer",	(PyCFunction)pyCreatePlayer,	METH_NOARGS,	"creates new player"},
	{"getSoundDevices", (PyCFunction)pyGetSoundDevices, METH_NOARGS,	"get list of sound device names"},
	{"getMetadata",		pyGetMetadata,	METH_VARARGS,	"get metadata for Song"},
	{"calcAcoustIdFingerprint",		pyCalcAcoustIdFingerprint,	METH_VARARGS,	"calculate AcoustID fingerprint for Song"},
	{"calcBitmapThumbnail",		(PyCFunction)pyCalcBitmapThumbnail,	METH_VARARGS|METH_KEYWORDS,	"calculate bitmap thumbnail for Song"},
	{"calcReplayGain",		(PyCFunction)pyCalcReplayGain,	METH_VARARGS|METH_KEYWORDS,	"calculate ReplayGain for Song"},
	{"setFfmpegLogLevel",		pySetFfmpegLogLevel,	METH_VARARGS,	"set FFmpeg log level (av_log_set_level)"},
	{"enableDebugLog",	(PyCFunction)pyEnableDebugLog,	METH_VARARGS,	"enable/disable debug log"},
	{NULL,				NULL}	/* sentinel */
};

PyDoc_STRVAR(module_doc,
"Music player.");

static PyObject* EventClass = NULL;

static void init() {
	PyEval_InitThreads(); /* Start the interpreter's thread-awareness */
	initPlayerOutput();
	initPlayerDecoder();
}

PyMODINIT_FUNC
initmusicplayer(void)
{
	//printf("initmusicplayer\n");
	init();
	if (PyType_Ready(&Player_Type) < 0)
		Py_FatalError("Can't initialize player type");
	PyObject* m = Py_InitModule3("musicplayer", module_methods, module_doc);
	if(!m) {
		Py_FatalError("Can't initialize musicplayer module");
		return;
	}

	if(EventClass == NULL) {
		PyObject* classDict = PyDict_New();
		assert(classDict);
		PyObject* className = PyString_FromString("Event");
		assert(className);
		EventClass = PyClass_New(NULL, classDict, className);
		assert(EventClass);
		Py_XDECREF(classDict); classDict = NULL;
		Py_XDECREF(className); className = NULL;
	}

	if(EventClass) {
		Py_INCREF(EventClass);
		PyModule_AddObject(m, "Event", EventClass); // takes the ref
	}
}
<|endoftext|>