<commit_before>//
// Copyright (c) 2017 The nanoFramework project contributors
// See LICENSE file in the project root for full license information.
//

#include <nanoHAL.h>
#include <nanoCLR_Application.h>
#include <nanoCLR_Runtime.h>
#include <nanoCLR_Types.h>
#include <CLRStartup.h>

// FIXME
// these are dummy data, we'll have to figure out how to fill these after the build happens
char nanoCLR_Dat_Start[100 ];
char nanoCLR_Dat_End  [1 ];

struct Settings
{
    CLR_SETTINGS m_clrOptions;
    bool m_fInitialized;

    //--//

    HRESULT Initialize(CLR_SETTINGS params)
    {
        NANOCLR_HEADER();

        m_clrOptions = params;

        NANOCLR_CHECK_HRESULT(CLR_RT_ExecutionEngine::CreateInstance());
#if !defined(BUILD_RTM)
        CLR_Debug::Printf( "Created EE.\r\n" );
#endif

#if !defined(BUILD_RTM)
        if(params.WaitForDebugger)
        {
            CLR_EE_DBG_SET( Stopped );
        }
#endif

        NANOCLR_CHECK_HRESULT(g_CLR_RT_ExecutionEngine.StartHardware());
#if !defined(BUILD_RTM)
        CLR_Debug::Printf( "Started Hardware.\r\n" );
#endif

        // UNDONE: FIXME: CLR_DBG_Debugger::Debugger_Discovery();

        m_fInitialized = true;

        NANOCLR_NOCLEANUP();
    }

    HRESULT LoadAssembly( const CLR_RECORD_ASSEMBLY* header, CLR_RT_Assembly*& assm )
    {
        NANOCLR_HEADER();

        const CLR_RT_NativeAssemblyData *pNativeAssmData;

        NANOCLR_CHECK_HRESULT(CLR_RT_Assembly::CreateInstance( header, assm ));

        // Get handlers for native functions in assembly
        pNativeAssmData = GetAssemblyNativeData( assm->m_szName );

        // If pNativeAssmData not NULL- means this assembly has native calls and there is pointer to table with native calls.
        if ( pNativeAssmData != NULL )
        {
            // First verify that check sum in assembly object matches hardcoded check sum.
            if ( assm->m_header->nativeMethodsChecksum != pNativeAssmData->m_checkSum )
            {
                CLR_Debug::Printf("***********************************************************************\r\n");
                CLR_Debug::Printf("*                                                                     *\r\n");
                CLR_Debug::Printf("* ERROR!!!!  Firmware version does not match managed code version!!!! *\r\n");
                CLR_Debug::Printf("*                                                                     *\r\n");
                CLR_Debug::Printf("*                                                                     *\r\n");
                CLR_Debug::Printf("* Invalid native checksum: %s 0x%08X!=0x%08X *\r\n",
                                    assm->m_szName,
                                    assm->m_header->nativeMethodsChecksum,
                                    pNativeAssmData->m_checkSum
                                 );
                CLR_Debug::Printf("*                                                                     *\r\n");
                CLR_Debug::Printf("***********************************************************************\r\n");

                NANOCLR_SET_AND_LEAVE(CLR_E_ASSM_WRONG_CHECKSUM);
            }

            // Assembly has valid pointer to table with native methods. Save it.
            assm->m_nativeCode = (const CLR_RT_MethodHandler *)pNativeAssmData->m_pNativeMethods;
        }
        g_CLR_RT_TypeSystem.Link( assm );
        NANOCLR_NOCLEANUP();
    }

    HRESULT Load()
    {
        NANOCLR_HEADER();

#if !defined(BUILD_RTM)
        CLR_Debug::Printf( "Create TS.\r\n" );
#endif
        //NANOCLR_CHECK_HRESULT(LoadKnownAssemblies( (char*)&__deployment_start__, (char*)&__deployment_end__ ));

#if !defined(BUILD_RTM)
        CLR_Debug::Printf( "Loading Deployment Assemblies.\r\n" );
#endif

        LoadDeploymentAssemblies();

        //--//

#if !defined(BUILD_RTM)
        CLR_Debug::Printf( "Resolving.\r\n" );
#endif
        NANOCLR_CHECK_HRESULT(g_CLR_RT_TypeSystem.ResolveAll());

        g_CLR_RT_Persistence_Manager.Initialize();

        // UNDONE: FIXME: NANOCLR_CHECK_HRESULT(g_CLR_RT_TypeSystem.PrepareForExecution());

#if defined(NANOCLR_PROFILE_HANDLER)
        CLR_PROF_Handler::Calibrate();
#endif

        NANOCLR_CLEANUP();

#if !defined(BUILD_RTM)
        if(FAILED(hr)) CLR_Debug::Printf( "Error: %08x\r\n", hr );
#endif

        NANOCLR_CLEANUP_END();
    }

    HRESULT LoadKnownAssemblies( char* start, char* end )
    {
        //--//
        NANOCLR_HEADER();
        char *assStart = start;
        char *assEnd = end;
        const CLR_RECORD_ASSEMBLY* header;

#if !defined(BUILD_RTM)
        CLR_Debug::Printf(" Loading start at %x, end %x\r\n", (unsigned int)assStart, (unsigned int)assEnd);
#endif

        g_buildCRC = SUPPORT_ComputeCRC( assStart, (unsigned int)assEnd -(unsigned int) assStart, 0 );

        header = (const CLR_RECORD_ASSEMBLY*)assStart;

        while((char*)header + sizeof(CLR_RECORD_ASSEMBLY) < assEnd && header->GoodAssembly())
        {
            CLR_RT_Assembly* assm;

            // Creates instance of assembly, sets pointer to native functions, links to g_CLR_RT_TypeSystem
            NANOCLR_CHECK_HRESULT(LoadAssembly( header, assm ));

            header = (const CLR_RECORD_ASSEMBLY*)ROUNDTOMULTIPLE((size_t)header + header->TotalSize(), CLR_UINT32);
        }

        NANOCLR_NOCLEANUP();
    }

    HRESULT ContiguousBlockAssemblies(BlockStorageStream stream)
    {
        NANOCLR_HEADER();

        const CLR_RECORD_ASSEMBLY* header;
        unsigned char * assembliesBuffer ;
        signed int  headerInBytes = sizeof(CLR_RECORD_ASSEMBLY);
        unsigned char * headerBuffer  = NULL;

        headerBuffer = (unsigned char*)CLR_RT_Memory::Allocate( headerInBytes, true );  CHECK_ALLOCATION(headerBuffer);
        CLR_RT_Memory::ZeroFill( headerBuffer, headerInBytes );

        while(TRUE)
        {
            if(!BlockStorageStream_Read(&stream, &headerBuffer, headerInBytes )) break;

            header = (const CLR_RECORD_ASSEMBLY*)headerBuffer;

            // check header first before read
            if(!header->GoodHeader())
            {
                break;
            }

            unsigned int assemblySizeInByte = ROUNDTOMULTIPLE(header->TotalSize(), CLR_UINT32);

            // read the assemblies
            assembliesBuffer = (unsigned char*)CLR_RT_Memory::Allocate_And_Erase( assemblySizeInByte, CLR_RT_HeapBlock ::HB_Unmovable );

            if (!assembliesBuffer)
            {
                // release the headerbuffer which has being used and leave
                CLR_RT_Memory::Release( headerBuffer );

                NANOCLR_SET_AND_LEAVE(CLR_E_OUT_OF_MEMORY);
            }

            BlockStorageStream_Seek(&stream, -headerInBytes, BlockStorageStream_SeekCurrent);

            if(!BlockStorageStream_Read(&stream, &assembliesBuffer, assemblySizeInByte)) break;

            header = (const CLR_RECORD_ASSEMBLY*)assembliesBuffer;

            if(!header->GoodAssembly())
            {
                CLR_RT_Memory::Release( assembliesBuffer );
                break;
            }

            // we have good Assembly

            CLR_RT_Assembly* assm;

            CLR_Debug::Printf( "Attaching deployed file.\r\n" );

            // Creates instance of assembly, sets pointer to native functions, links to g_CLR_RT_TypeSystem
            if (FAILED(LoadAssembly(header, assm)))
            {
                CLR_RT_Memory::Release( assembliesBuffer );
                break;
            }
            assm->m_flags |= CLR_RT_Assembly::Deployed;
        }

        CLR_RT_Memory::Release( headerBuffer );

        NANOCLR_NOCLEANUP();
    }

    HRESULT LoadDeploymentAssemblies()
    {
        NANOCLR_HEADER();

        // perform initialization of BlockStorageStream structure
        BlockStorageStream stream;

        // init the stream for deployment storage
        if (!BlockStorageStream_Initialize(&stream, StorageUsage_DEPLOYMENT))
        {
#if !defined(BUILD_RTM)
            CLR_Debug::Printf( "ERROR: failed to initialize DEPLOYMENT storage\r\n" );
#endif
            NANOCLR_SET_AND_LEAVE(CLR_E_NOT_SUPPORTED);
        }

        ContiguousBlockAssemblies(stream);

        NANOCLR_NOCLEANUP();
    }

    void Cleanup()
    {
        g_CLR_RT_Persistence_Manager.Uninitialize();

        // UNDONE: FIXME: CLR_RT_ExecutionEngine::DeleteInstance();

        m_fInitialized = false;
    }

    Settings()
    {
        m_fInitialized = false;
    }

};

static Settings s_ClrSettings;

