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

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sfx2.hxx"
#include <com/sun/star/registry/MergeConflictException.hpp>
#include <com/sun/star/registry/XSimpleRegistry.hpp>
#include <com/sun/star/container/XNameAccess.hpp>
#include <comphelper/processfactory.hxx>
#include <tools/config.hxx>
#include <svtools/pathoptions.hxx>
#include <svtools/moduleoptions.hxx>
#include <tools/urlobj.hxx>
#include <unotools/ucbstreamhelper.hxx>
#include <comphelper/sequenceashashmap.hxx>

#include <sfx2/sfx.hrc>
#include <sfx2/docfilt.hxx>
#include <sfx2/docfac.hxx>
#include "viewfac.hxx"
#include "fltfnc.hxx"
#include "arrdecl.hxx"
#include <sfx2/app.hxx>
#include <sfx2/module.hxx>
#include <sfx2/mnumgr.hxx>
#include "sfxresid.hxx"
#include <sfx2/sfxuno.hxx>
#include "doc.hrc"

namespace css = ::com::sun::star;

//========================================================================

DECL_PTRARRAY( SfxViewFactoryArr_Impl, SfxViewFactory*, 2, 2 )

//========================================================================

DBG_NAME(SfxObjectFactory)

//static SfxObjectFactoryArr_Impl* pObjFac = 0;

//========================================================================

struct SfxObjectFactory_Impl
{
    SfxViewFactoryArr_Impl      aViewFactoryArr;// Liste von <SfxViewFactory>s
    SfxFilterArr_Impl           aFilterArr;     // Liste von <SFxFilter>n
    ResId*                      pNameResId;
    ::rtl::OUString             aServiceName;
    SfxFilterContainer*         pFilterContainer;
    SfxModule*                  pModule;
    sal_uInt16                  nImageId;
    String                      aStandardTemplate;
    sal_Bool                    bTemplateInitialized;
    SvGlobalName                aClassName;

    SfxObjectFactory_Impl() :
        pNameResId          ( NULL ),
        pFilterContainer    ( NULL ),
        pModule             ( NULL ),
        nImageId            ( 0 ),
        bTemplateInitialized( sal_False )
        {}
};

//========================================================================

SfxFilterContainer* SfxObjectFactory::GetFilterContainer( sal_Bool /*bForceLoad*/ ) const
{
    return pImpl->pFilterContainer;
}

//--------------------------------------------------------------------

SfxObjectFactory::SfxObjectFactory
(
    const SvGlobalName&     rName,
    SfxObjectShellFlags     nFlagsP,
    const char*             pName
) :    pShortName( pName ),
       pImpl( new SfxObjectFactory_Impl ),
       nFlags( nFlagsP )
{
    DBG_CTOR(SfxObjectFactory, 0);
    pImpl->pFilterContainer = new SfxFilterContainer( String::CreateFromAscii( pName ) );

    String aShortName( String::CreateFromAscii( pShortName ) );
    aShortName.ToLowerAscii();
    pImpl->aClassName = rName;
    if ( aShortName.EqualsAscii( "swriter" ) )
        pImpl->pNameResId = new SfxResId( STR_DOCTYPENAME_SW );
    else if ( aShortName.EqualsAscii( "swriter/web" ) )
        pImpl->pNameResId = new SfxResId( STR_DOCTYPENAME_SWWEB );
    else if ( aShortName.EqualsAscii( "swriter/globaldocument" ) )
        pImpl->pNameResId = new SfxResId( STR_DOCTYPENAME_SWGLOB );
    else if ( aShortName.EqualsAscii( "scalc" ) )
        pImpl->pNameResId = new SfxResId( STR_DOCTYPENAME_SC );
    else if ( aShortName.EqualsAscii( "simpress" ) )
        pImpl->pNameResId = new SfxResId( STR_DOCTYPENAME_SI );
    else if ( aShortName.EqualsAscii( "sdraw" ) )
        pImpl->pNameResId = new SfxResId( STR_DOCTYPENAME_SD );
    else if ( aShortName.EqualsAscii( "message" ) )
        pImpl->pNameResId = new SfxResId( STR_DOCTYPENAME_MESSAGE );
}

//--------------------------------------------------------------------

SfxObjectFactory::~SfxObjectFactory()
{
    DBG_DTOR(SfxObjectFactory, 0);

    const sal_uInt16 nCount = pImpl->aFilterArr.Count();
    for ( sal_uInt16 i = 0; i < nCount; ++i )
        delete pImpl->aFilterArr[i];
    delete pImpl->pNameResId;
    delete pImpl;
}

//--------------------------------------------------------------------

void SfxObjectFactory::RegisterViewFactory
(
    SfxViewFactory &rFactory
)
{
    sal_uInt16 nPos;
    for ( nPos = 0;
          nPos < pImpl->aViewFactoryArr.Count() &&
          pImpl->aViewFactoryArr[nPos]->GetOrdinal() <= rFactory.GetOrdinal();
          ++nPos )
    /* empty loop */;
    pImpl->aViewFactoryArr.Insert(nPos, &rFactory);
}

//--------------------------------------------------------------------

sal_uInt16 SfxObjectFactory::GetViewFactoryCount() const
{
    return pImpl->aViewFactoryArr.Count();
}

//--------------------------------------------------------------------

SfxViewFactory& SfxObjectFactory::GetViewFactory(sal_uInt16 i) const
{
    return *pImpl->aViewFactoryArr[i];
}

//--------------------------------------------------------------------

SfxModule* SfxObjectFactory::GetModule() const
{
    return pImpl->pModule;
}

void SfxObjectFactory::SetModule_Impl( SfxModule *pMod )
{
    pImpl->pModule = pMod;
}

void SfxObjectFactory::SetStandardTemplate( const String& rServiceName, const String& rTemplate )
{
    SvtModuleOptions::EFactory eFac = SvtModuleOptions::ClassifyFactoryByServiceName(rServiceName);
    if (eFac == SvtModuleOptions::E_UNKNOWN_FACTORY)
        eFac = SvtModuleOptions::ClassifyFactoryByShortName(rServiceName);
    if (eFac != SvtModuleOptions::E_UNKNOWN_FACTORY)
        SvtModuleOptions().SetFactoryStandardTemplate(eFac, rTemplate);
}

String SfxObjectFactory::GetStandardTemplate( const String& rServiceName )
{
    SvtModuleOptions::EFactory eFac = SvtModuleOptions::ClassifyFactoryByServiceName(rServiceName);
    if (eFac == SvtModuleOptions::E_UNKNOWN_FACTORY)
        eFac = SvtModuleOptions::ClassifyFactoryByShortName(rServiceName);

    String sTemplate;
    if (eFac != SvtModuleOptions::E_UNKNOWN_FACTORY)
        sTemplate = SvtModuleOptions().GetFactoryStandardTemplate(eFac);

    return sTemplate;
}

/*
const SfxObjectFactory* SfxObjectFactory::GetFactory( const String& rFactoryURL )
{
    const SfxObjectFactory* pFactory = 0;
    String aFact( rFactoryURL );
    String aPrefix( DEFINE_CONST_UNICODE( "private:factory/" ) );
    if ( aPrefix.Len() == aFact.Match( aPrefix ) )
        // Aufruf m"oglich mit z.B. "swriter" oder "private:factory/swriter"
        aFact.Erase( 0, aPrefix.Len() );
    sal_uInt16 nPos = aFact.Search( '?' );

    // Etwaige Parameter abschneiden
    aFact.Erase( nPos, aFact.Len() );

    SfxApplication *pApp = SFX_APP();

    // "swriter4" durch "swriter" ersetzen, zum Vergleichen uppercase verwenden
    WildCard aSearchedFac( aFact.EraseAllChars('4').ToUpperAscii() );
    for( sal_uInt16 n = GetObjectFactoryCount_Impl(); !pFactory && n--; )
    {
        pFactory = &GetObjectFactory_Impl( n );
        String aCompareTo = String::CreateFromAscii( pFactory->GetShortName() );
        aCompareTo.ToUpperAscii();
        if( !aSearchedFac.Matches( aCompareTo ) )
            pFactory = 0;
    }

    return pFactory;
}
*/

const SfxFilter* SfxObjectFactory::GetTemplateFilter() const
{
    USHORT nVersion=0;
    SfxFilterMatcher aMatcher ( String::CreateFromAscii( pShortName ) );
    SfxFilterMatcherIter aIter( &aMatcher );
    const SfxFilter *pFilter = 0;
    const SfxFilter *pTemp = aIter.First();
    while ( pTemp )
    {
        if( pTemp->IsOwnFormat() && pTemp->IsOwnTemplateFormat() && ( pTemp->GetVersion() > nVersion ) )
        {
            pFilter = pTemp;
            nVersion = (USHORT) pTemp->GetVersion();
        }

        pTemp = aIter.Next();
    }

    return pFilter;
}

void SfxObjectFactory::SetDocumentTypeNameResource( const ResId& rId )
{
    DBG_ASSERT( !pImpl->pNameResId, "UI-Namensresource mehrfach gesetzt!" );
    pImpl->pNameResId = new ResId( rId );
}

String SfxObjectFactory::GetDocumentTypeName() const
{
    if ( pImpl->pNameResId )
        return String( *pImpl->pNameResId );
    return String();
}

void SfxObjectFactory::SetDocumentServiceName( const ::rtl::OUString& rServiceName )
{
    pImpl->aServiceName = rServiceName;
}

const ::rtl::OUString& SfxObjectFactory::GetDocumentServiceName() const
{
    return pImpl->aServiceName;
}

const SvGlobalName& SfxObjectFactory::GetClassId() const
{
    return pImpl->aClassName;
}

String SfxObjectFactory::GetFactoryURL() const
{
    ::rtl::OUStringBuffer aURLComposer;
    aURLComposer.appendAscii( "private:factory/" );
    aURLComposer.appendAscii( GetShortName() );
    return aURLComposer.makeStringAndClear();
}

String SfxObjectFactory::GetModuleName() const
{
    static ::rtl::OUString SERVICENAME_MODULEMANAGER = ::rtl::OUString::createFromAscii("com.sun.star.frame.ModuleManager");
    static ::rtl::OUString PROP_MODULEUINAME         = ::rtl::OUString::createFromAscii("ooSetupFactoryUIName");

    try
    {
        css::uno::Reference< css::lang::XMultiServiceFactory > xSMGR = ::comphelper::getProcessServiceFactory();

        css::uno::Reference< css::container::XNameAccess > xModuleManager(
            xSMGR->createInstance(SERVICENAME_MODULEMANAGER),
            css::uno::UNO_QUERY_THROW);

        ::rtl::OUString sDocService(GetDocumentServiceName());
        ::comphelper::SequenceAsHashMap aPropSet( xModuleManager->getByName(sDocService) );
        ::rtl::OUString sModuleName = aPropSet.getUnpackedValueOrDefault(PROP_MODULEUINAME, ::rtl::OUString());
        return String(sModuleName);
    }
    catch(const css::uno::RuntimeException&)
        { throw; }
    catch(const css::uno::Exception&)
        {}

    return String();
}

sal_uInt16 SfxObjectFactory::GetViewNo_Impl( const sal_uInt16 i_nViewId, const sal_uInt16 i_nFallback ) const
{
    for ( sal_uInt16 curViewNo = 0; curViewNo < GetViewFactoryCount(); ++curViewNo )
    {
        const sal_uInt16 curViewId = GetViewFactory( curViewNo ).GetOrdinal();
        if ( i_nViewId == curViewId )
           return curViewNo;
    }
    return i_nFallback;
}

SfxViewFactory* SfxObjectFactory::GetViewFactoryByViewName( const String& i_rViewName ) const
{
    SfxViewFactory* pViewFactory = NULL;
    for (   USHORT nViewNo = 0;
            nViewNo < GetViewFactoryCount();
            ++nViewNo
        )
    {
        SfxViewFactory& rViewFac( GetViewFactory( nViewNo ) );
        if ( rViewFac.GetViewName() == i_rViewName )
            return &rViewFac;
    }
    return NULL;
}
<commit_msg>dba33b: #i10000#<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: docfac.cxx,v $
 * $Revision: 1.28 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sfx2.hxx"
#include <com/sun/star/registry/MergeConflictException.hpp>
#include <com/sun/star/registry/XSimpleRegistry.hpp>
#include <com/sun/star/container/XNameAccess.hpp>
#include <comphelper/processfactory.hxx>
#include <tools/config.hxx>
#include <svtools/pathoptions.hxx>
#include <svtools/moduleoptions.hxx>
#include <tools/urlobj.hxx>
#include <unotools/ucbstreamhelper.hxx>
#include <comphelper/sequenceashashmap.hxx>

