<commit_before>/*
 * Copyright (C) 2005-2019 Centre National d'Etudes Spatiales (CNES)
 *
 * This file is part of Orfeo Toolbox
 *
 *     https://www.orfeo-toolbox.org/
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef otbWrapperInputImageParameter_hxx
#define otbWrapperInputImageParameter_hxx

#include "otbWrapperInputImageParameter.h"

#include "otbWrapperCastImage.h"

namespace otb
{
namespace Wrapper
{

#define CLAMP_IMAGE_IF( Out, In, image_base )	\
  {							\
    In * in_image = dynamic_cast< In * >( image_base );	\
							\
    if( in_image )						\
      return Cast< Out, In >( in_image );			\
  }

#define CLAMP_IMAGE_BASE( T, image_base )				\
  {									\
    CLAMP_IMAGE_IF( T, UInt8VectorImageType, image_base );		\
    CLAMP_IMAGE_IF( T, Int16VectorImageType, image_base );		\
    CLAMP_IMAGE_IF( T, UInt16VectorImageType, image_base );	\
    CLAMP_IMAGE_IF( T, Int32VectorImageType, image_base );		\
    CLAMP_IMAGE_IF( T, UInt32VectorImageType, image_base );	\
									\
    CLAMP_IMAGE_IF( T, FloatVectorImageType, image_base );		\
    CLAMP_IMAGE_IF( T, DoubleVectorImageType, image_base );	\
									\
    CLAMP_IMAGE_IF( T, ComplexInt16VectorImageType, image_base );	\
    CLAMP_IMAGE_IF( T, ComplexInt32VectorImageType, image_base );	\
									\
    CLAMP_IMAGE_IF( T, ComplexFloatVectorImageType, image_base );	\
    CLAMP_IMAGE_IF( T, ComplexDoubleVectorImageType, image_base );	\
    									\
    CLAMP_IMAGE_IF( T, UInt8RGBImageType, image_base );		\
    CLAMP_IMAGE_IF( T, UInt8RGBAImageType, image_base );		\
									\
    CLAMP_IMAGE_IF( T, UInt8ImageType, image_base );		\
    CLAMP_IMAGE_IF( T, Int16ImageType, image_base );		\
    CLAMP_IMAGE_IF( T, UInt16ImageType, image_base );		\
    CLAMP_IMAGE_IF( T, Int32ImageType, image_base );		\
    CLAMP_IMAGE_IF( T, UInt32ImageType, image_base );		\
									\
    CLAMP_IMAGE_IF( T, FloatImageType, image_base );		\
    CLAMP_IMAGE_IF( T, DoubleImageType, image_base );		\
									\
    CLAMP_IMAGE_IF( T, ComplexInt16ImageType, image_base );	\
    CLAMP_IMAGE_IF( T, ComplexInt32ImageType, image_base );	\
									\
    CLAMP_IMAGE_IF( T, ComplexFloatImageType, image_base );	\
    CLAMP_IMAGE_IF( T, ComplexDoubleImageType, image_base );	\
									\
    return nullptr;							\
  }

template< typename TOutputImage,
	  typename TInputImage >
TOutputImage *
InputImageParameter
::Cast( TInputImage * image )
{
  details::CastImage< TOutputImage, TInputImage > clamp( image );

  if( clamp.ocif )
    clamp.ocif->UpdateOutputInformation();

  m_InputCaster = clamp.icif;
  m_OutputCaster = clamp.ocif;

  return clamp.out;
}

template <class TImageType>
TImageType*
InputImageParameter::GetImage()
{
  // Used m_PreviousFileName because if not, when the user call twice GetImage,
  // it without changing the filename, it returns 2 different
  // image pointers
  // Only one image type can be used

  // 2 cases : the user set a filename vs. the user set an image
  if( m_UseFilename )
    {
    if( m_PreviousFileName!=m_FileName &&
	!m_FileName.empty() )
      {
      //////////////////////// Filename case:
      // A new valid filename has been given : a reader is created
      typedef otb::ImageFileReader<TImageType> ReaderType;

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

      reader->SetFileName( m_FileName );

      reader->UpdateOutputInformation();

      m_Image = reader->GetOutput();
      m_Reader = reader;

      m_PreviousFileName = m_FileName;

      // Pay attention, don't return m_Image because it is a ImageBase...
      return reader->GetOutput();
      }
    else
      {
      // In this case, the reader and the image should already be there
      if (m_Image.IsNull())
        {
        itkExceptionMacro("No input image or filename detected...");
        }
      else
        {
        // Check if the image type asked here is the same as the one used for the reader
        if (dynamic_cast<TImageType*> (m_Image.GetPointer()))
          {
          return dynamic_cast<TImageType*> (m_Image.GetPointer());
          }
        else
        {
          itkExceptionMacro(
              "GetImage() was already called with a different type, "
              "probably due to two calls to GetParameter<Type>Image with different types in application code.");
        }
        }
      }
    }

  else
    {
    //////////////////////// Image case:
    if (m_Image.IsNull())
      {
      return nullptr;
      }
    // Check if the image type asked here is the same as m_image
    else if ( dynamic_cast < TImageType* > ( m_Image.GetPointer() ) )
      {
      return dynamic_cast < TImageType* > ( m_Image.GetPointer() );
      }
    // check if we already done this cast
    else if ( dynamic_cast <
      ClampImageFilter < DoubleVectorImageType , TImageType >* >
      ( m_OutputCaster.GetPointer() ) )
      {
      return dynamic_cast <
      ClampImageFilter < DoubleVectorImageType , TImageType >* >
        ( m_OutputCaster.GetPointer() )->GetOutput();
      }
    else
    {
      CLAMP_IMAGE_BASE( TImageType, m_Image.GetPointer() );
    }
  }
}

/** declare a specialization for ImageBaseType */
template <>
OTBApplicationEngine_EXPORT
ImageBaseType*
InputImageParameter::GetImage<ImageBaseType>();

} // End namespace Wrapper
} // End namespace otb

#endif
<commit_msg>BUG: InputImageParameter check for existing output caster<commit_after>/*
 * Copyright (C) 2005-2019 Centre National d'Etudes Spatiales (CNES)
 *
 * This file is part of Orfeo Toolbox
 *
 *     https://www.orfeo-toolbox.org/
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef otbWrapperInputImageParameter_hxx
#define otbWrapperInputImageParameter_hxx

#include "otbWrapperInputImageParameter.h"

#include "otbWrapperCastImage.h"

namespace otb
{
namespace Wrapper
{

#define CLAMP_IMAGE_IF( Out, In, image_base )	\
  {							\
    In * in_image = dynamic_cast< In * >( image_base );	\
							\
    if( in_image )						\
      return Cast< Out, In >( in_image );			\
  }

#define CLAMP_IMAGE_BASE( T, image_base )				\
  {									\
    CLAMP_IMAGE_IF( T, UInt8VectorImageType, image_base );		\
    CLAMP_IMAGE_IF( T, Int16VectorImageType, image_base );		\
    CLAMP_IMAGE_IF( T, UInt16VectorImageType, image_base );	\
    CLAMP_IMAGE_IF( T, Int32VectorImageType, image_base );		\
    CLAMP_IMAGE_IF( T, UInt32VectorImageType, image_base );	\
									\
    CLAMP_IMAGE_IF( T, FloatVectorImageType, image_base );		\
    CLAMP_IMAGE_IF( T, DoubleVectorImageType, image_base );	\
									\
    CLAMP_IMAGE_IF( T, ComplexInt16VectorImageType, image_base );	\
    CLAMP_IMAGE_IF( T, ComplexInt32VectorImageType, image_base );	\
									\
    CLAMP_IMAGE_IF( T, ComplexFloatVectorImageType, image_base );	\
    CLAMP_IMAGE_IF( T, ComplexDoubleVectorImageType, image_base );	\
    									\
    CLAMP_IMAGE_IF( T, UInt8RGBImageType, image_base );		\
    CLAMP_IMAGE_IF( T, UInt8RGBAImageType, image_base );		\
									\
    CLAMP_IMAGE_IF( T, UInt8ImageType, image_base );		\
    CLAMP_IMAGE_IF( T, Int16ImageType, image_base );		\
    CLAMP_IMAGE_IF( T, UInt16ImageType, image_base );		\
    CLAMP_IMAGE_IF( T, Int32ImageType, image_base );		\
    CLAMP_IMAGE_IF( T, UInt32ImageType, image_base );		\
									\
    CLAMP_IMAGE_IF( T, FloatImageType, image_base );		\
    CLAMP_IMAGE_IF( T, DoubleImageType, image_base );		\
									\
    CLAMP_IMAGE_IF( T, ComplexInt16ImageType, image_base );	\
    CLAMP_IMAGE_IF( T, ComplexInt32ImageType, image_base );	\
									\
    CLAMP_IMAGE_IF( T, ComplexFloatImageType, image_base );	\
    CLAMP_IMAGE_IF( T, ComplexDoubleImageType, image_base );	\
									\
    return nullptr;							\
  }

template< typename TOutputImage,
	  typename TInputImage >
TOutputImage *
InputImageParameter
::Cast( TInputImage * image )
{
  details::CastImage< TOutputImage, TInputImage > clamp( image );

  if( clamp.ocif )
    clamp.ocif->UpdateOutputInformation();

  m_InputCaster = clamp.icif;
  m_OutputCaster = clamp.ocif;

  return clamp.out;
}

template <class TImageType>
TImageType*
InputImageParameter::GetImage()
{
  // Used m_PreviousFileName because if not, when the user call twice GetImage,
  // it without changing the filename, it returns 2 different
  // image pointers
  // Only one image type can be used

  // 2 cases : the user set a filename vs. the user set an image
  if( m_UseFilename )
    {
    if( m_PreviousFileName!=m_FileName &&
	!m_FileName.empty() )
      {
      //////////////////////// Filename case:
      // A new valid filename has been given : a reader is created
      typedef otb::ImageFileReader<TImageType> ReaderType;

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

      reader->SetFileName( m_FileName );

      reader->UpdateOutputInformation();

      m_Image = reader->GetOutput();
      m_Reader = reader;

      m_PreviousFileName = m_FileName;

      // Pay attention, don't return m_Image because it is a ImageBase...
      return reader->GetOutput();
      }
    else
      {
      // In this case, the reader and the image should already be there
      if (m_Image.IsNull())
        {
        itkExceptionMacro("No input image or filename detected...");
        }
      else
        {
        // Check if the image type asked here is the same as the one used for the reader
        if (dynamic_cast<TImageType*> (m_Image.GetPointer()))
          {
          return dynamic_cast<TImageType*> (m_Image.GetPointer());
          }
        else
        {
          itkExceptionMacro(
              "GetImage() was already called with a different type, "
              "probably due to two calls to GetParameter<Type>Image with different types in application code.");
        }
        }
      }
    }

  else
    {
    //////////////////////// Image case:
    if (m_Image.IsNull())
      {
      return nullptr;
      }
    // Check if the image type asked here is the same as m_image
    else if ( dynamic_cast < TImageType* > ( m_Image.GetPointer() ) )
      {
      return dynamic_cast < TImageType* > ( m_Image.GetPointer() );
      }
    // check if we already done this cast
    else if ( dynamic_cast <
      ClampImageFilter < DoubleVectorImageType , TImageType >* >
      ( m_OutputCaster.GetPointer() ) )
      {
      return dynamic_cast <
      ClampImageFilter < DoubleVectorImageType , TImageType >* >
        ( m_OutputCaster.GetPointer() )->GetOutput();
      }
    else
    {
        if (m_OutputCaster.IsNotNull())
        {
          itkExceptionMacro(
              "GetImage() was already called with a different type, "
              "probably due to two calls to GetParameter<Type>Image with different types in application code.");
        }
      CLAMP_IMAGE_BASE( TImageType, m_Image.GetPointer() );
    }
  }
}

/** declare a specialization for ImageBaseType */
template <>
OTBApplicationEngine_EXPORT
ImageBaseType*
InputImageParameter::GetImage<ImageBaseType>();

} // End namespace Wrapper
} // End namespace otb