void ClrStartup(CLR_SETTINGS params)
{
    NATIVE_PROFILE_CLR_STARTUP();
    Settings settings;
    ASSERT(sizeof(CLR_RT_HeapBlock_Raw) == sizeof(CLR_RT_HeapBlock));
    bool softReboot;

    do
    {
        softReboot = false;

        CLR_RT_Assembly::InitString();

#if !defined(BUILD_RTM)
        CLR_Debug::Printf( "\r\nnanoCLR (Build %d.%d.%d.%d)\r\n\r\n", VERSION_MAJOR, VERSION_MINOR, VERSION_BUILD, VERSION_REVISION );
#endif

        CLR_RT_Memory::Reset();

#if !defined(BUILD_RTM)
        CLR_Debug::Printf( "Starting...\r\n" );
#endif

        HRESULT hr;

        if(SUCCEEDED(hr = s_ClrSettings.Initialize(params)))
        {
            if(SUCCEEDED(hr = s_ClrSettings.Load()))
            {
#if !defined(BUILD_RTM)
                CLR_Debug::Printf( "Ready.\r\n" );
#endif

                (void)g_CLR_RT_ExecutionEngine.Execute( NULL, params.MaxContextSwitches );

#if !defined(BUILD_RTM)
                CLR_Debug::Printf( "Done.\r\n" );
#endif
            }
        }

        if( CLR_EE_DBG_IS_NOT( RebootPending ))
        {
#if defined(NANOCLR_ENABLE_SOURCELEVELDEBUGGING)
            CLR_EE_DBG_SET_MASK(State_ProgramExited, State_Mask);
            CLR_EE_DBG_EVENT_BROADCAST(CLR_DBG_Commands::c_Monitor_ProgramExit, 0, NULL, WP_Flags_c_NonCritical);
#endif //#if defined(NANOCLR_ENABLE_SOURCELEVELDEBUGGING)

            if(params.EnterDebuggerLoopAfterExit)
            {
                // UNDONE: FIXME: CLR_DBG_Debugger::Debugger_WaitForCommands();
            }
        }

        // DO NOT USE 'ELSE IF' here because the state can change in Debugger_WaitForCommands() call

        if( CLR_EE_DBG_IS( RebootPending ))
        {
            if(CLR_EE_REBOOT_IS( ClrOnly ))
            {
                softReboot = true;

                params.WaitForDebugger = CLR_EE_REBOOT_IS(ClrOnlyStopDebugger);

                s_ClrSettings.Cleanup();

                // UNDONE: FIXME: HAL_Uninitialize();

                // UNDONE: FIXME: SmartPtr_IRQ::ForceDisabled();

                //re-init the hal for the reboot (initially it is called in bootentry)
                // UNDONE: FIXME: HAL_Initialize();

                // make sure interrupts are back on
                // UNDONE: FIXME: SmartPtr_IRQ::ForceEnabled();
            }
            else
            {
                CPU_Reset();
            }
        }

    } while( softReboot );

}
<commit_msg>Improve ContiguousBlockAssemblies (#371)<commit_after>//
// Copyright (c) 2017 The nanoFramework project contributors
// See LICENSE file in the project root for full license information.
//

#include <nanoHAL.h>
#include <nanoCLR_Application.h>
#include <nanoCLR_Runtime.h>
#include <nanoCLR_Types.h>
#include <CLRStartup.h>

// FIXME
// these are dummy data, we'll have to figure out how to fill these after the build happens
char nanoCLR_Dat_Start[100 ];
char nanoCLR_Dat_End  [1 ];

struct Settings
{
    CLR_SETTINGS m_clrOptions;
    bool m_fInitialized;

    //--//

    HRESULT Initialize(CLR_SETTINGS params)
    {
        NANOCLR_HEADER();

        m_clrOptions = params;

        NANOCLR_CHECK_HRESULT(CLR_RT_ExecutionEngine::CreateInstance());
#if !defined(BUILD_RTM)
        CLR_Debug::Printf( "Created EE.\r\n" );
#endif

#if !defined(BUILD_RTM)
        if(params.WaitForDebugger)
        {
            CLR_EE_DBG_SET( Stopped );
        }
#endif

        NANOCLR_CHECK_HRESULT(g_CLR_RT_ExecutionEngine.StartHardware());
#if !defined(BUILD_RTM)
        CLR_Debug::Printf( "Started Hardware.\r\n" );
#endif

        // UNDONE: FIXME: CLR_DBG_Debugger::Debugger_Discovery();

        m_fInitialized = true;

        NANOCLR_NOCLEANUP();
    }

    HRESULT LoadAssembly( const CLR_RECORD_ASSEMBLY* header, CLR_RT_Assembly*& assm )
    {
        NANOCLR_HEADER();

        const CLR_RT_NativeAssemblyData *pNativeAssmData;

        NANOCLR_CHECK_HRESULT(CLR_RT_Assembly::CreateInstance( header, assm ));

        // Get handlers for native functions in assembly
        pNativeAssmData = GetAssemblyNativeData( assm->m_szName );

        // If pNativeAssmData not NULL- means this assembly has native calls and there is pointer to table with native calls.
        if ( pNativeAssmData != NULL )
        {
            // First verify that check sum in assembly object matches hardcoded check sum.
            if ( assm->m_header->nativeMethodsChecksum != pNativeAssmData->m_checkSum )
            {
                CLR_Debug::Printf("***********************************************************************\r\n");
                CLR_Debug::Printf("*                                                                     *\r\n");
                CLR_Debug::Printf("* ERROR!!!!  Firmware version does not match managed code version!!!! *\r\n");
                CLR_Debug::Printf("*                                                                     *\r\n");
                CLR_Debug::Printf("*                                                                     *\r\n");
                CLR_Debug::Printf("* Invalid native checksum: %s 0x%08X!=0x%08X *\r\n",
                                    assm->m_szName,
                                    assm->m_header->nativeMethodsChecksum,
                                    pNativeAssmData->m_checkSum
                                 );
                CLR_Debug::Printf("*                                                                     *\r\n");
                CLR_Debug::Printf("***********************************************************************\r\n");

                NANOCLR_SET_AND_LEAVE(CLR_E_ASSM_WRONG_CHECKSUM);
            }

            // Assembly has valid pointer to table with native methods. Save it.
            assm->m_nativeCode = (const CLR_RT_MethodHandler *)pNativeAssmData->m_pNativeMethods;
        }
        g_CLR_RT_TypeSystem.Link( assm );
        NANOCLR_NOCLEANUP();
    }

    HRESULT Load()
    {
        NANOCLR_HEADER();

#if !defined(BUILD_RTM)
        CLR_Debug::Printf( "Create TS.\r\n" );
#endif
        //NANOCLR_CHECK_HRESULT(LoadKnownAssemblies( (char*)&__deployment_start__, (char*)&__deployment_end__ ));

#if !defined(BUILD_RTM)
        CLR_Debug::Printf( "Loading Deployment Assemblies.\r\n" );
#endif

        LoadDeploymentAssemblies();

        //--//

#if !defined(BUILD_RTM)
        CLR_Debug::Printf( "Resolving.\r\n" );
#endif
        NANOCLR_CHECK_HRESULT(g_CLR_RT_TypeSystem.ResolveAll());

        g_CLR_RT_Persistence_Manager.Initialize();

        NANOCLR_CHECK_HRESULT(g_CLR_RT_TypeSystem.PrepareForExecution());

#if defined(NANOCLR_PROFILE_HANDLER)
        CLR_PROF_Handler::Calibrate();
#endif

        NANOCLR_CLEANUP();

#if !defined(BUILD_RTM)
        if(FAILED(hr)) CLR_Debug::Printf( "Error: %08x\r\n", hr );
#endif

        NANOCLR_CLEANUP_END();
    }

    HRESULT LoadKnownAssemblies( char* start, char* end )
    {
        //--//
        NANOCLR_HEADER();
        char *assStart = start;
        char *assEnd = end;
        const CLR_RECORD_ASSEMBLY* header;

#if !defined(BUILD_RTM)
        CLR_Debug::Printf(" Loading start at %x, end %x\r\n", (unsigned int)assStart, (unsigned int)assEnd);
#endif

        g_buildCRC = SUPPORT_ComputeCRC( assStart, (unsigned int)assEnd -(unsigned int) assStart, 0 );

        header = (const CLR_RECORD_ASSEMBLY*)assStart;

        while((char*)header + sizeof(CLR_RECORD_ASSEMBLY) < assEnd && header->GoodAssembly())
        {
            CLR_RT_Assembly* assm;

            // Creates instance of assembly, sets pointer to native functions, links to g_CLR_RT_TypeSystem
            NANOCLR_CHECK_HRESULT(LoadAssembly( header, assm ));

            header = (const CLR_RECORD_ASSEMBLY*)ROUNDTOMULTIPLE((size_t)header + header->TotalSize(), CLR_UINT32);
        }

        NANOCLR_NOCLEANUP();
    }

    HRESULT ContiguousBlockAssemblies(BlockStorageStream stream)
    {
        NANOCLR_HEADER();

        const CLR_RECORD_ASSEMBLY* header;
        unsigned char * assembliesBuffer ;
        signed int  headerInBytes = sizeof(CLR_RECORD_ASSEMBLY);
        unsigned char * headerBuffer  = NULL;

        while(TRUE)
        {
            if(!BlockStorageStream_Read(&stream, &headerBuffer, headerInBytes )) break;

            header = (const CLR_RECORD_ASSEMBLY*)headerBuffer;

            // check header first before read
            if(!header->GoodHeader())
            {
                // check failed, try to continue to the next
                continue;
            }

            unsigned int assemblySizeInByte = ROUNDTOMULTIPLE(header->TotalSize(), CLR_UINT32);

            // advance stream beyond header
            BlockStorageStream_Seek(&stream, -headerInBytes, BlockStorageStream_SeekCurrent);

            // read the assembly
            if(!BlockStorageStream_Read(&stream, &assembliesBuffer, assemblySizeInByte)) break;

            header = (const CLR_RECORD_ASSEMBLY*)assembliesBuffer;

            if(!header->GoodAssembly())
            {
                // check failed, try to continue to the next
                continue;
            }

            // we have good Assembly
            CLR_RT_Assembly* assm;

            CLR_Debug::Printf( "Attaching deployed file.\r\n" );

            // Creates instance of assembly, sets pointer to native functions, links to g_CLR_RT_TypeSystem
            if (FAILED(LoadAssembly(header, assm)))
            {
                // load failed, try to continue to the next
                continue;
            }

            // load successfull, mark as deployed
            assm->m_flags |= CLR_RT_Assembly::Deployed;
        }

        NANOCLR_NOCLEANUP();
    }

    HRESULT LoadDeploymentAssemblies()
    {
        NANOCLR_HEADER();

        // perform initialization of BlockStorageStream structure
        BlockStorageStream stream;

        // init the stream for deployment storage
        if (!BlockStorageStream_Initialize(&stream, StorageUsage_DEPLOYMENT))
        {
#if !defined(BUILD_RTM)
            CLR_Debug::Printf( "ERROR: failed to initialize DEPLOYMENT storage\r\n" );
#endif
            NANOCLR_SET_AND_LEAVE(CLR_E_NOT_SUPPORTED);
        }

        ContiguousBlockAssemblies(stream);

        NANOCLR_NOCLEANUP();
    }

    void Cleanup()
    {
        g_CLR_RT_Persistence_Manager.Uninitialize();

        // UNDONE: FIXME: CLR_RT_ExecutionEngine::DeleteInstance();

        m_fInitialized = false;
    }

    Settings()
    {
        m_fInitialized = false;
    }

};

static Settings s_ClrSettings;

void ClrStartup(CLR_SETTINGS params)
{
    NATIVE_PROFILE_CLR_STARTUP();
    Settings settings;
    ASSERT(sizeof(CLR_RT_HeapBlock_Raw) == sizeof(CLR_RT_HeapBlock));
    bool softReboot;

    do
    {
        softReboot = false;

        CLR_RT_Assembly::InitString();

#if !defined(BUILD_RTM)
        CLR_Debug::Printf( "\r\nnanoCLR (Build %d.%d.%d.%d)\r\n\r\n", VERSION_MAJOR, VERSION_MINOR, VERSION_BUILD, VERSION_REVISION );
#endif

        CLR_RT_Memory::Reset();

#if !defined(BUILD_RTM)
        CLR_Debug::Printf( "Starting...\r\n" );
#endif

        HRESULT hr;

        if(SUCCEEDED(hr = s_ClrSettings.Initialize(params)))
        {
            if(SUCCEEDED(hr = s_ClrSettings.Load()))
            {
#if !defined(BUILD_RTM)
                CLR_Debug::Printf( "Ready.\r\n" );
#endif

                (void)g_CLR_RT_ExecutionEngine.Execute( NULL, params.MaxContextSwitches );

#if !defined(BUILD_RTM)
                CLR_Debug::Printf( "Done.\r\n" );
#endif
            }
        }

        if( CLR_EE_DBG_IS_NOT( RebootPending ))
        {
#if defined(NANOCLR_ENABLE_SOURCELEVELDEBUGGING)
            CLR_EE_DBG_SET_MASK(State_ProgramExited, State_Mask);
            CLR_EE_DBG_EVENT_BROADCAST(CLR_DBG_Commands::c_Monitor_ProgramExit, 0, NULL, WP_Flags_c_NonCritical);
#endif //#if defined(NANOCLR_ENABLE_SOURCELEVELDEBUGGING)

            if(params.EnterDebuggerLoopAfterExit)
            {
                // UNDONE: FIXME: CLR_DBG_Debugger::Debugger_WaitForCommands();
            }
        }

        // DO NOT USE 'ELSE IF' here because the state can change in Debugger_WaitForCommands() call

        if( CLR_EE_DBG_IS( RebootPending ))
        {
            if(CLR_EE_REBOOT_IS( ClrOnly ))
            {
                softReboot = true;

                params.WaitForDebugger = CLR_EE_REBOOT_IS(ClrOnlyStopDebugger);

                s_ClrSettings.Cleanup();

                // UNDONE: FIXME: HAL_Uninitialize();

                // UNDONE: FIXME: SmartPtr_IRQ::ForceDisabled();

                //re-init the hal for the reboot (initially it is called in bootentry)
                // UNDONE: FIXME: HAL_Initialize();

                // make sure interrupts are back on
                // UNDONE: FIXME: SmartPtr_IRQ::ForceEnabled();
            }
            else
            {
                CPU_Reset();
            }
        }

    } while( softReboot );

}
<|endoftext|>


<commit_before>#include "rosplan_knowledge_base/KnowledgeComparitor.h"

/* implementation of KnowledgeComparitor.h */
namespace KCL_rosplan {

	/**
	 * returns true iff a matches the knowledge in b.
	 */
	bool KnowledgeComparitor::containsKnowledge(const rosplan_knowledge_msgs::KnowledgeItem &a, const rosplan_knowledge_msgs::KnowledgeItem &b) {

		if(a.knowledge_type != b.knowledge_type) return false;

		if(a.knowledge_type == rosplan_knowledge_msgs::KnowledgeItem::INSTANCE) {

			// check instance knowledge
			if(0!=a.instance_type.compare(b.instance_type)) return false;
			if(a.instance_name!="" && 0!=a.instance_name.compare(b.instance_name)) return false;

		} else {

			// check fact or function
			if(a.attribute_name!="" && 0!=a.attribute_name.compare(b.attribute_name)) return false;
			if(a.is_negative != b.is_negative) return false;
			if(a.values.size() != b.values.size()) return false;
			for(size_t i=0;i<a.values.size();i++) {
				if(""!=a.values[i].value && a.values[i].value != b.values[i].value)
					return false;
			}
		}

		return true;
	}

	/**
	 * returns true is the knowledge item contains the instance, as instance or attribute parameter.
	 */
	bool KnowledgeComparitor::containsInstance(const rosplan_knowledge_msgs::KnowledgeItem &a, std::string &name) {

		if(0==a.instance_name.compare(name))
			return true;

		for(size_t i=0;i<a.values.size();i++) {
			if(0==a.values[i].value.compare(name))
				return true;
		}

		return false;
	}

} // close namespace
<commit_msg>checking parameter labels in knowledge base<commit_after>#include "rosplan_knowledge_base/KnowledgeComparitor.h"

/* implementation of KnowledgeComparitor.h */
namespace KCL_rosplan {

	/**
	 * returns true iff a matches the knowledge in b.
	 */
	bool KnowledgeComparitor::containsKnowledge(const rosplan_knowledge_msgs::KnowledgeItem &a, const rosplan_knowledge_msgs::KnowledgeItem &b) {

		if(a.knowledge_type != b.knowledge_type) return false;

		if(a.knowledge_type == rosplan_knowledge_msgs::KnowledgeItem::INSTANCE) {

			// check instance knowledge
			if(0!=a.instance_type.compare(b.instance_type)) return false;
			if(a.instance_name!="" && 0!=a.instance_name.compare(b.instance_name)) return false;

		} else {

			// check fact or function
			if(a.attribute_name!="" && 0!=a.attribute_name.compare(b.attribute_name)) return false;
			if(a.is_negative != b.is_negative) return false;
			if(a.values.size() != b.values.size()) return false;

			for(size_t i=0;i<a.values.size();i++) {

				// don't care about this parameter
				if(""==a.values[i].value) continue;

				// find matching object in parameters of b
				bool found = false;
				for(size_t i=0;i<b.values.size();i++) {
					 if(a.values[i].key == b.values[i].key && a.values[i].value == b.values[i].value) {
						found = true;
						break;
					}
				}
				if(!found) return false;
			}
		}

		return true;
	}

	/**
	 * returns true is the knowledge item contains the instance, as instance or attribute parameter.
	 */
	bool KnowledgeComparitor::containsInstance(const rosplan_knowledge_msgs::KnowledgeItem &a, std::string &name) {

		if(0==a.instance_name.compare(name))
			return true;

		for(size_t i=0;i<a.values.size();i++) {
			if(0==a.values[i].value.compare(name))
				return true;
		}

		return false;
	}

} // close namespace
<|endoftext|>


<commit_before>//
//  main.cpp
//  GettingFrameData
//
//  Created by 中村 薫 on 2013/08/12.
//  Copyright (c) 2013年 中村 薫. All rights reserved.
//
#include <iostream>
#include <Leap.h>

void GettingFramesByPolling()
{
  Leap::Controller leap;

  int64_t lastFrame = 0;
  while ( 1 ) {
    auto frame = leap.frame();
    if ( !leap.isConnected() ) {
      std::cout << "leap is not connected." << std::endl;
      continue;
    }

    bool focus = leap.hasFocus();
    if ( !focus ) {
      std::cout << "application is not focus." << std::endl;
      continue;
    }

    auto currentFrameid = frame.id();
    if ( currentFrameid == lastFrame ) {
      //std::cout << "processed frame id." << std::endl;
      continue;
    }

    //std::cout << "frame count : " << (currentFrameid - lastFrame) << std::endl;

    lastFrame = currentFrameid;

    // 指の位置の平均値を計算する
    int count = 0;
    Leap::Vector average = Leap::Vector();
    Leap::Finger fingerToAverage = frame.fingers()[0];
    for( int i = 0; i < 10; i++ ) {
      // フレーム履歴と指のIDで、過去の指の位置を取得する
      Leap::Finger fingerFromFrame = leap.frame(i).finger(fingerToAverage.id());
      if( fingerFromFrame.isValid() ) {
        average += fingerFromFrame.tipPosition();
        count++;
      }
    }
    average /= count;
    std::cout << "finger point : " << average << std::endl;
  }
}

class SampleListrener : public Leap::Listener
{
public:

  virtual void onFocusGained(const Leap::Controller&) {
    std::cout << __FUNCTION__ << std::endl;
  }

  virtual void onFocusLost(const Leap::Controller&) {
    std::cout << __FUNCTION__ << std::endl;
  }

};

void GettingFramesWithCallbacks()
{
  SampleListrener listner;
  Leap::Controller leap;
  leap.addListener( listner );

  std::cout << "Press Enter to quit..." << std::endl;
  std::cin.get();

  leap.removeListener( listner );
}

#if 1
int main()
{
#if 0
  // ポーリング
  GettingFramesByPolling();
#else
  // コールバック
  GettingFramesWithCallbacks();
#endif

  return 0;
}
#endif

#if 0
int main()
{
  Leap::Controller leap;
  int64_t previousFrameId = -1;

  // 以前のフレームを取得する

  while ( 1 ) {
    auto frame = leap.frame();
    if ( previousFrameId == frame.id() ) {
      continue;
    }

    previousFrameId = frame.id();

    // フレーム更新処理(onFrame()相当)
  }

  // 終了処理(onExit()相当)

  return 0;
}
#endif

#if 0
int main()
{
  bool isPrevConnected = false;
  bool hadPrevFocus = false;
  int64_t previousFrameId = -1;

  Leap::Controller leap;

  // 初期化処理(oninit()相当)

  while ( 1 ) {
    auto frame = leap.frame();

    // 接続状態を確認する
    {
      bool isCurrentConnected = leap.isConnected();
      if ( isPrevConnected != isCurrentConnected ) {
        if ( isCurrentConnected ) {
          // Leap Motion コントローラーが接続された(onConnected()相当)
          std::cout << "Leap Motion connected." << std::endl;
        }
        else {
          // Leap Motion コントローラーが抜かれた(onDisconnected()相当)
          std::cout << "Leap Motion disconnected." << std::endl;
        }
      }

      isPrevConnected = isCurrentConnected;
    }

    // フォーカス状態を確認する
    {
      bool hadCurrentFocus = leap.hasFocus();
      if ( hadPrevFocus != hadCurrentFocus ) {
        if ( hadCurrentFocus ) {
          // アプリケーションのフォーカスが有効になった(onFocusGained()相当)
          std::cout << "Focus gained." << std::endl;
        }
        else {
          // アプリケーションのフォーカスが無効になった(onFocusLost()相当)
          std::cout << "Focus lost." << std::endl;
        }
      }

      hadPrevFocus = hadCurrentFocus;
    }

    // フレームが更新されていなければ何もしない
    {
      if ( previousFrameId == frame.id() ) {
        continue;
      }

      previousFrameId = frame.id();
    }

    // フレーム更新処理(onFrame()相当)
  }

  // 終了処理(onExit()相当)

  return 0;
}
#endif

#if 0
int main()
{
  Leap::Controller leap;
  int64_t previousFrameId = -1;

  while ( 1 ) {
    // 最新のフレームを取得する (leap.frame( 0 ) と同じ)
    auto currentFrame = leap.frame();
    if ( previousFrameId == currentFrame.id() ) {
      continue;
    }

    previousFrameId = currentFrame.id();

    // 直前の5フレームを取得する
    std::cout << currentFrame.id() << ", ";
    for ( int i = 1; i <= 5; ++i ) {
      auto previousFrame = leap.frame( i );
      std::cout << previousFrame.id() << ", ";
    }
    std::cout << std::endl;
  }

  // 終了処理(onExit()相当)

  return 0;
}
#endif
<commit_msg>動作のコメントを追加<commit_after>//
//  main.cpp
//  GettingFrameData
//
//  Created by 中村 薫 on 2013/08/12.
//  Copyright (c) 2013年 中村 薫. All rights reserved.
//
#include <iostream>
#include <Leap.h>

// ポーリングでフレームを取得する
void GettingFramesByPolling()
{
  Leap::Controller leap;

  int64_t lastFrame = 0;
  while ( 1 ) {
    auto frame = leap.frame();
    if ( !leap.isConnected() ) {
      std::cout << "leap is not connected." << std::endl;
      continue;
    }

    bool focus = leap.hasFocus();
    if ( !focus ) {
      std::cout << "application is not focus." << std::endl;
      continue;
    }

    auto currentFrameid = frame.id();
    if ( currentFrameid == lastFrame ) {
      //std::cout << "processed frame id." << std::endl;
      continue;
    }

    //std::cout << "frame count : " << (currentFrameid - lastFrame) << std::endl;

    lastFrame = currentFrameid;

    // 指の位置の平均値を計算する
    int count = 0;
    Leap::Vector average = Leap::Vector();
    Leap::Finger fingerToAverage = frame.fingers()[0];
    for( int i = 0; i < 10; i++ ) {
      // フレーム履歴と指のIDで、過去の指の位置を取得する
      Leap::Finger fingerFromFrame = leap.frame(i).finger(fingerToAverage.id());
      if( fingerFromFrame.isValid() ) {
        average += fingerFromFrame.tipPosition();
        count++;
      }
    }
    average /= count;
    std::cout << "finger point : " << average << std::endl;
  }
}

class SampleListrener : public Leap::Listener
{
public:

  virtual void onFocusGained(const Leap::Controller&) {
    std::cout << __FUNCTION__ << std::endl;
  }

  virtual void onFocusLost(const Leap::Controller&) {
    std::cout << __FUNCTION__ << std::endl;
  }

};

void GettingFramesWithCallbacks()
{
  SampleListrener listner;
  Leap::Controller leap;
  leap.addListener( listner );

  std::cout << "Press Enter to quit..." << std::endl;
  std::cin.get();

  leap.removeListener( listner );
}

// フレームの取り方のサンプル
#if 0
int main()
{
#if 0
  // ポーリング
  GettingFramesByPolling();
#else
  // コールバック
  GettingFramesWithCallbacks();
#endif

  return 0;
}
#endif

// ポーリング処理の例
#if 0
int main()
{
  Leap::Controller leap;
  int64_t previousFrameId = -1;

  // 以前のフレームを取得する

  while ( 1 ) {
    auto frame = leap.frame();
    if ( previousFrameId == frame.id() ) {
      continue;
    }

    previousFrameId = frame.id();

    // フレーム更新処理(onFrame()相当)
  }

  // 終了処理(onExit()相当)

  return 0;
}
#endif

// ポーリング時の接続状態およびフォーカス状態を取得する
#if 1
int main()
{
  bool isPrevConnected = false;
  bool hadPrevFocus = false;
  int64_t previousFrameId = -1;

  Leap::Controller leap;

  // 初期化処理(oninit()相当)

  while ( 1 ) {
    auto frame = leap.frame();

    // 接続状態を確認する
    {
      bool isCurrentConnected = leap.isConnected();
      if ( isPrevConnected != isCurrentConnected ) {
        if ( isCurrentConnected ) {
          // Leap Motion コントローラーが接続された(onConnected()相当)
          std::cout << "Leap Motion connected." << std::endl;
        }
        else {
          // Leap Motion コントローラーが抜かれた(onDisconnected()相当)
          std::cout << "Leap Motion disconnected." << std::endl;
        }
      }

      isPrevConnected = isCurrentConnected;
    }

    // フォーカス状態を確認する
    {
      bool hadCurrentFocus = leap.hasFocus();
      if ( hadPrevFocus != hadCurrentFocus ) {
        if ( hadCurrentFocus ) {
          // アプリケーションのフォーカスが有効になった(onFocusGained()相当)
          std::cout << "Focus gained." << std::endl;
        }
        else {
          // アプリケーションのフォーカスが無効になった(onFocusLost()相当)
          std::cout << "Focus lost." << std::endl;
        }
      }

      hadPrevFocus = hadCurrentFocus;
    }

    // フレームが更新されていなければ何もしない
    {
      if ( previousFrameId == frame.id() ) {
        continue;
      }

      previousFrameId = frame.id();
    }

    // フレーム更新処理(onFrame()相当)
  }

  // 終了処理(onExit()相当)

  return 0;
}
#endif

// 直前のフレームを取得する
#if 0
int main()
{
  Leap::Controller leap;
  int64_t previousFrameId = -1;

  while ( 1 ) {
    // 最新のフレームを取得する (leap.frame( 0 ) と同じ)
    auto currentFrame = leap.frame();
    if ( previousFrameId == currentFrame.id() ) {
      continue;
    }

    previousFrameId = currentFrame.id();

    // 直前の5フレームを取得する
    std::cout << currentFrame.id() << ", ";
    for ( int i = 1; i <= 5; ++i ) {
      auto previousFrame = leap.frame( i );
      std::cout << previousFrame.id() << ", ";
    }
    std::cout << std::endl;
  }

  // 終了処理(onExit()相当)

  return 0;
}
#endif
<|endoftext|>


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

#ifndef _SC_XMLTABLESHAPEIMPORTHELPER_HXX
#define _SC_XMLTABLESHAPEIMPORTHELPER_HXX

#ifndef _XMLOFF_SHAPEIMPORT_HXX_
#include <xmloff/shapeimport.hxx>
#endif
#ifndef _COM_SUN_STAR_TABLE_CELLADDRESS_HPP_
#include <com/sun/star/table/CellAddress.hpp>
#endif

class ScXMLImport;
class ScXMLAnnotationContext;

class XMLTableShapeImportHelper : public XMLShapeImportHelper
{
    ::com::sun::star::table::CellAddress aStartCell;
    ScXMLAnnotationContext* pAnnotationContext;
    sal_Bool bOnTable;

public:

    XMLTableShapeImportHelper( ScXMLImport& rImp, SvXMLImportPropertyMapper *pImpMapper=0 );
    ~XMLTableShapeImportHelper();

    void SetLayer(com::sun::star::uno::Reference<com::sun::star::drawing::XShape>& rShape, sal_Int16 nLayerID, const rtl::OUString& sType) const;
    virtual void finishShape(com::sun::star::uno::Reference< com::sun::star::drawing::XShape >& rShape,
            const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList >& xAttrList,
            com::sun::star::uno::Reference< com::sun::star::drawing::XShapes >& rShapes);

    void SetCell (const ::com::sun::star::table::CellAddress& rAddress) { aStartCell = rAddress; }
    void SetOnTable (const sal_Bool bTempOnTable) { bOnTable = bTempOnTable; }
    void SetAnnotation(ScXMLAnnotationContext* pAnnotation) { pAnnotationContext = pAnnotation; }
};

#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.10.700); FILE MERGED 2008/04/01 15:30:29 thb 1.10.700.3: #i85898# Stripping all external header guards 2008/04/01 12:36:32 thb 1.10.700.2: #i85898# Stripping all external header guards 2008/03/31 17:14:56 rt 1.10.700.1: #i87441# Change license header to LPGL v3.<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: XMLTableShapeImportHelper.hxx,v $
 * $Revision: 1.11 $
 *
 * 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.
 *
 ************************************************************************/

#ifndef _SC_XMLTABLESHAPEIMPORTHELPER_HXX
#define _SC_XMLTABLESHAPEIMPORTHELPER_HXX

#include <xmloff/shapeimport.hxx>
#include <com/sun/star/table/CellAddress.hpp>

class ScXMLImport;
class ScXMLAnnotationContext;

class XMLTableShapeImportHelper : public XMLShapeImportHelper
{
    ::com::sun::star::table::CellAddress aStartCell;
    ScXMLAnnotationContext* pAnnotationContext;
    sal_Bool bOnTable;

public:

    XMLTableShapeImportHelper( ScXMLImport& rImp, SvXMLImportPropertyMapper *pImpMapper=0 );
    ~XMLTableShapeImportHelper();

    void SetLayer(com::sun::star::uno::Reference<com::sun::star::drawing::XShape>& rShape, sal_Int16 nLayerID, const rtl::OUString& sType) const;
    virtual void finishShape(com::sun::star::uno::Reference< com::sun::star::drawing::XShape >& rShape,
            const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList >& xAttrList,
            com::sun::star::uno::Reference< com::sun::star::drawing::XShapes >& rShapes);

    void SetCell (const ::com::sun::star::table::CellAddress& rAddress) { aStartCell = rAddress; }
    void SetOnTable (const sal_Bool bTempOnTable) { bOnTable = bTempOnTable; }
    void SetAnnotation(ScXMLAnnotationContext* pAnnotation) { pAnnotationContext = pAnnotation; }
};

#endif
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: MasterScriptProvider.hxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: svesik $ $Date: 2004-04-19 23:16:21 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _FRAMEWORK_SCRIPT_PROVIDER_XFUNCTIONPROVIDER_HXX_
#define _FRAMEWORK_SCRIPT_PROVIDER_XFUNCTIONPROVIDER_HXX_

#include <rtl/ustring>
#include <cppuhelper/implbase4.hxx>
#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/uno/RuntimeException.hpp>
#include <com/sun/star/lang/XInitialization.hpp>

#include <drafts/com/sun/star/script/provider/XScriptProvider.hpp>
#include <drafts/com/sun/star/script/browse/XBrowseNode.hpp>

#include "InvocationCtxProperties.hxx"
#include "ProviderCache.hxx"
namespace func_provider
{
// for simplification
#define css ::com::sun::star
#define dcsss ::drafts::com::sun::star::script

class MasterScriptProvider :
            public ::cppu::WeakImplHelper4 < dcsss::provider::XScriptProvider,
                dcsss::browse::XBrowseNode, css::lang::XServiceInfo,
                css::lang::XInitialization >
{
public:
    MasterScriptProvider(
        const css::uno::Reference< css::uno::XComponentContext >
        & xContext ) throw( css::uno::RuntimeException );
    ~MasterScriptProvider();

    // XServiceInfo implementation
    virtual ::rtl::OUString SAL_CALL getImplementationName( )
        throw( css::uno::RuntimeException );

    // XBrowseNode implementation
    virtual ::rtl::OUString SAL_CALL getName()
        throw ( css::uno::RuntimeException );
    virtual css::uno::Sequence< css::uno::Reference< dcsss::browse::XBrowseNode > > SAL_CALL getChildNodes()
        throw ( css::uno::RuntimeException );
    virtual sal_Bool SAL_CALL hasChildNodes()
        throw ( css::uno::RuntimeException );
    virtual sal_Int16 SAL_CALL getType()
        throw ( css::uno::RuntimeException );

    virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName )
        throw( css::uno::RuntimeException );
    virtual css::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames( )
        throw( css::uno::RuntimeException );

    // XScriptProvider implementation
    virtual css::uno::Reference < dcsss::provider::XScript > SAL_CALL
        getScript( const ::rtl::OUString& scriptURI )
        throw( css::lang::IllegalArgumentException, css::uno::RuntimeException );

    /**
     *  XInitialise implementation
     *
     * @param args expected to contain a single ::rtl::OUString
     * containing the URI
     */
    virtual void SAL_CALL initialize( const css::uno::Sequence < css::uno::Any > & args )
        throw ( css::uno::Exception, css::uno::RuntimeException);

    // Public method to return all Language Providers in this MasterScriptProviders
    // context.
    css::uno::Sequence< css::uno::Reference< dcsss::provider::XScriptProvider > > SAL_CALL
        getAllProviders() throw ( css::uno::RuntimeException );
private:
    bool  isValid();
    const css::uno::Sequence< ::rtl::OUString >& getProviderNames();

    ProviderCache* providerCache();
    /* to obtain other services if needed */
    css::uno::Reference< css::uno::XComponentContext > m_xContext;
    css::uno::Reference< css::lang::XMultiComponentFactory > m_xMgr;
    css::uno::Reference< css::frame::XModel > m_xModel;
    css::uno::Sequence< css::uno::Any > m_sAargs;
    // This component supports XInitialization, it can be created
    // using createInstanceXXX() or createInstanceWithArgumentsXXX using
    // the service Mangager.
    // Need to detect proper initialisation and validity
    // for the object, so m_bIsValid indicates that the object is valid is set in ctor
    // in case of createInstanceWithArgumentsXXX() called m_bIsValid is set to reset
    // and then set to true when initialisation is complete

    bool m_bIsValid;
    // m_bInitialised ensure initialisation only takes place once.
    bool m_bInitialised;
    css::uno::Reference< css::beans::XPropertySet > m_XScriptingContext;
    ProviderCache* m_pPCache;
    osl::Mutex m_mutex;
};
} // namespace func_provider
#endif //_FRAMEWORK_SCRIPT_PROVIDER_XFUNCTIONPROVIDER_HXX_
<commit_msg>INTEGRATION: CWS scriptingf4 (1.7.4); FILE MERGED 2004/05/06 12:47:20 npower 1.7.4.1: #i28812# Adding support for new MasterScriptProviderFactory service. MasterScriptProvider no longer aggregates the browsenodes of all other MasterScriptProviders ( was a bad idea anyway ). This function is now performed by the standalone singleton css:script:browse::theBrowseNodeFactory which will aggregate the nodes, merge nodes from various languages and also sort them Issue number: Submitted by: Reviewed by:<commit_after>/*************************************************************************
 *
 *  $RCSfile: MasterScriptProvider.hxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: rt $ $Date: 2004-05-19 08:28:24 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _FRAMEWORK_SCRIPT_PROVIDER_XFUNCTIONPROVIDER_HXX_