#include <sfx2/sfx.hrc>
#include <sfx2/docfilt.hxx>
#include <sfx2/docfac.hxx>
#include "viewfac.hxx"
#include "fltfnc.hxx"
#include "arrdecl.hxx"
#include <sfx2/app.hxx>
#include <sfx2/module.hxx>
#include <sfx2/mnumgr.hxx>
#include "sfxresid.hxx"
#include <sfx2/sfxuno.hxx>
#include "doc.hrc"

namespace css = ::com::sun::star;

//========================================================================

DECL_PTRARRAY( SfxViewFactoryArr_Impl, SfxViewFactory*, 2, 2 )

//========================================================================

DBG_NAME(SfxObjectFactory)

//static SfxObjectFactoryArr_Impl* pObjFac = 0;

//========================================================================

struct SfxObjectFactory_Impl
{
    SfxViewFactoryArr_Impl      aViewFactoryArr;// Liste von <SfxViewFactory>s
    SfxFilterArr_Impl           aFilterArr;     // Liste von <SFxFilter>n
    ResId*                      pNameResId;
    ::rtl::OUString             aServiceName;
    SfxFilterContainer*         pFilterContainer;
    SfxModule*                  pModule;
    sal_uInt16                  nImageId;
    String                      aStandardTemplate;
    sal_Bool                    bTemplateInitialized;
    SvGlobalName                aClassName;

    SfxObjectFactory_Impl() :
        pNameResId          ( NULL ),
        pFilterContainer    ( NULL ),
        pModule             ( NULL ),
        nImageId            ( 0 ),
        bTemplateInitialized( sal_False )
        {}
};

//========================================================================

SfxFilterContainer* SfxObjectFactory::GetFilterContainer( sal_Bool /*bForceLoad*/ ) const
{
    return pImpl->pFilterContainer;
}

//--------------------------------------------------------------------

SfxObjectFactory::SfxObjectFactory
(
    const SvGlobalName&     rName,
    SfxObjectShellFlags     nFlagsP,
    const char*             pName
) :    pShortName( pName ),
       pImpl( new SfxObjectFactory_Impl ),
       nFlags( nFlagsP )
{
    DBG_CTOR(SfxObjectFactory, 0);
    pImpl->pFilterContainer = new SfxFilterContainer( String::CreateFromAscii( pName ) );

    String aShortName( String::CreateFromAscii( pShortName ) );
    aShortName.ToLowerAscii();
    pImpl->aClassName = rName;
    if ( aShortName.EqualsAscii( "swriter" ) )
        pImpl->pNameResId = new SfxResId( STR_DOCTYPENAME_SW );
    else if ( aShortName.EqualsAscii( "swriter/web" ) )
        pImpl->pNameResId = new SfxResId( STR_DOCTYPENAME_SWWEB );
    else if ( aShortName.EqualsAscii( "swriter/globaldocument" ) )
        pImpl->pNameResId = new SfxResId( STR_DOCTYPENAME_SWGLOB );
    else if ( aShortName.EqualsAscii( "scalc" ) )
        pImpl->pNameResId = new SfxResId( STR_DOCTYPENAME_SC );
    else if ( aShortName.EqualsAscii( "simpress" ) )
        pImpl->pNameResId = new SfxResId( STR_DOCTYPENAME_SI );
    else if ( aShortName.EqualsAscii( "sdraw" ) )
        pImpl->pNameResId = new SfxResId( STR_DOCTYPENAME_SD );
    else if ( aShortName.EqualsAscii( "message" ) )
        pImpl->pNameResId = new SfxResId( STR_DOCTYPENAME_MESSAGE );
}

//--------------------------------------------------------------------

SfxObjectFactory::~SfxObjectFactory()
{
    DBG_DTOR(SfxObjectFactory, 0);

    const sal_uInt16 nCount = pImpl->aFilterArr.Count();
    for ( sal_uInt16 i = 0; i < nCount; ++i )
        delete pImpl->aFilterArr[i];
    delete pImpl->pNameResId;
    delete pImpl;
}

//--------------------------------------------------------------------

void SfxObjectFactory::RegisterViewFactory
(
    SfxViewFactory &rFactory
)
{
    sal_uInt16 nPos;
    for ( nPos = 0;
          nPos < pImpl->aViewFactoryArr.Count() &&
          pImpl->aViewFactoryArr[nPos]->GetOrdinal() <= rFactory.GetOrdinal();
          ++nPos )
    /* empty loop */;
    pImpl->aViewFactoryArr.Insert(nPos, &rFactory);
}

//--------------------------------------------------------------------

sal_uInt16 SfxObjectFactory::GetViewFactoryCount() const
{
    return pImpl->aViewFactoryArr.Count();
}

//--------------------------------------------------------------------

SfxViewFactory& SfxObjectFactory::GetViewFactory(sal_uInt16 i) const
{
    return *pImpl->aViewFactoryArr[i];
}

//--------------------------------------------------------------------

SfxModule* SfxObjectFactory::GetModule() const
{
    return pImpl->pModule;
}

void SfxObjectFactory::SetModule_Impl( SfxModule *pMod )
{
    pImpl->pModule = pMod;
}

void SfxObjectFactory::SetStandardTemplate( const String& rServiceName, const String& rTemplate )
{
    SvtModuleOptions::EFactory eFac = SvtModuleOptions::ClassifyFactoryByServiceName(rServiceName);
    if (eFac == SvtModuleOptions::E_UNKNOWN_FACTORY)
        eFac = SvtModuleOptions::ClassifyFactoryByShortName(rServiceName);
    if (eFac != SvtModuleOptions::E_UNKNOWN_FACTORY)
        SvtModuleOptions().SetFactoryStandardTemplate(eFac, rTemplate);
}

String SfxObjectFactory::GetStandardTemplate( const String& rServiceName )
{
    SvtModuleOptions::EFactory eFac = SvtModuleOptions::ClassifyFactoryByServiceName(rServiceName);
    if (eFac == SvtModuleOptions::E_UNKNOWN_FACTORY)
        eFac = SvtModuleOptions::ClassifyFactoryByShortName(rServiceName);

    String sTemplate;
    if (eFac != SvtModuleOptions::E_UNKNOWN_FACTORY)
        sTemplate = SvtModuleOptions().GetFactoryStandardTemplate(eFac);

    return sTemplate;
}

/*
const SfxObjectFactory* SfxObjectFactory::GetFactory( const String& rFactoryURL )
{
    const SfxObjectFactory* pFactory = 0;
    String aFact( rFactoryURL );
    String aPrefix( DEFINE_CONST_UNICODE( "private:factory/" ) );
    if ( aPrefix.Len() == aFact.Match( aPrefix ) )
        // Aufruf m"oglich mit z.B. "swriter" oder "private:factory/swriter"
        aFact.Erase( 0, aPrefix.Len() );
    sal_uInt16 nPos = aFact.Search( '?' );

    // Etwaige Parameter abschneiden
    aFact.Erase( nPos, aFact.Len() );

    SfxApplication *pApp = SFX_APP();

    // "swriter4" durch "swriter" ersetzen, zum Vergleichen uppercase verwenden
    WildCard aSearchedFac( aFact.EraseAllChars('4').ToUpperAscii() );
    for( sal_uInt16 n = GetObjectFactoryCount_Impl(); !pFactory && n--; )
    {
        pFactory = &GetObjectFactory_Impl( n );
        String aCompareTo = String::CreateFromAscii( pFactory->GetShortName() );
        aCompareTo.ToUpperAscii();
        if( !aSearchedFac.Matches( aCompareTo ) )
            pFactory = 0;
    }

    return pFactory;
}
*/

const SfxFilter* SfxObjectFactory::GetTemplateFilter() const
{
    USHORT nVersion=0;
    SfxFilterMatcher aMatcher ( String::CreateFromAscii( pShortName ) );
    SfxFilterMatcherIter aIter( &aMatcher );
    const SfxFilter *pFilter = 0;
    const SfxFilter *pTemp = aIter.First();
    while ( pTemp )
    {
        if( pTemp->IsOwnFormat() && pTemp->IsOwnTemplateFormat() && ( pTemp->GetVersion() > nVersion ) )
        {
            pFilter = pTemp;
            nVersion = (USHORT) pTemp->GetVersion();
        }

        pTemp = aIter.Next();
    }

    return pFilter;
}

void SfxObjectFactory::SetDocumentTypeNameResource( const ResId& rId )
{
    DBG_ASSERT( !pImpl->pNameResId, "UI-Namensresource mehrfach gesetzt!" );
    pImpl->pNameResId = new ResId( rId );
}

String SfxObjectFactory::GetDocumentTypeName() const
{
    if ( pImpl->pNameResId )
        return String( *pImpl->pNameResId );
    return String();
}

void SfxObjectFactory::SetDocumentServiceName( const ::rtl::OUString& rServiceName )
{
    pImpl->aServiceName = rServiceName;
}

const ::rtl::OUString& SfxObjectFactory::GetDocumentServiceName() const
{
    return pImpl->aServiceName;
}

const SvGlobalName& SfxObjectFactory::GetClassId() const
{
    return pImpl->aClassName;
}

String SfxObjectFactory::GetFactoryURL() const
{
    ::rtl::OUStringBuffer aURLComposer;
    aURLComposer.appendAscii( "private:factory/" );
    aURLComposer.appendAscii( GetShortName() );
    return aURLComposer.makeStringAndClear();
}

String SfxObjectFactory::GetModuleName() const
{
    static ::rtl::OUString SERVICENAME_MODULEMANAGER = ::rtl::OUString::createFromAscii("com.sun.star.frame.ModuleManager");
    static ::rtl::OUString PROP_MODULEUINAME         = ::rtl::OUString::createFromAscii("ooSetupFactoryUIName");

    try
    {
        css::uno::Reference< css::lang::XMultiServiceFactory > xSMGR = ::comphelper::getProcessServiceFactory();

        css::uno::Reference< css::container::XNameAccess > xModuleManager(
            xSMGR->createInstance(SERVICENAME_MODULEMANAGER),
            css::uno::UNO_QUERY_THROW);

        ::rtl::OUString sDocService(GetDocumentServiceName());
        ::comphelper::SequenceAsHashMap aPropSet( xModuleManager->getByName(sDocService) );
        ::rtl::OUString sModuleName = aPropSet.getUnpackedValueOrDefault(PROP_MODULEUINAME, ::rtl::OUString());
        return String(sModuleName);
    }
    catch(const css::uno::RuntimeException&)
        { throw; }
    catch(const css::uno::Exception&)
        {}

    return String();
}

sal_uInt16 SfxObjectFactory::GetViewNo_Impl( const sal_uInt16 i_nViewId, const sal_uInt16 i_nFallback ) const
{
    for ( sal_uInt16 curViewNo = 0; curViewNo < GetViewFactoryCount(); ++curViewNo )
    {
        const sal_uInt16 curViewId = GetViewFactory( curViewNo ).GetOrdinal();
        if ( i_nViewId == curViewId )
           return curViewNo;
    }
    return i_nFallback;
}

SfxViewFactory* SfxObjectFactory::GetViewFactoryByViewName( const String& i_rViewName ) const
{
    for (   USHORT nViewNo = 0;
            nViewNo < GetViewFactoryCount();
            ++nViewNo
        )
    {
        SfxViewFactory& rViewFac( GetViewFactory( nViewNo ) );
        if ( rViewFac.GetViewName() == i_rViewName )
            return &rViewFac;
    }
    return NULL;
}
<|endoftext|>


<commit_before>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------

// RUN: cat %s | %cling 2>&1 | FileCheck %s
#include <type_traits>
#include <cstdlib>
#include <string>

cling::runtime::gClingOpts->AllowRedefinition = 1;

// ==== Test UsingDirectiveDecl/UsingDecl
// These should not be nested into a `__cling_N5xxx' namespace (but placed at
// the TU scope) so that the declaration they name is globally available.
using namespace std;
namespace NS { string baz("Cling"); }
using NS::baz;
baz
//CHECK: (std::string &) "Cling"

// ==== Redeclare `i' with a different type
int i = 1
//CHECK-NEXT: (int) 1
double i = 3.141592
//CHECK-NEXT: (double) 3.1415920

// ==== Provide different definition for type
struct MyStruct;
struct MyStruct { unsigned u; };
MyStruct{1111U}.u
//CHECK-NEXT: (unsigned int) 1111
struct MyStruct { int i, j; } foo{33, 0}
//CHECK-NEXT: (struct MyStruct &)
foo.i
//CHECK-NEXT: (int) 33
struct MyStruct;  // nop
MyStruct{0, 99}.j
//CHECK-NEXT: (int) 99

// ==== Make `foo' a typedef type
typedef int foo;
foo bar = 1
//CHECK-NEXT: (int) 1
typedef MyStruct foo;
foo{11, 99}.i
//CHECK-NEXT: (int) 11
bar
// CHECK-NEXT: (int) 1