#endif
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: ScriptingContext.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 02:31:14 $
 *
 *  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
 *
 ************************************************************************/
#include <com/sun/star/beans/PropertyAttribute.hpp>
#include <com/sun/star/frame/XModel.hpp>

#include <cppuhelper/implementationentry.hxx>
#include <cppuhelper/factory.hxx>

#include <util/scriptingconstants.hxx>
#include <util/util.hxx>

#include "ScriptingContext.hxx"

using namespace com::sun::star;
using namespace com::sun::star::uno;
#define DOC_REF_PROPID  1
#define DOC_STORAGE_ID_PROPID 2
#define DOC_URI_PROPID   3
#define RESOLVED_STORAGE_ID_PROPID  4
#define SCRIPT_INFO_PROPID  5
#define SCRIPTINGCONTEXT_DEFAULT_ATTRIBS()   beans::PropertyAttribute::TRANSIENT | beans::PropertyAttribute::MAYBEVOID
namespace func_provider
{

//*************************************************************************
// XScriptingContext implementation
//
//*************************************************************************
ScriptingContext::ScriptingContext( const Reference< XComponentContext > & xContext ) : //ScriptingContextImpl_BASE( GetMutex()),
    OPropertyContainer( GetBroadcastHelper() ),
        m_xContext( xContext )
{
    OSL_TRACE( "< ScriptingContext ctor called >\n" );

    validateXRef( m_xContext,
                  "ScriptingContext::ScriptingContext: No context available\n" );

    Any nullAny;

    scripting_constants::ScriptingConstantsPool& scriptingConstantsPool =
        scripting_constants::ScriptingConstantsPool::instance();
    registerPropertyNoMember( scriptingConstantsPool.DOC_REF, DOC_REF_PROPID, SCRIPTINGCONTEXT_DEFAULT_ATTRIBS(),::getCppuType(  (const Reference< css::frame::XModel >* ) NULL ), NULL ) ;
    registerPropertyNoMember( scriptingConstantsPool.DOC_STORAGE_ID, DOC_STORAGE_ID_PROPID, SCRIPTINGCONTEXT_DEFAULT_ATTRIBS(), ::getCppuType(  (const sal_Int32* ) NULL ), NULL ) ;
    registerPropertyNoMember( scriptingConstantsPool.DOC_URI, DOC_URI_PROPID, SCRIPTINGCONTEXT_DEFAULT_ATTRIBS(), ::getCppuType(  (const ::rtl::OUString* ) NULL ), NULL ) ;
    registerPropertyNoMember( scriptingConstantsPool.RESOLVED_STORAGE_ID, RESOLVED_STORAGE_ID_PROPID, SCRIPTINGCONTEXT_DEFAULT_ATTRIBS(), ::getCppuType(  (const sal_Int32* ) NULL ), NULL );
    registerPropertyNoMember( scriptingConstantsPool.SCRIPT_INFO, SCRIPT_INFO_PROPID, SCRIPTINGCONTEXT_DEFAULT_ATTRIBS(), ::getCppuType(  (const sal_Int32* ) NULL ), NULL );
}

ScriptingContext::~ScriptingContext()
{
    OSL_TRACE( "< ScriptingContext dtor called >\n" );
}
// -----------------------------------------------------------------------------
// OPropertySetHelper
// -----------------------------------------------------------------------------

::cppu::IPropertyArrayHelper& ScriptingContext::getInfoHelper(  )
{
    return *getArrayHelper();
}

// -----------------------------------------------------------------------------
// OPropertyArrayUsageHelper
// -----------------------------------------------------------------------------

::cppu::IPropertyArrayHelper* ScriptingContext::createArrayHelper(  ) const
{
    Sequence< beans::Property > aProps;
    describeProperties( aProps );
    return new ::cppu::OPropertyArrayHelper( aProps );
}
// -----------------------------------------------------------------------------
// XPropertySet
// -----------------------------------------------------------------------------

Reference< beans::XPropertySetInfo > ScriptingContext::getPropertySetInfo(  ) throw (RuntimeException)
{
    Reference< beans::XPropertySetInfo > xInfo( createPropertySetInfo( getInfoHelper() ) );
    return xInfo;
}
// -----------------------------------------------------------------------------// XTypeProvider
// -----------------------------------------------------------------------------
IMPLEMENT_GET_IMPLEMENTATION_ID( ScriptingContext )

css::uno::Sequence< css::uno::Type > SAL_CALL ScriptingContext::getTypes(  ) throw (css::uno::RuntimeException)
{
    return OPropertyContainer::getTypes();
}
} // namespace func_provider
<commit_msg>INTEGRATION: CWS pchfix02 (1.7.36); FILE MERGED 2006/09/01 17:35:36 kaib 1.7.36.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: ScriptingContext.cxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-16 12:29:15 $
 *
 *  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_scripting.hxx"
#include <com/sun/star/beans/PropertyAttribute.hpp>
#include <com/sun/star/frame/XModel.hpp>

#include <cppuhelper/implementationentry.hxx>
#include <cppuhelper/factory.hxx>

#include <util/scriptingconstants.hxx>
#include <util/util.hxx>

#include "ScriptingContext.hxx"

using namespace com::sun::star;
using namespace com::sun::star::uno;
#define DOC_REF_PROPID  1
#define DOC_STORAGE_ID_PROPID 2
#define DOC_URI_PROPID   3
#define RESOLVED_STORAGE_ID_PROPID  4
#define SCRIPT_INFO_PROPID  5
#define SCRIPTINGCONTEXT_DEFAULT_ATTRIBS()   beans::PropertyAttribute::TRANSIENT | beans::PropertyAttribute::MAYBEVOID
namespace func_provider
{

//*************************************************************************
// XScriptingContext implementation
//
//*************************************************************************
ScriptingContext::ScriptingContext( const Reference< XComponentContext > & xContext ) : //ScriptingContextImpl_BASE( GetMutex()),
    OPropertyContainer( GetBroadcastHelper() ),
        m_xContext( xContext )
{
    OSL_TRACE( "< ScriptingContext ctor called >\n" );

    validateXRef( m_xContext,
                  "ScriptingContext::ScriptingContext: No context available\n" );

    Any nullAny;

    scripting_constants::ScriptingConstantsPool& scriptingConstantsPool =
        scripting_constants::ScriptingConstantsPool::instance();
    registerPropertyNoMember( scriptingConstantsPool.DOC_REF, DOC_REF_PROPID, SCRIPTINGCONTEXT_DEFAULT_ATTRIBS(),::getCppuType(  (const Reference< css::frame::XModel >* ) NULL ), NULL ) ;
    registerPropertyNoMember( scriptingConstantsPool.DOC_STORAGE_ID, DOC_STORAGE_ID_PROPID, SCRIPTINGCONTEXT_DEFAULT_ATTRIBS(), ::getCppuType(  (const sal_Int32* ) NULL ), NULL ) ;
    registerPropertyNoMember( scriptingConstantsPool.DOC_URI, DOC_URI_PROPID, SCRIPTINGCONTEXT_DEFAULT_ATTRIBS(), ::getCppuType(  (const ::rtl::OUString* ) NULL ), NULL ) ;
    registerPropertyNoMember( scriptingConstantsPool.RESOLVED_STORAGE_ID, RESOLVED_STORAGE_ID_PROPID, SCRIPTINGCONTEXT_DEFAULT_ATTRIBS(), ::getCppuType(  (const sal_Int32* ) NULL ), NULL );
    registerPropertyNoMember( scriptingConstantsPool.SCRIPT_INFO, SCRIPT_INFO_PROPID, SCRIPTINGCONTEXT_DEFAULT_ATTRIBS(), ::getCppuType(  (const sal_Int32* ) NULL ), NULL );
}

ScriptingContext::~ScriptingContext()
{
    OSL_TRACE( "< ScriptingContext dtor called >\n" );
}
// -----------------------------------------------------------------------------
// OPropertySetHelper
// -----------------------------------------------------------------------------

::cppu::IPropertyArrayHelper& ScriptingContext::getInfoHelper(  )
{
    return *getArrayHelper();
}

// -----------------------------------------------------------------------------
// OPropertyArrayUsageHelper
// -----------------------------------------------------------------------------

::cppu::IPropertyArrayHelper* ScriptingContext::createArrayHelper(  ) const
{
    Sequence< beans::Property > aProps;
    describeProperties( aProps );
    return new ::cppu::OPropertyArrayHelper( aProps );
}
// -----------------------------------------------------------------------------
// XPropertySet
// -----------------------------------------------------------------------------

Reference< beans::XPropertySetInfo > ScriptingContext::getPropertySetInfo(  ) throw (RuntimeException)
{
    Reference< beans::XPropertySetInfo > xInfo( createPropertySetInfo( getInfoHelper() ) );
    return xInfo;
}
// -----------------------------------------------------------------------------// XTypeProvider
// -----------------------------------------------------------------------------
IMPLEMENT_GET_IMPLEMENTATION_ID( ScriptingContext )

css::uno::Sequence< css::uno::Type > SAL_CALL ScriptingContext::getTypes(  ) throw (css::uno::RuntimeException)
{
    return OPropertyContainer::getTypes();
}
} // namespace func_provider
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: directsql.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: hr $ $Date: 2003-03-19 17:52:39 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc..
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _DBACCESS_UI_DIRECTSQL_HXX_
#define _DBACCESS_UI_DIRECTSQL_HXX_

#ifndef _SV_DIALOG_HXX
#include <vcl/dialog.hxx>
#endif
#ifndef _SVEDIT_HXX
#include <svtools/svmedit.hxx>
#endif
#ifndef _SV_FIXED_HXX
#include <vcl/fixed.hxx>
#endif
#ifndef _SV_LSTBOX_HXX
#include <vcl/lstbox.hxx>
#endif
#ifndef _SV_BUTTON_HXX
#include <vcl/button.hxx>
#endif
#ifndef _COMPHELPER_STLTYPES_HXX_
#include <comphelper/stl_types.hxx>
#endif
#include <deque>

#ifndef _COM_SUN_STAR_SDBC_XCONNECTION_HPP_
#include <com/sun/star/sdbc/XConnection.hpp>
#endif
#ifndef _UNOTOOLS_EVENTLISTENERADAPTER_HXX_
#include <unotools/eventlisteneradapter.hxx>
#endif
#ifndef _OSL_MUTEX_HXX_
#include <osl/mutex.hxx>
#endif

//........................................................................
namespace dbaui
{
//........................................................................