#define _FRAMEWORK_SCRIPT_PROVIDER_XFUNCTIONPROVIDER_HXX_

#include <rtl/ustring>
#include <cppuhelper/implbase4.hxx>
#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/uno/RuntimeException.hpp>
#include <com/sun/star/lang/XInitialization.hpp>

#include <drafts/com/sun/star/script/provider/XScriptProvider.hpp>
#include <drafts/com/sun/star/script/browse/XBrowseNode.hpp>

#include "InvocationCtxProperties.hxx"
#include "ProviderCache.hxx"
namespace func_provider
{
// for simplification
#define css ::com::sun::star
#define dcsss ::drafts::com::sun::star::script

 typedef ::cppu::WeakImplHelper4<
     dcsss::provider::XScriptProvider,
     dcsss::browse::XBrowseNode, css::lang::XServiceInfo,
     css::lang::XInitialization > t_helper;
class MasterScriptProvider : public t_helper
{
public:
    MasterScriptProvider(
        const css::uno::Reference< css::uno::XComponentContext >
        & xContext ) throw( css::uno::RuntimeException );
    ~MasterScriptProvider();

    // XServiceInfo implementation
    virtual ::rtl::OUString SAL_CALL getImplementationName( )
        throw( css::uno::RuntimeException );

    // XBrowseNode implementation
    virtual ::rtl::OUString SAL_CALL getName()
        throw ( css::uno::RuntimeException );
    virtual css::uno::Sequence< css::uno::Reference< dcsss::browse::XBrowseNode > > SAL_CALL getChildNodes()
        throw ( css::uno::RuntimeException );
    virtual sal_Bool SAL_CALL hasChildNodes()
        throw ( css::uno::RuntimeException );
    virtual sal_Int16 SAL_CALL getType()
        throw ( css::uno::RuntimeException );

    virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName )
        throw( css::uno::RuntimeException );
    virtual css::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames( )
        throw( css::uno::RuntimeException );

    // XScriptProvider implementation
    virtual css::uno::Reference < dcsss::provider::XScript > SAL_CALL
        getScript( const ::rtl::OUString& scriptURI )
        throw( css::lang::IllegalArgumentException, css::uno::RuntimeException );

    /**
     *  XInitialise implementation
     *
     * @param args expected to contain a single ::rtl::OUString
     * containing the URI
     */
    virtual void SAL_CALL initialize( const css::uno::Sequence < css::uno::Any > & args )
        throw ( css::uno::Exception, css::uno::RuntimeException);

    // Public method to return all Language Providers in this MasterScriptProviders
    // context.
    css::uno::Sequence< css::uno::Reference< dcsss::provider::XScriptProvider > > SAL_CALL
        getAllProviders() throw ( css::uno::RuntimeException );
private:
    ::rtl::OUString parseLocationName( const ::rtl::OUString& location );
    void  createPkgProvider();
    bool  isValid();
    const css::uno::Sequence< ::rtl::OUString >& getProviderNames();

    ProviderCache* providerCache();
    /* to obtain other services if needed */
    css::uno::Reference< css::uno::XComponentContext > m_xContext;
    css::uno::Reference< css::lang::XMultiComponentFactory > m_xMgr;
    css::uno::Reference< css::frame::XModel > m_xModel;
    css::uno::Sequence< css::uno::Any > m_sAargs;
    ::rtl::OUString m_sNodeName;
    // This component supports XInitialization, it can be created
    // using createInstanceXXX() or createInstanceWithArgumentsXXX using
    // the service Mangager.
    // Need to detect proper initialisation and validity
    // for the object, so m_bIsValid indicates that the object is valid is set in ctor
    // in case of createInstanceWithArgumentsXXX() called m_bIsValid is set to reset
    // and then set to true when initialisation is complete