// ==== Give a new defintion for `foo'; test function overload
char foo(int x) { return 'X'; }
int foo() { return 0; }
foo()
//CHECK-NEXT: (int) 0
foo(0)
//CHECK-NEXT: (char) 'X'
double foo() { return 1; }
foo()
//CHECK-NEXT: (double) 1.0000000

// ==== (Re)define a class template
template <typename T> struct S { T i; };
S<int> foo{99};
foo.i
//CHECK-NEXT: (int) 99
template <typename T> struct S { T i, j; };
S<double>{0, 33.0}.j
//CHECK-NEXT: (double) 33.000000

// ==== Test function templates
template <typename T>
typename std::enable_if<std::is_same<T, int>::value, int>::type f(T x) { return x; }
template <typename T>
typename std::enable_if<!std::is_same<T, int>::value, int>::type f(T x) { return 0x55aa; }
f(33)
//CHECK-NEXT: (int) 33
f(3.3f)
//CHECK-NEXT: (int) 21930

template <typename T>
typename std::enable_if<std::is_same<T, int>::value, int>::type f(T x) { return 0xaa55; }
f(33)
//CHECK-NEXT: (int) 43605
f(3.3f)
//CHECK-NEXT: (int) 21930
//expected-no-diagnostics
.q
<commit_msg>Improve DeclShadowing.C test<commit_after>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------

// RUN: cat %s | %cling 2>&1 | FileCheck %s
#include "cling/Interpreter/Interpreter.h"
#include "cling/Utils/AST.h"
#include "clang/AST/Decl.h"

#include <type_traits>
#include <cstdlib>
#include <string>

unsigned _i;
struct _X {};
int _g() { return 1; }

cling::runtime::gClingOpts->AllowRedefinition = 1;

void g() {}

// ==== Test UsingDirectiveDecl/UsingDecl
// These should not be nested into a `__cling_N5xxx' namespace (but placed at
// the TU scope) so that the declaration they name is globally available.
using namespace std;
namespace NS { string baz("Cling"); }
using NS::baz;
baz
//CHECK: (std::string &) "Cling"

// ==== Redeclare `i' with a different type
int i = 1
//CHECK-NEXT: (int) 1
double i = 3.141592
//CHECK-NEXT: (double) 3.1415920

// ==== Provide different definition for type
struct MyStruct;
struct MyStruct { unsigned u; };
MyStruct{1111U}.u
//CHECK-NEXT: (unsigned int) 1111
struct MyStruct { int i, j; } foo{33, 0}
//CHECK-NEXT: (struct MyStruct &)
foo.i
//CHECK-NEXT: (int) 33
struct MyStruct;  // nop
MyStruct{0, 99}.j
//CHECK-NEXT: (int) 99

// ==== Make `foo' a typedef type
typedef int foo;
foo bar = 1
//CHECK-NEXT: (int) 1
typedef MyStruct foo;
foo{11, 99}.i
//CHECK-NEXT: (int) 11
bar
// CHECK-NEXT: (int) 1

// ==== Give a new defintion for `foo'; test function overload
char foo(int x) { return 'X'; }
int foo() { return 0; }
foo()
//CHECK-NEXT: (int) 0
foo(0)
//CHECK-NEXT: (char) 'X'
double foo() { return 1; }
foo()
//CHECK-NEXT: (double) 1.0000000

// ==== (Re)define a class template
template <typename T> struct S { T i; };
S<int> foo{99};
foo.i
//CHECK-NEXT: (int) 99
template <typename T> struct S { T i, j; };
S<double>{0, 33.0}.j
//CHECK-NEXT: (double) 33.000000

// ==== Test function templates
template <typename T>
typename std::enable_if<std::is_same<T, int>::value, int>::type f(T x) { return x; }
template <typename T>
typename std::enable_if<!std::is_same<T, int>::value, int>::type f(T x) { return 0x55aa; }
f(33)
//CHECK-NEXT: (int) 33
f(3.3f)
//CHECK-NEXT: (int) 21930

template <typename T>
typename std::enable_if<std::is_same<T, int>::value, int>::type f(T x) { return 0xaa55; }
f(33)
//CHECK-NEXT: (int) 43605
f(3.3f)
//CHECK-NEXT: (int) 21930

cling::runtime::gClingOpts->AllowRedefinition = 0;

// ==== Check DeclContext
// If DefinitionShadower is enabled, declaration context is an inline namespace;
// otherwise it should be the TU.
clang::Sema& _S = gCling->getSema();
const clang::NamedDecl *_decl{nullptr};

_decl = cling::utils::Lookup::Named(&_S, "_i", nullptr)
//CHECK-NEXT: (const clang::NamedDecl *) 0x{{[1-9a-f][0-9a-f]*$}}
_decl->getDeclContext()->isTranslationUnit()
//CHECK-NEXT: (bool) true

_decl = cling::utils::Lookup::Named(&_S, "_X", nullptr)
//CHECK-NEXT: (const clang::NamedDecl *) 0x{{[1-9a-f][0-9a-f]*$}}
_decl->getDeclContext()->isTranslationUnit()
//CHECK-NEXT: (bool) true

_decl = cling::utils::Lookup::Named(&_S, "_g", nullptr)
//CHECK-NEXT: (const clang::NamedDecl *) 0x{{[1-9a-f][0-9a-f]*$}}
_decl->getDeclContext()->isTranslationUnit()
//CHECK-NEXT: (bool) true

_decl = cling::utils::Lookup::Named(&_S, "bar", nullptr)
//CHECK-NEXT: (const clang::NamedDecl *) 0x{{[1-9a-f][0-9a-f]*$}}
_decl->getDeclContext()->isInlineNamespace()
//CHECK-NEXT: (bool) true

_decl = cling::utils::Lookup::Named(&_S, "MyStruct", nullptr)
//CHECK-NEXT: (const clang::NamedDecl *) 0x{{[1-9a-f][0-9a-f]*$}}
_decl->getDeclContext()->isInlineNamespace()
//CHECK-NEXT: (bool) true

_decl = cling::utils::Lookup::Named(&_S, "g", nullptr)
//CHECK-NEXT: (const clang::NamedDecl *) 0x{{[1-9a-f][0-9a-f]*$}}
_decl->getDeclContext()->isInlineNamespace()
//CHECK-NEXT: (bool) true

//expected-no-diagnostics
.q
<|endoftext|>


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

#include "MqChannel.h"
#include "PlatformDep.h"
#include "IqrfLogging.h"
#include "JsonUtils.h"
#include "VersionInfo.h"
#include <fstream>

TRC_INIT()

bool exitFlag = false;
bool sentFlag = false;

void helpAndExit()
{
  std::cerr << "Usage" << std::endl;
  std::cerr << "  iqrfapp" << std::endl;
  std::cerr << "  iqrfapp help" << std::endl;
  std::cerr << "  iqrfapp readonly" << std::endl;
  std::cerr << "  iqrfapp raw <DpaBytesSeparatedByDots> timeout <ValueInMs>" << std::endl;
  std::cerr << "  iqrfapp conf [operational|forwarding|service]" << std::endl;
  std::cerr << "  iqrfapp <JsonDpaRequest>" << std::endl;
  std::cerr << "Examples" << std::endl;
  std::cerr << "  iqrfapp" << std::endl;
  std::cerr << "  iqrfapp help" << std::endl;
  std::cerr << "  iqrfapp raw 01.00.06.03.ff.ff timeout 1000" << std::endl;
  std::cerr << "  iqrfapp conf operational" << std::endl;
  std::cerr << "  iqrfapp \"{\\\"ctype\\\":\\\"dpa\\\",\\\"type\\\":\\\"raw\\\",\\\"timeout\\\":1000,\\\"request\\\":\\\"01.00.06.03.ff.ff\\\"}\"" << std::endl;
                  /*"{\"ctype\":\"dpa\",\"type\":\"raw\",\"timeout\":1000,\"request\":\"01.00.06.03.ff.ff\"}"*/
  std::cerr << "Tips" << std::endl;
  std::cerr << "  Adjust default timeout in iqrfapp.json to the needs of the application using iqrfapp tool or define timeout as cmd param." << std::endl;
  std::cerr << "  Default timeout in iqrfapp.json is 5000 ms." << std::endl;
  exit(-1);
}

int parseCommand(std::string cmd) {

  rapidjson::Document doc;
  int timeout = -1;

  try {
    jutils::parseString(cmd, doc);
    jutils::assertIsObject("", doc);
    timeout = jutils::getMemberAs<int>("timeout", doc);
  }
  catch (std::exception &e) {
    CATCH_EX("Cannot parse command: ", std::logic_error, e);
  }

  return timeout;
}

int handleMessageFromMq(const ustring& message)
{
  TRC_DBG("Received from MQ: " << std::endl << FORM_HEX(message.data(), message.size()));
  std::string msg((char*)message.data(), message.size());

  if (sentFlag) {
    std::cout << msg << std::endl;
    exitFlag = true;
    sentFlag = false;
  }

  return 0;
}