    //====================================================================
    //= DirectSQLDialog
    //====================================================================
    class DirectSQLDialog
            :public ModalDialog
            ,public ::utl::OEventListenerAdapter
    {
    protected:
        ::osl::Mutex    m_aMutex;

        FixedLine       m_aFrame;
        FixedText       m_aSQLLabel;
        MultiLineEdit   m_aSQL;
        PushButton      m_aExecute;
        FixedText       m_aHistoryLabel;
        ListBox*        m_pSQLHistory;
        FixedLine       m_aStatusFrame;
        MultiLineEdit   m_aStatus;
        FixedLine       m_aButtonSeparator;
        HelpButton      m_aHelp;
        PushButton      m_aClose;

        typedef ::std::deque< String >  StringQueue;
        StringQueue     m_aStatementHistory;    // previous statements
        StringQueue     m_aNormalizedHistory;   // previous statements, normalized to be used in the list box

        sal_Int32       m_nHistoryLimit;
        sal_Int32       m_nStatusCount;

        ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >
                        m_xConnection;

    public:
        DirectSQLDialog(
            Window* _pParent,
            const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _rxConn);
        ~DirectSQLDialog();

        /// add an history entry
        void addHistoryEntry(const String& _rStatement);

        /// set the limit for the history size
        void setHistoryLimit(sal_Int32 _nMaxEntries);

        /// number of history entries
        sal_Int32 getHistorySize() const;

    protected:
        void executeCurrent();
        void switchToHistory(sal_Int32 _nHistoryPos, sal_Bool _bUpdateListBox = sal_True);

        // OEventListenerAdapter
        virtual void _disposing( const ::com::sun::star::lang::EventObject& _rSource );

    protected:
        DECL_LINK( OnExecute, void* );
        DECL_LINK( OnClose, void* );
        DECL_LINK( OnListEntrySelected, void* );
        DECL_LINK( OnStatementModified, void* );

    private:
        /// adds a statement to the statement history
        void implAddToStatementHistory(const String& _rStatement);

        /// ensures that our history has at most m_nHistoryLimit entries
        void implEnsureHistoryLimit();

        /// executes the statement given, adds the status to the status list
        void implExecuteStatement(const String& _rStatement);

        /// adds a status text to the status list
        void addStatusText(const String& _rMessage);

#ifdef DBG_UTIL
        const sal_Char* impl_CheckInvariants() const;
#endif
    };

    //====================================================================
#ifdef DBG_UTIL
#define CHECK_INVARIANTS(methodname)    \
    {   \
        const sal_Char* pError = impl_CheckInvariants();    \
        if (pError) \
            OSL_ENSURE(sal_False, (ByteString(methodname) += ByteString(": ") += ByteString(pError)).GetBuffer());  \
    }
#else
#define CHECK_INVARIANTS(methodname)
#endif

//........................................................................
}   // namespace dbaui
//........................................................................

#endif // _DBACCESS_UI_DIRECTSQL_HXX_

<commit_msg>INTEGRATION: CWS ooo19126 (1.3.434); FILE MERGED 2005/09/05 17:34:49 rt 1.3.434.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: directsql.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 15:52:11 $
 *
 *  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
 *
 ************************************************************************/

#ifndef _DBACCESS_UI_DIRECTSQL_HXX_
#define _DBACCESS_UI_DIRECTSQL_HXX_

#ifndef _SV_DIALOG_HXX
#include <vcl/dialog.hxx>
#endif
#ifndef _SVEDIT_HXX
#include <svtools/svmedit.hxx>
#endif
#ifndef _SV_FIXED_HXX
#include <vcl/fixed.hxx>
#endif
#ifndef _SV_LSTBOX_HXX
#include <vcl/lstbox.hxx>
#endif
#ifndef _SV_BUTTON_HXX
#include <vcl/button.hxx>
#endif
#ifndef _COMPHELPER_STLTYPES_HXX_
#include <comphelper/stl_types.hxx>
#endif
#include <deque>

#ifndef _COM_SUN_STAR_SDBC_XCONNECTION_HPP_
#include <com/sun/star/sdbc/XConnection.hpp>
#endif
#ifndef _UNOTOOLS_EVENTLISTENERADAPTER_HXX_
#include <unotools/eventlisteneradapter.hxx>
#endif
#ifndef _OSL_MUTEX_HXX_
#include <osl/mutex.hxx>
#endif

//........................................................................
namespace dbaui
{
//........................................................................

    //====================================================================
    //= DirectSQLDialog
    //====================================================================
    class DirectSQLDialog
            :public ModalDialog
            ,public ::utl::OEventListenerAdapter
    {
    protected:
        ::osl::Mutex    m_aMutex;

        FixedLine       m_aFrame;
        FixedText       m_aSQLLabel;
        MultiLineEdit   m_aSQL;
        PushButton      m_aExecute;
        FixedText       m_aHistoryLabel;
        ListBox*        m_pSQLHistory;
        FixedLine       m_aStatusFrame;
        MultiLineEdit   m_aStatus;
        FixedLine       m_aButtonSeparator;
        HelpButton      m_aHelp;
        PushButton      m_aClose;

        typedef ::std::deque< String >  StringQueue;
        StringQueue     m_aStatementHistory;    // previous statements
        StringQueue     m_aNormalizedHistory;   // previous statements, normalized to be used in the list box

        sal_Int32       m_nHistoryLimit;
        sal_Int32       m_nStatusCount;

        ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >
                        m_xConnection;

    public:
        DirectSQLDialog(
            Window* _pParent,
            const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _rxConn);
        ~DirectSQLDialog();

        /// add an history entry
        void addHistoryEntry(const String& _rStatement);

        /// set the limit for the history size
        void setHistoryLimit(sal_Int32 _nMaxEntries);

        /// number of history entries
        sal_Int32 getHistorySize() const;

    protected:
        void executeCurrent();
        void switchToHistory(sal_Int32 _nHistoryPos, sal_Bool _bUpdateListBox = sal_True);

        // OEventListenerAdapter
        virtual void _disposing( const ::com::sun::star::lang::EventObject& _rSource );

    protected:
        DECL_LINK( OnExecute, void* );
        DECL_LINK( OnClose, void* );
        DECL_LINK( OnListEntrySelected, void* );
        DECL_LINK( OnStatementModified, void* );

    private:
        /// adds a statement to the statement history
        void implAddToStatementHistory(const String& _rStatement);

        /// ensures that our history has at most m_nHistoryLimit entries
        void implEnsureHistoryLimit();

        /// executes the statement given, adds the status to the status list
        void implExecuteStatement(const String& _rStatement);

        /// adds a status text to the status list
        void addStatusText(const String& _rMessage);

#ifdef DBG_UTIL
        const sal_Char* impl_CheckInvariants() const;
#endif
    };

    //====================================================================
#ifdef DBG_UTIL
#define CHECK_INVARIANTS(methodname)    \
    {   \
        const sal_Char* pError = impl_CheckInvariants();    \
        if (pError) \
            OSL_ENSURE(sal_False, (ByteString(methodname) += ByteString(": ") += ByteString(pError)).GetBuffer());  \
    }
#else
#define CHECK_INVARIANTS(methodname)
#endif

//........................................................................
}   // namespace dbaui
//........................................................................

#endif // _DBACCESS_UI_DIRECTSQL_HXX_

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: charsets.cxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 16:11:47 $
 *
 *  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
 *
 ************************************************************************/

#ifndef _DBAUI_CHARSETS_HXX_
#include "charsets.hxx"
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _DBU_MISCRES_HRC_
#include "dbumiscres.hrc"
#endif
#ifndef _DBU_MISC_HRC_
#include "dbu_misc.hrc"
#endif
#ifndef _RTL_TENCINFO_H
#include <rtl/tencinfo.h>
#endif
#ifndef _TOOLS_RCID_H
#include <tools/rcid.h>
#endif
#ifndef _DBAUI_LOCALRESACCESS_HXX_
#include "localresaccess.hxx"
#endif

//.........................................................................
namespace dbaui
{
//.........................................................................
    using namespace ::dbtools;

    //=========================================================================
    //= OCharsetDisplay
    //=========================================================================
    //-------------------------------------------------------------------------
    OCharsetDisplay::OCharsetDisplay()
        :OCharsetMap()
        ,SvxTextEncodingTable()
    {
        {
            OLocalResourceAccess aCharsetStrings( RSC_CHARSETS, RSC_RESOURCE );
            m_aSystemDisplayName = String( ResId( 1 ) );
        }
    }

    //-------------------------------------------------------------------------
    sal_Bool OCharsetDisplay::approveEncoding( const rtl_TextEncoding _eEncoding, const rtl_TextEncodingInfo& _rInfo ) const
    {
        if ( !OCharsetMap::approveEncoding( _eEncoding, _rInfo ) )
            return sal_False;

        if ( RTL_TEXTENCODING_DONTKNOW == _eEncoding )
            return sal_True;

        return 0 != GetTextString( _eEncoding ).Len();
    }

    //-------------------------------------------------------------------------
    OCharsetDisplay::const_iterator OCharsetDisplay::begin() const
    {
        return const_iterator( this, OCharsetMap::begin() );
    }

    //-------------------------------------------------------------------------
    OCharsetDisplay::const_iterator OCharsetDisplay::end() const
    {
        return const_iterator( this, OCharsetMap::end() );
    }

    //-------------------------------------------------------------------------
    OCharsetDisplay::const_iterator OCharsetDisplay::find(const rtl_TextEncoding _eEncoding) const
    {
        OCharsetMap::const_iterator aBaseIter = OCharsetMap::find(_eEncoding);
        return const_iterator( this, aBaseIter );
    }

    //-------------------------------------------------------------------------
    OCharsetDisplay::const_iterator OCharsetDisplay::find(const ::rtl::OUString& _rIanaName, const IANA&) const
    {
        OCharsetMap::const_iterator aBaseIter = OCharsetMap::find(_rIanaName, OCharsetMap::IANA());
        return const_iterator( this, aBaseIter );
    }

    //-------------------------------------------------------------------------
    OCharsetDisplay::const_iterator OCharsetDisplay::find(const ::rtl::OUString& _rDisplayName, const Display&) const
    {
        rtl_TextEncoding eEncoding = RTL_TEXTENCODING_DONTKNOW;
        if ( _rDisplayName != m_aSystemDisplayName )
        {
            eEncoding = GetTextEncoding( _rDisplayName );
            OSL_ENSURE( RTL_TEXTENCODING_DONTKNOW != eEncoding,
                "OCharsetDisplay::find: non-empty display name, but DONTKNOW!" );
        }
        return const_iterator( this, OCharsetMap::find( eEncoding ) );
    }

    //=========================================================================
    //= CharsetDisplayDerefHelper
    //=========================================================================
    //-------------------------------------------------------------------------
    CharsetDisplayDerefHelper::CharsetDisplayDerefHelper(const CharsetDisplayDerefHelper& _rSource)
        :CharsetDisplayDerefHelper_Base(_rSource)
        ,m_sDisplayName(m_sDisplayName)
    {
    }

    //-------------------------------------------------------------------------
    CharsetDisplayDerefHelper::CharsetDisplayDerefHelper(const CharsetDisplayDerefHelper_Base& _rBase, const ::rtl::OUString& _rDisplayName)
        :CharsetDisplayDerefHelper_Base(_rBase)
        ,m_sDisplayName(_rDisplayName)
    {
        DBG_ASSERT( m_sDisplayName.getLength(), "CharsetDisplayDerefHelper::CharsetDisplayDerefHelper: invalid display name!" );
    }

    //-------------------------------------------------------------------------
    CharsetDisplayDerefHelper::CharsetDisplayDerefHelper()
    {
    }