    bool m_bIsValid;
    // m_bInitialised ensure initialisation only takes place once.
    bool m_bInitialised;
    css::uno::Reference< css::beans::XPropertySet > m_XScriptingContext;
    ProviderCache* m_pPCache;
    osl::Mutex m_mutex;
    ::rtl::OUString m_sCtxString;
};
} // namespace func_provider
#endif //_FRAMEWORK_SCRIPT_PROVIDER_XFUNCTIONPROVIDER_HXX_
<|endoftext|>


<commit_before>#include "adopter.h"
#include "serializer.h"
#include "mousegestures.h"
#include "ui_mousegestures.h"
#include "pathcorrector.h"
#include "validpathcreator.h"
#include "GeometricForms.h"
#include "paintmanager.h"
#include "multistrokeRecognizers/multistrokeGesturesManagers.h"
#include "test/xmlparser.h"

static const QString xmlDir = "../../unreal/trunk/qrxml";
static const QString idealGesturesFile =
        "NeuralNetwork/learnGestures/ideal_gestures.xml";
static const QString generatedGesturesFile = "NeuralNetwork/learnGestures/generated_gestures.xml";
static const QString testGesturesFile = "usersGestures.xml";

MouseGestures::MouseGestures(QWidget *parent)
    : QMainWindow(parent), ui(new Ui::MouseGestures)
{
    ui->setupUi(this);
    connect(ui->actionOpen, SIGNAL(triggered()), this, SLOT(loadFile()));
    connect(ui->twObjectPathTable, SIGNAL
            (currentItemChanged(QTableWidgetItem*,QTableWidgetItem*)), this, SLOT(drawGesture()));
    connect(ui->actionSave, SIGNAL(triggered()), this, SLOT(save()));
    connect(ui->actionTest, SIGNAL(triggered()), this, SLOT(chooseTestAlgorithm()));
    connect(ui->actionGenerate_gestures, SIGNAL(triggered()), this, SLOT(generateGestures()));
    connect(ui->actionSave_test_gestures, SIGNAL(triggered()), this, SLOT(saveTestGestures()));
    connect(ui->actionOpen_test_gestures, SIGNAL(triggered()), this, SLOT(openTestGestures()));
    mPaintManager = new PaintManager(ui->gvGesture);
    mGesturesManager = new LevenshteinHullGesturesManager();
    mRecognizer = new AbstractRecognizer(mGesturesManager);
}

void MouseGestures::openTestGestures()
{
    QMap<QString, UsersGestures> usersGestures = XmlParser::parseXml(testGesturesFile);
    mRecognizer = new AbstractRecognizer(mGesturesManager, usersGestures);
    showTable();
}

void MouseGestures::saveTestGestures()
{
    XmlParser::saveMore(this->mRecognizer->getAllGestures(), testGesturesFile);
}

void MouseGestures::generateGestures()
{
    //TODO:: change idealGestures
    QMap<QString, UsersGestures> usersGestures = XmlParser::parseXml(idealGesturesFile);
    QMap<QString, UsersGestures> generatedGestures;
    foreach (QString object, usersGestures.keys())
    {
        const int maxAngle = 45;
        const int angleDiff = 10;
        PathVector idealGesture = usersGestures[object].first;
        QList<QString> newGestures;
        qDebug() << object;
        for (int i = - maxAngle; i <= maxAngle; i += angleDiff)
        {
            int maxSecondAngle = maxAngle - abs(i);
            for (int j = - maxSecondAngle; j <= maxSecondAngle; j += angleDiff)
            {
                PathVector gesture = PathCorrector::distortGesture(idealGesture, i, j);
                //TODO:: change for incoherent gestures
                newGestures.push_back(Parser::pathToString(gesture));
            }
        }
        UsersGestures generatedGesture(usersGestures[object].first, newGestures);
        generatedGestures.insert(object, generatedGesture);
    }
    XmlParser::save(generatedGestures, generatedGesturesFile);
}

void MouseGestures::chooseTestAlgorithm()
{
    mTestWindow = new TestWindow(this);
    mTestWindow->show();
}

void MouseGestures::contextMenuEvent(QContextMenuEvent *event)
{
    QMenu menu(this);
    QAction *rotate = new QAction("Rotate path", this);
    connect(rotate, SIGNAL(triggered()), this, SLOT(rotatePath()));
    menu.addAction(rotate);
    QAction *increase = new QAction("Increase path", this);
    connect(increase, SIGNAL(triggered()), this, SLOT(increasePath()));
    menu.addAction(increase);
    QAction *decrease = new QAction("Decrease path", this);
    connect(decrease, SIGNAL(triggered()), this, SLOT(decreasePath()));
    menu.addAction(decrease);
    menu.exec(event->globalPos());
}

void MouseGestures::rotatePath()
{
//    QString pathStr = ui->twObjectPathTable->currentItem()->text();
//    QList<QPoint> path = Parser::stringToPath(pathStr);
//    path = PathCorrector::rotate(path);
//    ui->twObjectPathTable->currentItem()->setText(Parser::pathToString(path));
//    //TODO:: add changing path for single-stroke gestures
}

void MouseGestures::increasePath(double koef)
{
//    QString pathStr = ui->twObjectPathTable->currentItem()->text();
//    QList<QPoint> path = Parser::stringToPath(pathStr);
//    path = PathCorrector::increase(path, koef);
//    ui->twObjectPathTable->currentItem()->setText(Parser::pathToString(path));
//    //TODO:: add changing path for single-stroke gestures
}

void MouseGestures::increasePath()
{
    increasePath(2);
}

void MouseGestures::decreasePath()
{
    increasePath(0.5);
}

void MouseGestures::save()
{
    Objects objects;
    Serializer serializer(mFileName);
    serializer.serialize(objects);
}

void MouseGestures::changePath()
{
    //	int currentRow = ui->twObjectPathTable->currentRow();
    //	QString name = ui->twObjectPathTable->item(currentRow, objectColumn)->text();
    //	QString pathStr = ui->twObjectPathTable->item(currentRow, pathColumn)->text();
    //	QList<QPoint> path = Parser::stringToPath(pathStr);
    //	if (path.isEmpty())
    //	{
    //		QMessageBox msgBox;
    //		msgBox.setText("Invalid string. Path cannot be modified.");
    //		msgBox.exec();
    //	}
}

void MouseGestures::loadFile()
{
    //save();
    mFileName = QFileDialog::getOpenFileName(this,
                                             tr("Open Xml"), xmlDir,
                                             tr("Xml files (*.xml)"));
    int rowCount = ui->twObjectPathTable->rowCount();
    for (int i = 0; i < rowCount; i++)
    {
        ui->twObjectPathTable->removeRow(0);
    }
    Serializer serializer(mFileName);
    EntityVector entities = serializer.deserialize();
    //mGesturesManager = new LevenshteinHullGesturesManager();
    mRecognizer = new AbstractRecognizer(mGesturesManager, entities);
    //	addEntities(entities);
    showTable();
    //	this->mKeyBulder = new MultistrokeGesturesManager(entities);
}

void MouseGestures::showTable()
{
    this->disconnect(ui->twObjectPathTable, SIGNAL(itemChanged(QTableWidgetItem*)), this, SLOT(changePath()));
    foreach (QString object, mRecognizer->getObjects())
    {
        int rowCount = ui->twObjectPathTable->rowCount();
        ui->twObjectPathTable->setRowCount(rowCount + 1);
        QTableWidgetItem *item = new QTableWidgetItem(object);
        ui->twObjectPathTable->setItem(rowCount, 0, item);
    }
    connect(ui->twObjectPathTable, SIGNAL(itemChanged(QTableWidgetItem*)), this, SLOT(changePath()));
}

void MouseGestures::mouseMoveEvent(QMouseEvent * event)
{
    mRecognizer->mouseMove(event->pos());
    this->update();
}

void MouseGestures::mouseReleaseEvent(QMouseEvent *event)
{
    //    mCorrectPath = PathCorrector::correctPath(mMousePath);
    //    QString object = mKeyObjectTable.getObject(mCorrectPath);
    //    ui->teObject->setText(object);
    mRecognizer->mouseRelease(event->pos());
    this->update();
}

void MouseGestures::keyPressEvent(QKeyEvent * event)
{
    if (event->key() != Qt::Key_Return)
        return;
    QString object = mRecognizer->recognizeObject();
    showObjectsMenu(object);
    //mCorrectPath = PathCorrector::correctPath(mMousePath);
    ui->teObject->setText(object);
    this->update();
}

void MouseGestures::showObjectsMenu(QString const & object)
{
    QMenu * menu = new QMenu(this);
    QList<QString> objects = mRecognizer->getObjects();
    objects.removeAll(object);
    objects.push_front(object);
    foreach (QString object, objects)
    {
        QAction * action = new QAction(object, this);
        menu->addAction(action);
    }
    connect(menu, SIGNAL(triggered(QAction*)), this, SLOT(addTestGesture(QAction *)));
    menu->exec();
}

void MouseGestures::addTestGesture(QAction * action)
{
    mRecognizer->saveGesture(action->text());
}

void MouseGestures::mousePressEvent(QMouseEvent * event)
{
    mRecognizer->mousePress(event->pos());
    this->update();
}

void MouseGestures::paintEvent(QPaintEvent *)
{
    QPainter painter(this);
    PaintManager::drawPath(&painter, mRecognizer->getGesture());
}

void MouseGestures::drawGesture()
{
    QString name = ui->twObjectPathTable->currentItem()->text();
    mRecognizer->drawGesture(name, mPaintManager);
}

MouseGestures::~MouseGestures()
{
    delete ui;
}
<commit_msg>change way of choosing object<commit_after>#include "adopter.h"
#include "serializer.h"
#include "mousegestures.h"
#include "ui_mousegestures.h"
#include "pathcorrector.h"
#include "validpathcreator.h"
#include "GeometricForms.h"
#include "paintmanager.h"
#include "multistrokeRecognizers/multistrokeGesturesManagers.h"
#include "test/xmlparser.h"

static const QString xmlDir = "../../unreal/trunk/qrxml";
static const QString idealGesturesFile =
        "NeuralNetwork/learnGestures/ideal_gestures.xml";
static const QString generatedGesturesFile = "NeuralNetwork/learnGestures/generated_gestures.xml";
static const QString testGesturesFile = "usersGestures.xml";

MouseGestures::MouseGestures(QWidget *parent)
    : QMainWindow(parent), ui(new Ui::MouseGestures)
{
    ui->setupUi(this);
    connect(ui->actionOpen, SIGNAL(triggered()), this, SLOT(loadFile()));
    connect(ui->twObjectPathTable, SIGNAL
            (currentItemChanged(QTableWidgetItem*,QTableWidgetItem*)), this, SLOT(drawGesture()));
    connect(ui->actionSave, SIGNAL(triggered()), this, SLOT(save()));
    connect(ui->actionTest, SIGNAL(triggered()), this, SLOT(chooseTestAlgorithm()));
    connect(ui->actionGenerate_gestures, SIGNAL(triggered()), this, SLOT(generateGestures()));
    connect(ui->actionSave_test_gestures, SIGNAL(triggered()), this, SLOT(saveTestGestures()));
    connect(ui->actionOpen_test_gestures, SIGNAL(triggered()), this, SLOT(openTestGestures()));
    mPaintManager = new PaintManager(ui->gvGesture);
    mGesturesManager = new LevenshteinHullGesturesManager();
    mRecognizer = new AbstractRecognizer(mGesturesManager);
}