//just workaround - TODO cmdl params are not properly tested - maybe boost?
int main(int argc, char** argv)
{
  TRC_START("", iqrf::Level::inf, 0);
  std::string command;
  std::string rawTimeout;

  bool cmdl = false;
  bool json = false;
  bool raw = false;
  bool readonly = false;

  int defaultTimeout = 5000;

  switch (argc) {
  case 1:
  {
    cmdl = true;
    break;
  }
  case 2:
  {
    std::string arg1 = argv[1];
    if (arg1 == "help") {
      helpAndExit();
    }
    else if (arg1 == "readonly") {
      readonly = true;
    }
    else {
      json = true;
    }
    break;
  }
  case 3:
  {
    std::string arg1 = argv[1];
    std::string arg2 = argv[2];
    if (arg1 == "conf" && arg2 != "operational" && arg2 != "forwarding" && arg2 != "service") {
      helpAndExit();
    }
    if (arg1 != "raw") {
      helpAndExit();
    }
    break;
  }
  // raw with timeout
  case 5:
  {
    std::string arg1 = argv[1];
    std::string arg2 = argv[2];
    std::string arg3 = argv[3];
    std::string arg4 = argv[4];

    if (arg1 != "raw" && arg3 != "timeout") {
      helpAndExit();
    }
    else {
      raw = true;
      rawTimeout = arg4;
    }
    break;
  }
  default:; //just continue and try
  }

  std::ostringstream os;
  for (int i = 1; i < argc; i++)
    os << argv[i] << " ";
  command = os.str();

  std::string cfgFileName("iqrfapp.json");
  std::string localMqName("iqrf-daemon-100");
  std::string remoteMqName("iqrf-daemon-110");
  std::ifstream f;

  f.open(cfgFileName);

  if (!f.is_open()) {
    std::string pth = "/etc/iqrf-daemon/";
    cfgFileName = pth + cfgFileName;
    f.open(cfgFileName);
  }

  if (f.is_open()) {
    TRC_DBG("Reading cfg from: " << PAR(cfgFileName));

    rapidjson::Document cfg;
    try {
      jutils::parseJsonFile(cfgFileName, cfg);
      jutils::assertIsObject("", cfg);

      localMqName = jutils::getPossibleMemberAs<std::string>("LocalMqName", cfg, localMqName);
      remoteMqName = jutils::getPossibleMemberAs<std::string>("RemoteMqName", cfg, remoteMqName);

      int timeout = -1;
      timeout = jutils::getPossibleMemberAs<int>("DefaultTimeout", cfg, timeout);
      if (timeout >= 0) {
        defaultTimeout = timeout;
      }
    }
    catch (std::logic_error &e) {
      CATCH_EX("Cannot read configuration file: " << PAR(cfgFileName), std::logic_error, e);
      TRC_DBG("Using default params");
    }
  }
  else {
    TRC_DBG("Using default params");
  }

  if (json) {
    int timeout = parseCommand(command);
    if (timeout >= 0) {
      defaultTimeout = timeout;
    }
    TRC_DBG("New timeout: " << PAR(defaultTimeout));
  }

  if (raw) {
    int timeout = -1;
    timeout = std::stoi(rawTimeout);
    if (timeout >= 0) {
      defaultTimeout = timeout;
    }
    TRC_DBG("New timeout: " << PAR(defaultTimeout));
  }

  TRC_DBG(PAR(remoteMqName) << PAR(localMqName));

  MqChannel* mqChannel = ant_new MqChannel(remoteMqName, localMqName, 1024);

  // received messages from IQRF channel are pushed to IQRF MessageQueueChannel
  mqChannel->registerReceiveFromHandler([&](const std::basic_string<unsigned char>& msg) -> int {
    return handleMessageFromMq(msg); });

  bool run = true;

  if (cmdl) {
    std::cout << std::endl << "iqrfapp " << PAR(IQRFAPP_VERSION) << PAR(BUILD_TIMESTAMP) << std::endl;
  }

  while (run)
  {
    if (cmdl) {
      std::cout << std::endl << ">> ";
      getline(std::cin, command);
    }

    ustring msgu((unsigned char*)command.data(), command.size());

    if(!readonly) {
      try {
        mqChannel->sendTo(msgu);
        sentFlag = true;
      }
      catch (std::exception& e) {
        TRC_DBG("SendTo failed: " << e.what());
        std::cerr << "Send failure" << std::endl;
      }
    }
    else {
      std::cout << "Listening for asynchronous messages, timeout: " << defaultTimeout << std::endl;
    }

    if (defaultTimeout != 0) {
      for (int i = 0; i < defaultTimeout; i++) {
        std::this_thread::sleep_for(std::chrono::milliseconds(1));
        // exit when we receive response
        if (exitFlag) break;
      }
    }
    // defaultTimeout == 0 means waiting until there is the response
    else {
      while (!exitFlag)
        ;
    }

    if (!cmdl) {
      break;
    }
  }

//TODO solve blocking dtor on WIN
#ifndef WIN
  delete mqChannel;
#endif

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

#include "TaskQueue.h"
#include "MqChannel.h"
#include "PlatformDep.h"
#include "IqrfLogging.h"
#include "JsonUtils.h"
#include "VersionInfo.h"
#include <string>
#include <fstream>
#include <stdexcept>

class Iqrfapp
{
public:
  Iqrfapp();
  ~Iqrfapp();
  int run(const std::vector<std::string>& params);

private:
  const std::string CMD_HELP = "help";
  const std::string CMD_READO = "readonly";
  const std::string CMD_READA = "readall";
  const std::string CMD_RAW = "raw";
  const std::string CMD_CONF = "conf";
  const std::string CMD_JSON = "json";
  const std::string CMD_EXIT = "exit";

  int runCmd(const std::vector<std::string>& params);
  void handleMessageReceived(const ustring& message);
  bool waitForMessageReceived(int extraTime = 0);
  void showWaitForMessageReceivedResult(bool res);
  void setTimeout(int timeout);
  void sendParamsAsMessage(const std::vector<std::string>& params);

  void interactiveCmd();
  void helpCmd();
  void readonlyCmd(const std::vector<std::string>& params);
  void readallCmd(const std::vector<std::string>& params);
  void rawCmd(const std::vector<std::string>& params);
  void confCmd(const std::vector<std::string>& params);
  void jsonCmd(const std::vector<std::string>& params);

  std::string m_cfgFileName;
  std::string m_localMqName;
  std::string m_remoteMqName;
  int m_defaultTimeout = 5000;

  TaskQueue<ustring> *m_msgQueue = nullptr;
  MqChannel* m_mqChannel = nullptr;

  std::mutex m_mutexMessageReceived;
  std::condition_variable m_conditionMessageReceived;
  bool m_flagMessageReceived = false;
  ustring m_messageReceived;
  int m_actualTimeout = 5000;

  bool exitFlag = false;
  bool sentFlag = false;
};

TRC_INIT()

//TODO cmdl params are not properly parsed in expected cmdl tools way - maybe boost?
int main(int argc, char** argv)
{
  TRC_START("", iqrf::Level::inf, 0);

  TRC_ENTER("");

  Iqrfapp iqrfapp;

  std::vector<std::string> params;

  for (int i = 1; i < argc; i++)
    params.push_back(argv[i]);

  int retval = iqrfapp.run(params);

  TRC_LEAVE(PAR(retval));
  return retval;
}

Iqrfapp::Iqrfapp()
{
  TRC_ENTER("");

  std::string m_cfgFileName = "iqrfapp.json";
  std::string localMqName = "iqrf-daemon-100";
  std::string remoteMqName = "iqrf-daemon-110";

  std::ifstream f;

  //open in working directory
  f.open(m_cfgFileName);

  if (!f.is_open()) {
    std::string pth = "/etc/iqrf-daemon/";
    m_cfgFileName = pth + m_cfgFileName;

    //open in default path
    f.open(m_cfgFileName);
  }

  if (f.is_open()) {
    TRC_DBG("Reading cfg from: " << PAR(m_cfgFileName));

    rapidjson::Document cfg;
    try {
      jutils::parseJsonFile(m_cfgFileName, cfg);
      jutils::assertIsObject("", cfg);

      m_localMqName = jutils::getPossibleMemberAs<std::string>("LocalMqName", cfg, m_localMqName);
      m_remoteMqName = jutils::getPossibleMemberAs<std::string>("RemoteMqName", cfg, m_remoteMqName);

      int timeout = -1;
      timeout = jutils::getPossibleMemberAs<int>("DefaultTimeout", cfg, timeout);
      if (timeout >= 0) {
        m_defaultTimeout = timeout;
      }
    }
    catch (std::logic_error &e) {
      CATCH_EX("Cannot JSON parse configuration file: " << PAR(m_cfgFileName), std::logic_error, e);
      TRC_DBG("Using default params");
    }
  }
  else {
    TRC_DBG("Using default params");
  }

  f.close();

  //we work with these params
  TRC_DBG(PAR(remoteMqName) << PAR(localMqName) << PAR(m_defaultTimeout));

  //instantiate incomming message queue
  m_msgQueue = ant_new TaskQueue<ustring>([&](ustring msg) {
    handleMessageReceived(msg);
  });

  //instantiate MQ channel
  m_mqChannel = ant_new MqChannel(remoteMqName, localMqName, 1024);

  //register message handler for messages received from MQ channel
  m_mqChannel->registerReceiveFromHandler([&](const std::basic_string<unsigned char>& msg) -> int {
    //msgs are pushed to the queue here
    m_msgQueue->pushToQueue(msg);
    return 0;
  });

  TRC_LEAVE("");
}

Iqrfapp::~Iqrfapp()
{
  delete m_msgQueue;
  //TODO solve blocking dtor on WIN
#ifndef WIN
  delete m_mqChannel;
#endif
}

int Iqrfapp::run(const std::vector<std::string>& params)
{
  TRC_ENTER("");

  int retval = 0;

  if (0 == params.size()) {
    interactiveCmd();
  }
  else {
    retval = runCmd(params);
  }

  TRC_LEAVE(PAR(retval));
  return retval;
}

int Iqrfapp::runCmd(const std::vector<std::string>& params)
{
  TRC_ENTER("");

  int retval = 0;

  if (0 == params.size()) {
    retval = -1;
  }
  else {
    const std::string& cmd = params[0];

    try {
      if (cmd == CMD_HELP) {
        helpCmd();
      }
      else if (cmd == CMD_READO) {
        readonlyCmd(params);
      }
      else if (cmd == CMD_READA) {
        readallCmd(params);
      }
      else if (cmd == CMD_RAW) {
        rawCmd(params);
      }
      else if (cmd == CMD_CONF) {
        confCmd(params);
      }
      else if (cmd == CMD_EXIT) {
        retval = -3;
      }
      else if (cmd == CMD_JSON) {
        jsonCmd(params);
      }
      else {
        jsonCmd(params);
      }
    }
    catch (std::logic_error& e) {
      std::cerr << e.what() << std::endl;
      helpCmd();
      retval = -1;
    }
  }
  TRC_LEAVE(PAR(retval));
  return retval;
}

void Iqrfapp::handleMessageReceived(const ustring& message)
{
  TRC_ENTER("");
  TRC_DBG("Received from MQ: " << std::endl << FORM_HEX(message.data(), message.size()));

  {
    std::unique_lock<std::mutex> lck(m_mutexMessageReceived);
    m_messageReceived = message;
    m_flagMessageReceived = true;
    m_conditionMessageReceived.notify_all();
  }

  TRC_LEAVE("");
}

bool Iqrfapp::waitForMessageReceived(int extraTime)
{
  TRC_ENTER("");

  bool retval = false;

  if (m_actualTimeout <= 0) {
    std::unique_lock<std::mutex> lck(m_mutexMessageReceived);
    //wait for message
    m_conditionMessageReceived.wait(lck, [&] { return m_flagMessageReceived; }); //lock is released in wait
    //lock is reacquired here
    m_flagMessageReceived = false;
    retval = true;
  }
  else {
    std::unique_lock<std::mutex> lck(m_mutexMessageReceived);
    //wait for message
    //add extraTime to extend waiting time to allow daemon process timeout response (otherwise it end earlier)
    if (m_conditionMessageReceived.wait_for(lck, std::chrono::milliseconds(m_actualTimeout + extraTime), [&] { return m_flagMessageReceived; })) {
      //finished waiting
      m_flagMessageReceived = false;
      retval = true;
    }
    else {
      //timeout
      m_flagMessageReceived = false;
      retval = false;
    }
  }

  TRC_LEAVE(PAR(retval));
  return retval;
}

void Iqrfapp::showWaitForMessageReceivedResult(bool res)
{
  if (res) {
    std::string msg((char*)m_messageReceived.data(), m_messageReceived.size());
    std::cout << "Received: " << msg << std::endl;
  }
  else {
    std::cout << "Timeout" << std::endl;
  }
}

void Iqrfapp::setTimeout(int timeout)
{
  TRC_ENTER("");
  if (timeout >= 0) {
    m_actualTimeout = timeout;
    TRC_DBG("Set: " PAR(m_actualTimeout));
  }
  else {
    m_actualTimeout = m_defaultTimeout;
    TRC_WAR(PAR(timeout) << "is invalid keep " <<  PAR(m_defaultTimeout));

  }
  TRC_LEAVE("");
}

void Iqrfapp::sendParamsAsMessage(const std::vector<std::string>& params)
{
  TRC_ENTER("");
  std::ostringstream os;
  for (const auto & par : params)
    os << par << " ";

  std::string msg = os.str();
  ustring msgu((unsigned char*)msg.data(), msg.size());

  try {
    m_mqChannel->sendTo(msgu);
  }
  catch (std::exception& e) {
    TRC_DBG("SendTo failed: " << e.what());
    std::cerr << "Send failure: " << e.what() << std::endl;
  }
  TRC_LEAVE("");
}

void Iqrfapp::interactiveCmd()
{
  TRC_ENTER("");
  while (true)
  {
    std::string command;
    std::cout << std::endl << ">> ";
    getline(std::cin, command);

    //parse command
    std::vector<std::string> params;
    std::istringstream is(command);
    std::string par;
    while (!is.eof()) {
      is >> par;
      params.push_back(par);
    }

    int retval = runCmd(params);
    if (-3 == retval)
      break;
  }

  TRC_LEAVE("");
}

void Iqrfapp::helpCmd()
{
  std::cerr << "Usage" << std::endl;
  std::cerr << "  iqrfapp" << std::endl;
  std::cerr << "  iqrfapp help" << std::endl;
  std::cerr << "  iqrfapp readonly [timeout <ValueInMs>]" << std::endl;
  std::cerr << "  iqrfapp readall" << std::endl;
  std::cerr << "  iqrfapp raw <DpaBytesSeparatedByDots> [timeout <ValueInMs>]" << std::endl;
  std::cerr << "  iqrfapp conf operational|forwarding|service" << std::endl;
  std::cerr << "  iqrfapp [json] <JsonDpaRequest>" << std::endl;
  std::cerr << "Examples" << std::endl;
  std::cerr << "  iqrfapp" << std::endl;
  std::cerr << "  iqrfapp help" << std::endl;
  std::cerr << "  iqrfapp raw 01.00.06.03.ff.ff timeout 1000" << std::endl;
  std::cerr << "  iqrfapp conf operational" << std::endl;
  std::cerr << "  iqrfapp \"{\\\"ctype\\\":\\\"dpa\\\",\\\"type\\\":\\\"raw\\\",\\\"timeout\\\":1000,\\\"request\\\":\\\"01.00.06.03.ff.ff\\\"}\"" << std::endl;
  std::cerr << "Tips" << std::endl;
  std::cerr << "  Adjust default timeout in iqrfapp.json to the needs of the application using iqrfapp tool or define timeout as cmd param." << std::endl;
  std::cerr << "  Default timeout in iqrfapp.json is 5000 ms." << std::endl;
}

void Iqrfapp::readonlyCmd(const std::vector<std::string>& params)
{
  TRC_ENTER("");

  if (params.size() != 1 && params.size() != 3) {
    throw std::logic_error("expected 1 or 3 parameters");
  }

  int timeout = m_defaultTimeout;

  if (params.size() == 3) {
    if (params[1] != "timeout") {
      throw std::logic_error("expected 2nd parameter: timeout");
    }

    try {
      timeout = std::stoi(params[2]);
    }
    catch (std::invalid_argument&) {
      throw std::logic_error("expected 3rd parameter <millis> representing integer value");
    }
  }

  setTimeout(timeout);
  std::cout << "Listening for asynchronous messages: " << NAME_PAR(timeout, m_actualTimeout) << std::endl;
  bool res = waitForMessageReceived();
  showWaitForMessageReceivedResult(res);

  TRC_LEAVE("");
}

void Iqrfapp::readallCmd(const std::vector<std::string>& params)
{
  TRC_ENTER("");

  if (params.size() != 1) {
    throw std::logic_error("expected 1 parameters");
  }

  //TODO break by CTRL-C
  while (true) {
    std::cout << "Listening for asynchronous messages (stop by CTRL-C): " << std::endl;
    setTimeout(0);
    bool res = waitForMessageReceived();
    showWaitForMessageReceivedResult(res);
  }

  TRC_LEAVE("");
}

void Iqrfapp::rawCmd(const std::vector<std::string>& params)
{
  TRC_ENTER("");
  if (params.size() != 2 && params.size() != 4) {
    throw std::logic_error("expected 2 or 4 parameters");
  }

  int timeout = m_defaultTimeout;

  if (params.size() == 4) {
    if (params[2] != "timeout") {
      throw std::logic_error("expected 3rd parameter: timeout");
    }

    try {
      timeout = std::stoi(params[3]);
    }
    catch (std::invalid_argument&) {
      throw std::logic_error("expected 4th parameter <millis> representing integer value");
    }
  }

  setTimeout(timeout);
  sendParamsAsMessage(params);

  bool res = waitForMessageReceived(500);
  showWaitForMessageReceivedResult(res);

  TRC_LEAVE("");
}

void Iqrfapp::confCmd(const std::vector<std::string>& params)
{
  TRC_ENTER("");
  if (params.size() != 2) {
    throw std::logic_error("expected 2 parameters");
  }

  const std::string par2 = params[1];
  if (par2 != "operational" && par2 != "forwarding" && par2 != "service") {
    throw std::logic_error("expected 3rd parameter: [operational | forwarding | service]");
  }
  else {
  }

  sendParamsAsMessage(params);

  bool res = waitForMessageReceived(500);
  showWaitForMessageReceivedResult(res);

  TRC_LEAVE("");
}

void Iqrfapp::jsonCmd(const std::vector<std::string>& params)
{
  TRC_ENTER("");
  std::string json;
  if (params.size() == 2) {
    json = params[1]; //possible format: json <JSON>
  }
  else if (params.size() == 1) {
    json = params[0]; //possible format: <JSON>
  }
  else {
    throw std::logic_error("expected 1 or 2 parameters");
  }

  //parse JSON
  rapidjson::Document doc;
  int timeout = m_defaultTimeout;

  try {
    jutils::parseString(json, doc);
    jutils::assertIsObject("", doc);
    timeout = jutils::getPossibleMemberAs<int>("timeout", doc, timeout); //optional
  }
  catch (std::exception &e) {
    std::string errstr = "expected JSON format: ";
    errstr += e.what();
    throw std::logic_error(errstr);
  }

  setTimeout(timeout);
  sendParamsAsMessage(params);

  bool res = waitForMessageReceived(500);
  showWaitForMessageReceivedResult(res);

  TRC_LEAVE("");
}
<|endoftext|>


<commit_before>/* Copyright 2015 Google Inc. All Rights Reserved.

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.
==============================================================================*/

#define EIGEN_USE_THREADS

#include "tensorflow/core/kernels/dense_update_ops.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/register_types.h"
#include "tensorflow/core/kernels/assign_op.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/platform/mutex.h"
#include "tensorflow/core/platform/types.h"

namespace tensorflow {

template <typename Device, typename T>
class AssignOpT : public AssignOp {
 public:
  using AssignOp::AssignOp;

  void Copy(OpKernelContext* context, Tensor* lhs, const Tensor& rhs) override {
    functor::DenseUpdate<Device, T, ASSIGN> copy;
    copy(context->eigen_device<Device>(), lhs->flat<T>(), rhs.flat<T>());
  }
};

// TODO(jeff): Get rid of use_exclusive_lock_ option
template <typename Device, typename T, DenseUpdateType OP>
class DenseUpdateOp : public OpKernel {
 public:
  explicit DenseUpdateOp(OpKernelConstruction* context) : OpKernel(context) {
    OP_REQUIRES_OK(context,
                   context->GetAttr("use_locking", &use_exclusive_lock_));
    const DataType dt = DataTypeToEnum<T>::v();
    OP_REQUIRES_OK(context, context->MatchSignature({MakeRefType(dt), dt},
                                                    {MakeRefType(dt)}));
  }

  void Compute(OpKernelContext* context) override {
    // We always return the input ref.
    context->forward_ref_input_to_ref_output(0, 0);

    if (use_exclusive_lock_) {
      mutex_lock l(*context->input_ref_mutex(0));
      DoUpdate(context);
    } else {
      DoUpdate(context);
    }
  }

 private:
  void DoUpdate(OpKernelContext* context) {
    Tensor Tparams = context->mutable_input(0, use_exclusive_lock_);
    const Tensor& Tupdate = context->input(1);
    OP_REQUIRES(context, Tparams.IsInitialized(),
                errors::FailedPrecondition("Attempting to use uninitialized "
                                           "parameters: ",
                                           def().input(0)));
    OP_REQUIRES(
        context, Tparams.IsSameSize(Tupdate),
        errors::InvalidArgument("Parameters and update must be the same size"));

    functor::DenseUpdate<Device, T, OP> update_functor;
    update_functor(context->eigen_device<Device>(), Tparams.flat<T>(),
                   Tupdate.flat<T>());
  }

  bool use_exclusive_lock_;
};

typedef Eigen::ThreadPoolDevice CPUDevice;
typedef Eigen::GpuDevice GPUDevice;

#define REGISTER_KERNELS(type)                                     \
  REGISTER_KERNEL_BUILDER(                                         \
      Name("Assign").Device(DEVICE_CPU).TypeConstraint<type>("T"), \
      AssignOpT<CPUDevice, type>);

TF_CALL_ALL_TYPES(REGISTER_KERNELS);
#undef REGISTER_KERNELS

#if GOOGLE_CUDA
// Only register 'Assign' on GPU for the subset of types also supported by
// 'Variable' (see variable_ops.cc.)
#define REGISTER_GPU_KERNELS(type)                                 \
  namespace functor {                                              \
  template <>                                                      \
  void DenseUpdate<GPUDevice, type, ASSIGN>::operator()(           \
      const GPUDevice& d, typename TTypes<type>::Flat lhs,         \
      typename TTypes<type>::ConstFlat rhs);                       \
  extern template struct DenseUpdate<GPUDevice, type, ASSIGN>;     \
  }                                                                \
  REGISTER_KERNEL_BUILDER(                                         \
      Name("Assign").Device(DEVICE_GPU).TypeConstraint<type>("T"), \
      AssignOpT<GPUDevice, type>);

TF_CALL_GPU_NUMBER_TYPES(REGISTER_GPU_KERNELS);
#undef REGISTER_GPU_KERNELS
#endif  // GOOGLE_CUDA

#define REGISTER_KERNELS(type)                                        \
  REGISTER_KERNEL_BUILDER(                                            \
      Name("AssignAdd").Device(DEVICE_CPU).TypeConstraint<type>("T"), \
      DenseUpdateOp<CPUDevice, type, DenseUpdateType::ADD>);          \
  REGISTER_KERNEL_BUILDER(                                            \
      Name("AssignSub").Device(DEVICE_CPU).TypeConstraint<type>("T"), \
      DenseUpdateOp<CPUDevice, type, DenseUpdateType::SUB>);

TF_CALL_NUMBER_TYPES(REGISTER_KERNELS);
#undef REGISTER_KERNELS

#if GOOGLE_CUDA
// Forward declarations of the functor specializations for GPU.
namespace functor {
#define DECLARE_GPU_SPEC_FOR_OP(T, OP)                     \
  template <>                                              \
  void DenseUpdate<GPUDevice, T, OP>::operator()(          \
      const GPUDevice& d, typename TTypes<T>::Flat params, \
      typename TTypes<T>::ConstFlat update);               \
  extern template struct DenseUpdate<GPUDevice, T, OP>
#define DECLARE_GPU_SPEC(T)                         \
  DECLARE_GPU_SPEC_FOR_OP(T, DenseUpdateType::ADD); \
  DECLARE_GPU_SPEC_FOR_OP(T, DenseUpdateType::SUB)
TF_CALL_GPU_NUMBER_TYPES(DECLARE_GPU_SPEC);
#undef DECLARE_GPU_SPEC
#undef DECLARE_GPU_SPEC_FOR_OP
}  // namespace functor

#define REGISTER_GPU_KERNELS(type)                                    \
  REGISTER_KERNEL_BUILDER(                                            \
      Name("AssignAdd").Device(DEVICE_GPU).TypeConstraint<type>("T"), \
      DenseUpdateOp<GPUDevice, type, DenseUpdateType::ADD>);          \
  REGISTER_KERNEL_BUILDER(                                            \
      Name("AssignSub").Device(DEVICE_GPU).TypeConstraint<type>("T"), \
      DenseUpdateOp<GPUDevice, type, DenseUpdateType::SUB>);
TF_CALL_GPU_NUMBER_TYPES(REGISTER_GPU_KERNELS);
#undef REGISTER_GPU_KERNELS
#endif  // end GOOGLE_CUDA

}  // namespace tensorflow
<commit_msg>Register quantized types for dense assign. Change: 119104425<commit_after>/* Copyright 2015 Google Inc. All Rights Reserved.

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.
==============================================================================*/

#define EIGEN_USE_THREADS

#include "tensorflow/core/kernels/dense_update_ops.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/register_types.h"
#include "tensorflow/core/kernels/assign_op.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/platform/mutex.h"
#include "tensorflow/core/platform/types.h"

namespace tensorflow {

template <typename Device, typename T>
class AssignOpT : public AssignOp {
 public:
  using AssignOp::AssignOp;

  void Copy(OpKernelContext* context, Tensor* lhs, const Tensor& rhs) override {
    functor::DenseUpdate<Device, T, ASSIGN> copy;
    copy(context->eigen_device<Device>(), lhs->flat<T>(), rhs.flat<T>());
  }
};

// TODO(jeff): Get rid of use_exclusive_lock_ option
template <typename Device, typename T, DenseUpdateType OP>
class DenseUpdateOp : public OpKernel {
 public:
  explicit DenseUpdateOp(OpKernelConstruction* context) : OpKernel(context) {
    OP_REQUIRES_OK(context,
                   context->GetAttr("use_locking", &use_exclusive_lock_));
    const DataType dt = DataTypeToEnum<T>::v();
    OP_REQUIRES_OK(context, context->MatchSignature({MakeRefType(dt), dt},
                                                    {MakeRefType(dt)}));
  }

  void Compute(OpKernelContext* context) override {
    // We always return the input ref.
    context->forward_ref_input_to_ref_output(0, 0);

    if (use_exclusive_lock_) {
      mutex_lock l(*context->input_ref_mutex(0));
      DoUpdate(context);
    } else {
      DoUpdate(context);
    }
  }

 private:
  void DoUpdate(OpKernelContext* context) {
    Tensor Tparams = context->mutable_input(0, use_exclusive_lock_);
    const Tensor& Tupdate = context->input(1);
    OP_REQUIRES(context, Tparams.IsInitialized(),
                errors::FailedPrecondition("Attempting to use uninitialized "
                                           "parameters: ",
                                           def().input(0)));
    OP_REQUIRES(
        context, Tparams.IsSameSize(Tupdate),
        errors::InvalidArgument("Parameters and update must be the same size"));

    functor::DenseUpdate<Device, T, OP> update_functor;
    update_functor(context->eigen_device<Device>(), Tparams.flat<T>(),
                   Tupdate.flat<T>());
  }

  bool use_exclusive_lock_;
};

typedef Eigen::ThreadPoolDevice CPUDevice;
typedef Eigen::GpuDevice GPUDevice;

#define REGISTER_KERNELS(type)                                     \
  REGISTER_KERNEL_BUILDER(                                         \
      Name("Assign").Device(DEVICE_CPU).TypeConstraint<type>("T"), \
      AssignOpT<CPUDevice, type>);

TF_CALL_ALL_TYPES(REGISTER_KERNELS);
TF_CALL_QUANTIZED_TYPES(REGISTER_KERNELS);
#undef REGISTER_KERNELS

#if GOOGLE_CUDA
// Only register 'Assign' on GPU for the subset of types also supported by
// 'Variable' (see variable_ops.cc.)
#define REGISTER_GPU_KERNELS(type)                                 \
  namespace functor {                                              \
  template <>                                                      \
  void DenseUpdate<GPUDevice, type, ASSIGN>::operator()(           \
      const GPUDevice& d, typename TTypes<type>::Flat lhs,         \
      typename TTypes<type>::ConstFlat rhs);                       \
  extern template struct DenseUpdate<GPUDevice, type, ASSIGN>;     \
  }                                                                \
  REGISTER_KERNEL_BUILDER(                                         \
      Name("Assign").Device(DEVICE_GPU).TypeConstraint<type>("T"), \
      AssignOpT<GPUDevice, type>);

TF_CALL_GPU_NUMBER_TYPES(REGISTER_GPU_KERNELS);
#undef REGISTER_GPU_KERNELS
#endif  // GOOGLE_CUDA

#define REGISTER_KERNELS(type)                                        \
  REGISTER_KERNEL_BUILDER(                                            \
      Name("AssignAdd").Device(DEVICE_CPU).TypeConstraint<type>("T"), \
      DenseUpdateOp<CPUDevice, type, DenseUpdateType::ADD>);          \
  REGISTER_KERNEL_BUILDER(                                            \
      Name("AssignSub").Device(DEVICE_CPU).TypeConstraint<type>("T"), \
      DenseUpdateOp<CPUDevice, type, DenseUpdateType::SUB>);

TF_CALL_NUMBER_TYPES(REGISTER_KERNELS);
#undef REGISTER_KERNELS

#if GOOGLE_CUDA
// Forward declarations of the functor specializations for GPU.
namespace functor {
#define DECLARE_GPU_SPEC_FOR_OP(T, OP)                     \
  template <>                                              \
  void DenseUpdate<GPUDevice, T, OP>::operator()(          \
      const GPUDevice& d, typename TTypes<T>::Flat params, \
      typename TTypes<T>::ConstFlat update);               \
  extern template struct DenseUpdate<GPUDevice, T, OP>
#define DECLARE_GPU_SPEC(T)                         \
  DECLARE_GPU_SPEC_FOR_OP(T, DenseUpdateType::ADD); \
  DECLARE_GPU_SPEC_FOR_OP(T, DenseUpdateType::SUB)
TF_CALL_GPU_NUMBER_TYPES(DECLARE_GPU_SPEC);
#undef DECLARE_GPU_SPEC
#undef DECLARE_GPU_SPEC_FOR_OP
}  // namespace functor

#define REGISTER_GPU_KERNELS(type)                                    \
  REGISTER_KERNEL_BUILDER(                                            \
      Name("AssignAdd").Device(DEVICE_GPU).TypeConstraint<type>("T"), \
      DenseUpdateOp<GPUDevice, type, DenseUpdateType::ADD>);          \
  REGISTER_KERNEL_BUILDER(                                            \
      Name("AssignSub").Device(DEVICE_GPU).TypeConstraint<type>("T"), \
      DenseUpdateOp<GPUDevice, type, DenseUpdateType::SUB>);
TF_CALL_GPU_NUMBER_TYPES(REGISTER_GPU_KERNELS);
#undef REGISTER_GPU_KERNELS
#endif  // end GOOGLE_CUDA

}  // namespace tensorflow
<|endoftext|>


<commit_before>#include <GG/PtRect.h>

#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE StrongIntegralTypedef

#include <boost/test/unit_test.hpp>

int i = 7;
double d = 3.1;
GG::X x(2);
GG::X_d xd(5.1);

int temp_int;
double temp_double;

#define ARITHMETIC_ITERATION(op)                                   \
    BOOST_CHECK_EQUAL(Value(i op x), i op Value(x));               \
    BOOST_CHECK_EQUAL(Value(x op i), Value(x) op i);               \
    BOOST_CHECK_EQUAL(Value(d op x), d op Value(x));               \
    BOOST_CHECK_EQUAL(Value(x op d), Value(x) op d);               \
    BOOST_CHECK_EQUAL(Value(x op x), Value(x) op Value(x));        \
    BOOST_CHECK_EQUAL(Value(x op xd), Value(x) op Value(xd));      \
    BOOST_CHECK_EQUAL(Value(xd op x), Value(xd) op Value(x));      \
                                                                   \
    BOOST_CHECK_EQUAL(Value(i op xd), i op Value(xd));             \
    BOOST_CHECK_EQUAL(Value(xd op i), Value(xd) op i);             \
    BOOST_CHECK_EQUAL(Value(d op xd), d op Value(xd));             \
    BOOST_CHECK_EQUAL(Value(xd op d), Value(xd) op d);             \
    BOOST_CHECK_EQUAL(Value(xd op xd), Value(xd) op Value(xd))

#define RESET()                                 \
    i = 7;                                      \
    d = 3.1;                                    \
    x = GG::X(2);                               \
    xd = GG::X_d(5.1)

#define ASSIGN_ARITHMETIC_ITERATION(op)                                 \
    BOOST_CHECK_EQUAL(Value(x op i), (temp_int = Value(x)) op i); RESET(); \
    BOOST_CHECK_EQUAL(Value(x op d), (temp_int = Value(x)) op d); RESET(); \
    BOOST_CHECK_EQUAL(Value(x op x), (temp_int = Value(x)) op (temp_int = Value(x))); RESET(); \
    BOOST_CHECK_EQUAL(Value(x op xd), (temp_int = Value(x)) op (temp_double = Value(xd))); RESET(); \
    BOOST_CHECK_EQUAL(Value(xd op x), (temp_double = Value(xd)) op (temp_int = Value(x))); RESET(); \
                                                                        \
    BOOST_CHECK_EQUAL(Value(xd op i), (temp_double = Value(xd)) op i); RESET(); \
    BOOST_CHECK_EQUAL(Value(xd op d), (temp_double = Value(xd)) op d); RESET(); \
    BOOST_CHECK_EQUAL(Value(xd op xd), (temp_double = Value(xd)) op (temp_double = Value(xd))); RESET()

#define COMPARISON_ITERATION(op)                                 \
    BOOST_CHECK_EQUAL(i op x, i op Value(x));                    \
    BOOST_CHECK_EQUAL(x op i, Value(x) op i);                    \
    BOOST_CHECK_EQUAL(d op x, d op Value(x));                    \
    BOOST_CHECK_EQUAL(x op d, Value(x) op d);                    \
    BOOST_CHECK_EQUAL(x op x, Value(x) op Value(x));             \
    BOOST_CHECK_EQUAL(x op xd, Value(x) op Value(xd));           \
    BOOST_CHECK_EQUAL(xd op x, Value(xd) op Value(x));           \
                                                                 \
    BOOST_CHECK_EQUAL(i op xd, i op Value(xd));                  \
    BOOST_CHECK_EQUAL(xd op i, Value(xd) op i);                  \
    BOOST_CHECK_EQUAL(d op xd, d op Value(xd));                  \
    BOOST_CHECK_EQUAL(xd op d, Value(xd) op d);                  \
    BOOST_CHECK_EQUAL(xd op xd, Value(xd) op Value(xd))

BOOST_AUTO_TEST_CASE( arithmetic )
{
    ARITHMETIC_ITERATION(+);
    ARITHMETIC_ITERATION(-);
    ARITHMETIC_ITERATION(*);
    BOOST_CHECK_EQUAL(Value(x / i), Value(x) / i);
    BOOST_CHECK_EQUAL(Value(x / d), Value(x) / d);
    BOOST_CHECK_EQUAL(Value(x / x), Value(x) / Value(x));
    BOOST_CHECK_EQUAL(Value(x / xd), Value(x) / Value(xd));
    BOOST_CHECK_EQUAL(Value(xd / x), Value(xd) / Value(x));
    BOOST_CHECK_EQUAL(Value(xd / i), Value(xd) / i);
    BOOST_CHECK_EQUAL(Value(xd / d), Value(xd) / d);
    BOOST_CHECK_EQUAL(Value(xd / xd), Value(xd) / Value(xd));

    ASSIGN_ARITHMETIC_ITERATION(+=);
    ASSIGN_ARITHMETIC_ITERATION(-=);
    ASSIGN_ARITHMETIC_ITERATION(*=);
    ASSIGN_ARITHMETIC_ITERATION(/=);
}

BOOST_AUTO_TEST_CASE( comparison )
{
    COMPARISON_ITERATION(<);
    COMPARISON_ITERATION(>);
    COMPARISON_ITERATION(==);
    COMPARISON_ITERATION(!=);
    COMPARISON_ITERATION(<=);
    COMPARISON_ITERATION(>=);
}

BOOST_AUTO_TEST_CASE( unary )
{
    BOOST_CHECK_EQUAL(++x, ++(temp_int = Value(x)));
    BOOST_CHECK_EQUAL(++xd, ++(temp_double = Value(xd)));
    BOOST_CHECK_EQUAL(x++, (temp_int = Value(x))++);
    BOOST_CHECK_EQUAL(xd++, (temp_double = Value(xd))++);
    BOOST_CHECK_EQUAL(x, temp_int);
    BOOST_CHECK_EQUAL(xd, temp_double);

    BOOST_CHECK_EQUAL(--x, --(temp_int = Value(x)));
    BOOST_CHECK_EQUAL(--xd, --(temp_double = Value(xd)));
    BOOST_CHECK_EQUAL(x--, (temp_int = Value(x))--);
    BOOST_CHECK_EQUAL(xd--, (temp_double = Value(xd))--);
    BOOST_CHECK_EQUAL(x, temp_int);
    BOOST_CHECK_EQUAL(xd, temp_double);

    BOOST_CHECK_EQUAL(!x, !Value(x));
    BOOST_CHECK_EQUAL(!xd, !Value(xd));

    BOOST_CHECK_EQUAL(-x, -Value(x));
    BOOST_CHECK_EQUAL(-xd, -Value(xd));
}
<commit_msg>Fixed the excruciatingly badly written tests in TestStrongIntegralTypedef.cpp.<commit_after>#include <GG/PtRect.h>

#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE StrongIntegralTypedef

#include <boost/test/unit_test.hpp>

int i = 7;
double d = 3.1;
GG::X x(2);
GG::X_d xd(5.1);

int temp_int;
int temp_int_1;
int temp_int_2;
double temp_double;
double temp_double_1;
double temp_double_2;

#define ARITHMETIC_ITERATION(op)                                   \
    BOOST_CHECK_EQUAL(Value(i op x), i op Value(x));               \
    BOOST_CHECK_EQUAL(Value(x op i), Value(x) op i);               \
    BOOST_CHECK_EQUAL(Value(d op x), d op Value(x));               \
    BOOST_CHECK_EQUAL(Value(x op d), Value(x) op d);               \
    BOOST_CHECK_EQUAL(Value(x op x), Value(x) op Value(x));        \
    BOOST_CHECK_EQUAL(Value(x op xd), Value(x) op Value(xd));      \
    BOOST_CHECK_EQUAL(Value(xd op x), Value(xd) op Value(x));      \
                                                                   \
    BOOST_CHECK_EQUAL(Value(i op xd), i op Value(xd));             \
    BOOST_CHECK_EQUAL(Value(xd op i), Value(xd) op i);             \
    BOOST_CHECK_EQUAL(Value(d op xd), d op Value(xd));             \
    BOOST_CHECK_EQUAL(Value(xd op d), Value(xd) op d);             \
    BOOST_CHECK_EQUAL(Value(xd op xd), Value(xd) op Value(xd))

#define RESET()                                 \
    i = 7;                                      \
    d = 3.1;                                    \
    x = GG::X(2);                               \
    xd = GG::X_d(5.1)

#define ASSIGN_ARITHMETIC_ITERATION(op)                                 \
    temp_int_1 = Value(x op i);                                         \
    RESET();                                                            \
    temp_int = Value(x);                                                \
    temp_int_2 = temp_int op i;                                         \
    RESET();                                                            \
    BOOST_CHECK_EQUAL(temp_int_1, temp_int_2);                          \
                                                                        \
    temp_double_1 = Value(x op d);                                      \
    RESET();                                                            \
    temp_int = Value(x);                                                \
    temp_double_2 = temp_int op d;                                      \
    RESET();                                                            \
    BOOST_CHECK_EQUAL(temp_double_1, temp_double_2);                    \
                                                                        \
    temp_int_1 = Value(x op x);                                         \
    RESET();                                                            \
    temp_int = Value(x);                                                \
    temp_int_2 = temp_int op temp_int;                                  \
    RESET();                                                            \
    BOOST_CHECK_EQUAL(temp_int_1, temp_int_2);                          \
                                                                        \
    temp_double_1 = Value(x op xd);                                     \
    RESET();                                                            \
    temp_int = Value(x);                                                \
    temp_double = Value(xd);                                            \
    temp_double_2 = temp_int op temp_double;                            \
    RESET();                                                            \
    BOOST_CHECK_EQUAL(temp_double_1, temp_double_2);                    \
                                                                        \
    temp_double_1 = Value(xd op x);                                     \
    RESET();                                                            \
    temp_double = Value(xd);                                            \
    temp_int = Value(x);                                                \
    temp_double_2 = temp_double op temp_int;                            \
    RESET();                                                            \
    BOOST_CHECK_EQUAL(temp_double_1, temp_double_2);                    \
                                                                        \
    temp_double_1 = Value(xd op i);                                     \
    RESET();                                                            \
    temp_double = Value(xd);                                            \
    temp_double_2 = temp_double op i;                                   \
    RESET();                                                            \
    BOOST_CHECK_EQUAL(temp_double_1, temp_double_2);                    \
                                                                        \
    temp_double_1 = Value(xd op d);                                     \
    RESET();                                                            \
    temp_double = Value(xd);                                            \
    temp_double_2 = temp_double op d;                                   \
    RESET();                                                            \
    BOOST_CHECK_EQUAL(temp_double_1, temp_double_2);                    \
                                                                        \
    temp_double_1 = Value(xd op xd);                                    \
    RESET();                                                            \
    temp_double = Value(xd);                                            \
    temp_double_2 = temp_double op temp_double;                         \
    RESET();                                                            \
    BOOST_CHECK_EQUAL(temp_double_1, temp_double_2)

#define COMPARISON_ITERATION(op)                                 \
    BOOST_CHECK_EQUAL(i op x, i op Value(x));                    \
    BOOST_CHECK_EQUAL(x op i, Value(x) op i);                    \
    BOOST_CHECK_EQUAL(d op x, d op Value(x));                    \
    BOOST_CHECK_EQUAL(x op d, Value(x) op d);                    \
    BOOST_CHECK_EQUAL(x op x, Value(x) op Value(x));             \
    BOOST_CHECK_EQUAL(x op xd, Value(x) op Value(xd));           \
    BOOST_CHECK_EQUAL(xd op x, Value(xd) op Value(x));           \
                                                                 \
    BOOST_CHECK_EQUAL(i op xd, i op Value(xd));                  \
    BOOST_CHECK_EQUAL(xd op i, Value(xd) op i);                  \
    BOOST_CHECK_EQUAL(d op xd, d op Value(xd));                  \
    BOOST_CHECK_EQUAL(xd op d, Value(xd) op d);                  \
    BOOST_CHECK_EQUAL(xd op xd, Value(xd) op Value(xd))

BOOST_AUTO_TEST_CASE( arithmetic )
{
    ARITHMETIC_ITERATION(+);
    ARITHMETIC_ITERATION(-);
    ARITHMETIC_ITERATION(*);

    BOOST_CHECK_EQUAL(Value(x / i), Value(x) / i);
    BOOST_CHECK_EQUAL(Value(x / d), Value(x) / d);
    BOOST_CHECK_EQUAL(Value(x / x), Value(x) / Value(x));
    BOOST_CHECK_EQUAL(Value(x / xd), Value(x) / Value(xd));
    BOOST_CHECK_EQUAL(Value(xd / x), Value(xd) / Value(x));
    BOOST_CHECK_EQUAL(Value(xd / i), Value(xd) / i);
    BOOST_CHECK_EQUAL(Value(xd / d), Value(xd) / d);
    BOOST_CHECK_EQUAL(Value(xd / xd), Value(xd) / Value(xd));

    BOOST_CHECK_EQUAL(Value(x % i), Value(x) % i);
    BOOST_CHECK_EQUAL(Value(x % x), Value(x) % Value(x));

    ASSIGN_ARITHMETIC_ITERATION(+=);
    ASSIGN_ARITHMETIC_ITERATION(-=);
    ASSIGN_ARITHMETIC_ITERATION(*=);
    ASSIGN_ARITHMETIC_ITERATION(/=);

    temp_int_1 = Value(x %= i);
    RESET();
    temp_int = Value(x);
    temp_int_2 = temp_int %= i;
    RESET();
    BOOST_CHECK_EQUAL(temp_int_1, temp_int_2);

    temp_int_1 = Value(x %= x);
    RESET();
    temp_int = Value(x);
    temp_int_2 = temp_int %= temp_int;
    RESET();
    BOOST_CHECK_EQUAL(temp_int_1, temp_int_2);
}

BOOST_AUTO_TEST_CASE( comparison )
{
    COMPARISON_ITERATION(<);
    COMPARISON_ITERATION(>);
    COMPARISON_ITERATION(==);
    COMPARISON_ITERATION(!=);
    COMPARISON_ITERATION(<=);
    COMPARISON_ITERATION(>=);
}

BOOST_AUTO_TEST_CASE( unary )
{
    GG::X temp_x_1;
    GG::X_d temp_xd_1;

    temp_x_1 = ++x;
    RESET();
    temp_int_2 = ++(temp_int = Value(x));
    RESET();
    BOOST_CHECK_EQUAL(temp_x_1, temp_int_2);

    temp_xd_1 = ++xd;
    RESET();
    temp_double_2 = ++(temp_double = Value(xd));
    RESET();
    BOOST_CHECK_EQUAL(temp_xd_1, temp_double_2);

    temp_x_1 = x++;
    RESET();
    temp_int_2 = (temp_int = Value(x))++;
    RESET();
    BOOST_CHECK_EQUAL(temp_x_1, temp_int_2);

    temp_xd_1 = xd++;
    RESET();
    temp_double_2 = (temp_double = Value(xd))++;
    RESET();
    BOOST_CHECK_EQUAL(temp_xd_1, temp_double_2);

    temp_x_1 = --x;
    RESET();
    temp_int_2 = --(temp_int = Value(x));
    RESET();
    BOOST_CHECK_EQUAL(temp_x_1, temp_int_2);

    temp_xd_1 = --xd;
    RESET();
    temp_double_2 = --(temp_double = Value(xd));
    RESET();
    BOOST_CHECK_EQUAL(temp_xd_1, temp_double_2);

    temp_x_1 = x--;
    RESET();
    temp_int_2 = (temp_int = Value(x))--;
    RESET();
    BOOST_CHECK_EQUAL(temp_x_1, temp_int_2);

    temp_xd_1 = xd--;
    RESET();
    temp_double_2 = (temp_double = Value(xd))--;
    RESET();
    BOOST_CHECK_EQUAL(temp_xd_1, temp_double_2);

    BOOST_CHECK_EQUAL(!x, !Value(x));
    BOOST_CHECK_EQUAL(!xd, !Value(xd));

    BOOST_CHECK_EQUAL(-x, -Value(x));
    BOOST_CHECK_EQUAL(-xd, -Value(xd));
}
<|endoftext|>


<commit_before>/*******************************************************
 * Copyright (c) 2015, ArrayFire
 * All rights reserved.
 *
 * This file is distributed under 3-clause BSD license.
 * The complete license agreement can be obtained at:
 * http://arrayfire.com/licenses/BSD-3-Clause
 ********************************************************/

#pragma once
#include <Param.hpp>
#include <err_cpu.hpp>
#include <utility.hpp>

namespace cpu {
namespace kernel {

template<typename T>
T getConjugate(const T &in) {
    // For non-complex types return same
    return in;
}

template<>
cfloat getConjugate(const cfloat &in) {
    return std::conj(in);
}

template<>
cdouble getConjugate(const cdouble &in) {
    return std::conj(in);
}

template<typename T, bool conjugate>
void transpose(Param<T> output, CParam<T> input) {
    const af::dim4 odims    = output.dims();
    const af::dim4 ostrides = output.strides();
    const af::dim4 istrides = input.strides();

    T *out            = output.get();
    T const *const in = input.get();

    for (dim_t l = 0; l < odims[3]; ++l) {
        for (dim_t k = 0; k < odims[2]; ++k) {
            // Outermost loop handles batch mode
            // if input has no data along third dimension
            // this loop runs only once
            for (dim_t j = 0; j < odims[1]; ++j) {
                for (dim_t i = 0; i < odims[0]; ++i) {
                    // calculate array indices based on offsets and strides
                    // the helper getIdx takes care of indices
                    const dim_t inIdx  = getIdx(istrides, j, i, k, l);
                    const dim_t outIdx = getIdx(ostrides, i, j, k, l);
                    if (conjugate)
                        out[outIdx] = getConjugate(in[inIdx]);
                    else
                        out[outIdx] = in[inIdx];
                }
            }
            // outData and inData pointers doesn't need to be
            // offset as the getIdx function is taking care
            // of the batch parameter
        }
    }
}

template<typename T>
void transpose(Param<T> out, CParam<T> in, const bool conjugate) {
    return (conjugate ? transpose<T, true>(out, in)
                      : transpose<T, false>(out, in));
}

template<typename T, bool conjugate>
void transpose_inplace(Param<T> input) {
    const af::dim4 idims    = input.dims();
    const af::dim4 istrides = input.strides();

    T *in = input.get();

    for (dim_t l = 0; l < idims[3]; ++l) {
        for (dim_t k = 0; k < idims[2]; ++k) {
            // Outermost loop handles batch mode
            // if input has no data along third dimension
            // this loop runs only once
            //
            // Run only bottom triangle. std::swap swaps with upper triangle
            for (dim_t j = 0; j < idims[1]; ++j) {
                for (dim_t i = j + 1; i < idims[0]; ++i) {
                    // calculate array indices based on offsets and strides
                    // the helper getIdx takes care of indices
                    const dim_t iIdx = getIdx(istrides, j, i, k, l);
                    const dim_t oIdx = getIdx(istrides, i, j, k, l);
                    if (conjugate) {
                        in[iIdx] = getConjugate(in[iIdx]);
                        in[oIdx] = getConjugate(in[oIdx]);
                        std::swap(in[iIdx], in[oIdx]);
                    } else {
                        std::swap(in[iIdx], in[oIdx]);
                    }
                }
            }
        }
    }
}

template<typename T>
void transpose_inplace(Param<T> in, const bool conjugate) {
    return (conjugate ? transpose_inplace<T, true>(in)
                      : transpose_inplace<T, false>(in));
}

}  // namespace kernel
}  // namespace cpu
<commit_msg>Speed up CPU transpose<commit_after>/*******************************************************
 * Copyright (c) 2015, ArrayFire
 * All rights reserved.
 *
 * This file is distributed under 3-clause BSD license.
 * The complete license agreement can be obtained at:
 * http://arrayfire.com/licenses/BSD-3-Clause
 ********************************************************/

#pragma once
#include <Param.hpp>
#include <err_cpu.hpp>
#include <utility.hpp>

namespace cpu {
namespace kernel {

template<typename T>
T getConjugate(const T &in) {
    // For non-complex types return same
    return in;
}

template<>
cfloat getConjugate(const cfloat &in) {
    return std::conj(in);
}

template<>
cdouble getConjugate(const cdouble &in) {
    return std::conj(in);
}

template<typename T, int M, int N>
void transpose_kernel(T *output, const T *input, int ostride, int istride) {
    for (int j = 0; j < N; j++) {
        for (int i = 0; i < M; i++) { output[i * ostride] = input[i]; }
        input += istride;
        output++;
    }
}

template<typename T>
void transpose_real(Param<T> output, CParam<T> input) {
    const af::dim4 odims    = output.dims();
    const af::dim4 ostrides = output.strides();
    const af::dim4 istrides = input.strides();

    T *out            = output.get();
    T const *const in = input.get();

    constexpr int M = 8;
    constexpr int N = 8;

    dim_t odims1_down = floor(odims[1] / N) * N;
    dim_t odims0_down = floor(odims[0] / M) * M;

    for (dim_t l = 0; l < odims[3]; ++l) {
        for (dim_t k = 0; k < odims[2]; ++k) {
            // Outermost loop handles batch mode
            // if input has no data along third dimension
            // this loop runs only once
            T *out_      = out + l * ostrides[3] + k * ostrides[2];
            const T *in_ = in + l * istrides[3] + k * istrides[2];

            if (odims1_down > 0) {
                for (dim_t j = 0; j <= odims1_down; j += N) {
                    for (dim_t i = 0; i < odims0_down; i += M) {
                        transpose_kernel<T, M, N>(out_, in_, ostrides[1],
                                                  istrides[1]);
                        out_ += M;
                        in_ += istrides[1] * N;
                    }

                    for (dim_t jj = 0; jj < N; jj++) {
                        for (dim_t i = odims0_down; i < odims[0]; i++) {
                            *out_ = *in_;
                            out_++;
                            in_ += istrides[1];
                        }
                        out_ += ostrides[1] - (odims[0] - odims0_down);
                        in_ -= (odims[0] - odims0_down) * istrides[1] - 1;
                    }
                    out_ = out + l * ostrides[3] + k * ostrides[2] +
                           j * ostrides[1];
                    in_ = in + l * istrides[3] + k * istrides[2] + j;
                }
            }
            for (dim_t j = odims1_down; j < odims[1]; j++) {
                out_ =
                    out + l * ostrides[3] + k * ostrides[2] + j * ostrides[1];
                in_ = in + l * istrides[3] + k * istrides[2] + j;
                for (dim_t i = 0; i < odims[0]; i++) {
                    *out_ = *in_;
                    out_++;
                    in_ += istrides[1];
                }
            }
        }
    }
}

template<typename T>
void transpose_conj(Param<T> output, CParam<T> input) {
    const af::dim4 odims    = output.dims();
    const af::dim4 ostrides = output.strides();
    const af::dim4 istrides = input.strides();

    T *out            = output.get();
    T const *const in = input.get();

    for (dim_t l = 0; l < odims[3]; ++l) {
        for (dim_t k = 0; k < odims[2]; ++k) {
            // Outermost loop handles batch mode
            // if input has no data along third dimension
            // this loop runs only once

            for (dim_t j = 0; j < odims[1]; ++j) {
                for (dim_t i = 0; i < odims[0]; ++i) {
                    // calculate array indices based on offsets and strides
                    // the helper getIdx takes care of indices
                    const dim_t inIdx  = getIdx(istrides, j, i, k, l);
                    const dim_t outIdx = getIdx(ostrides, i, j, k, l);
                    out[outIdx]        = getConjugate(in[inIdx]);
                }
            }
            // outData and inData pointers doesn't need to be
            // offset as the getIdx function is taking care
            // of the batch parameter
        }
    }
}

template<typename T>
void transpose(Param<T> out, CParam<T> in, const bool conjugate) {
    return (conjugate ? transpose_conj<T>(out, in)
                      : transpose_real<T>(out, in));
}

template<typename T, bool conjugate>
void transpose_inplace(Param<T> input) {
    const af::dim4 idims    = input.dims();
    const af::dim4 istrides = input.strides();

    T *in = input.get();

    for (dim_t l = 0; l < idims[3]; ++l) {
        for (dim_t k = 0; k < idims[2]; ++k) {
            // Outermost loop handles batch mode
            // if input has no data along third dimension
            // this loop runs only once
            //
            // Run only bottom triangle. std::swap swaps with upper triangle
            for (dim_t j = 0; j < idims[1]; ++j) {
                for (dim_t i = j + 1; i < idims[0]; ++i) {
                    // calculate array indices based on offsets and strides
                    // the helper getIdx takes care of indices
                    const dim_t iIdx = getIdx(istrides, j, i, k, l);
                    const dim_t oIdx = getIdx(istrides, i, j, k, l);
                    if (conjugate) {
                        in[iIdx] = getConjugate(in[iIdx]);
                        in[oIdx] = getConjugate(in[oIdx]);
                        std::swap(in[iIdx], in[oIdx]);
                    } else {
                        std::swap(in[iIdx], in[oIdx]);
                    }
                }
            }
        }
    }
}

template<typename T>
void transpose_inplace(Param<T> in, const bool conjugate) {
    return (conjugate ? transpose_inplace<T, true>(in)
                      : transpose_inplace<T, false>(in));
}

}  // namespace kernel
}  // namespace cpu
<|endoftext|>


<commit_before>
// This test demonstrates using tracing to give you something like a
// stack trace in case of a crash (due to a compiler bug, or a bug in
// external code). We use a posix signal handler, which is probably
// os-dependent, so I'm going to enable this test on linux only.

#ifdef __linux__

#include <Halide.h>
#include <stdio.h>
#include <signal.h>
#include <stack>
#include <string>

using namespace Halide;
using std::stack;
using std::string;

stack<string> stack_trace;

void my_trace(const char *function, int event_type,
              int type_code, int bits, int width,
              int value_index, const void *value,
              int num_int_args, const int *int_args) {

    const string event_types[] = {"Load ",
                                  "Store ",
                                  "Begin realization ",
                                  "End realization ",
                                  "Produce ",
                                  "Update ",
                                  "Consume ",
                                  "End consume "};

    if (event_type == 3 || event_type > 4) {
        // These events signal the end of some previous event
        stack_trace.pop();
    }
    if (event_type == 2 || event_type == 4 || event_type == 5 || event_type == 6) {
        // These events signal the start of some new region
        stack_trace.push(event_types[event_type] + function);
    }
}

void signal_handler(int signum) {
    printf("Correctly triggered a segfault. Here is the stack trace:\n");
    while (!stack_trace.empty()) {
        printf("%s\n", stack_trace.top().c_str());
        stack_trace.pop();
    }

    printf("Success!\n");
    exit(0);
}

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

   signal(SIGSEGV, signal_handler);

    // Loads from this image will barf, because we've messed up the host pointer
    Image<int> input(100, 100);
    buffer_t *buf = (buffer_t *)input;
    buf->host = (uint8_t *)17;

    Func f("f"), g("g"), h("h");
    Var x("x"), y("y");

    f(x, y) = x+y;
    f.compute_root().trace_realizations();

    g(x, y) = f(x, y) + 37;
    g.compute_root().trace_realizations();

    h(x, y) = g(x, y) + input(x, y);
    h.trace_realizations();

    h.set_custom_trace(&my_trace);
    h.realize(100, 100);

    printf("The code should not have reached this print statement.\n");
    return -1;
}