    //=========================================================================
    //= OCharsetDisplay::ExtendedCharsetIterator
    //=========================================================================
    //-------------------------------------------------------------------------
    OCharsetDisplay::ExtendedCharsetIterator::ExtendedCharsetIterator( const OCharsetDisplay* _pContainer, const base_iterator& _rPosition )
        :m_pContainer(_pContainer)
        ,m_aPosition(_rPosition)
    {
        DBG_ASSERT(m_pContainer, "OCharsetDisplay::ExtendedCharsetIterator::ExtendedCharsetIterator : invalid container!");
    }

    //-------------------------------------------------------------------------
    OCharsetDisplay::ExtendedCharsetIterator::ExtendedCharsetIterator(const ExtendedCharsetIterator& _rSource)
        :m_pContainer( _rSource.m_pContainer )
        ,m_aPosition( _rSource.m_aPosition )
    {
    }

    //-------------------------------------------------------------------------
    CharsetDisplayDerefHelper OCharsetDisplay::ExtendedCharsetIterator::operator*() const
    {
        DBG_ASSERT( m_aPosition != m_pContainer->OCharsetDisplay_Base::end(), "OCharsetDisplay::ExtendedCharsetIterator::operator* : invalid position!");

        rtl_TextEncoding eEncoding = (*m_aPosition).getEncoding();
        return CharsetDisplayDerefHelper(
            *m_aPosition,
            RTL_TEXTENCODING_DONTKNOW == eEncoding ? m_pContainer->m_aSystemDisplayName : (::rtl::OUString)m_pContainer->GetTextString( eEncoding )
        );
    }

    //-------------------------------------------------------------------------
    const OCharsetDisplay::ExtendedCharsetIterator& OCharsetDisplay::ExtendedCharsetIterator::operator++()
    {
        DBG_ASSERT( m_aPosition != m_pContainer->OCharsetDisplay_Base::end(), "OCharsetDisplay::ExtendedCharsetIterator::operator++ : invalid position!");
        if ( m_aPosition != m_pContainer->OCharsetDisplay_Base::end() )
            ++m_aPosition;
        return *this;
    }

    //-------------------------------------------------------------------------
    const OCharsetDisplay::ExtendedCharsetIterator& OCharsetDisplay::ExtendedCharsetIterator::operator--()
    {
        DBG_ASSERT( m_aPosition != m_pContainer->OCharsetDisplay_Base::begin(), "OCharsetDisplay::ExtendedCharsetIterator::operator-- : invalid position!");
        if ( m_aPosition != m_pContainer->OCharsetDisplay_Base::begin() )
            --m_aPosition;
        return *this;
    }

    //-------------------------------------------------------------------------
    bool operator==(const OCharsetDisplay::ExtendedCharsetIterator& lhs, const OCharsetDisplay::ExtendedCharsetIterator& rhs)
    {
        return (lhs.m_pContainer == rhs.m_pContainer) && (lhs.m_aPosition == rhs.m_aPosition);
    }

//.........................................................................
}   // namespace dbaui
//.........................................................................

<commit_msg>INTEGRATION: CWS dba203c (1.8.110); FILE MERGED 2006/03/29 11:35:43 fs 1.8.110.1: #133638# renamed ambiguous ::dbui::OLocalResourceAccess to LocalresourceAccess<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: charsets.cxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: rt $ $Date: 2006-05-04 08:45:40 $
 *
 *  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
 *
 ************************************************************************/

#ifndef _DBAUI_CHARSETS_HXX_
#include "charsets.hxx"
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _DBU_MISCRES_HRC_
#include "dbumiscres.hrc"
#endif
#ifndef _DBU_MISC_HRC_
#include "dbu_misc.hrc"
#endif
#ifndef _RTL_TENCINFO_H
#include <rtl/tencinfo.h>
#endif
#ifndef _TOOLS_RCID_H
#include <tools/rcid.h>
#endif
#ifndef _DBAUI_LOCALRESACCESS_HXX_
#include "localresaccess.hxx"
#endif

//.........................................................................
namespace dbaui
{
//.........................................................................
    using namespace ::dbtools;

    //=========================================================================
    //= OCharsetDisplay
    //=========================================================================
    //-------------------------------------------------------------------------
    OCharsetDisplay::OCharsetDisplay()
        :OCharsetMap()
        ,SvxTextEncodingTable()
    {
        {
            LocalResourceAccess aCharsetStrings( RSC_CHARSETS, RSC_RESOURCE );
            m_aSystemDisplayName = String( ResId( 1 ) );
        }
    }

    //-------------------------------------------------------------------------
    sal_Bool OCharsetDisplay::approveEncoding( const rtl_TextEncoding _eEncoding, const rtl_TextEncodingInfo& _rInfo ) const
    {
        if ( !OCharsetMap::approveEncoding( _eEncoding, _rInfo ) )
            return sal_False;

        if ( RTL_TEXTENCODING_DONTKNOW == _eEncoding )
            return sal_True;

        return 0 != GetTextString( _eEncoding ).Len();
    }

    //-------------------------------------------------------------------------
    OCharsetDisplay::const_iterator OCharsetDisplay::begin() const
    {
        return const_iterator( this, OCharsetMap::begin() );
    }

    //-------------------------------------------------------------------------
    OCharsetDisplay::const_iterator OCharsetDisplay::end() const
    {
        return const_iterator( this, OCharsetMap::end() );
    }

    //-------------------------------------------------------------------------
    OCharsetDisplay::const_iterator OCharsetDisplay::find(const rtl_TextEncoding _eEncoding) const
    {
        OCharsetMap::const_iterator aBaseIter = OCharsetMap::find(_eEncoding);
        return const_iterator( this, aBaseIter );
    }

    //-------------------------------------------------------------------------
    OCharsetDisplay::const_iterator OCharsetDisplay::find(const ::rtl::OUString& _rIanaName, const IANA&) const
    {
        OCharsetMap::const_iterator aBaseIter = OCharsetMap::find(_rIanaName, OCharsetMap::IANA());
        return const_iterator( this, aBaseIter );
    }

    //-------------------------------------------------------------------------
    OCharsetDisplay::const_iterator OCharsetDisplay::find(const ::rtl::OUString& _rDisplayName, const Display&) const
    {
        rtl_TextEncoding eEncoding = RTL_TEXTENCODING_DONTKNOW;
        if ( _rDisplayName != m_aSystemDisplayName )
        {
            eEncoding = GetTextEncoding( _rDisplayName );
            OSL_ENSURE( RTL_TEXTENCODING_DONTKNOW != eEncoding,
                "OCharsetDisplay::find: non-empty display name, but DONTKNOW!" );
        }
        return const_iterator( this, OCharsetMap::find( eEncoding ) );
    }

    //=========================================================================
    //= CharsetDisplayDerefHelper
    //=========================================================================
    //-------------------------------------------------------------------------
    CharsetDisplayDerefHelper::CharsetDisplayDerefHelper(const CharsetDisplayDerefHelper& _rSource)
        :CharsetDisplayDerefHelper_Base(_rSource)
        ,m_sDisplayName(m_sDisplayName)
    {
    }

    //-------------------------------------------------------------------------
    CharsetDisplayDerefHelper::CharsetDisplayDerefHelper(const CharsetDisplayDerefHelper_Base& _rBase, const ::rtl::OUString& _rDisplayName)
        :CharsetDisplayDerefHelper_Base(_rBase)
        ,m_sDisplayName(_rDisplayName)
    {
        DBG_ASSERT( m_sDisplayName.getLength(), "CharsetDisplayDerefHelper::CharsetDisplayDerefHelper: invalid display name!" );
    }

    //-------------------------------------------------------------------------
    CharsetDisplayDerefHelper::CharsetDisplayDerefHelper()
    {
    }

    //=========================================================================
    //= OCharsetDisplay::ExtendedCharsetIterator
    //=========================================================================
    //-------------------------------------------------------------------------
    OCharsetDisplay::ExtendedCharsetIterator::ExtendedCharsetIterator( const OCharsetDisplay* _pContainer, const base_iterator& _rPosition )
        :m_pContainer(_pContainer)
        ,m_aPosition(_rPosition)
    {
        DBG_ASSERT(m_pContainer, "OCharsetDisplay::ExtendedCharsetIterator::ExtendedCharsetIterator : invalid container!");
    }

    //-------------------------------------------------------------------------
    OCharsetDisplay::ExtendedCharsetIterator::ExtendedCharsetIterator(const ExtendedCharsetIterator& _rSource)
        :m_pContainer( _rSource.m_pContainer )
        ,m_aPosition( _rSource.m_aPosition )
    {
    }

    //-------------------------------------------------------------------------
    CharsetDisplayDerefHelper OCharsetDisplay::ExtendedCharsetIterator::operator*() const
    {
        DBG_ASSERT( m_aPosition != m_pContainer->OCharsetDisplay_Base::end(), "OCharsetDisplay::ExtendedCharsetIterator::operator* : invalid position!");

        rtl_TextEncoding eEncoding = (*m_aPosition).getEncoding();
        return CharsetDisplayDerefHelper(
            *m_aPosition,
            RTL_TEXTENCODING_DONTKNOW == eEncoding ? m_pContainer->m_aSystemDisplayName : (::rtl::OUString)m_pContainer->GetTextString( eEncoding )
        );
    }

    //-------------------------------------------------------------------------
    const OCharsetDisplay::ExtendedCharsetIterator& OCharsetDisplay::ExtendedCharsetIterator::operator++()
    {
        DBG_ASSERT( m_aPosition != m_pContainer->OCharsetDisplay_Base::end(), "OCharsetDisplay::ExtendedCharsetIterator::operator++ : invalid position!");
        if ( m_aPosition != m_pContainer->OCharsetDisplay_Base::end() )
            ++m_aPosition;
        return *this;
    }

    //-------------------------------------------------------------------------
    const OCharsetDisplay::ExtendedCharsetIterator& OCharsetDisplay::ExtendedCharsetIterator::operator--()
    {
        DBG_ASSERT( m_aPosition != m_pContainer->OCharsetDisplay_Base::begin(), "OCharsetDisplay::ExtendedCharsetIterator::operator-- : invalid position!");
        if ( m_aPosition != m_pContainer->OCharsetDisplay_Base::begin() )
            --m_aPosition;
        return *this;
    }

    //-------------------------------------------------------------------------
    bool operator==(const OCharsetDisplay::ExtendedCharsetIterator& lhs, const OCharsetDisplay::ExtendedCharsetIterator& rhs)
    {
        return (lhs.m_pContainer == rhs.m_pContainer) && (lhs.m_aPosition == rhs.m_aPosition);
    }

//.........................................................................
}   // namespace dbaui
//.........................................................................

<|endoftext|>


<commit_before>#include <iostream>
#include <iomanip>
#include <string>
#include <openssl/sha.h>

using namespace std;
#define HASHSIZE 32

string getCutHex(unsigned char hash[HASHSIZE]) {
	string base64Index = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!#";
	string output = "";

	for (int i = 0; i < 12; i+=3) {
		output += base64Index[hash[i+0]>>2];
		output += base64Index[((hash[i+0]&0x03)<<4) + (hash[i+1]>>4)];
		output += base64Index[((hash[i+1]&0x0F)<<2) + (hash[i+2]>>6)];
		output += base64Index[hash[i+2] & 0x3F];
	}

	return output;
}