void MouseGestures::openTestGestures()
{
    QMap<QString, UsersGestures> usersGestures = XmlParser::parseXml(testGesturesFile);
    mRecognizer = new AbstractRecognizer(mGesturesManager, usersGestures);
    showTable();
}

void MouseGestures::saveTestGestures()
{
    XmlParser::saveMore(this->mRecognizer->getAllGestures(), testGesturesFile);
}

void MouseGestures::generateGestures()
{
    //TODO:: change idealGestures
    QMap<QString, UsersGestures> usersGestures = XmlParser::parseXml(idealGesturesFile);
    QMap<QString, UsersGestures> generatedGestures;
    foreach (QString object, usersGestures.keys())
    {
        const int maxAngle = 45;
        const int angleDiff = 10;
        PathVector idealGesture = usersGestures[object].first;
        QList<QString> newGestures;
        qDebug() << object;
        for (int i = - maxAngle; i <= maxAngle; i += angleDiff)
        {
            int maxSecondAngle = maxAngle - abs(i);
            for (int j = - maxSecondAngle; j <= maxSecondAngle; j += angleDiff)
            {
                PathVector gesture = PathCorrector::distortGesture(idealGesture, i, j);
                //TODO:: change for incoherent gestures
                newGestures.push_back(Parser::pathToString(gesture));
            }
        }
        UsersGestures generatedGesture(usersGestures[object].first, newGestures);
        generatedGestures.insert(object, generatedGesture);
    }
    XmlParser::save(generatedGestures, generatedGesturesFile);
}

void MouseGestures::chooseTestAlgorithm()
{
    mTestWindow = new TestWindow(this);
    mTestWindow->show();
}

void MouseGestures::contextMenuEvent(QContextMenuEvent *event)
{
    QMenu menu(this);
    QAction *rotate = new QAction("Rotate path", this);
    connect(rotate, SIGNAL(triggered()), this, SLOT(rotatePath()));
    menu.addAction(rotate);
    QAction *increase = new QAction("Increase path", this);
    connect(increase, SIGNAL(triggered()), this, SLOT(increasePath()));
    menu.addAction(increase);
    QAction *decrease = new QAction("Decrease path", this);
    connect(decrease, SIGNAL(triggered()), this, SLOT(decreasePath()));
    menu.addAction(decrease);
    menu.exec(event->globalPos());
}

void MouseGestures::rotatePath()
{
    //    QString pathStr = ui->twObjectPathTable->currentItem()->text();
    //    QList<QPoint> path = Parser::stringToPath(pathStr);
    //    path = PathCorrector::rotate(path);
    //    ui->twObjectPathTable->currentItem()->setText(Parser::pathToString(path));
    //    //TODO:: add changing path for single-stroke gestures
}

void MouseGestures::increasePath(double koef)
{
    //    QString pathStr = ui->twObjectPathTable->currentItem()->text();
    //    QList<QPoint> path = Parser::stringToPath(pathStr);
    //    path = PathCorrector::increase(path, koef);
    //    ui->twObjectPathTable->currentItem()->setText(Parser::pathToString(path));
    //    //TODO:: add changing path for single-stroke gestures
}

void MouseGestures::increasePath()
{
    increasePath(2);
}

void MouseGestures::decreasePath()
{
    increasePath(0.5);
}

void MouseGestures::save()
{
    Objects objects;
    Serializer serializer(mFileName);
    serializer.serialize(objects);
}

void MouseGestures::changePath()
{
    //	int currentRow = ui->twObjectPathTable->currentRow();
    //	QString name = ui->twObjectPathTable->item(currentRow, objectColumn)->text();
    //	QString pathStr = ui->twObjectPathTable->item(currentRow, pathColumn)->text();
    //	QList<QPoint> path = Parser::stringToPath(pathStr);
    //	if (path.isEmpty())
    //	{
    //		QMessageBox msgBox;
    //		msgBox.setText("Invalid string. Path cannot be modified.");
    //		msgBox.exec();
    //	}
}

void MouseGestures::loadFile()
{
    //save();
    mFileName = QFileDialog::getOpenFileName(this,
                                             tr("Open Xml"), xmlDir,
                                             tr("Xml files (*.xml)"));
    int rowCount = ui->twObjectPathTable->rowCount();
    for (int i = 0; i < rowCount; i++)
    {
        ui->twObjectPathTable->removeRow(0);
    }
    Serializer serializer(mFileName);
    EntityVector entities = serializer.deserialize();
    //mGesturesManager = new LevenshteinHullGesturesManager();
    mRecognizer = new AbstractRecognizer(mGesturesManager, entities);
    //	addEntities(entities);
    showTable();
    //	this->mKeyBulder = new MultistrokeGesturesManager(entities);
}

void MouseGestures::showTable()
{
    this->disconnect(ui->twObjectPathTable, SIGNAL(itemChanged(QTableWidgetItem*)), this, SLOT(changePath()));
    foreach (QString object, mRecognizer->getObjects())
    {
        int rowCount = ui->twObjectPathTable->rowCount();
        ui->twObjectPathTable->setRowCount(rowCount + 1);
        QTableWidgetItem *item = new QTableWidgetItem(object);
        ui->twObjectPathTable->setItem(rowCount, 0, item);
    }
    connect(ui->twObjectPathTable, SIGNAL(itemChanged(QTableWidgetItem*)), this, SLOT(changePath()));
}

void MouseGestures::mouseMoveEvent(QMouseEvent * event)
{
    mRecognizer->mouseMove(event->pos());
    this->update();
}

void MouseGestures::mouseReleaseEvent(QMouseEvent *event)
{
    //    mCorrectPath = PathCorrector::correctPath(mMousePath);
    //    QString object = mKeyObjectTable.getObject(mCorrectPath);
    //    ui->teObject->setText(object);
    mRecognizer->mouseRelease(event->pos());
    this->update();
}

void MouseGestures::keyPressEvent(QKeyEvent * event)
{
    if (event->key() != Qt::Key_Return)
        return;
    QString object = mRecognizer->recognizeObject();
    if (ui->twObjectPathTable->rowCount() != 0)
    {
        QTableWidgetItem * currentItem = ui->twObjectPathTable->currentItem();
        if (currentItem != NULL)
            mRecognizer->saveGesture(currentItem->text());
    }
    //showObjectsMenu(object);
    //mCorrectPath = PathCorrector::correctPath(mMousePath);
    ui->teObject->setText(object);
    this->update();
}

void MouseGestures::showObjectsMenu(QString const & object)
{
    QMenu * menu = new QMenu(this);
    QList<QString> objects = mRecognizer->getObjects();
    objects.removeAll(object);
    objects.push_front(object);
    foreach (QString object, objects)
    {
        QAction * action = new QAction(object, this);
        menu->addAction(action);
    }
    connect(menu, SIGNAL(triggered(QAction*)), this, SLOT(addTestGesture(QAction *)));
    menu->exec();
}

void MouseGestures::addTestGesture(QAction * action)
{
    mRecognizer->saveGesture(action->text());
}

void MouseGestures::mousePressEvent(QMouseEvent * event)
{
    mRecognizer->mousePress(event->pos());
    this->update();
}

void MouseGestures::paintEvent(QPaintEvent *)
{
    QPainter painter(this);
    PaintManager::drawPath(&painter, mRecognizer->getGesture());
}

void MouseGestures::drawGesture()
{
    QString name = ui->twObjectPathTable->currentItem()->text();
    mRecognizer->drawGesture(name, mPaintManager);
}

MouseGestures::~MouseGestures()
{
    delete ui;
}
<|endoftext|>


<commit_before><commit_msg>PUT, GET, RESERVE - CLIETN SIDE - OK<commit_after><|endoftext|>


<commit_before>/// \file
/// \ingroup tutorial_roofit
/// \notebook -js
/// Likelihood and minimization: Parameter uncertainties for weighted unbinned ML fits
///
/// \macro_image
/// \macro_output
/// \macro_code
/// \author 11/2019 - Christoph Langenbruch

#include "TH1D.h"
#include "TCanvas.h"
#include "TROOT.h"
#include "TStyle.h"
#include "TRandom3.h"
#include "TLegend.h"
#include "RooRealVar.h"
#include "RooFitResult.h"
#include "RooDataSet.h"
#include "RooPolynomial.h"

using namespace RooFit;