#else

int main(int argc, char **argv) {
    printf("Test skipped because we're not on linux\n");
    return 0;
}

#endif
<commit_msg>Adding missing #include to tracing_stack test<commit_after>
// This test demonstrates using tracing to give you something like a
// stack trace in case of a crash (due to a compiler bug, or a bug in
// external code). We use a posix signal handler, which is probably
// os-dependent, so I'm going to enable this test on linux only.

#ifdef __linux__

#include <Halide.h>
#include <stdio.h>
#include <signal.h>
#include <stack>
#include <string>

using namespace Halide;
using std::stack;
using std::string;

stack<string> stack_trace;

void my_trace(const char *function, int event_type,
              int type_code, int bits, int width,
              int value_index, const void *value,
              int num_int_args, const int *int_args) {

    const string event_types[] = {"Load ",
                                  "Store ",
                                  "Begin realization ",
                                  "End realization ",
                                  "Produce ",
                                  "Update ",
                                  "Consume ",
                                  "End consume "};

    if (event_type == 3 || event_type > 4) {
        // These events signal the end of some previous event
        stack_trace.pop();
    }
    if (event_type == 2 || event_type == 4 || event_type == 5 || event_type == 6) {
        // These events signal the start of some new region
        stack_trace.push(event_types[event_type] + function);
    }
}