string getPassword(string masterpass, string domain) {
	string prehash = masterpass+domain;
	unsigned char hash[HASHSIZE];
	SHA256((unsigned char*)prehash.c_str(), prehash.size(), hash);

	getCutHex(hash);

	//unsigned char hash[20];
	return prehash;
}

void help() {
	cout << "THIS IS THE HELP PAGE" << endl;
}

int main(int argc, char* argv[]) {
	// check to make sure there are enough arguments
	// if (argc < 3) {
	// 	cout << "you must specify a username with -u" << endl;
	// 	help();
	// 	return 0;
	// }

	bool silent = false;
	bool passwordFlag = false;
	string domain = "";
	string password = "";
	string *pointer = NULL;

	for (int i = 1; i < argc; i++) {
		if (string(argv[i]) == "-p") { // password flag
			pointer = &password;
		}
		else if (string(argv[i]) == "-d") { // domain flag
			pointer = &domain;
		}
		else if (string(argv[i]) == "-s") { // silent flag
			silent = true;
		}
		else if (string(argv[i]) == "-h") { // help flag
			cout << "triggered on the help flag" << endl;
			help();
			return 0;
		}
		else {
			if (pointer == NULL) {
				cout << "triggered on bad argument " << argv[i] << endl;
				help();
				return 0;
			}
		}
	}

	if (passwordFlag && !silent) {
		cout <<"WARNING: you should not use the -p flag as it may be insecure" << endl;
	}

	getPassword ("harvy","dent");

	cout << "DONE!" << endl;
}<commit_msg>tested support of domain input<commit_after>#include <iostream>
#include <iomanip>
#include <string>
#include <openssl/sha.h>

using namespace std;
#define HASHSIZE 32

string getCutHex(unsigned char hash[HASHSIZE]) {
	string base64Index = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!#";
	string output = "";

	for (int i = 0; i < 12; i+=3) {
		output += base64Index[hash[i+0]>>2];
		output += base64Index[((hash[i+0]&0x03)<<4) + (hash[i+1]>>4)];
		output += base64Index[((hash[i+1]&0x0F)<<2) + (hash[i+2]>>6)];
		output += base64Index[hash[i+2] & 0x3F];
	}

	return output;
}

string getPassword(string masterpass, string domain) {
	string prehash = masterpass+domain;
	unsigned char hash[HASHSIZE];
	SHA256((unsigned char*)prehash.c_str(), prehash.size(), hash);

	getCutHex(hash);

	//unsigned char hash[20];
	return prehash;
}

void help() {
	cout << "THIS IS THE HELP PAGE" << endl;
}

int main(int argc, char* argv[]) {
	// check to make sure there are enough arguments
	// if (argc < 3) {
	// 	cout << "you must specify a username with -u" << endl;
	// 	help();
	// 	return 0;
	// }

	bool silent = false;
	bool passwordFlag = false;
	string domain = "";
	string password = "";
	string *pointer = NULL;

	for (int i = 1; i < argc; i++) {
		if (string(argv[i]) == "-p") { // password flag
			pointer = &password;
		}
		else if (string(argv[i]) == "-d") { // domain flag
			pointer = &domain;
		}
		else if (string(argv[i]) == "-s") { // silent flag
			silent = true;
		}
		else if (string(argv[i]) == "-h") { // help flag
			cout << "triggered on the help flag" << endl;
			help();
			return 0;
		}
		else {
			if (pointer == NULL) {
				cout << "triggered on bad argument " << argv[i] << endl;
				help();
				return 0;
			}
			else {
				*pointer += argv[i];
			}
		}
	}

	if (passwordFlag && !silent) {
		cout <<"WARNING: you should not use the -p flag as it may be insecure" << endl;
	}

	cout << "domain is: " << domain << endl;
	cout << "password is: " << password << endl;
	getPassword ("harvy","dent");

	cout << "DONE!" << endl;
}<|endoftext|>


<commit_before>#ifndef RECURSE_REQUEST_HPP
#define RECURSE_REQUEST_HPP

#include <QTcpSocket>
#include <QHash>
#include <QUrl>
#include <QUrlQuery>

class Request
{

public:
    //!
    //! \brief data
    //! client request buffer data
    //!
    QString data;

    //!
    //! \brief socket
    //! underlying client socket
    //!
    QTcpSocket *socket;

    //!
    //! \brief body_parsed
    //! Data to be filled by body parsing middleware
    //!
    QHash<QString, QVariant> body_parsed;

    //!
    //! \brief body
    //!
    QString body;

    //!
    //! \brief method
    //! HTTP method, eg: GET
    //!
    QString method;

    //!
    //! \brief protocol
    //! Request protocol, eg: HTTP
    //!
    QString protocol;

    //!
    //! \brief secure
    //! Shorthand for protocol == "HTTPS" to check if a requet was issued via TLS
    //!
    bool secure = protocol == "HTTPS";

    //!
    //! \brief url
    //! HTTP request url, eg: /helloworld
    //!
    QUrl url;

    //!
    //! \brief query
    //! query strings
    //!
    QUrlQuery query;

    //!
    //! \brief params
    //!r
    //! request parameters that can be filled by router middlewares
    //! it's easier to provide container here (which doesn't have to be used)
    QHash<QString, QString> params;

    //!
    //! \brief length
    //! HTTP request Content-Length
    //!
    qint64 length = 0;

    //!
    //! \brief ip
    //! Client ip address
    //!
    QHostAddress ip;

    //!
    //! \brief cookies
    //! HTTP cookies in key/value form
    //!
    QHash<QString, QString> cookies;

    //!
    //! \brief hostname
    //! HTTP hostname from "Host" HTTP header
    //!
    QString hostname;

    //!
    //! \brief get
    //! Return HTTP request header specified by the key
    //!
    //! \param QString case-insensitive key of the header
    //! \return QString header value
    //!
    QString get(const QString &key)
    {
        return m_header[key.toLower()];
    }

    //!
    //! \brief parse
    //! parse data from request
    //!
    //! \param QString request
    //! \return true on success, false otherwise, considered bad request
    //!
    bool parse(QString request);

private:
    //!
    //! \brief header
    //! HTTP request headers, eg: header["content-type"] = "text/plain"
    //!
    QHash<QString, QString> m_header;

    //!
    //! \brief httpRx
    //! match HTTP request line
    //!
    QRegExp httpRx = QRegExp("^(?=[A-Z]).* \\/.* HTTP\\/[0-9]\\.[0-9]\\r\\n");
};

inline bool Request::parse(QString request)
{
    // buffer all data
    this->data += request;

    // Save client ip address
    this->ip = this->socket->peerAddress();

    // if no header is present, just append all data to request.body
    if (!this->data.contains(httpRx))
    {
        this->body.append(this->data);
        return true;
    }

    QStringList data_list = this->data.split("\r\n");
    bool is_body = false;

    for (int i = 0; i < data_list.size(); ++i)
    {
        if (is_body)
        {
            this->body.append(data_list.at(i));
            this->length += this->body.size();
            continue;
        }

        QStringList entity_item = data_list.at(i).split(":");

        if (entity_item.length() < 2 && entity_item.at(0).size() < 1 && !is_body)
        {
            is_body = true;
            continue;
        }
        else if (i == 0 && entity_item.length() < 2)
        {
            QStringList first_line = entity_item.at(0).split(" ");
            this->method = first_line.at(0);
            this->url = first_line.at(1).trimmed();
            this->query.setQuery(this->url.query());
            this->protocol = first_line.at(2).trimmed();
            continue;
        }

        m_header[entity_item.at(0).toLower()] = entity_item.at(1).trimmed().toLower();
    }

    if (m_header.contains("host"))
        this->hostname = m_header["host"];

    // extract cookies
    // eg: USER_TOKEN=Yes;test=val
    if (m_header.contains("cookie"))
    {
        for (const QString &cookie : this->get("cookie").split(";"))
        {
            int split = cookie.trimmed().indexOf("=");
            if (split == -1)
                continue;

            QString key = cookie.left(split).trimmed();
            if (!key.size())
                continue;

            QString value = cookie.mid(split + 1).trimmed();

            this->cookies[key.toLower()] = value.toLower();
        }
    }

    return true;
}

#endif
<commit_msg>performance improvements<commit_after>#ifndef RECURSE_REQUEST_HPP
#define RECURSE_REQUEST_HPP

#include <QTcpSocket>
#include <QHash>
#include <QUrl>
#include <QUrlQuery>

class Request
{

public:
    //!
    //! \brief data
    //! client request buffer data
    //!
    QString data;

    //!
    //! \brief socket
    //! underlying client socket
    //!
    QTcpSocket *socket;

    //!
    //! \brief body_parsed
    //! Data to be filled by body parsing middleware
    //!
    QHash<QString, QVariant> body_parsed;

    //!
    //! \brief body
    //!
    QString body;

    //!
    //! \brief method
    //! HTTP method, eg: GET
    //!
    QString method;

    //!
    //! \brief protocol
    //! Request protocol, eg: HTTP
    //!
    QString protocol;

    //!
    //! \brief secure
    //! Shorthand for protocol == "HTTPS" to check if a requet was issued via TLS
    //!
    bool secure = protocol == "HTTPS";

    //!
    //! \brief url
    //! HTTP request url, eg: /helloworld
    //!
    QUrl url;

    //!
    //! \brief query
    //! query strings
    //!
    QUrlQuery query;

    //!
    //! \brief params
    //!r
    //! request parameters that can be filled by router middlewares
    //! it's easier to provide container here (which doesn't have to be used)
    QHash<QString, QString> params;

    //!
    //! \brief length
    //! HTTP request Content-Length
    //!
    qint64 length = 0;

    //!
    //! \brief ip
    //! Client ip address
    //!
    QHostAddress ip;

    //!
    //! \brief cookies
    //! HTTP cookies in key/value form
    //!
    QHash<QString, QString> cookies;

    //!
    //! \brief hostname
    //! HTTP hostname from "Host" HTTP header
    //!
    QString hostname;

    //!
    //! \brief get
    //! Return HTTP request header specified by the key
    //!
    //! \param QString case-insensitive key of the header
    //! \return QString header value
    //!
    QString get(const QString &key)
    {
        return m_header[key.toLower()];
    }

    //!
    //! \brief parse
    //! parse data from request
    //!
    //! \param QString request
    //! \return true on success, false otherwise, considered bad request
    //!
    bool parse(QString request);

private:
    //!
    //! \brief header
    //! HTTP request headers, eg: header["content-type"] = "text/plain"
    //!
    QHash<QString, QString> m_header;

    //!
    //! \brief httpRx
    //! match HTTP request line
    //!
    QRegExp httpRx = QRegExp("^(?=[A-Z]).* \\/.* HTTP\\/[0-9]\\.[0-9]\\r\\n");
};