int rf611_weightedfits(int acceptancemodel=2) {
  // P a r a m e t e r   u n c e r t a i n t i e s   f o r   w e i g h t e d   u n b i n n e d   M L   f i t s
  // ---------------------------------------------------------------------------------------------------------
  //
  //Based on example from https://arxiv.org/abs/1911.01303
  //
  //This example compares different approaches to determining parameter uncertainties in weighted unbinned maximum likelihood fits.
  //Performing a weighted unbinned maximum likelihood fits can be useful to account for acceptance effects and to statistically subtract background events using the sPlot formalism.
  //It is however well known that the inverse Hessian matrix does not yield parameter uncertainties with correct coverage in the presence of event weights.
  //Three approaches to the determination of parameter uncertainties are compared in this example:
  //
  //1. Using the inverse weighted Hessian matrix [SumW2Error(false)]
  //
  //2. Using the expression [SumW2Error(true)]
  //   V_{ij} = H_{ik}^{-1} C_{kl} H_{lj}^{-1}
  //   where H is the weighted Hessian matrix and C is the Hessian matrix with squared weights
  //
  //3. The asymptotically correct approach (for details please see https://arxiv.org/abs/1911.01303) [Asymptotic(true)]
  //   V_{ij} = H_{ik}^{-1} D_{kl} H_{lj}^{-1}
  //   where H is the weighted Hessian matrix and D is given by
  //   D_{kl} = sum_{e=1}^{N} w_e^2 \frac{\partial log P}{\partial lambda_k}\frac{\partial log P}{\partial lambda_l}
  //   with the event weight w_e
  //
  //The example performs the fit of a second order polynomial in the angle cos(theta) [-1,1] to a weighted data set.
  //The polynomial is given by
  //  P = (1 + c0*cos(theta) + c1*cos(theta)*cos(theta)) / Norm
  //The two coefficients c0 and c1 and their uncertainties are to be determined in the fit.
  //
  //The per-event weight is used to correct for an acceptance effect, two different acceptance models can be studied:
  //  acceptancemodel==1: eff = 0.3+0.7*cos(theta)*cos(theta)
  //  acceptancemodel==2: eff = 1.0-0.7*cos(theta)*cos(theta)
  //The data is generated to be flat before the acceptance effect.
  //
  //The performance of the different approaches to determine parameter uncertainties is compared using the pull distributions from a large number of pseudoexperiments.
  //The pull is defined as (lambda_i-\lambda_{gen})/\sigma(\lambda_i), where \lambda_i is the fitted parameter and \sigma(\lambda_i) its uncertainty for pseudoexperiment number i.
  //If the fit is unbiased and the parameter uncertainties are estimated correctly, the pull distribution should be a Gaussian centered around zero with a width of one.

  // I n i t i a l i s a t i o n   a n d   S e t u p
  //------------------------------------------------

  //plotting options
  gStyle->SetPaintTextFormat(".1f");
  gStyle->SetEndErrorSize(6.0);
  gStyle->SetTitleSize(0.05, "XY");
  gStyle->SetLabelSize(0.05, "XY");
  gStyle->SetTitleOffset(0.9, "XY");
  gStyle->SetTextSize(0.05);
  gStyle->SetPadLeftMargin(0.125);
  gStyle->SetPadBottomMargin(0.125);
  gStyle->SetPadTopMargin(0.075);
  gStyle->SetPadRightMargin(0.075);
  gStyle->SetMarkerStyle(20);
  gStyle->SetMarkerSize(1.0);
  gStyle->SetHistLineWidth(2.0);
  gStyle->SetHistLineColor(1);

  //initialise TRandom3
  TRandom3* rnd = new TRandom3();
  rnd->SetSeed(191101303);

  //accepted events and events weighted to account for the acceptance
  TH1D* haccepted = new TH1D("haccepted", "Generated events;cos(#theta);#events", 40, -1.0, 1.0);
  TH1D* hweighted = new TH1D("hweighted", "Generated events;cos(#theta);#events", 40, -1.0, 1.0);
  //histograms holding pull distributions
  //using the inverse Hessian matrix
  TH1D* hc0pull1 = new TH1D("hc0pull1", "Inverse weighted Hessian matrix [SumW2Error(false)];Pull (c_{0}^{fit}-c_{0}^{gen})/#sigma(c_{0});", 20, -5.0, 5.0);
  TH1D* hc1pull1 = new TH1D("hc1pull1", "Inverse weighted Hessian matrix [SumW2Error(false)];Pull (c_{1}^{fit}-c_{1}^{gen})/#sigma(c_{1});", 20, -5.0, 5.0);
  //using the correction with the Hessian matrix with squared weights
  TH1D* hc0pull2 = new TH1D("hc0pull2", "Hessian matrix with squared weights [SumW2Error(true)];Pull (c_{0}^{fit}-c_{0}^{gen})/#sigma(c_{0});", 20, -5.0, 5.0);
  TH1D* hc1pull2 = new TH1D("hc1pull2", "Hessian matrix with squared weights [SumW2Error(true)];Pull (c_{1}^{fit}-c_{1}^{gen})/#sigma(c_{1});", 20, -5.0, 5.0);
  //asymptotically correct approach
  TH1D* hc0pull3 = new TH1D("hc0pull3", "Asymptotically correct approach [Asymptotic(true)];Pull (c_{0}^{fit}-c_{0}^{gen})/#sigma(c_{0});", 20, -5.0, 5.0);
  TH1D* hc1pull3 = new TH1D("hc1pull3", "Asymptotically correct approach [Asymptotic(true)];Pull (c_{1}^{fit}-c_{1}^{gen})/#sigma(c_{1});", 20, -5.0, 5.0);

  //number of pseudoexperiments (toys) and number of events per pseudoexperiment
  unsigned int ntoys = 500;
  unsigned int nstats = 5000;
  //parameters used in the generation
  double c0gen = 0.0;
  double c1gen = 0.0;

  // M a i n   l o o p   o v e r   a l l   p s e u d o e x p e r i m e n t s
  //------------------------------------------------------------------------
  for (unsigned int i=0; i<ntoys; i++)
    {
      //S e t u p   p a r a m e t e r s   a n d   P D F
      //-----------------------------------------------
      //angle theta and the weight to account for the acceptance effect
      RooRealVar costheta("costheta","costheta", -1.0, 1.0);
      RooRealVar weight("weight","weight", 0.0, 1000.0);

      //initialise parameters to fit
      RooRealVar c0("c0","c0", c0gen, -1.0, 1.0);
      RooRealVar c1("c1","c1", c1gen, -1.0, 1.0);
      c0.setError(0.01);
      c1.setError(0.01);
      //create simple second order polynomial as probability density function
      RooPolynomial pol("pol", "pol", costheta, RooArgList(c0, c1), 1);

      //G e n e r a t e   d a t a   s e t   f o r   p s e u d o e x p e r i m e n t   i
      //-------------------------------------------------------------------------------
      RooDataSet data("data","data",RooArgSet(costheta, weight), WeightVar("weight"));
      //generate nstats events
      for (unsigned int j=0; j<nstats; j++)
	{
	  bool finished = false;
	  //use simple accept/reject for generation
	  while (!finished)
	    {
	      costheta = 2.0*rnd->Rndm()-1.0;
	      //efficiency for the specific value of cos(theta)
	      double eff = 1.0;
	      if (acceptancemodel == 1)
		eff = 1.0 - 0.7 * costheta.getValV()*costheta.getValV();
	      else
		eff = 0.3 + 0.7 * costheta.getValV()*costheta.getValV();
	      //use 1/eff as weight to account for acceptance
	      weight = 1.0/eff;
	      //accept/reject
	      if (10.0*rnd->Rndm() < eff*pol.getValV())
		finished = true;
	    }
	  haccepted->Fill(costheta.getValV());
	  hweighted->Fill(costheta.getValV(), weight.getValV());
	  data.add(RooArgSet(costheta, weight), weight.getValV());
	}

      //F i t   t o y   u s i n g   t h e   t h r e e   d i f f e r e n t   a p p r o a c h e s   t o   u n c e r t a i n t y   d e t e r m i n a t i o n
      //-------------------------------------------------------------------------------------------------------------------------------------------------
      RooFitResult* result = pol.fitTo(data, Save(true), SumW2Error(false));//this uses the inverse weighted Hessian matrix
      hc0pull1->Fill((c0.getValV()-c0gen)/c0.getError());
      hc1pull1->Fill((c1.getValV()-c1gen)/c1.getError());

      result = pol.fitTo(data, Save(true), SumW2Error(true));//this uses the correction with the Hesse matrix with squared weights
      hc0pull2->Fill((c0.getValV()-c0gen)/c0.getError());
      hc1pull2->Fill((c1.getValV()-c1gen)/c1.getError());

      result = pol.fitTo(data, Save(true), AsymptoticError(true));//this uses the asymptotically correct approach
      hc0pull3->Fill((c0.getValV()-c0gen)/c0.getError());
      hc1pull3->Fill((c1.getValV()-c1gen)/c1.getError());
    }

  // P l o t   o u t p u t   d i s t r i b u t i o n s
  //--------------------------------------------------

  //plot accepted (weighted) events
  gStyle->SetOptStat(0);
  gStyle->SetOptFit(0);
  TCanvas* cevents = new TCanvas("cevents", "cevents", 800, 600);
  cevents->cd(1);
  hweighted->SetMinimum(0.0);
  hweighted->SetLineColor(2);
  hweighted->Draw("hist");
  haccepted->Draw("same hist");
  TLegend* leg = new TLegend(0.6, 0.8, 0.9, 0.9);
  leg->AddEntry(haccepted, "Accepted");
  leg->AddEntry(hweighted, "Weighted");
  leg->Draw();
  cevents->Update();

  //plot pull distributions
  TCanvas* cpull = new TCanvas("cpull", "cpull", 1200, 800);
  cpull->Divide(3,2);
  cpull->cd(1);
  gStyle->SetOptStat(1100);
  gStyle->SetOptFit(11);
  hc0pull1->Fit("gaus");
  hc0pull1->Draw("ep");
  cpull->cd(2);
  hc0pull2->Fit("gaus");
  hc0pull2->Draw("ep");
  cpull->cd(3);
  hc0pull3->Fit("gaus");
  hc0pull3->Draw("ep");
  cpull->cd(4);
  hc1pull1->Fit("gaus");
  hc1pull1->Draw("ep");
  cpull->cd(5);
  hc1pull2->Fit("gaus");
  hc1pull2->Draw("ep");
  cpull->cd(6);
  hc1pull3->Fit("gaus");
  hc1pull3->Draw("ep");
  cpull->Update();

  return 0;
}
<commit_msg>[RF] Update tutorial for asymptotic errors.<commit_after>/// \file
/// \ingroup tutorial_roofit
/// \notebook -js
/// Likelihood and minimization: Parameter uncertainties for weighted unbinned ML fits
///
/// ## Parameter uncertainties for weighted unbinned ML fits
///
/// Based on example from https://arxiv.org/abs/1911.01303
///
/// This example compares different approaches to determining parameter uncertainties in weighted unbinned maximum likelihood fits.
/// Performing a weighted unbinned maximum likelihood fits can be useful to account for acceptance effects and to statistically subtract background events using the sPlot formalism.
/// It is however well known that the inverse Hessian matrix does not yield parameter uncertainties with correct coverage in the presence of event weights.
/// Three approaches to the determination of parameter uncertainties are compared in this example:
///
/// 1. Using the inverse weighted Hessian matrix [`SumW2Error(false)`]
///
/// 2. Using the expression [`SumW2Error(true)`]
///    \f[
///      V_{ij} = H_{ik}^{-1} C_{kl} H_{lj}^{-1}
///    \f]
///    where H is the weighted Hessian matrix and C is the Hessian matrix with squared weights
///
/// 3. The asymptotically correct approach (for details please see https://arxiv.org/abs/1911.01303) [`Asymptotic(true)`]
///    \f[
///      V_{ij} = H_{ik}^{-1} D_{kl} H_{lj}^{-1}
///    \f]
///    where H is the weighted Hessian matrix and D is given by
///    \f[
///      D_{kl} = \sum_{e=1}^{N} w_e^2 \frac{\partial \log(P)}{\partial \lambda_k}\frac{\partial \log(P)}{\partial \lambda_l}
///    \f]
///    with the event weight \f$w_e\f$.
///
/// The example performs the fit of a second order polynomial in the angle cos(theta) [-1,1] to a weighted data set.
/// The polynomial is given by
/// \f[
///   P = \frac{ 1 + c_0 \cdot \cos(\theta) + c_1 \cdot \cos(\theta) \cdot \cos(\theta) }{\mathrm{Norm}}
/// \f]
/// The two coefficients \f$ c_0 \f$ and \f$ c_1 \f$ and their uncertainties are to be determined in the fit.
///
/// The per-event weight is used to correct for an acceptance effect, two different acceptance models can be studied:
/// - `acceptancemodel==1`: eff = \f$ 0.3 + 0.7 \cdot \cos(\theta) \cdot \cos(\theta) \f$
/// - `acceptancemodel==2`: eff = \f$ 1.0 - 0.7 \cdot \cos(\theta) \cdot \cos(\theta) \f$
/// The data is generated to be flat before the acceptance effect.
///
/// The performance of the different approaches to determine parameter uncertainties is compared using the pull distributions from a large number of pseudoexperiments.
/// The pull is defined as \f$ (\lambda_i - \lambda_{gen})/\sigma(\lambda_i) \f$, where \f$ \lambda_i \f$ is the fitted parameter and \f$ \sigma(\lambda_i) \f$ its
/// uncertainty for pseudoexperiment number i.
/// If the fit is unbiased and the parameter uncertainties are estimated correctly, the pull distribution should be a Gaussian centered around zero with a width of one.
///
/// \macro_image
/// \macro_output
/// \macro_code
/// \author 11/2019 - Christoph Langenbruch

#include "TH1D.h"
#include "TCanvas.h"
#include "TROOT.h"
#include "TStyle.h"
#include "TRandom3.h"
#include "TLegend.h"
#include "RooRealVar.h"
#include "RooFitResult.h"
#include "RooDataSet.h"
#include "RooPolynomial.h"

using namespace RooFit;