void signal_handler(int signum) {
    printf("Correctly triggered a segfault. Here is the stack trace:\n");
    while (!stack_trace.empty()) {
        printf("%s\n", stack_trace.top().c_str());
        stack_trace.pop();
    }

    printf("Success!\n");
    exit(0);
}

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

   signal(SIGSEGV, signal_handler);

    // Loads from this image will barf, because we've messed up the host pointer
    Image<int> input(100, 100);
    buffer_t *buf = (buffer_t *)input;
    buf->host = (uint8_t *)17;

    Func f("f"), g("g"), h("h");
    Var x("x"), y("y");

    f(x, y) = x+y;
    f.compute_root().trace_realizations();

    g(x, y) = f(x, y) + 37;
    g.compute_root().trace_realizations();

    h(x, y) = g(x, y) + input(x, y);
    h.trace_realizations();

    h.set_custom_trace(&my_trace);
    h.realize(100, 100);

    printf("The code should not have reached this print statement.\n");
    return -1;
}

#else

#include <stdio.h>

int main(int argc, char **argv) {
    printf("Test skipped because we're not on linux\n");
    return 0;
}

#endif
<|endoftext|>


<commit_before>#include <Halide.h>
#include <sys/time.h>

using namespace Halide;

double currentTime() {
    timeval t;
    gettimeofday(&t, NULL);
    return t.tv_sec * 1000.0 + t.tv_usec / 1000.0f;
}

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

    Func f, g, h; Var x, y;

    h(x) = x;
    g(x) = h(x-1) + h(x+1);
    f(x, y) = (g(x-1) + g(x+1)) + y;

    h.root();
    g.root();

    if (use_gpu()) {
        f.cudaTile(x, y, 16, 16);
        g.cudaTile(x, 128);
        h.cudaTile(x, 128);
    }

    Image<int> out = f.realize(32, 32);

    for (int y = 0; y < 32; y++) {
        for (int x = 0; x < 32; x++) {
            if (out(x, y) != x*4 + y) {
                printf("out(%d, %d) = %d instead of %d\n", x, y, out(x, y), x*4+y);
                return -1;
            }
        }
    }

    printf("Success!\n");
    return 0;
}
<commit_msg>Clear spurious timing code from bounds_interence<commit_after>#include <Halide.h>
using namespace Halide;

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

    Func f, g, h; Var x, y;

    h(x) = x;
    g(x) = h(x-1) + h(x+1);
    f(x, y) = (g(x-1) + g(x+1)) + y;

    h.root();
    g.root();

    if (use_gpu()) {
        f.cudaTile(x, y, 16, 16);
        g.cudaTile(x, 128);
        h.cudaTile(x, 128);
    }

    Image<int> out = f.realize(32, 32);

    for (int y = 0; y < 32; y++) {
        for (int x = 0; x < 32; x++) {
            if (out(x, y) != x*4 + y) {
                printf("out(%d, %d) = %d instead of %d\n", x, y, out(x, y), x*4+y);
                return -1;
            }
        }
    }

    printf("Success!\n");
    return 0;
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
 */