inline bool Request::parse(QString request)
{
    // buffer all data
    this->data += request;

    // Save client ip address
    this->ip = this->socket->peerAddress();

    // if no header is present, just append all data to request.body
    if (!this->data.contains(httpRx))
    {
        this->body.append(this->data);
        return true;
    }

    auto data_list = this->data.splitRef("\r\n");
    bool is_body = false;

    for (int i = 0; i < data_list.size(); ++i)
    {
        if (is_body)
        {
            this->body.append(data_list.at(i));
            this->length += this->body.size();
            continue;
        }

        auto entity_item = data_list.at(i).split(":");

        if (entity_item.length() < 2 && entity_item.at(0).size() < 1 && !is_body)
        {
            is_body = true;
            continue;
        }
        else if (i == 0 && entity_item.length() < 2)
        {
            auto first_line = entity_item.at(0).split(" ");
            this->method = first_line.at(0).toString();
            this->url = first_line.at(1).toString();
            this->query.setQuery(this->url.query());
            this->protocol = first_line.at(2).toString();
            continue;
        }

        m_header[entity_item.at(0).toString()] = entity_item.at(1).toString();
    }

    if (m_header.contains("host"))
        this->hostname = m_header["host"];

    // extract cookies
    // eg: USER_TOKEN=Yes;test=val
    if (m_header.contains("cookie"))
    {
        for (const auto &cookie : this->get("cookie").splitRef(";"))
        {
            int split = cookie.indexOf("=");
            if (split == -1)
                continue;

            auto key = cookie.left(split);
            if (!key.size())
                continue;

            auto value = cookie.mid(split + 1);

            this->cookies[key.toString().toLower()] = value.toString().toLower();
        }
    }

    return true;
}

#endif
<|endoftext|>


<commit_before>/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * Written (W) 2011-2012 Heiko Strathmann
 * Copyright (C) 2011 Berlin Institute of Technology and Max-Planck-Society
 * Written (W) 2012 Victor Sadkov
 * Copyright (C) 2011 Moscow State University
 */

#include <shogun/base/init.h>
#include <shogun/mathematics/Statistics.h>
#include <shogun/mathematics/Math.h>

using namespace shogun;

void test_confidence_intervals()
{
	int32_t data_size=100;
	SGVector<float64_t> data(data_size);

	CMath::random_vector(data.vector, data.vlen, 0.0, 1.0);

	float64_t low, up, mean;
	float64_t error_prob=0.1;
	mean=CStatistics::confidence_intervals_mean(data, error_prob, low, up);

	SG_SPRINT("sample mean: %f. True mean lies in [%f,%f] with %f%%\n",
			mean, low, up, 100*(1-error_prob));

	SG_SPRINT("variance: %f\n", CStatistics::variance(data));
	SG_SPRINT("deviation: %f\n", CStatistics::std_deviation(data));
}

void test_inverse_incomplete_gamma()
{
	/* some tests for high precision MATLAB comparison */
	float64_t difference=CStatistics::inverse_incomplete_gamma(1, 1-0.95)*2;
	difference-=5.991464547107981;
	difference=CMath::abs(difference);
	ASSERT(difference<=10E-15);

	difference=CStatistics::inverse_incomplete_gamma(0, 1-0.95)*3;
	ASSERT(difference==0);

	difference=CStatistics::inverse_incomplete_gamma(2, 1-0.95)*0.1;
	difference-=0.474386451839058;
	difference=CMath::abs(difference);
	ASSERT(difference<=10E-15)
}

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

	test_confidence_intervals();
	test_inverse_incomplete_gamma();

	exit_shogun();

	return 0;
}

<commit_msg>fixed a non-terminating test case<commit_after>/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * Written (W) 2011-2012 Heiko Strathmann
 * Copyright (C) 2011 Berlin Institute of Technology and Max-Planck-Society
 * Written (W) 2012 Victor Sadkov
 * Copyright (C) 2011 Moscow State University
 */

#include <shogun/base/init.h>
#include <shogun/mathematics/Statistics.h>
#include <shogun/mathematics/Math.h>

using namespace shogun;

void test_confidence_intervals()
{
	int32_t data_size=100;
	SGVector<float64_t> data(data_size);

	CMath::random_vector(data.vector, data.vlen, 0.0, 1.0);

	float64_t low, up, mean;
	float64_t error_prob=0.1;
	mean=CStatistics::confidence_intervals_mean(data, error_prob, low, up);

	SG_SPRINT("sample mean: %f. True mean lies in [%f,%f] with %f%%\n",
			mean, low, up, 100*(1-error_prob));

	SG_SPRINT("variance: %f\n", CStatistics::variance(data));
	SG_SPRINT("deviation: %f\n", CStatistics::std_deviation(data));
}

void test_inverse_incomplete_gamma()
{
	/* some tests for high precision MATLAB comparison */
	float64_t difference=CStatistics::inverse_incomplete_gamma(1, 1-0.95)*2;
	difference-=5.991464547107981;
	difference=CMath::abs(difference);
	ASSERT(difference<=10E-15);

	difference=CStatistics::inverse_incomplete_gamma(0.1, 1-0.95)*3;
	difference-=1.741305315969402;
	difference=CMath::abs(difference);
	ASSERT(difference<=10E-15)

	difference=CStatistics::inverse_incomplete_gamma(2, 1-0.95)*0.1;
	difference-=0.474386451839058;
	difference=CMath::abs(difference);
	ASSERT(difference<=10E-15)
}

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

	test_confidence_intervals();
	test_inverse_incomplete_gamma();

	exit_shogun();

	return 0;
}

<|endoftext|>


<commit_before>#include "clm.h"

void JelinekMercerFeature::set_interpolation(float lambda) {
  this->_bigram_contribution = 1.0 - lambda;
  this->_unigram_contribution = lambda;
}

float JelinekMercerFeature::interpolation() const {
    return this->_unigram_contribution;
}

void JelinekMercerFeature::set_slop(int slop) {
  assert(slop >= 0);
  _slop = slop;
}

void JelinekMercerFeature::set_censor_slop(bool censor_slop) {
  _censor_slop = censor_slop;
}

bool JelinekMercerFeature::censor_slop() const {
  return _censor_slop;
}

int JelinekMercerFeature::slop() const {
  return _slop;
}

void JelinekMercerFeature::set_cutoff(float cutoff) {
  _cutoff = cutoff;
}

float JelinekMercerFeature::cutoff() const {
  return _cutoff;
}

void JelinekMercerFeature::set_score(bool score) {
  _score = score;
}

bool JelinekMercerFeature::score() const {
  return _score;
}

void JelinekMercerFeature::set_log_length(bool log_length) {
  _log_length = log_length;
}

bool JelinekMercerFeature::log_length() const {
  return _log_length;
}

void JelinekMercerFeature::set_min_span(int span) {
  _min_span = span;
}

int JelinekMercerFeature::min_span() const {
  return _min_span;
}

void JelinekMercerFeature::set_min_start_rank(int rank) {
  _min_start_rank = rank;
}

int JelinekMercerFeature::min_start_rank() const {
  return _min_start_rank;
}

void JelinekMercerFeature::set_smooth(float smooth) {
  assert(smooth > 0.0);
  _smooth = smooth;
  _smooth_norm = smooth * (float)_vocab;
}

float JelinekMercerFeature::smooth() const {
  return _smooth;
}

void JelinekMercerFeature::add_stop(int word) {
  _stopwords.insert(word);
}

void JelinekMercerFeature::read_vocab(const std::string filename) {
  std::ifstream infile;
  infile.open(filename.c_str());

  int type;
  int count;
  int contexts;
  int next;
  std::string word;

  infile >> _corpora;

  infile >> _vocab;
  _types.resize(_vocab);
  _corpus_names.resize(_corpora);
  for (int ii=0; ii < _vocab; ++ii) {
    infile >> word;
    _types[ii] = word;
    if (ii % 25000 == 0)
      std::cout << "Read vocab " << word << " (" << ii << "/" << _vocab << ")" << std::endl;
  }

  this->_unigram.resize(_corpora);
  this->_bigram.resize(_corpora);
  this->_normalizer.resize(_corpora);
  this->_compare.resize(_corpora);

  /*
   * Size the counts appropriately
   */
  for (int cc=0; cc < _corpora; ++cc) {
    infile >> _corpus_names[cc];
    infile >> _compare[cc];
    _normalizer[cc] = 0;
  }
  std::cout << "Done reading " << _vocab << " vocab from " << _corpora << " corpora" << std::endl;
}

/*
 * Read in a protocol buffers contents and add to counts
 */
void JelinekMercerFeature::read_counts(const std::string filename) {
  std::cout << "reading corpus from " << filename << " (";
  std::ifstream infile;
  infile.open(filename.c_str());

  int corpus_id;
  std::string corpus_name;
  int num_contexts;

  infile >> corpus_name;
  infile >> corpus_id;
  infile >> num_contexts;
  std::cout << corpus_name << "," << corpus_id << ")" << std::endl;
  assert(_corpora > 0);

  assert(_normalizer[corpus_id] == 0.0);
  for (int vv=0; vv < num_contexts; ++vv) {
    // Set unigram counts
    int total;
    int first;
    int num_bigrams;
    std::string word;

    infile >> word;
    infile >> first;
    infile >> total;
    infile >> num_bigrams;
    _normalizer[corpus_id] += (float)total;
    _unigram[corpus_id][first] = total;
    assert(word == _types[first]);

    for (int bb=0; bb < num_bigrams; ++bb) {
      int second;
      int count;
      infile >> second;
      infile >> count;

      _bigram[corpus_id][bigram(first, second)] = count;
    }
  }
  infile.close();
}

int JelinekMercerFeature::bigram_count(int corpus, int first, int second) {
  bigram key = bigram(first, second);
  if (_bigram[corpus].find(key) == _bigram[corpus].end()) return 0;
  else return _bigram[corpus][key];
}

int JelinekMercerFeature::unigram_count(int corpus, int word) {
  if (_unigram[corpus].find(word) == _unigram[corpus].end()) return 0;
  else return _unigram[corpus][word];
}

int JelinekMercerFeature::sum(int *first, int nitems) {
    int i, sum = 0;
    for (i = 0; i < nitems; i++) {
        sum += first[i];
    }
    return sum;
}