int rf611_weightedfits(int acceptancemodel=2) {
  // I n i t i a l i s a t i o n   a n d   S e t u p
  //------------------------------------------------

  //plotting options
  gStyle->SetPaintTextFormat(".1f");
  gStyle->SetEndErrorSize(6.0);
  gStyle->SetTitleSize(0.05, "XY");
  gStyle->SetLabelSize(0.05, "XY");
  gStyle->SetTitleOffset(0.9, "XY");
  gStyle->SetTextSize(0.05);
  gStyle->SetPadLeftMargin(0.125);
  gStyle->SetPadBottomMargin(0.125);
  gStyle->SetPadTopMargin(0.075);
  gStyle->SetPadRightMargin(0.075);
  gStyle->SetMarkerStyle(20);
  gStyle->SetMarkerSize(1.0);
  gStyle->SetHistLineWidth(2.0);
  gStyle->SetHistLineColor(1);

  //initialise TRandom3
  TRandom3* rnd = new TRandom3();
  rnd->SetSeed(191101303);

  //accepted events and events weighted to account for the acceptance
  TH1D* haccepted = new TH1D("haccepted", "Generated events;cos(#theta);#events", 40, -1.0, 1.0);
  TH1D* hweighted = new TH1D("hweighted", "Generated events;cos(#theta);#events", 40, -1.0, 1.0);
  //histograms holding pull distributions
  //using the inverse Hessian matrix
  TH1D* hc0pull1 = new TH1D("hc0pull1", "Inverse weighted Hessian matrix [SumW2Error(false)];Pull (c_{0}^{fit}-c_{0}^{gen})/#sigma(c_{0});", 20, -5.0, 5.0);
  TH1D* hc1pull1 = new TH1D("hc1pull1", "Inverse weighted Hessian matrix [SumW2Error(false)];Pull (c_{1}^{fit}-c_{1}^{gen})/#sigma(c_{1});", 20, -5.0, 5.0);
  //using the correction with the Hessian matrix with squared weights
  TH1D* hc0pull2 = new TH1D("hc0pull2", "Hessian matrix with squared weights [SumW2Error(true)];Pull (c_{0}^{fit}-c_{0}^{gen})/#sigma(c_{0});", 20, -5.0, 5.0);
  TH1D* hc1pull2 = new TH1D("hc1pull2", "Hessian matrix with squared weights [SumW2Error(true)];Pull (c_{1}^{fit}-c_{1}^{gen})/#sigma(c_{1});", 20, -5.0, 5.0);
  //asymptotically correct approach
  TH1D* hc0pull3 = new TH1D("hc0pull3", "Asymptotically correct approach [Asymptotic(true)];Pull (c_{0}^{fit}-c_{0}^{gen})/#sigma(c_{0});", 20, -5.0, 5.0);
  TH1D* hc1pull3 = new TH1D("hc1pull3", "Asymptotically correct approach [Asymptotic(true)];Pull (c_{1}^{fit}-c_{1}^{gen})/#sigma(c_{1});", 20, -5.0, 5.0);

  //number of pseudoexperiments (toys) and number of events per pseudoexperiment
  constexpr unsigned int ntoys = 500;
  constexpr unsigned int nstats = 5000;
  //parameters used in the generation
  constexpr double c0gen = 0.0;
  constexpr double c1gen = 0.0;

  // Silence fitting and minimisation messages
  auto& msgSv = RooMsgService::instance();
  msgSv.getStream(1).removeTopic(RooFit::Minimization);
  msgSv.getStream(1).removeTopic(RooFit::Fitting);

  std::cout << "Running " << ntoys*3 << " toy fits ..." << std::endl;

  // M a i n   l o o p :   r u n   p s e u d o e x p e r i m e n t s
  //----------------------------------------------------------------
  for (unsigned int i=0; i<ntoys; i++) {
    //S e t u p   p a r a m e t e r s   a n d   P D F
    //-----------------------------------------------
    //angle theta and the weight to account for the acceptance effect
    RooRealVar costheta("costheta","costheta", -1.0, 1.0);
    RooRealVar weight("weight","weight", 0.0, 1000.0);

    //initialise parameters to fit
    RooRealVar c0("c0","0th-order coefficient", c0gen, -1.0, 1.0);
    RooRealVar c1("c1","1st-order coefficient", c1gen, -1.0, 1.0);
    c0.setError(0.01);
    c1.setError(0.01);
    //create simple second-order polynomial as probability density function
    RooPolynomial pol("pol", "pol", costheta, RooArgList(c0, c1), 1);

    //G e n e r a t e   d a t a   s e t   f o r   p s e u d o e x p e r i m e n t   i
    //-------------------------------------------------------------------------------
    RooDataSet data("data","data",RooArgSet(costheta, weight), WeightVar("weight"));
    //generate nstats events
    for (unsigned int j=0; j<nstats; j++) {
      bool finished = false;
      //use simple accept/reject for generation
      while (!finished) {
        costheta = 2.0*rnd->Rndm()-1.0;
        //efficiency for the specific value of cos(theta)
        double eff = 1.0;
        if (acceptancemodel == 1)
          eff = 1.0 - 0.7 * costheta.getVal()*costheta.getVal();
        else
          eff = 0.3 + 0.7 * costheta.getVal()*costheta.getVal();
        //use 1/eff as weight to account for acceptance
        weight = 1.0/eff;
        //accept/reject
        if (10.0*rnd->Rndm() < eff*pol.getVal())
          finished = true;
      }
      haccepted->Fill(costheta.getVal());
      hweighted->Fill(costheta.getVal(), weight.getVal());
      data.add(RooArgSet(costheta, weight), weight.getVal());
    }

    //F i t   t o y   u s i n g   t h e   t h r e e   d i f f e r e n t   a p p r o a c h e s   t o   u n c e r t a i n t y   d e t e r m i n a t i o n
    //-------------------------------------------------------------------------------------------------------------------------------------------------
    //this uses the inverse weighted Hessian matrix
    RooFitResult* result = pol.fitTo(data, Save(true), SumW2Error(false), PrintLevel(-1), BatchMode(true));
    hc0pull1->Fill((c0.getVal()-c0gen)/c0.getError());
    hc1pull1->Fill((c1.getVal()-c1gen)/c1.getError());

    //this uses the correction with the Hesse matrix with squared weights
    result = pol.fitTo(data, Save(true), SumW2Error(true), PrintLevel(-1), BatchMode(true));
    hc0pull2->Fill((c0.getVal()-c0gen)/c0.getError());
    hc1pull2->Fill((c1.getVal()-c1gen)/c1.getError());

    //this uses the asymptotically correct approach
    result = pol.fitTo(data, Save(true), AsymptoticError(true), PrintLevel(-1), BatchMode(true));
    hc0pull3->Fill((c0.getVal()-c0gen)/c0.getError());
    hc1pull3->Fill((c1.getVal()-c1gen)/c1.getError());
  }

  std::cout << "... done." << std::endl;

  // P l o t   o u t p u t   d i s t r i b u t i o n s
  //--------------------------------------------------

  //plot accepted (weighted) events
  gStyle->SetOptStat(0);
  gStyle->SetOptFit(0);
  TCanvas* cevents = new TCanvas("cevents", "cevents", 800, 600);
  cevents->cd(1);
  hweighted->SetMinimum(0.0);
  hweighted->SetLineColor(2);
  hweighted->Draw("hist");
  haccepted->Draw("same hist");
  TLegend* leg = new TLegend(0.6, 0.8, 0.9, 0.9);
  leg->AddEntry(haccepted, "Accepted");
  leg->AddEntry(hweighted, "Weighted");
  leg->Draw();
  cevents->Update();

  //plot pull distributions
  TCanvas* cpull = new TCanvas("cpull", "cpull", 1200, 800);
  cpull->Divide(3,2);
  cpull->cd(1);
  gStyle->SetOptStat(1100);
  gStyle->SetOptFit(11);
  hc0pull1->Fit("gaus");
  hc0pull1->Draw("ep");
  cpull->cd(2);
  hc0pull2->Fit("gaus");
  hc0pull2->Draw("ep");
  cpull->cd(3);
  hc0pull3->Fit("gaus");
  hc0pull3->Draw("ep");
  cpull->cd(4);
  hc1pull1->Fit("gaus");
  hc1pull1->Draw("ep");
  cpull->cd(5);
  hc1pull2->Fit("gaus");
  hc1pull2->Draw("ep");
  cpull->cd(6);
  hc1pull3->Fit("gaus");
  hc1pull3->Draw("ep");
  cpull->Update();

  return 0;
}
<|endoftext|>


<commit_before>#include "skiphash_copy.h"
#include <string>
#include "../../urbackupcommon/chunk_hasher.h"
#include "../../stringtools.h"
#include "../../urbackupcommon/os_functions.h"
#include <memory>

bool skiphash_copy(const std::wstring& src_path,
	const std::wstring& dst_path,
	const std::wstring& hashinput_path)
{
	std::auto_ptr<IFile> src(Server->openFile(os_file_prefix(src_path), MODE_READ_SEQUENTIAL));

	if(!src.get())
	{
		Server->Log(L"Could not open source file for reading at \"" + src_path+L"\"", LL_ERROR);
		return false;
	}

	std::auto_ptr<IFile> hashoutput(Server->openFile(os_file_prefix(dst_path+L".hash"), MODE_WRITE));

	if(!hashoutput.get())
	{
		Server->Log(L"Could not open hash output for writing at \""+dst_path+L".hash\"", LL_ERROR);
		return false;
	}

	bool dst_exists = Server->fileExists(dst_path);

	std::auto_ptr<IFile> dst(Server->openFile(os_file_prefix(dst_path), MODE_RW));

	if(!dst.get())
	{
		Server->Log(L"Could not open output file for writing at \""+dst_path+L"\"", LL_ERROR);
		return false;
	}

	std::auto_ptr<IFile> hashinput;

	if(!hashinput_path.empty())
	{
		hashinput.reset(Server->openFile(os_file_prefix(hashinput_path), MODE_READ));

		if(!hashinput.get())
		{
			Server->Log(L"Could not open hash input file at \""+hashinput_path+L"\"", LL_ERROR);
			return false;
		}
	}

	if(!dst_exists || !hashinput.get())
	{
		Server->Log("Destination file does not exist or there is no hash input. Performing full copy (with hash output)...", LL_INFO);
		return build_chunk_hashs(src.get(), hashoutput.get(), NULL, false, dst.get(), false)!="";
	}
	else
	{
		int64 inplace_written = 0;
		bool ret = build_chunk_hashs(src.get(), hashoutput.get(), NULL, false,
			dst.get(), true, &inplace_written, hashinput.get())!="";
		float skipped_pc=0;
		if(src->Size()>0)
		{
			skipped_pc = 100.f - 100.f*src->Size()/inplace_written;
		}

		Server->Log("Wrote "+PrettyPrintBytes(inplace_written)
			+". Skipped "+PrettyPrintBytes(src->Size()-inplace_written)+" ("+
			nconvert(static_cast<int>(skipped_pc+0.5f))+"%)", LL_INFO);

		return ret;
	}
}

int skiphash_copy_file()
{
	std::string src = Server->getServerParameter("src");
	std::string dst = Server->getServerParameter("dst");
	std::string hashsrc = Server->getServerParameter("hashsrc");

	return skiphash_copy(Server->ConvertToUnicode(src),
		Server->ConvertToUnicode(dst),
		Server->ConvertToUnicode(hashsrc)) ? 1 : 0;
}
<commit_msg>Create file if it does not exist<commit_after>#include "skiphash_copy.h"
#include <string>
#include "../../urbackupcommon/chunk_hasher.h"
#include "../../stringtools.h"
#include "../../urbackupcommon/os_functions.h"
#include <memory>

bool skiphash_copy(const std::wstring& src_path,
	const std::wstring& dst_path,
	const std::wstring& hashinput_path)
{
	std::auto_ptr<IFile> src(Server->openFile(os_file_prefix(src_path), MODE_READ_SEQUENTIAL));

	if(!src.get())
	{
		Server->Log(L"Could not open source file for reading at \"" + src_path+L"\"", LL_ERROR);
		return false;
	}

	std::auto_ptr<IFile> hashoutput(Server->openFile(os_file_prefix(dst_path+L".hash"), MODE_WRITE));

	if(!hashoutput.get())
	{
		Server->Log(L"Could not open hash output for writing at \""+dst_path+L".hash\"", LL_ERROR);
		return false;
	}

	bool dst_exists = Server->fileExists(dst_path);

	std::auto_ptr<IFile> dst(Server->openFile(os_file_prefix(dst_path), MODE_RW));

	if(!dst.get())
	{
		dst.reset(Server->openFile(os_file_prefix(dst_path), MODE_WRITE));
	}

	if(!dst.get())
	{
		Server->Log(L"Could not open output file for writing at \""+dst_path+L"\"", LL_ERROR);
		return false;
	}

	std::auto_ptr<IFile> hashinput;

	if(!hashinput_path.empty())
	{
		hashinput.reset(Server->openFile(os_file_prefix(hashinput_path), MODE_READ));

		if(!hashinput.get())
		{
			Server->Log(L"Could not open hash input file at \""+hashinput_path+L"\"", LL_ERROR);
			return false;
		}
	}

	if(!dst_exists || !hashinput.get())
	{
		Server->Log("Destination file does not exist or there is no hash input. Performing full copy (with hash output)...", LL_INFO);
		return build_chunk_hashs(src.get(), hashoutput.get(), NULL, false, dst.get(), false)!="";
	}
	else
	{
		int64 inplace_written = 0;
		bool ret = build_chunk_hashs(src.get(), hashoutput.get(), NULL, false,
			dst.get(), true, &inplace_written, hashinput.get())!="";
		float skipped_pc=0;
		if(src->Size()>0)
		{
			skipped_pc = 100.f - 100.f*src->Size()/inplace_written;
		}

		Server->Log("Wrote "+PrettyPrintBytes(inplace_written)
			+". Skipped "+PrettyPrintBytes(src->Size()-inplace_written)+" ("+
			nconvert(static_cast<int>(skipped_pc+0.5f))+"%)", LL_INFO);

		return ret;
	}
}

int skiphash_copy_file()
{
	std::string src = Server->getServerParameter("src");
	std::string dst = Server->getServerParameter("dst");
	std::string hashsrc = Server->getServerParameter("hashsrc");

	return skiphash_copy(Server->ConvertToUnicode(src),
		Server->ConvertToUnicode(dst),
		Server->ConvertToUnicode(hashsrc)) ? 1 : 0;
}
<|endoftext|>