#include "bgp/tunnel_encap/tunnel_encap.h"

#include <stdio.h>

#include <algorithm>
#include <sstream>

#include "base/parse_object.h"

using std::copy;
using std::string;

TunnelEncap::TunnelEncap(string encap) {
    TunnelEncapType::Encap id = TunnelEncapType::TunnelEncapFromString(encap);
    if (id == TunnelEncapType::UNSPEC) return;
    data_[0] = 0x03;
    data_[1] = 0x0C;
    // Reserved
    put_value(&data_[2], 4, 0);
    put_value(&data_[6], 2, id);
}

TunnelEncap::TunnelEncap(TunnelEncapType::Encap tunnel_encap) {
    data_[0] = 0x03;
    data_[1] = 0x0C;
    // Reserved
    put_value(&data_[2], 4, 0);
    put_value(&data_[6], 2, tunnel_encap);
}

TunnelEncap::TunnelEncap(const bytes_type &data) {
    copy(data.begin(), data.end(), data_.begin());
}

TunnelEncapType::Encap TunnelEncap::tunnel_encap() const {
    if (data_[0] != 0x03 || data_[1] != 0x0c)
        return TunnelEncapType::UNSPEC;
    uint16_t value = get_value(&data_[6], 2);
    if (TunnelEncapType::TunnelEncapIsValid(value)) {
        return static_cast<TunnelEncapType::Encap>(value);
    } else {
        return TunnelEncapType::UNSPEC;
    }
}