const std::string JelinekMercerFeature::feature(const std::string name,
						int corpus, int *sent,
						int length) {
  assert(length > 0);
  assert(corpus < _corpora);
  int baseline = _compare[corpus];

  // Create vectors to hold probabilities and masks
  _slop_mask.resize(length);
  std::fill(_slop_mask.begin(), _slop_mask.end(), false);
  _span_mask.resize(length);
  _span_start.resize(length);
  _d_bigram.resize(length);
  _b_bigram.resize(length);
  _d_unigram.resize(length);
  _b_unigram.resize(length);

  // Step 1: find the spans
  // Consider the first word part of a span unless it's very frequent
  // This will also contribute to the overall likelihood computation later
  _span_mask[0] = true;

  // Extend from the first position.  Also compute the total likelihood while
  // we're at it.
  for (int ii=1; ii < length; ++ii) {
    if (this->bigram_count(corpus, sent[ii - 1], sent[ii]) > 0) {
      // The current word is only true if the previous word was or it isn't
      // too frequent.
      _span_mask[ii] = _span_mask[ii - 1] ||
          (sent[ii] >= _min_start_rank && _stopwords.find(sent[ii]) == _stopwords.end());
    } else {
      _span_mask[ii] = false;
    }
  }

  if (kDEBUG) {
    for (int ii=0; ii < length; ++ii) {
      if (_span_mask[ii]) std::cout << "\t" << "+" << _types[sent[ii]];
      else std::cout << "\t" << "-" << _types[sent[ii]];
    }
    std::cout << "\t<- tokens/mask" << std::endl;
  }

  // Filter spans that end with high-frequency words
  for (int ii=length; ii >= 0; --ii) {
    if (_span_mask[ii] && // It is in a span
	(ii==length || !_span_mask[ii+1]) && // at the end
	sent[ii] < _min_start_rank) {// and is high frequency
      _span_mask[ii] = false; // Then remove it from span
    }
  }

  // Add back in slop
  if (_slop > 0) {
    int position = 2;
    while (position < length - 1) {
      // Could this position expand a run if we had slop?
      if (_span_mask[position - 1] && !_span_mask[position]) {
        int slop_left = _slop;

        for (int ii=position; ii < std::min(position + _slop, length - 1); ++ii) {
          // If this is a LM hit, then
          // mark all positions before it as a slop position
          if (!_span_mask[ii]) {
            _slop_mask[ii] = true;
            --slop_left;
          }

          if (slop_left == 0) break;
          position = ii;
        }
        ++position;
      } else {
        // There's no run to expand, so just move onto the next position.
        ++position;
      }
    }
  }

  // For each element in the span, figure out where its span begins and compute
  // probabilities.
  _b_unigram[0] = this->score(baseline, -1, sent[0]);
  _d_unigram[0] = this->score(corpus, -1, sent[0]);
  float complete_prob = _d_unigram[0] - _b_unigram[0];

  int start = -1;
  for (int ii=0; ii < length; ++ii) {
    // Do we end a span?
    if (!(_span_mask[ii] || _slop_mask[ii])) {
      start = -1;
    } else {
      // Do we start a new one?
      if (start < 0) start = ii;
      // If we're in a span, we'll want unigram probabilities
      _d_unigram[ii] = this->score(corpus, -1, sent[ii]);
      _b_unigram[ii] = this->score(baseline, -1, sent[ii]);
    }
    _span_start[ii] = start;

    // save the probabilities for later span calculations
    _d_bigram[ii] = this->score(corpus, sent[ii - 1], sent[ii]);
    _b_bigram[ii] = this->score(baseline, sent[ii - 1], sent[ii]);
    complete_prob += _d_bigram[ii] - _b_bigram[ii];
  }

  if (kDEBUG) {
    std::cout << "\tX";
    for (int ii=1; ii < length; ++ii)
      std::cout << "\t" << this->bigram_count(corpus, sent[ii-1], sent[ii]);
    std::cout << std::endl;

    for (int ii=0; ii < length; ++ii) {
      if (_span_mask[ii]) std::cout << "\t" << "+";
      else std::cout << "\t" << "-";
    }
    std::cout << "\t<- revision" << std::endl;

    for (int ii=0; ii < length; ++ii) {
      if (_slop_mask[ii]) std::cout << "\t" << "+";
      else std::cout << "\t" << "-";
    }
    std::cout << "\t<- slop" << std::endl;

    for (int ii=0; ii < length; ++ii) std::cout << "\t" << _span_start[ii];
    std::cout << "\t<- start" << std::endl;

    for (int ii=0; ii < length; ++ii) std::cout << std::setprecision(3) << "\t" << _d_bigram[ii];
    std::cout << "\t<- domain bigram" << std::endl;

    for (int ii=0; ii < length; ++ii) std::cout << "\t" << std::setprecision(3) << _b_bigram[ii];
    std::cout << "\t<- base bigram" << std::endl;

    for (int ii=0; ii < length; ++ii) std::cout << "\t" << this->unigram_count(corpus, sent[ii]);
    std::cout << "\t<- domain unigram count" << std::endl;

    for (int ii=0; ii < length; ++ii) std::cout << "\t" << this->unigram_norm(corpus);
    std::cout << "\t<- domain unigram norm" << std::endl;

    for (int ii=0; ii < length; ++ii) std::cout << std::setprecision(3) << "\t" << _d_unigram[ii];
    std::cout << "\t<- domain unigram" << std::endl;

    for (int ii=0; ii < length; ++ii) std::cout << "\t" << std::setprecision(3) << _b_unigram[ii];
    std::cout << "\t<- base unigram" << std::endl;
  }

  // Now we can output the feature and compute the probability of spans
  std::ostringstream buffer;
  buffer << std::fixed;
  buffer << std::setprecision(2);
  int longest_span  = 0;
  float max_prob = 0;
  for (int ii=1; ii < length; ++ii) {
    if (_span_start[ii] >= 0) {
      if (ii - _span_start[ii] >= longest_span)
	longest_span = ii - _span_start[ii] + 1;

      // Skip if it's too short
      if (ii - _span_start[ii] < _min_span - 1) continue;

      for (int start = _span_start[ii]; start <= ii - _min_span; ++start) {
        float span_probability;
        if (_stopwords.find(sent[start]) != _stopwords.end()) continue;

        span_probability = _d_unigram[start] - _b_unigram[start];

        // First compute the span probabilities
        for (int jj = start + 1; jj <= ii; ++jj) {
          span_probability += _d_bigram[jj] - _b_bigram[jj];
        }

        if (span_probability > _cutoff) {
          if (span_probability > max_prob) max_prob = span_probability;
          buffer << _corpus_names[corpus];
          for (int jj = start; jj <= ii; ++jj) {
            buffer << "_";
            if (_censor_slop && _slop_mask[jj]) buffer << "SLOP";
            else buffer << sent[jj];
          }
          if (_score) {
            buffer << ":";
            buffer << span_probability;
          }
          buffer << " ";
        }
      }
    }
  }

  // Output the probability
  if (_score) {
    buffer << name;
    buffer << "_PROB:";
    buffer << complete_prob / ((float)length);

    buffer << " ";
    buffer << name;
    buffer << "_MAX:";
    buffer << max_prob;
    buffer << " ";
  }

  buffer << name;
  buffer << "_LEN:";
  buffer << longest_span;

  if (_log_length) {
    buffer << " " << name;
    buffer << "_LGLEN:";
    buffer << log(1 + longest_span);
  }

  return buffer.str();
}

float JelinekMercerFeature::unigram_norm(int corpus) {
  return (float)this->_normalizer[corpus] + _smooth_norm;
}

float JelinekMercerFeature::score(int corpus, int first, int second) {
  // Store the unigram probability in the score
  float unigram_num = (float)this->unigram_count(corpus, second) + _smooth;
  float unigram_den = this->unigram_norm(corpus);
  float score = unigram_num / unigram_den;

  if (kDEBUG) {
    std::cout << _corpus_names[corpus] << " LL for " << first;
    //if (first >= 0) std::cout << "(" << _types[first] << ")";
    std::cout << " " << second << "(" << _types[second] << ")" << std::endl;
    std::cout << "UNI:" << unigram_num << "/" << unigram_den << "=" << score << std::endl;
  }

  if (first >= 0) { // first == -1 means we just want unigram probability
    int bigram_den = this->unigram_count(corpus, first);
    int bigram_num = this->bigram_count(corpus, first, second);
    if (bigram_den == 0 || bigram_num == 0) {
      score *= _unigram_contribution;
    } else {
      score = this->_bigram_contribution * (float)bigram_num / (float)bigram_den +
	_unigram_contribution * score;
    }
  }

  if (kDEBUG) {
    std::cout << "Final:" << log(score) << std::endl;
  }

  return log(score);
}
<commit_msg>shorten lines<commit_after>#include "clm.h"

void JelinekMercerFeature::set_interpolation(float lambda) {
  this->_bigram_contribution = 1.0 - lambda;
  this->_unigram_contribution = lambda;
}

float JelinekMercerFeature::interpolation() const {
    return this->_unigram_contribution;
}

void JelinekMercerFeature::set_slop(int slop) {
  assert(slop >= 0);
  _slop = slop;
}

void JelinekMercerFeature::set_censor_slop(bool censor_slop) {
  _censor_slop = censor_slop;
}

bool JelinekMercerFeature::censor_slop() const {
  return _censor_slop;
}

int JelinekMercerFeature::slop() const {
  return _slop;
}

void JelinekMercerFeature::set_cutoff(float cutoff) {
  _cutoff = cutoff;
}

float JelinekMercerFeature::cutoff() const {
  return _cutoff;
}

void JelinekMercerFeature::set_score(bool score) {
  _score = score;
}

bool JelinekMercerFeature::score() const {
  return _score;
}

void JelinekMercerFeature::set_log_length(bool log_length) {
  _log_length = log_length;
}

bool JelinekMercerFeature::log_length() const {
  return _log_length;
}

void JelinekMercerFeature::set_min_span(int span) {
  _min_span = span;
}

int JelinekMercerFeature::min_span() const {
  return _min_span;
}

void JelinekMercerFeature::set_min_start_rank(int rank) {
  _min_start_rank = rank;
}

int JelinekMercerFeature::min_start_rank() const {
  return _min_start_rank;
}

void JelinekMercerFeature::set_smooth(float smooth) {
  assert(smooth > 0.0);
  _smooth = smooth;
  _smooth_norm = smooth * (float)_vocab;
}

float JelinekMercerFeature::smooth() const {
  return _smooth;
}

void JelinekMercerFeature::add_stop(int word) {
  _stopwords.insert(word);
}

void JelinekMercerFeature::read_vocab(const std::string filename) {
  std::ifstream infile;
  infile.open(filename.c_str());

  int type;
  int count;
  int contexts;
  int next;
  std::string word;

  infile >> _corpora;

  infile >> _vocab;
  _types.resize(_vocab);
  _corpus_names.resize(_corpora);
  for (int ii=0; ii < _vocab; ++ii) {
    infile >> word;
    _types[ii] = word;
    if (ii % 25000 == 0)
      std::cout << "Read vocab " << word << " (" << ii << "/" << _vocab << ")" << std::endl;
  }

  this->_unigram.resize(_corpora);
  this->_bigram.resize(_corpora);
  this->_normalizer.resize(_corpora);
  this->_compare.resize(_corpora);

  /*
   * Size the counts appropriately
   */
  for (int cc=0; cc < _corpora; ++cc) {
    infile >> _corpus_names[cc];
    infile >> _compare[cc];
    _normalizer[cc] = 0;
  }
  std::cout << "Done reading " << _vocab << " vocab from " << _corpora << " corpora" << std::endl;
}

/*
 * Read in a protocol buffers contents and add to counts
 */
void JelinekMercerFeature::read_counts(const std::string filename) {
  std::cout << "reading corpus from " << filename << " (";
  std::ifstream infile;
  infile.open(filename.c_str());

  int corpus_id;
  std::string corpus_name;
  int num_contexts;

  infile >> corpus_name;
  infile >> corpus_id;
  infile >> num_contexts;
  std::cout << corpus_name << "," << corpus_id << ")" << std::endl;
  assert(_corpora > 0);

  assert(_normalizer[corpus_id] == 0.0);
  for (int vv=0; vv < num_contexts; ++vv) {
    // Set unigram counts
    int total;
    int first;
    int num_bigrams;
    std::string word;

    infile >> word;
    infile >> first;
    infile >> total;
    infile >> num_bigrams;
    _normalizer[corpus_id] += (float)total;
    _unigram[corpus_id][first] = total;
    assert(word == _types[first]);

    for (int bb=0; bb < num_bigrams; ++bb) {
      int second;
      int count;
      infile >> second;
      infile >> count;

      _bigram[corpus_id][bigram(first, second)] = count;
    }
  }
  infile.close();
}

int JelinekMercerFeature::bigram_count(int corpus, int first, int second) {
  bigram key = bigram(first, second);
  if (_bigram[corpus].find(key) == _bigram[corpus].end()) return 0;
  else return _bigram[corpus][key];
}

int JelinekMercerFeature::unigram_count(int corpus, int word) {
  if (_unigram[corpus].find(word) == _unigram[corpus].end()) return 0;
  else return _unigram[corpus][word];
}

int JelinekMercerFeature::sum(int *first, int nitems) {
    int i, sum = 0;
    for (i = 0; i < nitems; i++) {
        sum += first[i];
    }
    return sum;
}

const std::string JelinekMercerFeature::feature(const std::string name,
						int corpus, int *sent,
						int length) {
  assert(length > 0);
  assert(corpus < _corpora);
  int baseline = _compare[corpus];

  // Create vectors to hold probabilities and masks
  _slop_mask.resize(length);
  std::fill(_slop_mask.begin(), _slop_mask.end(), false);
  _span_mask.resize(length);
  _span_start.resize(length);
  _d_bigram.resize(length);
  _b_bigram.resize(length);
  _d_unigram.resize(length);
  _b_unigram.resize(length);

  // Step 1: find the spans
  // Consider the first word part of a span unless it's very frequent
  // This will also contribute to the overall likelihood computation later
  _span_mask[0] = true;

  // Extend from the first position.  Also compute the total likelihood while
  // we're at it.
  for (int ii=1; ii < length; ++ii) {
    if (this->bigram_count(corpus, sent[ii - 1], sent[ii]) > 0) {
      // The current word is only true if the previous word was or it isn't
      // too frequent.
      _span_mask[ii] = _span_mask[ii - 1] ||
          (sent[ii] >= _min_start_rank && _stopwords.find(sent[ii]) == _stopwords.end());
    } else {
      _span_mask[ii] = false;
    }
  }

  if (kDEBUG) {
    for (int ii=0; ii < length; ++ii) {
      if (_span_mask[ii]) std::cout << "\t" << "+" << _types[sent[ii]];
      else std::cout << "\t" << "-" << _types[sent[ii]];
    }
    std::cout << "\t<- tokens/mask" << std::endl;
  }

  // Filter spans that end with high-frequency words
  for (int ii=length; ii >= 0; --ii) {
    if (_span_mask[ii] && // It is in a span
	(ii==length || !_span_mask[ii+1]) && // at the end
	sent[ii] < _min_start_rank) {// and is high frequency
      _span_mask[ii] = false; // Then remove it from span
    }
  }

  // Add back in slop
  if (_slop > 0) {
    int position = 2;
    while (position < length - 1) {
      // Could this position expand a run if we had slop?
      if (_span_mask[position - 1] && !_span_mask[position]) {
        int slop_left = _slop;

        for (int ii=position; ii < std::min(position + _slop, length - 1); ++ii) {
          // If this is a LM hit, then
          // mark all positions before it as a slop position
          if (!_span_mask[ii]) {
            _slop_mask[ii] = true;
            --slop_left;
          }

          if (slop_left == 0) break;
          position = ii;
        }
        ++position;
      } else {
        // There's no run to expand, so just move onto the next position.
        ++position;
      }
    }
  }

  // For each element in the span, figure out where its span begins and compute
  // probabilities.
  _b_unigram[0] = this->score(baseline, -1, sent[0]);
  _d_unigram[0] = this->score(corpus, -1, sent[0]);
  float complete_prob = _d_unigram[0] - _b_unigram[0];

  int start = -1;
  for (int ii=0; ii < length; ++ii) {
    // Do we end a span?
    if (!(_span_mask[ii] || _slop_mask[ii])) {
      start = -1;
    } else {
      // Do we start a new one?
      if (start < 0) start = ii;
      // If we're in a span, we'll want unigram probabilities
      _d_unigram[ii] = this->score(corpus, -1, sent[ii]);
      _b_unigram[ii] = this->score(baseline, -1, sent[ii]);
    }
    _span_start[ii] = start;

    // save the probabilities for later span calculations
    _d_bigram[ii] = this->score(corpus, sent[ii - 1], sent[ii]);
    _b_bigram[ii] = this->score(baseline, sent[ii - 1], sent[ii]);
    complete_prob += _d_bigram[ii] - _b_bigram[ii];
  }

  if (kDEBUG) {
    std::cout << "\tX";
    for (int ii=1; ii < length; ++ii)
      std::cout << "\t" << this->bigram_count(corpus, sent[ii-1], sent[ii]);
    std::cout << std::endl;

    for (int ii=0; ii < length; ++ii) {
      if (_span_mask[ii]) std::cout << "\t" << "+";
      else std::cout << "\t" << "-";
    }
    std::cout << "\t<- revision" << std::endl;

    for (int ii=0; ii < length; ++ii) {
      if (_slop_mask[ii]) std::cout << "\t" << "+";
      else std::cout << "\t" << "-";
    }
    std::cout << "\t<- slop" << std::endl;

    for (int ii=0; ii < length; ++ii) std::cout << "\t" << _span_start[ii];
    std::cout << "\t<- start" << std::endl;

    for (int ii=0; ii < length; ++ii) std::cout << std::setprecision(3) << "\t" << _d_bigram[ii];
    std::cout << "\t<- domain bigram" << std::endl;

    for (int ii=0; ii < length; ++ii) std::cout << "\t" << std::setprecision(3) << _b_bigram[ii];
    std::cout << "\t<- base bigram" << std::endl;

    for (int ii=0; ii < length; ++ii) std::cout << "\t" << this->unigram_count(corpus, sent[ii]);
    std::cout << "\t<- domain unigram count" << std::endl;

    for (int ii=0; ii < length; ++ii) std::cout << "\t" << this->unigram_norm(corpus);
    std::cout << "\t<- domain unigram norm" << std::endl;

    for (int ii=0; ii < length; ++ii) std::cout << std::setprecision(3) << "\t" << _d_unigram[ii];
    std::cout << "\t<- domain unigram" << std::endl;

    for (int ii=0; ii < length; ++ii) std::cout << "\t" << std::setprecision(3) << _b_unigram[ii];
    std::cout << "\t<- base unigram" << std::endl;
  }

  // Now we can output the feature and compute the probability of spans
  std::ostringstream buffer;
  buffer << std::fixed;
  buffer << std::setprecision(2);
  int longest_span  = 0;
  float max_prob = 0;
  for (int ii=1; ii < length; ++ii) {
    if (_span_start[ii] >= 0) {
      if (ii - _span_start[ii] >= longest_span)
	longest_span = ii - _span_start[ii] + 1;

      // Skip if it's too short
      if (ii - _span_start[ii] < _min_span - 1) continue;

      for (int start = _span_start[ii]; start <= ii - _min_span; ++start) {
        float span_probability;
        if (_stopwords.find(sent[start]) != _stopwords.end()) continue;

        span_probability = _d_unigram[start] - _b_unigram[start];

        // First compute the span probabilities
        for (int jj = start + 1; jj <= ii; ++jj) {
          span_probability += _d_bigram[jj] - _b_bigram[jj];
        }

        if (span_probability > _cutoff) {
          if (span_probability > max_prob) max_prob = span_probability;
          buffer << corpus;
          for (int jj = start; jj <= ii; ++jj) {
            buffer << "_";
            if (_censor_slop && _slop_mask[jj]) buffer << "SLOP";
            else buffer << sent[jj];
          }
          if (_score) {
            buffer << ":";
            buffer << span_probability;
          }
          buffer << " ";
        }
      }
    }
  }

  // Output the probability
  if (_score) {
    buffer << name;
    buffer << "_PROB:";
    buffer << complete_prob / ((float)length);

    buffer << " ";
    buffer << name;
    buffer << "_MAX:";
    buffer << max_prob;
    buffer << " ";
  }

  buffer << name;
  buffer << "_LEN:";
  buffer << longest_span;

  if (_log_length) {
    buffer << " " << name;
    buffer << "_LGLEN:";
    buffer << log(1 + longest_span);
  }

  return buffer.str();
}

float JelinekMercerFeature::unigram_norm(int corpus) {
  return (float)this->_normalizer[corpus] + _smooth_norm;
}

float JelinekMercerFeature::score(int corpus, int first, int second) {
  // Store the unigram probability in the score
  float unigram_num = (float)this->unigram_count(corpus, second) + _smooth;
  float unigram_den = this->unigram_norm(corpus);
  float score = unigram_num / unigram_den;

  if (kDEBUG) {
    std::cout << _corpus_names[corpus] << " LL for " << first;
    //if (first >= 0) std::cout << "(" << _types[first] << ")";
    std::cout << " " << second << "(" << _types[second] << ")" << std::endl;
    std::cout << "UNI:" << unigram_num << "/" << unigram_den << "=" << score << std::endl;
  }

  if (first >= 0) { // first == -1 means we just want unigram probability
    int bigram_den = this->unigram_count(corpus, first);
    int bigram_num = this->bigram_count(corpus, first, second);
    if (bigram_den == 0 || bigram_num == 0) {
      score *= _unigram_contribution;
    } else {
      score = this->_bigram_contribution * (float)bigram_num / (float)bigram_den +
	_unigram_contribution * score;
    }
  }

  if (kDEBUG) {
    std::cout << "Final:" << log(score) << std::endl;
  }

  return log(score);
}
<|endoftext|>


<commit_before>/*
 * Hamming Window Function Unit for Jamoma DSP
 * Copyright © 2010 by Trond Lossius
 *
 * License: This code is licensed under the terms of the GNU LGPL
 * http://www.gnu.org/licenses/lgpl.html
 */

#include "HammingWindow.h"

#define thisTTClass			HammingWindow
#define thisTTClassName		"hamming"
#define thisTTClassTags		"audio, processor, function, window"

TT_AUDIO_CONSTRUCTOR
{
	setProcessMethod(processAudio);
	setCalculateMethod(calculateValue);
}

HammingWindow::~HammingWindow()
{
	;
}

// hanning(x) = 0.5 + 0.5*cos(2*PI*(x-0.5))
TTErr HammingWindow::calculateValue(const TTFloat64& x, TTFloat64& y, TTPtrSizedInt data)
{
	y = 0.54 + 0.46*cos(kTTwoTPi*(x-0.5));
	return kTTErrNone;
}

TTErr HammingWindow::processAudio(TTAudioSignalArrayPtr inputs, TTAudioSignalArrayPtr outputs)
{
	TT_WRAP_CALCULATE_METHOD(calculateValue);
}

<commit_msg>fixing typo <commit_after>/*
 * Hamming Window Function Unit for Jamoma DSP
 * Copyright © 2010 by Trond Lossius
 *
 * License: This code is licensed under the terms of the GNU LGPL
 * http://www.gnu.org/licenses/lgpl.html
 */

#include "HammingWindow.h"

#define thisTTClass			HammingWindow
#define thisTTClassName		"hamming"
#define thisTTClassTags		"audio, processor, function, window"

TT_AUDIO_CONSTRUCTOR
{
	setProcessMethod(processAudio);
	setCalculateMethod(calculateValue);
}

HammingWindow::~HammingWindow()
{
	;
}

// hanning(x) = 0.5 + 0.5*cos(2*PI*(x-0.5))
TTErr HammingWindow::calculateValue(const TTFloat64& x, TTFloat64& y, TTPtrSizedInt data)
{
	y = 0.54 + 0.46*cos(kTTTwoPi*(x-0.5));
	return kTTErrNone;
}

TTErr HammingWindow::processAudio(TTAudioSignalArrayPtr inputs, TTAudioSignalArrayPtr outputs)
{
	TT_WRAP_CALCULATE_METHOD(calculateValue);
}

<|endoftext|>