string TunnelEncap::ToString() {
    string str("encapsulation:");
    str += TunnelEncapType::TunnelEncapToString(tunnel_encap());
    return str;
}

string TunnelEncap::ToXmppString() {
    return TunnelEncapType::TunnelEncapToXmppString(tunnel_encap());
}
<commit_msg>Initialize TunnelEncap:::data_ byte array properly in the constructor<commit_after>/*
 * Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
 */

#include "bgp/tunnel_encap/tunnel_encap.h"

#include <stdio.h>

#include <algorithm>
#include <sstream>

#include "base/parse_object.h"

using std::copy;
using std::fill;
using std::string;

TunnelEncap::TunnelEncap(string encap) {
    fill(data_.begin(), data_.end(), 0);
    TunnelEncapType::Encap id = TunnelEncapType::TunnelEncapFromString(encap);
    if (id == TunnelEncapType::UNSPEC) return;
    data_[0] = 0x03;
    data_[1] = 0x0C;
    // Reserved
    put_value(&data_[2], 4, 0);
    put_value(&data_[6], 2, id);
}

TunnelEncap::TunnelEncap(TunnelEncapType::Encap tunnel_encap) {
    fill(data_.begin(), data_.end(), 0);
    data_[0] = 0x03;
    data_[1] = 0x0C;
    // Reserved
    put_value(&data_[2], 4, 0);
    put_value(&data_[6], 2, tunnel_encap);
}

TunnelEncap::TunnelEncap(const bytes_type &data) {
    copy(data.begin(), data.end(), data_.begin());
}

TunnelEncapType::Encap TunnelEncap::tunnel_encap() const {
    if (data_[0] != 0x03 || data_[1] != 0x0c)
        return TunnelEncapType::UNSPEC;
    uint16_t value = get_value(&data_[6], 2);
    if (TunnelEncapType::TunnelEncapIsValid(value)) {
        return static_cast<TunnelEncapType::Encap>(value);
    } else {
        return TunnelEncapType::UNSPEC;
    }
}

string TunnelEncap::ToString() {
    string str("encapsulation:");
    str += TunnelEncapType::TunnelEncapToString(tunnel_encap());
    return str;
}

string TunnelEncap::ToXmppString() {
    return TunnelEncapType::TunnelEncapToXmppString(tunnel_encap());
}
<|endoftext|>